diff --git "a/065.jsonl" "b/065.jsonl" new file mode 100644--- /dev/null +++ "b/065.jsonl" @@ -0,0 +1,1146 @@ +{"seq_id": "3101271927", "text": "\"\"\"tests vulture_manager.py\"\"\"\nfrom pathlib import Path\n\nimport pytest\n\nfrom vulture.core import Item\n\nfrom pytest_vulture.conf.reader import IniReader\nfrom pytest_vulture.vulture.manager import VultureManager\n\n\n# pylint: disable=protected-access,too-many-arguments\n\n\n\n\n\n@pytest.mark.parametrize(\n \"results,file,answer\",\n [\n ([], \"test.py\", None),\n ([Item(\"test\", \"function\", Path(\"src/test.py\"), 8, 8, \"unused function 'test'\", 50)], \"not_test.py\", None),\n ([Item(\"test\", \"function\", Path(\"src/test.py\"), 8, 8, \"unused function 'test'\", 50)], \"test.py\", None),\n ([Item(\"test\", \"function\", Path(\"src/test.py\"), 8, 8, \"unused function 'test'\", 50)], \"src/test.py\",\n \"line 8 : unused function 'test'\"),\n ([Item(\"test\", \"function\", Path(\"src/test.py\"), 9, 9, \"unused function 'toto'\", 50)], \"src/test.py\",\n \"line 9 : unused function 'toto'\"),\n ]\n)\ndef test_get_file_errors(tmp_path, results, file, answer):\n \"\"\"Tests the getting file\"\"\"\n manager = VultureManager(tmp_path / \"test2\", IniReader(tmp_path / \"test\"))\n manager._results = results\n\n assert manager.get_file_errors(file) == answer\n", "repo_name": "Gatewatcher/pytest-vulture", "sub_path": "test/tests/unit/test_vulture_manager.py", "file_name": "test_vulture_manager.py", "file_ext": "py", "file_size_in_byte": 1159, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pytest_vulture.vulture.manager.VultureManager", "line_number": 32, "usage_type": "call"}, {"api_name": "pytest_vulture.conf.reader.IniReader", "line_number": 32, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 18, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 18, "usage_type": "attribute"}, {"api_name": "vulture.core.Item", "line_number": 22, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 22, "usage_type": "call"}, {"api_name": "vulture.core.Item", "line_number": 23, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 23, "usage_type": "call"}, {"api_name": "vulture.core.Item", "line_number": 24, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 24, "usage_type": "call"}, {"api_name": "vulture.core.Item", "line_number": 26, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 26, "usage_type": "call"}]} +{"seq_id": "35535981815", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nfrom Mul_models import models_select\nimport torch\nfrom PIL import Image\nfrom os.path import join\nfrom torchvision import transforms\nimport torchvision\nimport torch.nn.functional as F\n\ndef imgshow(img):\n img=img/2+0.5\n npimg=img.numpy()\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n plt.show()\n\nclass Test:\n def __init__(self,model,weight_path=None,image_path='./samples',transforms=None):\n self.weight_path = weight_path\n self.image_path=image_path\n self.transforms=transforms\n self.model=model\n Net = models_select(class_num=2)\n self.net = Net.net(self.model)\n self.net.load_state_dict(torch.load(self.weight_path))\n self.net.eval()\n #print(self.net)\n def result(self):\n for image in os.listdir(self.image_path):\n img=Image.open(join(self.image_path,image))\n img=self.transforms(img)\n #imgshow(img)\n img = img.unsqueeze(0)\n #print(img.size())\n output=self.net(img)\n print(output)\n _, predicted = torch.max(output, 1)\n print(image,predicted)\n\nif __name__=='__main__':\n if not os.path.isdir('./samples'):\n os.mkdir('./samples')\n #transform = transforms.Compose([transforms.Resize((224, 224)), transforms.ToTensor(),\n # transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))])\n transform = transforms.Compose([transforms.Resize((224, 224)), transforms.ToTensor()])\n T=Test(model='ResNet50',weight_path='./Weights/best_ResNet50_1_99.pth',transforms=transform)\n T.result()\n", "repo_name": "JXQI/crack_Identify", "sub_path": "test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 1689, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "24", "api": [{"api_name": "matplotlib.pyplot.imshow", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 15, "usage_type": "name"}, {"api_name": "numpy.transpose", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 16, "usage_type": "name"}, {"api_name": "torchvision.transforms", "line_number": 22, "usage_type": "name"}, {"api_name": "Mul_models.models_select", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 26, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 30, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 31, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 31, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path", "line_number": 42, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 43, "usage_type": "call"}, {"api_name": "torchvision.transforms.Compose", "line_number": 46, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 46, "usage_type": "name"}, {"api_name": "torchvision.transforms.Resize", "line_number": 46, "usage_type": "call"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 46, "usage_type": "call"}]} +{"seq_id": "29740344441", "text": "from scripts.report_scripts.data_mixin import *\nimport pandas as pd\n#Подключение гугл таблиц\nfrom scripts.filemanager.googlesheets_upload_lib import Googlesheets \nfrom scripts.filemanager.googlesheets_upload_lib import ListConventer\n\n\"\"\"\nБазовый отчет по Расходам в Яндекс Директ\n\"\"\"\n\nclass DataPrepare: \n def __init__ (self, client):\n self.client = client\n self.work()\n \n def work (self):\n \n \"\"\"\n Подкласс получения данных\n \"\"\"\n class GetData (GetMixinGenerateBigData):\n client = self.client \n dataset_name = 'yandex_direct_campaign_report' \n deep = 12\n gt = GetData()\n self.data = gt.data\n \n\n\nclass PayDirectReport:\n \n def __init__ (self, client):\n self.client = client\n dp = DataPrepare (client)\n self.data = dp.data\n self.go_report()\n def go_report(self):\n \n data = self.data\n client = self.client\n\n #Базовая подготовка данных\n\n def campaign_func (row):\n split = row['CampaignName'].split('.')\n if len(split) > 1:\n return split[1]\n return split[0]\n\n def type_func (row):\n return row['CampaignName'].split('.')[0]\n\n data['Campaign'] = data.apply(campaign_func, axis=1)\n data['Type'] = data.apply(type_func, axis=1)\n data['SumCTR'] = data.apply (lambda x: x['Ctr'] * x['Clicks'], \n axis=1)\n data['SumCRate'] = data.apply (lambda x: x['ConversionRate'] * x['Clicks'], \n axis=1)\n \n #Базовый отчет\n data_longtime = data.groupby('startOfMonth').sum().\\\n sort_values('startOfMonth', ascending=True).reset_index()\n\n def expand_func(data): \n\n data['Ctr'] = \\\n data.apply(lambda x: int(x['SumCTR'] / x['Clicks'] * 100) / 100 \\\n if x['SumCTR'] != 0\\\n else 0, axis=1)\n data['ConversionRate'] = \\\n data.apply(lambda x: int(x['SumCRate'] / x['Clicks'] * 100) / 100 \\\n if x['SumCRate'] !=0\\\n else 0, axis=1)\n\n return data\n\n data_longtime = expand_func(data_longtime)\n data_longtime = data_longtime[['startOfMonth', 'Impressions', 'Clicks', 'Ctr',\n 'Campaign_cost', 'ConversionRate']] \n \n #Отчет по типам трафика\n data_type = data.groupby(['startOfMonth', 'Type'])\\\n .sum().sort_values('startOfMonth', ascending=True).reset_index()\n\n\n data_type = data_type\\\n [ (data_type['Type']=='Поиск') | \\\n (data_type['Type']=='РСЯ') | \\\n (data_type['Type']=='Баннер на поиске')]\n\n data_type = expand_func(data_type)\n data_type = data_type[['startOfMonth', 'Type', 'Impressions', 'Clicks', 'Ctr',\n 'Campaign_cost', 'ConversionRate']] \n \n #Отчет по кампаниям\n data_campaign = data.groupby(['startOfMonth', 'Campaign'])\\\n .sum().sort_values('startOfMonth', ascending=True).reset_index()\n\n data_campaign = expand_func(data_campaign)\n data_campaign = data_campaign[['startOfMonth', 'Campaign', \n 'Impressions', 'Clicks', 'Ctr',\n 'Campaign_cost', 'ConversionRate']] \n \n \n \n lc = ListConventer(data_longtime,\n 'width_headers')\n lc.conventer()\n\n maxlonglist = 14\n maxwidthlist = 6\n width = [''] * maxwidthlist\n maxlist = [width] * maxlonglist\n\n Googlesheets('data pay direct!a1:f14', maxlist, client) \n Googlesheets('data pay direct!a1:f14', lc.datsheets, client) \n\n\n\n lc = ListConventer(data_type,\n 'width_headers')\n lc.conventer()\n\n maxlonglist = 60\n maxwidthlist = 6\n width = [''] * maxwidthlist\n maxlist = [width] * maxlonglist\n\n Googlesheets('data pay direct!h1:z60', maxlist, client) \n Googlesheets('data pay direct!h1:z60', lc.datsheets, client) \n\n\n lc = ListConventer(data_campaign,\n 'width_headers')\n lc.conventer()\n\n maxlonglist = 700\n maxwidthlist = 7\n width = [''] * maxwidthlist\n maxlist = [width] * maxlonglist\n\n Googlesheets('data pay direct!a18:g800', maxlist, client) \n Googlesheets('data pay direct!a18:g800', lc.datsheets, client)\n", "repo_name": "ustsl/IAB_FW_CLEAN", "sub_path": "reports/report list 1/pay_direct_report.py", "file_name": "pay_direct_report.py", "file_ext": "py", "file_size_in_byte": 4808, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "scripts.filemanager.googlesheets_upload_lib.ListConventer", "line_number": 106, "usage_type": "call"}, {"api_name": "scripts.filemanager.googlesheets_upload_lib.Googlesheets", "line_number": 115, "usage_type": "call"}, {"api_name": "scripts.filemanager.googlesheets_upload_lib.Googlesheets", "line_number": 116, "usage_type": "call"}, {"api_name": "scripts.filemanager.googlesheets_upload_lib.ListConventer", "line_number": 120, "usage_type": "call"}, {"api_name": "scripts.filemanager.googlesheets_upload_lib.Googlesheets", "line_number": 129, "usage_type": "call"}, {"api_name": "scripts.filemanager.googlesheets_upload_lib.Googlesheets", "line_number": 130, "usage_type": "call"}, {"api_name": "scripts.filemanager.googlesheets_upload_lib.ListConventer", "line_number": 133, "usage_type": "call"}, {"api_name": "scripts.filemanager.googlesheets_upload_lib.Googlesheets", "line_number": 142, "usage_type": "call"}, {"api_name": "scripts.filemanager.googlesheets_upload_lib.Googlesheets", "line_number": 143, "usage_type": "call"}]} +{"seq_id": "37384237854", "text": "''' Help the user achieve a high score in a real game of threes by using a move searcher.\n\nThis assistant takes manual input from the user, allowing it to be used with any game. '''\n\nfrom __future__ import print_function\nimport os\nimport numpy as np\nimport re\nimport sys\n\nfrom base_assistant import run_assistant, movenames\nfrom threes import do_move, get_lines\n\nPY3 = sys.version_info[0] >= 3\n\nif not PY3:\n range = xrange\n input = raw_input\n\ndef to_ind(val):\n try:\n return {0:0, 1:1, 2:2, 3:3, 6:4, 12:5, 24:6, 48:7, 96:8, 192:9, 384:10, 768:11, 1536:12, 3072:13, 6144:14}[val]\n except KeyError as e:\n raise Exception(\"Invalid value %s\" % val)\n\nclass ManualAssistant:\n def __init__(self):\n self.last_board = None\n self.last_move = None\n\n def _ask_tileset(self):\n tileset = input(\"Upcoming tile(s)? \")\n tileset = {'blue': '1', 'red': '2', 'white': '3+'}.get(tileset, tileset)\n if tileset in ('3+', '6+'):\n return tileset # will be fixed up\n tileset = re.split(r'[\\s,]', tileset)\n return {to_ind(int(v)) for v in tileset}\n\n def _fixup_tileset(self, tileset, board):\n if tileset not in ('3+', '6+'):\n return tileset\n\n maxval = board.max()\n out = set(range(4, maxval-3+1))\n if tileset == '3+':\n out |= {3}\n else:\n out |= {4} # make sure the tileset isn't empty\n return out\n\n def _parse_delta(self, ind, val=None, move=None):\n if self.last_board is None:\n raise Exception(\"Can't specify a delta: last board is unknown\")\n\n ind = int(ind)\n if val is None:\n if len(self.last_tiles) > 1:\n raise Exception(\"Can't omit tile value: multiple possible previous tiles\")\n val = list(self.last_tiles)[0]\n else:\n val = to_ind(int(val))\n if val not in self.last_tiles:\n raise Exception(\"New tile wasn't in previous tile set\")\n\n if move is None:\n move = self.last_move\n\n move = movenames.index(move)\n newboard = self.last_board.copy()\n changed = do_move(newboard, move)\n line = get_lines(newboard, move)[ind-1]\n if line[-1] != 0:\n raise Exception(\"Incorrect changed row/col\")\n line[-1] = val\n return newboard\n\n def _parse_board(self, bits):\n out = np.array([to_ind(int(x)) if x else 0 for x in bits], dtype=int)\n return out.reshape((4,4))\n\n def _ask_board(self):\n if self.last_board is None:\n print(\"Current board?\")\n else:\n print(\"Current board or difference from last board?\")\n\n bits = []\n while 1:\n line = re.split(r'[\\s,]+', input())\n bits += line\n if 1 <= len(bits) < 4:\n return self._parse_delta(*bits)\n elif len(bits) == 16:\n return self._parse_board(bits)\n elif len(bits) > 16:\n raise Exception(\"More than 16 numbers specified!\")\n\n def gen_board(self):\n while 1:\n while 1:\n try:\n board = self._ask_board()\n break\n except Exception as e:\n print(\"Didn't understand your input:\", e)\n\n while 1:\n try:\n tileset = self._ask_tileset()\n break\n except Exception as e:\n print(\"Didn't understand your input:\", e)\n\n tileset = self._fixup_tileset(tileset, board)\n yield board, tileset, False\n self.last_board = board\n self.last_tiles = tileset\n\n def make_move(self, move):\n print(\"*** Suggested move:\", move)\n print()\n self.last_move = move\n\ndef parse_args(argv):\n import argparse\n parser = argparse.ArgumentParser(description=\"Suggest moves for Threes!\")\n\n args = parser.parse_args(argv)\n return args\n\ndef main(argv):\n from itertools import count\n args = parse_args(argv)\n\n print('Welcome to the Threes! assistant. See README.md for help on input formats.')\n assistant = ManualAssistant()\n run_assistant(assistant.gen_board(), assistant.make_move, False)\n\nif __name__ == '__main__':\n import sys\n exit(main(sys.argv[1:]))\n", "repo_name": "nneonneo/threes-ai", "sub_path": "manual_assistant.py", "file_name": "manual_assistant.py", "file_ext": "py", "file_size_in_byte": 4339, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 50, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sys.version_info", "line_number": 14, "usage_type": "attribute"}, {"api_name": "re.split", "line_number": 36, "usage_type": "call"}, {"api_name": "base_assistant.movenames.index", "line_number": 68, "usage_type": "call"}, {"api_name": "base_assistant.movenames", "line_number": 68, "usage_type": "name"}, {"api_name": "threes.do_move", "line_number": 70, "usage_type": "call"}, {"api_name": "threes.get_lines", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 78, "usage_type": "call"}, {"api_name": "re.split", "line_number": 89, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 126, "usage_type": "call"}, {"api_name": "base_assistant.run_assistant", "line_number": 137, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 141, "usage_type": "attribute"}]} +{"seq_id": "31294166628", "text": "import os\n\nimport numpy as np\nfrom analysis.simulation import Simulator\nfrom data import dataOperation\nfrom data.dataOperation import combineTopicChat\nfrom uti.utility import write_to_json_file, read_csv_todf, write_to_csv_file, create_fix_random_matrix\n\n\nclass Synthesizer:\n def __init__(self, text_source, output_tu_json, output_synthesized_text_s, sequence_max):\n self.sequence_max = sequence_max\n self.output_tu_json = output_tu_json\n self.text_source = text_source\n self.output_synthesized_text_s = output_synthesized_text_s\n def synthesize(self, A):\n if os.path.exists(self.output_tu_json):\n os.remove(self.output_tu_json)\n if os.path.exists(self.output_synthesized_text_s):\n os.remove(self.output_synthesized_text_s)\n chatSequence = []\n sequence_ID = 1\n csv_columns = ['sequenceID','text']\n all_messages = [csv_columns]\n df = read_csv_todf(self.text_source)\n index = 1\n for i in range(10000):\n simulator1 = Simulator(A, D, 0)\n simulator2 = Simulator(A, D, 2)\n simulator1.simulation()\n if len(simulator1.time_sequence) < 7 or len(simulator1.time_sequence)>12:\n continue\n simulator2.simulation()\n if len(simulator2.time_sequence) < 7 or len(simulator2.time_sequence)>12:\n continue\n result, l1, l2 = combineTopicChat(simulator1, simulator2)\n group_sequence = result[\"group_sequence\"]\n\n sequence1 = df[df.sequenceID ==index]\n index+=1\n indexlist = sequence1.index\n count = len(indexlist)\n while l1 > count:\n sequence1 = df[df.sequenceID == index]\n indexlist = sequence1.index\n count = len(indexlist)\n index+=1\n sequence2 = df[df.sequenceID == index]\n indexlist = sequence2.index\n count = len(indexlist)\n while l2 > count:\n sequence2 = df[df.sequenceID == index]\n indexlist = sequence2.index\n count = len(indexlist)\n index += 1\n\n textlist1 = sequence1.text.to_list()\n textlist2 = sequence2.text.to_list()\n p1=p2=0\n for group_id in group_sequence:\n if group_id == 0:\n all_messages.append([sequence_ID, textlist1[p1]])\n p1+=1\n else :\n all_messages.append([sequence_ID, textlist2[p2]])\n p2+=1\n chatSequence.append(result)\n sequence_ID+=1\n if sequence_ID == self.sequence_max:\n break\n\n write_to_csv_file(self.output_synthesized_text_s, all_messages)\n write_to_json_file(self.output_tu_json, chatSequence)\n\n def synthesize_random(self, A):\n if os.path.exists(self.output_tu_json):\n os.remove(self.output_tu_json)\n if os.path.exists(self.output_synthesized_text_s):\n os.remove(self.output_synthesized_text_s)\n chatSequence = []\n sequence_ID = 1\n csv_columns = ['sequenceID','text']\n all_messages = [csv_columns]\n df = read_csv_todf(self.text_source)\n index = 1\n for i in range(10000):\n simulator1 = Simulator(A, D, 0)\n simulator1.simulation()\n if len(simulator1.time_sequence) < 7 or len(simulator1.time_sequence)> 12:\n continue\n\n l1 = len(simulator1.time_sequence)\n group_sequence = simulator1.group_sequence\n\n sequence1 = df[df.sequenceID ==index]\n index+=1\n indexlist = sequence1.index\n count = len(indexlist)\n while l1 > count:\n sequence1 = df[df.sequenceID == index]\n indexlist = sequence1.index\n count = len(indexlist)\n index+=1\n\n\n textlist1 = sequence1.text.to_list()\n\n p1=0\n for group_id in group_sequence:\n all_messages.append([sequence_ID, textlist1[p1]])\n p1+=1\n\n chatSequence.append({\"time_sequence\":simulator1.time_sequence, \"user_sequence\":simulator1.user_sequence})\n sequence_ID+=1\n if sequence_ID == self.sequence_max:\n break\n\n write_to_csv_file(self.output_synthesized_text_s, all_messages)\n write_to_json_file(self.output_tu_json, chatSequence)\n\n\n\nif __name__ == '__main__':\n D = 4\n A = create_fix_random_matrix(D)\n np.fill_diagonal(A, 0)\n '''\n A[0, 1] = 0.9\n A[0, 2] = 0.01\n A[0, 3] = 0.01\n A[1, 0] = 0.9\n A[1, 2] = 0.01\n A[1, 3] = 0.01\n A[2, 0] = 0.01\n A[2, 1] = 0.01\n A[2, 3] = 0.9\n A[3, 0] = 0.01\n A[3, 1] = 0.01\n A[3, 2] = 0.9\n '''\n folder = \"/home/chauncey/PycharmProjects/Parsing_Telegram_Chat_History/data/synthesizer_data/blended_skill_talk/\"\n source_file = os.path.join(folder, \"test.csv\" )\n output_tu_json =os.path.join(folder, \"/tu_sequence.json\" )\n output_synthesized_text_s = os.path.join(folder, \"/text_sequence.csv\")\n synthesizer =Synthesizer(source_file,output_tu_json,output_synthesized_text_s,201)\n synthesizer.synthesize(A)", "repo_name": "ChaunceyCXC/Infectivity_Network", "sub_path": "preprocess/Synthesizer.py", "file_name": "Synthesizer.py", "file_ext": "py", "file_size_in_byte": 5367, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "os.path.exists", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 20, "usage_type": "call"}, {"api_name": "uti.utility.read_csv_todf", "line_number": 25, "usage_type": "call"}, {"api_name": "analysis.simulation.Simulator", "line_number": 28, "usage_type": "call"}, {"api_name": "analysis.simulation.Simulator", "line_number": 29, "usage_type": "call"}, {"api_name": "data.dataOperation.combineTopicChat", "line_number": 36, "usage_type": "call"}, {"api_name": "uti.utility.write_to_csv_file", "line_number": 72, "usage_type": "call"}, {"api_name": "uti.utility.write_to_json_file", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path", "line_number": 76, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path", "line_number": 78, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 79, "usage_type": "call"}, {"api_name": "uti.utility.read_csv_todf", "line_number": 84, "usage_type": "call"}, {"api_name": "analysis.simulation.Simulator", "line_number": 87, "usage_type": "call"}, {"api_name": "uti.utility.write_to_csv_file", "line_number": 118, "usage_type": "call"}, {"api_name": "uti.utility.write_to_json_file", "line_number": 119, "usage_type": "call"}, {"api_name": "uti.utility.create_fix_random_matrix", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.fill_diagonal", "line_number": 126, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 142, "usage_type": "call"}, {"api_name": "os.path", "line_number": 142, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 143, "usage_type": "call"}, {"api_name": "os.path", "line_number": 143, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 144, "usage_type": "call"}, {"api_name": "os.path", "line_number": 144, "usage_type": "attribute"}]} +{"seq_id": "39091185249", "text": "from flask import render_template, flash, request, url_for, redirect, abort, session, Markup\nfrom flask_login import login_user, current_user, logout_user, login_required\nfrom flask_mail import Message\nfrom application import app, bcrypt, mail, login_manager\n\nfrom application.classes.course import Course \nfrom application.classes.user import User\nfrom application.classes.assignment import Assignment\nfrom application.forms.forms import AssignmentForm\n\nimport os \nimport json \nimport re\nfrom datetime import datetime \nfrom bson import ObjectId\n\n## Routesin this file\n# /add_assignment\n# /update_assignment\n\n@app.route(\"/add_assignment\", methods=[\"GET\", \"POST\"], defaults={'close': False})\n@app.route(\"/add_assignment/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef add_assignment(close):\n form = AssignmentForm()\n\n courses = sorted(current_user.courses, key = lambda x: x.period)\n choices = [(str(course.id), f\"{str(course.name)} - {course.period}\") for course in courses]\n form.course.choices = choices\n\n if form.validate_on_submit():\n a = Assignment(str(ObjectId()), form.name.data, form.a_type.data, form.course.data, \n datetime.combine(form.due_date.data, form.due_time.data), form.notes.data)\n current_user.add_assignment(a)\n\n if close:\n return \"\"\n\n flash('Assignment added successfuly', 'success')\n return redirect(url_for(\"dashboard\"))\n\n return render_template('add_assignment.html', form=form, update=False, close=close)\n\n@app.route(\"/update_assignment/\", methods=[\"GET\", \"POST\"], defaults={'close': False})\n@app.route(\"/update_assignment//\", methods=[\"GET\", \"POST\"])\n@login_required\ndef update_assignment(assignment_id, close):\n form = AssignmentForm()\n\n assignment = current_user.get_assignment_by_id(assignment_id)\n if not assignment:\n abort(404)\n\n form = AssignmentForm(name=assignment.name, course_id=assignment.course_id, due_date=assignment.due_date.date(),\n due_time=assignment.due_date.time(), notes=assignment.notes, a_type=assignment.a_type)\n\n form.submit.label.text = \"Update Assignment\"\n\n courses = sorted(current_user.courses, key = lambda x: x.period)\n choices = [(str(course.id), f\"{str(course.name)} - {course.period}\") for course in courses]\n form.course.choices = choices\n\n if form.validate_on_submit():\n current_user.update_assignment(assignment_id, name=form.name.data, a_type=form.a_type.data,\n course_id=form.course.data, notes=form.notes.data,\n due_date=datetime.combine(form.due_date.data, form.due_time.data))\n flash('Assignment updated successfuly', 'success')\n return redirect(url_for(\"dashboard\"))\n\n form.course.data = assignment.course_id\n\n return render_template('add_assignment.html', form=form, update=True, assignment=assignment, close=close)\n\n@app.route(\"/complete_assignment/\", methods=[\"POST\"])\ndef complete_assignment(assignment_id):\n assignment = current_user.get_assignment_by_id(assignment_id)\n if not assignment:\n return {\"Status\": \"Failure\"}\n\n current_user.delete_assignment(assignment_id)\n current_user.increment_assignment_count()\n\n return {\"Status\": \"Success\"}\n\n@app.route(\"/delete_assignment/\", methods=[\"POST\"])\ndef delete_assignment(assignment_id):\n assignment = current_user.get_assignment_by_id(assignment_id)\n if not assignment:\n return {\"Status\": \"Failure\"}\n\n current_user.delete_assignment(assignment_id)\n\n return {\"Status\": \"Success\"}\n\n@app.route(\"/get_assignments//\", methods=[\"GET\"])\ndef get_assignments(course, a_type):\n assignments = [] if not current_user.assignments else current_user.assignments\n assignments = sorted(assignments, key=lambda x: x.due_date)\n assignments = [(a, current_user.get_course_by_id(a.course_id), a.due_date.strftime(\"%a, %m/%d/%y %I:%M %p\")) for a in assignments]\n \n if course != \"all\":\n assignments = [a for a in assignments if a[0].course_id == course]\n if a_type != \"all\":\n assignments = [a for a in assignments if a[0].a_type == a_type]\n\n return render_template('assignments_update.html', assignments=assignments)", "repo_name": "ronnachum11/locker", "sub_path": "application/routes/assignment_routes.py", "file_name": "assignment_routes.py", "file_ext": "py", "file_size_in_byte": 4404, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "application.forms.forms.AssignmentForm", "line_number": 25, "usage_type": "call"}, {"api_name": "flask_login.current_user.courses", "line_number": 27, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 27, "usage_type": "name"}, {"api_name": "application.classes.assignment.Assignment", "line_number": 32, "usage_type": "call"}, {"api_name": "bson.ObjectId", "line_number": 32, "usage_type": "call"}, {"api_name": "datetime.datetime.combine", "line_number": 33, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 33, "usage_type": "name"}, {"api_name": "flask_login.current_user.add_assignment", "line_number": 34, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 34, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 39, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 40, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 40, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 42, "usage_type": "call"}, {"api_name": "application.app.route", "line_number": 21, "usage_type": "call"}, {"api_name": "application.app", "line_number": 21, "usage_type": "name"}, {"api_name": "application.app.route", "line_number": 22, "usage_type": "call"}, {"api_name": "application.app", "line_number": 22, "usage_type": "name"}, {"api_name": "flask_login.login_required", "line_number": 23, "usage_type": "name"}, {"api_name": "application.forms.forms.AssignmentForm", "line_number": 48, "usage_type": "call"}, {"api_name": "flask_login.current_user.get_assignment_by_id", "line_number": 50, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 50, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 52, "usage_type": "call"}, {"api_name": "application.forms.forms.AssignmentForm", "line_number": 54, "usage_type": "call"}, {"api_name": "flask_login.current_user.courses", "line_number": 59, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 59, "usage_type": "name"}, {"api_name": "flask_login.current_user.update_assignment", "line_number": 64, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 64, "usage_type": "name"}, {"api_name": "datetime.datetime.combine", "line_number": 66, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 66, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 67, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 68, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 68, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 72, "usage_type": "call"}, {"api_name": "application.app.route", "line_number": 44, "usage_type": "call"}, {"api_name": "application.app", "line_number": 44, "usage_type": "name"}, {"api_name": "application.app.route", "line_number": 45, "usage_type": "call"}, {"api_name": "application.app", "line_number": 45, "usage_type": "name"}, {"api_name": "flask_login.login_required", "line_number": 46, "usage_type": "name"}, {"api_name": "flask_login.current_user.get_assignment_by_id", "line_number": 76, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 76, "usage_type": "name"}, {"api_name": "flask_login.current_user.delete_assignment", "line_number": 80, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 80, "usage_type": "name"}, {"api_name": "flask_login.current_user.increment_assignment_count", "line_number": 81, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 81, "usage_type": "name"}, {"api_name": "application.app.route", "line_number": 74, "usage_type": "call"}, {"api_name": "application.app", "line_number": 74, "usage_type": "name"}, {"api_name": "flask_login.current_user.get_assignment_by_id", "line_number": 87, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 87, "usage_type": "name"}, {"api_name": "flask_login.current_user.delete_assignment", "line_number": 91, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 91, "usage_type": "name"}, {"api_name": "application.app.route", "line_number": 85, "usage_type": "call"}, {"api_name": "application.app", "line_number": 85, "usage_type": "name"}, {"api_name": "flask_login.current_user.assignments", "line_number": 97, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 97, "usage_type": "name"}, {"api_name": "flask_login.current_user.get_course_by_id", "line_number": 99, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 99, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 106, "usage_type": "call"}, {"api_name": "application.app.route", "line_number": 95, "usage_type": "call"}, {"api_name": "application.app", "line_number": 95, "usage_type": "name"}]} +{"seq_id": "73507352383", "text": "import argparse \n\nimport torch \nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom sleep_classification.trainer import Trainer\nfrom sleep_classification.data_loader import load_dataloader_for_featureNet\n\nfrom sleep_classification.models import DeepSleepNet\n\ndef define_argparser():\n p = argparse.ArgumentParser() \n \n p.add_argument('--model_fn', required=True)\n p.add_argument('--log_dir', default=\"/tensorboard_logs\")\n p.add_argument('--gpu_id', type= int,default=0 if torch.cuda.is_available() else -1)\n\n p.add_argument('--train_ratio', type=float,default=0.9)\n p.add_argument('--data_dir', type=str,default='G:/내 드라이브/EEG_classification/output')\n p.add_argument('--n_fold',type=int,default=20)\n p.add_argument('--fold_idx', type=int,required=True)\n \n p.add_argument('--batch_size',type=int,default=512)\n p.add_argument('--n_epochs',type=int,default=200)\n p.add_argument('--verbose',type=int,default=2)\n\n p.add_argument('--use_dropout',type=bool, default=True)\n p.add_argument('--use_rnn',type=bool, default=True)\n \n p.add_argument('--max_grad', type=float, default=-1)\n\n config = p.parse_args()\n\n return config\n\ndef main(config):\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n train_loader, valid_loader, test_loader = load_dataloader_for_featureNet(config)\n\n print(\"Train:\", len(train_loader.dataset))\n print(\"Valid:\", len(valid_loader.dataset))\n print(\"Test:\", len(test_loader.dataset))\n\n model = DeepSleepNet(input_dim=1,n_classes=5,is_train=True,use_dropout=config.use_dropout,use_rnn=config.use_rnn).to(device)\n optimizer = optim.Adam(model.parameters())\n crit = nn.CrossEntropyLoss()\n\n trainer = Trainer(config)\n\n trainer.tb_logger.writer.add_graph(model=model,input_to_model=torch.randn(128,1,3000).to(device),verbose=True)\n\n if config.verbose >= 2:\n print(model)\n print(optimizer)\n print(crit)\n\n trainer.train(model, crit, optimizer, train_loader, valid_loader)\n trainer.test(test_loader)\n trainer.tb_logger.close()\n\n\n\nif __name__ == '__main__':\n config = define_argparser()\n main(config)\n", "repo_name": "Ldoun/EEG-AI", "sub_path": "train.py", "file_name": "train.py", "file_ext": "py", "file_size_in_byte": 2171, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 13, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 17, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 38, "usage_type": "attribute"}, {"api_name": "sleep_classification.data_loader.load_dataloader_for_featureNet", "line_number": 40, "usage_type": "call"}, {"api_name": "sleep_classification.models.DeepSleepNet", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 47, "usage_type": "name"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 48, "usage_type": "name"}, {"api_name": "sleep_classification.trainer.Trainer", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.randn", "line_number": 52, "usage_type": "call"}]} +{"seq_id": "74944157501", "text": "from django import forms\nfrom .models import Url\nfrom django.forms.widgets import TextInput\n\n\nclass UrlForm(forms.ModelForm):\n\n long_url = forms.URLField(\n max_length=200, \n label=\"URL\",\n # help_text=\"Please enter the URL of the page.\", \n initial=\"http://\",\n widget=TextInput\n )\n\n class Meta:\n model = Url\n fields= ['long_url']\n", "repo_name": "theduckfliesagain/url-shortener", "sub_path": "shortener/urls/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 387, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.forms.ModelForm", "line_number": 6, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 6, "usage_type": "name"}, {"api_name": "django.forms.URLField", "line_number": 8, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 8, "usage_type": "name"}, {"api_name": "django.forms.widgets.TextInput", "line_number": 13, "usage_type": "name"}, {"api_name": "models.Url", "line_number": 17, "usage_type": "name"}]} +{"seq_id": "15667700901", "text": "import typing\r\n\r\nfrom kombu.exceptions import OperationalError\r\nfrom redis.exceptions import ConnectionError as RedisConnectionError\r\n\r\nfrom project.server.extensions import celery, redis_client\r\n\r\n\r\ndef celery_status() -> typing.Optional[dict]:\r\n \"\"\" Try to get status of celery. Returns None is celery is not active\"\"\"\r\n try:\r\n i = celery.control.inspect()\r\n stats = i.stats()\r\n registered_tasks = i.registered()\r\n active_tasks = i.active()\r\n scheduled_tasks = i.scheduled()\r\n result = {\r\n 'stats': stats,\r\n 'registered_tasks': registered_tasks,\r\n 'active_tasks': active_tasks,\r\n 'scheduled_tasks': scheduled_tasks\r\n }\r\n return result\r\n except OperationalError:\r\n return None\r\n\r\n\r\ndef redis_status() -> typing.Optional[bool]:\r\n \"\"\" Try to ping redis. Return None on error and True on success. \"\"\"\r\n try:\r\n redis = redis_client.redis\r\n return redis.ping()\r\n except RedisConnectionError:\r\n return None\r\n", "repo_name": "M0r13n/Smartphoniker-shop", "sub_path": "project/server/common/stats.py", "file_name": "stats.py", "file_ext": "py", "file_size_in_byte": 1049, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "24", "api": [{"api_name": "project.server.extensions.celery.control.inspect", "line_number": 12, "usage_type": "call"}, {"api_name": "project.server.extensions.celery.control", "line_number": 12, "usage_type": "attribute"}, {"api_name": "project.server.extensions.celery", "line_number": 12, "usage_type": "name"}, {"api_name": "kombu.exceptions.OperationalError", "line_number": 24, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 9, "usage_type": "attribute"}, {"api_name": "redis.exceptions", "line_number": 31, "usage_type": "name"}, {"api_name": "project.server.extensions.redis_client.redis", "line_number": 31, "usage_type": "attribute"}, {"api_name": "project.server.extensions.redis_client", "line_number": 31, "usage_type": "name"}, {"api_name": "redis.exceptions.ping", "line_number": 32, "usage_type": "call"}, {"api_name": "redis.exceptions", "line_number": 32, "usage_type": "name"}, {"api_name": "redis.exceptions.ConnectionError", "line_number": 33, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 28, "usage_type": "attribute"}]} +{"seq_id": "9894409543", "text": "import asyncio\nimport sqlite3\nfrom fetch_data import get_info\n\nconn = sqlite3.connect('../../mobile.db')\nresult = asyncio.get_event_loop().run_until_complete(get_info())\nc = conn.cursor()\n# Create table - STATIONS\nc.execute('''CREATE TABLE STATIONS\n ([generated_id] INTEGER PRIMARY KEY ,[Station_id] TEXT, [Station_Name] TEXT, [Latitude] FLOAT, [Longnitude] FLOAT)''')\nfor r in result:\n c.execute(\"INSERT INTO STATIONS VALUES (NULL, :Station_id, :Station_Name, :Latitude, :Longnitude)\", r)\n\nconn.commit()\n", "repo_name": "Kadir94/djangoAPI", "sub_path": "djangoapp/mobiletasks/connectiondb.py", "file_name": "connectiondb.py", "file_ext": "py", "file_size_in_byte": 520, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sqlite3.connect", "line_number": 5, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 6, "usage_type": "call"}, {"api_name": "fetch_data.get_info", "line_number": 6, "usage_type": "call"}]} +{"seq_id": "11776707362", "text": "# pyre-strict\n\nimport setuptools\n\nwith open('README.md', 'r') as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name='paytext',\n version='0.0.2',\n author='Yngve Høiseth',\n author_email='yngve@hoiseth.net',\n description='Generalize texts from payment card transactions',\n long_description=long_description,\n long_description_content_type='text/markdown',\n url='https://github.com/yhoiseth/paytext',\n packages=setuptools.find_packages(),\n classifiers=(\n 'Programming Language :: Python :: 3',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n ),\n)\n", "repo_name": "yhoiseth/paytext", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 644, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "setuptools.setup", "line_number": 8, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 17, "usage_type": "call"}]} +{"seq_id": "8509312399", "text": "from django.test import TestCase\n\nfrom ui.voyager import get_open_library_item_title\n\n\nclass OpenLibraryTitleTest(TestCase):\n def test_correct_title(self):\n \"this is from issue 487 where open libray link points to correct title\"\n title = \"Life on the Mississippi\"\n open_library_link = \"http://openlibrary.org/books/OL6710196M/Life_on_the_Mississippi\"\n open_library_title = get_open_library_item_title(open_library_link)\n self.assertEqual(title[0:10], open_library_title[0:10])\n\n def test_incorrect_title(self):\n \"from issue 420\"\n title = \"Frank Lloyd Wright's Hanna House : the clients' report Paul R. and Jean S. Hanna\"\n open_library_link = \"http://openlibrary.org/books/OL24933180M/The_Baptist_position_as_to_the_Bible\"\n open_library_title = get_open_library_item_title(open_library_link)\n self.assertNotEqual(title[0:10], open_library_title[0:10])\n", "repo_name": "gwu-libraries/launchpad", "sub_path": "lp/ui/tests/open_library_title_test.py", "file_name": "open_library_title_test.py", "file_ext": "py", "file_size_in_byte": 927, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 15, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.test.TestCase", "line_number": 6, "usage_type": "name"}, {"api_name": "ui.voyager.get_open_library_item_title", "line_number": 11, "usage_type": "call"}, {"api_name": "ui.voyager.get_open_library_item_title", "line_number": 18, "usage_type": "call"}]} +{"seq_id": "41129438773", "text": "import scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.item import Item, Field\n\n\nfrom items import awayTeamRushItem\nimport logging\nimport re\n\nclass EspnspiderSpider(scrapy.Spider):\n name = \"espnSpider\"\n allowed_domains = [\"espn.com\"]\n start_urls = (\n 'http://www.espn.com/nfl/boxscore?gameId=400874586',\n )\n\n rules = (\n Rule(LinkExtractor(), callback='parse_item', follow=False),\n )\n\n global awayItem\n awayItem = awayTeamRushItem()\n\n def parse(self, response):\n rushers = response.xpath('//*[@id=\"gamepackage-rushing\"]/div/div[1]/div/div/table/tbody/*/td[1]/a/span[1]/text()').extract()\n\n carries = response.xpath('//*[@id=\"gamepackage-rushing\"]/div/div[1]/div/div/table/tbody/*/td[2]/text()').extract()\n\n yards = response.xpath('//*[@id=\"gamepackage-rushing\"]/div/div[1]/div/div/table/tbody/*/td[3]/text()').extract()\n\n averages = response.xpath('//*[@id=\"gamepackage-rushing\"]/div/div[1]/div/div/table/tbody/*/td[4]/text()').extract()\n\n touchdowns = response.xpath('//*[@id=\"gamepackage-rushing\"]/div/div[1]/div/div/table/tbody/*/td[5]/text()').extract()\n\n longs = response.xpath('//*[@id=\"gamepackage-rushing\"]/div/div[1]/div/div/table/tbody/*/td[6]/text()').extract()\n\n awayItemIndex = 0\n\n for rusher in rushers:\n awayItem = awayTeamRushItem()\n\n awayItem['car'] = str(carries[awayItemIndex])\n awayItem['yds'] = str(yards[awayItemIndex])\n awayItem['avg'] = str(averages[awayItemIndex])\n awayItem['td'] = str(touchdowns[awayItemIndex])\n awayItem['longest'] = str(longs[awayItemIndex])\n awayItem['rusher'] = str(rusher)\n\n awayItemIndex+=1\n\n yield awayItem\n", "repo_name": "gannonk08/scrapy-demo", "sub_path": "scrapy_demo/scrapy_demo/spiders/espnSpider.py", "file_name": "espnSpider.py", "file_ext": "py", "file_size_in_byte": 1817, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "scrapy.Spider", "line_number": 11, "usage_type": "attribute"}, {"api_name": "scrapy.spiders.Rule", "line_number": 19, "usage_type": "call"}, {"api_name": "scrapy.linkextractors.LinkExtractor", "line_number": 19, "usage_type": "call"}, {"api_name": "items.awayTeamRushItem", "line_number": 23, "usage_type": "call"}, {"api_name": "items.awayTeamRushItem", "line_number": 41, "usage_type": "call"}]} +{"seq_id": "35886338081", "text": "import torch\nfrom tqdm import tqdm\nimport json, os, sys\nfrom rouge import Rouge\nfrom transformers import AutoTokenizer\nfrom nltk import sent_tokenize\nimport argparse\n\ndef get_args(): \n parser = argparse.ArgumentParser()\n parser.add_argument('--ckpt', default=125000, type=int)\n args = parser.parse_args()\n return args\n\nargs = get_args()\nckpt = args.ckpt\n\nsys.path.append('src') \n\ndevice = 'cuda'\nckpt_list = [_.split('-')[-1] for _ in os.listdir('/workspace/ckpt/kobart_ckpt') if _.startswith('checkpoint')]\nckpt_list.sort()\n\ntest_dataset = json.load(open('data/article/valid_dataset.json', 'r', encoding='utf-8'))\ntokenizer = AutoTokenizer.from_pretrained('models/kobart')\nrouge_scorer = Rouge()\ntarget_list = [target['abs'] for target in test_dataset]\n\ndef tokenize_list(data_list):\n return [' '.join(tokenizer.tokenize(data)) for data in data_list]\n\n\ntokenized_target_list = tokenize_list(target_list)\nbest_rouge = 0\n\n# for ckpt in ckpt_list:\nresult_list = []\nmodel_path = f'/workspace/ckpt/kobart_ckpt/checkpoint-{ckpt}'\nmodel = torch.load(os.path.join(model_path, 'multitask_ext_abs_summary_model.pt')).model.to(device)\nprint(f\"Current doing... {model_path.split('/')[-1]}\")\n\nfor data in tqdm(test_dataset):\n doc = ' '.join(data['sentences'])\n input_ids = tokenizer(doc, return_tensors=\"pt\").input_ids.to(device)\n\n output = model.generate(input_ids, num_beams=5, eos_token_id=1, repetition_penalty=1.2, no_repeat_ngram_size=1, early_stopping=True,\n max_length=150)\n result = tokenizer.decode(output[0], skip_special_toknes=True).replace('', '')\n result = sent_tokenize(result)[0]\n result_list.append(result)\n\ntokenized_result_list = tokenize_list(result_list)\nscores = rouge_scorer.get_scores(tokenized_result_list, tokenized_target_list, avg=True)\nrouge_score = scores['rouge-l']['f']\nif rouge_score > best_rouge:\n best_rouge = rouge_score\n best_score = scores\n best_ckpt = ckpt\nprint(f\"Best CKPT: {best_ckpt}, Best score: {best_score}\")\n\nwith open(f'results/infer/{ckpt}_results.txt', 'w', encoding='utf-8') as f:\n f.write('\\n'.join(result_list))\n\nwith open(f'results/rouge/{ckpt}_rouge.json', 'w') as f:\n json.dump(best_score, f, indent='\\t')", "repo_name": "CommoMo/Ext-Abs-Summ", "sub_path": "get_rouge.py", "file_name": "get_rouge.py", "file_ext": "py", "file_size_in_byte": 2233, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 10, "usage_type": "call"}, {"api_name": "sys.path.append", "line_number": 18, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 18, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 21, "usage_type": "call"}, {"api_name": "json.load", "line_number": 24, "usage_type": "call"}, {"api_name": "transformers.AutoTokenizer.from_pretrained", "line_number": 25, "usage_type": "call"}, {"api_name": "transformers.AutoTokenizer", "line_number": 25, "usage_type": "name"}, {"api_name": "rouge.Rouge", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path", "line_number": 39, "usage_type": "attribute"}, {"api_name": "tqdm.tqdm", "line_number": 42, "usage_type": "call"}, {"api_name": "nltk.sent_tokenize", "line_number": 49, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 65, "usage_type": "call"}]} +{"seq_id": "4180674774", "text": "# -*- coding:utf-8 -*-\r\n\"\"\"\r\n 爬虫案例流程\r\n 1,明确需求,需要爬取那些信息?\r\n 2,分析信息来自与哪里?\r\n 开发者工具,抓包分析,数据包来源与哪里?\r\n 视频 m3u8,分片段模式\r\n 分析网页源代码进行分析\r\n 想要视频内容 -------》 分片段ts文件 ---------》 m3u8文件里面 ----》 网页源代码\r\n headers ----> cookies host referer ua\r\n 3,\r\n 代码具体实现:\r\n 1,发送请求,网站url发起请求\r\n 2,获取数据,获取服务器相应html数据,并通过re模块正则表达式匹配\r\n 3,解析数据,提取我们想要的,m3u8 Ts,url请求链接\r\n\r\n 4,发送请求 m3u8url 获取 Ts数据\r\n 5,获取数据\r\n 6,解析数据\r\n 7,保存数据\r\n\"\"\"\r\nimport requests\r\nimport re\r\nimport json\r\nfrom pathlib import Path\r\nimport time\r\n# 伪装浏览器 headers\r\nheaders = {\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36\"\r\n}\r\nvedio_dir = Path('./vedio')\r\nvedio_dir.mkdir(exist_ok=True)\r\n\r\ndef afun_init(url):\r\n # 发送请求,获取数据\r\n response = requests.get(url=url, headers=headers)\r\n # 提取视频标题\r\n title = re.findall('\"title\":\"(.*?)\"', response.text)[1]\r\n print(title)\r\n # 获取m3u8链接,获取Ts数据\r\n u3u8_str = re.findall('window.pageInfo = window.videoInfo = (.*?)};', response.text)[0]\r\n u3u8_str += '}'\r\n # 字符串类型数据\r\n # 根据键值对取m3u8url\r\n u3u8_json = json.loads(u3u8_str)\r\n # 二次转换\r\n # backupUrl 视频m3u8链接 对应的视频画质\r\n m3u8_url = \\\r\n json.loads(u3u8_json['currentVideoInfo']['ksPlayJson'])['adaptationSet'][0]['representation'][0]['backupUrl'][0]\r\n print(m3u8_url)\r\n # 获取m3u8链接完毕,获取Ts链接全部文件\r\n m3u8_data = requests.get(url=m3u8_url, headers=headers).text\r\n # 解析数据,获取Ts文件\r\n # 拆分分割符号\r\n m3u8_data = re.sub('#E.*', '', m3u8_data).split()\r\n return m3u8_data, title\r\n\r\nif __name__ == '__main__':\r\n print(\"A站视频下载器|单线程版\")\r\n while True:\r\n print(\"注: url值为 0 退出系统\")\r\n url = input(\"请输入视频url: \")\r\n if url == \"0\":\r\n break\r\n start_time = time.time()\r\n m3u8_data = afun_init(url)[0]\r\n title = afun_init(url)[1]\r\n # for 循环遍历 ts 内容\r\n print(m3u8_data)\r\n for ts in m3u8_data:\r\n ts_url = 'https://ali-safety-video.acfun.cn/mediacloud/acfun/acfun_video/' + ts\r\n # 获取视频二进制数据\r\n ts_content = requests.get(url=ts_url, headers=headers, timeout=5).content\r\n # 若视频标题不符合规范将会报错\r\n with open('./vedio/' + m3u8_data[0][0:5] + '.mp4', 'ab') as f:\r\n f.write(ts_content)\r\n print(ts_url)\r\n end_time = time.time()\r\n print(\"视频下载时间\", end_time - start_time)\r\n print(\"下载完毕\\n\")\r\n", "repo_name": "gaogaotwo/Project-Note-Code", "sub_path": "A站.py", "file_name": "A站.py", "file_ext": "py", "file_size_in_byte": 3129, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pathlib.Path", "line_number": 31, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 36, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 38, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 41, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 45, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 49, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 52, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 55, "usage_type": "call"}, {"api_name": "time.time", "line_number": 65, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 73, "usage_type": "call"}, {"api_name": "time.time", "line_number": 78, "usage_type": "call"}]} +{"seq_id": "34303176417", "text": "\n\nimport torch\nimport torch.nn.functional as F\n\nfrom diffusion import DiffusionTrainer\nfrom bert import DiffusionBERT\nfrom transformers import BertTokenizer\n\nT = 100\ntokenizer = BertTokenizer.from_pretrained(\"bert-base-uncased\")\nmodel = DiffusionBERT(vocab_size=tokenizer.vocab_size)\nmaxlen = 128\n\ntest = DiffusionTrainer(T=T,\n tokenizer=tokenizer,\n model=model,\n maxlen=maxlen)\n\nprint(\"mask_token_ids \", tokenizer.mask_token_id)\nprint(\"pad_token_ids \", tokenizer.pad_token_id)\nprint(\"number \", tokenizer.convert_ids_to_tokens([10000]))\n\nx_t = F.one_hot(torch.tensor(tokenizer.mask_token_id), num_classes=30522).repeat(128, 1).unsqueeze(0).cuda()\nattention_mask = torch.ones((1, 128)).cuda()\n\nprint(x_t.shape)\nprint(attention_mask.shape)\n\nresult = test.predict_text(x_t=x_t, attention_mask=attention_mask)\n\nprint(result)\n", "repo_name": "YHL04/diffusionbert", "sub_path": "__test__.py", "file_name": "__test__.py", "file_ext": "py", "file_size_in_byte": 890, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "transformers.BertTokenizer.from_pretrained", "line_number": 11, "usage_type": "call"}, {"api_name": "transformers.BertTokenizer", "line_number": 11, "usage_type": "name"}, {"api_name": "bert.DiffusionBERT", "line_number": 12, "usage_type": "call"}, {"api_name": "diffusion.DiffusionTrainer", "line_number": 15, "usage_type": "call"}, {"api_name": "torch.nn.functional.one_hot", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 24, "usage_type": "name"}, {"api_name": "torch.tensor", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "39993290159", "text": "from django.urls import path, include\n\nfrom .views import * \n\napp_name = 'blog'\nurlpatterns = [\n path('',IndexView.as_view(),name='index'),\n path('/', BlogSingleView.as_view(), name='blog_single'),\n path('contact/', ContactView.as_view(), name='contact'),\n path('about/', AboutView.as_view(), name='about'),\n path('subscribe/', subscribe, name='subscribe'),\n path('user/', include('blog.user_post_interactions.urls'))\n]", "repo_name": "ferizoozoo/MediumLikeBlog", "sub_path": "blog/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 445, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 12, "usage_type": "call"}]} +{"seq_id": "11429339586", "text": "# ============================================================================\n# FILE: type.py\n# AUTHOR: Shougo Matsushita \n# License: MIT license\n# ============================================================================\n\nfrom pynvim import Nvim\nimport typing\n\nfrom defx.base.column import Base, Highlights\nfrom defx.context import Context\nfrom defx.util import Candidate, len_bytes\nfrom defx.view import View\n\n\nclass Column(Base):\n\n def __init__(self, vim: Nvim) -> None:\n super().__init__(vim)\n\n self.name = 'type'\n types = [\n {\n 'name': 'text', 'globs': ['*.txt', '*.md', 'README'],\n 'icon': '[T]', 'highlight': 'Constant'\n },\n {\n 'name': 'image', 'globs': ['*.jpg'],\n 'icon': '[I]', 'highlight': 'Type'\n },\n {\n 'name': 'archive', 'globs': ['*.zip'],\n 'icon': '[A]', 'highlight': 'Special'\n },\n {\n 'name': 'executable', 'globs': ['*.exe'],\n 'icon': '[X]', 'highlight': 'Statement'\n },\n ]\n self.vars = {\n 'types': types,\n }\n self.has_get_with_highlights = True\n\n self._length: int = 0\n\n def on_init(self, view: View, context: Context) -> None:\n self._length = max([self.vim.call('strwidth', x['icon'])\n for x in self.vars['types']])\n\n def get_with_highlights(\n self, context: Context, candidate: Candidate\n ) -> typing.Tuple[str, Highlights]:\n for t in self.vars['types']:\n for glob in t['globs']:\n if not candidate['action__path'].match(glob):\n continue\n return (str(t['icon']), [\n (f\"{self.highlight_name}_{t['name']}\",\n self.start, len_bytes(t['icon']))\n ])\n\n return (' ' * self._length, [])\n\n def length(self, context: Context) -> int:\n return self._length\n\n def syntaxes(self) -> typing.List[str]:\n return [self.syntax_name + '_' + x['name'] for x\n in self.vars['types']]\n\n def highlight_commands(self) -> typing.List[str]:\n commands: typing.List[str] = []\n for t in self.vars['types']:\n commands.append(\n 'highlight default link {}_{} {}'.format(\n self.highlight_name, t['name'], t['highlight']))\n return commands\n", "repo_name": "Shougo/defx.nvim", "sub_path": "rplugin/python3/defx/column/type.py", "file_name": "type.py", "file_ext": "py", "file_size_in_byte": 2514, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1167, "dataset": "github-code", "pt": "24", "api": [{"api_name": "defx.base.column.Base", "line_number": 16, "usage_type": "name"}, {"api_name": "pynvim.Nvim", "line_number": 18, "usage_type": "name"}, {"api_name": "defx.view.View", "line_number": 47, "usage_type": "name"}, {"api_name": "defx.context.Context", "line_number": 47, "usage_type": "name"}, {"api_name": "defx.context.Context", "line_number": 52, "usage_type": "name"}, {"api_name": "defx.util.Candidate", "line_number": 52, "usage_type": "name"}, {"api_name": "defx.util.len_bytes", "line_number": 60, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 53, "usage_type": "attribute"}, {"api_name": "defx.base.column.Highlights", "line_number": 53, "usage_type": "name"}, {"api_name": "defx.context.Context", "line_number": 65, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 68, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 73, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 72, "usage_type": "attribute"}]} +{"seq_id": "30780282300", "text": "# -*- coding: utf-8 -*-\n\"\"\"User views.\"\"\"\n\nfrom flask import (\n Blueprint,\n current_app,\n flash,\n jsonify,\n redirect,\n render_template,\n request,\n url_for,\n)\nfrom flask_login import current_user, login_required\n\nfrom interview_simulator.extensions import db\nfrom interview_simulator.user.models import UserFile\n\nfrom .forms import UploadForm\nfrom .services import chat_gpt, gpt_questions, transcribe_audio_with_whisper\n\nblueprint = Blueprint(\"user\", __name__, url_prefix=\"/users\", static_folder=\"../static\")\n\n\n@blueprint.route(\"/upload\", methods=[\"GET\", \"POST\"])\n@login_required\ndef upload():\n \"\"\"\n Handles the uploading of the Resume and Job Description files.\n\n Returns:\n - A string representing the HTML page displaying the form for uploading the files.\n \"\"\"\n form = UploadForm()\n if form.validate_on_submit():\n resume_text = form.resume_text.data\n job_description = form.job_description.data\n\n # Save the uploaded resume and job description to the database\n user_file = UserFile(\n file_name=\"Resume\", file_content=resume_text, user=current_user\n )\n db.session.add(user_file)\n\n user_file = UserFile(\n file_name=\"Job Description\", file_content=job_description, user=current_user\n )\n db.session.add(user_file)\n\n db.session.commit()\n\n flash(\"Resume and Job Description uploaded successfully!\", \"success\")\n return redirect(url_for(\"user.home_logged_in\"))\n return render_template(\"users/upload.html\", form=form)\n\n\n@blueprint.route(\"/check_uploads\")\n@login_required\ndef check_uploads():\n \"\"\"\n Checks if the user has uploaded a resume and job description and returns a JSON response.\n\n Returns:\n - A string representing the JSON response indicating if the user has uploaded the files.\n \"\"\"\n latest_resume = (\n UserFile.query.filter_by(user_id=current_user.id, file_name=\"Resume\")\n .order_by(UserFile.upload_date.desc())\n .first()\n )\n latest_job_description = (\n UserFile.query.filter_by(user_id=current_user.id, file_name=\"Job Description\")\n .order_by(UserFile.upload_date.desc())\n .first()\n )\n\n if latest_resume and latest_job_description:\n return jsonify(\n {\n \"uploaded\": True,\n \"resume\": latest_resume.file_content,\n \"job_description\": latest_job_description.file_content,\n }\n )\n else:\n return jsonify({\"uploaded\": False, \"resume\": None, \"job_description\": None})\n\n\n@blueprint.route(\"/start_game\", methods=[\"POST\"])\n@login_required\ndef start_game():\n \"\"\"\n Starts the game by calling the gpt_questions() function.\n\n Returns:\n - A string representing the JSON response containing the interview questions.\n \"\"\"\n resume = request.json.get(\"resume\")\n job_description = request.json.get(\"job_description\")\n questions = gpt_questions(resume, job_description)\n return jsonify(questions)\n\n\n@blueprint.route(\"/transcribe\", methods=[\"POST\"])\n@login_required\ndef transcribe():\n \"\"\"\n Transcribes an audio file using the Whisper ASR API and returns a JSON response.\n\n Returns:\n - A string representing the JSON response containing the transcribed text,\n the ChatGPT API response and the question asked.\n \"\"\"\n # Get the audio file from the request\n audio_file = request.files.get(\"audio\")\n question = request.form.get(\"question\")\n\n # log the audio file\n current_app.logger.info(f\"Audio file: {audio_file}\")\n\n if audio_file:\n # Extract the audio data from the file\n audio_data = audio_file.read()\n\n # Extract the transcribed text from the API response\n transcription = transcribe_audio_with_whisper(audio_data)\n\n # Call the ChatGPT API\n response = chat_gpt(question, transcription)\n\n # Return the transcription as a JSON response\n return jsonify(\n {\"transcription\": transcription, \"response\": response, \"question\": question}\n )\n else:\n # Return an error response if no audio file was provided\n return jsonify({\"error\": \"No audio file provided\"}), 400\n\n\n@blueprint.route(\"/home_logged_in\", methods=[\"GET\", \"POST\"])\n@login_required\ndef home_logged_in():\n \"\"\"\n Handles the home page for logged-in users.\n\n This function renders the home_logged_in.html template, which displays the form for inputting a message to ChatGPT.\n\n Returns:\n - A string representing the HTML page displaying the form for inputting a message to ChatGPT.\n \"\"\"\n return render_template(\"users/home_logged_in.html\")\n", "repo_name": "theuerc/interview_simulator", "sub_path": "interview_simulator/user/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 4658, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.Blueprint", "line_number": 22, "usage_type": "call"}, {"api_name": "forms.UploadForm", "line_number": 34, "usage_type": "call"}, {"api_name": "interview_simulator.user.models.UserFile", "line_number": 40, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 41, "usage_type": "name"}, {"api_name": "interview_simulator.extensions.db.session.add", "line_number": 43, "usage_type": "call"}, {"api_name": "interview_simulator.extensions.db.session", "line_number": 43, "usage_type": "attribute"}, {"api_name": "interview_simulator.extensions.db", "line_number": 43, "usage_type": "name"}, {"api_name": "interview_simulator.user.models.UserFile", "line_number": 45, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 46, "usage_type": "name"}, {"api_name": "interview_simulator.extensions.db.session.add", "line_number": 48, "usage_type": "call"}, {"api_name": "interview_simulator.extensions.db.session", "line_number": 48, "usage_type": "attribute"}, {"api_name": "interview_simulator.extensions.db", "line_number": 48, "usage_type": "name"}, {"api_name": "interview_simulator.extensions.db.session.commit", "line_number": 50, "usage_type": "call"}, {"api_name": "interview_simulator.extensions.db.session", "line_number": 50, "usage_type": "attribute"}, {"api_name": "interview_simulator.extensions.db", "line_number": 50, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 53, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 53, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 54, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 26, "usage_type": "name"}, {"api_name": "interview_simulator.user.models.UserFile.query.filter_by", "line_number": 67, "usage_type": "call"}, {"api_name": "interview_simulator.user.models.UserFile.query", "line_number": 67, "usage_type": "attribute"}, {"api_name": "interview_simulator.user.models.UserFile", "line_number": 67, "usage_type": "name"}, {"api_name": "flask_login.current_user.id", "line_number": 67, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 67, "usage_type": "name"}, {"api_name": "interview_simulator.user.models.UserFile.upload_date.desc", "line_number": 68, "usage_type": "call"}, {"api_name": "interview_simulator.user.models.UserFile.upload_date", "line_number": 68, "usage_type": "attribute"}, {"api_name": "interview_simulator.user.models.UserFile", "line_number": 68, "usage_type": "name"}, {"api_name": "interview_simulator.user.models.UserFile.query.filter_by", "line_number": 72, "usage_type": "call"}, {"api_name": "interview_simulator.user.models.UserFile.query", "line_number": 72, "usage_type": "attribute"}, {"api_name": "interview_simulator.user.models.UserFile", "line_number": 72, "usage_type": "name"}, {"api_name": "flask_login.current_user.id", "line_number": 72, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 72, "usage_type": "name"}, {"api_name": "interview_simulator.user.models.UserFile.upload_date.desc", "line_number": 73, "usage_type": "call"}, {"api_name": "interview_simulator.user.models.UserFile.upload_date", "line_number": 73, "usage_type": "attribute"}, {"api_name": "interview_simulator.user.models.UserFile", "line_number": 73, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 78, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 86, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 58, "usage_type": "name"}, {"api_name": "flask.request.json.get", "line_number": 98, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 98, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 98, "usage_type": "name"}, {"api_name": "flask.request.json.get", "line_number": 99, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 99, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 99, "usage_type": "name"}, {"api_name": "services.gpt_questions", "line_number": 100, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 101, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 90, "usage_type": "name"}, {"api_name": "flask.request.files.get", "line_number": 115, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 115, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 115, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 116, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 116, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 116, "usage_type": "name"}, {"api_name": "flask.current_app.logger.info", "line_number": 119, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 119, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 119, "usage_type": "name"}, {"api_name": "services.transcribe_audio_with_whisper", "line_number": 126, "usage_type": "call"}, {"api_name": "services.chat_gpt", "line_number": 129, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 132, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 137, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 105, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 151, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 141, "usage_type": "name"}]} +{"seq_id": "35252557940", "text": "__author__ = \"Thibault Dayris\"\n__copyright__ = \"Copyright 2023, Thibault Dayris\"\n__email__ = \"thibault.dayris@gustaveroussy.fr\"\n__license__ = \"MIT\"\n\n\nfrom tempfile import TemporaryDirectory\nfrom snakemake.shell import shell\n\n\nlog = snakemake.log_fmt_shell(stdout=True, stderr=True, append=True)\nextra = snakemake.params.get(\"extra\", \"\")\n\n# pyroe uses the flank-length value to name its output files\n# in the result directory. We need this value to acquired output\n# files and let snakemake-wrapper choose its output file names.\nread_length = snakemake.params.get(\"read_length\", 101)\nflank_trim_length = snakemake.params.get(\"flank_trim_length\", 5)\nflank_length = read_length - flank_trim_length\n\nspliced = snakemake.input.get(\"spliced\", \"\")\nif spliced:\n spliced = \"--extra-spliced \" + spliced\n\n\nunspliced = snakemake.input.get(\"unspliced\", \"\")\nif unspliced:\n unspliced = \"--extra-unspliced \" + unspliced\n\n\nwith TemporaryDirectory() as tempdir:\n shell(\n \"pyroe make-spliced+intronic \"\n \"{extra} {spliced} \"\n \"{unspliced} \"\n \"{snakemake.input.fasta} \"\n \"{snakemake.input.gtf} \"\n \"{read_length} \"\n \"{tempdir} \"\n \"{log}\"\n )\n\n if snakemake.output.get(\"fasta\", False):\n shell(\n \"mv --verbose \"\n \"{tempdir}/splici_fl{flank_length}.fa \"\n \"{snakemake.output.fasta} {log}\"\n )\n\n if snakemake.output.get(\"gene_id_to_name\", False):\n shell(\n \"mv --verbose \"\n \"{tempdir}/gene_id_to_name.tsv \"\n \"{snakemake.output.gene_id_to_name} {log}\"\n )\n\n if snakemake.output.get(\"t2g\", False):\n shell(\n \"mv --verbose \"\n \"{tempdir}/splici_fl{flank_length}_t2g_3col.tsv \"\n \"{snakemake.output.t2g} {log} \"\n )\n", "repo_name": "snakemake/snakemake-wrappers", "sub_path": "bio/pyroe/makesplicedintronic/wrapper.py", "file_name": "wrapper.py", "file_ext": "py", "file_size_in_byte": 1796, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 182, "dataset": "github-code", "pt": "24", "api": [{"api_name": "snakemake.shell.log_fmt_shell", "line_number": 11, "usage_type": "call"}, {"api_name": "snakemake.shell", "line_number": 11, "usage_type": "name"}, {"api_name": "snakemake.shell.params.get", "line_number": 12, "usage_type": "call"}, {"api_name": "snakemake.shell.params", "line_number": 12, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 12, "usage_type": "name"}, {"api_name": "snakemake.shell.params.get", "line_number": 17, "usage_type": "call"}, {"api_name": "snakemake.shell.params", "line_number": 17, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 17, "usage_type": "name"}, {"api_name": "snakemake.shell.params.get", "line_number": 18, "usage_type": "call"}, {"api_name": "snakemake.shell.params", "line_number": 18, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 18, "usage_type": "name"}, {"api_name": "snakemake.shell.input.get", "line_number": 21, "usage_type": "call"}, {"api_name": "snakemake.shell.input", "line_number": 21, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 21, "usage_type": "name"}, {"api_name": "snakemake.shell.input.get", "line_number": 26, "usage_type": "call"}, {"api_name": "snakemake.shell.input", "line_number": 26, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 26, "usage_type": "name"}, {"api_name": "tempfile.TemporaryDirectory", "line_number": 31, "usage_type": "call"}, {"api_name": "snakemake.shell.shell", "line_number": 32, "usage_type": "call"}, {"api_name": "snakemake.shell.output.get", "line_number": 43, "usage_type": "call"}, {"api_name": "snakemake.shell.output", "line_number": 43, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 43, "usage_type": "name"}, {"api_name": "snakemake.shell.shell", "line_number": 44, "usage_type": "call"}, {"api_name": "snakemake.shell.output.get", "line_number": 50, "usage_type": "call"}, {"api_name": "snakemake.shell.output", "line_number": 50, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 50, "usage_type": "name"}, {"api_name": "snakemake.shell.shell", "line_number": 51, "usage_type": "call"}, {"api_name": "snakemake.shell.output.get", "line_number": 57, "usage_type": "call"}, {"api_name": "snakemake.shell.output", "line_number": 57, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 57, "usage_type": "name"}, {"api_name": "snakemake.shell.shell", "line_number": 58, "usage_type": "call"}]} +{"seq_id": "29737401719", "text": "import os\nfrom setuptools import setup\n\nwith open('requirements.txt') as f:\n required = f.read().splitlines()\n\nsetup(\n name='django-keen',\n version='0.1.3',\n author='Jannis Gebauer',\n author_email='ja.geb@pricemesh.io',\n packages=['dkeen',],\n url='http://pypi.python.org/pypi/django-keen/',\n license='LICENSE.txt',\n description='Simple wrapper for django around the official keen.io client',\n long_description=open('README.md').read(),\n install_requires=required\n)", "repo_name": "jayfk/django-keen", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 497, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "setuptools.setup", "line_number": 7, "usage_type": "call"}]} +{"seq_id": "22541081394", "text": "# import dependencies\nimport cv2 # connect webcam, process images\nimport mediapipe as mp # holistic API\nimport time # to calculate FPS\n# import tensorflow as tf, keras # to create model for training\n# from keras.models import load_model # load pretrained model\nimport numpy as np # processing\n\nimport imageio\n\n\n\nif __name__ == '__main__':\n width, height = 1280, 720\n # SETUP MEDIAPIPE\n print('Setting up................')\n mp_drawing = mp.solutions.drawing_utils # help draw the detections\n mp_holistic = mp.solutions.holistic # a Holistic class object\n\n # GET REALTIME WEBCAM FEED\n print('Getting webcam feed.................')\n ## define a video capture object, 0 is the webcam\n ## by default, each frame has size (480x640) (480 x 640)\n start, end = 0, 0 # helper variables to calculate FPS\n demo_path = '.\\\\assets\\\\demo\\\\mantalking.mp4'\n cap = cv2.VideoCapture(0)\n cap.set(3, width)\n cap.set(4, height)\n print('Initiate Holistic Model') \n # Initiate holistic model\n # dataset = []\n demo_frames = []\n with mp_holistic.Holistic( \\\n # model_complexity=2,\n min_detection_confidence=0.5, \\\n min_tracking_confidence=0.5) as holistic:\n print('Opening webcam feed........... Press q to stop')\n while cap.isOpened():\n\n start = time.time()\n # Capture the video frame\n # by frame\n success, frame = cap.read()\n if not success:\n print('Cannot receive frame from camera')\n break\n\n # flip the image vertically for later selfie view display\n # recolor feed from BGR to RGB so that the model will have good performance\n frame = cv2.cvtColor(cv2.flip(frame, 1), cv2.COLOR_BGR2RGB)\n\n # to improve performance, mark the image as not writeable to\n # pass by reference instead of making a copy\n frame.flags.writeable = False\n \n # make detection\n results = holistic.process(frame) # store all different kinds of landmarks...\n\n # enable drawing landmark annotation on the frame\n frame.flags.writeable = True \n cv2.imshow('ko che', cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))\n frame = np.zeros(frame.shape) \n # recolor feed from RGB to BGR so it can be displayed\n # frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n \n # extract mouth features\n # mouth_landmarks = []\n # if results.face_landmarks:\n # mouth_landmarks.append(np.array([results.face_landmarks.landmark[61].x * width, results.face_landmarks.landmark[61].y * height]))\n # mouth_landmarks.append(np.array([results.face_landmarks.landmark[291].x * width, results.face_landmarks.landmark[291].y * height]))\n # mouth_landmarks.append(np.array([results.face_landmarks.landmark[0].x * width, results.face_landmarks.landmark[0].y * height]))\n # mouth_landmarks.append(np.array([results.face_landmarks.landmark[17].x * width, results.face_landmarks.landmark[17].y * height]))\n\n # mouth_landmarks.append(np.array([results.face_landmarks.landmark[14].x * width, results.face_landmarks.landmark[14].y * height]))\n # # mouth_landmarks.append(np.array([results.face_landmarks.landmark[87].x * width, results.face_landmarks.landmark[87].y * height]))\n # # mouth_landmarks.append(np.array([results.face_landmarks.landmark[312].x * width, results.face_landmarks.landmark[312].y * height]))\n # # mouth_landmarks.append(np.array([results.face_landmarks.landmark[317].x * width, results.face_landmarks.landmark[317].y * height]))\n # vector_1 = mouth_landmarks[4] - mouth_landmarks[1]\n # vector_2 = mouth_landmarks[4] - mouth_landmarks[0]\n # angle = np.arccos(np.dot(vector_1 / np.linalg.norm(vector_1), \\\n # vector_2 / np.linalg.norm(vector_2)))*57.2958\n # for x, y in mouth_landmarks:\n # frame = cv2.circle(frame, (int(x), int(y)), radius=5, color=(0, 0, 255), thickness=5)\n # # draw facemesh \n # mp_drawing.draw_landmarks(frame, \\\n # results.face_landmarks,\\\n # mp_holistic.FACEMESH_TESSELATION,\\\n # # stylizing\n # mp_drawing.DrawingSpec(color=(245,117,66), thickness=1, circle_radius=1), \n # mp_drawing.DrawingSpec(color=(245,66,230), thickness=1, circle_radius=1))\n # cv2.putText(frame, str(f'angle: {round(angle, 3)} degree'), (10, 680), cv2.FONT_HERSHEY_COMPLEX, 3, (153,43,37), 3)\n # # draw pose landmarks\n # mp_drawing.draw_landmarks(frame, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS)\n # draw left hand landmarks\n mp_drawing.draw_landmarks(frame, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS)\n # if results.left_hand_landmarks: print(results.left_hand_landmarks)\n # draw right hand landmarks\n mp_drawing.draw_landmarks(frame, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS)\n \n # calculate how long this code takes to process a frame on a CPU\n end = time.time() \n fps = 1/(end - start)\n # display FPS on the frame\n # cv2.putText(frame, str(f'FPS: {int(fps)}'), (10, 70), cv2.FONT_HERSHEY_COMPLEX, 3, (255, 255, 255), 3)\n \n # demo_frames.append(frame)\n # Display the resulting frame\n cv2.imshow('Webcam Feed', frame)\n\n # the 'q' button is set as the\n # quitting button you may use any\n # desired button of your choice\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n # After the loop release the cap object\n cap.release()\n # Destroy all the windows\n cv2.destroyAllWindows()\n # imageio.mimsave('./proof/mouth_angle.gif', demo_frames, fps=10)\n print('Saving mouth dataset..........')\n # print(dataset)\n", "repo_name": "uyenbhku/CS231_ImageProcessingProject", "sub_path": "dev_files/baseline.py", "file_name": "baseline.py", "file_ext": "py", "file_size_in_byte": 6330, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "mediapipe.solutions", "line_number": 17, "usage_type": "attribute"}, {"api_name": "mediapipe.solutions", "line_number": 18, "usage_type": "attribute"}, {"api_name": "cv2.VideoCapture", "line_number": 26, "usage_type": "call"}, {"api_name": "time.time", "line_number": 40, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 50, "usage_type": "call"}, {"api_name": "cv2.flip", "line_number": 50, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 50, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 61, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 61, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2BGR", "line_number": 61, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 62, "usage_type": "call"}, {"api_name": "time.time", "line_number": 101, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 108, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 113, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 119, "usage_type": "call"}]} +{"seq_id": "19494866258", "text": "# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.4'\n# jupytext_version: 1.2.4\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pymc3 as pm\n# #!pip3 install jupytext\n\ndf = pd.read_csv('./poverty.csv')\n\ndf.head()\n\nX = df['PovPct']\ny = df['Brth15to17']\n\nplt.scatter(X, y)\n\nbasic_model = pm.Model()\nwith basic_model:\n alpha = pm.Normal('alpha', mu=0, sigma=10)\n beta = pm.Normal('beta', mu=0, sigma=10)\n sigma = pm.HalfNormal('sigma', sigma=1)\n \n mu = alpha + beta*X\n \n y_obs = pm.Normal('Y_obs', mu=mu, sigma=sigma, observed=y) # observed apparently makes this the likelihood\n # presumably for glm one replaces normal with the appropriate residual.\n\nmap_estimate = pm.find_MAP(model=basic_model)\nmap_estimate\n\nwith basic_model:\n trace = pm.sample(5000)\n\npm.traceplot(trace)\n\n# +\n# https://docs.pymc.io/notebooks/GLM-hierarchical.html\n", "repo_name": "mwpb/bayesian-regression", "sub_path": "pym3_testing.py", "file_name": "pym3_testing.py", "file_ext": "py", "file_size_in_byte": 1104, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pandas.read_csv", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "pymc3.Model", "line_number": 31, "usage_type": "call"}, {"api_name": "pymc3.Normal", "line_number": 33, "usage_type": "call"}, {"api_name": "pymc3.Normal", "line_number": 34, "usage_type": "call"}, {"api_name": "pymc3.HalfNormal", "line_number": 35, "usage_type": "call"}, {"api_name": "pymc3.Normal", "line_number": 39, "usage_type": "call"}, {"api_name": "pymc3.find_MAP", "line_number": 42, "usage_type": "call"}, {"api_name": "pymc3.sample", "line_number": 46, "usage_type": "call"}, {"api_name": "pymc3.traceplot", "line_number": 48, "usage_type": "call"}]} +{"seq_id": "74268902448", "text": "import numpy as np\nimport torch\nfrom torch import functional\nfrom maze1_env import Maze\nfrom DQN import DeepQNetwork\n\nclass Config(object):\n TARGET_REPLACE_ITER = 100 # target update frequency\n BATCH_SIZE = 32\n LR = 0.01 # learning rate\n EPSILON = 0.9 # greedy policy\n GAMMA = 0.9 # reward discount\n MEMORY_SIZE = 500\n MAX_EPISODE = 500\n\nopt = Config()\nenv = Maze()\n\ndef update_dqn(RL):\n step = 0\n for episode in range(opt.MAX_EPISODE):\n # initial observation\n observation = env.reset()\n\n while True:\n # fresh env\n env.render()\n # RL choose action based on observation\n action = RL.choose_action(observation)\n # RL take action and get next observation and reward\n observation_, reward, done = env.step(action)\n RL.store_transition(observation, action, reward, observation_)\n if (step > 200) and (step % 5 == 0):\n RL.learn()\n # swap observation\n observation = observation_\n # break while loop when end of this episode\n if done:\n print('--------episode:{0}-------'.format(episode))\n break\n step += 1\n\n # end of game\n print('game over')\n env.destroy()\n\ndef train(**kwargs):\n for k_, v_ in kwargs.items():\n setattr(opt, k_, v_) \n\n RL = DeepQNetwork(env.n_actions, env.n_features, opt)\n env.after(100, update_dqn(RL))\n env.mainloop()\n \nif __name__ == '__main__': \n import fire\n fire.Fire()\n", "repo_name": "yuanyilikl/Reinforcement-Learning", "sub_path": "DQN_run.py", "file_name": "DQN_run.py", "file_ext": "py", "file_size_in_byte": 1607, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "maze1_env.Maze", "line_number": 17, "usage_type": "call"}, {"api_name": "DQN.DeepQNetwork", "line_number": 51, "usage_type": "call"}, {"api_name": "fire.Fire", "line_number": 57, "usage_type": "call"}]} +{"seq_id": "74416463422", "text": "import abc\nimport gin\nimport tensorflow as tf\n\n\ndef vtrace(values, rewards, done_terminated, done_abandoned, discount_factor,\n target_action_log_probs, behaviour_action_log_probs, lambda_=1.0,\n max_importance_weight=1., name='vtrace'):\n r\"\"\"Calculates V-trace value targets and advantages.\n\n Args:\n values: A float32 tensor of shape [T+1, B] with the value function estimates\n wrt. the target policy, i.e., for the time steps, i, i+1, ..., i+T.\n rewards: A float32 tensor of shape [T, B] containing rewards generated by\n following the behaviour policy after time steps i, i+1, ..., i+T-1.\n done_terminated: A boolean tensor of shape [T, B] signifying if the agent\n terminated after the actions in steps i, i+1, ..., i+T-1. This is\n equivalent to going into a terminal state with infinite rewards of 0.\n done_abandoned: A boolean tensor of shape [T, B] signifying if the agent did\n not further act after the actions in steps i, i+1, ..., i+T-1. This is not\n the same as termination and can be used if the maximum episode length is\n reached. This will set the advantage of that state to zero and the target\n value to the input value (which generally results in a zero gradient).\n discount_factor: Float with the discount factor to be used.\n target_action_log_probs: A float32 tensor of shape [T, B] with\n log-probabilities of taking the action by the current policy.\n behaviour_action_log_probs: A float32 tensor of shape [T, B] with\n log-probabilities of taking the action by the behavioural policy.\n lambda_: Float that determines the mix between 1-step (lambda_=0) and n-step\n (lambda_=1) bootstrapping\n max_importance_weight: Bigger importance weights are clipped.\n name: String with the name scope that all operations will be created in.\n\n Returns:\n A float32 tensor of shape [T, B] with value targets that can be used to\n train a baseline (V(x_t) - vs_t)^2.\n A float32 tensor of shape [T, B] of advantages.\n \"\"\"\n with tf.name_scope(name):\n # Compute importance sampling weights.\n log_rhos = target_action_log_probs - behaviour_action_log_probs\n log_rhos = tf.minimum(log_rhos, tf.math.log(max_importance_weight))\n rhos = tf.exp(log_rhos)\n\n # We compute the temporal differences with special handling of episodes\n # which ended. We consider two cases:\n # - Termination: In this case, the agent took a decision that led to proper\n # termination of the episode. In this case, the future value of the\n # policy is enforced to be zero. This is done by setting the next step\n # bootstrapping value to zero and not to the next value function (which\n # is the value of the state after the reset).\n not_terminated_mask = tf.cast(~done_terminated, tf.float32)\n next_step_bootstrap = not_terminated_mask * values[1:]\n\n # - Abandonment: The current episode was abandoned, e.g., due to a maximum\n # epsiode length. If the policy would have continued, it would have\n # continued to obtain rewards. We handle this by setting the temporal\n # difference and thus the advantage to zero.\n not_abandoned_mask = tf.cast(~done_abandoned, tf.float32)\n deltas = rewards + discount_factor * next_step_bootstrap - values[:-1]\n deltas *= not_abandoned_mask\n\n # For both cases, we do not propagate future temporal differences as they\n # relate to different episodes.\n propagate_future = not_terminated_mask * not_abandoned_mask\n\n # We accumulate temporal differences by iterating backwards in time and\n # computing advantages as we go using dynamic programming.\n accumulator = tf.zeros_like(values[0])\n targets = []\n advantages = []\n for i in range(int(rewards.shape[0]) - 1, -1, -1):\n future = propagate_future[i] * discount_factor * lambda_ * accumulator\n # For advantages we don't use importance weights because this is\n # the advantage exactly for the action which was taken.\n advantages.append(deltas[i] + future)\n # On the other hand, the accumulator corresponds to the value for the\n # current state so both terms are multiplied by rho.\n accumulator = rhos[i] * (deltas[i] + future)\n targets.append(values[i] + accumulator)\n\n # We need to return targets and values with stopped gradients, as we do not\n # want to differentiate through the generalized advantage estimator.\n targets = tf.convert_to_tensor(targets[::-1], dtype=tf.float32)\n advantages = tf.convert_to_tensor(advantages[::-1], dtype=tf.float32)\n return tf.stop_gradient(targets), tf.stop_gradient(advantages)\n\n\n\n\ndef gae(values, rewards, done_terminated, done_abandoned, discount_factor,\n target_action_log_probs=None, behaviour_action_log_probs=None,\n lambda_=1.0, name='gae'):\n \"\"\"Generalized Advantages Estimator.\n\n Args:\n See V-trace above.\n\n Returns:\n A float32 tensor of shape [T, B] with value targets that can be used to\n train a baseline (V(x_t) - vs_t)^2.\n A float32 tensor of shape [T, B] of advantages.\n \"\"\"\n return vtrace(values, rewards, done_terminated, done_abandoned,\n discount_factor,\n tf.zeros_like(rewards), tf.zeros_like(rewards),\n lambda_, 1., name)\n\n\nclass AdvantageEstimator(tf.Module, metaclass=abc.ABCMeta):\n \"\"\"Abstract base class for advantage estimators.\"\"\"\n\n @abc.abstractmethod\n def __call__(self, values, rewards, done_terminated, done_abandoned,\n discount_factor, target_action_log_probs,\n behaviour_action_log_probs):\n r\"\"\"Computes advantages and value function targets.\n\n Args:\n values: A float32 tensor of shape [T+1, B] with the value function\n estimates wrt. the target policy, i.e., for the time steps, i, i+1,\n ..., i+T.\n rewards: A float32 tensor of shape [T, B] containing rewards generated by\n following the behaviour policy after time steps i, i+1, ..., i+T-1.\n done_terminated: A boolean tensor of shape [T, B] signifying if the agent\n terminated after the actions in steps i, i+1, ..., i+T-1. This is\n equivalent to going into a terminal state with infinite rewards of 0.\n done_abandoned: A boolean tensor of shape [T, B] signifying if the agent\n did not further act after the actions in steps i, i+1, ..., i+T-1. This\n is not the same as termination and can be used if the maximum episode\n length is reached. This will set the advantage of that state to zero and\n the target value to the input value (which generally results in a zero\n gradient).\n discount_factor: Float with the discount factor to be used.\n target_action_log_probs: A float32 tensor of shape [T, B] with\n log-probabilities of taking the action by the current policy\n behaviour_action_log_probs: A float32 tensor of shape [T, B] with\n log-probabilities of taking the action by the behavioural policy\n\n\n Returns:\n A float32 tensor of shape [T, B] with value targets that can be used to\n train a baseline (V(x_t) - vs_t)^2.\n A float32 tensor of shape [T, B] of advantages.\n \"\"\"\n raise NotImplementedError('`__call__()` is not implemented!')\n\n\n@gin.configurable\nclass GAE(AdvantageEstimator):\n\n def __init__(self, lambda_, name='gam'):\n super().__init__()\n self.lambda_ = lambda_\n\n def __call__(self, *args, **kwargs):\n return gae(*args, **kwargs, lambda_=self.lambda_, name=self.name)\n\n\n@gin.configurable\nclass VTrace(AdvantageEstimator):\n\n def __init__(self, lambda_, max_importance_weight=1., name='vtrace'):\n super().__init__(name)\n self.lambda_ = lambda_\n self.max_importance_weight = max_importance_weight\n\n def __call__(self, *args, **kwargs):\n return vtrace(*args, **kwargs,\n max_importance_weight=self.max_importance_weight,\n lambda_=self.lambda_, name=self.name)\n\n\n@gin.configurable\nclass NStep(AdvantageEstimator):\n \"\"\"N-step returns.\"\"\"\n\n def __init__(self, n, name='nstep2'):\n super().__init__(name)\n self.n = n\n\n def __call__(self, values, rewards, done_terminated, done_abandoned,\n discount_factor, target_action_log_probs,\n behaviour_action_log_probs):\n with tf.name_scope(self.name):\n # We compute the n-step returns in min(n, unroll_length) steps.\n unroll_length = int(rewards.shape[0])\n eff_n = self.n if self.n < unroll_length else unroll_length\n\n # We pad the dimension with n-1 additional values with abandon=True so\n # that we don't have to handle the last n-1 steps differently.\n values_pad = tf.zeros((eff_n - 1, values.shape[1]), dtype=tf.float32)\n done_terminated_pad = tf.zeros((eff_n - 1, values.shape[1]),\n dtype=tf.bool)\n done_abandoned_pad = tf.ones((eff_n - 1, values.shape[1]), dtype=tf.bool)\n rewards_pad = tf.zeros((eff_n - 1, values.shape[1]), dtype=tf.float32)\n\n nvalues = tf.concat([values, values_pad], axis=0)\n ndone_terminated = tf.concat([done_terminated, done_terminated_pad],\n axis=0)\n ndone_abandoned = tf.concat([done_abandoned, done_abandoned_pad], axis=0)\n nrewards = tf.concat([rewards, rewards_pad], axis=0)\n\n future_value = nvalues[eff_n:]\n\n window_size = rewards.shape[0]\n\n for i in range(eff_n):\n # Extract relevant sub tensors.\n start = eff_n - i - 1\n end = start + window_size\n rel_n_values = nvalues[start:end]\n rel_rewards = nrewards[start:end]\n rel_done_terminated = ndone_terminated[start:end]\n rel_done_abandoned = ndone_abandoned[start:end]\n\n # We compute the targets with special handling of episodes\n # which ended. We consider two cases:\n # - Termination: In this case, the agent took a decision that led to\n # proper termination of the episode. In this case, the future value\n # of the policy is enforced to be zero. This is done by setting the\n # next step bootstrapping value to zero and not to the next value\n # function (which is the value of the state after the reset).\n not_terminated_mask = tf.cast(~rel_done_terminated, tf.float32)\n next_step_bootstrap = not_terminated_mask * future_value\n\n # - Abandonment: The current episode was abandoned, e.g., due to a\n # maximum episode length (or padding). If the policy would have\n # continued, it would have continued to obtain rewards. We handle\n # this by setting the value to the current value.\n not_abandoned_mask = tf.cast(~rel_done_abandoned, tf.float32)\n abandoned_mask = tf.cast(rel_done_abandoned, tf.float32)\n\n one_step_bootstrap = rel_rewards + discount_factor * next_step_bootstrap\n\n future_value = (not_abandoned_mask*one_step_bootstrap +\n abandoned_mask*rel_n_values)\n\n advantages = future_value - values[:-1]\n return tf.stop_gradient(future_value), tf.stop_gradient(advantages)\n", "repo_name": "google-research/seed_rl", "sub_path": "agents/policy_gradient/modules/advantages.py", "file_name": "advantages.py", "file_ext": "py", "file_size_in_byte": 11097, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 783, "dataset": "github-code", "pt": "24", "api": [{"api_name": "tensorflow.name_scope", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.minimum", "line_number": 42, "usage_type": "call"}, {"api_name": "tensorflow.math.log", "line_number": 42, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 42, "usage_type": "attribute"}, {"api_name": "tensorflow.exp", "line_number": 43, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 52, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 52, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 59, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 59, "usage_type": "attribute"}, {"api_name": "tensorflow.zeros_like", "line_number": 69, "usage_type": "call"}, {"api_name": "tensorflow.convert_to_tensor", "line_number": 84, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 84, "usage_type": "attribute"}, {"api_name": "tensorflow.convert_to_tensor", "line_number": 85, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 85, "usage_type": "attribute"}, {"api_name": "tensorflow.stop_gradient", "line_number": 86, "usage_type": "call"}, {"api_name": "tensorflow.zeros_like", "line_number": 106, "usage_type": "call"}, {"api_name": "tensorflow.Module", "line_number": 110, "usage_type": "attribute"}, {"api_name": "abc.ABCMeta", "line_number": 110, "usage_type": "attribute"}, {"api_name": "abc.abstractmethod", "line_number": 113, "usage_type": "attribute"}, {"api_name": "gin.configurable", "line_number": 149, "usage_type": "attribute"}, {"api_name": "gin.configurable", "line_number": 160, "usage_type": "attribute"}, {"api_name": "tensorflow.name_scope", "line_number": 185, "usage_type": "call"}, {"api_name": "tensorflow.zeros", "line_number": 192, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 192, "usage_type": "attribute"}, {"api_name": "tensorflow.zeros", "line_number": 193, "usage_type": "call"}, {"api_name": "tensorflow.bool", "line_number": 194, "usage_type": "attribute"}, {"api_name": "tensorflow.ones", "line_number": 195, "usage_type": "call"}, {"api_name": "tensorflow.bool", "line_number": 195, "usage_type": "attribute"}, {"api_name": "tensorflow.zeros", "line_number": 196, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 196, "usage_type": "attribute"}, {"api_name": "tensorflow.concat", "line_number": 198, "usage_type": "call"}, {"api_name": "tensorflow.concat", "line_number": 199, "usage_type": "call"}, {"api_name": "tensorflow.concat", "line_number": 201, "usage_type": "call"}, {"api_name": "tensorflow.concat", "line_number": 202, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 224, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 224, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 231, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 231, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 232, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 232, "usage_type": "attribute"}, {"api_name": "tensorflow.stop_gradient", "line_number": 240, "usage_type": "call"}, {"api_name": "gin.configurable", "line_number": 174, "usage_type": "attribute"}]} +{"seq_id": "74516767730", "text": "import torch\r\nimport os\r\nfrom glob import glob\r\n\r\nmodel_folder = './models'\r\nfolder = os.listdir(model_folder)\r\n\r\nfor i in range(len(folder)):\r\n filenames = glob(os.path.join(model_folder, folder[i], '*.pth'))\r\n for j in range(len(filenames)):\r\n model = torch.load(filenames[j], map_location='cpu')\r\n backbone = 0\r\n neck = 0\r\n head = 0\r\n all = 0\r\n for key in list(model['state_dict'].keys()):\r\n if 'backbone' in key:\r\n # if key.startswith('img_backbone'):\r\n backbone += model['state_dict'][key].nelement()\r\n elif 'neck' in key:\r\n neck += model['state_dict'][key].nelement()\r\n elif 'head' in key:\r\n head += model['state_dict'][key].nelement()\r\n\r\n all += model['state_dict'][key].nelement()\r\n print(filenames[j])\r\n print(f\"Backbone param: {backbone / 1e6}M\")\r\n print(f\"Neck param: {neck / 1e6}M\")\r\n print(f\"Head param: {head / 1e6}M\")\r\n print(f\"Total param: {all / 1e6}M\")\r\n\r\n# smaller 63374123\r\n# v4 69140395\r\n", "repo_name": "Daniel-xsy/BEV-Attack", "sub_path": "mmdet_adv/tools/analysis_tools/get_params.py", "file_name": "get_params.py", "file_ext": "py", "file_size_in_byte": 1092, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "20", "api": [{"api_name": "os.listdir", "line_number": 6, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 11, "usage_type": "call"}]} +{"seq_id": "17096658626", "text": "import requests\n\nservice_url = 'https://example.com'\n\nexpected_status_code = 200\n\ndef check_service_status(url,expected_code):\n try:\n response = requests.get(url)\n if response.status_code == expected_code:\n return True\n else:\n return False\n except requests.exceptions.RequestException:\n return False\nif check_service_status(service_url,expected_status_code):\n print(\"The service at {} is up and running.\".format(service_url))\nelse:\n print(\"The service at {} is up and running.\".format(service_url))", "repo_name": "Shreyashbhise/PythonForDevOps", "sub_path": "practiceexampl3.py", "file_name": "practiceexampl3.py", "file_ext": "py", "file_size_in_byte": 561, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "requests.get", "line_number": 9, "usage_type": "call"}, {"api_name": "requests.exceptions", "line_number": 14, "usage_type": "attribute"}]} +{"seq_id": "38994124664", "text": "import os\nimport discord\nimport random\nfrom replit import db\n\n\nclient = discord.Client()\n\n######################### UPDATE em r_palavras_acrescentadas #####################################\ndef uptade_encouragements(encouraging_message):\n if \"encouragements\" in db.keys():\n encouragements = db[\"encouragements\"]\n encouragements.append(encouraging_message)\n db[\"encouragements\"] = encouragements\n else:\n db[\"encouragements\"] = [encouraging_message]\n\ndef delete_encouragements(index):\n encouragements = db[\"encouragements\"]\n if len (encouragements) > index:\n del encouragements [index]\n db[\"encouragements\"] = encouragements\n################################################################################################\n######################## UPDATE em palavras_acrescentadas #####################################\ndef uptade_encouragements2(encouraging_message2):\n if \"encouragements2\" in db.keys():\n encouragements2 = db[\"encouragements2\"]\n encouragements2.append(encouraging_message2)\n db[\"encouragements2\"] = encouragements2\n else:\n db[\"encouragements2\"] = [encouraging_message2]\n\ndef delete_encouragements2(index2):\n encouragements2 = db[\"encouragements2\"]\n if len (encouragements2) > index2:\n del encouragements2 [index2]\n db[\"encouragements2\"] = encouragements2\n################################################################################################3\n\n@client.event\nasync def on_ready():\n #print(\"We have logged in as {0.user}\".format(client))\n print(f\"Connected succesfully as {client.user}\")\n\npalavras_acrescentadas = [\"jogo\",\"mano\"]\nr_palavras_acrescentadas = [\"bacana\",\"ha ha ha\"]\n\ndiferente = [\"quero uivar\",\"Tô com fome\", \"que canseira\", \"relaxa carinha\",\"acho que tô com pulga\"]\nr_diferente = [\"quero uivar\",\"Tô com fome\", \"que canseira\", \"relaxa carinha\",\"acho que tô com pulga\"]\n\npalavrax = [\"oi \", \"ola \"]\nr_palavrax = [\"olá amigo como vc está hoje?\",\" tô perdido aqui\",\"au au au\",\"eu sou o cão coragem\"]\n\ncumprimentosx = [\"bem\",\"bom\",\"legal\"]\nr_cumprimentosx = [\"vc disse bem uhuu que bacana\",\"vc disse bom, que legal carinha\", \"vc escreveu legal e eu concordo com vc!!\"]\n\ngx = [\"bom dia\",\"boa noite\", \"boa tarde\"]\nr_gx = [\"para vc também\", \"bom para todos\", \"bom mesmo uhu\"]\n\nif \"responding\" not in db.keys():\n db[\"responding\"] = True\n\n@client.event\nasync def on_message(message):\n if message.author == client.user:\n return\n############## acrescenta palavra na lista r_palavras_acrescentadas #######\n \n if db[\"responding\"]:\n options = r_palavras_acrescentadas\n if \"encouragements\" in db.keys():\n options.extend(db[\"encouragements\"]) #adiciona lista em outra lista\n #options = options + db[\"encouragements\"]\n \n if any(word in message.content for word in palavras_acrescentadas):\n await message.channel.send(random.choice(options))\n \n if message.content.startswith(\"$new \"):\n encouraging_message = message.content.split(\"$new \",1)[1]\n uptade_encouragements(encouraging_message)\n await message.channel.send(\"New encouraging message added.\")\n\n if message.content.startswith(\"$del\"):\n encouragements = []\n if \"encouragements\" in db.keys():\n index = int(message.content.split(\"$del\",1)[1])\n delete_encouragements(index)\n encouragements = db[\"encouragements\"]\n await message.channel.send(encouragements)\n############################################################################\n if message.content.startswith(\"$list\"):\n encouragements = []\n if \"encouragements\" in db.keys():\n encouragements = db[\"encouragements\"]\n await message.channel.send(encouragements)\n\n if message.content.startswith(\"$responding\"):\n value = message.content.split(\"$responding \",1)[1]\n\n if value.lower() == \"true\":\n db[\"responding\"] = True\n await message.channel.send(\"cao coragem ligado!\")\n else:\n db[\"responding\"] = False\n await message.channel.send(\"cao coragem desligado\")\n\n #############################################################################\n ############## acrescenta palavra na lista palavras_acrescentadas #######\n options2 = palavras_acrescentadas\n if \"encouragements2\" in db.keys():\n options2.extend(db[\"encouragements2\"]) #adiciona lista em outra lista\n #options = options + db[\"encouragements\"]\n \n if any(word in message.content for word in r_palavras_acrescentadas):\n await message.channel.send(random.choice(options2))\n \n if message.content.startswith(\"$new_palavras \"):\n encouraging_message2 = message.content.split(\"$new_palavras \",1)[1]\n uptade_encouragements2(encouraging_message2)\n await message.channel.send(\"New encouraging message added.\")\n\n if message.content.startswith(\"$del_palavras\"):\n encouragements2 = []\n if \"encouragements2\" in db.keys():\n index2 = int(message.content.split(\"$del_palavras\",1)[1])\n delete_encouragements2(index2)\n encouragements2 = db[\"encouragements2\"]\n await message.channel.send(encouragements2)\n ############################################################################# \n\n if message.content == \"duliano\":\n await message.channel.send(\"escreva no particular para o seu amigo\")\n dm = await message.author.create_dm() # Creates a dm channel with the user\n await dm.send(\"o que você quer falar com duliano?\") # Sends the user the message\n\n if any (palavra in message.content for palavra in diferente):\n await message.channel.send(random.choice(r_diferente))\n\n if any (palavra in message.content + (\" \") for palavra in palavrax):\n await message.channel.send(random.choice(r_palavrax))\n\n if any (palavra in message.content != \"bom\" for palavra in gx):\n await message.channel.send(random.choice(r_gx))\n\n if any (palavra in message.content != \"bom dia\" for palavra in cumprimentosx):\n await message.channel.send(random.choice(r_cumprimentosx))\n\n '''else:\n await message.author.send(\"Ainda não aprendi essa palavra \\nMe ensina?\")'''\n\nclient.run(os.getenv(\"REC\"))\nmy_secret = os.environ['REC']", "repo_name": "cardosodbc/bot_discord_cao_coragem", "sub_path": "_discord.py", "file_name": "_discord.py", "file_ext": "py", "file_size_in_byte": 6354, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "discord.Client", "line_number": 7, "usage_type": "call"}, {"api_name": "replit.db.keys", "line_number": 11, "usage_type": "call"}, {"api_name": "replit.db", "line_number": 11, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 12, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 14, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 16, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 19, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 22, "usage_type": "name"}, {"api_name": "replit.db.keys", "line_number": 26, "usage_type": "call"}, {"api_name": "replit.db", "line_number": 26, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 27, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 29, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 31, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 34, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 37, "usage_type": "name"}, {"api_name": "replit.db.keys", "line_number": 60, "usage_type": "call"}, {"api_name": "replit.db", "line_number": 60, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 61, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 69, "usage_type": "name"}, {"api_name": "replit.db.keys", "line_number": 71, "usage_type": "call"}, {"api_name": "replit.db", "line_number": 71, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 72, "usage_type": "name"}, {"api_name": "random.choice", "line_number": 76, "usage_type": "call"}, {"api_name": "replit.db.keys", "line_number": 85, "usage_type": "call"}, {"api_name": "replit.db", "line_number": 85, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 88, "usage_type": "name"}, {"api_name": "replit.db.keys", "line_number": 93, "usage_type": "call"}, {"api_name": "replit.db", "line_number": 93, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 94, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 101, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 104, "usage_type": "name"}, {"api_name": "replit.db.keys", "line_number": 110, "usage_type": "call"}, {"api_name": "replit.db", "line_number": 110, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 111, "usage_type": "name"}, {"api_name": "random.choice", "line_number": 115, "usage_type": "call"}, {"api_name": "replit.db.keys", "line_number": 124, "usage_type": "call"}, {"api_name": "replit.db", "line_number": 124, "usage_type": "name"}, {"api_name": "replit.db", "line_number": 127, "usage_type": "name"}, {"api_name": "random.choice", "line_number": 137, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 140, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 143, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 146, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 151, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 152, "usage_type": "attribute"}]} +{"seq_id": "667133840", "text": "import os\nimport logging\nimport tempfile\nfrom pathlib import Path\n\nimport torch.multiprocessing as mp\n\nfrom mindsdb.__about__ import __version__ as mindsdb_version\nfrom mindsdb.interfaces.database.database import DatabaseWrapper\nfrom mindsdb.interfaces.storage.db import session, Predictor\nfrom mindsdb.interfaces.storage.fs import FsSotre\nfrom mindsdb.utilities.config import Config\nfrom mindsdb.utilities.fs import create_process_mark, delete_process_mark\n\n\nctx = mp.get_context('spawn')\n\n\ndef create_learn_mark():\n if os.name == 'posix':\n p = Path(tempfile.gettempdir()).joinpath('mindsdb/learn_processes/')\n p.mkdir(parents=True, exist_ok=True)\n p.joinpath(f'{os.getpid()}').touch()\n\n\ndef delete_learn_mark():\n if os.name == 'posix':\n p = Path(tempfile.gettempdir()).joinpath('mindsdb/learn_processes/').joinpath(f'{os.getpid()}')\n if p.exists():\n p.unlink()\n\n\ndef run_learn(name, db_name, from_data, to_predict, kwargs, datasource_id, company_id):\n import mindsdb_native\n import mindsdb_datasources\n import mindsdb\n import torch\n import gc\n\n if 'join_learn_process' in kwargs:\n del kwargs['join_learn_process']\n\n create_process_mark('learn')\n\n config = Config()\n fs_store = FsSotre()\n mdb = mindsdb_native.Predictor(name=name, run_env={'trigger': 'mindsdb'})\n\n predictor_record = Predictor.query.filter_by(company_id=company_id, name=db_name).first()\n predictor_record.datasource_id = datasource_id\n predictor_record.to_predict = to_predict\n predictor_record.native_version = mindsdb_native.__version__\n predictor_record.mindsdb_version = mindsdb_version\n predictor_record.learn_args = {\n 'to_predict': to_predict,\n 'kwargs': kwargs\n }\n predictor_record.data = {\n 'name': db_name,\n 'status': 'training'\n }\n session.commit()\n\n to_predict = to_predict if isinstance(to_predict, list) else [to_predict]\n data_source = getattr(mindsdb_datasources, from_data['class'])(*from_data['args'], **from_data['kwargs'])\n try:\n mdb.learn(\n from_data=data_source,\n to_predict=to_predict,\n **kwargs\n )\n\n except Exception as e:\n log = logging.getLogger('mindsdb.main')\n log.error(f'Predictor learn error: {e}')\n predictor_record.data = {\n 'name': db_name,\n 'status': 'error'\n }\n session.commit()\n delete_process_mark('learn')\n\n fs_store.put(name, f'predictor_{company_id}_{predictor_record.id}', config['paths']['predictors'])\n\n model_data = mindsdb_native.F.get_model_data(name)\n\n try:\n torch.cuda.empty_cache()\n except Exception as e:\n pass\n gc.collect()\n\n predictor_record = Predictor.query.filter_by(company_id=company_id, name=db_name).first()\n predictor_record.data = model_data\n session.commit()\n\n model_data['name'] = db_name\n DatabaseWrapper(company_id).register_predictors([model_data])\n delete_process_mark('learn')\n\n\nclass LearnProcess(ctx.Process):\n daemon = True\n\n def __init__(self, *args):\n super(LearnProcess, self).__init__(args=args)\n\n def run(self):\n '''\n running at subprocess due to\n ValueError: signal only works in main thread\n\n this is work for celery worker here?\n '''\n run_learn(*self._args)\n", "repo_name": "sbsreekanth/mindsdb", "sub_path": "mindsdb/interfaces/model/learn_process.py", "file_name": "learn_process.py", "file_ext": "py", "file_size_in_byte": 3382, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "20", "api": [{"api_name": "torch.multiprocessing.get_context", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.multiprocessing", "line_number": 16, "usage_type": "name"}, {"api_name": "os.name", "line_number": 20, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 21, "usage_type": "call"}, {"api_name": "tempfile.gettempdir", "line_number": 21, "usage_type": "call"}, {"api_name": "os.getpid", "line_number": 23, "usage_type": "call"}, {"api_name": "os.name", "line_number": 27, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 28, "usage_type": "call"}, {"api_name": "tempfile.gettempdir", "line_number": 28, "usage_type": "call"}, {"api_name": "os.getpid", "line_number": 28, "usage_type": "call"}, {"api_name": "mindsdb.utilities.fs.create_process_mark", "line_number": 43, "usage_type": "call"}, {"api_name": "mindsdb.utilities.config.Config", "line_number": 45, "usage_type": "call"}, {"api_name": "mindsdb.interfaces.storage.fs.FsSotre", "line_number": 46, "usage_type": "call"}, {"api_name": "mindsdb_native.Predictor", "line_number": 47, "usage_type": "call"}, {"api_name": "mindsdb.interfaces.storage.db.Predictor.query.filter_by", "line_number": 49, "usage_type": "call"}, {"api_name": "mindsdb.interfaces.storage.db.Predictor.query", "line_number": 49, "usage_type": "attribute"}, {"api_name": "mindsdb.interfaces.storage.db.Predictor", "line_number": 49, "usage_type": "name"}, {"api_name": "mindsdb_native.__version__", "line_number": 52, "usage_type": "attribute"}, {"api_name": "mindsdb.__about__.__version__", "line_number": 53, "usage_type": "name"}, {"api_name": "mindsdb.interfaces.storage.db.session.commit", "line_number": 62, "usage_type": "call"}, {"api_name": "mindsdb.interfaces.storage.db.session", "line_number": 62, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 74, "usage_type": "call"}, {"api_name": "mindsdb.interfaces.storage.db.session.commit", "line_number": 80, "usage_type": "call"}, {"api_name": "mindsdb.interfaces.storage.db.session", "line_number": 80, "usage_type": "name"}, {"api_name": "mindsdb.utilities.fs.delete_process_mark", "line_number": 81, "usage_type": "call"}, {"api_name": "mindsdb_native.F.get_model_data", "line_number": 85, "usage_type": "call"}, {"api_name": "mindsdb_native.F", "line_number": 85, "usage_type": "attribute"}, {"api_name": "torch.cuda.empty_cache", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 88, "usage_type": "attribute"}, {"api_name": "gc.collect", "line_number": 91, "usage_type": "call"}, {"api_name": "mindsdb.interfaces.storage.db.Predictor.query.filter_by", "line_number": 93, "usage_type": "call"}, {"api_name": "mindsdb.interfaces.storage.db.Predictor.query", "line_number": 93, "usage_type": "attribute"}, {"api_name": "mindsdb.interfaces.storage.db.Predictor", "line_number": 93, "usage_type": "name"}, {"api_name": "mindsdb.interfaces.storage.db.session.commit", "line_number": 95, "usage_type": "call"}, {"api_name": "mindsdb.interfaces.storage.db.session", "line_number": 95, "usage_type": "name"}, {"api_name": "mindsdb.interfaces.database.database.DatabaseWrapper", "line_number": 98, "usage_type": "call"}, {"api_name": "mindsdb.utilities.fs.delete_process_mark", "line_number": 99, "usage_type": "call"}]} +{"seq_id": "30495040041", "text": "\"\"\"\nTesting sales_inserter plus the DB Commands (Which is imported into sales_inserter\n\"\"\"\n\nfrom SQL import sales_inserter as si\nfrom datetime import date\n\nii = si.InsertItem()\n# print('Asserting if _id_lookup correctly returns an id.')\n# assert ii._id_lookup('patients', 'patient_name', 'Angeles Pollard') == 1332\n# ii.db.connect()\n# ii.quick_sale(\"1500\", None, 'VSP', [1, 5, 6])\n# ii.db.commit_close()\n# ii.insert_sale('Newton Powers', purchase_items=[('Eye Exam', 8500), ('Refraction', 4900)]) # Works!\n\n# ii.db.delete('sale', ('patient', 1332))\n\n# ii.db.update(['products', ('id', 1), ('id', 29)])\n\n#\n# sales_items = ii.db.view('sale_item')\n# print(sales_items)\n\n# patient = ii.db.view('patients', ('patient_name', 'Angeles Pollard'))\n# print(patient)\n\n# print(ii.db.view('sale', ('purchase_time::date', '2019-02-23')))\n#\n# ii.db._connect()\n# for i in range(2100):\n# ii.db.update_avg_dollar(i, slow=False) # Works!\n#\n# ii.db._commit_close()\n\nif __name__ == '__main__':\n products = ii.db.view('products')\n for item in products:\n print(f\"({item[0]}) {item[1]} - ${(item[2] / 100)}\")\n\n sales = ii.db.view('sale')\n print(sales)\n\n sale_time = date(2014, 2, 20)\n patient_id = 102\n sale_id = ii.db.view(f\"sale WHERE purchase_time = '{sale_time}' AND patient = {patient_id}\", field=\"id\")\n print(sale_id)\n\n", "repo_name": "KarlKeisel/Eyewear-Saleswebsite", "sub_path": "tests/test_sales_inserter.py", "file_name": "test_sales_inserter.py", "file_ext": "py", "file_size_in_byte": 1341, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "SQL.sales_inserter.InsertItem", "line_number": 8, "usage_type": "call"}, {"api_name": "SQL.sales_inserter", "line_number": 8, "usage_type": "name"}, {"api_name": "datetime.date", "line_number": 43, "usage_type": "call"}]} +{"seq_id": "24169378647", "text": "import win32api, win32gui, win32con\r\nimport win32com.client as wclt\r\nimport win32clipboard as clipbd\r\nimport time, re, datetime\r\nfrom tkinter import Label, Button, Tk, Entry, Frame, StringVar, IntVar, DoubleVar, Text, Spinbox, Checkbutton, BooleanVar, messagebox, HORIZONTAL\r\nfrom tkinter.constants import END\r\nimport threading as thd\r\nfrom pythoncom import CoInitialize\r\n\r\nclass GUI_MAIN_APP(Frame):\r\n def __init__(self, master = None) -> None:\r\n super().__init__(master)\r\n self.master = master\r\n self.pack()\r\n self.create_widget()\r\n\r\n def w_size(self, content: str) -> int:\r\n return len(content) * 12\r\n\r\n def create_widget(self) -> None:\r\n self.place(x = 0, y = 0, width=450, height=700)\r\n note = '''说明: 在输入框种输入要传输的内容选择文件复选框后,\r\n 会在倒计时之后直接发送剪贴板中的内容, 默认的发送日期为当天日期,\r\n 在日期输入框中输入日期格式例如2022-01-01, \r\n 时间格式例如13:45:23,7:23:05.'''\r\n self.note_label = Label(self, text = note, justify = 'left').place(x = 10, y = 0, width = 400, height = 65)\r\n\r\n l1_ct = '窗口名称:'\r\n Label(self, text=l1_ct).place(x = 10, y = 70, width = self.w_size(l1_ct))\r\n \r\n wl_ct = '文件传输助手'\r\n self.wlct = StringVar()\r\n self.wlct.set(wl_ct)\r\n self.window_name_entry = Entry(self, textvariable = self.wlct)\r\n self.window_name_entry.place(x = self.w_size(l1_ct) + 10, y = 70, width = 196)\r\n \r\n l2_ct = '要发送的内容: '\r\n Label(self, text = l2_ct).place(x = 10, y = 100, width = self.w_size(l2_ct) - 10)\r\n self.content_text = Text(self)\r\n self.content_text.place(x = 10, y = 130, width = 400, height = 300)\r\n\r\n l3_ct = '循环次数:'\r\n self.lts_ct = IntVar()\r\n Label(self, text = l3_ct).place(x = 10, y = 435, width = self.w_size(l3_ct))\r\n self.loop_times_spinbox = Spinbox(self, from_ = 1, to = 100000, textvariable = self.lts_ct)\r\n self.loop_times_spinbox.place(x = self.w_size(l3_ct) + 10, y = 435)\r\n\r\n l4_ct = '循环时间间隔(秒):'\r\n Label(self, text = l4_ct).place(x = 10, y = 465, width = self.w_size(l4_ct) - 15)\r\n\r\n self.lti_ct = DoubleVar()\r\n self.lti_ct.set(1)\r\n self.loop_time_interval_entry = Entry(self, textvariable = self.lti_ct)\r\n self.loop_time_interval_entry.place(x = self.w_size(l4_ct) + 10, y = 465, width = 60)\r\n\r\n l5_ct = '日期:'\r\n Label(self, text = l5_ct).place(x = 10, y = 495, width = self.w_size(l5_ct))\r\n\r\n dt = time.strftime('%Y-%m-%d', time.localtime())\r\n self.dt_ct = StringVar()\r\n self.dt_ct.set(dt)\r\n self.send_date_entry = Entry(self, textvariable = self.dt_ct)\r\n self.send_date_entry.place(x = self.w_size(l5_ct) + 10, y = 495, width = self.w_size(dt))\r\n\r\n l6_ct = '时间:'\r\n Label(self, text = l6_ct).place(x = self.w_size(dt) + self.w_size(l5_ct) + 20,\r\n y = 495, width = self.w_size(l6_ct))\r\n\r\n tt = time.strftime('%H:%M:%S', time.localtime())\r\n self.tt_ct = StringVar()\r\n self.tt_ct.set(tt)\r\n self.send_time_entry = Entry(self, textvariable = self.tt_ct)\r\n self.send_time_entry.place(x = self.w_size(dt) + self.w_size(l5_ct) + self.w_size(l6_ct) + 30,\r\n y = 495, width = self.w_size(tt))\r\n\r\n l7_ct = '是否为文件(勾选后为True, 不勾选为False)'\r\n Label(self, text = l7_ct).place(x = 10, y = 525, width = round(self.w_size(l7_ct) * 0.72))\r\n\r\n self.fcbv = BooleanVar()\r\n self.file_check_box = Checkbutton(self, command = self.file_check_box_action)\r\n self.file_check_box.place(x = round(self.w_size(l7_ct) * 0.72) + 10, y = 525)\r\n\r\n self.indicator_content = StringVar()\r\n Label(self, textvariable = self.indicator_content).place(x = 150, y = 580, width = 120)\r\n \r\n self.send_button = Button(self, text = '发送', command = self.send_button_action)\r\n self.send_button.place(x = 155, y = 600, width = 100, height = 50)\r\n\r\n def file_check_box_action(self) -> None:\r\n if not self.fcbv.get():\r\n self.fcbv.set(not self.fcbv.get())\r\n else:\r\n self.fcbv.set(not self.fcbv.get())\r\n\r\n def send_button_action(self) -> None:\r\n send_date = self.dt_ct.get()\r\n send_time = self.tt_ct.get()\r\n rgx = re.compile(r'\\d{4}\\-\\d{2}-\\d{2} \\d{1,2}:\\d{2}:\\d{2}')\r\n input_date_time = f'{send_date} {send_time}'\r\n if rgx.match(input_date_time):\r\n time_left = get_date_time_sub(send_time, send_date)\r\n if thd.active_count() < 2:\r\n loop_times = self.lts_ct.get()\r\n loop_time_interval = self.lti_ct.get()\r\n file_flag = self.fcbv.get()\r\n window_name = self.wlct.get()\r\n send_content = self.content_text.get(1.0, END)\r\n self.indicator_content.set(f'已经过:{0}%')\r\n msg = {'window_name': window_name, 'send_content': send_content,\r\n 'loop_times': loop_times, 'loop_time_interval': loop_time_interval,\r\n 'file_flag': file_flag, 'send_date': send_date, 'send_time': send_time,\r\n 'input_date_time': input_date_time}\r\n mt = thd.Thread(target = self.indicator_increse, args = (time_left, msg))\r\n mt.start()\r\n else:\r\n messagebox.showerror('时间日期错误', '请重新输入时间或日期再次尝试')\r\n\r\n def indicator_increse(self, time_left: int, msg: dict) -> None:\r\n for i in range(time_left + 1):\r\n self.indicator_content.set(f'已经过:{i / time_left * 100:.2f}%')\r\n time.sleep(1)\r\n self.update()\r\n messagebox.showinfo('发送提醒', '正在执行发送任务...')\r\n loop_execute(msg.get('window_name'), msg.get('send_content'), msg.get('loop_time_interval'),\r\n msg.get('loop_times'), msg.get('file_flag'))\r\n messagebox.showinfo('任务提醒', '发送任务已完成。')\r\n\r\ndef get_window_handler(wname: str) -> int:\r\n win_ha = win32gui.FindWindow('ChatWnd', wname)\r\n win32gui.BringWindowToTop(win_ha)\r\n CoInitialize()\r\n sl = wclt.Dispatch('WScript.Shell')\r\n sl.SendKeys('%')\r\n win32gui.SetForegroundWindow(win_ha)\r\n return win_ha\r\n\r\ndef message_send(win_ha: int) -> None:\r\n win32api.keybd_event(17, 0, 0, 0)\r\n time.sleep(0.1)\r\n win32gui.SendMessage(win_ha, win32con.WM_KEYDOWN, 86, 0)\r\n time.sleep(0.1)\r\n win32gui.SendMessage(win_ha, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)\r\n win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)\r\n\r\ndef content_copy_to_clipboard(text):\r\n clipbd.OpenClipboard()\r\n clipbd.EmptyClipboard()\r\n clipbd.SetClipboardText(text)\r\n clipbd.CloseClipboard()\r\n\r\ndef loop_execute(window_name: str,\r\n sending_text: str,\r\n time_interval: float,\r\n loop_times: int,\r\n file_flg: bool) -> None:\r\n \r\n for _ in range(1, loop_times + 1):\r\n time.sleep(time_interval)\r\n if not file_flg:\r\n content_copy_to_clipboard(sending_text)\r\n w_ha = get_window_handler(window_name)\r\n message_send(w_ha)\r\n\r\ndef get_file_flg() -> bool:\r\n cont = input('If file send else type here: ').strip()\r\n if cont == 'True':\r\n return True\r\n else:\r\n return False\r\n\r\ndef get_date_time_sub(send_time: str, send_date: str = datetime.datetime.today().date().strftime('%H:%M:%S')) -> int:\r\n ti = time.localtime()\r\n fdt = f'{send_date} {send_time}'\r\n td = time.strptime(fdt, '%Y-%m-%d %H:%M:%S')\r\n tx = datetime.datetime(ti.tm_year, ti.tm_mon, ti.tm_mday, ti.tm_hour, ti.tm_min, ti.tm_sec)\r\n ty = datetime.datetime(td.tm_year, td.tm_mon, td.tm_mday, td.tm_hour, td.tm_min, td.tm_sec)\r\n return (ty - tx).days * 24 * 3600 + (ty - tx).seconds\r\n\r\nif __name__ == '__main__':\r\n root = Tk()\r\n root.title('微信轰炸工具 Ver GM 1.0.1')\r\n root.geometry('420x700+200+50')\r\n app = GUI_MAIN_APP(root)\r\n app.mainloop()\r\n", "repo_name": "ItiharaYuuko/wechat_loop", "sub_path": "wechat_loop.pyw", "file_name": "wechat_loop.pyw", "file_ext": "pyw", "file_size_in_byte": 8314, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "tkinter.Frame", "line_number": 10, "usage_type": "name"}, {"api_name": "tkinter.Label", "line_number": 26, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 29, "usage_type": "call"}, {"api_name": "tkinter.StringVar", "line_number": 32, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 34, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 38, "usage_type": "call"}, {"api_name": "tkinter.Text", "line_number": 39, "usage_type": "call"}, {"api_name": "tkinter.IntVar", "line_number": 43, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 44, "usage_type": "call"}, {"api_name": "tkinter.Spinbox", "line_number": 45, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 49, "usage_type": "call"}, {"api_name": "tkinter.DoubleVar", "line_number": 51, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 53, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 57, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 59, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 59, "usage_type": "call"}, {"api_name": "tkinter.StringVar", "line_number": 60, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 62, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 66, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 69, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 69, "usage_type": "call"}, {"api_name": "tkinter.StringVar", "line_number": 70, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 72, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 77, "usage_type": "call"}, {"api_name": "tkinter.BooleanVar", "line_number": 79, "usage_type": "call"}, {"api_name": "tkinter.Checkbutton", "line_number": 80, "usage_type": "call"}, {"api_name": "tkinter.StringVar", "line_number": 83, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 84, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 86, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 98, "usage_type": "call"}, {"api_name": "threading.active_count", "line_number": 102, "usage_type": "call"}, {"api_name": "tkinter.constants.END", "line_number": 107, "usage_type": "argument"}, {"api_name": "threading.Thread", "line_number": 113, "usage_type": "call"}, {"api_name": "tkinter.messagebox.showerror", "line_number": 116, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 116, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 121, "usage_type": "call"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 123, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 123, "usage_type": "name"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 126, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 126, "usage_type": "name"}, {"api_name": "win32gui.FindWindow", "line_number": 129, "usage_type": "call"}, {"api_name": "win32gui.BringWindowToTop", "line_number": 130, "usage_type": "call"}, {"api_name": "pythoncom.CoInitialize", "line_number": 131, "usage_type": "call"}, {"api_name": "win32com.client.Dispatch", "line_number": 132, "usage_type": "call"}, {"api_name": "win32com.client", "line_number": 132, "usage_type": "name"}, {"api_name": "win32gui.SetForegroundWindow", "line_number": 134, "usage_type": "call"}, {"api_name": "win32api.keybd_event", "line_number": 138, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 139, "usage_type": "call"}, {"api_name": "win32gui.SendMessage", "line_number": 140, "usage_type": "call"}, {"api_name": "win32con.WM_KEYDOWN", "line_number": 140, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 141, "usage_type": "call"}, {"api_name": "win32gui.SendMessage", "line_number": 142, "usage_type": "call"}, {"api_name": "win32con.WM_KEYDOWN", "line_number": 142, "usage_type": "attribute"}, {"api_name": "win32con.VK_RETURN", "line_number": 142, "usage_type": "attribute"}, {"api_name": "win32api.keybd_event", "line_number": 143, "usage_type": "call"}, {"api_name": "win32con.KEYEVENTF_KEYUP", "line_number": 143, "usage_type": "attribute"}, {"api_name": "win32clipboard.OpenClipboard", "line_number": 146, "usage_type": "call"}, {"api_name": "win32clipboard.EmptyClipboard", "line_number": 147, "usage_type": "call"}, {"api_name": "win32clipboard.SetClipboardText", "line_number": 148, "usage_type": "call"}, {"api_name": "win32clipboard.CloseClipboard", "line_number": 149, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 158, "usage_type": "call"}, {"api_name": "datetime.datetime.today", "line_number": 171, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 171, "usage_type": "attribute"}, {"api_name": "time.localtime", "line_number": 172, "usage_type": "call"}, {"api_name": "time.strptime", "line_number": 174, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 175, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 176, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 180, "usage_type": "call"}]} +{"seq_id": "3112870991", "text": "import sys\nimport pygame as p\nfrom config import *\nfrom utils import *\nfrom Sorting import *\n\n\ndef draw_sorted(window, algo, count):\n\ttry:\n\t\t# Get current list and the numbers compared this turn\n\t\tsorted_list, i = next(count)\n\t\tn_num = len(sorted_list)\n\n\t\tdraw_bg(window, algo)\n\n\t\tfor j, v in enumerate(sorted_list):\n\t\t\trect = p.Rect(*create_rect(j, v, n_num))\n\t\t\tif j <= i:\n\t\t\t\tp.draw.rect(window, PASTEL_GREEN, rect)\n\t\t\telse:\n\t\t\t\tp.draw.rect(window, WHITE, rect)\n\n\t\tp.display.flip()\n\n\texcept StopIteration:\n\t\treturn True\t\n\n\ndef draw_sorting(window, curr_list, v1, v2):\n\tn_num = len(curr_list)\n\tfor i, v in enumerate(curr_list):\n\t\trect = p.Rect(*create_rect(i, v, n_num))\n\t\tif v == v1:\n\t\t\tp.draw.rect(window, PASTEL_PINK, rect)\n\t\telif v == v2:\n\t\t\tp.draw.rect(window, PASTEL_BLUE, rect)\n\t\telse:\n\t\t\tp.draw.rect(window, WHITE, rect)\n\n\ndef draw_bg(window, algo):\n\twindow.fill(BACKGROUND)\n\tcomicsans = p.font.SysFont('Helvetica', 20)\n\tname_surface = comicsans.render(algo, False, WHITE)\n\twindow.blit(name_surface, (20, 20))\n\ndef draw(window, algo, l, n):\n\ttry:\n\t\t# Get current list and the numbers compared this turn\n\t\tcurr_list, v1, v2 = next(l)\n\t\tdraw_bg(window, algo)\n\t\tdraw_sorting(window, curr_list, v1, v2)\n\n\t\tp.display.flip()\n\n\texcept StopIteration:\n\t\treturn True\n\n\ndef main():\n\t# Initialize pygame\n\tp.init()\n\tp.font.init()\n\n\t# Create pygame window\n\twindow = p.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))\n\tclock = p.time.Clock()\n\n\tsorting_algorithms = {\n\t\t'Bubble Sort': bubble_sort,\n\t\t'Selection Sort': selection_sort,\n\t\t'Insertion Sort': insertion_sort,\n\t}\n\n\t# Initialize parameters\n\tn = 30\n\tascending = False\n\tlst = generate_list(n)\n\tcount = counter(sorted(lst, reverse = not ascending))\n\n\talgo = 'Selection Sort'\n\tl = sorting_algorithms[algo](lst, ascending = ascending)\n\n\t# Initialize flags\n\trunning = True\n\treset = False\n\tfinished = False\n\n\twhile running:\n\t\tclock.tick(FPS)\n\n\t\tif reset:\n\t\t\tlst = generate_list(n)\n\t\t\tl = bubble_sort(lst)\n\n\t\tfor e in p.event.get():\n\t\t\tif e.type == p.QUIT:\n\t\t\t\trunning = False\n\t\t\t\tp.quit()\n\t\t\t\tsys.exit()\n\n\t\tif not finished and draw(window, algo, l, n):\n\t\t\tfinished = True\n\n\t\tif finished and draw_sorted(window, algo, count):\n\t\t\tp.time.wait(2000)\n\t\t\trunning = False\n\t\t\tp.quit()\n\nif __name__ == '__main__':\n\tmain()", "repo_name": "kaiwinut/pygame-sorting-visualizer", "sub_path": "src/sortviz/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2257, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pygame.Rect", "line_number": 17, "usage_type": "call"}, {"api_name": "pygame.draw.rect", "line_number": 19, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 19, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 21, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 21, "usage_type": "attribute"}, {"api_name": "pygame.display.flip", "line_number": 23, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pygame.Rect", "line_number": 32, "usage_type": "call"}, {"api_name": "pygame.draw.rect", "line_number": 34, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 34, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 36, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 36, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 38, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 38, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 43, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 43, "usage_type": "attribute"}, {"api_name": "pygame.display.flip", "line_number": 54, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 54, "usage_type": "attribute"}, {"api_name": "pygame.init", "line_number": 62, "usage_type": "call"}, {"api_name": "pygame.font.init", "line_number": 63, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 63, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 66, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 66, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 67, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 67, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 96, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 96, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 97, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 99, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 100, "usage_type": "call"}, {"api_name": "pygame.time.wait", "line_number": 106, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 106, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 108, "usage_type": "call"}]} +{"seq_id": "21911083259", "text": "# coding: utf-8\n\nimport six\n\nfrom huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization\n\n\nclass AgreeTenantAuthorizationV2Req:\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n sensitive_list = []\n\n openapi_types = {\n 'auth_detail_list': 'list[TenantAgreeAuthDetailV2]',\n 'auth_effective_time': 'int',\n 'auth_expire_time': 'int',\n 'group_id': 'str',\n 'agency_id': 'str'\n }\n\n attribute_map = {\n 'auth_detail_list': 'auth_detail_list',\n 'auth_effective_time': 'auth_effective_time',\n 'auth_expire_time': 'auth_expire_time',\n 'group_id': 'group_id',\n 'agency_id': 'agency_id'\n }\n\n def __init__(self, auth_detail_list=None, auth_effective_time=None, auth_expire_time=None, group_id=None, agency_id=None):\n \"\"\"AgreeTenantAuthorizationV2Req\n\n The model defined in huaweicloud sdk\n\n :param auth_detail_list: 授权详情列表\n :type auth_detail_list: list[:class:`huaweicloudsdkosm.v2.TenantAgreeAuthDetailV2`]\n :param auth_effective_time: 授权生效时间\n :type auth_effective_time: int\n :param auth_expire_time: 授权到期时间\n :type auth_expire_time: int\n :param group_id: 组id\n :type group_id: str\n :param agency_id: 委托id\n :type agency_id: str\n \"\"\"\n \n \n\n self._auth_detail_list = None\n self._auth_effective_time = None\n self._auth_expire_time = None\n self._group_id = None\n self._agency_id = None\n self.discriminator = None\n\n if auth_detail_list is not None:\n self.auth_detail_list = auth_detail_list\n if auth_effective_time is not None:\n self.auth_effective_time = auth_effective_time\n if auth_expire_time is not None:\n self.auth_expire_time = auth_expire_time\n if group_id is not None:\n self.group_id = group_id\n if agency_id is not None:\n self.agency_id = agency_id\n\n @property\n def auth_detail_list(self):\n \"\"\"Gets the auth_detail_list of this AgreeTenantAuthorizationV2Req.\n\n 授权详情列表\n\n :return: The auth_detail_list of this AgreeTenantAuthorizationV2Req.\n :rtype: list[:class:`huaweicloudsdkosm.v2.TenantAgreeAuthDetailV2`]\n \"\"\"\n return self._auth_detail_list\n\n @auth_detail_list.setter\n def auth_detail_list(self, auth_detail_list):\n \"\"\"Sets the auth_detail_list of this AgreeTenantAuthorizationV2Req.\n\n 授权详情���表\n\n :param auth_detail_list: The auth_detail_list of this AgreeTenantAuthorizationV2Req.\n :type auth_detail_list: list[:class:`huaweicloudsdkosm.v2.TenantAgreeAuthDetailV2`]\n \"\"\"\n self._auth_detail_list = auth_detail_list\n\n @property\n def auth_effective_time(self):\n \"\"\"Gets the auth_effective_time of this AgreeTenantAuthorizationV2Req.\n\n 授权生效时间\n\n :return: The auth_effective_time of this AgreeTenantAuthorizationV2Req.\n :rtype: int\n \"\"\"\n return self._auth_effective_time\n\n @auth_effective_time.setter\n def auth_effective_time(self, auth_effective_time):\n \"\"\"Sets the auth_effective_time of this AgreeTenantAuthorizationV2Req.\n\n 授权生效时间\n\n :param auth_effective_time: The auth_effective_time of this AgreeTenantAuthorizationV2Req.\n :type auth_effective_time: int\n \"\"\"\n self._auth_effective_time = auth_effective_time\n\n @property\n def auth_expire_time(self):\n \"\"\"Gets the auth_expire_time of this AgreeTenantAuthorizationV2Req.\n\n 授权到期时间\n\n :return: The auth_expire_time of this AgreeTenantAuthorizationV2Req.\n :rtype: int\n \"\"\"\n return self._auth_expire_time\n\n @auth_expire_time.setter\n def auth_expire_time(self, auth_expire_time):\n \"\"\"Sets the auth_expire_time of this AgreeTenantAuthorizationV2Req.\n\n 授权到期时间\n\n :param auth_expire_time: The auth_expire_time of this AgreeTenantAuthorizationV2Req.\n :type auth_expire_time: int\n \"\"\"\n self._auth_expire_time = auth_expire_time\n\n @property\n def group_id(self):\n \"\"\"Gets the group_id of this AgreeTenantAuthorizationV2Req.\n\n 组id\n\n :return: The group_id of this AgreeTenantAuthorizationV2Req.\n :rtype: str\n \"\"\"\n return self._group_id\n\n @group_id.setter\n def group_id(self, group_id):\n \"\"\"Sets the group_id of this AgreeTenantAuthorizationV2Req.\n\n 组id\n\n :param group_id: The group_id of this AgreeTenantAuthorizationV2Req.\n :type group_id: str\n \"\"\"\n self._group_id = group_id\n\n @property\n def agency_id(self):\n \"\"\"Gets the agency_id of this AgreeTenantAuthorizationV2Req.\n\n 委托id\n\n :return: The agency_id of this AgreeTenantAuthorizationV2Req.\n :rtype: str\n \"\"\"\n return self._agency_id\n\n @agency_id.setter\n def agency_id(self, agency_id):\n \"\"\"Sets the agency_id of this AgreeTenantAuthorizationV2Req.\n\n 委托id\n\n :param agency_id: The agency_id of this AgreeTenantAuthorizationV2Req.\n :type agency_id: str\n \"\"\"\n self._agency_id = agency_id\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n if attr in self.sensitive_list:\n result[attr] = \"****\"\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n import simplejson as json\n if six.PY2:\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)\n\n def __repr__(self):\n \"\"\"For `print`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, AgreeTenantAuthorizationV2Req):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n", "repo_name": "huaweicloud/huaweicloud-sdk-python-v3", "sub_path": "huaweicloud-sdk-osm/huaweicloudsdkosm/v2/model/agree_tenant_authorization_v2_req.py", "file_name": "agree_tenant_authorization_v2_req.py", "file_ext": "py", "file_size_in_byte": 7199, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 104, "dataset": "github-code", "pt": "20", "api": [{"api_name": "six.iteritems", "line_number": 186, "usage_type": "call"}, {"api_name": "six.PY2", "line_number": 212, "usage_type": "attribute"}, {"api_name": "sys.setdefaultencoding", "line_number": 215, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 216, "usage_type": "call"}, {"api_name": "huaweicloudsdkcore.utils.http_utils.sanitize_for_serialization", "line_number": 216, "usage_type": "call"}]} +{"seq_id": "33150573155", "text": "import random\r\nimport sys\r\nimport json\r\nfrom musicInfo import *\r\n\r\nclass NGramModel(object):\r\n\r\n def __init__(self):\r\n \"\"\"\r\n Requires: nothing\r\n Modifies: self (this instance of the NGramModel object)\r\n Effects: This is the NGramModel constructor. It sets up an empty\r\n dictionary as a member variable. It is called from the\r\n constructors of the NGramModel child classes. This\r\n function is done for you.\r\n \"\"\"\r\n self.nGramCounts = {}\r\n\r\n def __str__(self):\r\n \"\"\"\r\n Requires: nothing\r\n Modifies: nothing\r\n Effects: Returns the string to print when you call print on an\r\n NGramModel object. This string will be formatted in JSON\r\n and display the currently trained dataset.\r\n This function is done for you.\r\n \"\"\"\r\n return self.__class__.__name__ + ':\\n' +\\\r\n json.dumps(\r\n self.nGramCounts,\r\n sort_keys=True,\r\n indent=4,\r\n separators=(',', ': ')\r\n )\r\n\r\n def prepData(self, text):\r\n \"\"\"\r\n Requires: text is a list of lists of strings\r\n Modifies: nothing\r\n Effects: returns a copy of text where each inner list starts with\r\n the symbols '^::^' and '^:::^', and ends with the symbol\r\n '$:::$'. For example, if an inner list in text were\r\n ['hello', 'goodbye'], that list would become\r\n ['^::^', '^:::^', 'hello', 'goodbye', '$:::$'] in the\r\n returned copy.\r\n \"\"\"\r\n textCopy = []\r\n for line in text:\r\n textCopy.append(['^::^', '^:::^'] + line + ['$:::$'])\r\n return textCopy\r\n\r\n def trainModel(self, text):\r\n \"\"\"\r\n Requires: text is a list of lists of strings\r\n Modifies: self.nGramCounts\r\n Effects: this function populates the self.nGramCounts dictionary.\r\n It does not need to be modified here because you will\r\n override it in the NGramModel child classes according\r\n to the spec.\r\n \"\"\"\r\n pass\r\n\r\n def trainingDataHasNGram(self, sentence):\r\n \"\"\"\r\n Requires: sentence is a list of strings, and trainingDataHasNGram\r\n has returned True for this particular language model\r\n Modifies: nothing\r\n Effects: returns a bool indicating whether or not this n-gram model\r\n can be used to choose the next token for the current\r\n sentence. This function does not need to be modified because\r\n you will override it in NGramModel child classes according\r\n to the spec.\r\n \"\"\"\r\n pass\r\n\r\n def getCandidateDictionary(self, sentence):\r\n \"\"\"\r\n Requires: sentence is a list of strings\r\n Modifies: nothing\r\n Effects: returns the dictionary of candidate next words to be added\r\n to the current sentence. This function does not need to be\r\n modified because you will override it in the NGramModel child\r\n classes according to the spec.\r\n \"\"\"\r\n pass\r\n\r\n def weightedChoice(self, candidates):\r\n \"\"\"\r\n Requires: candidates is a dictionary; the keys of candidates are items\r\n you want to choose from and the values are integers\r\n Modifies: nothing\r\n Effects: returns a candidate item (a key in the candidates dictionary)\r\n based on the algorithm described in the spec.\r\n \"\"\"\r\n #create a list of the keys in candidates\r\n words = []\r\n for key in candidates:\r\n words.append(key)\r\n #create a list of the values in candidates\r\n values = []\r\n for key in candidates:\r\n values.append(candidates[key])\r\n #create the list of cumulative values\r\n cumulative = []\r\n count = 0\r\n for number in values:\r\n count += number\r\n cumulative.append(count)\r\n #get a random number between [1, last number in cumulative]\r\n x = random.randrange(0, cumulative[-1])\r\n #as soon as the cumulative value is higher than random number, return key\r\n for i in range(len(words)):\r\n if cumulative[i] > x:\r\n return words[i]\r\n\r\n def getNextToken(self, sentence):\r\n \"\"\"\r\n Requires: sentence is a list of strings, and this model can be used to\r\n choose the next token for the current sentence\r\n Modifies: nothing\r\n Effects: returns the next token to be added to sentence by calling\r\n the getCandidateDictionary and weightedChoice functions.\r\n For more information on how to put all these functions\r\n together, see the spec.\r\n \"\"\"\r\n return self.weightedChoice(self.getCandidateDictionary(sentence))\r\n\r\n def getNextNote(self, musicalSentence, possiblePitches):\r\n \"\"\"\r\n Requires: musicalSentence is a list of PySynth tuples,\r\n possiblePitches is a list of possible pitches for this\r\n line of music (in other words, a key signature), and this\r\n model can be used to choose the next note for the current\r\n musical sentence\r\n Modifies: nothing\r\n Effects: returns the next note to be added to the \"musical sentence\".\r\n For details on how to do this and how this will differ\r\n from getNextToken, see the spec.\r\n \"\"\"\r\n #makes dict consisting of possible notes\r\n allCandidates = self.getCandidateDictionary(musicalSentence)\r\n #makes new dict consisting of possible notes that are also in the key signature\r\n constrainedCandidates = {}\r\n for note in allCandidates:\r\n if note[0][: -1] in possiblePitches or note == '$:::$':\r\n constrainedCandidates[note] = allCandidates[note]\r\n if constrainedCandidates != {}:\r\n return self.weightedChoice(constrainedCandidates)\r\n else:\r\n return (random.choice(possiblePitches) + '4', random.choice(NOTE_DURATIONS))\r\n\r\n###############################################################################\r\n# Main\r\n###############################################################################\r\n\r\nif __name__ == '__main__':\r\n # Add your tests here\r\n text = [ ['the', 'quick', 'brown', 'fox'], ['the', 'lazy', 'dog'] ]\r\n choices = { 'the': 2, 'quick': 1, 'brown': 1 }\r\n mod = NGramModel()\r\n print(mod)\r\n dict = {'the' : 2, 'birthday' : 5, 'python' : 1, 'jessica' : 10, 'aaron' : 9, 'brad' : 48, 'seven' : 6}\r\n sentence = ['happy', 'birthday']\r\n mod.weightedChoice(dict)\r\n", "repo_name": "aawill/Creative-AI-Music-Generator", "sub_path": "models/nGramModel.py", "file_name": "nGramModel.py", "file_ext": "py", "file_size_in_byte": 6912, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "json.dumps", "line_number": 29, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 110, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 150, "usage_type": "call"}]} +{"seq_id": "25062275689", "text": "import db\nimport cv2\nimport face\nimport frame\nimport yaml\nimport typedef\nimport utils\nimport numpy as np\nimport copy\nimport pickle\n\n\ndef main(config):\n ss = config['source_scale']\n frame_drawer = frame.drawer.Drawer()\n capturer = cv2.VideoCapture(config['source'])\n face_detector = face.detectors.get(**config['face_detector'])\n face_validators = face.validators.get_list(config['face_validators'])\n frame_filters = frame.filters.get_list(config['frame_filters'])\n face_buffer = face.buffer.FaceBuffer(config['face_buffer_size'])\n face_encoder = face.encoders.get(**config['face_encoder'])\n face_recognizer = face.recognizers.get(face_encoder, **config['face_recognizer'])\n storage = db.initialize(**config['database'])\n face_trackers = []\n\n try:\n with open('storage.pkl', 'rb') as db_file:\n storage = pickle.load(db_file)\n print(\"Database was loaded from file.\")\n print(f\"Number of persons in DB: {len(storage.get_face_ids())}\")\n except:\n print(\"No databese to load.\")\n\n while True:\n read_ok, image = capturer.read()\n if not read_ok:\n cv2.imshow(\"Frame\", typedef.NO_VIDEO_FRAME)\n key = cv2.waitKey(1) & 0xFF\n if key == ord(\"q\"):\n capturer.release()\n break\n continue\n image_copy = image.copy()\n\n image = cv2.resize(image, None, fx=ss, fy=ss, interpolation=cv2.INTER_CUBIC)\n image = frame.filters.apply(frame_filters, image)\n face_boxes = face_detector(image)\n face_boxes = face.validators.apply(face_validators, image, face_boxes)\n\n face_ids, face_boxes = face.trackers.apply(face_trackers, image, face_boxes)\n face_trackers = face.trackers.drop_wasted(face_trackers)\n _face_boxes = copy.deepcopy(face_boxes)\n face_boxes = face.validators.apply(face_validators, image, face_boxes)\n _face_ids = []\n for face_id, _face_box in zip(face_ids, _face_boxes):\n for face_box in face_boxes:\n if _face_box == face_box:\n _face_ids.append(face_id)\n\n for face_id, face_box in zip(_face_ids, face_boxes):\n\n face_image = utils.crop(image, *face_box)\n face_image = cv2.resize(face_image, tuple(config['face_shape']),\n interpolation=cv2.INTER_AREA)\n\n if face_id == typedef.UNKNOWN_FACE_ID:\n face_id = utils.generate_tmp_face_id()\n tracker = face.trackers.get(**config['face_tracker'])\n tracker.init(image, face_box, face_id)\n face_trackers.append(tracker)\n\n if utils.is_tmp_id(face_id):\n face_buffer.update(face_id, face_image)\n if face_buffer.is_full(face_id):\n mean_face = face_buffer.get_mean_face(face_id)\n recognized_ok, rec_face_id = face_recognizer(mean_face, storage)\n\n tracked_face_id = face_id\n if not recognized_ok:\n encoded_mean_face = face_encoder(mean_face)\n face_id = storage.generate_face_id()\n storage.add(face_id, encoded_mean_face)\n else:\n face_id = rec_face_id\n face.trackers.update_face_ids(face_trackers, [tracked_face_id], [face_id])\n\n face_box = tuple(np.int64(np.array(face_box) * (1 / ss)))\n frame_drawer.draw_box(image_copy, face_box)\n frame_drawer.draw_face_id(image_copy, face_box, face_id)\n\n cv2.imshow(\"Frame\", image_copy)\n key = cv2.waitKey(1) & 0xFF\n if key == ord(\"q\"):\n capturer.release()\n break\n cv2.destroyAllWindows()\n with open('storage.pkl', 'wb') as db_file:\n pickle.dump(storage, db_file)\n\n\nif __name__ == '__main__':\n with open('config.yml', 'r') as file:\n main(yaml.safe_load(file))\n", "repo_name": "shaxov/spy-eye", "sub_path": "run.py", "file_name": "run.py", "file_ext": "py", "file_size_in_byte": 3989, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "frame.drawer.Drawer", "line_number": 15, "usage_type": "call"}, {"api_name": "frame.drawer", "line_number": 15, "usage_type": "attribute"}, {"api_name": "cv2.VideoCapture", "line_number": 16, "usage_type": "call"}, {"api_name": "face.detectors.get", "line_number": 17, "usage_type": "call"}, {"api_name": "face.detectors", "line_number": 17, "usage_type": "attribute"}, {"api_name": "face.validators.get_list", "line_number": 18, "usage_type": "call"}, {"api_name": "face.validators", "line_number": 18, "usage_type": "attribute"}, {"api_name": "frame.filters.get_list", "line_number": 19, "usage_type": "call"}, {"api_name": "frame.filters", "line_number": 19, "usage_type": "attribute"}, {"api_name": "face.buffer.FaceBuffer", "line_number": 20, "usage_type": "call"}, {"api_name": "face.buffer", "line_number": 20, "usage_type": "attribute"}, {"api_name": "face.encoders.get", "line_number": 21, "usage_type": "call"}, {"api_name": "face.encoders", "line_number": 21, "usage_type": "attribute"}, {"api_name": "face.recognizers.get", "line_number": 22, "usage_type": "call"}, {"api_name": "face.recognizers", "line_number": 22, "usage_type": "attribute"}, {"api_name": "db.initialize", "line_number": 23, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 37, "usage_type": "call"}, {"api_name": "typedef.NO_VIDEO_FRAME", "line_number": 37, "usage_type": "attribute"}, {"api_name": "cv2.waitKey", "line_number": 38, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 45, "usage_type": "call"}, {"api_name": "cv2.INTER_CUBIC", "line_number": 45, "usage_type": "attribute"}, {"api_name": "frame.filters.apply", "line_number": 46, "usage_type": "call"}, {"api_name": "frame.filters", "line_number": 46, "usage_type": "attribute"}, {"api_name": "face.validators.apply", "line_number": 48, "usage_type": "call"}, {"api_name": "face.validators", "line_number": 48, "usage_type": "attribute"}, {"api_name": "face.trackers.apply", "line_number": 50, "usage_type": "call"}, {"api_name": "face.trackers", "line_number": 50, "usage_type": "attribute"}, {"api_name": "face.trackers.drop_wasted", "line_number": 51, "usage_type": "call"}, {"api_name": "face.trackers", "line_number": 51, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 52, "usage_type": "call"}, {"api_name": "face.validators.apply", "line_number": 53, "usage_type": "call"}, {"api_name": "face.validators", "line_number": 53, "usage_type": "attribute"}, {"api_name": "utils.crop", "line_number": 62, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 63, "usage_type": "call"}, {"api_name": "cv2.INTER_AREA", "line_number": 64, "usage_type": "attribute"}, {"api_name": "typedef.UNKNOWN_FACE_ID", "line_number": 66, "usage_type": "attribute"}, {"api_name": "utils.generate_tmp_face_id", "line_number": 67, "usage_type": "call"}, {"api_name": "face.trackers.get", "line_number": 68, "usage_type": "call"}, {"api_name": "face.trackers", "line_number": 68, "usage_type": "attribute"}, {"api_name": "utils.is_tmp_id", "line_number": 72, "usage_type": "call"}, {"api_name": "face.trackers.update_face_ids", "line_number": 85, "usage_type": "call"}, {"api_name": "face.trackers", "line_number": 85, "usage_type": "attribute"}, {"api_name": "numpy.int64", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 87, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 91, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 92, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 96, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 98, "usage_type": "call"}, {"api_name": "yaml.safe_load", "line_number": 103, "usage_type": "call"}]} +{"seq_id": "34440016677", "text": "from abc import ABC, abstractmethod\nfrom typing import Optional\n\nfrom torchdata.dataloader2 import DataLoader2, DistributedReadingService, MultiProcessingReadingService, SequentialReadingService \nfrom torch.utils.data import DataLoader\n\nimport pytorch_lightning as pl\nfrom pytorch_lightning.utilities.exceptions import MisconfigurationException\n\nimport logging\npl_logger = logging.getLogger('pytorch_lightning')\n\nclass BaseTDM(pl.LightningDataModule, ABC):\n\tdef __init__(self, \n\t\t\ttrain_urls:Optional[list]=None,\n\t\t\ttest_urls:Optional[list]=None,\n\t\t\tvalid_urls:Optional[list]=None,\n\t\t\tpredict_urls:Optional[list]=None,\n\t\t\tbatch_size:Optional[int]=1,\n\t\t\tnum_workers:Optional[int]=0,\n\t\t\tpersistent_workers:Optional[bool]=True,\n\t\t\tshuffle:Optional[bool]=True,\n\t\t):\n\t\tsuper().__init__()\n\n\t\tself.train_data_dir = train_urls\n\t\tself.test_data_dir = test_urls\n\t\tself.valid_data_dir = valid_urls\n\t\tself.predict_data_dir = predict_urls\n\n\t\tself.shuffle = shuffle\n\t\tself.batch_size = batch_size\n\t\tself.num_workers = num_workers\n\t\tself.persistent_workers = persistent_workers\n\n\t@abstractmethod\n\tdef to_sampels(self, data):\n\t\tpass\n\t\n\t@abstractmethod\n\tdef create_pipeline(self, data_dir):\n\t\tpass\n\n\t@abstractmethod\n\tdef collate_fn(self, data):\n\t\tpass\n\n\tdef setup(self, stage:Optional[str] = None):\n\t\tif self.train_data_dir and len(self.train_data_dir)>0:\n\t\t\tself.train = self.create_pipeline(self.train_data_dir)\n\n\t\tif self.test_data_dir and len(self.test_data_dir)>0:\n\t\t\tself.test = self.create_pipeline(self.test_data_dir)\n\n\t\tif self.valid_data_dir and len(self.valid_data_dir)>0:\n\t\t\tself.valid = self.create_pipeline(self.valid_data_dir)\n\n\t\tif self.predict_data_dir and len(self.predict_data_dir)>0:\n\t\t\tself.predict = self.create_pipeline(self.predict_data_dir)\n\n\tdef _dataloader2(self, dataset):\n\t\tservice = [\n\t\t\tDistributedReadingService(),\n\t\t\tMultiProcessingReadingService(num_workers=self.num_workers),\n\t\t]\n\t\treading_service = SequentialReadingService(*service)\n\t\treturn DataLoader2(dataset, reading_service=reading_service)\n\n\tdef _dataloader(self, dataset):\n\t\treturn DataLoader(dataset, num_workers=self.num_workers, batch_size=self.batch_size, collate_fn=self.collate_fn)\n\n\tdef train_dataloader(self):\n\t\tif not self.train_data_dir:\n\t\t\traise MisconfigurationException('train_urls not set.')\n\t\treturn self._dataloader(self.train)\n\n\tdef val_dataloader(self):\n\t\tif not self.valid_data_dir:\n\t\t\traise MisconfigurationException('valid_urls not set.')\n\t\treturn self._dataloader(self.valid)\n\n\tdef test_dataloader(self):\n\t\tif not self.test_data_dir:\n\t\t\traise MisconfigurationException('test_urls not set.')\n\t\treturn self._dataloader(self.test)\n\n\tdef predict_dataloader(self):\n\t\tif not self.predict_data_dir:\n\t\t\traise MisconfigurationException('predict_urls not set.')\n\t\treturn self._dataloader(self.predict)", "repo_name": "knoriy/video2caption", "sub_path": "src/datamodule/base.py", "file_name": "base.py", "file_ext": "py", "file_size_in_byte": 2790, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "logging.getLogger", "line_number": 11, "usage_type": "call"}, {"api_name": "pytorch_lightning.LightningDataModule", "line_number": 13, "usage_type": "attribute"}, {"api_name": "abc.ABC", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 15, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 16, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 17, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 18, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 19, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 20, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 21, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 22, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 36, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 40, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 44, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 48, "usage_type": "name"}, {"api_name": "torchdata.dataloader2.DistributedReadingService", "line_number": 63, "usage_type": "call"}, {"api_name": "torchdata.dataloader2.MultiProcessingReadingService", "line_number": 64, "usage_type": "call"}, {"api_name": "torchdata.dataloader2.SequentialReadingService", "line_number": 66, "usage_type": "call"}, {"api_name": "torchdata.dataloader2.DataLoader2", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 70, "usage_type": "call"}, {"api_name": "pytorch_lightning.utilities.exceptions.MisconfigurationException", "line_number": 74, "usage_type": "call"}, {"api_name": "pytorch_lightning.utilities.exceptions.MisconfigurationException", "line_number": 79, "usage_type": "call"}, {"api_name": "pytorch_lightning.utilities.exceptions.MisconfigurationException", "line_number": 84, "usage_type": "call"}, {"api_name": "pytorch_lightning.utilities.exceptions.MisconfigurationException", "line_number": 89, "usage_type": "call"}]} +{"seq_id": "37326198417", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport random\nimport re\nfrom PIL import Image\nfrom pylab import *\nimport sys\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.applications.vgg16 import *\nfrom tensorflow.keras.models import *\nimport tensorflow.keras.backend as K\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import Convolution2D, ZeroPadding2D, MaxPooling2D, Cropping2D, Conv2D\nfrom tensorflow.keras.layers import Input, Add, Dropout, Permute, add\nfrom tensorflow.compat.v1.layers import conv2d_transpose\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.python.keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\n\nlabel_codes=[(255,0,0), (0,255,0), (255,255,0),(0,0,0)]\nlabel_names=['comp_1','comp2_2', 'both','background']\nDATA_PATH='./dataset/'\ncode2id = {v:k for k,v in enumerate(label_codes)}\nid2code = {k:v for k,v in enumerate(label_codes)}\nname2id = {v:k for k,v in enumerate(label_names)}\nid2name = {k:v for k,v in enumerate(label_names)}\n\ndata_gen_args = dict(rescale=1./255)\nmask_gen_args = dict()\n\ntrain_frames_datagen = ImageDataGenerator(**data_gen_args)\ntrain_masks_datagen = ImageDataGenerator(**mask_gen_args)\nval_frames_datagen = ImageDataGenerator(**data_gen_args)\nval_masks_datagen = ImageDataGenerator(**mask_gen_args)\ndef _read_to_tensor(fname, output_height=256, output_width=256, normalize_data=False):\n '''Function to read images from given image file path, and provide resized images as tensors\n Inputs:\n fname - image file path\n output_height - required output image height\n output_width - required output image width\n normalize_data - if True, normalize data to be centered around 0 (mean 0, range 0 to 1)\n Output: Processed image tenso\n '''\n\n # Read the image as a tensor\n img_strings = tf.io.read_file(fname)\n imgs_decoded = tf.image.decode_jpeg(img_strings)\n\n # Resize the image\n output = tf.image.resize(imgs_decoded, [output_height, output_width])\n\n # Normalize if required\n if normalize_data:\n output = (output - 128) / 128\n return output\n\n#reading frames and masks\ndef read_images(img_dir):\n '''Function to get all image directories, read images and masks in separate tensors\n Inputs:\n img_dir - file directory\n Outputs\n frame_tensors, masks_tensors, frame files list, mask files list\n '''\n\n # Get the file names list from provided directory\n file_list = [f for f in os.listdir(img_dir) if os.path.isfile(os.path.join(img_dir, f))]\n\n # Separate frame and mask files lists, exclude unnecessary files\n frames_list = [file for file in file_list if ('_labeled' not in file) and ('txt' not in file) and ('m' not in file)]\n frames_list.sort()\n masks_list = [file for file in file_list if ('_labeled' in file) and ('txt' not in file) and ('m' not in file)]\n masks_list.sort()\n print('{} frame files found in the provided directory.'.format(len(frames_list)))\n print('{} mask files found in the provided directory.'.format(len(masks_list)))\n\n # Create file paths from file names\n frames_paths = [os.path.join(img_dir, fname) for fname in frames_list]\n masks_paths = [os.path.join(img_dir, fname) for fname in masks_list]\n\n # Create dataset of tensors\n frame_data = tf.data.Dataset.from_tensor_slices(frames_paths)\n masks_data = tf.data.Dataset.from_tensor_slices(masks_paths)\n\n # Read images into the tensor dataset\n frame_tensors = frame_data.map(_read_to_tensor)\n masks_tensors = masks_data.map(_read_to_tensor)\n\n print('Completed importing {} frame images from the provided directory.'.format(len(frames_list)))\n print('Completed importing {} mask images from the provided directory.'.format(len(masks_list)))\n\n return frame_tensors, masks_tensors, frames_list, masks_list\n\n\ndef parse_code(l):\n '''Function to parse lines in a text file, returns separated elements (label codes and names in this case)\n '''\n if len(l.strip().split(\"\\t\")) == 2:\n a, b = l.strip().split(\"\\t\")\n return tuple(int(i) for i in a.split(' ')), b\n else:\n a, b, c = l.strip().split(\"\\t\")\n return tuple(int(i) for i in a.split(' ')), c\n\ndef generate_image_folder_structure(DATA_PATH,frames, masks, frames_list, masks_list):\n '''Function to save images in the appropriate folder directories\n Inputs:\n frames - frame tensor dataset\n masks - mask tensor dataset\n frames_list - frame file paths\n masks_list - mask file paths\n '''\n # Create iterators for frames and masks\n frame_batches = tf.compat.v1.data.make_one_shot_iterator(\n frames) # outside of TF Eager, we would use make_one_shot_iterator\n mask_batches = tf.compat.v1.data.make_one_shot_iterator(masks)\n\n # Iterate over the train images while saving the frames and masks in appropriate folders\n dir_name = 'train'\n for file in zip(frames_list[:-round(0.2 * len(frames_list))], masks_list[:-round(0.2 * len(masks_list))]):\n # Convert tensors to numpy arrays\n frame = frame_batches.next().numpy().astype(np.uint8)\n mask = mask_batches.next().numpy().astype(np.uint8)\n\n # Convert numpy arrays to images\n frame = Image.fromarray(frame)\n mask = Image.fromarray(mask)\n\n # Save frames and masks to correct directories\n frame.save(DATA_PATH + '{}_frames/{}'.format(dir_name, dir_name) + '/' + file[0])\n mask.save(DATA_PATH + '{}_masks/{}'.format(dir_name, dir_name) + '/' + file[1])\n\n # Iterate over the val images while saving the frames and masks in appropriate folders\n dir_name = 'val'\n for file in zip(frames_list[-round(0.2 * len(frames_list)):], masks_list[-round(0.2 * len(masks_list)):]):\n # Convert tensors to numpy arrays\n frame = frame_batches.next().numpy().astype(np.uint8)\n mask = mask_batches.next().numpy().astype(np.uint8)\n\n # Convert numpy arrays to images\n frame = Image.fromarray(frame)\n mask = Image.fromarray(mask)\n\n # Save frames and masks to correct directories\n frame.save(DATA_PATH + '{}_frames/{}'.format(dir_name, dir_name) + '/' + file[0])\n mask.save(DATA_PATH + '{}_masks/{}'.format(dir_name, dir_name) + '/' + file[1])\n\n print(\"Saved {} frames to directory {}\".format(len(frames_list), DATA_PATH))\n print(\"Saved {} masks to directory {}\".format(len(masks_list), DATA_PATH))\n\ndef rgb_to_onehot(rgb_image, colormap = id2code):\n '''Function to one hot encode RGB mask labels\n Inputs:\n rgb_image - image matrix (eg. 256 x 256 x 3 dimension numpy ndarray)\n colormap - dictionary of color to label id\n Output: One hot encoded image of dimensions (height x width x num_classes) where num_classes = len(colormap)\n '''\n num_classes = len(colormap)\n shape = rgb_image.shape[:2]+(num_classes,)\n encoded_image = np.zeros( shape, dtype=np.int8 )\n for i, cls in enumerate(colormap):\n encoded_image[:,:,i] = np.all(rgb_image.reshape( (-1,3) ) == colormap[i], axis=1).reshape(shape[:2])\n return encoded_image\n\n\ndef onehot_to_rgb(onehot, colormap = id2code):\n '''Function to decode encoded mask labels\n Inputs:\n onehot - one hot encoded image matrix (height x width x num_classes)\n colormap - dictionary of color to label id\n Output: Decoded RGB image (height x width x 3)\n '''\n single_layer = np.argmax(onehot, axis=-1)\n output = np.zeros( onehot.shape[:2]+(3,) )\n for k in colormap.keys():\n output[single_layer==k] = colormap[k]\n return np.uint8(output)\n\n\ndef TrainAugmentGenerator(seed=1, batch_size=5 ):\n '''Train Image data generator\n Inputs:\n seed - seed provided to the flow_from_directory function to ensure aligned data flow\n batch_size - number of images to import at a time\n Output: Decoded RGB image (height x width x 3)\n '''\n train_image_generator = train_frames_datagen.flow_from_directory(\n DATA_PATH + 'train_frames/',\n batch_size=batch_size, seed=seed)\n\n train_mask_generator = train_masks_datagen.flow_from_directory(\n DATA_PATH + 'train_masks/',\n batch_size=batch_size, seed=seed)\n\n while True:\n X1i = train_image_generator.next()\n X2i = train_mask_generator.next()\n\n # One hot encoding RGB images\n mask_encoded = [rgb_to_onehot(X2i[0][x, :, :, :], id2code) for x in range(X2i[0].shape[0])]\n\n yield X1i[0], np.asarray(mask_encoded)\n\n\ndef ValAugmentGenerator(seed=1, batch_size=5):\n '''Validation Image data generator\n Inputs:\n seed - seed provided to the flow_from_directory function to ensure aligned data flow\n batch_size - number of images to import at a time\n Output: Decoded RGB image (height x width x 3)\n '''\n val_image_generator = val_frames_datagen.flow_from_directory(\n DATA_PATH + 'val_frames/',\n batch_size=batch_size, seed=seed)\n\n val_mask_generator = val_masks_datagen.flow_from_directory(\n DATA_PATH + 'val_masks/',\n batch_size=batch_size, seed=seed)\n\n while True:\n X1i = val_image_generator.next()\n X2i = val_mask_generator.next()\n\n # One hot encoding RGB images\n mask_encoded = [rgb_to_onehot(X2i[0][x, :, :, :], id2code) for x in range(X2i[0].shape[0])]\n yield X1i[0], np.asarray(mask_encoded)\n\n\ndef read_test_images(img_dir):\n '''Function to get all image directories, read images and masks in separate tensors\n Inputs:\n img_dir - file directory\n Outputs\n frame_tensors, masks_tensors, frame files list, mask files list\n '''\n\n # Get the file names list from provided directory\n file_list = [f for f in os.listdir(img_dir) if os.path.isfile(os.path.join(img_dir, f))]\n\n # Separate frame and mask files lists, exclude unnecessary files\n frames_list = [file for file in file_list if ('_labeled' not in file) and ('txt' not in file) and ('m' not in file)]\n frames_list.sort()\n print('{} frame files found in the provided directory.'.format(len(frames_list)))\n\n # Create file paths from file names\n frames_paths = [os.path.join(img_dir, fname) for fname in frames_list]\n\n # Create dataset of tensors\n frame_data = tf.data.Dataset.from_tensor_slices(frames_paths)\n\n # Read images into the tensor dataset\n frame_tensors = frame_data.map(_read_to_tensor)\n\n print('Completed importing {} frame images from the provided directory.'.format(len(frames_list)))\n\n return frame_tensors, frames_list\n\ndef tversky_loss(y_true, y_pred):\n alpha = 0.5\n beta = 0.5\n\n ones = K.ones(K.shape(y_true))\n p0 = y_pred # proba that voxels are class i\n p1 = ones - y_pred # proba that voxels are not class i\n g0 = y_true\n g1 = ones - y_true\n\n num = K.sum(p0 * g0, (0, 1, 2, 3))\n den = num + alpha * K.sum(p0 * g1, (0, 1, 2, 3)) + beta * K.sum(p1 * g0, (0, 1, 2, 3))\n\n T = K.sum(num / den) # when summing over classes, T has dynamic range [0 Ncl]\n\n Ncl = K.cast(K.shape(y_true)[-1], 'float32')\n return Ncl - T\n\n\ndef dice_coef(y_true, y_pred):\n smooth=1\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f)\n return (2. * intersection + smooth) / (K.sum(y_true_f*y_true_f) + K.sum(y_pred_f*y_pred_f) + smooth)\n\n\ndef dice_coef_loss(y_true, y_pred):\n return 1.-dice_coef(y_true, y_pred)", "repo_name": "aidanamv/Unet-Segmenetation", "sub_path": "data_processing.py", "file_name": "data_processing.py", "file_ext": "py", "file_size_in_byte": 11708, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "tensorflow.keras.preprocessing.image.ImageDataGenerator", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.keras.preprocessing.image.ImageDataGenerator", "line_number": 35, "usage_type": "call"}, {"api_name": "tensorflow.keras.preprocessing.image.ImageDataGenerator", "line_number": 36, "usage_type": "call"}, {"api_name": "tensorflow.keras.preprocessing.image.ImageDataGenerator", "line_number": 37, "usage_type": "call"}, {"api_name": "tensorflow.io.read_file", "line_number": 49, "usage_type": "call"}, {"api_name": "tensorflow.io", "line_number": 49, "usage_type": "attribute"}, {"api_name": "tensorflow.image.decode_jpeg", "line_number": 50, "usage_type": "call"}, {"api_name": "tensorflow.image", "line_number": 50, "usage_type": "attribute"}, {"api_name": "tensorflow.image.resize", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.image", "line_number": 53, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path", "line_number": 70, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 81, "usage_type": "call"}, {"api_name": "os.path", "line_number": 81, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 82, "usage_type": "call"}, {"api_name": "os.path", "line_number": 82, "usage_type": "attribute"}, {"api_name": "tensorflow.data.Dataset.from_tensor_slices", "line_number": 85, "usage_type": "call"}, {"api_name": "tensorflow.data", "line_number": 85, "usage_type": "attribute"}, {"api_name": "tensorflow.data.Dataset.from_tensor_slices", "line_number": 86, "usage_type": "call"}, {"api_name": "tensorflow.data", "line_number": 86, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v1.data.make_one_shot_iterator", "line_number": 117, "usage_type": "call"}, {"api_name": "tensorflow.compat", "line_number": 117, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v1.data.make_one_shot_iterator", "line_number": 119, "usage_type": "call"}, {"api_name": "tensorflow.compat", "line_number": 119, "usage_type": "attribute"}, {"api_name": "numpy.uint8", "line_number": 125, "usage_type": "attribute"}, {"api_name": "numpy.uint8", "line_number": 126, "usage_type": "attribute"}, {"api_name": "PIL.Image.fromarray", "line_number": 129, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 129, "usage_type": "name"}, {"api_name": "PIL.Image.fromarray", "line_number": 130, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 130, "usage_type": "name"}, {"api_name": "numpy.uint8", "line_number": 140, "usage_type": "attribute"}, {"api_name": "numpy.uint8", "line_number": 141, "usage_type": "attribute"}, {"api_name": "PIL.Image.fromarray", "line_number": 144, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 144, "usage_type": "name"}, {"api_name": "PIL.Image.fromarray", "line_number": 145, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 145, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.int8", "line_number": 163, "usage_type": "attribute"}, {"api_name": "numpy.all", "line_number": 165, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 180, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 205, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 229, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 241, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 241, "usage_type": "call"}, {"api_name": "os.path", "line_number": 241, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 241, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 249, "usage_type": "call"}, {"api_name": "os.path", "line_number": 249, "usage_type": "attribute"}, {"api_name": "tensorflow.data.Dataset.from_tensor_slices", "line_number": 252, "usage_type": "call"}, {"api_name": "tensorflow.data", "line_number": 252, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.backend.ones", "line_number": 265, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 265, "usage_type": "name"}, {"api_name": "tensorflow.keras.backend.shape", "line_number": 265, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend.sum", "line_number": 271, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 271, "usage_type": "name"}, {"api_name": "tensorflow.keras.backend.sum", "line_number": 272, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 272, "usage_type": "name"}, {"api_name": "tensorflow.keras.backend.sum", "line_number": 274, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 274, "usage_type": "name"}, {"api_name": "tensorflow.keras.backend.cast", "line_number": 276, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 276, "usage_type": "name"}, {"api_name": "tensorflow.keras.backend.shape", "line_number": 276, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend.flatten", "line_number": 282, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 282, "usage_type": "name"}, {"api_name": "tensorflow.keras.backend.flatten", "line_number": 283, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 283, "usage_type": "name"}, {"api_name": "tensorflow.keras.backend.sum", "line_number": 284, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 284, "usage_type": "name"}, {"api_name": "tensorflow.keras.backend.sum", "line_number": 285, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 285, "usage_type": "name"}]} +{"seq_id": "21884309689", "text": "# coding: utf-8\n\nimport six\n\nfrom huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization\n\n\nclass ShowDataRequest:\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n sensitive_list = []\n\n openapi_types = {\n 'x_need_content': 'bool',\n 'eihealth_project_id': 'str',\n 'path': 'str'\n }\n\n attribute_map = {\n 'x_need_content': 'X-Need-Content',\n 'eihealth_project_id': 'eihealth_project_id',\n 'path': 'path'\n }\n\n def __init__(self, x_need_content=None, eihealth_project_id=None, path=None):\n \"\"\"ShowDataRequest\n\n The model defined in huaweicloud sdk\n\n :param x_need_content: 返回文件内容\n :type x_need_content: bool\n :param eihealth_project_id: 医疗智能体平台项目ID,您可以在EIHealth平台单击所需的项目名称,进入项目设置页面查看。\n :type eihealth_project_id: str\n :param path: 对象全路径(项目名称:|路径)\n :type path: str\n \"\"\"\n \n \n\n self._x_need_content = None\n self._eihealth_project_id = None\n self._path = None\n self.discriminator = None\n\n if x_need_content is not None:\n self.x_need_content = x_need_content\n self.eihealth_project_id = eihealth_project_id\n self.path = path\n\n @property\n def x_need_content(self):\n \"\"\"Gets the x_need_content of this ShowDataRequest.\n\n 返回文件内容\n\n :return: The x_need_content of this ShowDataRequest.\n :rtype: bool\n \"\"\"\n return self._x_need_content\n\n @x_need_content.setter\n def x_need_content(self, x_need_content):\n \"\"\"Sets the x_need_content of this ShowDataRequest.\n\n 返回文件内容\n\n :param x_need_content: The x_need_content of this ShowDataRequest.\n :type x_need_content: bool\n \"\"\"\n self._x_need_content = x_need_content\n\n @property\n def eihealth_project_id(self):\n \"\"\"Gets the eihealth_project_id of this ShowDataRequest.\n\n 医疗智能体平台项目ID,您可以在EIHealth平台单击所需的项目名称,进入项目设置页面查看。\n\n :return: The eihealth_project_id of this ShowDataRequest.\n :rtype: str\n \"\"\"\n return self._eihealth_project_id\n\n @eihealth_project_id.setter\n def eihealth_project_id(self, eihealth_project_id):\n \"\"\"Sets the eihealth_project_id of this ShowDataRequest.\n\n 医疗智能体平台项目ID,您可以在EIHealth平台单击所需的项目名称,进入项目设置页面查看。\n\n :param eihealth_project_id: The eihealth_project_id of this ShowDataRequest.\n :type eihealth_project_id: str\n \"\"\"\n self._eihealth_project_id = eihealth_project_id\n\n @property\n def path(self):\n \"\"\"Gets the path of this ShowDataRequest.\n\n 对象全路径(项目名称:|路径)\n\n :return: The path of this ShowDataRequest.\n :rtype: str\n \"\"\"\n return self._path\n\n @path.setter\n def path(self, path):\n \"\"\"Sets the path of this ShowDataRequest.\n\n 对象全路径(项目名称:|路径)\n\n :param path: The path of this ShowDataRequest.\n :type path: str\n \"\"\"\n self._path = path\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n if attr in self.sensitive_list:\n result[attr] = \"****\"\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n import simplejson as json\n if six.PY2:\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)\n\n def __repr__(self):\n \"\"\"For `print`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ShowDataRequest):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n", "repo_name": "huaweicloud/huaweicloud-sdk-python-v3", "sub_path": "huaweicloud-sdk-eihealth/huaweicloudsdkeihealth/v1/model/show_data_request.py", "file_name": "show_data_request.py", "file_ext": "py", "file_size_in_byte": 5186, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 104, "dataset": "github-code", "pt": "20", "api": [{"api_name": "six.iteritems", "line_number": 126, "usage_type": "call"}, {"api_name": "six.PY2", "line_number": 152, "usage_type": "attribute"}, {"api_name": "sys.setdefaultencoding", "line_number": 155, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 156, "usage_type": "call"}, {"api_name": "huaweicloudsdkcore.utils.http_utils.sanitize_for_serialization", "line_number": 156, "usage_type": "call"}]} +{"seq_id": "70807824383", "text": "import binascii\nimport collections\nimport itertools\nimport logging\nimport re\nimport socket\nimport struct\n\nfrom typing import List, Optional, Tuple\n\nlogger = logging.getLogger(__name__)\n\n\ndef target_to_ipv4(target: str) -> Optional[List]:\n \"\"\"Attempt to return a single IPv4 host list from a target string.\"\"\"\n\n try:\n socket.inet_pton(socket.AF_INET, target)\n return [target]\n except socket.error:\n return None\n\n\ndef target_to_ipv6(target: str) -> Optional[List]:\n \"\"\"Attempt to return a single IPv6 host list from a target string.\"\"\"\n\n try:\n socket.inet_pton(socket.AF_INET6, target)\n return [target]\n except socket.error:\n return None\n\n\ndef ipv4_range_to_list(start_packed, end_packed) -> Optional[List]:\n \"\"\"Return a list of IPv4 entries from start_packed to end_packed.\"\"\"\n\n new_list = list()\n start = struct.unpack('!L', start_packed)[0]\n end = struct.unpack('!L', end_packed)[0]\n\n for value in range(start, end + 1):\n new_ip = socket.inet_ntoa(struct.pack('!L', value))\n new_list.append(new_ip)\n\n return new_list\n\n\ndef target_to_ipv4_short(target: str) -> Optional[List]:\n \"\"\"Attempt to return a IPv4 short range list from a target string.\"\"\"\n\n splitted = target.split('-')\n if len(splitted) != 2:\n return None\n\n try:\n start_packed = socket.inet_pton(socket.AF_INET, splitted[0])\n end_value = int(splitted[1])\n except (socket.error, ValueError):\n return None\n\n # For subnet with mask lower than /24, ip addresses ending in .0 are\n # allowed.\n # The next code checks for a range starting with a A.B.C.0.\n # For the octet equal to 0, bytes() returns an empty binary b'',\n # which must be handle in a special way.\n _start_value = bytes(start_packed[3])\n if _start_value:\n start_value = int(binascii.hexlify(_start_value), 16)\n elif _start_value == b'':\n start_value = 0\n else:\n return None\n\n if end_value < 0 or end_value > 255 or end_value < start_value:\n return None\n\n end_packed = start_packed[0:3] + struct.pack('B', end_value)\n\n return ipv4_range_to_list(start_packed, end_packed)\n\n\ndef target_to_ipv4_cidr(target: str) -> Optional[List]:\n \"\"\"Attempt to return a IPv4 CIDR list from a target string.\"\"\"\n\n splitted = target.split('/')\n if len(splitted) != 2:\n return None\n\n try:\n start_packed = socket.inet_pton(socket.AF_INET, splitted[0])\n block = int(splitted[1])\n except (socket.error, ValueError):\n return None\n\n if block <= 0 or block > 30:\n return None\n\n start_value = int(binascii.hexlify(start_packed), 16) >> (32 - block)\n start_value = (start_value << (32 - block)) + 1\n\n end_value = (start_value | (0xFFFFFFFF >> block)) - 1\n\n start_packed = struct.pack('!I', start_value)\n end_packed = struct.pack('!I', end_value)\n\n return ipv4_range_to_list(start_packed, end_packed)\n\n\ndef target_to_ipv6_cidr(target: str) -> Optional[List]:\n \"\"\"Attempt to return a IPv6 CIDR list from a target string.\"\"\"\n\n splitted = target.split('/')\n if len(splitted) != 2:\n return None\n\n try:\n start_packed = socket.inet_pton(socket.AF_INET6, splitted[0])\n block = int(splitted[1])\n except (socket.error, ValueError):\n return None\n\n if block <= 0 or block > 126:\n return None\n\n start_value = int(binascii.hexlify(start_packed), 16) >> (128 - block)\n start_value = (start_value << (128 - block)) + 1\n\n end_value = (start_value | (int('ff' * 16, 16) >> block)) - 1\n\n high = start_value >> 64\n low = start_value & ((1 << 64) - 1)\n\n start_packed = struct.pack('!QQ', high, low)\n\n high = end_value >> 64\n low = end_value & ((1 << 64) - 1)\n\n end_packed = struct.pack('!QQ', high, low)\n\n return ipv6_range_to_list(start_packed, end_packed)\n\n\ndef target_to_ipv4_long(target: str) -> Optional[List]:\n \"\"\"Attempt to return a IPv4 long-range list from a target string.\"\"\"\n\n splitted = target.split('-')\n if len(splitted) != 2:\n return None\n\n try:\n start_packed = socket.inet_pton(socket.AF_INET, splitted[0])\n end_packed = socket.inet_pton(socket.AF_INET, splitted[1])\n except socket.error:\n return None\n\n if end_packed < start_packed:\n return None\n\n return ipv4_range_to_list(start_packed, end_packed)\n\n\ndef ipv6_range_to_list(start_packed, end_packed) -> List:\n \"\"\"Return a list of IPv6 entries from start_packed to end_packed.\"\"\"\n\n new_list = list()\n\n start = int(binascii.hexlify(start_packed), 16)\n end = int(binascii.hexlify(end_packed), 16)\n\n for value in range(start, end + 1):\n high = value >> 64\n low = value & ((1 << 64) - 1)\n new_ip = socket.inet_ntop(\n socket.AF_INET6, struct.pack('!2Q', high, low)\n )\n new_list.append(new_ip)\n\n return new_list\n\n\ndef target_to_ipv6_short(target: str) -> Optional[List]:\n \"\"\"Attempt to return a IPv6 short-range list from a target string.\"\"\"\n\n splitted = target.split('-')\n if len(splitted) != 2:\n return None\n\n try:\n start_packed = socket.inet_pton(socket.AF_INET6, splitted[0])\n end_value = int(splitted[1], 16)\n except (socket.error, ValueError):\n return None\n\n start_value = int(binascii.hexlify(start_packed[14:]), 16)\n if end_value < 0 or end_value > 0xFFFF or end_value < start_value:\n return None\n\n end_packed = start_packed[:14] + struct.pack('!H', end_value)\n\n return ipv6_range_to_list(start_packed, end_packed)\n\n\ndef target_to_ipv6_long(target: str) -> Optional[List]:\n \"\"\"Attempt to return a IPv6 long-range list from a target string.\"\"\"\n\n splitted = target.split('-')\n if len(splitted) != 2:\n return None\n\n try:\n start_packed = socket.inet_pton(socket.AF_INET6, splitted[0])\n end_packed = socket.inet_pton(socket.AF_INET6, splitted[1])\n except socket.error:\n return None\n\n if end_packed < start_packed:\n return None\n\n return ipv6_range_to_list(start_packed, end_packed)\n\n\ndef target_to_hostname(target: str) -> Optional[List]:\n \"\"\"Attempt to return a single hostname list from a target string.\"\"\"\n\n if len(target) == 0 or len(target) > 255:\n return None\n\n if not re.match(r'^[\\w.-]+$', target):\n return None\n\n return [target]\n\n\ndef target_to_list(target: str) -> Optional[List]:\n \"\"\"Attempt to return a list of single hosts from a target string.\"\"\"\n\n # Is it an IPv4 address ?\n new_list = target_to_ipv4(target)\n # Is it an IPv6 address ?\n if not new_list:\n new_list = target_to_ipv6(target)\n # Is it an IPv4 CIDR ?\n if not new_list:\n new_list = target_to_ipv4_cidr(target)\n # Is it an IPv6 CIDR ?\n if not new_list:\n new_list = target_to_ipv6_cidr(target)\n # Is it an IPv4 short-range ?\n if not new_list:\n new_list = target_to_ipv4_short(target)\n # Is it an IPv4 long-range ?\n if not new_list:\n new_list = target_to_ipv4_long(target)\n # Is it an IPv6 short-range ?\n if not new_list:\n new_list = target_to_ipv6_short(target)\n # Is it an IPv6 long-range ?\n if not new_list:\n new_list = target_to_ipv6_long(target)\n # Is it a hostname ?\n if not new_list:\n new_list = target_to_hostname(target)\n\n return new_list\n\n\ndef target_str_to_list(target_str: str) -> Optional[List]:\n \"\"\"Parses a targets string into a list of individual targets.\n Return a list of hosts, None if supplied target_str is None or\n empty, or an empty list in case of malformed target.\n \"\"\"\n new_list = list()\n\n if not target_str:\n return None\n\n target_str = target_str.strip(',')\n\n for target in target_str.split(','):\n target = target.strip()\n target_list = target_to_list(target)\n\n if target_list:\n new_list.extend(target_list)\n else:\n logger.info(\"%s: Invalid target value\", target)\n return []\n\n return list(collections.OrderedDict.fromkeys(new_list))\n\n\ndef resolve_hostname(hostname: str) -> Optional[str]:\n \"\"\"Returns IP of a hostname.\"\"\"\n\n assert hostname\n try:\n return socket.gethostbyname(hostname)\n except socket.gaierror:\n return None\n\n\ndef is_valid_address(address: str) -> bool:\n if not address:\n return False\n\n try:\n socket.inet_pton(socket.AF_INET, address)\n except OSError:\n # invalid IPv4 address\n try:\n socket.inet_pton(socket.AF_INET6, address)\n except OSError:\n # invalid IPv6 address\n return False\n\n return True\n\n\ndef get_hostname_by_address(address: str) -> str:\n \"\"\"Returns hostname of an address.\"\"\"\n\n if not is_valid_address(address):\n return ''\n\n try:\n hostname = socket.getfqdn(address)\n except (socket.gaierror, socket.herror):\n return ''\n\n if hostname == address:\n return ''\n\n return hostname\n\n\ndef port_range_expand(portrange: str) -> Optional[List]:\n \"\"\"\n Receive a port range and expands it in individual ports.\n\n @input Port range.\n e.g. \"4-8\"\n\n @return List of integers.\n e.g. [4, 5, 6, 7, 8]\n \"\"\"\n if not portrange or '-' not in portrange:\n return None\n\n try:\n port_range_min = int(portrange[: portrange.index('-')])\n port_range_max = int(portrange[portrange.index('-') + 1 :]) + 1\n except (IndexError, ValueError) as e:\n logger.info(\"Invalid port range format %s\", e)\n return None\n\n port_list = list()\n\n for single_port in range(\n port_range_min,\n port_range_max,\n ):\n port_list.append(single_port)\n\n return port_list\n\n\ndef port_str_arrange(ports: str) -> str:\n \"\"\"Gives a str in the format (always tcp listed first).\n T:U:\n \"\"\"\n b_tcp = ports.find(\"T\")\n b_udp = ports.find(\"U\")\n\n if (b_udp != -1 and b_tcp != -1) and b_udp < b_tcp:\n return ports[b_tcp:] + ports[b_udp:b_tcp]\n\n return ports\n\n\ndef ports_str_check_failed(port_str: str) -> bool:\n \"\"\"\n Check if the port string is well formed.\n Return True if fail, False other case.\n \"\"\"\n pattern = r'[^TU:0-9, \\-\\n]'\n if (\n re.search(pattern, port_str)\n or port_str.count('T') > 1\n or port_str.count('U') > 1\n or '-\\n' in port_str\n or '\\n-' in port_str\n or port_str[0] == '-'\n or port_str[len(port_str) - 1] == '-'\n or port_str.count(':') < (port_str.count('T') + port_str.count('U'))\n ):\n logger.error(\"Invalid port range format\")\n return True\n\n index = 0\n while index <= len(port_str) - 1:\n if port_str[index] == '-':\n try:\n int(port_str[index - 1])\n int(port_str[index + 1])\n except (TypeError, ValueError) as e:\n logger.error(\"Invalid port range format: %s\", e)\n return True\n index += 1\n\n return False\n\n\ndef ports_as_list(port_str: str) -> Tuple[Optional[List], Optional[List]]:\n \"\"\"\n Parses a ports string into two list of individual tcp and udp ports.\n\n @input string containing a port list\n e.g. T:1,2,3,5-8 U:22,80,600-1024\n\n @return two list of sorted integers, for tcp and udp ports respectively.\n \"\"\"\n if not port_str:\n logger.info(\"Invalid port value\")\n return [None, None]\n\n if ports_str_check_failed(port_str):\n logger.info(\"{0}: Port list malformed.\")\n return [None, None]\n\n tcp_list = list()\n udp_list = list()\n\n ports = port_str.replace(' ', '')\n ports = ports.replace('\\n', '')\n\n b_tcp = ports.find(\"T\")\n b_udp = ports.find(\"U\")\n\n if b_tcp != -1 and \"T:\" not in ports:\n return [None, None]\n if b_udp != -1 and \"U:\" not in ports:\n return [None, None]\n\n if len(ports) > 1 and ports[b_tcp - 1] == ',':\n ports = ports[: b_tcp - 1] + ports[b_tcp:]\n if len(ports) > 1 and ports[b_udp - 1] == ',':\n ports = ports[: b_udp - 1] + ports[b_udp:]\n\n ports = port_str_arrange(ports)\n\n tports = ''\n uports = ''\n # TCP ports listed first, then UDP ports\n if b_udp != -1 and b_tcp != -1:\n tports = ports[ports.index('T:') + 2 : ports.index('U:')]\n uports = ports[ports.index('U:') + 2 :]\n # Only UDP ports\n elif b_tcp == -1 and b_udp != -1:\n uports = ports[ports.index('U:') + 2 :]\n # Only TCP ports\n elif b_udp == -1 and b_tcp != -1:\n tports = ports[ports.index('T:') + 2 :]\n else:\n tports = ports\n\n if tports:\n for port in tports.split(','):\n port_range_expanded = port_range_expand(port)\n if '-' in port and port_range_expanded:\n tcp_list.extend(port_range_expanded)\n elif port != '' and '-' not in port:\n tcp_list.append(int(port))\n\n tcp_list.sort()\n\n if uports:\n for port in uports.split(','):\n port_range_expanded = port_range_expand(port)\n if '-' in port and port_range_expanded:\n udp_list.extend(port_range_expanded)\n elif port and '-' not in port:\n udp_list.append(int(port))\n udp_list.sort()\n\n if len(tcp_list) == 0 and len(udp_list) == 0:\n return [None, None]\n\n return (tcp_list, udp_list)\n\n\ndef get_tcp_port_list(port_str: str) -> Optional[List]:\n \"\"\"Return a list with tcp ports from a given port list in string format\"\"\"\n return ports_as_list(port_str)[0]\n\n\ndef get_udp_port_list(port_str: str) -> Optional[List]:\n \"\"\"Return a list with udp ports from a given port list in string format\"\"\"\n return ports_as_list(port_str)[1]\n\n\ndef port_list_compress(port_list: List) -> str:\n \"\"\"Compress a port list and return a string.\"\"\"\n\n if not port_list or len(port_list) == 0:\n logger.info(\"Invalid or empty port list.\")\n return ''\n\n port_list = sorted(set(port_list))\n compressed_list = []\n\n for _key, group in itertools.groupby(\n enumerate(port_list), lambda t: t[1] - t[0]\n ):\n group = list(group)\n\n if group[0][1] == group[-1][1]:\n compressed_list.append(str(group[0][1]))\n else:\n compressed_list.append(str(group[0][1]) + '-' + str(group[-1][1]))\n\n return ','.join(compressed_list)\n\n\ndef valid_port_list(port_list: str) -> bool:\n \"\"\"Validate a port list string.\n Parameters:\n port_list: string containing UDP and/or TCP\n port list as ranges or single comma\n separated ports \"\n Return True if it is a valid port list, False otherwise.\n \"\"\"\n\n # No port list provided\n if not port_list:\n return False\n\n # Remove white spaces\n port_list = port_list.replace(' ', '')\n\n # Special case is ignored.\n if port_list == 'U:,T:':\n return True\n\n # Invalid chars in the port list, like \\0 or \\n\n if ports_str_check_failed(port_list):\n return False\n\n tcp, udp = ports_as_list(port_list)\n # There is a port list but no tcp and no udp.\n if not tcp and not udp:\n return False\n\n if tcp:\n for port in tcp:\n if port < 1 or port > 65535:\n return False\n if udp:\n for port in udp:\n if port < 1 or port > 65535:\n return False\n\n return True\n", "repo_name": "greenbone/ospd-openvas", "sub_path": "ospd/network.py", "file_name": "network.py", "file_ext": "py", "file_size_in_byte": 15418, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 58, "dataset": "github-code", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 11, "usage_type": "call"}, {"api_name": "socket.inet_pton", "line_number": 18, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 18, "usage_type": "attribute"}, {"api_name": "socket.error", "line_number": 20, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 14, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 14, "usage_type": "name"}, {"api_name": "socket.inet_pton", "line_number": 28, "usage_type": "call"}, {"api_name": "socket.AF_INET6", "line_number": 28, "usage_type": "attribute"}, {"api_name": "socket.error", "line_number": 30, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 24, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 24, "usage_type": "name"}, {"api_name": "struct.unpack", "line_number": 38, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 39, "usage_type": "call"}, {"api_name": "socket.inet_ntoa", "line_number": 42, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 42, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 34, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 34, "usage_type": "name"}, {"api_name": "socket.inet_pton", "line_number": 56, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 56, "usage_type": "attribute"}, {"api_name": "socket.error", "line_number": 58, "usage_type": "attribute"}, {"api_name": "binascii.hexlify", "line_number": 68, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 77, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 48, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 48, "usage_type": "name"}, {"api_name": "socket.inet_pton", "line_number": 90, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 90, "usage_type": "attribute"}, {"api_name": "socket.error", "line_number": 92, "usage_type": "attribute"}, {"api_name": "binascii.hexlify", "line_number": 98, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 103, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 104, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 82, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 82, "usage_type": "name"}, {"api_name": "socket.inet_pton", "line_number": 117, "usage_type": "call"}, {"api_name": "socket.AF_INET6", "line_number": 117, "usage_type": "attribute"}, {"api_name": "socket.error", "line_number": 119, "usage_type": "attribute"}, {"api_name": "binascii.hexlify", "line_number": 125, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 133, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 138, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 109, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 109, "usage_type": "name"}, {"api_name": "socket.inet_pton", "line_number": 151, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 151, "usage_type": "attribute"}, {"api_name": "socket.inet_pton", "line_number": 152, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 152, "usage_type": "attribute"}, {"api_name": "socket.error", "line_number": 153, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 143, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 143, "usage_type": "name"}, {"api_name": "binascii.hexlify", "line_number": 167, "usage_type": "call"}, {"api_name": "binascii.hexlify", "line_number": 168, "usage_type": "call"}, {"api_name": "socket.inet_ntop", "line_number": 173, "usage_type": "call"}, {"api_name": "socket.AF_INET6", "line_number": 174, "usage_type": "attribute"}, {"api_name": "struct.pack", "line_number": 174, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 162, "usage_type": "name"}, {"api_name": "socket.inet_pton", "line_number": 189, "usage_type": "call"}, {"api_name": "socket.AF_INET6", "line_number": 189, "usage_type": "attribute"}, {"api_name": "socket.error", "line_number": 191, "usage_type": "attribute"}, {"api_name": "binascii.hexlify", "line_number": 194, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 198, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 181, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 181, "usage_type": "name"}, {"api_name": "socket.inet_pton", "line_number": 211, "usage_type": "call"}, {"api_name": "socket.AF_INET6", "line_number": 211, "usage_type": "attribute"}, {"api_name": "socket.inet_pton", "line_number": 212, "usage_type": "call"}, {"api_name": "socket.AF_INET6", "line_number": 212, "usage_type": "attribute"}, {"api_name": "socket.error", "line_number": 213, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 203, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 203, "usage_type": "name"}, {"api_name": "re.match", "line_number": 228, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 222, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 222, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 234, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 234, "usage_type": "name"}, {"api_name": "collections.OrderedDict.fromkeys", "line_number": 289, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 289, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 267, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 267, "usage_type": "name"}, {"api_name": "socket.gethostbyname", "line_number": 297, "usage_type": "call"}, {"api_name": "socket.gaierror", "line_number": 298, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 292, "usage_type": "name"}, {"api_name": "socket.inet_pton", "line_number": 307, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 307, "usage_type": "attribute"}, {"api_name": "socket.inet_pton", "line_number": 311, "usage_type": "call"}, {"api_name": "socket.AF_INET6", "line_number": 311, "usage_type": "attribute"}, {"api_name": "socket.getfqdn", "line_number": 326, "usage_type": "call"}, {"api_name": "socket.gaierror", "line_number": 327, "usage_type": "attribute"}, {"api_name": "socket.herror", "line_number": 327, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 336, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 336, "usage_type": "name"}, {"api_name": "re.search", "line_number": 387, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 413, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 413, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 413, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 491, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 491, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 496, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 496, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 501, "usage_type": "name"}, {"api_name": "itertools.groupby", "line_number": 511, "usage_type": "call"}]} +{"seq_id": "23008404203", "text": "from django.shortcuts import redirect, render_to_response, get_object_or_404\r\nfrom track.forms.user import LoginForm, RegisterForm, ModifyForm\r\nfrom django.contrib import auth\r\nfrom django.template import RequestContext\r\nfrom django.conf import settings\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom track.models import EUser, MapUser\r\nfrom django.http import Http404\r\nfrom datetime import datetime\r\n\r\n\r\n@login_required\r\ndef unstar(request, id):\r\n user = get_object_or_404(EUser, id=id)\r\n if request.user.username:\r\n try:\r\n mapu = MapUser.objects.get(Auser_id=request.user.id, Buser_id=id)\r\n except MapUser.DoesNotExist:\r\n raise Http404\r\n else:\r\n mapu.delete()\r\n user.fans -= 1\r\n user.save()\r\n return redirect('/users/%d/detail' % user.id)\r\n else:\r\n raise Http404\r\n\r\n\r\n@login_required\r\ndef star(request, id):\r\n user = get_object_or_404(EUser, id=id)\r\n if request.user.username:\r\n try:\r\n MapUser.objects.get(Auser_id=request.user.id, Buser_id=id)\r\n except MapUser.DoesNotExist:\r\n mapu = MapUser(Auser_id=request.user.id, Buser_id=id, time=datetime.now())\r\n mapu.save()\r\n user.fans += 1\r\n user.save()\r\n return redirect('/users/%d/detail' % user.id)\r\n else:\r\n raise Http404\r\n\r\n\r\n@login_required\r\ndef detail(request, id):\r\n user = get_object_or_404(EUser, id=id)\r\n is_followed = 1\r\n try:\r\n MapUser.objects.get(Auser_id=request.user.id, Buser_id=id)\r\n except MapUser.DoesNotExist:\r\n is_followed = 0\r\n if user.first_name is '':\r\n user.first_name = '保密'\r\n if user.last_name is '':\r\n user.last_name = '保密'\r\n if user.birth is None:\r\n user.birth = '保密'\r\n if user.nickname is None:\r\n user.nickname = '保密'\r\n if user.id != request.user.id:\r\n self = 0\r\n else:\r\n self = 1\r\n return render_to_response('user/detail.html', locals(), context_instance=RequestContext(request))\r\n\r\n\r\ndef get_logout(request):\r\n auth.logout(request)\r\n return redirect('/users/login')\r\n\r\n\r\ndef get_login(request, **kwargs):\r\n auth.logout(request)\r\n return render_to_response('user/login.html', kwargs, context_instance=RequestContext(request))\r\n\r\n\r\ndef post_login(request):\r\n form = LoginForm(request.POST)\r\n if not form.is_valid():\r\n return get_login(request, errors=form.errors)\r\n\r\n user = form.get_user()\r\n auth.login(request, user)\r\n\r\n return redirect('/users/%d/detail' % user.id)\r\n\r\n\r\ndef get_register(request, **kwargs):\r\n auth.logout(request)\r\n return render_to_response('user/register.html', kwargs, context_instance=RequestContext(request))\r\n\r\n\r\ndef post_register(request):\r\n form = RegisterForm(request.POST)\r\n\r\n if not form.is_valid():\r\n return get_register(request, errors=form.errors)\r\n\r\n user = form.save()\r\n user.set_password(form.cleaned_data.get('password'))\r\n user.save()\r\n return redirect(settings.LOGIN_URL)\r\n\r\n\r\n@login_required\r\ndef get_modify(request, **kwargs):\r\n return render_to_response('user/modify.html', kwargs, context_instance=RequestContext(request))\r\n\r\n\r\n@login_required\r\ndef post_modify(request):\r\n form = ModifyForm(request.POST)\r\n\r\n if not form.is_valid():\r\n return get_modify(request, errors=form.errors)\r\n\r\n user = request.user\r\n user.first_name = form.cleaned_data.get('firstname')\r\n user.last_name = form.cleaned_data.get('lastname')\r\n user.nickname = form.cleaned_data.get('nickname')\r\n user.email = form.cleaned_data.get('email')\r\n user.sex = form.cleaned_data.get('sex')\r\n user.birth = form.cleaned_data.get('birth')\r\n user.save()\r\n return redirect('/users/%d/detail' % request.user.id)", "repo_name": "zxpgo/news-website", "sub_path": "track/views/user.py", "file_name": "user.py", "file_ext": "py", "file_size_in_byte": 3812, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "django.shortcuts.get_object_or_404", "line_number": 14, "usage_type": "call"}, {"api_name": "track.models.EUser", "line_number": 14, "usage_type": "argument"}, {"api_name": "track.models.MapUser.objects.get", "line_number": 17, "usage_type": "call"}, {"api_name": "track.models.MapUser.objects", "line_number": 17, "usage_type": "attribute"}, {"api_name": "track.models.MapUser", "line_number": 17, "usage_type": "name"}, {"api_name": "track.models.MapUser.DoesNotExist", "line_number": 18, "usage_type": "attribute"}, {"api_name": "track.models.MapUser", "line_number": 18, "usage_type": "name"}, {"api_name": "django.http.Http404", "line_number": 19, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 24, "usage_type": "call"}, {"api_name": "django.http.Http404", "line_number": 26, "usage_type": "name"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 12, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 31, "usage_type": "call"}, {"api_name": "track.models.EUser", "line_number": 31, "usage_type": "argument"}, {"api_name": "track.models.MapUser.objects.get", "line_number": 34, "usage_type": "call"}, {"api_name": "track.models.MapUser.objects", "line_number": 34, "usage_type": "attribute"}, {"api_name": "track.models.MapUser", "line_number": 34, "usage_type": "name"}, {"api_name": "track.models.MapUser.DoesNotExist", "line_number": 35, "usage_type": "attribute"}, {"api_name": "track.models.MapUser", "line_number": 35, "usage_type": "name"}, {"api_name": "track.models.MapUser", "line_number": 36, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 36, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 36, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 40, "usage_type": "call"}, {"api_name": "django.http.Http404", "line_number": 42, "usage_type": "name"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 29, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 47, "usage_type": "call"}, {"api_name": "track.models.EUser", "line_number": 47, "usage_type": "argument"}, {"api_name": "track.models.MapUser.objects.get", "line_number": 50, "usage_type": "call"}, {"api_name": "track.models.MapUser.objects", "line_number": 50, "usage_type": "attribute"}, {"api_name": "track.models.MapUser", "line_number": 50, "usage_type": "name"}, {"api_name": "track.models.MapUser.DoesNotExist", "line_number": 51, "usage_type": "attribute"}, {"api_name": "track.models.MapUser", "line_number": 51, "usage_type": "name"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 65, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 65, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 45, "usage_type": "name"}, {"api_name": "django.contrib.auth.logout", "line_number": 69, "usage_type": "call"}, {"api_name": "django.contrib.auth", "line_number": 69, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 70, "usage_type": "call"}, {"api_name": "django.contrib.auth.logout", "line_number": 74, "usage_type": "call"}, {"api_name": "django.contrib.auth", "line_number": 74, "usage_type": "name"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 75, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 75, "usage_type": "call"}, {"api_name": "track.forms.user.LoginForm", "line_number": 79, "usage_type": "call"}, {"api_name": "django.contrib.auth.login", "line_number": 84, "usage_type": "call"}, {"api_name": "django.contrib.auth", "line_number": 84, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 86, "usage_type": "call"}, {"api_name": "django.contrib.auth.logout", "line_number": 90, "usage_type": "call"}, {"api_name": "django.contrib.auth", "line_number": 90, "usage_type": "name"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 91, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 91, "usage_type": "call"}, {"api_name": "track.forms.user.RegisterForm", "line_number": 95, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 103, "usage_type": "call"}, {"api_name": "django.conf.settings.LOGIN_URL", "line_number": 103, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 103, "usage_type": "name"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 108, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 108, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 106, "usage_type": "name"}, {"api_name": "track.forms.user.ModifyForm", "line_number": 113, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 126, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 111, "usage_type": "name"}]} +{"seq_id": "42685496135", "text": "from selenium import webdriver\r\nfrom selenium.webdriver.chrome.options import Options\r\nimport urllib.request, urllib.parse, urllib.error\r\nfrom bs4 import BeautifulSoup\r\nimport re\r\nimport csv\r\n\r\nnumChannels = 0\r\noptions = Options()\r\noptions.headless = True\r\ndriver = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe', chrome_options=options)\r\n\r\ndef BuildURL(url):\r\n try:\r\n driver.get(url)\r\n res = driver.execute_script(\"return document.documentElement.outerHTML\")\r\n soup = BeautifulSoup(res, \"lxml\")\r\n\r\n Ad = soup.find(\"ytd-app\")\r\n Ad = Ad.find(\"div\",{'id':'content'})\r\n Ad = Ad.find(\"ytd-page-manager\")\r\n return Ad\r\n except:\r\n print(\"Check internet connection while building URL\")\r\n return None\r\n\r\n\r\ndef getRelated(url,Ad):\r\n channelList = []\r\n\r\n # url = \"https://www.youtube.com/channel/UCCTtSp0T63xo2wQ4z9x3ORQ/about\"\r\n # url = \"https://www.youtube.com/channel/UCuXE1qQ4pqFhflKeQgcqlrg/about\"\r\n # url = input()\r\n\r\n try:\r\n # BuildURL\r\n\r\n relatedChannels = Ad.find(\"ytd-browse\",{'class':'style-scope ytd-page-manager'})\r\n relatedChannels = relatedChannels.find(\"ytd-two-column-browse-results-renderer\")\r\n relatedChannels = relatedChannels.find(\"div\",{\"id\":\"secondary\"})\r\n relatedChannels = relatedChannels.find(\"ytd-browse-secondary-contents-renderer\")\r\n relatedChannels = relatedChannels.find(\"div\",{\"id\":\"contents\"})\r\n except:\r\n print(\"Check internet connection while related\")\r\n return None\r\n\r\n linkFlag = 1\r\n while True:\r\n try:\r\n currChannels = relatedChannels.contents[linkFlag].find(\"div\",{\"id\":\"items\"})\r\n currChannels = currChannels.findAll(\"ytd-mini-channel-renderer\")\r\n # print(\"LOL\")\r\n for i in currChannels:\r\n i = str(i) # i is ytd-min-channel-renderer tag\r\n i = re.findall('href=\"(\\S+)\"',i)\r\n # i collects the channel sublink from href of tag in ytd-min-channel-renderer tag\r\n channelLink = \"https://www.youtube.com\" + i[0] + \"/about\" # channelLink is the whole link to channel\r\n channelList = channelList + [channelLink]\r\n linkFlag = linkFlag + 1\r\n # print(linkFlag)\r\n except:\r\n break\r\n return channelList\r\n\r\n\r\ndef getDescription(url,Ad):\r\n # url = \"https://www.youtube.com/channel/UCCTtSp0T63xo2wQ4z9x3ORQ/about\" \r\n try:\r\n #BuildURL\r\n\r\n description = Ad.find(\"ytd-browse\",{'class':'style-scope ytd-page-manager'})\r\n description = description.find(\"ytd-two-column-browse-results-renderer\")\r\n description = description.find(\"ytd-section-list-renderer\")\r\n description = description.find(\"div\",{'id':'contents'})\r\n description = description.find(\"ytd-item-section-renderer\")\r\n description = description.find(\"div\",{'id':'contents'})\r\n description = description.find(\"ytd-channel-about-metadata-renderer\")\r\n description = description.find(\"div\",{'id':'left-column'})\r\n description = description.find(\"div\",{'id':'description-container'})\r\n description = description.find(\"yt-formatted-string\",{'id':'description'})\r\n return str(Ad)\r\n except:\r\n print(\"Check internet connection while description\")\r\n return None\r\n\r\ndef getCountry(url,Ad):\r\n try:\r\n country = Ad.find(\"ytd-browse\",{'class':'style-scope ytd-page-manager'})\r\n country = country.find(\"ytd-two-column-browse-results-renderer\")\r\n country = country.find(\"ytd-section-list-renderer\")\r\n country = country.find(\"div\",{'id':'contents'})\r\n country = country.find(\"ytd-item-section-renderer\")\r\n country = country.find(\"div\",{'id':'contents'})\r\n country = country.find(\"ytd-channel-about-metadata-renderer\")\r\n country = country.find(\"div\",{'id':'left-column'})\r\n country = country.find(\"div\",{'id':'details-container'})\r\n country = country.find(\"table\",{'class':'style-scope ytd-channel-about-metadata-renderer'})\r\n country = country.find(\"tbody\",{'class':'style-scope ytd-channel-about-metadata-renderer'})\r\n country = country.findAll(\"tr\",{'class':'style-scope ytd-channel-about-metadata-renderer'})\r\n country = country[1].findAll(\"td\",{'class':'style-scope ytd-channel-about-metadata-renderer'})\r\n country = country[0].find(\"yt-formatted-string\",{'class':'style-scope ytd-channel-about-metadata-renderer'}).contents\r\n return str(country[0])\r\n except:\r\n return \"\"\r\n\r\ndef getSubscribers(url,Ad):\r\n try:\r\n subs = Ad.findAll(\"ytd-browse\",{'class':'style-scope ytd-page-manager'})\r\n subs = subs[0].find(\"div\",{'id':'header'})\r\n subs = subs.find(\"ytd-c4-tabbed-header-renderer\")\r\n subs = subs.find(\"app-header-layout\")\r\n subs = subs.find(\"div\",{'id':'wrapper'})\r\n subs = subs.find(\"app-header\",{'id':\"header\"})\r\n subs = subs.find(\"div\",{'id':'contentContainer'})\r\n subs = subs.find(\"div\",{'id':'channel-container'})\r\n subs = subs.find(\"div\",{'id':'channel-header'})\r\n subs = subs.find(\"div\",{'id':'channel-header-container'})\r\n subs = subs.find(\"div\",{'id':'inner-header-container'})\r\n subs = subs.find(\"yt-formatted-string\",{'id':'subscriber-count'}).contents\r\n subs = subs[0].split(' ')\r\n subs = subs[0].split(',')\r\n ans = \"\"\r\n for i in subs:\r\n ans = ans + str(i)\r\n return int(ans)\r\n except:\r\n return 0\r\n\r\ndef getName(url,Ad):\r\n try:\r\n name = Ad.findAll(\"ytd-browse\",{'class':'style-scope ytd-page-manager'})\r\n name = name[0].find(\"div\",{'id':'header'})\r\n name = name.find(\"ytd-c4-tabbed-header-renderer\")\r\n name = name.find(\"app-header-layout\")\r\n name = name.find(\"div\",{'id':'wrapper'})\r\n name = name.find(\"app-header\",{'id':\"header\"})\r\n name = name.find(\"div\",{'id':'contentContainer'})\r\n name = name.find(\"div\",{'id':'channel-container'})\r\n name = name.find(\"div\",{'id':'channel-header'})\r\n name = name.find(\"div\",{'id':'channel-header-container'})\r\n name = name.find(\"div\",{'id':'inner-header-container'})\r\n name = name.find(\"h1\",{'id':'channel-title-container'})\r\n name = name.find(\"span\",{'id':'channel-title'}).contents\r\n return str(name[0])\r\n except:\r\n return \" \"\r\n\r\n# check for mail an numbr regular expressions\r\ndef getRow(url,Ad):\r\n row = []\r\n name = str(getName(url,Ad))\r\n link = str(url)\r\n subs = int(getSubscribers(url,Ad))\r\n description = str(getDescription(url,Ad))\r\n mail = \" \"\r\n number = \" \"\r\n try:\r\n mail = re.findall('\\S+@\\S+',description)\r\n mail = str(mail[0])\r\n except:\r\n mail = \" \"\r\n try:\r\n number = re.findall(\"[0-9]\\S+\",description)\r\n i = 0\r\n for i in number:\r\n if len(i) >= 10:\r\n break\r\n number = str(i)\r\n except:\r\n number = \" \"\r\n\r\n # forming current row\r\n row.append(name)\r\n row.append(link)\r\n row.append(subs)\r\n row.append(mail)\r\n row.append(number)\r\n return row\r\n\r\ndef isPresent(channels,url):\r\n for i in channels:\r\n if i[1] == url:\r\n return False\r\n return True\r\n\r\ndef printChannel(url,channels):\r\n Ad = BuildURL(url)\r\n if Ad == None:\r\n print(\"Ad\")\r\n return None\r\n if getCountry(url,Ad) != \"India\":\r\n print(\"Coun\")\r\n return None\r\n if len(channels) >= numChannels:\r\n print(\"Reached\")\r\n return None\r\n \r\n channels.append(getRow(url,Ad)) # adding url to list\r\n list = getRelated(url,Ad) # getting related channels\r\n if list == None:\r\n print(\"Related\")\r\n return None\r\n for j in list:\r\n if isPresent(channels,str(j)): # Checking repitition\r\n printChannel(str(j),channels)\r\n\r\ndef buildCSV(list):\r\n csvList = open(\"urlList.csv\",'a',encoding='utf-8')\r\n for i in list:\r\n writer = csv.writer(csvList,delimiter=' ',lineterminator='\\r')\r\n writer.writerow(i)\r\n csvList.close()\r\n\r\n\r\n\r\n\r\nnumChannels = int(input(\"Enter number of channels you want to get : \"))\r\nurl = str(input(\"Enter URL : \"))\r\n#url = \"https://www.youtube.com/channel/UCCTtSp0T63xo2wQ4z9x3ORQ/about\"\r\n# https://www.youtube.com/channel/UCFda_3iggsKi_scQFbTIJPw/about Numchannels = 5 - error why?\r\n# https://www.youtube.com/channel/UCBnnsrvmuQ7tFdTL511dzBQ/about Numchannels = 5 - no error\r\n\r\nchannels = []\r\nprintChannel(url,channels)\r\ni = int(input(\"Continue to build csv press 1 : \"))\r\nif i == 1:\r\n buildCSV(channels)\r\n\r\nfor k in channels:\r\n print(k)\r\n", "repo_name": "6sr/Python", "sub_path": "YoutubeScraper/FormYoutuberList.py", "file_name": "FormYoutuberList.py", "file_ext": "py", "file_size_in_byte": 8731, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "selenium.webdriver.chrome.options.Options", "line_number": 9, "usage_type": "call"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 11, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 11, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 17, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 55, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 158, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 163, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 210, "usage_type": "call"}]} +{"seq_id": "12213466482", "text": "'''\nAuthor: fujiawei0724\nDate: 2022-06-07 11:01:56\nLastEditors: fujiawei0724\nLastEditTime: 2022-06-29 16:13:26\nDescription: mcts algorithm.\n'''\n\nimport sys\nsys.path.append('..')\nimport random\nimport cProfile\nimport _pickle as cPickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom collections import defaultdict\nfrom shapely.geometry import Polygon\n\nfrom subEnvironment import SubEnvironment, State\nfrom rl_behavior_planner.utils import *\n\nVEHICLE_INTENTION_SET = [VehicleIntention(lat_beh, lon_vel) \n for lat_beh in LateralBehavior \n for lon_vel in np.arange(-5.0, 5.0 + 1e-3, 1.0)]\n\n\n# A group of states in time order\nclass MacroState:\n moves_num = 11 * 3\n def __init__(self, states=None, lane_change_num=None, lane_info_with_speed=None, intention=None):\n self.states_ = states\n self.lane_change_num_ = lane_change_num\n self.lane_info_with_speed_ = lane_info_with_speed\n \n # Record behavior information\n self.intention_ = intention \n\n def reward(self):\n # TODO: add consideration of nonexistent lanes\n cost, is_collision, _, _, _ = MctsPolicyEvaluator.praise(self)\n if is_collision:\n return -1.0\n return 1.0 / cost\n \n def terminal(self):\n if self.states_[-1].terminal():\n return True\n return False\n\n # Generate random next state to construct the default policy\n def next_state(self, env, cur_intention):\n # Load data to environment and generate next state\n env.loadState(self.lane_info_with_speed_, self.states_[-1])\n next_state = env.simulateSingleStep(cur_intention)\n\n return next_state\n \n # Generate next macro state\n def next_macro_state(self, env):\n # Select intention randomly\n cur_intention = random.choice(VEHICLE_INTENTION_SET)\n \n # Calculate next state\n next_state = self.next_state(env, cur_intention)\n\n # Integrate ego macro state and the generated next state\n # TODO: check the logic about the copy of the current object (try to avoid the use of 'copy')\n next_macro_state = MacroState()\n next_macro_state.states_ = copy.deepcopy(self.states_)\n next_macro_state.states_.append(next_state)\n next_macro_state.lane_change_num_ = self.lane_change_num_\n next_macro_state.intention_ = cur_intention\n if cur_intention.lat_beh_ == LateralBehavior.LaneChangeLeft or cur_intention.lat_beh_ == LateralBehavior.LaneChangeRight:\n next_macro_state.lane_change_num_ += 1\n next_macro_state.lane_info_with_speed_ = self.lane_info_with_speed_\n\n return next_macro_state\n \n # Visualization lane situation and vehicles states sequence\n def visualization(self, ax):\n # Construct lane server\n center_lane = None\n left_lane = None\n right_lane = None\n left_lane_exist, right_lane_exist, center_left_distance, center_right_distance = self.lane_info_with_speed_[0], self.lane_info_with_speed_[1], self.lane_info_with_speed_[2], self.lane_info_with_speed_[3]\n \n # Initialize lane with the assumption that the lane has 500m to drive at least\n center_lane_start_point = PathPoint(0.0, 0.0)\n center_lane_end_point = PathPoint(500.0, 0.0)\n center_lane = Lane(center_lane_start_point, center_lane_end_point, LaneId.CenterLane)\n # center_lane_points_array = Visualization.transformPathPointsToArray(center_lane.path_points_)\n if left_lane_exist:\n left_lane_start_point = PathPoint(0.0, center_left_distance)\n left_lane_end_point = PathPoint(500.0, center_left_distance)\n left_lane = Lane(left_lane_start_point, left_lane_end_point, LaneId.LeftLane)\n # left_lane_points_array = Visualization.transformPathPointsToArray(left_lane.path_points_)\n if right_lane_exist:\n right_lane_start_point = PathPoint(0.0, -center_right_distance)\n right_lane_end_point = PathPoint(500.0, -center_right_distance)\n right_lane = Lane(right_lane_start_point, right_lane_end_point, LaneId.RightLane)\n # right_lane_points_array = Visualization.transformPathPointsToArray(right_lane.path_points_)\n\n # Construct lane server\n lanes = dict()\n lanes[center_lane.id_] = center_lane\n if left_lane_exist:\n lanes[left_lane.id_] = left_lane\n if right_lane_exist:\n lanes[right_lane.id_] = right_lane\n lane_server = LaneServer(lanes)\n\n # Visualization lanes\n if LaneId.CenterLane in lane_server.lanes_:\n center_lane = lane_server.lanes_[LaneId.CenterLane]\n center_lane_points_array = Visualization.transformPathPointsToArray(center_lane.path_points_)\n ax.plot(center_lane_points_array[:, 0], center_lane_points_array[:, 1], c='m', linewidth=1.0)\n ax.plot(center_lane.left_boundary_points_[:, 0], center_lane.left_boundary_points_[:, 1], c='black',\n ls='--', linewidth=1.0)\n ax.plot(center_lane.right_boundary_points_[:, 0], center_lane.right_boundary_points_[:, 1], c='black',\n ls='--', linewidth=1.0)\n if LaneId.LeftLane in lane_server.lanes_:\n left_lane = lane_server.lanes_[LaneId.LeftLane]\n left_lane_points_array = Visualization.transformPathPointsToArray(left_lane.path_points_)\n ax.plot(left_lane_points_array[:, 0], left_lane_points_array[:, 1], c='m', linewidth=1.0)\n ax.plot(left_lane.left_boundary_points_[:, 0], left_lane.left_boundary_points_[:, 1], c='black', ls='--',\n linewidth=1.0)\n ax.plot(left_lane.right_boundary_points_[:, 0], left_lane.right_boundary_points_[:, 1], c='black', ls='--',\n linewidth=1.0)\n if LaneId.RightLane in lane_server.lanes_:\n right_lane = lane_server.lanes_[LaneId.RightLane]\n right_lane_points_array = Visualization.transformPathPointsToArray(right_lane.path_points_)\n ax.plot(right_lane_points_array[:, 0], right_lane_points_array[:, 1], c='m', linewidth=1.0)\n ax.plot(right_lane.left_boundary_points_[:, 0], right_lane.left_boundary_points_[:, 1], c='black', ls='--',\n linewidth=1.0)\n ax.plot(right_lane.right_boundary_points_[:, 0], right_lane.right_boundary_points_[:, 1], c='black',\n ls='--', linewidth=1.0)\n \n\n # Transform to trajectories\n ego_veh_states = []\n sur_vehs_states = defaultdict(list)\n for state in self.states_:\n ego_veh_states.append(state.ego_vehicle_)\n for sur_veh_id, sur_veh in state.surround_vehicles_.items():\n sur_vehs_states[sur_veh_id].append(sur_veh)\n ego_traj = Trajectory(ego_veh_states)\n sur_trajs = dict()\n for sur_veh_id, sur_veh_states in sur_vehs_states.items():\n sur_trajs[sur_veh_id] = Trajectory(sur_veh_states)\n \n # Visualization trajectories\n traj_length = len(ego_traj.vehicle_states_)\n for i in range(0, traj_length):\n if i == 0:\n # For current position\n ego_vehicle_polygon = Polygon(ego_traj.vehicle_states_[i].rectangle_.vertex_)\n ax.plot(*ego_vehicle_polygon.exterior.xy, c='r')\n # ax.text(ego_vehicle.position_.x_, ego_vehicle.position_.y_, 'id: {}, v: {}'.format(ego_vehicle.id_, ego_vehicle.velocity_), size=10.0)\n # Traverse surround vehicle\n for sur_veh_id, sur_veh_tra in sur_trajs.items():\n sur_vehicle_polygon = Polygon(sur_veh_tra.vehicle_states_[i].rectangle_.vertex_)\n ax.plot(*sur_vehicle_polygon.exterior.xy, c='green')\n # ax.text(sur_veh_tra.vehicle_states_[i].position_.x_, sur_veh_tra.vehicle_states_[i].position_.y_, 'id: {}, v: {}'.format(sur_veh_id, sur_veh_tra.vehicle_states_[i].velocity_), size=10.0)\n\n else:\n # For predicted position\n # For current position\n ego_vehicle_polygon = Polygon(ego_traj.vehicle_states_[i].rectangle_.vertex_)\n ax.plot(*ego_vehicle_polygon.exterior.xy, c='r', ls='--')\n # ax.text(lane_keeping_ego_trajectory.vehicle_states_[i].position_.x_, lane_keeping_ego_trajectory.vehicle_states_[i].position_.y_, 'id: {}, v: {}, time stamp: {}'.format(ego_vehicle.id_, lane_keeping_ego_trajectory.vehicle_states_[i].velocity_, lane_keeping_ego_trajectory.vehicle_states_[i].time_stamp_), size=10.0)\n # Traverse surround vehicle\n for sur_veh_id, sur_veh_tra in sur_trajs.items():\n sur_vehicle_polygon = Polygon(sur_veh_tra.vehicle_states_[i].rectangle_.vertex_)\n ax.plot(*sur_vehicle_polygon.exterior.xy, c='green', ls='--')\n # ax.text(sur_veh_tra.vehicle_states_[i].position_.x_, sur_veh_tra.vehicle_states_[i].position_.y_, 'id: {}, v: {}, time stamp: {}'.format(sur_veh_id, sur_veh_tra.vehicle_states_[i].velocity_, sur_veh_tra.vehicle_states_[i].time_stamp_), size=10.0)\n\n\n \n \n\n\n\n \n\n# Node in the search tree\nclass Node:\n def __init__(self, macro_state, parent=None):\n self.visit_num_ = 1\n self.reward_ = 0.0\n self.macro_state_ = macro_state\n self.children_ = []\n self.parent_ = parent\n \n def add_child(self, child_macro_state):\n child = Node(child_macro_state, self)\n self.children_.append(child)\n \n def update(self, reward):\n self.reward_ += reward\n self.visit_num_ += 1\n \n def fully_expanded(self):\n # TODO: add domain knowledge here to limit the scale of the search tree\n if len(self.children_) == self.macro_state_.moves_num:\n return True\n return False\n \n def best_policy(self):\n best_score = -np.inf\n best_children = []\n for c in self.children_:\n score = c.reward_ / c.visit_num_\n if score == best_score:\n best_children.append(c)\n if score > best_score:\n best_children = [c]\n best_score = score\n if len(best_children) == 0:\n print('Fatal error!!!')\n return random.choice(best_children)\n \n# Generate reward for the states sequence\nclass MctsPolicyEvaluator(PolicyEvaluator):\n \n @classmethod\n def calculateMultiLaneChangeCost(cls, change_num):\n return change_num * 0.3\n\n @classmethod\n def praise(cls, macro_state):\n # Reconstruct data \n ego_states = []\n sur_states = defaultdict(list)\n for st in macro_state.states_:\n ego_states.append(st.ego_vehicle_)\n for sur_id, sur_veh in st.surround_vehicles_.items():\n sur_states[sur_id].append(sur_veh)\n ego_traj = Trajectory(ego_states)\n sur_trajs = dict()\n for s_id, s_states in sur_states.items():\n sur_trajs[s_id] = Trajectory(s_states)\n \n # Calculate cost\n safety_cost, is_collision = cls.calculateSafetyCost(ego_traj, sur_trajs, macro_state.lane_info_with_speed_[-1])\n lane_change_cost = cls.calculateMultiLaneChangeCost(macro_state.lane_info_with_speed_[-1])\n efficiency_cost = cls.calculateEfficiencyCost(ego_traj, macro_state.lane_info_with_speed_[-1])\n comfort_cost = cls.calculateComfortCost(ego_traj)\n\n # # DEBUG\n # print('Safety cost: {}'.format(safety_cost))\n # print('Lane change cost: {}'.format(lane_change_cost))\n # print('Efficiency cost: {}'.format(efficiency_cost))\n # print('Comfort cost: {}'.format(comfort_cost))\n # print('All cost: {}'.format(safety_cost + lane_change_cost + efficiency_cost + comfort_cost))\n # # END DEBUG\n\n return safety_cost + lane_change_cost + efficiency_cost + comfort_cost, is_collision, safety_cost, lane_change_cost, efficiency_cost\n \n# Training the tree policy\nclass TreePolicyTrainer:\n def __init__(self, round_limit, time_limit, scalar):\n self.round_limit_ = round_limit\n self.time_limit_ = time_limit\n self.scalar_ = scalar\n \n '''\n description: train the tree policy\n param {root} root node of the search tree\n return {root} the result of the training process\n ''' \n def train(self, root, env):\n for iter in range(self.round_limit_):\n print('-------------------Start No. {} training epoch-------------------'.format(iter))\n front = self.tree_policy(root, env)\n reward = self.default_policy(front.macro_state_, env)\n self.backup(front, reward)\n return root\n \n '''\n description: stretch a tree node\n param {node} start node, also the node manipulated \n return {node} the ternimal node in the branch of the start node\n ''' \n def tree_policy(self, node, env):\n while node.macro_state_.terminal() == False:\n if len(node.children_) == 0:\n return self.expand(node, env)\n elif random.uniform(0, 1) < 0.5:\n node = self.best_child(node)\n else:\n if node.fully_expanded() == False:\n return self.expand(node, env)\n else:\n node = self.best_child(node)\n return node\n \n def expand(self, node, env):\n tried_children = [c.macro_state_ for c in node.children_]\n next_macro_state = node.macro_state_.next_macro_state(env)\n while next_macro_state in tried_children and next_macro_state.terminal() == False:\n next_macro_state = node.macro_state_.next_macro_state(env)\n node.add_child(next_macro_state)\n return node.children_[-1]\n\n def best_child(self, node):\n best_score = -np.inf\n best_children = []\n for c in node.children_:\n exploit = c.reward_ / c.visit_num_\n explore = np.sqrt(2.0 * np.log(node.visit_num_) / float(c.visit_num_))\n score = exploit + self.scalar_ * explore\n if score == best_score:\n best_children.append(c)\n if score > best_score:\n best_children = [c]\n best_score = score\n if len(best_children) == 0:\n print('Fatal error!!!')\n return random.choice(best_children)\n\n def default_policy(self, macro_state, env):\n while macro_state.terminal() == False:\n macro_state = macro_state.next_macro_state(env)\n\n # # DEBUG\n # macro_state.states_[-1].ego_vehicle_.print()\n # # END DEBUG\n\n return macro_state.reward()\n\n def backup(self, node, reward):\n while node != None:\n node.visit_num_ += 1\n node.reward_ += reward\n node = node.parent_\n return \n \n \n\nif __name__ == '__main__':\n # Load environment data randomly\n random.seed(0)\n left_lane_exist = random.randint(0, 1)\n right_lane_exist = random.randint(0, 1)\n center_left_distance = random.uniform(3.0, 4.5)\n center_right_distance = random.uniform(3.0, 4.5)\n lane_info = [left_lane_exist, right_lane_exist, center_left_distance, center_right_distance]\n lane_speed_limit = random.uniform(10.0, 25.0)\n lane_info_with_speed = [left_lane_exist, right_lane_exist, center_left_distance, center_right_distance, lane_speed_limit]\n\n # Construct ego vehicle and surround vehicles randomly\n ego_vehicle = EgoInfoGenerator.generateOnce()\n surround_vehicles_generator = AgentGenerator(left_lane_exist, right_lane_exist, center_left_distance, center_right_distance)\n surround_vehicles = surround_vehicles_generator.generateAgents(random.randint(0, 10))\n random.seed()\n\n # Block the situation with a wrong initialization information\n while ego_vehicle.velocity_ > lane_speed_limit:\n print('Reset vehicle information')\n ego_vehicle = EgoInfoGenerator.generateOnce()\n\n # Construct environment\n env = SubEnvironment()\n\n # Construct trainer\n scalar = 1.0 / (2.0 * np.sqrt(2.0))\n mcts_trainer = TreePolicyTrainer(1000, None, scalar)\n\n # Initialize start node \n root = Node(MacroState([State(ego_vehicle, surround_vehicles, 0.0)], 0, lane_info_with_speed))\n mcts_trainer.train(root, env)\n\n # # Test running performance\n # cProfile.run('mcts_trainer.train(root, env)')\n\n # Output the result\n while len(root.children_) != 0:\n root = root.best_policy()\n root.macro_state_.intention_.print()\n root.macro_state_.intention_.print()\n\n # Visualization\n fig = plt.figure(0)\n ax = plt.axes()\n ax.axis('equal')\n root.macro_state_.visualization(ax)\n plt.show()\n\n \n ", "repo_name": "fujiawei0724/motion_planning_scripts", "sub_path": "mcts_planner/mcts.py", "file_name": "mcts.py", "file_ext": "py", "file_size_in_byte": 16835, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "20", "api": [{"api_name": "sys.path.append", "line_number": 10, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 24, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 61, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 141, "usage_type": "call"}, {"api_name": "shapely.geometry.Polygon", "line_number": 156, "usage_type": "call"}, {"api_name": "shapely.geometry.Polygon", "line_number": 161, "usage_type": "call"}, {"api_name": "shapely.geometry.Polygon", "line_number": 168, "usage_type": "call"}, {"api_name": "shapely.geometry.Polygon", "line_number": 173, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 209, "usage_type": "attribute"}, {"api_name": "random.choice", "line_number": 220, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 233, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 288, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 306, "usage_type": "attribute"}, {"api_name": "numpy.sqrt", "line_number": 310, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 310, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 319, "usage_type": "call"}, {"api_name": "random.seed", "line_number": 342, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 343, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 344, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 345, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 346, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 348, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 354, "usage_type": "call"}, {"api_name": "random.seed", "line_number": 355, "usage_type": "call"}, {"api_name": "subEnvironment.SubEnvironment", "line_number": 363, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 366, "usage_type": "call"}, {"api_name": "subEnvironment.State", "line_number": 370, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 383, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 383, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axes", "line_number": 384, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 384, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 387, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 387, "usage_type": "name"}]} +{"seq_id": "23484700980", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport getopt\nimport sys\n\nfrom PIL import Image\nimport numpy as np\nfrom transforms.DqKT import DqKT\n# from transforms_gpgpu.dqkt_gpgpu import DqktGPGPU\nfrom transforms.DAT import DAT\nfrom block_tools.BlockTools import BlockTools\nfrom qr_tools.MyQR62 import MyQR62\n\nfrom scipy import misc\nimport math\n\n\ndef binary2int(binary):\n # Devuelve el entero correspondiente a una lista de binarios\n n = len(binary)\n v = 0\n for i in range(n):\n v += (2**(n-i-1))*binary[i]\n return v\n\n\ndef get_dwt(chromosome):\n \"\"\"\n Devuelve la subbanda de la DWT a utilizar (0, 1, 2, 3) -> (LL, LH, HL, HH)\n \"\"\"\n return binary2int(chromosome[0:2])\n\n\ndef zigzag(n):\n indexorder = sorted(\n ((x, y) for x in range(n) for y in range(n)), key=lambda s: (s[0]+s[1], -s[1] if (s[0]+s[1]) % 2 else s[1]))\n return {index: n for n, index in enumerate(indexorder)}\n\n\ndef get_indice(m):\n zarray = zigzag(8)\n indice = []\n n = int(len(zarray) ** 0.5 + 0.5)\n for x in range(n):\n for y in range(n):\n if zarray[(x, y)] == m:\n indice.append(x)\n indice.append(y)\n return indice\n\n\ndef mypwlcm(dic, valores):\n '''\n dic: diccionario compuesto por la semila y el valor de p\n valores: lista de valores a tratar\n '''\n valores_finales = []\n cantidad_valores = len(valores)\n posiciones = orden(dic, cantidad_valores)\n # print 'Posiciones: ', posiciones\n posiciones_distintas = lista_valores_distintos(posiciones)\n # print 'Posiciones distintas: ', posiciones_distintas\n if len(posiciones_distintas) == len(posiciones):\n v = []\n for i in range(len(posiciones_distintas)):\n v.append(valores[i])\n return v\n if len(posiciones_distintas) == 1:\n return valores\n for i in range(len(posiciones_distintas)):\n valores_finales.append(valores[posiciones_distintas[i]])\n posiciones_faltantes = lista_valores_faltantes(\n posiciones_distintas, cantidad_valores)\n # print 'Faltantes: ', posiciones_faltantes\n if len(posiciones_faltantes) > 0:\n v = []\n for i in range(len(posiciones_faltantes)):\n v.append(valores[posiciones_faltantes[i]])\n valores_finales.extend(mypwlcm(dic, v))\n return valores_finales\n\n\ndef pwlcm(dic):\n # dic: diccionario compuesto por la semila y el valor de p\n if (dic['semilla'] >= 0) and (dic['semilla'] < dic['p']):\n x = dic['semilla'] / dic['p']\n elif (dic['semilla'] >= dic['p']) and (dic['semilla'] < 0.5):\n x = (dic['semilla'] - dic['p']) / (0.5 - dic['p'])\n elif (dic['semilla'] >= 0.5) and (dic['semilla'] < 1):\n dic['semilla'] = 1 - dic['semilla']\n x = pwlcm(dic)\n return x\n\n\ndef orden(dic, cant=40):\n lista = []\n for i in range(cant):\n if i != 0:\n dic_a = {}\n dic_a['semilla'] = temp\n dic_a['p'] = dic['p']\n temp = pwlcm(dic_a)\n else:\n temp = pwlcm(dic)\n lista.append(int(math.floor(math.fmod(temp * 10**14, cant))))\n return lista\n\n\ndef lista_valores_distintos(lista):\n lista_nueva = []\n for i in lista:\n if i not in lista_nueva:\n lista_nueva.append(i)\n return lista_nueva\n\n\ndef lista_valores_faltantes(posiciones_distintas, cantidad_valores):\n posiciones_faltantes = []\n for i in range(cantidad_valores):\n if i not in posiciones_distintas:\n posiciones_faltantes.append(i)\n return posiciones_faltantes\n\n\ndef mypwlcm_limit(dic, valores, limite):\n '''\n dic: diccionario compuesto por la semila y el valor de p\n valores: lista de valores a tratar\n '''\n valores_finales = []\n cantidad_valores = len(valores)\n posiciones = orden(dic, cantidad_valores)\n # print 'Posiciones: ', posiciones\n posiciones_distintas = lista_valores_distintos(posiciones)\n # print 'Posiciones distintas: ', posiciones_distintas\n if len(valores_finales) > limite:\n return valores_finales\n if len(posiciones_distintas) == len(posiciones):\n v = []\n for i in range(len(posiciones_distintas)):\n v.append(valores[i])\n return v\n if len(posiciones_distintas) == 1:\n return valores\n for i in range(len(posiciones_distintas)):\n valores_finales.append(valores[posiciones_distintas[i]])\n posiciones_faltantes = lista_valores_faltantes(\n posiciones_distintas, cantidad_valores)\n # print 'Faltantes: ', posiciones_faltantes\n if len(posiciones_faltantes) > 0:\n v = []\n for i in range(len(posiciones_faltantes)):\n v.append(valores[posiciones_faltantes[i]])\n valores_finales.extend(mypwlcm_limit(dic, v, limite))\n return valores_finales\n\n\ndef extract(watermarked_filename):\n delta = 128\n c = [1, 19]\n from image_tools.ImageTools import ImageTools\n dqkt = DqKT()\n myqr = MyQR62()\n dat = DAT()\n itools = ImageTools()\n\n watermarked_image = Image.open(watermarked_filename)\n watermarked_ycbcr_image = itools.rgb2ycbcr(watermarked_image)\n watermarked_array = watermarked_ycbcr_image[:, :, 0]\n bt_of_watermarked_image_without_noise = BlockTools(watermarked_array)\n\n extract = []\n\n len_of_watermark = 3844\n\n # Utilizar Bloques segun key\n dic = {'semilla': 0.00325687, 'p': 0.22415897}\n valores = []\n cantidad = bt_of_watermarked_image_without_noise.max_blocks()\n for i in range(cantidad):\n valores.append(i)\n v = mypwlcm_limit(dic, valores, len_of_watermark)\n\n for i in range(len_of_watermark):\n\n dqkt_block = dqkt.dqkt2(\n np.array(\n bt_of_watermarked_image_without_noise.get_block(v[i]+1),\n dtype=np.float32))\n\n negative = False\n if dqkt_block[get_indice(c[1])[0], get_indice(c[1])[1]] < 0:\n negative = True\n\n C1 = (2*delta*round(abs(dqkt_block[get_indice(c[1])[0], get_indice(c[1])[1]])/(2.0*delta)) + delta/2.0) - abs(dqkt_block[get_indice(c[1])[0], get_indice(c[1])[1]])\n C0 = (2*delta*round(abs(dqkt_block[get_indice(c[1])[0], get_indice(c[1])[1]])/(2.0*delta)) - delta/2.0) - abs(dqkt_block[get_indice(c[1])[0], get_indice(c[1])[1]])\n\n if negative:\n C1 *= -1\n C0 *= -1\n if C0 < C1:\n extract.append(0)\n else:\n extract.append(1)\n\n wh = int(math.sqrt(len_of_watermark))\n extract_image = Image.new(\"1\", (wh, wh), 255)\n array_extract_image = misc.fromimage(extract_image)\n\n for i in range(wh):\n for y in range(wh):\n if extract[wh*i+y] == 0:\n array_extract_image[i, y] = 0\n\n watermark_array_image = misc.toimage(array_extract_image)\n for i in range(10):\n watermark_array_image = dat.dat2(watermark_array_image)\n\n b = BlockTools(misc.fromimage(watermark_array_image), 2, 2)\n for m in range(1, b.max_blocks()+1):\n b.set_color(m)\n\n return misc.toimage(myqr.get_resconstructed(b.get()))\n\n\ndef main(args):\n input_filename = None\n watermark_filename = None\n output_filename = None\n\n # print('ARGV :', sys.argv[1:])\n\n options, remainder = getopt.getopt(\n sys.argv[1:], 'i:w:o:v',\n ['input', 'watermark', 'output='])\n # print('OPTIONS :', options)\n\n for opt, arg in options:\n if opt in ('-i', '--input'):\n input_filename = arg\n elif opt in ('-w', '--watermark'):\n watermark_filename = arg\n elif opt in ('-o', '--output'):\n output_filename = arg\n\n if input_filename:\n extract_watermark = extract(input_filename)\n extract_watermark.save(output_filename, quality=100)\n\n return 0\n\n\nif __name__ == '__main__':\n import sys\n sys.exit(main(sys.argv))\n", "repo_name": "eadomenech/benchmark", "sub_path": "watermarking/static/watermarking/methods_examples/my_extract.py", "file_name": "my_extract.py", "file_ext": "py", "file_size_in_byte": 7791, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "math.floor", "line_number": 105, "usage_type": "call"}, {"api_name": "math.fmod", "line_number": 105, "usage_type": "call"}, {"api_name": "transforms.DqKT.DqKT", "line_number": 162, "usage_type": "call"}, {"api_name": "qr_tools.MyQR62.MyQR62", "line_number": 163, "usage_type": "call"}, {"api_name": "transforms.DAT.DAT", "line_number": 164, "usage_type": "call"}, {"api_name": "image_tools.ImageTools.ImageTools", "line_number": 165, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 167, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 167, "usage_type": "name"}, {"api_name": "block_tools.BlockTools.BlockTools", "line_number": 170, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 187, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 189, "usage_type": "attribute"}, {"api_name": "math.sqrt", "line_number": 206, "usage_type": "call"}, {"api_name": "PIL.Image.new", "line_number": 207, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 207, "usage_type": "name"}, {"api_name": "scipy.misc.fromimage", "line_number": 208, "usage_type": "call"}, {"api_name": "scipy.misc", "line_number": 208, "usage_type": "name"}, {"api_name": "scipy.misc.toimage", "line_number": 215, "usage_type": "call"}, {"api_name": "scipy.misc", "line_number": 215, "usage_type": "name"}, {"api_name": "block_tools.BlockTools.BlockTools", "line_number": 219, "usage_type": "call"}, {"api_name": "scipy.misc.fromimage", "line_number": 219, "usage_type": "call"}, {"api_name": "scipy.misc", "line_number": 219, "usage_type": "name"}, {"api_name": "scipy.misc.toimage", "line_number": 223, "usage_type": "call"}, {"api_name": "scipy.misc", "line_number": 223, "usage_type": "name"}, {"api_name": "getopt.getopt", "line_number": 233, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 234, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 255, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 255, "usage_type": "attribute"}]} +{"seq_id": "13136919447", "text": "from datetime import datetime\n\nnow = datetime.now() # time object\n\nprint(\"now =\", now)\n\nfile1 = open('myfile.txt', 'w')\nL = [\"This is Delhi \\n\", \"This is Paris \\n\", \"This is London \\n\"]\ns = \"Hello\\n\"\n \n# Writing a string to file\nfile1.write(s)\n \n# Writing multiple strings\n# at a time\nfile1.writelines(L)\n \n# Closing file\nfile1.close()\n\nnow2 = datetime.now() # time object\n\nprint(\"now2 =\", now2)\nprint(\"difence\", now2-now)", "repo_name": "ermsharo/EP_Modelagem", "sub_path": "logs.py", "file_name": "logs.py", "file_ext": "py", "file_size_in_byte": 425, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "datetime.datetime.now", "line_number": 3, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 3, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 21, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 21, "usage_type": "name"}]} +{"seq_id": "29845512816", "text": "\"\"\"add name\n\nRevision ID: 32974039eb89\nRevises: f35e1eca70f7\nCreate Date: 2022-12-18 19:51:20.619707\n\n\"\"\"\nimport sqlalchemy as sa\n\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = \"32974039eb89\"\ndown_revision = \"f35e1eca70f7\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column(\"plugin_testapi_reviews\", sa.Column(\"name\", sa.Text(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column(\"plugin_testapi_reviews\", \"name\")\n # ### end Alembic commands ###\n", "repo_name": "bitcartcc/sample-plugin", "sub_path": "src/backend/testapi/versions/32974039eb89_add_name.py", "file_name": "32974039eb89_add_name.py", "file_ext": "py", "file_size_in_byte": 672, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "alembic.op.add_column", "line_number": 21, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 21, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 21, "usage_type": "call"}, {"api_name": "sqlalchemy.Text", "line_number": 21, "usage_type": "call"}, {"api_name": "alembic.op.drop_column", "line_number": 27, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 27, "usage_type": "name"}]} +{"seq_id": "6086577225", "text": "from __future__ import absolute_import, unicode_literals\n\nimport os\nimport json\nfrom django.conf import settings\nimport redis\nfrom celery import Celery\nfrom zipfile import ZipFile\nfrom io import BytesIO\nfrom urllib.request import Request, urlopen\nfrom datetime import date\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')\napp = Celery('backend')\napp.config_from_object('django.conf:settings', namespace='CELERY')\napp.conf.enable_utc = False\napp.autodiscover_tasks()\n\n\n@app.task(bind=True)\ndef wake_up(self):\n redis_instance = redis.StrictRedis(host=settings.REDIS_HOST,\n port=settings.REDIS_PORT,\n password=settings.REDIS_PASSWORD,\n db=0)\n today = str(date.today())\n todays_date = list(today.split('-'))\n todays_date.reverse()\n dt = \"\"\n for x in todays_date:\n dt += x[-2:]\n req = Request(f'https://www.bseindia.com/download/BhavCopy/Equity/EQ{dt}_CSV.zip', headers={'User-Agent': 'Mozilla/5.0'})\n with ZipFile(BytesIO(urlopen(req).read())) as my_zip_file:\n for contained_file in my_zip_file.namelist():\n for line in my_zip_file.open(contained_file).readlines():\n output = line.decode()\n lst_info = output.split(',')\n dct = {\n \"code\": lst_info[0],\n \"name\": lst_info[1],\n \"open\": lst_info[4],\n \"high\": lst_info[5],\n \"low\": lst_info[6],\n \"close\": lst_info[7]\n }\n json_dct = json.dumps(dct)\n redis_instance.set(lst_info[1], json_dct)\n\n\n\n\n\n\n\n\n\n\n# @app.task(bind=True)\n# def debug_task(self):\n# print('Request: {0!r}'.format(self.request))\n\n# @app.task(bind=True)\n# def send_import_summary(self):\n# print(\"Hello world\")", "repo_name": "9643kavinder/bse-stator-backend", "sub_path": "backend/celery.py", "file_name": "celery.py", "file_ext": "py", "file_size_in_byte": 1908, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "os.environ.setdefault", "line_number": 13, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 13, "usage_type": "attribute"}, {"api_name": "celery.Celery", "line_number": 14, "usage_type": "call"}, {"api_name": "redis.StrictRedis", "line_number": 22, "usage_type": "call"}, {"api_name": "django.conf.settings.REDIS_HOST", "line_number": 22, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 22, "usage_type": "name"}, {"api_name": "django.conf.settings.REDIS_PORT", "line_number": 23, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 23, "usage_type": "name"}, {"api_name": "django.conf.settings.REDIS_PASSWORD", "line_number": 24, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 24, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 26, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 26, "usage_type": "name"}, {"api_name": "urllib.request.Request", "line_number": 32, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 33, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 33, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 33, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 46, "usage_type": "call"}]} +{"seq_id": "15311865107", "text": "# Primeiro mini-projeto\nfrom tweepy.streaming import StreamListener \nfrom tweepy import OAuthHandler\nfrom tweepy import Stream\nfrom datetime import datetime\nimport json\nimport os\n\n# Consumer Key\nconsumer_key = os.environ['tweeter_api_key']\n\n# Consumer Secret\nconsumer_secret = os.environ['tweeter_api_secret']\n\n# Access Token\naccess_token = os.environ['tweeter_token']\n\n# Token Secret\naccess_token_secret = os.environ['tweeter_token_secret']\n\n# Criando a autenticação\nauth = OAuthHandler(consumer_key, consumer_secret)\n\nauth.set_access_token(access_token, access_token_secret)\n\n# Classe para capturar stream de dados do tweeter\nclass MyListener(StreamListener):\n def on_data(self, dados):\n tweet = json.loads(dados)\n created_at = tweet['created_at']\n id_str = tweet['id_str']\n text = tweet['text']\n obj = {'created_at':created_at, 'id_str':id_str, 'text':text}\n tweetind = col.insertone(obj).inserted_id\n print(obj)\n return True\n\n# Criando o objeto mylistener\nmy_listener = MyListener()\n\nmy_stream = Stream(auth, listener = MyListener)", "repo_name": "EndriwMichel/estudoPython", "sub_path": "PythonDsa/cap6/mini_projeto.py", "file_name": "mini_projeto.py", "file_ext": "py", "file_size_in_byte": 1096, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "os.environ", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 13, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 19, "usage_type": "attribute"}, {"api_name": "tweepy.OAuthHandler", "line_number": 22, "usage_type": "call"}, {"api_name": "tweepy.streaming.StreamListener", "line_number": 27, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 29, "usage_type": "call"}, {"api_name": "tweepy.Stream", "line_number": 41, "usage_type": "call"}]} +{"seq_id": "12475773932", "text": "# coding=UTF-8\r\nimport requests\r\n\r\n#将网页转化成列表,\r\nurl = 'http://www.****.com/'\r\nheader = {'User-Agent': '***********'}\r\nresponse = requests.get(url,headers=header).text\r\n#切割字符串,转列表\r\na = response.split('\\n')\r\nz = []\r\n#for 循环读取每一个字符串,删除其中的\\n\\t\\d和空格,\r\nfor i in a:\r\n responses = i.strip()\r\n #组成新的列表\r\n z.append(responses)\r\n#去除列表中的None和空字符串\r\nc = list(filter(None, z))\r\nprint(c)\r\n\r\n#这是对比两个网页的不同之处\r\na = ['', '']\r\nb = ['a', '']\r\naa = set(a)\r\nbb = set(b)\r\na_b = bb - aa\r\nprint(str(a_b))\r\n", "repo_name": "miaoyongsen/look-here-now-", "sub_path": "网页转列表-对比两个网页不同之处.py", "file_name": "网页转列表-对比两个网页不同之处.py", "file_ext": "py", "file_size_in_byte": 776, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "requests.get", "line_number": 7, "usage_type": "call"}]} +{"seq_id": "2884177946", "text": "import os\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom api.settings import PROJECT_ROOT\nfrom api.util.SentimentData import SentimentData\nimport pandas as pd\nfrom api.serialziers import Dictionary, DictionarySerializer\nimport pickle\nfrom rest_framework import serializers\n\n\n@api_view(['GET'])\ndef get_sentiment_analysis(request):\n ticker = request.GET.get('ticker', '')\n print(request.data)\n with open(os.path.join(PROJECT_ROOT + '/FinBert.pkl'), 'rb') as f:\n finbert = pickle.load(f)\n hot_posts = SentimentData.get_raddit_data(ticker)\n hot_tweets = SentimentData.get_stock_twit_data(ticker)\n data = []\n analysis = 0\n\n for tweet in hot_tweets:\n if len(tweet['body']) == 0 or len(tweet['body']) > 200:\n continue\n result = finbert(tweet['body'])\n\n score = calculateScore(result[0][\"score\"], result[0]['label'])\n analysis = analysis + score\n data.append({\n \"analysis\": score,\n \"label\": result[0]['label'],\n \"paragraph\": tweet['body'],\n \"name\": tweet['user']['name'],\n \"avatar_url\": tweet['user']['avatar_url'],\n \"like_count\": tweet['user']['like_count'],\n \"username\": tweet['user']['username'],\n \"followers\": tweet['user']['followers'],\n \"type\": \"stock_tweet\"\n })\n\n for post in hot_posts:\n if len(post.title) == 0 or len(post.title) > 3000:\n continue\n result = finbert(post.title)\n score = calculateScore(result[0][\"score\"], result[0]['label'])\n analysis = analysis + score\n data.append({\n \"analysis\": score,\n \"label\": result[0]['label'],\n \"title\": post.title,\n \"paragraph\": post.selftext,\n \"url\": post.url,\n \"likes\": post.likes,\n # \"subreddit\": post.subreddit,\n \"ups\": post.ups,\n \"subreddit_subscribers\": post.subreddit_subscribers,\n \"downs\": post.downs,\n \"vote\": post.ups-post.downs,\n \"type\": \"reddit\",\n })\n # analysis = analysis/\n\n analysis = analysis / (len(data))\n # GenericSzl = getGenericSerializer(model)\n dictionary = Dictionary({\n \"complete_analysis\": analysis,\n \"data\": data\n })\n return Response(DictionarySerializer(dictionary).data)\n\n\ndef calculateScore(score, label):\n value = 50\n # score = score/100\n if label == 'neutral':\n if score < 0.6:\n value = value - 10 * score\n else:\n value = value + 10 * score\n elif label == 'positive':\n value = value + 30 * score\n elif label == 'negative':\n value = value - 30 * score\n\n return value\n# result = finbert(analysis_text)\n# return Response(analysis)\n\n# def get_queryset(self):\n# model = self.kwargs.get('model')\n# return getattr(models, model).objects.all()\n# def getGenericSerializer(model_arg):\n# class GenericSerializer(serializers.ModelSerializer):\n# class Meta:\n# model = model_arg\n# fields = '__all__'\n#\n# return GenericSerializer\n\n# finbert = pickle.load(open(os.path.join(PROJECT_ROOT+'/FinBert.pkl')))\n", "repo_name": "hurrairaa/stock-analysis", "sub_path": "api/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 3430, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "os.path.join", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path", "line_number": 16, "usage_type": "attribute"}, {"api_name": "api.settings.PROJECT_ROOT", "line_number": 16, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 17, "usage_type": "call"}, {"api_name": "api.util.SentimentData.SentimentData.get_raddit_data", "line_number": 18, "usage_type": "call"}, {"api_name": "api.util.SentimentData.SentimentData", "line_number": 18, "usage_type": "name"}, {"api_name": "api.util.SentimentData.SentimentData.get_stock_twit_data", "line_number": 19, "usage_type": "call"}, {"api_name": "api.util.SentimentData.SentimentData", "line_number": 19, "usage_type": "name"}, {"api_name": "api.serialziers.Dictionary", "line_number": 66, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 70, "usage_type": "call"}, {"api_name": "api.serialziers.DictionarySerializer", "line_number": 70, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 12, "usage_type": "call"}]} +{"seq_id": "5634493262", "text": "# pip install opencv-python\n# pip install numpy\n# pip install torch\n# pip install transformers\n# pip install pillow\n\nimport cv2\nimport os\nimport numpy as np\nimport time\nfrom transformers import DetrFeatureExtractor, DetrForObjectDetection, pipeline, \\\n YolosFeatureExtractor, YolosForObjectDetection\nfrom PIL import Image, ImageDraw\n\n\n\ndef get_metadata(file_path):\n \"\"\"\n This function outputs the metadata of the input video file.\n\n :param file_path: Path to the input video file.\n :return: video_fps, total_frames, frames_height, frames_width\n \"\"\"\n\n # read video from file\n recording = cv2.VideoCapture(file_path)\n\n # Read metadata of the video\n video_fps = recording.get(cv2.CAP_PROP_FPS)\n total_frames = int(recording.get(cv2.CAP_PROP_FRAME_COUNT))\n frames_height = int(recording.get(cv2.CAP_PROP_FRAME_HEIGHT))\n frames_width = int(recording.get(cv2.CAP_PROP_FRAME_WIDTH))\n\n print(f\"Frame per second: {video_fps} \\nTotal Frames: {total_frames} \\nHeight: {frames_height} \\nWidth: {frames_width}\")\n return video_fps, total_frames, frames_height, frames_width\n\n\ndef process_frames(file_path, output_file_path):\n \"\"\"\n This function will take an input video and run every fram through the DETR-resnet-50 model to detect abjects in the frames.\n All objectes will be marked with a box and all frames will be put back together to the output video.\n\n :param file_path: Path to the input recording file\n :param output_file_path: Path and name of the output file\n :return: Returns the input video with boxes around the detected objects\n \"\"\"\n\n # initialize variables\n count = 0 # count to ensure all frames have been processed\n list_frames = [] # list of all processed frames\n recording = cv2.VideoCapture(file_path) # reading the input video with cv2\n\n # extract video metadata\n video_fps = recording.get(cv2.CAP_PROP_FPS) # check fps of input video\n total_frames = int(recording.get(cv2.CAP_PROP_FRAME_COUNT)) # count total frames of input video\n frames_height = int(recording.get(cv2.CAP_PROP_FRAME_HEIGHT)) # check pixel height of input video frame\n frames_width = int(recording.get(cv2.CAP_PROP_FRAME_WIDTH)) # check pixel width of input video frame\n codec = cv2.VideoWriter.fourcc(*'mp4v') # define format of output video\n\n # define the video output format and the values to resize the frames\n output_frames_height = 1080\n output_frames_width = 1920\n video_writer = cv2.VideoWriter(output_file_path, codec, video_fps, (output_frames_width, output_frames_height))\n\n # Initialize detr-resnet-50 model\n ##feature_extractor = DetrFeatureExtractor.from_pretrained(\"facebook/detr-resnet-50\") # Taken from HuggingFace\n ##model = DetrForObjectDetection.from_pretrained(\"facebook/detr-resnet-50\") # Taken from HuggingFace\n\n # Initialize Yolos-tiny model\n feature_extractor = YolosFeatureExtractor.from_pretrained('hustvl/yolos-tiny')\n model = YolosForObjectDetection.from_pretrained('hustvl/yolos-tiny')\n\n # create the object detection pipeline\n object_detection_pipe = pipeline(\"object-detection\",\n model=model,\n feature_extractor=feature_extractor)\n\n while count != 50:\n\n\n\n # Read video and retrieve individual frames\n ret, frame = recording.read()\n\n if frame is None:\n continue\n\n # Resize image for faster processing\n resizeFrame = cv2.resize(frame, (output_frames_width, output_frames_height))\n\n # Convert np array to PIL image - pipeline only works with PIL images\n pilFrame = Image.fromarray(np.uint8(resizeFrame))\n\n start = time.perf_counter()\n\n # Detect all objects in the frame\n results = object_detection_pipe(pilFrame)\n\n end = time.perf_counter()\n\n ms = (end-start) * 10**6\n seconds = ms / (10**6)\n print(f\"Elapsed {seconds:.03f} secs.\")\n\n # Add boxes and description of boxes to image\n im1 = ImageDraw.Draw(pilFrame)\n for result in results:\n box = result['box']\n xmin, xmax, ymin, ymax = box['xmin'], box['xmax'], box['ymin'], box['ymax']\n label = result['label']\n prob = result['score']\n shape = [xmin, ymin, xmax, ymax]\n text = f'{label}: {prob:0.2f}'\n if label == \"person\":\n im1.rectangle(shape, outline=\"red\", width=3)\n im1.text((xmin,ymax), text, fill=\"black\")\n elif label == \"sports ball\":\n im1.rectangle(shape, outline=\"blue\", width=3)\n im1.text((xmin, ymax), text, fill=\"black\")\n else:\n continue\n\n # Convert PIL image back to numpy array\n pilFrame = np.array(pilFrame)\n\n # Write the frame to the output video\n video_writer.write(pilFrame)\n\n # Print for every 50 frames processed\n if (count % 50 == 0):\n print('Processed ', count, ' frames')\n list_frames.append(frame)\n if len(list_frames) == int(total_frames):\n break\n\n # Increase count for every processed frame\n count += 1\n\n # Release to close all the resources that we have opened for reading and writing the video\n recording.release()\n video_writer.release()\n\n cv2.destroyAllWindows()\n\n\n# Define the input and output video location\ndir = ('/Users/christophmeier/Code_MastersThesis/AttackHeigtTracker/inputVideo')\nfile = os.listdir(dir)[0]\npath = str(dir) + '/' + str(file)\n\noutputDir = '/Users/christophmeier/Code_MastersThesis/AttackHeigtTracker/'\noutputFileName = 'processedVideo'\noutputFileType = 'mp4'\noutputFile = outputDir + outputFileName + '.' + outputFileType\n\n# check metadata\nget_metadata(path)\n\n# process every frame\nprocess_frames(path, outputFile)\n\n", "repo_name": "chrisP-cpmr/Object_Detection_BeachVolleyball", "sub_path": "AttackHeigtTracker/readRecording.py", "file_name": "readRecording.py", "file_ext": "py", "file_size_in_byte": 5975, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "cv2.VideoCapture", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.CAP_PROP_FPS", "line_number": 29, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FRAME_COUNT", "line_number": 30, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FRAME_HEIGHT", "line_number": 31, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FRAME_WIDTH", "line_number": 32, "usage_type": "attribute"}, {"api_name": "cv2.VideoCapture", "line_number": 51, "usage_type": "call"}, {"api_name": "cv2.CAP_PROP_FPS", "line_number": 54, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FRAME_COUNT", "line_number": 55, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FRAME_HEIGHT", "line_number": 56, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FRAME_WIDTH", "line_number": 57, "usage_type": "attribute"}, {"api_name": "cv2.VideoWriter.fourcc", "line_number": 58, "usage_type": "call"}, {"api_name": "cv2.VideoWriter", "line_number": 58, "usage_type": "attribute"}, {"api_name": "cv2.VideoWriter", "line_number": 63, "usage_type": "call"}, {"api_name": "transformers.YolosFeatureExtractor.from_pretrained", "line_number": 70, "usage_type": "call"}, {"api_name": "transformers.YolosFeatureExtractor", "line_number": 70, "usage_type": "name"}, {"api_name": "transformers.YolosForObjectDetection.from_pretrained", "line_number": 71, "usage_type": "call"}, {"api_name": "transformers.YolosForObjectDetection", "line_number": 71, "usage_type": "name"}, {"api_name": "transformers.pipeline", "line_number": 74, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 89, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 92, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 92, "usage_type": "name"}, {"api_name": "numpy.uint8", "line_number": 92, "usage_type": "call"}, {"api_name": "time.perf_counter", "line_number": 94, "usage_type": "call"}, {"api_name": "time.perf_counter", "line_number": 99, "usage_type": "call"}, {"api_name": "PIL.ImageDraw.Draw", "line_number": 106, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 106, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 124, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 143, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 148, "usage_type": "call"}]} +{"seq_id": "21910889579", "text": "# coding: utf-8\n\nimport six\n\nfrom huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization\n\n\nclass ResourceInstanceReqBody:\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n sensitive_list = []\n\n openapi_types = {\n 'without_any_tag': 'bool',\n 'tags': 'list[TagsDTO]',\n 'matches': 'list[Match]'\n }\n\n attribute_map = {\n 'without_any_tag': 'without_any_tag',\n 'tags': 'tags',\n 'matches': 'matches'\n }\n\n def __init__(self, without_any_tag=None, tags=None, matches=None):\n \"\"\"ResourceInstanceReqBody\n\n The model defined in huaweicloud sdk\n\n :param without_any_tag: 不包含任意一个标签,该字段为true时查询所有不带标签的资源。\n :type without_any_tag: bool\n :param tags: 包含标签,最多包含10个key,每个key下面的value最多10个,结构体不能缺失,key不能为空或者空字符串。Key不能重复,同一个key中values不能重复。返回包含所有标签的资源列表,key之间是与的关系,key-value结构中value是或的关系。无tag过滤条件时返回全量数据。\n :type tags: list[:class:`huaweicloudsdkorganizations.v1.TagsDTO`]\n :param matches: 要绑定到新创建的帐号的标签列表。\n :type matches: list[:class:`huaweicloudsdkorganizations.v1.Match`]\n \"\"\"\n \n \n\n self._without_any_tag = None\n self._tags = None\n self._matches = None\n self.discriminator = None\n\n if without_any_tag is not None:\n self.without_any_tag = without_any_tag\n if tags is not None:\n self.tags = tags\n if matches is not None:\n self.matches = matches\n\n @property\n def without_any_tag(self):\n \"\"\"Gets the without_any_tag of this ResourceInstanceReqBody.\n\n 不包含任意一个标签,该字段为true时查询所有不带标签的资源。\n\n :return: The without_any_tag of this ResourceInstanceReqBody.\n :rtype: bool\n \"\"\"\n return self._without_any_tag\n\n @without_any_tag.setter\n def without_any_tag(self, without_any_tag):\n \"\"\"Sets the without_any_tag of this ResourceInstanceReqBody.\n\n 不包含任意一个标签,该字段为true时查询所有不带标签的资源。\n\n :param without_any_tag: The without_any_tag of this ResourceInstanceReqBody.\n :type without_any_tag: bool\n \"\"\"\n self._without_any_tag = without_any_tag\n\n @property\n def tags(self):\n \"\"\"Gets the tags of this ResourceInstanceReqBody.\n\n 包含标签,最多包含10个key,每个key下面的value最多10个,结构体不能缺失,key不能为空或者空字符串。Key不能重复,同一个key中values不能重复。返回包含所有标签的资源列表,key之间是与的关系,key-value结构中value是或的关系。无tag过滤条件时返回全量数据。\n\n :return: The tags of this ResourceInstanceReqBody.\n :rtype: list[:class:`huaweicloudsdkorganizations.v1.TagsDTO`]\n \"\"\"\n return self._tags\n\n @tags.setter\n def tags(self, tags):\n \"\"\"Sets the tags of this ResourceInstanceReqBody.\n\n 包含标签,最多包含10个key,每个key下面的value最多10个,结构体不能缺失,key不能为空或者空字符串。Key不能重复,同一个key中values不能重复。返回包含所有标签的资源列表,key之间是与的关系,key-value结构中value是或的关系。无tag过滤条件时返回全量数据。\n\n :param tags: The tags of this ResourceInstanceReqBody.\n :type tags: list[:class:`huaweicloudsdkorganizations.v1.TagsDTO`]\n \"\"\"\n self._tags = tags\n\n @property\n def matches(self):\n \"\"\"Gets the matches of this ResourceInstanceReqBody.\n\n 要绑定到新创建的帐号的标签列表。\n\n :return: The matches of this ResourceInstanceReqBody.\n :rtype: list[:class:`huaweicloudsdkorganizations.v1.Match`]\n \"\"\"\n return self._matches\n\n @matches.setter\n def matches(self, matches):\n \"\"\"Sets the matches of this ResourceInstanceReqBody.\n\n 要绑定到新创建的帐号的标签列表。\n\n :param matches: The matches of this ResourceInstanceReqBody.\n :type matches: list[:class:`huaweicloudsdkorganizations.v1.Match`]\n \"\"\"\n self._matches = matches\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n if attr in self.sensitive_list:\n result[attr] = \"****\"\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n import simplejson as json\n if six.PY2:\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)\n\n def __repr__(self):\n \"\"\"For `print`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ResourceInstanceReqBody):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n", "repo_name": "huaweicloud/huaweicloud-sdk-python-v3", "sub_path": "huaweicloud-sdk-organizations/huaweicloudsdkorganizations/v1/model/resource_instance_req_body.py", "file_name": "resource_instance_req_body.py", "file_ext": "py", "file_size_in_byte": 6328, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 104, "dataset": "github-code", "pt": "20", "api": [{"api_name": "six.iteritems", "line_number": 128, "usage_type": "call"}, {"api_name": "six.PY2", "line_number": 154, "usage_type": "attribute"}, {"api_name": "sys.setdefaultencoding", "line_number": 157, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 158, "usage_type": "call"}, {"api_name": "huaweicloudsdkcore.utils.http_utils.sanitize_for_serialization", "line_number": 158, "usage_type": "call"}]} +{"seq_id": "25763712056", "text": "\nfrom odoo import fields, models, api\nfrom datetime import datetime\nfrom odoo.exceptions import AccessError, UserError, ValidationError\nfrom odoo.tools.translate import _\n\n\n\nclass HrLeave(models.Model):\n _inherit = 'hr.leave'\n # delegations_id = fields.Many2one('employee.delegations')\n delegations_employee_id = fields.Many2one('hr.employee', 'delegations')\n \n def action_approve(self):\n\n # group_e.write({'users': [(1, self.env.user.id)]})\n\n super().action_approve()\n\n for rec in self :\n is_leave_user_test = rec.user_has_groups('hr_holidays.group_hr_holidays_user')\n if is_leave_user_test:\n print(is_leave_user_test, '//////////////////////////////////////////////////////////////////////')\n\n group_e = self.env.ref('hr_holidays.group_hr_holidays_user', False)\n group_e.write({'users': [(3, self.env.user.employee_id.id)]})\n group_e.write({'users': [(4, rec.delegations_employee_id.id)]})\n delegations_info = {'employee_id':self.env.user.employee_id.id,'delegated_employee_id':rec.delegations_employee_id.id,\n 'date_from':rec.date_from,'date_to':rec.date_to,'state':'draft','name':'test','date':datetime.now(),}\n filed = self.env['employee.delegations'].create(delegations_info)\n filed.onchange_method()\n filed.access_granted()\n notification_ids = [((0, 0, {\n 'res_partner_id': rec.delegations_employee_id.id,\n 'notification_type': 'inbox'}))]\n # user_id = self.env.user.id\n # message = (\"You have a assigned a delegations from %s from %s to %s\") % (self.env.user.employee_id.name,rec.date_from,rec.date_to)\n # channel = self.env['mail.channel'].channel_get([rec.delegations_employee_id.id])\n # channel_id = self.env['mail.channel'].browse(channel[\"id\"])\n # channel_id.message_post(author_id=user_id,\n # body=(message),\n # message_type='notification',\n # subtype_xmlid=\"mail.mt_comment\",\n # notification_ids=notification_ids,\n # partner_ids=[rec.delegations_employee_id.id],\n # notify_by_email=False,\n # )\n\n\n\n def _check_double_validation_rules(self, employees, state):\n super(HrLeave, self)._check_double_validation_rules(employees,state)\n print(\"here/************************************************************************************/\")\n is_leave_user = self.user_has_groups('hr_holidays.group_hr_holidays_user')\n if state == 'validate1':\n # print(is_leave_user , \"/*********************************************************************/\")\n employees2 = [employee.leave_manager_id.id for employee in employees ]#employees.filtered(lambda employee: employee.leave_manager_id != self.env.user)\n print(employees2, '/________________________________________-------------__========000____-----')\n #\n # if employees2 :\n # if self.env.user in employees:\n # raise AccessError(_('You cannot first approve a time off for %s, because you are not his time off manager', employees[0].name))\n # elif state == 'validate' and not is_leave_user:\n # print(\"test +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n\n\n", "repo_name": "sideeg/nidlp", "sub_path": "employee_delegations/models/hr_leave.py", "file_name": "hr_leave.py", "file_ext": "py", "file_size_in_byte": 3609, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "odoo.models.Model", "line_number": 9, "usage_type": "attribute"}, {"api_name": "odoo.models", "line_number": 9, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 12, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 12, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 29, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 29, "usage_type": "name"}]} +{"seq_id": "21284310742", "text": "from decimal import Decimal\nfrom django.http import HttpResponseRedirect\nfrom django.conf import settings\nfrom django.shortcuts import redirect, render, get_object_or_404\nfrom django.views.decorators.http import require_POST\nfrom movie_store.models import Movie\nfrom movie_store.forms import BasketAddProductForm \n\nclass Basket(object):\n \n def __init__(self, request):\n self.session = request.session\n basket = self.session.get(settings.BASKET_SESSION_ID)\n if not basket:\n # save an empty basket in the session\n basket = self.session[settings.BASKET_SESSION_ID] = {}\n self.basket = basket\n\n def __iter__(self):\n print(f'basket: { self.basket }')\n movie_ids = self.basket.keys()\n movies = Movie.objects.filter(id__in=movie_ids)\n\n basket = self.basket.copy()\n for movie in movies:\n basket[str(movie.id)]['movie'] = movie\n basket[str(movie.id)]['movie_id'] = movie.id\n\n for item in basket.values():\n item['price'] = Decimal(item['price'])\n item['total_price'] = item['price'] * item['quantity']\n yield item\n\n def __len__(self):\n return sum(item['quantity'] for item in self.basket.values())\n\n def add(self, movie, quantity=1, override_quantity=False):\n movie_id = str(movie.id)\n if movie_id not in self.basket:\n self.basket[movie_id] = {'quantity': 0,\n 'price': str(movie.price)}\n if override_quantity:\n self.basket[movie_id]['quantity'] = quantity\n else:\n self.basket[movie_id]['quantity'] += quantity\n self.save()\n\n def save(self):\n self.session.modified = True\n\n def remove(self, movie):\n movie_id = str(movie.id)\n if movie_id in self.basket:\n del self.basket[movie_id]\n self.save()\n\n def clear(self):\n del self.session[settings.BASKET_SESSION_ID]\n self.save()\n\n def get_total_price(self):\n return sum(Decimal(item['price']) * item['quantity'] for item in self.basket.values())\n\n\n@require_POST\ndef basket_add(request, movie_id):\n basket = Basket(request)\n movie = get_object_or_404(Movie, id=movie_id)\n form = BasketAddProductForm(request.POST)\n if form.is_valid():\n cd = form.cleaned_data\n basket.add(movie=movie,\n quantity=cd['quantity'],\n override_quantity=cd['override'])\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\n@require_POST\ndef basket_remove(request, movie_id):\n basket = Basket(request)\n movie = get_object_or_404(Movie, id=movie_id)\n basket.remove(movie)\n return redirect('basket_detail')\n\ndef basket_detail(request):\n basket = Basket(request)\n total = len(basket)\n for item in basket:\n item['update_quantity_form'] = BasketAddProductForm(initial={'quantity': item['quantity'],\n 'override': True})\n return render(request, 'movie_store/basket.html', {'basket': basket, 'total':total})\n", "repo_name": "topherlee/movie-store", "sub_path": "movie_store/views/basket.py", "file_name": "basket.py", "file_ext": "py", "file_size_in_byte": 3124, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "django.conf.settings.BASKET_SESSION_ID", "line_number": 13, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 13, "usage_type": "name"}, {"api_name": "django.conf.settings.BASKET_SESSION_ID", "line_number": 16, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 16, "usage_type": "name"}, {"api_name": "movie_store.models.Movie.objects.filter", "line_number": 22, "usage_type": "call"}, {"api_name": "movie_store.models.Movie.objects", "line_number": 22, "usage_type": "attribute"}, {"api_name": "movie_store.models.Movie", "line_number": 22, "usage_type": "name"}, {"api_name": "decimal.Decimal", "line_number": 30, "usage_type": "call"}, {"api_name": "django.conf.settings.BASKET_SESSION_ID", "line_number": 58, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 58, "usage_type": "name"}, {"api_name": "decimal.Decimal", "line_number": 62, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 68, "usage_type": "call"}, {"api_name": "movie_store.models.Movie", "line_number": 68, "usage_type": "argument"}, {"api_name": "movie_store.forms.BasketAddProductForm", "line_number": 69, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 75, "usage_type": "call"}, {"api_name": "django.views.decorators.http.require_POST", "line_number": 65, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 80, "usage_type": "call"}, {"api_name": "movie_store.models.Movie", "line_number": 80, "usage_type": "argument"}, {"api_name": "django.shortcuts.redirect", "line_number": 82, "usage_type": "call"}, {"api_name": "django.views.decorators.http.require_POST", "line_number": 77, "usage_type": "name"}, {"api_name": "movie_store.forms.BasketAddProductForm", "line_number": 88, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 90, "usage_type": "call"}]} +{"seq_id": "1592649900", "text": "from django.shortcuts import render\nfrom django.http import JsonResponse, HttpResponse\nfrom rest_framework.decorators import api_view, renderer_classes\nfrom rest_framework.renderers import JSONRenderer\nfrom .serializers import ForecastSerializer\nfrom .predictor import get_forecast\nimport os\nfrom django.conf import settings\nimport pandas as pd\n\ndef index(request):\n return render(request, 'index.html')\n\ndata_path = os.path.join(settings.BASE_DIR, 'media', 'Cleaned_Balance_Stay.xlsx')\ndata = pd.read_excel(data_path)\n\n\n\n@api_view(['GET'])\n@renderer_classes([JSONRenderer])\ndef balance_forecast_view(request):\n profits_image, _, _ = get_forecast(plot_graphs=True) # Получаем изображение для прибыли\n\n if profits_image:\n response = HttpResponse(content_type=\"image/png\")\n response.write(profits_image.getvalue()) # Get the Profits forecast image\n return response\n\n return JsonResponse({\"message\": \"No graph generated.\"})\n\n@api_view(['GET'])\n@renderer_classes([JSONRenderer])\ndef profits_forecast_view(request):\n _, _, income_spends_image = get_forecast(plot_graphs=True) # Получаем изображение для доходов и расходов\n\n if income_spends_image:\n response = HttpResponse(content_type=\"image/png\")\n response.write(income_spends_image.getvalue()) # Get the Income & Spends forecast image\n return response\n\n return JsonResponse({\"message\": \"No graph generated.\"})\n\n@api_view(['GET'])\n@renderer_classes([JSONRenderer])\ndef income_spends_forecast_view(request):\n _, balance_image, _ = get_forecast(plot_graphs=True) # Получаем изображение для баланса\n\n if balance_image:\n response = HttpResponse(content_type=\"image/png\")\n response.write(balance_image.getvalue()) # Get the Balance forecast image\n return response\n\n return JsonResponse({\"message\": \"No graph generated.\"})\n", "repo_name": "enpure/stayresort-prediction", "sub_path": "stayresort/forecast/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1959, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.shortcuts.render", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "django.conf.settings.BASE_DIR", "line_number": 14, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 14, "usage_type": "name"}, {"api_name": "pandas.read_excel", "line_number": 15, "usage_type": "call"}, {"api_name": "predictor.get_forecast", "line_number": 22, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 25, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 29, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 19, "usage_type": "call"}, {"api_name": "rest_framework.decorators.renderer_classes", "line_number": 20, "usage_type": "call"}, {"api_name": "rest_framework.renderers.JSONRenderer", "line_number": 20, "usage_type": "name"}, {"api_name": "predictor.get_forecast", "line_number": 34, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 37, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 41, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 31, "usage_type": "call"}, {"api_name": "rest_framework.decorators.renderer_classes", "line_number": 32, "usage_type": "call"}, {"api_name": "rest_framework.renderers.JSONRenderer", "line_number": 32, "usage_type": "name"}, {"api_name": "predictor.get_forecast", "line_number": 46, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 49, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 53, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 43, "usage_type": "call"}, {"api_name": "rest_framework.decorators.renderer_classes", "line_number": 44, "usage_type": "call"}, {"api_name": "rest_framework.renderers.JSONRenderer", "line_number": 44, "usage_type": "name"}]} +{"seq_id": "13503119811", "text": "import numpy as np\nfrom tqdm import tqdm\nfrom utils import digitize_datetime, decay_func\n\ndef get_k_accuracy(res_mat):\n res_mat = np.array(res_mat)\n return [np.mean(np.sum(res_mat[:,:k], axis=1) > 0) for k in [1,5,10,15,20]]\n\ndef get_recommandation_result(testset, args, poi2region, emb_set, mode, weight=[1,1,1]):\n if mode == 'GE':\n embeddings, region_embeddings, time_embeddings = emb_set\n elif mode == 'STSG':\n# sem_emb, embeddings, time_embeddings = emb_set\n sem_emb, geo_emb, time_embeddings = emb_set\n sem_dim = sem_emb.shape[1]; geo_dim = geo_emb.shape[1];\n embeddings = np.concatenate([sem_emb, geo_emb], axis=1)\n elif mode == 'Skipgram_wt':\n embeddings, time_embeddings = emb_set\n elif mode == 'Skipgram_wot':\n embeddings = emb_set\n elif mode == 'POI2VEC':\n embeddings = emb_set\n elif mode == 'PRME':\n embeddings, embeddings_u, user_embeddings = emb_set\n\n result_mat = list()\n for u, seq in tqdm(enumerate(testset), total=len(testset)):\n lenseq = len(seq)\n lenitem = len(seq[0])\n poiseq, dtseq = seq[:,0], seq[:,lenitem-1]\n tslot_seq = digitize_datetime(dtseq, args.pattern)\n seq = np.concatenate([seq, digitize_datetime(dtseq, args.pattern)[:,None]], axis=1)\n\n for i in range(lenseq-1):\n history = seq[:i]\n target = seq[i+1] \n if lenitem == 2:\n l_n, dt_n, tslot_n = seq[i] #now\n l_y, dt_y, tslot_y = target\n elif lenitem == 3:\n l_n, usr, dt_n, tslot_n = seq[i]\n l_y, usr, dt_y, tslot_y = target\n else: assert 0\n \n decays = list()\n l_xs = history[:,0].astype(int)\n for j, x in enumerate(history):\n decays.append(decay_func(y=dt_y, x=x[lenitem-1]))\n\n embs = embeddings[l_xs]\n if args.use_decay == True:\n user_profile = np.sum(embs*np.array(decays).reshape(-1,1), axis=0)\n else: \n user_profile = np.mean(embs, axis=0)\n if not mode in ['POI2VEC', 'Skipgram_wot', 'PRME']:\n t_emb_now = time_embeddings[tslot_n]\n\n if mode == 'GE':\n r_emb_now = region_embeddings[poi2region[l_n]]\n scores = np.matmul(user_profile, embeddings.T) + \\\n np.matmul(r_emb_now, embeddings.T) + \\\n np.matmul(t_emb_now, embeddings.T)\n elif mode == 'STSG':\n# scores = np.matmul(user_profile, embeddings.T) + \\\n# np.matmul(t_emb_now, sem_emb.T)\n \n profile_sem, profile_geo = user_profile[:sem_dim], user_profile[sem_dim:]\n score_sem = np.matmul(profile_sem, sem_emb.T) / float(sem_dim)\n score_geo = np.matmul(profile_geo, geo_emb.T) / float(geo_dim)\n score_time = np.matmul(t_emb_now, sem_emb.T) / float(sem_dim)\n scores = np.stack([score_sem, score_geo, score_time],axis=0)*np.array(weight).reshape(3,1)\n scores = np.sum(scores, axis=0)\n elif mode == 'Skipgram_wt':\n scores = np.matmul(user_profile, embeddings.T) + \\\n np.matmul(t_emb_now, embeddings.T)\n elif mode == 'Skipgram_wot':\n scores = np.matmul(user_profile, embeddings.T)\n elif mode == 'POI2VEC':\n scores = np.matmul(user_profile, embeddings.T)\n elif mode == 'PRME':\n user_profile = user_embeddings[usr]\n scores = np.matmul(user_profile, embeddings_u.T) + \\\n np.matmul(embeddings[l_n], embeddings.T)\n# scores = np.matmul(user_profile, embeddings.T)\n result_mat.append((-scores).argsort()[:20] == l_y)\n return result_mat", "repo_name": "kunrenzhilu/recommand", "sub_path": "recommand_np.py", "file_name": "recommand_np.py", "file_ext": "py", "file_size_in_byte": 3874, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "numpy.array", "line_number": 6, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 7, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 7, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 16, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 27, "usage_type": "call"}, {"api_name": "utils.digitize_datetime", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 32, "usage_type": "call"}, {"api_name": "utils.digitize_datetime", "line_number": 32, "usage_type": "call"}, {"api_name": "utils.decay_func", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.stack", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 83, "usage_type": "call"}]} +{"seq_id": "15517289648", "text": "import os\nimport numpy as np\nimport pandas as pd\n\nfrom torchvision.transforms import ToTensor # transform PIL image to torch.Tensor\nimport torch\nfrom torch.utils.data import DataLoader # mini-batch loader\nfrom torch import nn\nfrom torch.utils.data import random_split\nfrom torchvision.models import resnet50\n\nimport hydra\nfrom hydra.core.config_store import ConfigStore\n\nfrom config import MNISTConfig\nfrom model import MNIST_lightning\nfrom data import CustomDataset\n\nfrom pytorch_lightning.callbacks.early_stopping import EarlyStopping\nimport pytorch_lightning as pl\n\n\ncs = ConfigStore.instance()\ncs.store(name=\"mnist_config\", node=MNISTConfig)\n\nlabels_item = {\n '0' : 0,\n '1' : 1,\n '2' : 2,\n '3' : 3,\n '4' : 4,\n '5' : 5,\n '6' : 6,\n '7' : 7,\n '8' : 8,\n '9' : 9,\n \n }\n\ndef toCSVfile(input_dir, output_dir, file_name):\n dir_list = os.listdir(input_dir)\n img_dir = []\n labels = []\n\n for dir in dir_list:\n current_path = os.path.join(input_dir, dir)\n idir = os.listdir(current_path)\n lb = [labels_item[dir]]*len(idir)\n\n img_dir += np.core.defchararray.add(current_path + \"/\", np.array(idir)).tolist()\n labels += lb\n df = pd.DataFrame({'filename': img_dir, 'label':labels})\n \n out_dir = output_dir + '/' + file_name\n if not os.path.exists(output_dir):\n os.mkdir(out_dir)\n if os.path.exists(out_dir):\n os.remove(out_dir)\n df.to_csv(out_dir, index = False)\n\n\n@hydra.main(config_path='../configs', config_name='train', version_base=None)\ndef main(cfg: MNISTConfig):\n toCSVfile(cfg.paths.data + '/' + cfg.files.train_folder, \n cfg.paths.data,\n cfg.files.train_file)\n\n \n data = CustomDataset(cfg.paths.data + '/' + cfg.files.train_file, dir = None, transform = ToTensor())\n\n # use 20% of training data for validation\n train_set_size = int(len(data) * cfg.train_size)\n valid_set_size = len(data) - train_set_size\n\n # split the train set into two\n seed = torch.Generator().manual_seed(cfg.params.seed)\n train_set, valid_set = random_split(data, [train_set_size, valid_set_size], generator=seed)\n\n # define dataloader\n train_loader = DataLoader(train_set, batch_size = cfg.params.batch_size, shuffle = True)\n valid_loader = DataLoader(valid_set, batch_size = cfg.params.batch_size, shuffle = False)\n\n # defind model\n model = MNIST_lightning(resnet50(num_classes = 10))\n trainer = pl.Trainer(devices=1, \n accelerator=\"gpu\", \n callbacks=[EarlyStopping(monitor=\"train_loss\", mode=\"min\")], \n max_epochs = cfg.params.n_epoch)\n trainer.fit(model, train_dataloaders=train_loader, val_dataloaders=valid_loader)\n\n\nif __name__ == '__main__':\n main()\n", "repo_name": "haydenshimada/MNIST-hydra-lightning", "sub_path": "src/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2818, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "hydra.core.config_store.ConfigStore.instance", "line_number": 23, "usage_type": "call"}, {"api_name": "hydra.core.config_store.ConfigStore", "line_number": 23, "usage_type": "name"}, {"api_name": "config.MNISTConfig", "line_number": 24, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path", "line_number": 46, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.core.defchararray.add", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.core", "line_number": 50, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 50, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path", "line_number": 55, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path", "line_number": 57, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 58, "usage_type": "call"}, {"api_name": "config.MNISTConfig", "line_number": 63, "usage_type": "name"}, {"api_name": "data.CustomDataset", "line_number": 69, "usage_type": "call"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 69, "usage_type": "call"}, {"api_name": "torch.Generator", "line_number": 76, "usage_type": "call"}, {"api_name": "torch.utils.data.random_split", "line_number": 77, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 81, "usage_type": "call"}, {"api_name": "model.MNIST_lightning", "line_number": 84, "usage_type": "call"}, {"api_name": "torchvision.models.resnet50", "line_number": 84, "usage_type": "call"}, {"api_name": "pytorch_lightning.Trainer", "line_number": 85, "usage_type": "call"}, {"api_name": "pytorch_lightning.callbacks.early_stopping.EarlyStopping", "line_number": 87, "usage_type": "call"}, {"api_name": "hydra.main", "line_number": 62, "usage_type": "call"}]} +{"seq_id": "34888076529", "text": "######################################\n# Kaihua Tang\n######################################\n\nimport os\nimport json\nimport math\nimport torch\nimport numpy as np \nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.optim.lr_scheduler as lr_scheduler\nimport torch.nn.functional as F \nfrom torch.optim.optimizer import Optimizer, required\n\nfrom utils.general_utils import *\n\nfrom torch import Tensor\nfrom typing import List, Optional\n\n\ndef create_optimizer(model, classifier, logger, config):\n training_opt = config['training_opt']\n lr = training_opt['optim_params']['lr']\n weight_decay = training_opt['optim_params']['weight_decay']\n\n # IMPORTANT\n # when the deadline is approaching, I suddenly found that I forgot to add momentum into my SGD optimizer.\n # therefore, I have to just accept the setting of 0 momentum, but since all the methods are replemented \n # under the same optimizer, our conclusions and analyses still hold\n # For the follower, please remember to add momentum here.\n\n logger.info('=====> Create optimizer')\n all_params = []\n\n for _, val in model.named_parameters():\n if not val.requires_grad:\n continue\n all_params += [{\"params\": [val], \"lr\": lr, \"weight_decay\": weight_decay}]\n for _, val in classifier.named_parameters():\n if not val.requires_grad:\n continue\n all_params += [{\"params\": [val], \"lr\": lr, \"weight_decay\": weight_decay}]\n \n if training_opt['optimizer'] == 'Adam':\n return optim.Adam(all_params)\n elif training_opt['optimizer'] == 'SGD':\n return optim.SGD(all_params)\n else:\n logger.info('********** ERROR: unidentified optimizer **********')\n\n\ndef create_optimizer_stage2(model, classifier, logger, config):\n training_opt = config['training_opt']\n lr = training_opt['optim_params']['lr']\n weight_decay = training_opt['optim_params']['weight_decay']\n\n # IMPORTANT\n # when the deadline is approaching, I suddenly found that I forgot to add momentum into my SGD optimizer.\n # therefore, I have to just accept the setting of 0 momentum, but since all the methods are replemented \n # under the same optimizer, our conclusions and analyses still hold\n # For the follower, please remember to add momentum here.\n\n logger.info('=====> Create optimizer')\n all_params = []\n\n # in two-stage training, the second stage should freeze the backbone\n logger.info('========= Freeze Backbone Parameters ===========')\n for _, val in model.named_parameters():\n val.requires_grad = False\n\n for _, val in classifier.named_parameters():\n if not val.requires_grad:\n continue\n all_params += [{\"params\": [val], \"lr\": lr, \"weight_decay\": weight_decay}]\n \n if training_opt['optimizer'] == 'Adam':\n return optim.Adam(all_params)\n elif training_opt['optimizer'] == 'SGD':\n return optim.SGD(all_params)\n else:\n logger.info('********** ERROR: unidentified optimizer **********')\n\n\ndef create_scheduler(optimizer, logger, config):\n training_opt = config['training_opt']\n\n logger.info('=====> Create Scheduler')\n scheduler_params = training_opt['scheduler_params']\n\n if training_opt['scheduler'] == 'cosine':\n return optim.lr_scheduler.CosineAnnealingLR(optimizer, training_opt['num_epochs'], eta_min=scheduler_params['endlr'])\n elif training_opt['scheduler'] == 'step':\n return optim.lr_scheduler.StepLR(optimizer, gamma=scheduler_params['gamma'], step_size=scheduler_params['step_size'])\n elif training_opt['scheduler'] == 'multistep':\n return optim.lr_scheduler.MultiStepLR(optimizer, gamma=scheduler_params['gamma'], milestones=scheduler_params['milestones'])\n else:\n logger.info('********** ERROR: unidentified optimizer **********')\n\n\n\ndef create_loss(logger, config, train_loader):\n training_opt = config['training_opt']\n\n if training_opt['loss'] == 'CrossEntropy':\n loss = nn.CrossEntropyLoss()\n elif training_opt['loss'] == 'Focal':\n loss = FocalLoss(gamma=2.0)\n elif training_opt['loss'] == 'BalancedSoftmax':\n loss = BlSoftmaxLoss(train_loader)\n elif training_opt['loss'] == 'LDAM':\n loss = LDAMLoss(train_loader, total_epoch=training_opt['num_epochs'])\n elif training_opt['loss'] == 'RIDE':\n loss = RIDELoss(train_loader, additional_diversity_factor=config['algorithm_opt']['diversity_factor'])\n elif training_opt['loss'] == 'TADE':\n loss = TADELoss(train_loader, tau=config['algorithm_opt']['tau'])\n else:\n logger.info('********** ERROR: unidentified optimizer **********')\n logger.info('====== Set Loss Function to {} ======='.format(training_opt['loss']))\n return loss\n\n\n\nclass CenterLoss(nn.Module):\n def __init__(self, num_classes=10, feat_dim=2, use_gpu=True):\n super(CenterLoss, self).__init__()\n self.num_class = num_classes\n self.num_feature = feat_dim\n if use_gpu:\n self.centers = nn.Parameter(torch.randn(self.num_class, self.num_feature).cuda())\n else:\n self.centers = nn.Parameter(torch.randn(self.num_class, self.num_feature))\n\n def forward(self, x, labels):\n center = self.centers[labels]\n dist = (x-center).pow(2).sum(dim=-1)\n loss = torch.clamp(dist, min=1e-12, max=1e+12).mean(dim=-1)\n\n return loss\n\n\nclass CenterCosLoss(nn.Module):\n def __init__(self, num_classes=10, feat_dim=2, use_gpu=True):\n super(CenterCosLoss, self).__init__()\n self.num_class = num_classes\n self.num_feature = feat_dim\n if use_gpu:\n self.centers = nn.Parameter(torch.randn(self.num_class, self.num_feature).cuda())\n else:\n self.centers = nn.Parameter(torch.randn(self.num_class, self.num_feature))\n\n def l2_norm(self, x):\n normed_x = x / torch.norm(x, 2, 1, keepdim=True)\n return normed_x\n\n def forward(self, x, labels):\n center = self.centers[labels]\n norm_c = self.l2_norm(center)\n norm_x = self.l2_norm(x)\n similarity = (norm_c * norm_x).sum(dim=-1)\n dist = 1.0 - similarity\n loss = torch.clamp(dist, min=1e-12, max=1e+12).mean(dim=-1)\n\n return loss\n\n\nclass CenterTripletLoss(nn.Module):\n def __init__(self, num_classes=10, feat_dim=2, use_gpu=True):\n super(CenterTripletLoss, self).__init__()\n self.num_class = num_classes\n self.num_feature = feat_dim\n if use_gpu:\n self.centers = nn.Parameter(torch.randn(self.num_class, self.num_feature).cuda())\n else:\n self.centers = nn.Parameter(torch.randn(self.num_class, self.num_feature))\n self.triplet_loss = nn.TripletMarginLoss(margin=1.0, p=2)\n\n def forward(self, x, preds, labels):\n # use most likely categories as negative samples\n preds = preds.softmax(-1)\n batch_size = x.shape[0]\n idxs = torch.arange(batch_size).to(x.device)\n preds[idxs, labels] = -1\n adv_labels = preds.max(-1)[1]\n\n anchor = x # num_batch, num_dim\n positive = self.centers[labels] # num_batch, num_dim\n negative = self.centers[adv_labels] # num_batch, num_dim\n\n output = self.triplet_loss(anchor, positive, negative)\n return output\n\n\n\nclass BlSoftmaxLoss(nn.Module):\n def __init__(self, train_loader, reduction=\"mean\"):\n super(BlSoftmaxLoss, self).__init__()\n # reduction: string. One of \"none\", \"mean\", \"sum\"\n label_count_array = count_dataset(train_loader)\n label_count_array = np.array(label_count_array) / np.sum(label_count_array)\n adjustments = np.log(label_count_array + 1e-12)\n adjustments = torch.from_numpy(adjustments).view(1, -1)\n self.adjustments = adjustments\n self.reduction = reduction\n\n def forward(self, logits, target):\n logits = logits + self.adjustments.to(logits.device)\n loss = F.cross_entropy(input=logits, target=target, reduction=self.reduction)\n return loss\n\nclass FocalLoss(nn.Module):\n def __init__(self, gamma=2.0, alpha=None, size_average=True):\n super(FocalLoss, self).__init__()\n self.gamma = gamma\n self.alpha = alpha\n self.size_average = size_average\n\n def forward(self, input, target):\n if input.dim()>2:\n input = input.view(input.size(0),input.size(1),-1) # N,C,H,W => N,C,H*W\n input = input.transpose(1,2) # N,C,H*W => N,H*W,C\n input = input.contiguous().view(-1,input.size(2)) # N,H*W,C => N*H*W,C\n target = target.view(-1,1)\n\n logpt = F.log_softmax(input, dim=-1)\n logpt = logpt.gather(1,target)\n logpt = logpt.view(-1)\n pt = logpt.detach().exp()\n\n if self.alpha is not None:\n assert False\n\n loss = -1 * (1-pt)**self.gamma * logpt\n if self.size_average: \n return loss.mean()\n else: \n return loss.sum()\n\nclass LDAMLoss(nn.Module):\n def __init__(self, dataloader, total_epoch, max_m=0.5, s=30):\n super(LDAMLoss, self).__init__()\n self.cls_num_list = count_dataset(dataloader)\n m_list = 1.0 / np.sqrt(np.sqrt(self.cls_num_list))\n m_list = m_list * (max_m / np.max(m_list))\n m_list = torch.FloatTensor(m_list)\n self.m_list = m_list\n assert s > 0\n self.s = s\n self.total_epoch = total_epoch\n\n def set_weight(self, epoch):\n idx = epoch // int(self.total_epoch * 0.8)\n betas = [0, 0.9999]\n effective_num = 1.0 - np.power(betas[idx], self.cls_num_list)\n per_cls_weights = (1.0 - betas[idx]) / np.array(effective_num)\n per_cls_weights = per_cls_weights / np.sum(per_cls_weights) * len(self.cls_num_list)\n self.weight = torch.FloatTensor(per_cls_weights)\n\n def forward(self, x, target):\n index = torch.zeros_like(x, dtype=torch.uint8)\n index.scatter_(1, target.data.view(-1, 1), 1)\n \n index_float = index.float().to(x.device)\n batch_m = torch.matmul(self.m_list.to(x.device)[None, :], index_float.transpose(0,1))\n batch_m = batch_m.view((-1, 1))\n x_m = x - batch_m\n \n output = torch.where(index, x_m, x)\n return F.cross_entropy(self.s*output, target, weight=self.weight.to(x.device))\n\n\nclass TADELoss(nn.Module):\n def __init__(self, dataloader, tau=2):\n super().__init__()\n self.base_loss = F.cross_entropy \n cls_num_list = count_dataset(dataloader)\n prior = np.array(cls_num_list) / np.sum(cls_num_list)\n self.prior = torch.tensor(prior).float().cuda()\n self.C_number = len(cls_num_list) # class number\n self.tau = tau \n\n def inverse_prior(self, prior): \n value, idx0 = torch.sort(prior)\n _, idx1 = torch.sort(idx0)\n idx2 = prior.shape[0]-1-idx1 # reverse the order\n inverse_prior = value.index_select(0,idx2)\n \n return inverse_prior\n\n def forward(self, output_logits, target, extra_info=None):\n if extra_info is None:\n return self.base_loss(output_logits, target) # output_logits indicates the final prediction\n\n loss = 0\n\n # Obtain logits from each expert \n expert1_logits = extra_info['logits'][0]\n expert2_logits = extra_info['logits'][1] \n expert3_logits = extra_info['logits'][2] \n \n # Softmax loss for expert 1 \n loss += self.base_loss(expert1_logits, target)\n \n # Balanced Softmax loss for expert 2 \n expert2_logits = expert2_logits + torch.log(self.prior + 1e-9) \n loss += self.base_loss(expert2_logits, target)\n \n # Inverse Softmax loss for expert 3\n inverse_prior = self.inverse_prior(self.prior)\n expert3_logits = expert3_logits + torch.log(self.prior + 1e-9) - self.tau * torch.log(inverse_prior+ 1e-9) \n loss += self.base_loss(expert3_logits, target)\n \n return loss\n\n\nclass RIDELoss(nn.Module):\n '''\n Copy from https://github.com/frank-xwang/RIDE-LongTailRecognition/blob/main/model/loss.py\n '''\n def __init__(self, dataloader=None, base_diversity_temperature=1.0, max_m=0.5, s=30, reweight=True, reweight_epoch=80, \n base_loss_factor=1.0, additional_diversity_factor=-0.2, reweight_factor=0.02):\n super().__init__()\n self.base_loss = F.cross_entropy\n self.base_loss_factor = base_loss_factor\n if not reweight:\n self.reweight_epoch = -1\n else:\n self.reweight_epoch = reweight_epoch\n\n # LDAM is a variant of cross entropy and we handle it with self.m_list.\n if dataloader is None:\n # No cls_num_list is provided, then we cannot adjust cross entropy with LDAM.\n\n self.m_list = None\n self.per_cls_weights_enabled = None\n self.per_cls_weights_enabled_diversity = None\n else:\n # We will use LDAM loss if we provide cls_num_list.\n cls_num_list = count_dataset(dataloader)\n m_list = 1.0 / np.sqrt(np.sqrt(cls_num_list))\n m_list = m_list * (max_m / np.max(m_list))\n m_list = torch.tensor(m_list, dtype=torch.float, requires_grad=False)\n self.m_list = m_list\n self.s = s\n assert s > 0\n \n if reweight_epoch != -1:\n idx = 1 # condition could be put in order to set idx\n betas = [0, 0.9999]\n effective_num = 1.0 - np.power(betas[idx], cls_num_list)\n per_cls_weights = (1.0 - betas[idx]) / np.array(effective_num)\n per_cls_weights = per_cls_weights / np.sum(per_cls_weights) * len(cls_num_list)\n self.per_cls_weights_enabled = torch.tensor(per_cls_weights, dtype=torch.float, requires_grad=False)\n else:\n self.per_cls_weights_enabled = None\n\n cls_num_list = np.array(cls_num_list) / np.sum(cls_num_list)\n C = len(cls_num_list)\n per_cls_weights = C * cls_num_list * reweight_factor + 1 - reweight_factor\n\n # Experimental normalization: This is for easier hyperparam tuning, the effect can be described in the learning rate so the math formulation keeps the same.\n # At the same time, the 1 - max trick that was previously used is not required since weights are already adjusted.\n per_cls_weights = per_cls_weights / np.max(per_cls_weights)\n\n assert np.all(per_cls_weights > 0), \"reweight factor is too large: out of bounds\"\n # save diversity per_cls_weights\n self.per_cls_weights_enabled_diversity = torch.tensor(per_cls_weights, dtype=torch.float, requires_grad=False).cuda()\n\n self.base_diversity_temperature = base_diversity_temperature\n self.additional_diversity_factor = additional_diversity_factor\n\n def to(self, device):\n super().to(device)\n if self.m_list is not None:\n self.m_list = self.m_list.to(device)\n \n if self.per_cls_weights_enabled is not None:\n self.per_cls_weights_enabled = self.per_cls_weights_enabled.to(device)\n\n if self.per_cls_weights_enabled_diversity is not None:\n self.per_cls_weights_enabled_diversity = self.per_cls_weights_enabled_diversity.to(device)\n\n return self\n\n def set_epoch(self, epoch):\n if self.reweight_epoch != -1:\n self.epoch = epoch\n\n if epoch > self.reweight_epoch:\n self.per_cls_weights_base = self.per_cls_weights_enabled\n self.per_cls_weights_diversity = self.per_cls_weights_enabled_diversity\n else:\n self.per_cls_weights_base = None\n self.per_cls_weights_diversity = None\n\n def get_final_output(self, output_logits, target):\n x = output_logits\n\n index = torch.zeros_like(x, dtype=torch.uint8, device=x.device)\n index.scatter_(1, target.data.view(-1, 1), 1)\n \n index_float = index.float()\n batch_m = torch.matmul(self.m_list[None, :], index_float.transpose(0,1))\n \n batch_m = batch_m.view((-1, 1))\n x_m = x - batch_m * self.s\n\n final_output = torch.where(index, x_m, x)\n return final_output\n\n def forward(self, output_logits, target, extra_info=None):\n if extra_info is None:\n return self.base_loss(output_logits, target)\n\n loss = 0\n\n self.to(output_logits.device)\n # Adding RIDE Individual Loss for each expert\n for logits_item in extra_info['logits']:\n ride_loss_logits = logits_item\n # the following line of code is unfair (original implementation) for no diversity loss\n #ride_loss_logits = output_logits if self.additional_diversity_factor == 0 else logits_item\n if self.m_list is None:\n loss += self.base_loss_factor * self.base_loss(ride_loss_logits, target)\n else:\n final_output = self.get_final_output(ride_loss_logits, target)\n loss += self.base_loss_factor * self.base_loss(final_output, target, weight=self.per_cls_weights_base)\n \n base_diversity_temperature = self.base_diversity_temperature\n\n if self.per_cls_weights_diversity is not None:\n diversity_temperature = base_diversity_temperature * self.per_cls_weights_diversity.view((1, -1))\n temperature_mean = diversity_temperature.mean().item()\n else:\n diversity_temperature = base_diversity_temperature\n temperature_mean = base_diversity_temperature\n \n output_dist = F.log_softmax(logits_item / diversity_temperature, dim=1)\n with torch.no_grad():\n # Using the mean takes only linear instead of quadratic time in computing and has only a slight difference so using the mean is preferred here\n mean_output_dist = F.softmax(output_logits / diversity_temperature, dim=1)\n \n loss += self.additional_diversity_factor * temperature_mean * temperature_mean * F.kl_div(output_dist, mean_output_dist, reduction='batchmean')\n \n return loss\n\n\n\n\n\n\n\n", "repo_name": "KaihuaTang/Generalized-Long-Tailed-Benchmarks.pytorch", "sub_path": "utils/training_utils.py", "file_name": "training_utils.py", "file_ext": "py", "file_size_in_byte": 18258, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 106, "dataset": "github-code", "pt": "20", "api": [{"api_name": "torch.optim.Adam", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 46, "usage_type": "name"}, {"api_name": "torch.optim.SGD", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 48, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 78, "usage_type": "name"}, {"api_name": "torch.optim.SGD", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 80, "usage_type": "name"}, {"api_name": "torch.optim.lr_scheduler.CosineAnnealingLR", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.optim.lr_scheduler", "line_number": 92, "usage_type": "attribute"}, {"api_name": "torch.optim", "line_number": 92, "usage_type": "name"}, {"api_name": "torch.optim.lr_scheduler.StepLR", "line_number": 94, "usage_type": "call"}, {"api_name": "torch.optim.lr_scheduler", "line_number": 94, "usage_type": "attribute"}, {"api_name": "torch.optim", "line_number": 94, "usage_type": "name"}, {"api_name": "torch.optim.lr_scheduler.MultiStepLR", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.optim.lr_scheduler", "line_number": 96, "usage_type": "attribute"}, {"api_name": "torch.optim", "line_number": 96, "usage_type": "name"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 106, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 106, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 124, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 124, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 130, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.nn.Parameter", "line_number": 132, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 132, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 132, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 137, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 142, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 142, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 148, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 148, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 148, "usage_type": "call"}, {"api_name": "torch.nn.Parameter", "line_number": 150, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 150, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 150, "usage_type": "call"}, {"api_name": "torch.norm", "line_number": 153, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 167, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 167, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 173, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 173, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 173, "usage_type": "call"}, {"api_name": "torch.nn.Parameter", "line_number": 175, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 175, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 175, "usage_type": "call"}, {"api_name": "torch.nn.TripletMarginLoss", "line_number": 176, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 176, "usage_type": "name"}, {"api_name": "torch.arange", "line_number": 182, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 195, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 195, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 200, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 200, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 201, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 202, "usage_type": "call"}, {"api_name": "torch.nn.functional.cross_entropy", "line_number": 208, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 208, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 211, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 211, "usage_type": "name"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 225, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 225, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 239, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 239, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 243, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 244, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 245, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 254, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 255, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 256, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 257, "usage_type": "call"}, {"api_name": "torch.zeros_like", "line_number": 260, "usage_type": "call"}, {"api_name": "torch.uint8", "line_number": 260, "usage_type": "attribute"}, {"api_name": "torch.matmul", "line_number": 264, "usage_type": "call"}, {"api_name": "torch.where", "line_number": 268, "usage_type": "call"}, {"api_name": "torch.nn.functional.cross_entropy", "line_number": 269, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 269, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 272, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 272, "usage_type": "name"}, {"api_name": "torch.nn.functional.cross_entropy", "line_number": 275, "usage_type": "attribute"}, {"api_name": "torch.nn.functional", "line_number": 275, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 277, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 277, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 278, "usage_type": "call"}, {"api_name": "torch.sort", "line_number": 283, "usage_type": "call"}, {"api_name": "torch.sort", "line_number": 284, "usage_type": "call"}, {"api_name": "torch.log", "line_number": 305, "usage_type": "call"}, {"api_name": "torch.log", "line_number": 310, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 316, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 316, "usage_type": "name"}, {"api_name": "torch.nn.functional.cross_entropy", "line_number": 323, "usage_type": "attribute"}, {"api_name": "torch.nn.functional", "line_number": 323, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 340, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 341, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 342, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 342, "usage_type": "attribute"}, {"api_name": "numpy.power", "line_number": 350, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 351, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 352, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 353, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 353, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 357, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 357, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 363, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 365, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 367, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 367, "usage_type": "attribute"}, {"api_name": "torch.zeros_like", "line_number": 399, "usage_type": "call"}, {"api_name": "torch.uint8", "line_number": 399, "usage_type": "attribute"}, {"api_name": "torch.matmul", "line_number": 403, "usage_type": "call"}, {"api_name": "torch.where", "line_number": 408, "usage_type": "call"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 438, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 438, "usage_type": "name"}, {"api_name": "torch.no_grad", "line_number": 439, "usage_type": "call"}, {"api_name": "torch.nn.functional.softmax", "line_number": 441, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 441, "usage_type": "name"}, {"api_name": "torch.nn.functional.kl_div", "line_number": 443, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 443, "usage_type": "name"}]} +{"seq_id": "36212403703", "text": "#! /usr/bin/python\n# coding: utf-8\nimport os\nimport io\nimport sys\nimport json\nimport time\nimport pprint\nimport argparse\n\npp = pprint.PrettyPrinter(indent=4)\n\nif not os.path.isfile('./config.json'):\n\tparser = argparse.ArgumentParser(description='IBM Bluemix Container \\\n\t\tManagement Instrument for Prototyping and Deployments',\n\t\tformatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\tparser.add_argument(\n\t\t'--flag', '-f', required=False, type=int, \n\t\thelp='flag number current or init value\\n \\\n\t\tdefaults to 0', default=0)\n\tparser.add_argument(\n\t\t'--ip', '-p', required=False, type=str, \n\t\thelp='optional public IP address')\n\tparser.add_argument(\n\t\t'--namespace', '-s', required=True, type=str, \n\t\thelp='designated namespace')\n\tparser.add_argument(\n\t\t'--directory', '-d', required=True, type=str, \n\t\thelp='absolute directory suggested')\n\tparser.add_argument(\n\t\t'--ports', '-r', required=True, type=int, nargs='+',\n\t\thelp='space separated list of ports, include 80')\n\tparser.add_argument(\n\t\t'--image', '-i', required=False, type=str, \n\t\thelp='static image name\\n \\\n\t\tdefaults to \"xyz\"', default='xyz')\n\tparser.add_argument(\n\t\t'--container', '-n', required=False, type=str, \n\t\thelp='static base container name\\n \\\n\t\tdefaults to \"bmContainer', default='bmContainer')\n\tparser.add_argument(\n\t\t'--url', '-u', required=False, type=str, \n\t\thelp='Bluemix base url, defaults to:\\n \\\n\t\tregistry.ng.bluemix.net/',\n\t\tdefault='registry.ng.bluemix.net/')\n\n\targs = parser.parse_args()\n\n\tconfigs = {\n\t\t'flag': args.flag,\n\t\t'directory': args.directory,\n\t\t'ports': args.ports,\n\t\t'ip': args.ip,\n\t\t'namespace': args.namespace,\n\t\t'image': args.image,\n\t\t'container': args.container,\n\t\t'url': args.url\n\t}\n\n\tprint('*** CONFIRMATION REQUIRED ***\\\n\t\t\\nplease confirm writing the following configurations to file:\\n')\n\tpp.pprint(configs)\n\tprint('\\nReturn Y to proceed or anything else to exit')\n\tans = raw_input()\n\tif ans.lower() != 'y':\n\t\tsys.exit()\n\n\twith io.open('config.json', 'w', encoding='utf-8') as f:\n\t\tf.write(unicode(json.dumps(configs, \n\t\t\t\t\t\tensure_ascii=False, indent = 4)))\n\n\tprint('*' * 40)\n\tprint('Congratulations, configuration is completed. \\\n\t\t \\nTo delete cartridge and images, run script without args: \\\n\t\t $ python image.py')\n\tsys.exit()\n\n\nwith open('config.json') as data_file: \n data = json.load(data_file)\n\ncontainer = data['container']\ndirectory = data['directory']\nflag = data['flag']\nimage = data['image']\nip = data['ip']\nnamespace = data['namespace']\nports = data['ports']\nurl = data['url']\n\nimageAddr = namespace + '/' + image + ':'\n\n# 1 - stop old container\noldContainer = container + str(flag)\ncommand = \"ice stop \" + oldContainer\nos.system(command)\n\n# 2 - if ip, unbind\nif ip is not None:\n\tcommand = \"ice ip unbind \" + ip + \" \" + oldContainer\n\tos.system(command)\n\n\n#3 - delete previous images\npreviousImageShort = imageAddr + str(flag)\npreviousImageLong = url + previousImageShort\ncommand = \"ice --local rmi \" + previousImageShort\nos.system(command)\ncommand = \"ice --local rmi \" + previousImageLong\nos.system(command)\ncommand = \"ice --cloud rmi \" + previousImageShort\nos.system(command)\n\n#4 - build, tag, push new image\nnewImageShort = imageAddr + str(flag + 1)\nnewImageLong = url + newImageShort\ncommand = \"ice --local build -t \" + newImageShort + \" \" + directory\nos.system(command)\ncommand = \"ice --local tag \" + newImageShort + \" \" + newImageLong\nos.system(command)\ncommand = \"ice --local push \" + newImageLong\n\n#5 - run new container\nnewContainer = container + str(flag + 1)\nspecifiedPorts = ''\nfor port in ports:\n\tspecifiedPorts+='-p ' + str(port) + ' '\ncommand = \"ice run --name \" + newContainer + \" \" + specifiedPorts + \" \" + newImageShort\nos.system(command)\n\n#6 - if ip bind port to new container\nif ip is not None:\n\tcommand = \"ice ip bind \" + ip + \" \" + newContainer\n\tos.system(command)\n\n#7 - delete old container\ncommand = \"ice rm \" + oldContainer\nos.system(command)\n\ndata['flag']+=1\n\nwith io.open('config.json', 'w+', encoding='utf-8') as f:\n\tf.write(unicode(json.dumps(data, \n\t\t\t\t\tensure_ascii=False, indent = 4)))\n", "repo_name": "aug2uag/BlueImage", "sub_path": "src/script.py", "file_name": "script.py", "file_ext": "py", "file_size_in_byte": 4045, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pprint.PrettyPrinter", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 14, "usage_type": "call"}, {"api_name": "argparse.ArgumentDefaultsHelpFormatter", "line_number": 16, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 66, "usage_type": "call"}, {"api_name": "io.open", "line_number": 68, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 69, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 76, "usage_type": "call"}, {"api_name": "json.load", "line_number": 80, "usage_type": "call"}, {"api_name": "os.system", "line_number": 96, "usage_type": "call"}, {"api_name": "os.system", "line_number": 101, "usage_type": "call"}, {"api_name": "os.system", "line_number": 108, "usage_type": "call"}, {"api_name": "os.system", "line_number": 110, "usage_type": "call"}, {"api_name": "os.system", "line_number": 112, "usage_type": "call"}, {"api_name": "os.system", "line_number": 118, "usage_type": "call"}, {"api_name": "os.system", "line_number": 120, "usage_type": "call"}, {"api_name": "os.system", "line_number": 129, "usage_type": "call"}, {"api_name": "os.system", "line_number": 134, "usage_type": "call"}, {"api_name": "os.system", "line_number": 138, "usage_type": "call"}, {"api_name": "io.open", "line_number": 142, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 143, "usage_type": "call"}]} +{"seq_id": "36488311623", "text": "import re\n\nfrom pyppeteer.browser import Browser, Page\nfrom pyppeteer.element_handle import ElementHandle\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom app.db.curriculum import store_or_update_curriculum\nfrom app.db.models import Curriculum\nfrom app.db.program import get_program_by_sigaa_id, get_programs\nfrom app.scraper.constants import ELEMENT_INNER_TEXT, curricula_list_base_url\nfrom app.scraper.utils import get_page\n\n\nasync def get_cell_text_by_header_text(page: Page, th_text: str) -> str:\n expression = f\"//th[contains(., '{th_text}')]/following-sibling::td\"\n [cell_element, *_] = await page.Jx(expression)\n\n cell_inner_text: str = await page.evaluate(ELEMENT_INNER_TEXT, cell_element)\n\n return cell_inner_text\n\n\nasync def get_programs_sigaa_ids(\n session: AsyncSession, program_sigaa_id: int | None = None\n) -> set[int]:\n programs_sigaa_ids: set[int] = set()\n\n if program_sigaa_id:\n programs_sigaa_ids.add(program_sigaa_id)\n else:\n programs = await get_programs(session)\n programs_sigaa_ids.update(program.sigaa_id for program in programs)\n\n return programs_sigaa_ids\n\n\ndef get_program_curricula_url(program_sigaa_id: int) -> str:\n return f\"{curricula_list_base_url}?id={program_sigaa_id}\"\n\n\nasync def get_program_curricula_page(browser: Browser, program_sigaa_id: int) -> Page:\n program_curricula_url = get_program_curricula_url(program_sigaa_id)\n\n page = await get_page(browser, url=program_curricula_url)\n\n return page\n\n\nasync def get_curricula_tr_elements(\n page: Page, curriculum_sigaa_id: str | None = None\n) -> list[ElementHandle]:\n table_xpath_selector = \"//table[@id='table_lt']\"\n tr_xpath_selector = \"//tr[(@class='linha_par' or @class='linha_impar')]\"\n xpath_selector = f\"{table_xpath_selector}{tr_xpath_selector}\"\n\n if curriculum_sigaa_id:\n td_xpath_selector = f\"[descendant::td[contains(., '{curriculum_sigaa_id}')]]\"\n xpath_selector += td_xpath_selector\n\n curricula_tr = await page.xpath(xpath_selector)\n\n return curricula_tr\n\n\nasync def get_curriculum_status(curriculum_tr: ElementHandle) -> bool:\n active_elements = await curriculum_tr.xpath(\"td[contains(., 'Ativa')]\")\n\n return bool(active_elements)\n\n\nasync def get_curriculum_page(\n browser: Browser, program_sigaa_id: int, curriculum_sigaa_id: str\n) -> Page:\n program_curricula_url = get_program_curricula_url(program_sigaa_id)\n\n page = await browser.newPage()\n await page.goto(program_curricula_url)\n\n [curriculum_tr] = await get_curricula_tr_elements(page, curriculum_sigaa_id)\n button = await curriculum_tr.J(\"a[title='Relatório da Estrutura Curricular']\")\n\n if not button:\n raise Exception(\"Could not find button to open curriculum page\")\n\n await button.click()\n await page.waitForNavigation()\n\n return page\n\n\nasync def get_curriculum_sigaa_id_by_tr_element(curriculum_tr: ElementHandle) -> str:\n raw_sigaa_id = await curriculum_tr.Jeval(\"td:first-child\", ELEMENT_INNER_TEXT)\n\n sigaa_id_pattern = \"Detalhes da Estrutura Curricular (.*),\"\n sigaa_id_match = re.search(sigaa_id_pattern, raw_sigaa_id)\n\n if not sigaa_id_match:\n raise Exception(\"Could not find curriculum sigaa_id\")\n\n sigaa_id = sigaa_id_match.group(1).strip()\n\n return sigaa_id\n\n\nasync def get_curriculum_sigaa_id(curriculum_page: Page) -> str:\n return await get_cell_text_by_header_text(curriculum_page, \"Código\")\n\n\nasync def get_curriculum_start_period(curriculum_page: Page) -> tuple[int, int]:\n header_text = \"Período Letivo de Entrada em Vigor\"\n raw_start_period = await get_cell_text_by_header_text(curriculum_page, header_text)\n\n [start_year, start_period] = raw_start_period.split(\".\")\n start_year = int(start_year)\n start_period = int(start_period)\n\n return start_year, start_period\n\n\nasync def get_curriculum_min_periods(curriculum_page: Page) -> int:\n min_periods = await get_cell_text_by_header_text(curriculum_page, \"Mínimo:\")\n min_periods = int(min_periods)\n\n return min_periods\n\n\nasync def get_curriculum_max_periods(curriculum_page: Page) -> int:\n max_periods = await get_cell_text_by_header_text(curriculum_page, \"Máximo:\")\n max_periods = int(max_periods)\n\n return max_periods\n\n\nasync def get_curriculum_min_period_workload(curriculum_page: Page) -> int:\n header_text = \"Carga Horária Mínima por Período Letivo\"\n raw_workload = await get_cell_text_by_header_text(curriculum_page, header_text)\n\n min_period_workload = format_workload_to_number(raw_workload)\n\n return min_period_workload\n\n\ndef format_workload_to_number(raw_workload: str) -> int:\n workload = int(raw_workload.replace(\"h\", \"\"))\n\n return workload\n\n\nasync def get_curriculum_max_period_workload(curriculum_page: Page) -> int:\n header_text = \"Carga Horária Máxima por Período Letivo\"\n raw_workload = await get_cell_text_by_header_text(curriculum_page, header_text)\n\n max_period_workload = format_workload_to_number(raw_workload)\n\n return max_period_workload\n\n\nasync def get_curriculum_min_workload(curriculum_page: Page) -> int:\n header_text = \"Total Mínima\"\n raw_workload = await get_cell_text_by_header_text(curriculum_page, header_text)\n\n min_workload = format_workload_to_number(raw_workload)\n\n return min_workload\n\n\nasync def get_curriculum_mandatory_components_workload(curriculum_page: Page) -> int:\n header_text = \"Total:\"\n raw_workload = await get_cell_text_by_header_text(curriculum_page, header_text)\n\n mandatory_components_workload = format_workload_to_number(raw_workload)\n\n return mandatory_components_workload\n\n\nasync def get_curriculum_min_elective_components_workload(curriculum_page: Page) -> int:\n header_text = \"Carga Horária Optativa Mínima:\"\n raw_workload = await get_cell_text_by_header_text(curriculum_page, header_text)\n\n min_elective_components_workload = format_workload_to_number(raw_workload)\n\n return min_elective_components_workload\n\n\nasync def get_curriculum_min_complementary_components_workload(\n curriculum_page: Page,\n) -> int:\n header_text = \"Carga Horária Complementar Mínima:\"\n raw_workload = await get_cell_text_by_header_text(curriculum_page, header_text)\n\n min_complementary_components_workload = format_workload_to_number(raw_workload)\n\n return min_complementary_components_workload\n\n\nasync def get_curriculum_max_complementary_components_workload(\n curriculum_page: Page,\n) -> int:\n header_text = \"Carga Horária Máxima de Componentes Eletivos\"\n raw_workload = await get_cell_text_by_header_text(curriculum_page, header_text)\n\n max_complementary_components_workload = format_workload_to_number(raw_workload)\n\n return max_complementary_components_workload\n\n\nasync def get_curriculum(\n session: AsyncSession, curriculum_page: Page, program_sigaa_id: int, active: bool\n) -> Curriculum:\n sigaa_id = await get_curriculum_sigaa_id(curriculum_page)\n start_year, start_period = await get_curriculum_start_period(curriculum_page)\n min_periods = await get_curriculum_min_periods(curriculum_page)\n max_periods = await get_curriculum_max_periods(curriculum_page)\n min_period_workload = await get_curriculum_min_period_workload(curriculum_page)\n max_period_workload = await get_curriculum_max_period_workload(curriculum_page)\n min_workload = await get_curriculum_min_workload(curriculum_page)\n\n mandatory_components_workload = await get_curriculum_mandatory_components_workload(\n curriculum_page\n )\n\n min_elective_components_workload = (\n await get_curriculum_min_elective_components_workload(curriculum_page)\n )\n\n max_elective_components_workload = min_elective_components_workload\n\n min_complementary_components_workload = (\n await get_curriculum_min_complementary_components_workload(curriculum_page)\n )\n\n max_complementary_components_workload = (\n await get_curriculum_max_complementary_components_workload(curriculum_page)\n )\n\n program = await get_program_by_sigaa_id(session, program_sigaa_id)\n\n if not program:\n raise Exception(\"Program not found\")\n\n curriculum = Curriculum(\n sigaa_id=sigaa_id,\n active=active,\n start_year=start_year,\n start_period=start_period,\n min_periods=min_periods,\n max_periods=max_periods,\n min_period_workload=min_period_workload,\n max_period_workload=max_period_workload,\n min_workload=min_workload,\n mandatory_components_workload=mandatory_components_workload,\n min_elective_components_workload=min_elective_components_workload,\n max_elective_components_workload=max_elective_components_workload,\n min_complementary_components_workload=min_complementary_components_workload,\n max_complementary_components_workload=max_complementary_components_workload,\n program_id=program.id,\n )\n\n return curriculum\n\n\nasync def scrape_curricula(\n browser: Browser,\n session: AsyncSession,\n program_sigaa_id: int | None = None,\n only_active: bool = True,\n):\n \"\"\"Scrape and store (or update) curricula.\"\"\"\n\n programs_sigaa_ids: set[int]\n programs_sigaa_ids = await get_programs_sigaa_ids(session, program_sigaa_id)\n\n # There are too many programs (~150) to open all tabs at once\n for p_sigaa_id in programs_sigaa_ids:\n curricula_page = await get_program_curricula_page(browser, p_sigaa_id)\n curricula_tr = await get_curricula_tr_elements(curricula_page)\n\n for curriculum_tr in curricula_tr:\n active = await get_curriculum_status(curriculum_tr)\n\n if only_active and not active:\n continue\n\n sigaa_id = await get_curriculum_sigaa_id_by_tr_element(curriculum_tr)\n curriculum_page = await get_curriculum_page(browser, p_sigaa_id, sigaa_id)\n\n curriculum = await get_curriculum(\n session, curriculum_page, p_sigaa_id, active\n )\n\n await store_or_update_curriculum(session, curriculum)\n\n await curriculum_page.close()\n\n await curricula_page.waitFor(1000)\n await curricula_page.close()\n", "repo_name": "irwinschmitt/fluxo-agil-api", "sub_path": "app/scraper/curricula.py", "file_name": "curricula.py", "file_ext": "py", "file_size_in_byte": 10158, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pyppeteer.browser.Page", "line_number": 14, "usage_type": "name"}, {"api_name": "app.scraper.constants.ELEMENT_INNER_TEXT", "line_number": 18, "usage_type": "argument"}, {"api_name": "sqlalchemy.ext.asyncio.AsyncSession", "line_number": 24, "usage_type": "name"}, {"api_name": "app.db.program.get_programs", "line_number": 31, "usage_type": "call"}, {"api_name": "app.scraper.constants.curricula_list_base_url", "line_number": 38, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Browser", "line_number": 41, "usage_type": "name"}, {"api_name": "app.scraper.utils.get_page", "line_number": 44, "usage_type": "call"}, {"api_name": "pyppeteer.browser.Page", "line_number": 41, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Page", "line_number": 50, "usage_type": "name"}, {"api_name": "pyppeteer.element_handle.ElementHandle", "line_number": 51, "usage_type": "name"}, {"api_name": "pyppeteer.element_handle.ElementHandle", "line_number": 65, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Browser", "line_number": 72, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Page", "line_number": 73, "usage_type": "name"}, {"api_name": "pyppeteer.element_handle.ElementHandle", "line_number": 91, "usage_type": "name"}, {"api_name": "app.scraper.constants.ELEMENT_INNER_TEXT", "line_number": 92, "usage_type": "argument"}, {"api_name": "re.search", "line_number": 95, "usage_type": "call"}, {"api_name": "pyppeteer.browser.Page", "line_number": 105, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Page", "line_number": 109, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Page", "line_number": 120, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Page", "line_number": 127, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Page", "line_number": 134, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Page", "line_number": 149, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Page", "line_number": 158, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Page", "line_number": 167, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Page", "line_number": 176, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Page", "line_number": 186, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Page", "line_number": 197, "usage_type": "name"}, {"api_name": "sqlalchemy.ext.asyncio.AsyncSession", "line_number": 208, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Page", "line_number": 208, "usage_type": "name"}, {"api_name": "app.db.program.get_program_by_sigaa_id", "line_number": 236, "usage_type": "call"}, {"api_name": "app.db.models.Curriculum", "line_number": 241, "usage_type": "call"}, {"api_name": "app.db.models.Curriculum", "line_number": 209, "usage_type": "name"}, {"api_name": "pyppeteer.browser.Browser", "line_number": 263, "usage_type": "name"}, {"api_name": "sqlalchemy.ext.asyncio.AsyncSession", "line_number": 264, "usage_type": "name"}, {"api_name": "app.db.curriculum.store_or_update_curriculum", "line_number": 291, "usage_type": "call"}]} +{"seq_id": "74899025010", "text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\n# name = './mandelbrot/data/mandelbrot_10000'\nname = './julia/data/julia_-0.134_0.250_100'\n\ndf= pd.read_csv(name+'.csv', header=None, dtype='float')\n\nsize = len(df)\n# drop last empty column\ndel df[df.columns[-1]] \n\nfractal_set = name.split('/')[1]\nif fractal_set == 'julia':\n cmap = cm.bone_r # julia\nelse:\n cmap = cm.viridis # mandelbrot\n\n# set colour for stable numbers / members\nmasked_array = np.ma.masked_where(df== 100.0, df)\ncmap.set_bad(color='black')\n\nplt.imshow(masked_array, cmap=cmap, interpolation='none')\nplt.gca().set_aspect(\"equal\")\nplt.axis(\"off\")\nplt.tight_layout()\n# plt.show()\n\npng_name = './'+fractal_set+'/plots/'+name.split('/')[-1]+'.png'\nplt.savefig(png_name, dpi=1000, bbox_inches=None)\n", "repo_name": "astroDimitrios/Fortran", "sub_path": "19_GDB/plot.py", "file_name": "plot.py", "file_ext": "py", "file_size_in_byte": 818, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pandas.read_csv", "line_number": 9, "usage_type": "call"}, {"api_name": "matplotlib.cm.bone_r", "line_number": 17, "usage_type": "attribute"}, {"api_name": "matplotlib.cm", "line_number": 17, "usage_type": "name"}, {"api_name": "matplotlib.cm.viridis", "line_number": 19, "usage_type": "attribute"}, {"api_name": "matplotlib.cm", "line_number": 19, "usage_type": "name"}, {"api_name": "numpy.ma.masked_where", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.ma", "line_number": 22, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}]} +{"seq_id": "42556080100", "text": "import hashlib\nimport os\nimport uuid\n\nfrom django.db import models\n\nfrom .issue import Issue\nfrom .timestamped import TimestampedModel\n\n\ndef get_s3_key(file_upload, filename):\n \"\"\"\n Get S3 key for the file - use a hash of the file bytes to\n ensure that files are unique and that filenames are not easily guessed.\n \"\"\"\n file = file_upload.file\n if file._file:\n img_bytes = file._file.file.read()\n file._file.file.seek(0)\n filename_base = hashlib.md5(img_bytes).hexdigest()\n _, filename_ext = os.path.splitext(filename)\n filename = filename_base + filename_ext.lower()\n\n return f\"{file_upload.UPLOAD_KEY}/{filename}\"\n\n\nclass FileUpload(TimestampedModel):\n \"\"\"\n An image or document uploaded by a user as a part of a issue.\n \"\"\"\n\n UPLOAD_KEY = \"file-uploads\"\n\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n file = models.FileField(upload_to=get_s3_key)\n issue = models.ForeignKey(Issue, on_delete=models.SET_NULL, null=True, blank=True)\n", "repo_name": "AnikaLegal/clerk", "sub_path": "app/core/models/upload.py", "file_name": "upload.py", "file_ext": "py", "file_size_in_byte": 1042, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 31, "dataset": "github-code", "pt": "24", "api": [{"api_name": "hashlib.md5", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "timestamped.TimestampedModel", "line_number": 27, "usage_type": "name"}, {"api_name": "django.db.models.UUIDField", "line_number": 34, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 34, "usage_type": "name"}, {"api_name": "uuid.uuid4", "line_number": 34, "usage_type": "attribute"}, {"api_name": "django.db.models.FileField", "line_number": 35, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 35, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 36, "usage_type": "call"}, {"api_name": "issue.Issue", "line_number": 36, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 36, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 36, "usage_type": "attribute"}]} +{"seq_id": "27184543162", "text": "import numpy as np\nimport tensorflow as tf\nfrom networks import generator\nfrom options.test_options import TestOptions\nfrom tqdm import tqdm\nimport os\nimport cv2\nimport glob\n\nopt = TestOptions().parse()\nsave_path = os.path.join(opt.checkpoint_path, opt.save_path, opt.image_save_path)\nif not os.path.exists(save_path):\n os.makedirs(save_path)\ncheckpoint_path = opt.weight_path\n\nclass get_evaluation(object):\n def __init__(self, opt):\n self.opt = opt\n self.test_list = glob.glob(os.path.join(self.opt.test_path, '*.jpg'))\n\n\n def open_image(self, path, width, height, angle, isDown=True, isCrop=False, isResize=True, isflip=False, isRotate=False):\n img = cv2.imread(path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n if isCrop:\n img = img[20:198, 0:178]\n if isResize:\n img = cv2.resize(img, (width, height), interpolation=cv2.INTER_LINEAR)\n if isflip: # horizontal flip\n img = cv2.flip(img, 1)\n if isRotate:\n img_waf = img\n img = cv2.getRotationMatrix2D((width / 2, height / 2), angle, 1)\n img = cv2.warpAffine(img_waf, img, (width, height))\n if isDown:\n img_lr_2 = cv2.resize(img, (64, 64), interpolation=cv2.INTER_LINEAR)\n img_lr_4 = cv2.resize(img_lr_2, (32, 32), interpolation=cv2.INTER_LINEAR)\n img_lr = cv2.resize(img_lr_4, (16, 16), interpolation=cv2.INTER_LINEAR)\n\n img_lr = img_lr.astype(np.float32)\n img = img.astype(np.float32)\n\n return img, img_lr\n\n def get_psnr_ssim(self,):\n\n for image in tqdm(sorted(self.test_list)):\n name = image.split('/')[-1]\n name = name.split('.')[0]\n imgs = []\n imgs_lr = []\n\n img, img_lr = self.open_image(image, width=self.opt.crop_size, height=self.opt.crop_size,\n isDown=True,\n isCrop=False,\n isResize=True,\n isflip=False,\n isRotate=False,\n angle=0)\n\n imgs.append(img)\n imgs_lr.append(img_lr)\n\n imgs_hr = np.array(imgs)\n imgs_lr = np.array(imgs_lr)\n\n imgs_sr, edgex2, edgex4, edgex8 = sess.run([RGB, Step1_edge, Step2_edge, Step3_edge],\n feed_dict={X_hr: imgs_hr,\n X_lr: imgs_lr})\n\n\n cv2.imwrite(os.path.join(save_path, str(name) + '_SR' + '.jpg'), cv2.cvtColor(imgs_sr[0] / 255, cv2.COLOR_RGB2BGR) * 255)\n imgs_lr = cv2.resize(imgs_lr[0], (128, 128), interpolation=cv2.INTER_LINEAR)\n cv2.imwrite(os.path.join(save_path, str(name) + '_LR' + '.jpg'), cv2.cvtColor(imgs_lr / 255, cv2.COLOR_RGB2BGR) * 255)\n\n\nX_lr = tf.placeholder(tf.float32, shape=[opt.batchSize, opt.crop_size/8, opt.crop_size/8, opt.output_nc])\nX_hr = tf.placeholder(tf.float32, shape=[opt.batchSize, opt.crop_size, opt.crop_size, opt.output_nc])\n\ntraining = False\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nconfig.gpu_options.visible_device_list = opt.gpu_ids\n\nRGB, Step1_edge, Step2_edge, Step3_edge = generator(X_lr)\n\nsess = tf.Session(config=config)\nsess.run(tf.global_variables_initializer())\nsaver = tf.train.Saver(max_to_keep=None)\nsave_file = os.path.join(checkpoint_path, 'G_weight.ckpt')\nsaver.restore(sess, save_file)\nevaluation = get_evaluation(opt)\nevaluation.get_psnr_ssim()\nprint('\\n HR images are generated !')\n", "repo_name": "BenjaminJonghyun/EIPNet", "sub_path": "test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 3591, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 13, "dataset": "github-code", "pt": "24", "api": [{"api_name": "options.test_options.TestOptions", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 13, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 23, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 24, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 24, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.INTER_LINEAR", "line_number": 28, "usage_type": "attribute"}, {"api_name": "cv2.flip", "line_number": 30, "usage_type": "call"}, {"api_name": "cv2.getRotationMatrix2D", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.warpAffine", "line_number": 34, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 36, "usage_type": "call"}, {"api_name": "cv2.INTER_LINEAR", "line_number": 36, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 37, "usage_type": "call"}, {"api_name": "cv2.INTER_LINEAR", "line_number": 37, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 38, "usage_type": "call"}, {"api_name": "cv2.INTER_LINEAR", "line_number": 38, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 40, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 41, "usage_type": "attribute"}, {"api_name": "tqdm.tqdm", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 65, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path", "line_number": 72, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 72, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2BGR", "line_number": 72, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 73, "usage_type": "call"}, {"api_name": "cv2.INTER_LINEAR", "line_number": 73, "usage_type": "attribute"}, {"api_name": "cv2.imwrite", "line_number": 74, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 74, "usage_type": "call"}, {"api_name": "os.path", "line_number": 74, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 74, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2BGR", "line_number": 74, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 77, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 77, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 78, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 78, "usage_type": "attribute"}, {"api_name": "tensorflow.ConfigProto", "line_number": 82, "usage_type": "call"}, {"api_name": "networks.generator", "line_number": 86, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 88, "usage_type": "call"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 89, "usage_type": "call"}, {"api_name": "tensorflow.train.Saver", "line_number": 90, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 90, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 91, "usage_type": "call"}, {"api_name": "os.path", "line_number": 91, "usage_type": "attribute"}]} +{"seq_id": "36500403307", "text": "from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render,redirect\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom django.urls import reverse\nimport datetime\nfrom .trajectoryPredictor import TrajectoryPredictor\nimport json\nfrom random import randrange\nfrom django.http import HttpResponse\nfrom pyecharts.charts import Line\nfrom pyecharts import options as opts\nfrom .models import TrajectoryData,Station,TrajectoryRecord,NextMinTrajectory\nfrom django.contrib.auth.models import User,Group\nfrom django.contrib.auth import authenticate,login,logout\nfrom .manageStaion import addStation\nfrom .serializers import NextMinTrajectorySerializer\nfrom rest_framework import generics,status\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\n# Create your views here.\nclass TaskList(APIView):\n def get(self, request, format=None):\n tasks = NextMinTrajectory.objects.all()\n serializer = NextMinTrajectorySerializer(tasks, many=True)\n return Response(serializer.data)\n\n def post(self, request, format=None):\n print(request.data)\n nextMinPredictor = TrajectoryPredictor()\n try:\n longitude,latitude,altitude = float(request.POST[\"longitude\"]),float(request.POST[\"latitude\"]),float(request.POST[\"altitude\"])\n pressure, temperature, humid = float(request.POST[\"pressure\"]), float(request.POST[\"temperature\"]), float(request.POST[\"humid\"])\n nspeed, espeed, uspeed = float(request.POST[\"nspeed\"]), float(request.POST[\"espeed\"]), float(request.POST[\"uspeed\"])\n one_X = [pressure, temperature, humid, nspeed, espeed, uspeed, longitude, latitude, altitude]\n nextlongtitude,nextlatitude,nextaltitude=nextMinPredictor.makeNextMinPrediction(one_X)\n serializer = NextMinTrajectorySerializer(data={\"longitude\":nextlongtitude,\"latitude\":nextlatitude,\"altitude\":nextaltitude})\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n except:\n return Response(\"参数错误\", status=status.HTTP_400_BAD_REQUEST)\n\n\ndef index(request):\n content={}\n content['user']=request.user\n return render(request,'main/index.html',context=content)\n\ndef tologin(request):\n if request.method == 'POST':\n return login_check(request)\n else:\n return render(request, 'main/login.html',{'login_info':0})\n\ndef login_check(request):\n useremail = request.POST.get('username')\n password = request.POST.get('password')\n n=authenticate(username=useremail,password=password)\n print(n)\n if n:\n login(request,user=n)\n return HttpResponseRedirect(reverse('main:index'))\n return render(request, 'main/login.html')\n\ndef register(request):\n if request.method == 'POST':\n return register_check(request)\n else:\n return render(request, 'main/register.html')\n\ndef register_check(request):\n useremail = request.POST.get('email')\n password = request.POST.get('password')\n username=request.POST.get('username')\n u=User.objects.filter(email=useremail).first()\n if not u:\n User.objects.create_user(username=username,email=useremail,password=password)\n return HttpResponseRedirect(reverse('main:login'))\n return render(request, 'main/register.html')\n\ndef tologout(request):\n logout(request)\n return HttpResponseRedirect(reverse('main:index'))\n\n@login_required\ndef trajectory(request):\n content = {}\n content['user'] = request.user\n global trajectoryPredictor\n trajectoryPredictor=TrajectoryPredictor()\n\n stations = Station.objects.all()\n content[\"stations\"] = stations\n return render(request, 'main/trajectory.html',context=content)\n\n@login_required\ndef trajectorySeries(request):\n stationId, stationName = request.POST[\"stationId\"].split()\n stationId=int(stationId)\n pressure,temperature,humid=float(request.POST[\"pressure\"]),float(request.POST[\"temperature\"]),float(request.POST[\"humid\"])\n nspeed,espeed,uspeed=float(request.POST[\"nspeed\"]),float(request.POST[\"espeed\"]),float(request.POST[\"uspeed\"])\n stationObj=Station.objects.get(stationId=stationId)\n longitude,latitude=stationObj.longitude,stationObj.latitude\n altitude=float(request.POST[\"altitude\"])\n one_X=[pressure,temperature,humid,nspeed,espeed,uspeed,longitude,latitude,altitude]\n\n longitudes, latitudes, altitudes=trajectoryPredictor.makeAPrediction(one_X)\n longitudes.insert(0,longitude)\n latitudes.insert(0,latitude)\n altitudes.insert(0,latitude)\n content={}\n content['user'] = request.user\n content['longitudes']=longitudes\n content['latitudes']=latitudes\n content['altitudes']=altitudes\n content['stationName']=stationObj.stationName\n content['stationLongitude'],content['stationLatitude']=longitude,latitude\n return render(request, 'main/trajectoryMap.html',context=content)\n\n@login_required\ndef historyPage(request):\n return HttpResponseRedirect(reverse('main:manageStation'))\n\n@login_required\ndef manageStation(request):\n content = {}\n content['user'] = request.user\n stations = Station.objects.all()\n content[\"longitude\"] = [s.longitude for s in stations]\n content[\"latitude\"] = [s.latitude for s in stations]\n content[\"altitude\"] = [s.altitude for s in stations]\n content[\"name\"] = [str(s.stationId) + str(s.stationName) for s in stations]\n content[\"stations\"]=stations\n return render(request, 'main/manageStation.html', context=content)\n\n\n\n\n\n\n\n\n@login_required\ndef modelPage(request):\n return render(request, 'main/model.html')\n\n\n\n", "repo_name": "season0817/trajectory_prediction_web", "sub_path": "main/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 5785, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "rest_framework.views.APIView", "line_number": 21, "usage_type": "name"}, {"api_name": "models.NextMinTrajectory.objects.all", "line_number": 23, "usage_type": "call"}, {"api_name": "models.NextMinTrajectory.objects", "line_number": 23, "usage_type": "attribute"}, {"api_name": "models.NextMinTrajectory", "line_number": 23, "usage_type": "name"}, {"api_name": "serializers.NextMinTrajectorySerializer", "line_number": 24, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 25, "usage_type": "call"}, {"api_name": "trajectoryPredictor.TrajectoryPredictor", "line_number": 29, "usage_type": "call"}, {"api_name": "serializers.NextMinTrajectorySerializer", "line_number": 36, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 39, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 39, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 39, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 41, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 41, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 41, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 43, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 43, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 43, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 49, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 55, "usage_type": "call"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 60, "usage_type": "call"}, {"api_name": "django.contrib.auth.login", "line_number": 63, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 64, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 64, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 65, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 71, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.filter", "line_number": 77, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 77, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 77, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.create_user", "line_number": 79, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 79, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 79, "usage_type": "name"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 80, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 80, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 81, "usage_type": "call"}, {"api_name": "django.contrib.auth.logout", "line_number": 84, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 85, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 85, "usage_type": "call"}, {"api_name": "trajectoryPredictor.TrajectoryPredictor", "line_number": 92, "usage_type": "call"}, {"api_name": "models.Station.objects.all", "line_number": 94, "usage_type": "call"}, {"api_name": "models.Station.objects", "line_number": 94, "usage_type": "attribute"}, {"api_name": "models.Station", "line_number": 94, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 96, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 87, "usage_type": "name"}, {"api_name": "models.Station.objects.get", "line_number": 104, "usage_type": "call"}, {"api_name": "models.Station.objects", "line_number": 104, "usage_type": "attribute"}, {"api_name": "models.Station", "line_number": 104, "usage_type": "name"}, {"api_name": "trajectoryPredictor.makeAPrediction", "line_number": 109, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 120, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 98, "usage_type": "name"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 124, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 124, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 122, "usage_type": "name"}, {"api_name": "models.Station.objects.all", "line_number": 130, "usage_type": "call"}, {"api_name": "models.Station.objects", "line_number": 130, "usage_type": "attribute"}, {"api_name": "models.Station", "line_number": 130, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 136, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 126, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 147, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 145, "usage_type": "name"}]} +{"seq_id": "22241275513", "text": "import collections\n\nimport numpy as np\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.internal import prefer_static as ps\nfrom tensorflow_probability.python.internal import tensor_util\n\nfrom tensorflow.python.util import nest # pylint: disable=g-direct-tensorflow-import\n\n__all__ = [\n 'broadcast_structure',\n 'call_fn',\n 'cast_structure',\n 'expand_as_args',\n 'map_structure_with_named_args'\n]\n\n_is_namedtuple = nest._is_namedtuple # pylint: disable=protected-access\n\n\nUNSPECIFIED = object()\n\n_STRUCTURES_HAVE_MISMATCHING_TYPES = (\n \"The two structures don't have the same sequence type. Input structure has \"\n 'type {input_type}, while shallow structure has type {shallow_type}.'\n)\n\n_STRUCTURES_HAVE_MISMATCHING_LENGTHS = (\n \"The two structures don't have the same sequence length. Input \"\n 'structure has length {input_length}, while shallow structure has length '\n '{shallow_length}.'\n)\n\n_SHALLOW_TREE_HAS_INVALID_KEYS = (\n \"The shallow_tree's keys are not a subset of the input_tree's keys. The \"\n 'shallow_tree has the following keys that are not in the input_tree: {}.'\n)\n\n_IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ = (\n 'If shallow structure is a sequence, input must also be a sequence. '\n 'Input has type: {}.'\n)\n\n\ndef broadcast_structure(to_structure, from_structure):\n \"\"\"Broadcasts `from_structure` to `to_structure`.\n\n This is useful for downstream usage of `zip` or `tf.nest.map_structure`.\n\n If `from_structure` is a singleton, it is tiled to match the structure of\n `to_structure`. Note that the elements in `from_structure` are not copied if\n this tiling occurs.\n\n Args:\n to_structure: A structure.\n from_structure: A structure.\n\n Returns:\n new_from_structure: Same structure as `to_structure`.\n\n #### Example:\n\n ```python\n a_structure = ['a', 'b', 'c']\n b_structure = broadcast_structure(a_structure, 'd')\n # -> ['d', 'd', 'd']\n c_structure = tf.nest.map_structure(\n lambda a, b: a + b, a_structure, b_structure)\n # -> ['ad', 'bd', 'cd']\n ```\n \"\"\"\n from_parts = tf.nest.flatten(from_structure)\n if len(from_parts) == 1:\n from_structure = tf.nest.map_structure(lambda _: from_parts[0],\n to_structure)\n return from_structure\n\n\ndef cast_structure(value, structure):\n \"\"\"Cast a structure.\"\"\"\n if tf.nest.is_nested(structure):\n if _is_namedtuple(structure): # pylint: disable=protected-access\n return type(structure)(*value)\n else:\n return type(structure)(value)\n return value\n\n\ndef map_structure_with_named_args(func,\n *structures,\n _check_types=True, # pylint: disable=invalid-name\n _expand_composites=False, # pylint: disable=invalid-name\n _up_to=UNSPECIFIED, # pylint: disable=invalid-name\n **named_structures):\n \"\"\"Calls `nest.map_structure` with named args.\n\n Args:\n func: a callable that accepts one or more named arguments.\n *structures: Structures of arguments passed positionally to `func`.\n _check_types: Forwarded as `map_structure(..., check_types=_check_types)`.\n _expand_composites: Forwarded as\n `map_structure(..., expand_composites=_expand_composites)`.\n _up_to: Optional shallow structure to map up to. If provided,\n `nest.map_structure_up_to` is called rather than `nest.map_structure`.\n Default value: `UNSPECIFIED`.\n **named_structures: Structures of arguments passed by name to `func`.\n Returns:\n A new structure matching that of the input structures (or the shallow\n structure `_up_to`, if specified), in which each element is computed\n by applying `func` to the corresponding elements of the input structures.\n\n #### Examples\n\n ```python\n func = lambda x, y: 2 * x + 3 * y\n\n map_structure_with_named_args(func, [1, 2], [10, 11])\n # ==> [32, 37]\n\n map_structure_with_named_args(func, [1, 2], y=[10, 11])\n # ==> [32, 37]\n\n map_structure_with_named_args(func, x=[1, 2], y=[10, 11])\n # ==> [32, 37]\n\n map_structure_with_named_args(func, [10, 11], x=[1, 2])\n # ==> TypeError: () got multiple values for argument 'x'.\n ```\n\n \"\"\"\n names, named_values = (zip(*named_structures.items())\n if named_structures else ((), ()))\n # Wrapper function that takes positional args and passes keyword args.\n def kwarg_passing_fn(*leaf_values):\n return func(*leaf_values[:len(structures)],\n **dict(zip(names, leaf_values[len(structures):])))\n\n map_fn = (nest.map_structure if _up_to is UNSPECIFIED\n else lambda *a, **kw: nest.map_structure_up_to(_up_to, *a, **kw))\n return map_fn(kwarg_passing_fn,\n *(structures + named_values),\n check_types=_check_types,\n expand_composites=_expand_composites)\n\n\ndef map_structure_coroutine(coroutine,\n *structures,\n _expand_composites=False, # pylint: disable=invalid-name\n _up_to=UNSPECIFIED, # pylint: disable=invalid-name\n _with_tuple_paths=False, # pylint: disable=invalid-name\n **named_structures):\n # pylint: disable=g-doc-return-or-yield\n \"\"\"Invokes a coroutine multiple times with args from provided structures.\n\n This is semantically identical to `map_structure_with_named_args`, except\n that the first argument is a generator or coroutine (a callable whose body\n contains `yield` statements) rather than a function. This is invoked with\n arguments from the provided structure(s), thus defining an outer generator/\n coroutine that `yield`s values in sequence from each call to the inner\n `coroutine`.\n\n The argument structures are traversed, and the coroutine is invoked, in\n the order defined by `tf.nest.flatten`. A stripped-down implementation of\n the core logic is as follows:\n\n ```python\n def map_structure_coroutine(coroutine, *structures):\n flat_results = []\n for args in zip(*[tf.nest.flatten(s) for s in structures]):\n retval = yield from coroutine(*args)\n flat_results.append(retval)\n return tf.nest.pack_sequence_as(structures[0], flat_results)\n ```\n\n Args:\n coroutine: a generator/coroutine callable that accepts one or more named\n arguments.\n *structures: Structures of arguments passed positionally to `coroutine`.\n _expand_composites: Forwarded as\n `tf.nest.flatten(..., expand_composites=_expand_composites)`.\n _up_to: Optional shallow structure to map up to. If provided,\n `nest.map_structure_up_to` is called rather than `nest.map_structure`.\n Default value: `UNSPECIFIED`.\n _with_tuple_paths: Python bool. If `True`, the first argument to `coroutine`\n is a tuple path to the current leaf of the argument structure(s).\n Default value: `False`.\n **named_structures: Structures of arguments passed by name to `coroutine`.\n Yields:\n Values `yield`ed by each invocation of `coroutine`, with invocations in\n order corresponding to `tf.nest.flatten`.\n Returns:\n A new structure matching that of the input structures (or the shallow\n structure `_up_to`, if specified), in which each element is the return\n value from applying `coroutine` to the corresponding elements of the input\n structures.\n\n ## Examples\n\n A JointDistributionCoroutine may define a reusable submodel as its own\n coroutine, for example:\n\n ```python\n def horseshoe_prior(path, scale):\n # Auxiliary-variable representation of a horseshoe prior on sparse weights.\n name = ','.join(path)\n z = yield tfd.HalfCauchy(loc=0., scale=scale, name=name + '_z')\n w_noncentered = yield tfd.Normal(\n loc=0., scale=z, name=name + '_w_noncentered')\n return z * w_noncentered\n ```\n\n Note that this submodel yields two auxiliary random variables, and returns the\n sampled weight as a third value.\n\n Using `map_structure_coroutine` we can define a structure of such submodels,\n and collect their return values:\n\n ```\n @tfd.JointDistributionCoroutineAutoBatched\n def model():\n weights = yield from nest_util.map_structure_coroutine(\n horseshoe_prior,\n scale={'a': tf.ones([5]) * 100., 'b': tf.ones([2]) * 1e-2},\n _with_tuple_paths=True)\n # ==> `weights` is a dict of weight values.\n yield tfd.Deterministic(\n tf.sqrt(tf.norm(weights['a'])**2 + tf.norm(weights['b'])**2),\n name='weights_norm')\n\n print(model.event_shape)\n # ==> StructTuple(\n # a_z=TensorShape([5]),\n # a_w_noncentered=TensorShape([5]),\n # b_z=TensorShape([2]),\n # b_w_noncentered=TensorShape([2]),\n # weights_norm=TensorShape([]))\n ```\n \"\"\"\n # pylint: enable=g-doc-return-or-yield\n\n names, named_structure_values = (zip(*named_structures.items())\n if named_structures else ((), ()))\n all_structures = structures + named_structure_values\n result_structure = all_structures[0] if _up_to is UNSPECIFIED else _up_to\n flat_arg_structures = [\n nest.flatten_up_to(result_structure, s)\n for s in all_structures]\n\n if _with_tuple_paths:\n # Pass tuple paths as a first positional arg (before any provided args).\n flat_paths = nest.yield_flat_paths(result_structure,\n expand_composites=_expand_composites)\n flat_arg_structures = [list(flat_paths)] + flat_arg_structures\n num_positional_args = 1 + len(structures)\n else:\n num_positional_args = len(structures)\n\n flat_results = []\n for leaf_values in zip(*flat_arg_structures):\n result = yield from coroutine(\n *leaf_values[:num_positional_args],\n **dict(zip(names, leaf_values[num_positional_args:])))\n flat_results.append(result)\n\n return nest.pack_sequence_as(result_structure, flat_results)\n\n\ndef _force_leaf(struct):\n # Returns `True` if `struct` should be treated as a leaf, rather than\n # expanded/recursed into.\n return hasattr(struct, '_tfp_nest_expansion_force_leaf')\n\n\ndef _force_expand_as_args(struct):\n return hasattr(struct, '_tfp_nest_expansion_force_args')\n\n\ndef expand_as_args(args):\n \"\"\"Returns `True` if `args` should be expanded as `*args`.\"\"\"\n return ((isinstance(args, collections.abc.Sequence) and\n not _is_namedtuple(args) and not _force_leaf(args)) or\n _force_expand_as_args(args))\n\n\ndef _expand_as_kwargs(args):\n # Returns `True` if `args` should be expanded as `**args`.\n return isinstance(args, collections.abc.Mapping) and not _force_leaf(args)\n\n\ndef _maybe_convertible_to_tensor(struct):\n # Returns `True` if `struct` should be passed to `convert_to_tensor`.\n return not _is_namedtuple(struct) or _force_leaf(struct)\n\n\ndef _get_shallow_structure(struct):\n # Get a shallow version of struct where the children are replaced by\n # 'False'.\n return nest.get_traverse_shallow_structure(lambda s: s is struct, struct)\n\n\ndef _nested_convert_to_tensor(struct, dtype=None, name=None):\n \"\"\"Eagerly converts struct to Tensor, recursing upon failure.\"\"\"\n if dtype is not None or not tf.nest.is_nested(struct):\n return tf.convert_to_tensor(struct, dtype=dtype)\n\n if _maybe_convertible_to_tensor(struct):\n try:\n # Try converting the structure wholesale.\n return tf.convert_to_tensor(struct, name=name)\n except (ValueError, TypeError):\n # Unfortunately Eager/Graph mode don't agree on the error type.\n pass\n # Try converting all of its children.\n shallow_struct = _get_shallow_structure(struct)\n return nest.map_structure_up_to(\n shallow_struct, lambda s: _nested_convert_to_tensor(s, name=name), struct)\n\n\ndef convert_args_to_tensor(args, dtype=None, name=None):\n \"\"\"Converts `args` to `Tensor`s.\n\n Use this when it is necessary to convert user-provided arguments that will\n then be passed to user-provided callables.\n\n When `dtype` is `None` this function behaves as follows:\n\n 1A. If the top-level structure is a `list`/`tuple` but not a `namedtuple`,\n then it is left as is and only its elements are converted to `Tensor`s.\n\n 2A. The sub-structures are converted to `Tensor`s eagerly. E.g. if `args` is\n `{'arg': [[1], [2]]}` it is converted to\n `{'arg': tf.constant([[1], [2]])}`. If the conversion fails, it will\n attempt to recurse into its children.\n\n When `dtype` is specified, it acts as both a structural and numeric type\n constraint. `dtype` can be a single `DType`, `None` or a nested collection\n thereof. The conversion rule becomes as follows:\n\n 1B. The return value of this function will have the same structure as `dtype`.\n\n 2B. If the leaf of `dtype` is a concrete `DType`, then the corresponding\n sub-structure in `args` is converted to a `Tensor`.\n\n 3B. If the leaf of `dtype` is `None`, then the corresponding sub-structure is\n converted eagerly as described in the rule 2A above.\n\n Args:\n args: Arguments to convert to `Tensor`s.\n dtype: Optional structure/numeric type constraint.\n name: Optional name-scope to use.\n\n Returns:\n args: Converted `args`.\n\n #### Examples.\n\n This table shows some useful conversion cases. `T` means `Tensor`, `NT` means\n `namedtuple` and `CNT` means a `namedtuple` with a `Tensor`-conversion\n function registered.\n\n | args | dtype | output |\n |:------------:|:----------:|:------------------:|\n | `{\"a\": 1}` | `None` | `{\"a\": T(1)}` |\n | `T(1)` | `None` | `T(1)` |\n | `[1]` | `None` | `[T(1)]` |\n | `[1]` | `tf.int32` | `T([1])` |\n | `[[T(1)]]` | `None` | `[T([1])]` |\n | `[[T(1)]]` | `[[None]]` | `[[T(1)]]` |\n | `NT(1, 2)` | `None` | `NT(T(1), T(2))` |\n | `NT(1, 2)` | `tf.int32` | `T([1, 2])` |\n | `CNT(1, 2)` | `None` | `T(...)` |\n | `[[1, [2]]]` | `None` | `[[T(1), T([2])]]` |\n\n \"\"\"\n if dtype is None:\n if expand_as_args(args) or _expand_as_kwargs(args):\n shallow_args = _get_shallow_structure(args)\n return nest.map_structure_up_to(\n shallow_args, lambda s: _nested_convert_to_tensor(s, name=name), args)\n else:\n return _nested_convert_to_tensor(args, name=name)\n else:\n return nest.map_structure_up_to(\n dtype, lambda s, dtype: _nested_convert_to_tensor(s, dtype, name), args,\n dtype)\n\n\ndef call_fn(fn, args):\n \"\"\"Calls `fn` with `args`, possibly expanding `args`.\n\n Use this function when calling a user-provided callable using user-provided\n arguments.\n\n The expansion rules are as follows:\n\n `fn(*args)` if `args` is a `list` or a `tuple`, but not a `namedtuple`.\n `fn(**args)` if `args` is a `dict`.\n `fn(args)` otherwise.\n\n Args:\n fn: A callable that takes either `args` as an argument(s).\n args: Arguments to `fn`.\n\n Returns:\n result: Return value of `fn`.\n \"\"\"\n\n if expand_as_args(args):\n return fn(*args)\n elif _expand_as_kwargs(args):\n return fn(**args)\n else:\n return fn(args)\n\n\ndef convert_to_nested_tensor(value, dtype=None, dtype_hint=None,\n allow_packing=False, as_shape_tensor=False,\n convert_ref=True, name=None):\n \"\"\"Converts the given `value` to a (structure of) `Tensor`.\n\n This function converts Python objects of various types to a (structure of)\n `Tensor` objects. It accepts `Tensor` objects, numpy arrays, Python lists, and\n Python scalars.\n\n Args:\n value: An object whose structure matches that of `dtype` and for which each\n leaf has a registered `Tensor` conversion function.\n dtype: Optional structure of dtypes defining the structure of outputs and\n the `dtype` argument for nested calls to `convert_to_tensor`. If not\n nested, will be broadcasted to match the structure of `dtype_hint`.\n dtype_hint: Optional structure of dtypes defining the structure of outputs\n and the `dtype_hint` argument for nested calls to `convert_to_tensor`. If\n not nested, will be broadcasted to match the structure of `dtype`.\n allow_packing: Python `bool`, default `False`. If `True`, allow\n `convert_to_nested_tensor` to stack nested lists of Tensors along the\n leading dimension. Otherwise, raise.\n as_shape_tensor: Optional boolean when if `True` uses\n `prefer_static.convert_to_shape_tensor` instead of `tf.convert_to_tensor`\n for JAX compatibility.\n convert_ref: Python `bool`, default `True`. If `True`, convert objects with\n reference semantics to Tensor.\n name: Optional name to use if a new `Tensor` is created. If inputs are\n structured, elements are named accoring to '{name}/{path}.{to}.{elem}'.\n\n Returns:\n tensor: A (structure of) `Tensor` based on `value`.\n \"\"\"\n dtype_is_nested = nest.is_nested(dtype)\n hint_is_nested = nest.is_nested(dtype_hint)\n # If only one of dtype/dtype_hint is nested, broadcast the atom to match.\n if dtype_is_nested and hint_is_nested:\n nest.assert_same_structure(dtype, dtype_hint)\n elif dtype_is_nested:\n dtype_hint = broadcast_structure(dtype, dtype_hint)\n elif hint_is_nested:\n dtype = broadcast_structure(dtype_hint, dtype)\n\n # Call coerce_structure to force the argument structure to match dtype.\n value = coerce_structure(dtype, value)\n\n def convert_fn(path, value, dtype, dtype_hint, name=None):\n if not allow_packing and nest.is_nested(value) and any(\n # Treat arrays like Tensors for full parity in JAX backend.\n tf.is_tensor(x) or isinstance(x, np.ndarray)\n for x in nest.flatten(value)):\n raise NotImplementedError(('Cannot convert a structure of tensors to a '\n 'single tensor. Saw {} at path {}.'\n ).format(value, path))\n if as_shape_tensor:\n return ps.convert_to_shape_tensor(value, dtype, dtype_hint, name=name)\n elif 'KerasTensor' in str(type(value)):\n # This is a hack to detect symbolic Keras tensors to work around\n # b/206660667. The issue was that symbolic Keras tensors would\n # break the Bijector cache on forward/inverse log det jacobian,\n # because tf.convert_to_tensor is not a no-op thereon.\n return value\n elif convert_ref:\n return tf.convert_to_tensor(value, dtype, dtype_hint, name=name)\n else:\n return tensor_util.convert_nonref_to_tensor(\n value, dtype, dtype_hint, name=name)\n\n ### The following branches only affect naming.\n # For unstructured calls, just use the provided name.\n if not nest.is_nested(dtype):\n return convert_fn((), value, dtype, dtype_hint, name=name)\n # For structured calls where name is provided, include a scope and name\n # members according to \"{path}.{to}.{element}\".\n elif name is not None:\n with tf.name_scope(name):\n convert_with_name = lambda path, *args: convert_fn( # pylint: disable=g-long-lambda\n path, *args, name='.'.join(map(str, path)))\n return nest.map_structure_with_tuple_paths_up_to(\n dtype, convert_with_name, value, dtype, dtype_hint, check_types=False)\n # For structured calls without name, skip the scope and don't pass a\n # struct-path to convert-to-tensor.\n else:\n return nest.map_structure_with_tuple_paths_up_to(\n dtype, convert_fn, value, dtype, dtype_hint, check_types=False)\n\n\nclass _DotString(object):\n\n def __str__(self):\n return '.'\n\n def __repr__(self):\n return '.'\n\n\n_DOT = _DotString()\n\n\n# pylint: disable=protected-access\n# TODO(b/173044916): Support namedtuple interop in nest and remove this method.\ndef coerce_structure(shallow_tree, input_tree):\n \"\"\"Coerces the containers in `input_tree` to exactly match `shallow_tree`.\n\n This method largely parallels the behavior of `nest.assert_shallow_structure`,\n but allows `namedtuples` to be interpreted as either sequences or mappings.\n It returns a structure with the container-classes found in `shallow_tree`\n and the contents of `input_tree`, such that `shallow_tree` and `input_tree`\n may be used safely in downstream calls to `nest.map_structure_up_to`.\n\n Note: this method does not currently support `expand_composites`.\n\n Example Usage:\n ```python\n\n ab = collections.namedtuple('AB', 'a b')(0, 1)\n ba = collections.namedtuple('BA', 'b a')(2, 3)\n\n coerce_structure(ab, ba)\n # -> AB(a=3, b=2)\n ```\n\n Args:\n shallow_tree: A (shallow) structure to be populated.\n input_tree: A (parallel) structure of values.\n Returns:\n A structure with containers from shallow_tree and values from input_tree.\n Raises:\n ValueError: When nested sub-structures have differing lengths.\n ValueError: When nested sub-structures have different keys.\n TypeError: When `shallow_tree` is deeper than `input_tree`\n TypeError: When nested sub-structures are incompatible (e.g., list vs dict).\n \"\"\"\n try:\n return _coerce_structure(shallow_tree, input_tree)\n except (ValueError, TypeError) as e:\n str1 = str(nest.map_structure(lambda _: _DOT, shallow_tree))\n str2 = str(nest.map_structure(lambda _: _DOT, input_tree))\n raise type(e)(('{}\\n'\n 'Entire first structure:\\n{}\\n'\n 'Entire second structure:\\n{}'\n ).format(e, str1, str2))\n\n\ndef _coerce_structure(shallow_tree, input_tree):\n \"\"\"Implementation of coerce_structure.\"\"\"\n if not nest.is_nested(shallow_tree):\n return input_tree\n\n if not nest.is_nested(input_tree):\n raise TypeError(\n _IF_SHALLOW_IS_SEQ_INPUT_MUST_BE_SEQ.format(type(input_tree))\n )\n\n if len(input_tree) != len(shallow_tree):\n raise ValueError(\n _STRUCTURES_HAVE_MISMATCHING_LENGTHS.format(\n input_length=len(input_tree), shallow_length=len(shallow_tree)\n )\n )\n\n # Determine whether shallow_tree should be treated as a Mapping or a Sequence.\n # Namedtuples can be interpreted either way (but keys take precedence).\n _shallow_is_namedtuple = nest._is_namedtuple(shallow_tree) # pylint: disable=invalid-name\n _shallow_is_mapping = isinstance(shallow_tree, collections.abc.Mapping) # pylint: disable=invalid-name\n shallow_supports_keys = _shallow_is_namedtuple or _shallow_is_mapping\n shallow_supports_iter = _shallow_is_namedtuple or not _shallow_is_mapping\n\n # Branch-selection depends on both shallow and input container-classes.\n input_is_mapping = isinstance(input_tree, collections.abc.Mapping)\n if nest._is_namedtuple(input_tree):\n if shallow_supports_keys:\n lookup_branch = lambda k: getattr(input_tree, k)\n else:\n input_iter = nest._yield_value(input_tree)\n lookup_branch = lambda _: next(input_iter)\n elif shallow_supports_keys and input_is_mapping:\n lookup_branch = lambda k: input_tree[k]\n elif shallow_supports_iter and not input_is_mapping:\n input_iter = nest._yield_value(input_tree)\n lookup_branch = lambda _: next(input_iter)\n else:\n raise TypeError(\n _STRUCTURES_HAVE_MISMATCHING_TYPES.format(\n input_type=type(input_tree),\n shallow_type=(\n type(shallow_tree.__wrapped__)\n if hasattr(shallow_tree, '__wrapped__')\n else type(shallow_tree)\n ),\n )\n )\n\n flat_coerced = []\n needs_wrapping = type(shallow_tree) is not type(input_tree)\n for shallow_key, shallow_branch in nest._yield_sorted_items(shallow_tree):\n try:\n input_branch = lookup_branch(shallow_key)\n except (KeyError, AttributeError):\n # pylint: disable=raise-missing-from\n raise ValueError(_SHALLOW_TREE_HAS_INVALID_KEYS.format([shallow_key]))\n flat_coerced.append(_coerce_structure(shallow_branch, input_branch))\n # Keep track of whether nested elements have changed.\n needs_wrapping |= input_branch is not flat_coerced[-1]\n\n # Only create a new instance if containers differ or contents changed.\n return (nest._sequence_like(shallow_tree, flat_coerced)\n if needs_wrapping else input_tree)\n\n# pylint: enable=protected-access\n", "repo_name": "tensorflow/probability", "sub_path": "tensorflow_probability/python/internal/nest_util.py", "file_name": "nest_util.py", "file_ext": "py", "file_size_in_byte": 23975, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3997, "dataset": "github-code", "pt": "24", "api": [{"api_name": "tensorflow.python.util.nest._is_namedtuple", "line_number": 19, "usage_type": "attribute"}, {"api_name": "tensorflow.python.util.nest", "line_number": 19, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.nest.flatten", "line_number": 73, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.nest", "line_number": 73, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 73, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.nest.map_structure", "line_number": 75, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.nest", "line_number": 75, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 75, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.nest.is_nested", "line_number": 82, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.nest", "line_number": 82, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 82, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.map_structure", "line_number": 139, "usage_type": "attribute"}, {"api_name": "tensorflow.python.util.nest", "line_number": 139, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.map_structure_up_to", "line_number": 140, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 140, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.flatten_up_to", "line_number": 247, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 247, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.yield_flat_paths", "line_number": 252, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 252, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.pack_sequence_as", "line_number": 266, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 266, "usage_type": "name"}, {"api_name": "collections.abc", "line_number": 281, "usage_type": "attribute"}, {"api_name": "collections.abc", "line_number": 288, "usage_type": "attribute"}, {"api_name": "tensorflow.python.util.nest.get_traverse_shallow_structure", "line_number": 299, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 299, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.nest.is_nested", "line_number": 304, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.nest", "line_number": 304, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 304, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.convert_to_tensor", "line_number": 305, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 305, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.convert_to_tensor", "line_number": 310, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 310, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.map_structure_up_to", "line_number": 316, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 316, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.map_structure_up_to", "line_number": 379, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 379, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.map_structure_up_to", "line_number": 384, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 384, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.is_nested", "line_number": 449, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 449, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.is_nested", "line_number": 450, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 450, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.assert_same_structure", "line_number": 453, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 453, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.is_nested", "line_number": 463, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 463, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.is_tensor", "line_number": 465, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 465, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 465, "usage_type": "attribute"}, {"api_name": "tensorflow.python.util.nest.flatten", "line_number": 466, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 466, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.prefer_static.convert_to_shape_tensor", "line_number": 471, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.prefer_static", "line_number": 471, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.convert_to_tensor", "line_number": 479, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 479, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.tensor_util.convert_nonref_to_tensor", "line_number": 481, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.tensor_util", "line_number": 481, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.is_nested", "line_number": 486, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 486, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.name_scope", "line_number": 491, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 491, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.map_structure_with_tuple_paths_up_to", "line_number": 494, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 494, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.map_structure_with_tuple_paths_up_to", "line_number": 499, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 499, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.map_structure", "line_number": 552, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 552, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.map_structure", "line_number": 553, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 553, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.is_nested", "line_number": 562, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 562, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest.is_nested", "line_number": 565, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 565, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest._is_namedtuple", "line_number": 579, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 579, "usage_type": "name"}, {"api_name": "collections.abc", "line_number": 580, "usage_type": "attribute"}, {"api_name": "collections.abc", "line_number": 585, "usage_type": "attribute"}, {"api_name": "tensorflow.python.util.nest._is_namedtuple", "line_number": 586, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 586, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest._yield_value", "line_number": 590, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 590, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest._yield_value", "line_number": 595, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 595, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest._yield_sorted_items", "line_number": 611, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 611, "usage_type": "name"}, {"api_name": "tensorflow.python.util.nest._sequence_like", "line_number": 622, "usage_type": "call"}, {"api_name": "tensorflow.python.util.nest", "line_number": 622, "usage_type": "name"}]} +{"seq_id": "24268932861", "text": "from clrprint import clrprint\nfrom datetime import datetime\nimport pandas as pd\n\ndef str_to_time(string):\n return datetime.strptime(string, \"%Y-%m-%d\")\n\nCOLUMN_TYPES = [int, int, None, None, str, str_to_time]\nCOLUMN_NAMES = [\"Delivery\", \"CO\", \"Quantity\", \"Logos\", \"Operator\", \"Date\"]\n\ndef search_for(path, target, column=0, chunksize=1000, max_col=6):\n results = pd.DataFrame()\n cols = range(0, max_col)\n for chunk in pd.read_csv(\n path,\n encoding=\"ISO-8859-1\",\n chunksize=chunksize,\n usecols=COLUMN_NAMES\n ):\n\n df = chunk.fillna(0)\n df[\"Date\"] = pd.to_datetime(df[\"Date\"].astype(str), format='mixed', errors=\"ignore\")\n df[\"Delivery\"] = df[\"Delivery\"].astype('int64', errors=\"ignore\")\n df[\"CO\"] = df[\"CO\"].astype('int64', errors=\"ignore\")\n try:\n df[\"Date\"] = df[\"Date\"].dt.strftime('%m/%d/%Y %I:%M %p')\n except:\n pass\n\n target_oftype = COLUMN_TYPES[column](target)\n found = df.loc[df.iloc[:, column] == target_oftype]\n results = pd.concat([results, found], ignore_index=True, sort=False)\n return results\n\nif __name__ == \"__main__\":\n try:\n column = int(input(\"column: \"))\n except Exception as e:\n clrprint(\"[Error]\", f\"{e}\", sep=\"\", clr=\"r,w\")\n\n try:\n target = int(input(\"target: \"))\n except Exception as e:\n clrprint(\"[Error]\", f\"{e}\", sep=\"\", clr=\"r,w\")\n\n start_time = datetime.now()\n results = search_for('res\\index.csv', target, column)\n\n print(results)\n clrprint(\"[DONE] \", \"Search completed in \", f\"{datetime.now() - start_time}\", \".\", sep=\"\", clr=\"g,w,y,w\")\n", "repo_name": "xavmcc3/order-search", "sub_path": "search_csv.py", "file_name": "search_csv.py", "file_ext": "py", "file_size_in_byte": 1651, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "datetime.datetime.strptime", "line_number": 6, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 6, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 12, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 14, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 22, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 32, "usage_type": "call"}, {"api_name": "clrprint.clrprint", "line_number": 39, "usage_type": "call"}, {"api_name": "clrprint.clrprint", "line_number": 44, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 46, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 46, "usage_type": "name"}, {"api_name": "clrprint.clrprint", "line_number": 50, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 50, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 50, "usage_type": "name"}]} +{"seq_id": "27714981665", "text": "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nimport logging\nimport os\nimport sys\n\nimport sushy\n\nfrom sushy_oem_idrac import utils\n\nUSERNAME = 'root'\nPASSWORD = 'calvin'\n\nSERVICE_ROOT = 'http://demo.snmplabs.com:80/redfish/v1'\n\nSYSTEM_ID = '437XR1138R2'\n\nBOOT_DEVICE = sushy.VIRTUAL_MEDIA_CD\nBOOT_MODE = sushy.BOOT_SOURCE_MODE_BIOS\n\nBOOT_IMAGE = 'http://demo.snmplabs.com/mini.iso'\n\nLOG = logging.getLogger(__name__)\n\n\ndef main():\n \"\"\"Boot Dell node from virtual media device\"\"\"\n\n LOG.setLevel(logging.INFO)\n handler = logging.StreamHandler()\n handler.setLevel(logging.INFO)\n LOG.addHandler(handler)\n\n authenticator = sushy.auth.BasicAuth(USERNAME, PASSWORD)\n\n conn = sushy.Sushy(SERVICE_ROOT, verify=False, auth=authenticator)\n\n LOG.info('connected to %s', SERVICE_ROOT)\n\n system = conn.get_system(\n os.path.join(SERVICE_ROOT, 'Systems', SYSTEM_ID))\n\n LOG.info('read system resource %s', system.identity)\n\n for manager in system.managers:\n\n LOG.info('trying manager %s', manager.identity)\n\n for v_media in manager.virtual_media.get_members():\n if BOOT_DEVICE not in v_media.media_types:\n continue\n\n LOG.info(\n 'device %s is present at %s', BOOT_DEVICE, manager.identity)\n\n try:\n manager_oem = manager.get_oem_extension('Dell')\n\n except sushy.exceptions.OEMExtensionNotFoundError:\n LOG.info('Dell OEM not found')\n continue\n\n LOG.info('found Dell OEM extension at %s', manager.identity)\n\n if v_media.inserted:\n v_media.eject_media()\n\n LOG.info('ejected virtual media')\n\n v_media.insert_media(BOOT_IMAGE, inserted=True,\n write_protected=True)\n\n LOG.info('inserted boot image %s into virtual media', BOOT_IMAGE)\n\n # the caller (e.g. ironic) sets boot mode first, boot device second\n system.set_system_boot_source(\n BOOT_DEVICE, enabled=sushy.BOOT_SOURCE_ENABLED_CONTINUOUS,\n mode=BOOT_MODE)\n\n # with Dell, patching System tree does not work as expected\n # we need to reboot for the new boot mode to take effect\n utils.reboot_system(system)\n\n LOG.info('set boot mode to %s', BOOT_MODE)\n\n manager_oem.set_virtual_boot_device(\n BOOT_DEVICE, persistent=False, manager=manager, system=system)\n\n LOG.info('set boot device to %s', BOOT_DEVICE)\n\n # real caller should better not use our way to reboot\n utils.reboot_system(system)\n\n LOG.info('system rebooted')\n\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main())\n", "repo_name": "etingof/sushy-oem-idrac", "sub_path": "sushy_oem_idrac/tests/functional/vmedia_boot.py", "file_name": "vmedia_boot.py", "file_ext": "py", "file_size_in_byte": 3264, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sushy.VIRTUAL_MEDIA_CD", "line_number": 27, "usage_type": "attribute"}, {"api_name": "sushy.BOOT_SOURCE_MODE_BIOS", "line_number": 28, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 32, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 38, "usage_type": "attribute"}, {"api_name": "logging.StreamHandler", "line_number": 39, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 40, "usage_type": "attribute"}, {"api_name": "sushy.auth.BasicAuth", "line_number": 43, "usage_type": "call"}, {"api_name": "sushy.auth", "line_number": 43, "usage_type": "attribute"}, {"api_name": "sushy.Sushy", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "sushy.exceptions", "line_number": 68, "usage_type": "attribute"}, {"api_name": "sushy.BOOT_SOURCE_ENABLED_CONTINUOUS", "line_number": 86, "usage_type": "attribute"}, {"api_name": "sushy_oem_idrac.utils.reboot_system", "line_number": 91, "usage_type": "call"}, {"api_name": "sushy_oem_idrac.utils", "line_number": 91, "usage_type": "name"}, {"api_name": "sushy_oem_idrac.utils.reboot_system", "line_number": 101, "usage_type": "call"}, {"api_name": "sushy_oem_idrac.utils", "line_number": 101, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 109, "usage_type": "call"}]} +{"seq_id": "14798373595", "text": "import functools\nimport math\nimport gdb\n\nfrom kgdb import *\n\ndef foreach_proc_in_system():\n allproc = gdb.lookup_global_symbol(\"allproc\").value()\n for p in list_foreach(allproc, \"p_list\"):\n yield p\n\n\ndef _vm_map_entry_succ(entry):\n after = entry['right']\n if after['left']['start'] > entry['start']:\n while True:\n after = after['left']\n if after['left'] == entry:\n break\n return after\n\n\ndef foreach_vm_map_entry(map):\n entry = map['header']['right']\n while entry != map['header'].address:\n yield entry\n entry = _vm_map_entry_succ(entry)\n\n\ndef cpu_foreach():\n all_cpus = gdb.lookup_global_symbol(\"all_cpus\").value()\n bitsz = gdb.lookup_type(\"long\").sizeof * 8\n maxid = gdb.lookup_global_symbol(\"mp_maxid\").value()\n\n cpu = 0\n while cpu <= maxid:\n upper = cpu >> int(math.log(bitsz, 2))\n lower = 1 << (cpu & (bitsz - 1))\n if (all_cpus['__bits'][upper] & lower) != 0:\n yield cpu\n cpu = cpu + 1\n\n\n# XXX-MJ doesn't handle \"struct vm_object *\"\n# XXX-MJ assumes there's a return value, assumes one parameter\ndef ctype(t):\n def thunk(f):\n @functools.wraps(f)\n def wrap(a):\n if a.type != gdb.lookup_type(t):\n raise gdb.GdbError(\"parameter type mismatch: expected {} have {}\".format(t, a.type))\n return f(a)\n return wrap\n return thunk\n\n@ctype(\"vm_object_t\")\ndef findobj(obj):\n \"\"\"Find all userspace vm_map entries referencing the specific VM object.\"\"\"\n for p in foreach_proc_in_system():\n for entry in foreach_vm_map_entry(p['p_vmspace']['vm_map'].address):\n if not entry['object']['vm_object']:\n continue\n if entry['object']['vm_object'] == obj:\n gdb.add_history(p)\n gdb.add_history(entry)\n return p\n", "repo_name": "markjdb/scripts", "sub_path": "kgdb/util.py", "file_name": "util.py", "file_ext": "py", "file_size_in_byte": 1890, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "24", "api": [{"api_name": "gdb.lookup_global_symbol", "line_number": 8, "usage_type": "call"}, {"api_name": "gdb.lookup_global_symbol", "line_number": 31, "usage_type": "call"}, {"api_name": "gdb.lookup_type", "line_number": 32, "usage_type": "call"}, {"api_name": "gdb.lookup_global_symbol", "line_number": 33, "usage_type": "call"}, {"api_name": "math.log", "line_number": 37, "usage_type": "call"}, {"api_name": "gdb.lookup_type", "line_number": 50, "usage_type": "call"}, {"api_name": "gdb.GdbError", "line_number": 51, "usage_type": "call"}, {"api_name": "functools.wraps", "line_number": 48, "usage_type": "call"}, {"api_name": "gdb.add_history", "line_number": 64, "usage_type": "call"}, {"api_name": "gdb.add_history", "line_number": 65, "usage_type": "call"}]} +{"seq_id": "31126851278", "text": "import torch\n\nimport unittest\nfrom utils.data.load_dataset import get_train_test_dataset\nfrom gpytorch.kernels import MaternKernel\nfrom hyperparameter_tuning.utils.gpytorch.models.cglb import CGLB\nfrom hyperparameter_tuning.utils.gpytorch.models.variational_gpr import OPTIMIZE_INDUCING_INPUTS, NUM_INDUCING_INPUTS, SELECTION_SCHEME, \\\n CONDITIONAL_VARIANCE, MAX_NUM_CG_STEPS\nfrom hyperparameter_tuning.utils.gpytorch.scipy import Scipy\n\n\nclass CGLBTestCase(unittest.TestCase):\n def test_gradient(self):\n device = \"cpu\"\n X, y, _, _ = get_train_test_dataset(\"wilson_pumadyn32nm\")\n X = torch.as_tensor(X)\n y = torch.as_tensor(y)\n X = X.to(device)\n y = y.to(device)\n k = MaternKernel()\n k = k.to(device)\n k.train()\n sn2 = lambda: torch.tensor(1, dtype=torch.float64, device=device)\n mu = lambda X: torch.zeros(X.shape[0], dtype=torch.float64, device=device)\n cglb = CGLB(X, y, k, sn2, mu, args={OPTIMIZE_INDUCING_INPUTS: True, NUM_INDUCING_INPUTS: 2,\n SELECTION_SCHEME: CONDITIONAL_VARIANCE, MAX_NUM_CG_STEPS: 100},\n device=device)\n\n loss = cglb.create_loss_closure()\n\n if False:\n t = time()\n tt = thread_time()\n l = loss()\n print(f\"time: {time() - t}\")\n print(f\"thread_time: {thread_time() - tt}\")\n\n t = time()\n tt = thread_time()\n l.backward()\n print(f\"time: {time() - t}\")\n print(f\"thread_time: {thread_time() - tt}\")\n\n variables = tuple([v for _, v in cglb.get_named_tunable_parameters()])\n\n if False:\n t = time()\n tt = thread_time()\n l = loss()\n print(f\"time: {time() - t}\")\n print(f\"thread_time: {thread_time() - tt}\")\n\n t = time()\n tt = thread_time()\n grads = torch.autograd.grad(l, variables)\n print(f\"time: {time() - t}\")\n print(f\"thread_time: {thread_time() - tt}\")\n\n # exit()\n\n x0 = Scipy.pack(variables)\n\n def _torch_eval(x):\n values = Scipy.unpack(variables, x)\n Scipy.assign(variables, values)\n return loss()\n\n torch.autograd.gradcheck(_torch_eval, x0)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "repo_name": "SimonBartels/acgp", "sub_path": "experiments/tests/optimization/test_cglb.py", "file_name": "test_cglb.py", "file_ext": "py", "file_size_in_byte": 2374, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "unittest.TestCase", "line_number": 12, "usage_type": "attribute"}, {"api_name": "utils.data.load_dataset.get_train_test_dataset", "line_number": 15, "usage_type": "call"}, {"api_name": "torch.as_tensor", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.as_tensor", "line_number": 17, "usage_type": "call"}, {"api_name": "gpytorch.kernels.MaternKernel", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.float64", "line_number": 23, "usage_type": "attribute"}, {"api_name": "torch.zeros", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.float64", "line_number": 24, "usage_type": "attribute"}, {"api_name": "hyperparameter_tuning.utils.gpytorch.models.cglb.CGLB", "line_number": 25, "usage_type": "call"}, {"api_name": "hyperparameter_tuning.utils.gpytorch.models.variational_gpr.OPTIMIZE_INDUCING_INPUTS", "line_number": 25, "usage_type": "name"}, {"api_name": "hyperparameter_tuning.utils.gpytorch.models.variational_gpr.NUM_INDUCING_INPUTS", "line_number": 25, "usage_type": "name"}, {"api_name": "hyperparameter_tuning.utils.gpytorch.models.variational_gpr.SELECTION_SCHEME", "line_number": 26, "usage_type": "name"}, {"api_name": "hyperparameter_tuning.utils.gpytorch.models.variational_gpr.MAX_NUM_CG_STEPS", "line_number": 26, "usage_type": "name"}, {"api_name": "hyperparameter_tuning.utils.gpytorch.models.variational_gpr.CONDITIONAL_VARIANCE", "line_number": 26, "usage_type": "name"}, {"api_name": "torch.autograd.grad", "line_number": 55, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 55, "usage_type": "attribute"}, {"api_name": "hyperparameter_tuning.utils.gpytorch.scipy.Scipy.pack", "line_number": 61, "usage_type": "call"}, {"api_name": "hyperparameter_tuning.utils.gpytorch.scipy.Scipy", "line_number": 61, "usage_type": "name"}, {"api_name": "hyperparameter_tuning.utils.gpytorch.scipy.Scipy.unpack", "line_number": 64, "usage_type": "call"}, {"api_name": "hyperparameter_tuning.utils.gpytorch.scipy.Scipy", "line_number": 64, "usage_type": "name"}, {"api_name": "hyperparameter_tuning.utils.gpytorch.scipy.Scipy.assign", "line_number": 65, "usage_type": "call"}, {"api_name": "hyperparameter_tuning.utils.gpytorch.scipy.Scipy", "line_number": 65, "usage_type": "name"}, {"api_name": "torch.autograd.gradcheck", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 68, "usage_type": "attribute"}, {"api_name": "unittest.main", "line_number": 72, "usage_type": "call"}]} +{"seq_id": "31768658331", "text": "# boto3 is official AWS SDK for python\r\nimport boto3\r\n\r\n# Dynamo DB connection local connection\r\ndynamodb = boto3.resource('dynamodb', region_name='us-west-2', endpoint_url=\"http://localhost:8000\")\r\n\r\n\r\n# The Following data will be inserted in their respective tables\r\nBOARDS = [\r\n {\"board_id\": 1, \"name\": 'CIE'},\r\n {\"board_id\": 2, \"name\": 'Edexel'},\r\n {\"board_id\": 3, \"name\": 'IB'},\r\n]\r\n\r\nLEVELS = [\r\n {\"level_id\": 1, \"level_name\": 'A Levels'},\r\n {\"level_id\": 2, \"level_name\": 'GCE O Levels'},\r\n {\"level_id\": 3, \"level_name\": 'IG'},\r\n]\r\n\r\nQUESTION_TYPES = [\r\n {\"question_type_id\": 1, \"type\": 'MCQ'},\r\n {\"question_type_id\": 2, \"type\": 'Descriptive'},\r\n]\r\n\r\nSUBJECTS = [\r\n {\"subject_id\": 1, \"subject_name\": 'Chemistry'},\r\n {\"subject_id\": 2, \"subject_name\": 'Biology'},\r\n {\"subject_id\": 3, \"subject_name\": 'Physics'},\r\n {\"subject_id\": 4, \"subject_name\": 'cord_sci'},\r\n]\r\n\r\n# Creating Board Table\r\nboard_table = dynamodb.create_table(\r\n TableName='boards',\r\n KeySchema=[\r\n {\r\n 'AttributeName': 'board_id',\r\n 'KeyType': 'HASH' # Partition key\r\n },\r\n ],\r\n AttributeDefinitions=[\r\n {\r\n 'AttributeName': 'board_id',\r\n 'AttributeType': 'N'\r\n }\r\n ],\r\n # ProvisionedThroughput is ignored in Local Dynamo DB instance\r\n ProvisionedThroughput={\r\n 'ReadCapacityUnits': 10,\r\n 'WriteCapacityUnits': 10\r\n }\r\n)\r\n\r\nprint(\"Boards Table Created!\")\r\n\r\n# Board table data insertion\r\nfor i in range(len(BOARDS)):\r\n board_table.put_item(\r\n Item={\r\n \"board_id\": BOARDS[i][\"board_id\"],\r\n \"name\": BOARDS[i][\"name\"],\r\n }\r\n )\r\n pass\r\n\r\nprint(\"Data inserted in Boards Table\")\r\n\r\n# Creating Level Table\r\nlevel_table = dynamodb.create_table(\r\n TableName='levels',\r\n KeySchema=[\r\n {\r\n 'AttributeName': 'level_id',\r\n 'KeyType': 'HASH' # Partition key\r\n },\r\n ],\r\n AttributeDefinitions=[\r\n {\r\n 'AttributeName': 'level_id',\r\n 'AttributeType': 'N'\r\n }\r\n ],\r\n # ProvisionedThroughput is ignored in Local Dynamo DB instance\r\n ProvisionedThroughput={\r\n 'ReadCapacityUnits': 10,\r\n 'WriteCapacityUnits': 10\r\n }\r\n)\r\n\r\nprint(\"Levels Table Created!\")\r\n\r\n# Level table data insertion\r\nfor i in range(len(LEVELS)):\r\n level_table.put_item(\r\n Item={\r\n \"level_id\": LEVELS[i][\"level_id\"],\r\n \"level_name\": LEVELS[i][\"level_name\"],\r\n }\r\n )\r\n pass\r\n\r\nprint(\"Data inserted in Levels Table\")\r\n\r\n# Creating Level Table\r\nsubject_table = dynamodb.create_table(\r\n TableName='subjects',\r\n KeySchema=[\r\n {\r\n 'AttributeName': 'subject_id',\r\n 'KeyType': 'HASH' # Partition key\r\n },\r\n ],\r\n AttributeDefinitions=[\r\n {\r\n 'AttributeName': 'subject_id',\r\n 'AttributeType': 'N'\r\n }\r\n ],\r\n # ProvisionedThroughput is ignored in Local Dynamo DB instance\r\n ProvisionedThroughput={\r\n 'ReadCapacityUnits': 10,\r\n 'WriteCapacityUnits': 10\r\n }\r\n)\r\n\r\nprint(\"Levels Table Created!\")\r\n\r\n# Level table data insertion\r\nfor i in range(len(SUBJECTS)):\r\n subject_table.put_item(\r\n Item={\r\n \"subject_id\": SUBJECTS[i][\"subject_id\"],\r\n \"subject_name\": SUBJECTS[i][\"subject_name\"],\r\n }\r\n )\r\n pass\r\n\r\nprint(\"Data inserted in Subjects Table\")\r\n\r\n# Creating Question_Types Table\r\nquestion_type_table = dynamodb.create_table(\r\n TableName='question_types',\r\n KeySchema=[\r\n {\r\n 'AttributeName': 'question_type_id',\r\n 'KeyType': 'HASH' # Partition key\r\n },\r\n ],\r\n AttributeDefinitions=[\r\n {\r\n 'AttributeName': 'question_type_id',\r\n 'AttributeType': 'N'\r\n }\r\n ],\r\n # ProvisionedThroughput is ignored in Local Dynamo DB instance\r\n ProvisionedThroughput={\r\n 'ReadCapacityUnits': 10,\r\n 'WriteCapacityUnits': 10\r\n }\r\n)\r\n\r\nprint(\"Levels Table Created!\")\r\n\r\n# Level table data insertion\r\nfor i in range(len(QUESTION_TYPES)):\r\n question_type_table.put_item(\r\n Item={\r\n \"question_type_id\": QUESTION_TYPES[i][\"question_type_id\"],\r\n \"type\": QUESTION_TYPES[i][\"type\"],\r\n }\r\n )\r\n\r\nprint(\"Data inserted in QUESTION_TYPES Table\")\r\n\r\n# Creating Questions Table\r\nquestions_table = dynamodb.create_table(\r\n TableName='questions',\r\n KeySchema=[\r\n {\r\n 'AttributeName': 'question_id',\r\n 'KeyType': 'HASH' # Partition key\r\n },\r\n ],\r\n AttributeDefinitions=[\r\n {\r\n 'AttributeName': 'question_id',\r\n 'AttributeType': 'N'\r\n }\r\n ],\r\n # ProvisionedThroughput is ignored in Local Dynamo DB instance\r\n ProvisionedThroughput={\r\n 'ReadCapacityUnits': 10,\r\n 'WriteCapacityUnits': 10\r\n }\r\n)\r\n\r\nprint(\"Questions Table Created!\")\r\n", "repo_name": "mbshakoor/exam-paper-generator", "sub_path": "import-util/create_tables.py", "file_name": "create_tables.py", "file_ext": "py", "file_size_in_byte": 4984, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "boto3.resource", "line_number": 5, "usage_type": "call"}]} +{"seq_id": "7385236727", "text": "# 1313. Decompress Run-Length Encoded List\n\nfrom typing import List\n\nclass Solution:\n def decompressRLElist(self, nums: List[int]) -> List[int]:\n encoded = []\n idx = 0\n while idx < len(nums):\n for i in range(nums[idx]):\n encoded.append(nums[idx+1])\n idx += 2\n\n return encoded\n\nsol = Solution().decompressRLElist(nums = [1,2,3,4])\nprint(sol)", "repo_name": "yunyunyang/leetcode-py", "sub_path": "algorithms/easy/decompress_run-length_encoded_list.py", "file_name": "decompress_run-length_encoded_list.py", "file_ext": "py", "file_size_in_byte": 408, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "typing.List", "line_number": 6, "usage_type": "name"}]} +{"seq_id": "41702102030", "text": "from torchvision import transforms\nimport torchvision.datasets as datasets\nfrom PIL import Image\nimport torch.utils.data as data\nimport torch\nimport numpy as np\nimport cv2\nfrom tqdm import tqdm\nimport random\nimport albumentations\nimport json\n# from tuils.preprocess import *\nfrom torch.utils.data.dataloader import default_collate\n\nfpath = open('../configs/seg_path_configs.json', encoding='utf-8')\npath_data = json.load(fpath)\ntrain_img_path = path_data['train_img_path']\n\ndef generate_transforms(image_size):\n # MAX_SIZE = 448\n IMAGENET_SIZE = image_size\n\n train_transform = albumentations.Compose([\n \n albumentations.Resize(IMAGENET_SIZE, IMAGENET_SIZE),\n albumentations.OneOf([\n albumentations.RandomGamma(gamma_limit=(60, 120), p=0.9),\n albumentations.RandomBrightness(limit=0.2, p=0.9),\n albumentations.RandomContrast(limit=0.2, p=0.9),\n albumentations.CLAHE(clip_limit=4.0, tile_grid_size=(4, 4), p=0.9),\n ]),\n albumentations.OneOf([\n albumentations.Blur(blur_limit=4, p=1),\n albumentations.MotionBlur(blur_limit=4, p=1),\n albumentations.MedianBlur(blur_limit=4, p=1)\n ], p=0.5),\n albumentations.HorizontalFlip(p=0.5),\n albumentations.ShiftScaleRotate(shift_limit=0.2, scale_limit=0.2, rotate_limit=20, interpolation=cv2.INTER_LINEAR,border_mode=cv2.BORDER_CONSTANT, p=1),\n albumentations.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), max_pixel_value=255.0, p=1.0)\n\n ])\n\n val_transform = albumentations.Compose([\n albumentations.Resize(IMAGENET_SIZE, IMAGENET_SIZE),\n albumentations.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), max_pixel_value=255.0, p=1.0)\n ])\n\n return train_transform, val_transform\n\ndef rle2mask(rle, width, height):\n mask= np.zeros(width* height)\n array = np.asarray([int(x) for x in rle.split()])\n starts = array[0::2]\n lengths = array[1::2]\n\n current_position = 0\n for index, start in enumerate(starts):\n current_position += start\n mask[current_position:current_position+lengths[index]] = 255\n current_position += lengths[index]\n\n return mask.reshape(width, height)\n\n\n\nclass Siim_Dataset(data.Dataset):\n\n def __init__(self,\n df = None,\n name_list = None,\n transform = None\n ):\n self.df = df\n self.name_list = name_list\n self.transform = transform\n\n def __len__(self):\n return len(self.name_list)\n\n def __getitem__(self, idx):\n\n name = self.name_list[idx]\n image = cv2.imread(train_img_path + name)\n rle = self.df[self.df['ImageId']==(name.replace('.png', '').replace('.jpg', ''))]['EncodedPixels']\n if rle.values[0] == ' -1':\n masks = np.zeros((1024, 1024))\n else:\n masks = [np.expand_dims(rle2mask(x, 1024, 1024).T,axis=0) for x in rle]\n masks = np.sum(masks,0)\n masks[masks>1] = 1\n masks = masks[0, :, :]\n\n if self.transform is not None:\n augmented = self.transform(image=image, mask=masks)\n image = augmented['image'].transpose(2, 0, 1)\n masks = np.expand_dims(augmented['mask'], axis=0)\n\n return image, masks\n\nclass Siim_Dataset_cls_seg_train(data.Dataset):\n\n def __init__(self,\n df = None,\n name_list = None,\n transform = None\n ):\n self.df = df\n self.name_list = name_list\n self.transform = transform\n self.kernel = np.ones((3,3), np.uint8)\n\n def __len__(self):\n return len(self.name_list)\n\n def __getitem__(self, idx):\n\n name = self.name_list[idx]\n image = cv2.imread(train_img_path + name)\n rle = self.df[self.df['ImageId']==(name.replace('.png', '').replace('.jpg', ''))]['EncodedPixels']\n\n if rle.values[0] == '-1':\n masks = np.zeros((1024, 1024))\n cls_label = torch.FloatTensor([0])\n \n elif rle.values[0] == '2':\n masks = np.zeros((1024, 1024))\n cls_label = torch.FloatTensor([1]) \n else:\n\n masks = [np.expand_dims(rle2mask(x, 1024, 1024).T,axis=0) for x in rle]\n masks = np.sum(masks,0)\n masks[masks>1] = 1\n masks = masks[0, :, :]\n\n cls_label = torch.FloatTensor([1])\n\n if self.transform is not None:\n augmented = self.transform(image=image, mask=masks)\n image = augmented['image'].transpose(2, 0, 1)\n masks = np.expand_dims(augmented['mask'], axis=0)\n\n return image, masks, cls_label\n\n\nclass Siim_Dataset_cls_seg_val(data.Dataset):\n\n def __init__(self,\n df = None,\n name_list = None,\n transform = None\n ):\n self.df = df\n self.name_list = name_list\n self.transform = transform\n self.kernel = np.ones((3,3), np.uint8) \n\n def __len__(self):\n return len(self.name_list)\n\n def __getitem__(self, idx):\n\n name = self.name_list[idx]\n image = cv2.imread(train_img_path + name)\n rle = self.df[self.df['ImageId']==(name.replace('.png', '').replace('.jpg', ''))]['EncodedPixels']\n\n if rle.values[0] == '-1':\n masks = np.zeros((1024, 1024))\n cls_label = torch.FloatTensor([0])\n elif rle.values[0] == '2':\n masks = np.zeros((1024, 1024))\n cls_label = torch.FloatTensor([1]) \n else:\n masks = [np.expand_dims(rle2mask(x, 1024, 1024).T,axis=0) for x in rle]\n masks = np.sum(masks,0)\n masks[masks>1] = 1\n masks = masks[0, :, :]\n\n cls_label = torch.FloatTensor([1])\n\n if self.transform is not None:\n augmented = self.transform(image=image, mask=masks)\n image = augmented['image'].transpose(2, 0, 1)\n masks = np.expand_dims(augmented['mask'], axis=0)\n\n return image, masks, cls_label\n\n\n\ndef generate_dataset_loader_cls_seg(df_all, c_train, train_transform, train_batch_size, c_val, val_transform, val_batch_size, workers):\n\n train_dataset = Siim_Dataset_cls_seg_train(df_all, c_train, train_transform)\n val_dataset = Siim_Dataset_cls_seg_val(df_all, c_val, val_transform)\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=train_batch_size, \n shuffle=True,\n num_workers=workers,\n pin_memory=True,\n drop_last=True)\n\n val_loader = torch.utils.data.DataLoader(\n val_dataset,\n batch_size=val_batch_size, \n shuffle=False,\n num_workers=workers,\n pin_memory=True,\n drop_last=False)\n\n return train_loader, val_loader\n", "repo_name": "SeuTao/kaggle-competition-solutions", "sub_path": "SIIM19_Pneumothorax_Segmentation_2nd_solution/src_unet_cls/dataset/dataset.py", "file_name": "dataset.py", "file_ext": "py", "file_size_in_byte": 6894, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 238, "dataset": "github-code", "pt": "24", "api": [{"api_name": "json.load", "line_number": 16, "usage_type": "call"}, {"api_name": "albumentations.Compose", "line_number": 23, "usage_type": "call"}, {"api_name": "albumentations.Resize", "line_number": 25, "usage_type": "call"}, {"api_name": "albumentations.OneOf", "line_number": 26, "usage_type": "call"}, {"api_name": "albumentations.RandomGamma", "line_number": 27, "usage_type": "call"}, {"api_name": "albumentations.RandomBrightness", "line_number": 28, "usage_type": "call"}, {"api_name": "albumentations.RandomContrast", "line_number": 29, "usage_type": "call"}, {"api_name": "albumentations.CLAHE", "line_number": 30, "usage_type": "call"}, {"api_name": "albumentations.OneOf", "line_number": 32, "usage_type": "call"}, {"api_name": "albumentations.Blur", "line_number": 33, "usage_type": "call"}, {"api_name": "albumentations.MotionBlur", "line_number": 34, "usage_type": "call"}, {"api_name": "albumentations.MedianBlur", "line_number": 35, "usage_type": "call"}, {"api_name": "albumentations.HorizontalFlip", "line_number": 37, "usage_type": "call"}, {"api_name": "albumentations.ShiftScaleRotate", "line_number": 38, "usage_type": "call"}, {"api_name": "cv2.INTER_LINEAR", "line_number": 38, "usage_type": "attribute"}, {"api_name": "cv2.BORDER_CONSTANT", "line_number": 38, "usage_type": "attribute"}, {"api_name": "albumentations.Normalize", "line_number": 39, "usage_type": "call"}, {"api_name": "albumentations.Compose", "line_number": 43, "usage_type": "call"}, {"api_name": "albumentations.Resize", "line_number": 44, "usage_type": "call"}, {"api_name": "albumentations.Normalize", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.utils.data.Dataset", "line_number": 66, "usage_type": "attribute"}, {"api_name": "torch.utils.data", "line_number": 66, "usage_type": "name"}, {"api_name": "cv2.imread", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.utils.data.Dataset", "line_number": 100, "usage_type": "attribute"}, {"api_name": "torch.utils.data", "line_number": 100, "usage_type": "name"}, {"api_name": "numpy.ones", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 110, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 122, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 126, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 131, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 140, "usage_type": "call"}, {"api_name": "torch.utils.data.Dataset", "line_number": 145, "usage_type": "attribute"}, {"api_name": "torch.utils.data", "line_number": 145, "usage_type": "name"}, {"api_name": "numpy.ones", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 155, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 167, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 168, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 170, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 171, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 173, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 174, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 178, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 183, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 194, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 194, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 202, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 202, "usage_type": "attribute"}]} +{"seq_id": "33032791636", "text": "from services.trakt import TraktService\nfrom services.plex import PlexService\nfrom plexapi.video import Video as PlexVideo\nfrom models import Movie, Availability\nfrom typing import List\nimport logging\n\n_logger = logging.getLogger(__name__)\n_logger.setLevel(logging.INFO)\n\nclass MediaService:\n def __init__(self, trakt_config: dict, plex_config: dict, secrets_manager_endpoint: str) -> None:\n self.trakt_service = TraktService(trakt_config.get('secret_name'), secrets_manager_endpoint)\n self.plex_service = PlexService(plex_config)\n\n def recommend_movie(self) -> Movie:\n trakt_movie = self.trakt_service.get_recommended_movie()\n movie: Movie = Movie.from_trakt(trakt_movie)\n movie.get_availability(self)\n return movie\n \n def search(self, query: str, media_type: str, limit: int) -> List[Movie]:\n results: List[PlexVideo] = self.plex_service.search_media(query, media_type, limit)\n media_list: List[Movie] = []\n if (len(results) == 0):\n return media_list\n\n platform_exclusions = ['netflix-basic-with-ads']\n for media in results:\n availability_list: List[Availability] = self.plex_service.get_media_availability(media)\n availability: List[Availability] = list(filter(lambda x: x.platform not in platform_exclusions, availability_list))\n movie: Movie = Movie.from_plex(media)\n movie.availability = availability\n media_list.append(movie)\n return media_list\n \n def get_media_availability(self, media: Movie) -> None:\n results: List[Movie] = self.search(f'{media.title} + ({media.year})', 1)\n if results:\n media.availability = results[0].availability\n\n\n", "repo_name": "mdinicola/watch-wizard", "sub_path": "watch_wizard/services/media.py", "file_name": "media.py", "file_ext": "py", "file_size_in_byte": 1739, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 8, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 9, "usage_type": "attribute"}, {"api_name": "services.trakt.TraktService", "line_number": 13, "usage_type": "call"}, {"api_name": "services.plex.PlexService", "line_number": 14, "usage_type": "call"}, {"api_name": "models.Movie", "line_number": 18, "usage_type": "name"}, {"api_name": "models.Movie.from_trakt", "line_number": 18, "usage_type": "call"}, {"api_name": "models.Movie", "line_number": 16, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 23, "usage_type": "name"}, {"api_name": "plexapi.video.Video", "line_number": 23, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 24, "usage_type": "name"}, {"api_name": "models.Movie", "line_number": 24, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 30, "usage_type": "name"}, {"api_name": "models.Availability", "line_number": 30, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 31, "usage_type": "name"}, {"api_name": "models.Availability", "line_number": 31, "usage_type": "name"}, {"api_name": "models.Movie", "line_number": 32, "usage_type": "name"}, {"api_name": "models.Movie.from_plex", "line_number": 32, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 22, "usage_type": "name"}, {"api_name": "models.Movie", "line_number": 22, "usage_type": "name"}, {"api_name": "models.Movie", "line_number": 37, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 38, "usage_type": "name"}, {"api_name": "models.Movie", "line_number": 38, "usage_type": "name"}]} +{"seq_id": "33199894256", "text": "#!/usr/bin/env python\n\nfrom __future__ import print_function\nimport os.path\nimport sys\nfrom optparse import OptionParser\nfrom pyfiglet import Figlet\nfrom subprocess import Popen, PIPE\ntry:\n from colorama import init\n init(strip=not sys.stdout.isatty())\n from termcolor import cprint\nexcept:\n def cprint(text, color):\n print(text)\n\n__version__ = '0.1'\n\ndef fail(text):\n cprint(text, 'red')\n\ndef win(text):\n cprint(text, 'green')\n\ndef dump(text):\n for line in text.split('\\n'):\n print(repr(line))\n\nclass Test(object):\n def __init__(self, opts):\n self.opts = opts\n self.ok = 0\n self.fail = 0\n self.failed = []\n self.oked = []\n # known bugs...\n self.skip = ['runic', 'pyramid', 'eftifont', 'DANC4', 'dietcola']\n # Toilet fonts that we don't handle identically, yet\n self.skip += ['emboss', 'emboss2', 'future', 'letter', 'pagga',\n 'smblock', 'smbraille', 'wideterm']\n # fonts that throw Unicode decoding errors\n self.skip += ['dosrebel', 'konto', 'kontoslant']\n # zip fonts we don't support\n self.skip += ['ascii12', 'ascii9', 'bigascii12', 'bigascii9',\n 'bigmono12', 'bigmono9', 'mono12', 'mono9', 'smascii12',\n 'smascii9', 'smmono12', 'smmono9']\n # what looks like the same bug, but in non-zip fonts\n self.skip += ['dwhistled', 'gradient']\n # failing tests:\n self.skip += ['crawford2', 'konto_slant', 'danc4', 'diet_cola',\n 'stronger_than_all']\n\n self.f = Figlet()\n\n def outputUsingFigletorToilet(self, text, font, fontpath):\n if os.path.isfile(fontpath + '.flf'):\n cmd = ('figlet', '-d', 'pyfiglet/fonts', '-f', font, text)\n elif os.path.isfile(fontpath + '.tlf'):\n cmd = ('toilet', '-d', 'pyfiglet/fonts', '-f', font, text)\n else:\n raise Exception('Missing font file: {}'.format(fontpath))\n\n p = Popen(cmd, bufsize=4096, stdout=PIPE)\n try:\n outputFiglet = p.communicate()[0].decode('utf8')\n except UnicodeDecodeError as e:\n print(\"Unicode Error handling font {}\".format(font))\n outputFiglet = ''\n return outputFiglet\n\n def validate_font_output(self, font, outputFiglet, outputPyfiglet):\n if outputPyfiglet == outputFiglet:\n win('[OK] %s' % font)\n self.ok += 1\n self.oked.append(font)\n return\n\n fail('[FAIL] %s' % font)\n self.fail += 1\n self.failed.append(font)\n self.show_result(outputFiglet, outputPyfiglet, font)\n\n def show_result(self, outputFiglet, outputPyfiglet, font):\n if self.opts.show is True:\n print('[PYTHON] *** %s\\n\\n' % font)\n dump(outputPyfiglet)\n print('[FIGLET] *** %s\\n\\n' % font)\n dump(outputFiglet)\n raw_input()\n\n def check_font(self, text, font):\n if font in self.skip:\n return\n fontpath = os.path.join('pyfiglet', 'fonts', font)\n\n self.f.setFont(font=font)\n\n outputPyfiglet = self.f.renderText(text)\n outputFiglet = self.outputUsingFigletorToilet(text, font, fontpath)\n\n # Our TLF rendering isn't perfect, yet\n strict = os.path.isfile(fontpath + '.flf')\n if not strict:\n outputPyfiglet = outputPyfiglet.strip('\\n')\n outputFiglet = outputFiglet.strip('\\n')\n\n self.validate_font_output(font, outputFiglet, outputPyfiglet)\n\n\n def check_text(self, text):\n for font in self.f.getFonts():\n self.check_font(text, font)\n\n def check_result(self):\n print('OK = %d, FAIL = %d' % (self.ok, self.fail))\n if len(self.failed) > 0:\n print('FAILED = %s' % repr(self.failed))\n\n return self.failed, self.oked\n\ndef banner(text):\n cprint(Figlet().renderText(text), \"blue\")\n\ndef main():\n parser = OptionParser(version=__version__)\n\n parser.add_option('-s', '--show', action='store_true', default=False,\n help='pause at each failure and compare output '\n '(default: %default)')\n\n opts, args = parser.parse_args()\n test = Test(opts)\n banner(\"TESTING one word\")\n test.check_text(\"foo\")\n banner(\"TESTING cut at space\")\n test.check_text(\"This is a very long text with many spaces and little words\")\n banner(\"TESTING cut at last char\")\n test.check_text(\"Averylongwordthatwillbecutatsomepoint I hope\")\n banner(\"TESTING explicit new line\")\n test.check_text(\"this text\\nuse new line\")\n if len(test.check_result()[0]) == 0:\n return 0\n else:\n return 1\n\n\nif __name__ == '__main__':\n sys.exit(main())\n", "repo_name": "pwaller/pyfiglet", "sub_path": "pyfiglet/test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 4766, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1241, "dataset": "github-code", "pt": "24", "api": [{"api_name": "colorama.init", "line_number": 11, "usage_type": "call"}, {"api_name": "sys.stdout.isatty", "line_number": 11, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 11, "usage_type": "attribute"}, {"api_name": "termcolor.cprint", "line_number": 20, "usage_type": "call"}, {"api_name": "termcolor.cprint", "line_number": 23, "usage_type": "call"}, {"api_name": "pyfiglet.Figlet", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path.path.isfile", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 56, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 56, "usage_type": "name"}, {"api_name": "os.path.path.isfile", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 58, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 58, "usage_type": "name"}, {"api_name": "subprocess.Popen", "line_number": 63, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 63, "usage_type": "name"}, {"api_name": "os.path.path.join", "line_number": 94, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 94, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 94, "usage_type": "name"}, {"api_name": "os.path.path.isfile", "line_number": 102, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 102, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 102, "usage_type": "name"}, {"api_name": "termcolor.cprint", "line_number": 122, "usage_type": "call"}, {"api_name": "pyfiglet.Figlet", "line_number": 122, "usage_type": "call"}, {"api_name": "optparse.OptionParser", "line_number": 125, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 148, "usage_type": "call"}]} +{"seq_id": "74549552381", "text": "import pandas as pd\nfrom datetime import datetime, timedelta\n\ndef change_wrongly_formatted_csv(input_file):\n with open(input_file) as file:\n data = file.read()\n data = data.replace(\";\", \",\")\n with open(input_file, \"w\") as file:\n file.write(data)\n\n# Converting datetime\ndef convert_timestamp_to_datetime(timestamp, before_or_after):\n date = timestamp.split(\"T\")[0]\n splitted_date = date.split(\"-\")\n time = timestamp.split(\"T\")[1]\n splitted_time = time.split(\"+\")[0].split(\":\")\n t = datetime(int(splitted_date[0]), int(splitted_date[1]), int(splitted_date[2]), int(splitted_time[0]), int(splitted_time[1]))\n data = {\"Timestamp\": t}\n data[before_or_after + \"hour\"] = t.hour\n data[before_or_after + \"month\"] = t.month\n data[before_or_after + \"year\"] = t.year\n data[before_or_after + \"day_of_week\"] = t.weekday()\n data[before_or_after + \"day_of_month\"] = t.day\n data[before_or_after + \"day_of_year\"] = t.timetuple().tm_yday\n return data\n\ntrafikk_data_path = \"trafikk.csv\"\n# change_wrongly_formatted_csv(trafikk_data_path)\ntrafikk_data = pd.read_csv(trafikk_data_path)\ntrafikk_data[\"output_volum\"] = 0\n\ntest_timestamp = \"2019-02-27T01:00+01:00\"\nfor i in trafikk_data.index:\n fra_time = trafikk_data.at[i, \"Fra\"]\n data_dict = convert_timestamp_to_datetime(fra_time, \"fra_\")\n for key, value in data_dict.items():\n trafikk_data.at[i, key] = value\n\ntrafikk_data = trafikk_data.drop([\"Navn\", \"Vegreferanse\", \"Fra\", \"Til\",\n \"Ikke gyldig lengde\", \"Lengdedekningsgrad (%)\", \"Felt\", \"Felt gyldig fra\",\n \"Felt gyldig til\", \"< 5\", \"6m\", \"> 5\", \"6m.1\", \"5\", \"6m - 7\", \"6m.2\", \"7\",\n \"6m - 12\", \"5m\", \"12\", \"5m - 16\", \"0m\", \"16\", \"0m - 24\", \"0m.1\", \"> 24\", \"0m.2\"], axis=1)\n\nnumber_of_hours_to_subtract = 6\n\nfor i in trafikk_data.index:\n for j in trafikk_data.index:\n before_data = trafikk_data.at[i, \"Timestamp\"]\n after_data = trafikk_data.at[j, \"Timestamp\"]\n t= datetime()\n timedelta(hours=6)\n before_data\n\n all_match = True\n for column in trafikk_data.columns.values:\n if(column == \"hour\" and trafikk_data.at[i, column] - 6 == trafikk_data.at[j, column]):\n pass\n elif(trafikk_data.at[i, column] == trafikk_data.at[j, column]):\n pass\n", "repo_name": "magmkri/hakathon-brain", "sub_path": "trafikk_data_with_own_model.py", "file_name": "trafikk_data_with_own_model.py", "file_ext": "py", "file_size_in_byte": 2303, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "datetime.datetime", "line_number": 17, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 29, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 50, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 51, "usage_type": "call"}]} +{"seq_id": "72951116861", "text": "\"\"\"\nThis module contains the Branch class (one branch of the tree)\nand the Nodes class name\n\"\"\"\nfrom __future__ import annotations\nimport numpy as np\nimport logging\nfrom scipy.spatial import cKDTree\nfrom .mesh import InvalidNodeError, Mesh\n\nlogger = logging.getLogger(__name__)\n\n\nclass Branch:\n \"\"\"Class that contains a branch of the fractal tree\n\n Args:\n mesh:\n an object of the mesh class, where the fractal tree will grow\n initial_node (int):\n initial node to grow the branch. This is an index that refers\n to a node in the nodes.nodes array.\n initial_direction (array):\n initial direction to grow the branch. In general, it refers to\n the direction of the last segment of the mother brach.\n initial_triangle (int):\n the index of triangle of the mesh where the initial_node sits.\n l (float):\n total length of the branch\n angle (float):\n angle (rad) with respect to the initial_direction\n in the plane of the initial_triangle triangle\n repulsitivity (float):\n repulsitivity parameter. Controls how much the branches repel each other.\n nodes:\n the object of the class nodes that contains all the\n nodes of the existing branches.\n brother_nodes (list):\n the nodes of the brother and mother branches, to be excluded\n from the collision detection between branches.\n num_segments (int):\n number of segments to divide the branch.\n\n\n Attributes:\n child (list):\n contains the indexes of the child branches.\n It is not assigned when created.\n dir (array):\n vector direction of the last segment of the branch.\n nodes (list):\n contains the node indices of the branch. The node coordinates can\n be retrieved using nodes.nodes[i]\n triangles (list):\n contains the indices of the triangles from the mesh where every\n node of the branch lies.\n tri (int):\n triangle index where last node sits.\n growing (bool):\n False if the branch collide or is out of the surface. True otherwise.\n\n \"\"\"\n\n def __init__(\n self,\n mesh: Mesh,\n initial_node: int,\n initial_direction: np.ndarray,\n initial_triangle: int,\n length: float,\n angle: float,\n repulsitivity: float,\n nodes: \"Nodes\",\n brother_nodes: list[int],\n num_segments: int,\n ):\n self.child = [0, 0]\n self.dir = np.array([0.0, 0.0, 0.0])\n self.nodes = []\n self.triangles = []\n\n self.queue = []\n self.growing = True\n\n nodes.update_collision_tree(brother_nodes)\n self.nodes.append(initial_node)\n self.queue.append(nodes.nodes[initial_node])\n self.triangles.append(initial_triangle)\n grad = nodes.gradient(self.queue[0])\n\n self._initialize_direction(\n init_normal=mesh.normals[initial_triangle],\n initial_direction=initial_direction,\n angle=angle,\n )\n self._update_direction(repulsitivity=repulsitivity, grad=grad)\n\n for i in range(1, num_segments):\n self._grow(mesh, length, i, num_segments, nodes, repulsitivity)\n if not self.growing:\n break\n\n self.nodes += nodes.add_nodes(self.queue[1:])\n if not self.growing:\n nodes.end_nodes.append(self.nodes[-1])\n\n self.tri = self.triangles[-1]\n\n def _initialize_direction(\n self, init_normal: np.ndarray, initial_direction: np.ndarray, angle: float\n ) -> None:\n inplane = -np.cross(initial_direction, init_normal)\n self.dir = np.cos(angle) * initial_direction + np.sin(angle) * inplane\n self.dir /= np.linalg.norm(self.dir)\n\n def _grow(\n self,\n mesh: Mesh,\n length: float,\n i: int,\n num_segments: int,\n nodes: \"Nodes\",\n repulsitivity: float,\n ) -> None:\n intriangle = self.add_node_to_queue(\n mesh, self.queue[i - 1], self.dir * length / num_segments\n )\n if not intriangle:\n logger.debug(f\"Point {i} not in triangle\")\n self.growing = False\n return\n\n collision = nodes.collision(self.queue[i])\n if collision[1] < length / 5.0:\n logger.debug(f\"Collision {i}: {collision}\")\n self.growing = False\n self.queue.pop()\n self.triangles.pop()\n return\n\n grad = nodes.gradient(self.queue[i])\n normal = mesh.normals[self.triangles[i], :]\n # Project the gradient to the surface\n grad = grad - (np.dot(grad, normal)) * normal\n self._update_direction(repulsitivity=repulsitivity, grad=grad)\n\n def _update_direction(self, repulsitivity: float, grad: np.ndarray) -> None:\n self.dir = (self.dir + repulsitivity * grad) / np.linalg.norm(\n self.dir + repulsitivity * grad\n )\n\n def add_node_to_queue(\n self, mesh: Mesh, initial_node: np.ndarray, dir: np.ndarray\n ) -> bool:\n \"\"\"Functions that projects a node in the mesh surface\n and it to the queue is it lies in the surface.\n\n Args:\n mesh:\n an object of the mesh class, where the fractal tree will grow\n initial_node (array):\n vector that contains the coordinates of the\n last node added in the branch.\n dir (array):\n vector that contains the direction from the initial_node\n to the node to project.\n\n Return:\n success (bool):\n true if the new node is in the triangle.\n\n \"\"\"\n try:\n point, triangle = mesh.project_new_point(initial_node + dir)\n except InvalidNodeError:\n return False\n\n success = False\n if triangle >= 0:\n self.queue.append(point)\n self.triangles.append(triangle)\n success = True\n\n return success\n\n\nclass Nodes:\n \"\"\"A class containing the nodes of the branches plus some\n functions to compute distance related quantities.\n\n Args:\n initial_node (array):\n an array with the coordinates of the initial node of the first branch.\n\n Attributes:\n nodes (list):\n list of arrays containing the coordinates of the nodes\n last_node (int):\n last added node.\n end_nodes (list):\n a list containing the indices of all end nodes\n (nodes that are not connected) of the tree.\n tree (scipy.spatial.cKDTree):\n a k-d tree to compute the distance from any point\n to the closest node in the tree. It is updated once a branch is finished.\n collision_tree (scipy.spatial.cKDTree):\n a k-d tree to compute the distance from any point to the closest node\n in the tree, except from the brother and mother branches.\n It is used to check collision between branches.\n\n \"\"\"\n\n def __init__(self, initial_node: np.ndarray) -> None:\n self.nodes = [initial_node]\n self.last_node = 0\n self.end_nodes: list[int] = []\n self.tree = cKDTree(self.nodes)\n\n def add_nodes(self, queue: list[np.ndarray]) -> list[int]:\n \"\"\"This function stores a list of nodes of a branch and\n returns the node indices. It also updates the tree to compute distances.\n\n Args:\n queue (list):\n a list of arrays containing the coordinates of the nodes of one branch.\n\n Returns:\n nodes_id (list):\n the indices of the added nodes.\n \"\"\"\n nodes_id = []\n for point in queue:\n self.nodes.append(point)\n self.last_node += 1\n nodes_id.append(self.last_node)\n\n self.tree = cKDTree(self.nodes)\n return nodes_id\n\n def distance_from_point(self, point: np.ndarray) -> float:\n \"\"\"This function returns the distance from any\n point to the closest node in the tree.\n\n Args:\n point (array):\n the coordinates of the point to calculate the distance from.\n\n Returns:\n d (float):\n the distance between point and the closest node in the tree.\n \"\"\"\n return self.tree.query(point)[0]\n\n def distance_from_node(self, node: int) -> float:\n \"\"\"This function returns the distance from any\n node to the closest node in the tree.\n\n Args:\n node (int):\n the index of the node to calculate the distance from.\n\n Returns:\n d (float):\n the distance between specified node and the closest node in the tree.\n \"\"\"\n return self.distance_from_point(self.nodes[node])\n\n def update_collision_tree(self, nodes_to_exclude: list[int]) -> None:\n \"\"\"This function updates the collision_tree excluding a\n list of nodes from all the nodes in the tree. If all the\n existing nodes are excluded, one distant node is added.\n\n Args\n nodes_to_exclude (list):\n contains the nodes to exclude from the tree.\n Usually it should be the mother and the brother branch nodes.\n\n Returns:\n none\n \"\"\"\n nodes = set(range(len(self.nodes))).difference(nodes_to_exclude)\n nodes_to_consider = [self.nodes[x] for x in nodes]\n self.nodes_to_consider_keys = list(nodes)\n if len(nodes_to_consider) == 0:\n nodes_to_consider = [\n np.array([-100000000000.0, -100000000000.0, -100000000000.0])\n ]\n self.nodes_to_consider_keys = [100000000]\n logger.debug(\"no nodes to consider\")\n\n self.collision_tree = cKDTree(nodes_to_consider)\n\n def collision(self, point: np.ndarray):\n \"\"\"This function returns the distance between one point and\n the closest node in the tree and the index of the closest\n node using the collision_tree.\n\n Args:\n point (array):\n the coordinates of the point to calculate the distance from.\n\n Returns:\n collision (tuple):\n (distance to the closest node, index of the closest node)\n \"\"\"\n d, node = self.collision_tree.query(point)\n collision = (self.nodes_to_consider_keys[node], d)\n return collision\n\n def gradient(self, point: np.ndarray, delta: float = 0.01):\n \"\"\"This function returns the gradient of the distance from\n the existing points of the tree from any point. It uses a\n central finite difference approximation.\n\n Args:\n point (array):\n the coordinates of the point to calculate the gradient of the distance from.\n\n Returns:\n grad (array):\n (x,y,z) components of gradient of the distance.\n \"\"\"\n\n dx = np.array([delta, 0, 0])\n dy = np.array([0.0, delta, 0.0])\n dz = np.array([0.0, 0.0, delta])\n\n diff = [\n point - dx,\n point + dx,\n point - dy,\n point + dy,\n point - dz,\n point + dz,\n ]\n xm, xp, ym, yp, zm, zp = self.tree.query(diff)[0]\n\n grad = np.array(\n [\n (xp - xm) / (2 * delta),\n (yp - ym) / (2 * delta),\n (zp - zm) / (2 * delta),\n ]\n )\n return grad\n", "repo_name": "fsahli/fractal-tree", "sub_path": "src/fractal_tree/branch.py", "file_name": "branch.py", "file_ext": "py", "file_size_in_byte": 11616, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 17, "dataset": "github-code", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 11, "usage_type": "call"}, {"api_name": "mesh.Mesh", "line_number": 66, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 68, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 78, "usage_type": "call"}, {"api_name": "mesh.normals", "line_number": 92, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 110, "usage_type": "attribute"}, {"api_name": "numpy.cross", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 113, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 113, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 114, "usage_type": "attribute"}, {"api_name": "mesh.Mesh", "line_number": 118, "usage_type": "name"}, {"api_name": "mesh.normals", "line_number": 142, "usage_type": "attribute"}, {"api_name": "numpy.dot", "line_number": 144, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 147, "usage_type": "attribute"}, {"api_name": "numpy.linalg.norm", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 148, "usage_type": "attribute"}, {"api_name": "mesh.Mesh", "line_number": 153, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 153, "usage_type": "attribute"}, {"api_name": "mesh.project_new_point", "line_number": 174, "usage_type": "call"}, {"api_name": "mesh.InvalidNodeError", "line_number": 175, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 213, "usage_type": "attribute"}, {"api_name": "scipy.spatial.cKDTree", "line_number": 217, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 219, "usage_type": "attribute"}, {"api_name": "scipy.spatial.cKDTree", "line_number": 237, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 240, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 286, "usage_type": "call"}, {"api_name": "scipy.spatial.cKDTree", "line_number": 291, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 293, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 310, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 324, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 325, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 326, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 338, "usage_type": "call"}]} +{"seq_id": "1584563767", "text": "from django.db import models\nfrom django.urls import reverse\nfrom .file_reader import read\nimport datetime\nimport django.utils\nimport datefinder\n\nclass Event(models.Model):\n class_year = (\n (\"FR\", \"Freshman\"),\n (\"SO\", \"Sophomore\"),\n (\"JR\", \"Junior\"),\n (\"SR\", \"Senior\"),\n (\"NA\", \"No Associated Class Year\"),\n )\n title = models.CharField(max_length=200, blank = True)\n description = models.TextField(blank=True)\n date = models.DateField(null=True,blank=True)\n course = models.CharField(max_length=10)\n course_year = models.CharField(max_length=2, choices=class_year, default=\"NA\")\n\n # Override the save function to allow input saves and auto-generation\n # of model instances\n def save(self):\n if (not self.title or not self.description or\n not self.date or not self.course):\n lessons = read()\n bulk_lessons = []\n for lesson in lessons:\n new_lesson = Event()\n new_lesson.title = ' '.join(lesson[0])\n new_lesson.description = ' '.join(lesson[2] + lesson[3])\n l = datefinder.find_dates(' '.join(lesson[1]))\n for d in l:\n new_lesson.date = d.date()\n self.date = d.date()\n new_lesson.course = 'MilArt'\n new_lesson.course_year = \"Junior\"\n bulk_lessons.append(new_lesson)\n Event.objects.bulk_create(bulk_lessons)\n else:\n super(Event, self).save()\n\n # Allow a user to click in an event and see it's details in a separate page\n @property\n def get_url(self):\n url = reverse('planner:event_view', args=(self.id,))\n return f' {self.course}: {self.title} '\n\nclass File(models.Model):\n description = models.CharField(max_length=255, blank=True)\n document = models.FileField(upload_to='documents/')\n uploaded_at = models.DateTimeField(auto_now_add=True)\n", "repo_name": "ShadowWolf7027/Django-Project", "sub_path": "planner/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 1992, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.db.models.Model", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 8, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 16, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 16, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 17, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 17, "usage_type": "name"}, {"api_name": "django.db.models.DateField", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 18, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 19, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 20, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 20, "usage_type": "name"}, {"api_name": "file_reader.read", "line_number": 27, "usage_type": "call"}, {"api_name": "datefinder.find_dates", "line_number": 33, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 47, "usage_type": "call"}, {"api_name": "django.db.models.Model", "line_number": 50, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 50, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 51, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 51, "usage_type": "name"}, {"api_name": "django.db.models.FileField", "line_number": 52, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 52, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 53, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 53, "usage_type": "name"}]} +{"seq_id": "41094630136", "text": "from time import * # Used for timing\r\nfrom serial import * # Used for serial communication with the arduino\r\nimport json # Parsing of data from Arduino\r\nimport threading\r\nfrom SETTINGS import *\r\nfrom collision_avoidance_algorithm import *\r\nfrom gps_functions import *\r\nfrom navigation import *\r\nimport os\r\nimport signal\r\nimport sys\r\nimport board # https://learn.adafruit.com/circuitpython-libraries-on-linux-and-the-nvidia-jetson-nano/digital-i-o\r\nimport digitalio\r\n\r\nbutton = digitalio.DigitalInOut(board.D4)\r\nbutton.direction = digitalio.Direction.INPUT\r\n\r\ne_stop = digitalio.DigitalInOut(board.D17)\r\ne_stop.direction = digitalio.Direction.INPUT\r\n\r\ndirection_data = False\r\nlocation_data = False\r\n\r\nMOTOR_PORT_INITALIZED = \"...\"\r\n\r\ndef get_motor_port():\r\n return MOTOR_PORT_INITALIZED\r\n\r\ndef get_coordinate(data_in):\r\n lat = getDecimal(data_in['lat'])\r\n lon = getDecimal(data_in['lon'])\r\n\r\n return lat, lon\r\n\r\n\r\ndef get_degree(data_in):\r\n value = data_in['dir'] + COMPASS_ANGLE_ADJUST\r\n return (value + 360) % 360\r\n\r\n\r\ndef get_direction():\r\n return direction_data\r\n\r\n\r\ndef get_location():\r\n return location_data\r\n\r\n\r\ndef usb_address_define():\r\n ports = [\"/dev/ttyUSB0\", \"/dev/ttyUSB1\", \"/dev/ttyUSB2\"]\r\n\r\n global NAV_PORT\r\n global SENSOR_PORT\r\n global MOTOR_PORT\r\n \r\n for port in ports:\r\n print(\"Testing port: \", port)\r\n ser_state = False # Connection state\r\n while not ser_state: # If not connected, try again\r\n if not button.value:\r\n state_handler.shutdown_flag = True\r\n #os.kill(os.getpid(), signal.SIGINT)\r\n if state_handler.shutdown_flag:\r\n print(\"Switch turned off\")\r\n sys.exit()\r\n try: # Set up error catch\r\n serial_conn = Serial(port, 9600, timeout=4) # Trying to connect serial\r\n serial_conn.setDTR(False)\r\n sleep(1)\r\n serial_conn.flushInput()\r\n serial_conn.setDTR(True)\r\n print(\"Successfully connected to \", port) # Print for the console\r\n try:\r\n print(\"Going to read data...\")\r\n data = serial_conn.readline()\r\n print(\"Inital data read: \", data)\r\n decoded = unicode(data, \"utf-8\")\r\n print(\"Inital data decoded: \", decoded)\r\n if decoded == \"NAV\\n\":\r\n print(\"Found the Navigation controller on port: \", port)\r\n NAV_PORT = port\r\n print(\"This is the nav port in settings: \", NAV_PORT)\r\n ser_state = True # If successful set the connection state true\r\n elif decoded == \"SENS\\n\":\r\n print(\"Found the Sensor controller on port: \", port)\r\n SENSOR_PORT = port\r\n print(\"This is the sensor port in settings: \", SENSOR_PORT)\r\n ser_state = True # If successful set the connection state true\r\n elif decoded == \"MOTOR\\r\\n\":\r\n print(\"Found the Motor controller on port: \", port)\r\n MOTOR_PORT = port\r\n MOTOR_PORT_INITALIZED = port\r\n state_handler.motor_port = port\r\n print(\"This is the motor port in settings: \", MOTOR_PORT)\r\n ser_state = True # If successful set the connection state true\r\n else:\r\n print(\"Port match not found for:\", data)\r\n except SerialException:\r\n print(\"Nothing read\")\r\n except SerialException: # Error handling\r\n if not button.value:\r\n os.kill(os.getpid(), signal.SIGINT)\r\n print('Trying to connect ', port) # Inform the user that we are trying to connect\r\n sleep(0.5) # Wait 0.5 second before trying again\r\n print(\"Done finding ports\")\r\n\r\n\r\ndef serial_connect(port): # This function connects the Navigation Controller\r\n ser_state = False # Connection state\r\n while not ser_state: # If not connected, try again\r\n if not button.value:\r\n state_handler.shutdown_flag = True\r\n #os.kill(os.getpid(), signal.SIGINT)\r\n if state_handler.shutdown_flag:\r\n print(\"Switch turned off\")\r\n sys.exit()\r\n try: # Set up error catch\r\n serial_conn = Serial(port, 9600, timeout=4) # Trying to connect serial\r\n serial_conn.setDTR(False)\r\n sleep(1)\r\n serial_conn.flushInput()\r\n serial_conn.setDTR(True)\r\n print(\"Successfully connected to \", port) # Print for the console\r\n try:\r\n print(\"Going to read data...\")\r\n data = serial_conn.readline()\r\n print(\"Inital data read: \", data)\r\n decoded = unicode(data, \"utf-8\")\r\n print(\"Inital data decoded: \", decoded)\r\n ser_state = True\r\n except SerialException:\r\n print(\"Nothing read\")\r\n\r\n return serial_conn\r\n\r\n except SerialException: # Error handling\r\n if not button.value:\r\n os.kill(os.getpid(), signal.SIGINT)\r\n print('Trying to connect ', port) # Inform the user that we are trying to connect\r\n sleep(0.5) # Wait 0.5 second before trying again\r\n\r\n\r\ndef decode_json_data(data):\r\n try:\r\n return json.loads(data.decode('utf-8'))\r\n except:\r\n return False\r\n\r\n\r\ndef get_navigation_data():\r\n ser = serial_connect(NAV_PORT) # Define ser as the serial connection.\r\n ser.readline() # Read the buffer to clear any unwanted bytes\r\n while True:\r\n if not button.value:\r\n state_handler.shutdown_flag = True\r\n #os.kill(os.getpid(), signal.SIGINT)\r\n if state_handler.shutdown_flag:\r\n sys.exit()\r\n\r\n state_handler.emergency_stop_flag = not e_stop.value\r\n\r\n try:\r\n data = ser.readline() # Read the serial data from the Arduino\r\n if data.decode('utf-8') != '': # If there is data\r\n # test = json.loads(data.decode('utf-8')) # Decode the data from the Arduino\r\n test_data = decode_json_data(data)\r\n if test_data != False:\r\n state_handler.navigation_disconnect_flag = False\r\n if test_data['data'] == 0:\r\n global direction_data\r\n direction_data = test_data\r\n if test_data['data'] == 1: # 1 means gps data, a 0 would be the direction data\r\n global location_data\r\n location_data = test_data\r\n # Print all the data\r\n else:\r\n print(\"Data Error on navigation port, raw data: \", data)\r\n # sleep(0.2)\r\n # state_handler.navigation_disconnect_flag = True\r\n else:\r\n print(\"Timeout on Navigation - Trying again...\")\r\n # state_handler.navigation_disconnect_flag = True\r\n except SerialException:\r\n # Disconnect of USB->UART occurred\r\n print(\"Device disconnected\")\r\n state_handler.navigation_disconnect_flag = True\r\n ser = serial_connect(NAV_PORT)\r\n\r\ndef sensor_bool_convert(sensor_value):\r\n if sensor_value == 1:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\ndef get_sensor_data():\r\n\r\n print(\"SENSOR LOOP STARTED\")\r\n\r\n ser = serial_connect(SENSOR_PORT) # Define ser as the serial connection.\r\n ser.flushInput()\r\n ser.readline() # Read the buffer to clear any unwanted bytes\r\n while True:\r\n if not button.value:\r\n state_handler.shutdown_flag = True\r\n #os.kill(os.getpid(), signal.SIGINT)\r\n if state_handler.shutdown_flag:\r\n sys.exit()\r\n\r\n state_handler.emergency_stop_flag = not e_stop.value\r\n\r\n try:\r\n data = ser.readline() # Read the serial data from the Arduino\r\n if data.decode('utf-8') != '': # If there is data\r\n # test = json.loads(data.decode('utf-8')) # Decode the data from the Arduino\r\n test_data = decode_json_data(data)\r\n if test_data != False:\r\n state_handler.sensor_disconnect_flag = False\r\n # Got the data, pass it and set different states of control system etc etc\r\n \r\n state_handler.front_collision_flag = sensor_bool_convert(test_data['T_F'])\r\n state_handler.rear_collision_flag = sensor_bool_convert(test_data['T_B'])\r\n\r\n ir_data = test_data['IR']\r\n sharp_data = test_data['SHARP']\r\n\r\n state_handler.ir_front_left = sensor_bool_convert(ir_data[0])\r\n state_handler.ir_front_right = sensor_bool_convert(ir_data[1])\r\n state_handler.ir_rear_left = sensor_bool_convert(ir_data[2])\r\n state_handler.ir_rear_right = sensor_bool_convert(ir_data[3])\r\n\r\n state_handler.json_string_recieved = test_data\r\n\r\n state_handler.sharp_front = sharp_data[0]\r\n \r\n if (state_handler.motor_driver_disconnect_flag is False and state_handler.navigation_disconnect_flag\r\n is False and state_handler.emergency_stop_flag is False):\r\n print(\"Sending ACK\")\r\n ser.write(69) # ACK to the sensor controller\r\n print(\"Did send ACK\")\r\n\r\n else:\r\n print(\"Data Error on sensor controller, raw data: \", data)\r\n state_handler.sensor_disconnect_flag = True\r\n else:\r\n print(\"Timeout on Sensor - Trying again...\")\r\n state_handler.sensor_disconnect_flag = True\r\n except SerialException:\r\n # Disconnect of USB->UART occurred\r\n print(\"Device disconnected\")\r\n state_handler.sensor_disconnect_flag = True\r\n ser = serial_connect(SENSOR_PORT)\r\n\r\n\r\n\r\nnav_loop = threading.Thread(name=\"background\", target=get_navigation_data)\r\nsensor_loop = threading.Thread(name='background', target=get_sensor_data)\r\n\r\ndef serial_init():\r\n nav_loop.start()\r\n sensor_loop.start()\r\n", "repo_name": "rasmushedeager/spro3grp4-E19", "sub_path": "serial_cummunications.py", "file_name": "serial_cummunications.py", "file_ext": "py", "file_size_in_byte": 10677, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "digitalio.DigitalInOut", "line_number": 15, "usage_type": "call"}, {"api_name": "board.D4", "line_number": 15, "usage_type": "attribute"}, {"api_name": "digitalio.Direction", "line_number": 16, "usage_type": "attribute"}, {"api_name": "digitalio.DigitalInOut", "line_number": 18, "usage_type": "call"}, {"api_name": "board.D17", "line_number": 18, "usage_type": "attribute"}, {"api_name": "digitalio.Direction", "line_number": 19, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 65, "usage_type": "call"}, {"api_name": "os.kill", "line_number": 102, "usage_type": "call"}, {"api_name": "os.getpid", "line_number": 102, "usage_type": "call"}, {"api_name": "signal.SIGINT", "line_number": 102, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 116, "usage_type": "call"}, {"api_name": "os.kill", "line_number": 138, "usage_type": "call"}, {"api_name": "os.getpid", "line_number": 138, "usage_type": "call"}, {"api_name": "signal.SIGINT", "line_number": 138, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 145, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 158, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 208, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 256, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 257, "usage_type": "call"}]} +{"seq_id": "17126084581", "text": "__author__ = \"Ivan Begtin (ibegtin@gmail.com)\"\n__version__ = \"3.0.4\"\n__copyright__ = \"Copyright (c) 2008 Ivan Begtin\"\n__license__ = \"Proprietary\"\n\nfrom setuptools import setup, find_packages\n\nsetup(name='opendata',\n version='1.0',\n description='Python OpenGovData (OpenData)',\n author='Ivan Begtin',\n author_email='ibegtin@gmail.com',\n url='',\n download_url='',\n packages=find_packages(),\n license='Creative Commons',\n keywords='opendata',\n classifiers=[\"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Libraries :: Python Modules\"\n ],\n )\n", "repo_name": "ivbeg/opengovdataru", "sub_path": "opendata/setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 935, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "24", "api": [{"api_name": "setuptools.setup", "line_number": 8, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 15, "usage_type": "call"}]} +{"seq_id": "71305125824", "text": "#-*- coding:utf-8 -*-\nimport logging\nimport cv2\nimport numpy as np\n\nfrom lxml import html\n\nfrom django.core.management.base import BaseCommand\nfrom django.conf import settings\n\nlogger = logging.getLogger(__name__)\n\nclass Command(BaseCommand):\n def add_arguments(self, parser):\n # Named (optional) arguments\n parser.add_argument('--demo_mode',\n action = 'store_true',\n dest = 'demo_mode',\n default = False,\n help = 'Set demo mode')\n parser.add_argument('--cat_id',\n action = 'store',\n dest = 'cat_id',\n type = str,\n default = False,\n help = 'Set cat tag for update')\n def handle(self, *args, **options):\n path = '/home/jocker/Downloads/tb50413_1.png'\n output = '/home/jocker/Downloads/tb50413_1_CLEAN.png'\n\ndef back_rm(filename):\n # Load the image\n img = cv2.imread(filename)\n\n # Convert the image to grayscale\n gr = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Make a copy of the grayscale image\n bg = gr.copy()\n\n # Apply morphological transformations\n for i in range(5):\n kernel2 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,\n (2 * i + 1, 2 * i + 1))\n bg = cv2.morphologyEx(bg, cv2.MORPH_CLOSE, kernel2)\n bg = cv2.morphologyEx(bg, cv2.MORPH_OPEN, kernel2)\n\n # Subtract the grayscale image from its processed copy\n dif = cv2.subtract(bg, gr)\n\n # Apply thresholding\n bw = cv2.threshold(dif, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]\n dark = cv2.threshold(bg, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]\n\n # Extract pixels in the dark region\n darkpix = gr[np.where(dark > 0)]\n\n # Threshold the dark region to get the darker pixels inside it\n darkpix = cv2.threshold(darkpix, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\n\n # Paste the extracted darker pixels in the watermark region\n bw[np.where(dark > 0)] = darkpix.T\n\n cv2.imwrite('final.jpg', bw)\n\n\n#back_rm('watermark.jpg')", "repo_name": "dkramorov/astwobytes", "sub_path": "apps/upload_tasks/management/commands/try_remove_watermark.py", "file_name": "try_remove_watermark.py", "file_ext": "py", "file_size_in_byte": 2057, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 11, "usage_type": "call"}, {"api_name": "django.core.management.base.BaseCommand", "line_number": 13, "usage_type": "name"}, {"api_name": "cv2.imread", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 36, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 36, "usage_type": "attribute"}, {"api_name": "cv2.getStructuringElement", "line_number": 43, "usage_type": "call"}, {"api_name": "cv2.MORPH_ELLIPSE", "line_number": 43, "usage_type": "attribute"}, {"api_name": "cv2.morphologyEx", "line_number": 45, "usage_type": "call"}, {"api_name": "cv2.MORPH_CLOSE", "line_number": 45, "usage_type": "attribute"}, {"api_name": "cv2.morphologyEx", "line_number": 46, "usage_type": "call"}, {"api_name": "cv2.MORPH_OPEN", "line_number": 46, "usage_type": "attribute"}, {"api_name": "cv2.subtract", "line_number": 49, "usage_type": "call"}, {"api_name": "cv2.threshold", "line_number": 52, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY_INV", "line_number": 52, "usage_type": "attribute"}, {"api_name": "cv2.THRESH_OTSU", "line_number": 52, "usage_type": "attribute"}, {"api_name": "cv2.threshold", "line_number": 53, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY_INV", "line_number": 53, "usage_type": "attribute"}, {"api_name": "cv2.THRESH_OTSU", "line_number": 53, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 56, "usage_type": "call"}, {"api_name": "cv2.threshold", "line_number": 59, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 59, "usage_type": "attribute"}, {"api_name": "cv2.THRESH_OTSU", "line_number": 59, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 62, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 64, "usage_type": "call"}]} +{"seq_id": "19202525168", "text": "from flask import Flask, render_template, redirect, request\nfrom loginform import LoginForm\nfrom my_configure import my_configure\n\napp = Flask(__name__)\n\n\n@app.route('/')\n@app.route('/index')\ndef index():\n user = \"Ученик Яндекс.Лицея\"\n return render_template('index.html', title='Домашняя страница', username=user)\n\n\n@app.route('/form_sample', methods=['GET', 'POST'])\ndef form():\n form = LoginForm()\n if form.validate_on_submit():\n print(request.form['username_first'])\n print(request.form['real_name'])\n print(request.form['password'])\n print(request.form['sex'])\n print(request.form['commentary'])\n print(request.form['language'])\n print(request.form['remember_me'])\n return redirect('/success')\n return render_template('login.html', title='Форма', form=form)\n\n\n@app.route('/success')\ndef success():\n return render_template('success.html')\n\n \nif __name__ == '__main__':\n my_configure(app)\n app.run(port=8080, host='127.0.0.1')\n", "repo_name": "gri-gri/web-server", "sub_path": "Urok 2/Elementy formy/server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 1048, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 5, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 12, "usage_type": "call"}, {"api_name": "loginform.LoginForm", "line_number": 17, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 19, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 19, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 20, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 20, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 21, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 21, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 22, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 22, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 23, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 23, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 24, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 25, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 25, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 26, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 27, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 32, "usage_type": "call"}, {"api_name": "my_configure.my_configure", "line_number": 36, "usage_type": "call"}]} +{"seq_id": "33194272253", "text": "import unicodedata\nfrom bs4 import BeautifulSoup\n\nSKIDPASE_BASEURL = 'http://skidpaste.org/'\n\nclass MyHTMLParser:\n def __init__(self, html_doc, requestHandler):\n self.soup = BeautifulSoup(html_doc, 'html.parser')\n self.requestHandler = requestHandler\n self.pastes = []\n self.parsedJson = {\"url\":[], \"title\":[],\"content\":[]}\n self.getdetails()\n\n def getdetails(self):\n limit = 10\n leftSideTag = self.soup.find(id=\"content_left\")\n for tr in leftSideTag.find_all('tr'):\n if limit == 0:\n return\n limit -= 1\n print(\"parsing paste\")\n a = tr.find('a')\n if a != None:\n title = a.get_text()\n url = SKIDPASE_BASEURL+a['href']+'.txt'\n textChunc = self.requestHandler.request(url)\n contentText = self.convertByteToString(textChunc)\n paste = {\"title\": title, 'url': url, 'content': contentText}\n self.pastes.append(paste)\n\n def getJson(self):\n return self.pastes\n\n def convertByteToString(self, text):\n txt = text.decode(encoding='UTF-8')\n print('convert')\n return txt\n", "repo_name": "danabig/skidPasteCrawler", "sub_path": "MyHTMLParser.py", "file_name": "MyHTMLParser.py", "file_ext": "py", "file_size_in_byte": 1209, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "bs4.BeautifulSoup", "line_number": 8, "usage_type": "call"}]} +{"seq_id": "41716730155", "text": "import math\n\nfrom pathlib import Path\n\nimport pytest\nimport torch\nimport torch.nn as nn\n\nfrom pytorch3d.transforms import random_rotation\n\nfrom deepmc.models.components.vn_dgcnn_pose_net import VN_DGCNN_pose, VN_DGCNN_pose_seg\nfrom deepmc.models.components.vnn import VNMaxPool\n\n\n@pytest.mark.parametrize(\"batch_size\", [2, 8])\ndef test_vn(batch_size):\n model = VN_DGCNN_pose().to(\"cuda:7\")\n\n inp = torch.rand(batch_size, 3, 1024).to(\"cuda:7\")\n out = model(inp).transpose(-1, -2)\n print(out.shape)\n\n R = random_rotation().to(\"cuda:7\")\n inp_r = R @ inp\n out2 = model(inp_r).transpose(-1, -2)\n out_r = R @ out\n \n print(out_r[0,0,0], out2[0,0,0])\n print(torch.abs(out_r - out2).max())\n\n@pytest.mark.parametrize(\"batch_size\", [1, 8])\ndef test_vnmaxpool(batch_size):\n model = VNMaxPool(682)\n\n inp = torch.rand(batch_size, 682, 3, 1024)\n out = model(inp)\n\n print(out.shape)\n\n # R = random_rotation()\n # inp_r = R @ inp.unsqueeze(-1)\n # inp_r = inp_r.squeeze()\n # out2 = m_enc(inp_r)\n # out2 = m_dec(out2)\n \n # print(torch.max(out1_r - out2))\n\n\n\ndef main():\n test_vn(4)\n # test_vnmaxpool(1)\n\nif __name__ == \"__main__\":\n main()", "repo_name": "beyaldiz/DeepMC", "sub_path": "tests/test_vn_dgcnn.py", "file_name": "test_vn_dgcnn.py", "file_ext": "py", "file_size_in_byte": 1193, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "deepmc.models.components.vn_dgcnn_pose_net.VN_DGCNN_pose", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.rand", "line_number": 19, "usage_type": "call"}, {"api_name": "pytorch3d.transforms.random_rotation", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.abs", "line_number": 29, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 15, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 15, "usage_type": "attribute"}, {"api_name": "deepmc.models.components.vnn.VNMaxPool", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.rand", "line_number": 35, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 31, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 31, "usage_type": "attribute"}]} +{"seq_id": "28958200042", "text": "from gpiozero import Device\n# from gpiozero.pins.pigpio import PiGPIOFactory\nfrom gpiozero import DigitalOutputDevice, PWMOutputDevice\nimport time\n# import RPi.GPIO as GPIO\n# Device.pin_factory = PiGPIOFactory()\n\n\nclass Motor:\n \"\"\"\n The class takes three pin numbers as the input to control one of the motor connected to TB6612FNG module.\n \"\"\"\n\n def __init__(self, in1, in2, pwm):\n self.in1 = DigitalOutputDevice(in1)\n self.in1.off()\n\n self.in2 = DigitalOutputDevice(in2)\n self.in2.on()\n\n self.pwm = PWMOutputDevice(pwm, frequency=1000)\n\n def set_throttle(self, val):\n \"\"\"Control the orientation and the speed of the motor.\n Arguments:\n val: a number between -1.0 and 1.0. The motor rotates in forward direction if val > 1, otherwise in reverse direction.\n Setting val to None will set the motor to stop mode.\n \"\"\"\n\n # Set the motor to stop mode.\n if val is None:\n self.in1.off()\n self.in2.off()\n self.pwm.value = 1.0\n\n else:\n # Determine the orientation of the motor.\n if val > 0.0:\n self.in1.off()\n self.in2.on()\n else:\n self.in1.on()\n self.in2.off()\n\n # Clamp the pwm signal (throttle) to [0, 1].\n pwm = max(0.0, min(abs(val), 1.0))\n\n # Note that setting PWM to low will brake the motor no matter what\n # in1 and in2 input is.\n self.pwm.value = pwm\n\n\n def close(self):\n self.in1.close()\n self.in2.close()\n self.pwm.close()\n\n\ndef test_left_wheel():\n # 22 -- pin 15 \n # 23 -- ping 16\n # 19 -- pin 35\n motor = Motor(22, 23, 19)\n # [-1, -0.5, 0, 0.5, 1]\n for val in [0.5, 1]:\n motor.set_throttle(val)\n time.sleep(1)\n\n # Set motor to stop mode.\n motor.set_throttle(None)\n motor.close()\n\ndef test_right_wheel():\n # 17 -- pin 11\n # 27 -- pin 13\n # 18 --- pin 12\n motor = Motor(17, 27, 18)\n for val in [0.5, 1]:\n motor.set_throttle(val)\n time.sleep(1)\n\n # Set motor to stop mode.\n motor.set_throttle(None)\n motor.close()\n\n\ndef test_two_wheel():\n l_motor = Motor(22, 23, 19)\n r_motor = Motor(17, 27, 18)\n\n for val in [0.5, 1]:\n l_motor.set_throttle(val)\n r_motor.set_throttle(val)\n time.sleep(0.5)\n\n\n\nif __name__ == \"__main__\":\n # test_left_wheel()\n # test_right_wheel()\n test_two_wheel()\n", "repo_name": "iamfaith/picar", "sub_path": "device.py", "file_name": "device.py", "file_ext": "py", "file_size_in_byte": 2520, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "gpiozero.DigitalOutputDevice", "line_number": 15, "usage_type": "call"}, {"api_name": "gpiozero.DigitalOutputDevice", "line_number": 18, "usage_type": "call"}, {"api_name": "gpiozero.PWMOutputDevice", "line_number": 21, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 67, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 80, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 94, "usage_type": "call"}]} +{"seq_id": "35151884863", "text": "import os\nfrom pprint import pprint\nimport torch\nfrom ml_research.train.PriceRangeTrainer import ProcessModel\nimport pandas as pd\nimport glob\nfrom torch.cuda.amp.autocast_mode import autocast\nimport torchmetrics\nfrom tqdm import tqdm\nimport numpy as np\n\n\ndef CrossValPred(iteration, datasetGenerator):\n gen = datasetGenerator\n iter = f\"iter_{iteration}\"\n taskName = gen.srcDfPath.split(\"/\")[-1]\n allFoldsLoader = gen.genDataloader()\n trainedModelDir = \"/home/alextay96/Desktop/workspace/mrm_workspace/dmg_consistent_detection/data/auto_select\"\n outputDir = \"/home/alextay96/Desktop/workspace/mrm_workspace/dmg_consistent_detection/data/cross_val_pred\"\n taskName = iter + \"_\" + taskName\n device = torch.device(\"cuda\")\n allDfWithPreds = []\n for _, valLoader in allFoldsLoader:\n srcDf: pd.DataFrame = valLoader.dataset.df\n allPredLogit = []\n foldId = srcDf[\"kfold\"].unique().item()\n search = f\"{trainedModelDir}/{foldId}/**/*.ckpt\"\n accMetrics = torchmetrics.Accuracy(num_classes=2).to(device)\n confMatMetrics = torchmetrics.ConfusionMatrix(\n num_classes=2, normalize=\"true\"\n ).to(device)\n allmodelPath = glob.glob(search, recursive=True)\n modelPath = allmodelPath[0]\n trainedModel = ProcessModel.load_from_checkpoint(modelPath)\n trainedModel = trainedModel.to(device)\n trainedModel.eval()\n with torch.no_grad():\n for img, targets in tqdm(valLoader):\n img = img.to(device)\n targets = targets.to(device)\n with autocast():\n logit = trainedModel(img)\n preds = torch.argmax(logit, dim=1)\n logitNp = logit.cpu().numpy().tolist()\n allPredLogit.extend(logitNp)\n accMetrics.update(preds, targets)\n confMatMetrics.update(preds, targets)\n assert len(allPredLogit) == len(srcDf)\n srcDf[\"logit\"] = allPredLogit\n srcDf[\"model_version\"] = modelPath\n allDfWithPreds.append(srcDf)\n print(accMetrics.compute())\n pprint(confMatMetrics.compute())\n accMetrics.reset()\n confMatMetrics.reset()\n allDf = pd.concat(allDfWithPreds)\n assert len(allDf) == len(allDf[\"dst_filename\"].unique())\n outputFile = f\"{outputDir}/preds_{taskName}\"\n allDf.to_csv(outputFile)\n return outputFile\n\n\nif __name__ == \"__main__\":\n CrossValPred(1)\n", "repo_name": "MLMonkATGY/dmg_consistent_detection", "sub_path": "ml_research/analysis/CrossValPred.py", "file_name": "CrossValPred.py", "file_ext": "py", "file_size_in_byte": 2455, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "torch.device", "line_number": 21, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 24, "usage_type": "attribute"}, {"api_name": "torchmetrics.Accuracy", "line_number": 28, "usage_type": "call"}, {"api_name": "torchmetrics.ConfusionMatrix", "line_number": 29, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 32, "usage_type": "call"}, {"api_name": "ml_research.train.PriceRangeTrainer.ProcessModel.load_from_checkpoint", "line_number": 34, "usage_type": "call"}, {"api_name": "ml_research.train.PriceRangeTrainer.ProcessModel", "line_number": 34, "usage_type": "name"}, {"api_name": "torch.no_grad", "line_number": 37, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.cuda.amp.autocast_mode.autocast", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.argmax", "line_number": 43, "usage_type": "call"}, {"api_name": "pprint.pprint", "line_number": 53, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 56, "usage_type": "call"}]} +{"seq_id": "30843185355", "text": "import sys\nfrom collections import deque\n\ninput = sys.stdin.readline\n\ndef solution(src, dest):\n need_visit = deque([(st, 0) for st in station_graph[src-1]])\n visited = {src}\n transfer_count = []\n\n while need_visit:\n station: int\n station, count = need_visit.popleft()\n # 목적지\n if station == dest:\n transfer_count.append(count)\n # 목적지 X\n if station not in visited:\n # 환승역 check\n visited.add(station)\n need_visit.extend([(st, count+1) if (count_station[st-1] >= 2) else (st, count) for st in station_graph[station-1]])\n else: continue\n\n print(transfer_count)\n if len(transfer_count) != 0:\n return min(transfer_count)\n return -1\n\n\nN, L = map(int, input().split())\n# {역 번호: [이동 가능한 역 리스트]} 초기화\nstation_graph = [[] for _ in range(N)]\ncount_station = [0 for _ in range(N)]\n\nfor _ in range(L):\n line = list(map(int, input().split()))\n for idx in range(len(line)-1):\n curr, nxt = line[idx], line[idx + 1]\n if nxt != -1:\n station_graph[curr-1].append(nxt)\n station_graph[nxt - 1].append(curr)\n count_station[curr-1] += 1\n\n# src, dest\nS, D = map(int, input().split())\n\nprint(solution(S, D))\n\n\n\"\"\"\n10 3\n1 2 3 4 5 -1\n9 7 10 -1\n7 6 3 8 -1\n1 10\n\n\n2\n\"\"\"", "repo_name": "jjaen0823/codingTest", "sub_path": "5_DFSBFS/BJ_최소환승경로_2021.py", "file_name": "BJ_최소환승경로_2021.py", "file_ext": "py", "file_size_in_byte": 1355, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sys.stdin", "line_number": 4, "usage_type": "attribute"}, {"api_name": "collections.deque", "line_number": 7, "usage_type": "call"}]} +{"seq_id": "27288180792", "text": "from django.shortcuts import render\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\nfrom .models import Task\nfrom .serializer import TaskSerializer\n\n# This is an example of function based view for serializer\n\n@api_view(['GET', 'POST'])\ndef task_list(request):\n \"\"\"\n lists all tasks or creates a task\n :param request:\n :return:\n \"\"\"\n if request.method == \"GET\":\n tasks = Task.objects.all()\n\n # tasks here is a query set. So we are essentially passing the entire query set into the serializer\n # the many=True attribute here is super important. Without this attribute an error would be raised\n\n serializer = TaskSerializer(tasks, many=True)\n return Response(serializer.data)\n\n elif request.method == \"POST\":\n serializer = TaskSerializer(data=request.DATA)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n else:\n # there is a validation error and hence there is a problem with the data in the request\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef task_detail(request, pk):\n \"\"\"\n get update or delete a specific task\n :param request:\n :param pk:\n :return:\n \"\"\"\n try:\n task = Task.objects.get(pk=pk)\n except Task.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n serializer = TaskSerializer(task)\n return Response(serializer.data)\n\n elif request.method == 'PUT':\n serializer = TaskSerializer(task, data=request.DATA)\n if serializer.is_valid():\n serializer.save()\n # returning the serializer data after saving it to the database\n return Response(serializer.data)\n\n else:\n # there were some validation errors with the data\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n elif request.method == 'DELETE':\n # recall we already have the task present\n task.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)", "repo_name": "RiflerRick/Django-Notes", "sub_path": "django-rest-framework/DjangoRestFrameworkDemo/api_demo/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2268, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "models.Task.objects.all", "line_number": 19, "usage_type": "call"}, {"api_name": "models.Task.objects", "line_number": 19, "usage_type": "attribute"}, {"api_name": "models.Task", "line_number": 19, "usage_type": "name"}, {"api_name": "serializer.TaskSerializer", "line_number": 24, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 25, "usage_type": "call"}, {"api_name": "serializer.data", "line_number": 25, "usage_type": "attribute"}, {"api_name": "serializer.TaskSerializer", "line_number": 28, "usage_type": "call"}, {"api_name": "serializer.is_valid", "line_number": 29, "usage_type": "call"}, {"api_name": "serializer.save", "line_number": 30, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 31, "usage_type": "call"}, {"api_name": "serializer.data", "line_number": 31, "usage_type": "attribute"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 31, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 31, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 35, "usage_type": "call"}, {"api_name": "serializer.errors", "line_number": 35, "usage_type": "attribute"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 35, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 35, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 11, "usage_type": "call"}, {"api_name": "models.Task.objects.get", "line_number": 46, "usage_type": "call"}, {"api_name": "models.Task.objects", "line_number": 46, "usage_type": "attribute"}, {"api_name": "models.Task", "line_number": 46, "usage_type": "name"}, {"api_name": "models.Task.DoesNotExist", "line_number": 47, "usage_type": "attribute"}, {"api_name": "models.Task", "line_number": 47, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 48, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_404_NOT_FOUND", "line_number": 48, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 48, "usage_type": "name"}, {"api_name": "serializer.TaskSerializer", "line_number": 51, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 52, "usage_type": "call"}, {"api_name": "serializer.data", "line_number": 52, "usage_type": "attribute"}, {"api_name": "serializer.TaskSerializer", "line_number": 55, "usage_type": "call"}, {"api_name": "serializer.is_valid", "line_number": 56, "usage_type": "call"}, {"api_name": "serializer.save", "line_number": 57, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 59, "usage_type": "call"}, {"api_name": "serializer.data", "line_number": 59, "usage_type": "attribute"}, {"api_name": "rest_framework.response.Response", "line_number": 63, "usage_type": "call"}, {"api_name": "serializer.errors", "line_number": 63, "usage_type": "attribute"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 63, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 63, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 68, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_204_NO_CONTENT", "line_number": 68, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 68, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 37, "usage_type": "call"}]} +{"seq_id": "35295853579", "text": "import sqlite3\nimport sys\n\n# MÉTODO QUE CREA CONEXIÓN CON LA BASE DE DATOS\ndef conectar():\n conexion = sqlite3.connect(\"EJERCICIOS_BD/articulos/articulosBD.db\") #realiza la conexión\n cursor = conexion.cursor() \n return conexion, cursor\n\n# MÉTODO QUE CIERRA LA CONEXIÓN CON LA BASE DE DATOS\ndef cerrar_conexion(conexion):\n conexion.close()\n\n# MÉTODO QUE CREA LA TABLA ARTÍCULOS\ndef crearTabla():\n conexion, cursor = conectar()\n sql = \"\"\"\n CREATE TABLE IF NOT EXISTS articulos(\n id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n nombre VARCHAR(20) NOT NULL,\n cantidad INT NOT NULL,\n importe FLOAT NOT NULL\n )\n \"\"\"\n if (cursor.execute(sql)):\n print(\"Tabla creada\")\n else: \n print(\"No se pudo crear la tabla\")\n cerrar_conexion(conexion)\n\n# MÉTODO QUE NOS CARGA EL MENÚ Y NOS DIRIGE A LA OPCIÓN SELECCIONADA\ndef menu():\n print(\"\\nINDIQUE QUE ACCIÓN DESEA REALIZAR\")\n print(\"1. Alta\")\n print(\"2. Listar\")\n print(\"3. Modificacion\")\n print(\"4. Borrado\")\n print(\"0. Salir\")\n\n opcion = input('--> ')\n if opcion not in ['1','2','3','4','0']:\n print('\\n********* Selecciona una opcion valida *********\\n')\n else:\n if opcion == '1':\n anadir_datos()\n if opcion == '2':\n listar_datos()\n if opcion == '3':\n modificar_datos()\n if opcion == '4':\n eliminar_datos()\n if opcion == '0':\n print('HASTA PRONTO !!')\n sys.exit() \n\n# MÉTODO QUE AÑADE DATOS A LA BASE DE DATOS\ndef anadir_datos():\n conexion, cursor = conectar()\n\n nombre = input(\"\\nINSERTA NOMBRE: \")\n cantidad = input(\"INSERTA CANTIDAD: \")\n importe = input(\"INSERTA IMPORTE: \")\n datos = (nombre, cantidad, importe)\n\n sql = \"\"\"INSERT INTO articulos(nombre, cantidad, importe) VALUES (?, ?, ?)\"\"\"\n if(cursor.execute(sql, datos)):\n print('\\n --- Datos guardados ---')\n else:\n print('*** No se pudieron guardar los datos ***')\n\n conexion.commit()\n conexion.close()\n menu()\n\n# MÉTODO QUE LISTA LOS DATOS DE LA BASE DE DATOS\ndef listar_datos():\n conexion, cursor = conectar()\n sql = \"SELECT * FROM articulos\"\n cursor.execute(sql)\n for fila in cursor:\n print(\"\\n\")\n print(\"*\"*25)\n print(f\"ID = {fila[0]}\")\n print(f\"NOMBRE = {fila[1]}\")\n print(f\"CANTIDAD = {fila[2]}\")\n print(f\"IMPORTE = {fila[3]}€\")\n print(\"*\"*25)\n\n conexion.close()\n menu()\n\n\ndef seleccionarId():\n conexion, cursor = conectar()\n idSeleccioando = input(\"\\nINSERTA ID DEL ARTÍCULO QUE QUIERAS MODIFICAR: \")\n\n seleccionar = \"SELECT * FROM articulos WHERE id=\"+idSeleccioando\n cursor.execute(seleccionar)\n\n for fila in cursor:\n print(\"\\n\")\n print(\"*\"*25)\n print(f\"ID = {fila[0]}\")\n print(f\"NOMBRE = {fila[1]}\")\n print(f\"CANTIDAD = {fila[2]}\")\n print(f\"IMPORTE = {fila[3]}€\")\n print(\"*\"*25)\n\n nombre = input(\"\\nINSERTA NUEVO NOMBRE: \")\n cantidad = input(\"INSERTA NUEVO CANTIDAD: \")\n importe = input(\"INSERTA NUEVO IMPORTE: \")\n\n conexion.close()\n return nombre,cantidad,importe,idSeleccioando\n \n\n# MÉTODO QUE MODIFICA LOS DATOS DE LA BASE DE DATOS\ndef modificar_datos():\n conexion, cursor = conectar()\n\n nombre,cantidad,importe,idSeleccioando = seleccionarId()\n\n sql = \"UPDATE articulos SET NOMBRE='\"+nombre+\"',CANTIDAD='\"+cantidad+\"',IMPORTE='\"+importe+\"' WHERE ID='\"+idSeleccioando+\"'\"\n cursor.execute(sql)\n cursor.close()\n conexion.commit()\n conexion.close()\n menu()\n\n# MÉTODO QUE ELIMINA LOS DATOS DE LA BASE DE DATOS\ndef eliminar_datos():\n conexion, cursor = conectar()\n\n idSeleccioando = input(\"\\nINSERTA ID DEL ARTÍCULO QUE QUIERAS MODIFICAR: \")\n sql = \"DELETE FROM articulos WHERE ID=\"+idSeleccioando\n if(cursor.execute(sql)):\n print(f'Se ha eliminado correctamente el articulo con id: {idSeleccioando}')\n else:\n print(f'Error al borrar el id: {idSeleccioando}')\n\n conexion.commit()\n conexion.close()\n menu()\n\n\n\nif __name__ == '__main__':\n crearTabla()\n menu()", "repo_name": "aleefb9/CURSO_AVANZADO_PYTHON", "sub_path": "EJERCICIOS_BD/articulos/ejercicio_articulos.py", "file_name": "ejercicio_articulos.py", "file_ext": "py", "file_size_in_byte": 4185, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sqlite3.connect", "line_number": 6, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 54, "usage_type": "call"}]} +{"seq_id": "30746213627", "text": "import json\nimport os\n\nimport numpy as np\nimport shapely\nimport torch\n\nfrom plankassembly.datasets.data_utils import add_noise, quantize_values\n\n\nclass Sideface():\n def __init__(self, linestring, line_width, line_type):\n self.linestring = linestring\n self.line_width = line_width\n self.line_type = line_type\n\n def to_polygon(self):\n return shapely.buffer(self.linestring, self.line_width / 2, cap_style=\"flat\")\n\n\ndef parse_sideface_from_polygons(polygons, max_thickness):\n\n lines = []\n for polygon in polygons:\n bounds = shapely.bounds(polygon).reshape(-1, 2)\n diffs = np.diff(bounds, axis=0).flatten()\n center = np.mean(bounds, 0)\n\n if diffs[1] < max_thickness:\n line = shapely.linestrings([bounds[0][0], bounds[1][0]], [center[1], center[1]])\n lines.append(Sideface(line, diffs[1], 1))\n\n if diffs[0] < max_thickness:\n line = shapely.linestrings([center[0], center[0]], [bounds[0][1], bounds[1][1]])\n lines.append(Sideface(line, diffs[0], 0))\n\n return lines\n\n\ndef merge_colinaer_sidefaces(lines, merge_tolerance, min_thickness):\n\n merged_lines = [lines[0], ]\n\n for query_line in lines[1:]:\n\n tree = shapely.STRtree([line.linestring for line in merged_lines])\n indices = tree.query(query_line.linestring, predicate='intersects')\n\n colinear_indices = []\n\n for index in np.sort(indices):\n # find colinear case and merge\n coords = shapely.get_coordinates([query_line.linestring, merged_lines[index].linestring])\n\n if ((np.max(coords[:, 0]) - np.min(coords[:, 0])) < merge_tolerance or\n (np.max(coords[:, 1]) - np.min(coords[:, 1])) < merge_tolerance) \\\n and np.abs(query_line.line_width - merged_lines[index].line_width) < merge_tolerance \\\n and query_line.line_type == merged_lines[index].line_type:\n colinear_indices.append(index)\n\n if len(colinear_indices) > 0:\n # merge colinear lines\n multilinestrings = shapely.multilinestrings(\n [query_line.linestring, ] + [merged_lines[i].linestring for i in colinear_indices])\n bounds = shapely.bounds(multilinestrings)\n bounds = np.array(bounds).reshape(2, 2)\n linestring = shapely.linestrings(*bounds.T)\n query_line = Sideface(linestring, query_line.line_width, query_line.line_type)\n\n # remove merged lines\n for i in reversed(colinear_indices):\n merged_lines.pop(i)\n\n # append new line\n merged_lines.append(query_line)\n\n merged_lines = [line.to_polygon() for line in merged_lines if line.line_width >= min_thickness]\n\n return merged_lines\n\n\nclass SidefaceDataset(torch.utils.data.Dataset):\n\n def __init__(self, root, info_files, token, cfg, augmentation=False):\n\n self.root = root\n self.info_files = info_files\n self.augmentation = augmentation\n self.token = token\n\n self.vocab_size = cfg.VOCAB_SIZE\n self.num_input_dof = cfg.NUM_INPUT_DOF\n self.max_input_length = cfg.MAX_INPUT_LENGTH\n self.max_output_length = cfg.MAX_OUTPUT_LENGTH\n self.num_bits = cfg.NUM_BITS\n\n self.aug_ratio = cfg.AUG_RATIO\n self.noise_ratio = cfg.NOISE_RATIO\n self.noise_length = cfg.NOISE_LENGTH\n\n self.max_thickness = cfg.MAX_THICKNESS / cfg.SCALE\n self.min_thickness = cfg.MIN_THICKNESS / cfg.SCALE\n self.merge_tolerance = cfg.MERGE_TOLERANCE / cfg.SCALE\n\n def __len__(self):\n return len(self.info_files)\n\n def extract_sideface(self, linestrings, views):\n\n sidefaces = []\n faceviews = []\n\n for view_index in range(3):\n\n line = [l_i for l_i, v_i in zip(linestrings, views) if v_i == view_index]\n\n if len(line) == 0:\n continue\n\n polygon = shapely.get_parts(shapely.polygonize(line))\n\n sideface = parse_sideface_from_polygons(polygon, self.max_thickness)\n\n if len(sideface) == 0:\n continue\n\n merged_sideface = merge_colinaer_sidefaces(sideface, self.merge_tolerance, self.min_thickness)\n\n sidefaces.extend(merged_sideface)\n faceviews.extend([view_index, ] * len(merged_sideface))\n\n sidefaces = shapely.bounds(sidefaces)\n\n return sidefaces, faceviews\n\n def prepare_input_sequence(self, faces, views):\n # input\n input_value = quantize_values(np.array(faces), self.num_bits)\n input_view = np.array(views, dtype='long')\n \n if len(faces) != 0:\n # sort faces by first by view, then by lines\n face_with_view = np.concatenate((input_value, input_view[..., np.newaxis]), axis=1)\n sort_inds = np.lexsort(face_with_view.T[[3, 1, 2, 0, 4]])\n\n input_value = input_value[sort_inds].flatten()\n input_view = input_view[sort_inds]\n\n # position\n _, counts = np.unique(input_view, return_counts=True)\n input_pos = np.concatenate([np.arange(count) for count in counts])\n\n # coordinate\n input_coord = np.arange(len(input_value)) % self.num_input_dof\n\n # repeat for each token\n input_pos = np.repeat(input_pos, 4)\n input_view = np.repeat(input_view, 4)\n\n else:\n # deal with empty sidefaces\n input_pos = np.zeros_like(input_view, dtype='long')\n input_coord = np.zeros_like(input_view, dtype='long')\n\n # add stop token\n input_value = np.append(input_value, self.token.END)\n num_input = len(input_value)\n\n # add pad tokens\n pad_length = self.max_input_length - num_input\n\n input_value = np.pad(input_value, (0, pad_length-1), constant_values=self.token.PAD)\n input_pos = np.pad(input_pos, (0, pad_length))\n input_coord = np.pad(input_coord, (0, pad_length))\n input_view = np.pad(input_view, (0, pad_length))\n input_mask = (input_value == self.token.PAD)\n\n inputs = {\n 'input_value': input_value,\n 'input_pos': input_pos,\n 'input_coord': input_coord,\n 'input_view': input_view,\n 'input_mask': input_mask\n }\n\n return inputs\n\n def prepare_output_sequence(self, planks, attach):\n # output\n value = quantize_values(planks, self.num_bits)\n\n # add stop token\n value = np.append(value, self.token.END)\n num_output = len(value)\n\n # add pad tokens\n value = np.pad(value, (0, self.max_output_length - num_output), constant_values=self.token.PAD)\n mask = (value == self.token.PAD)\n\n # label\n label = np.pad(attach, (0, self.max_output_length - len(attach)), constant_values=-1)\n\n label[label != -1] += self.vocab_size\n label[label == -1] = value[label == -1]\n\n outputs = {\n 'output_value': value,\n 'output_label': label,\n 'output_mask': mask\n }\n\n return outputs\n\n def __getitem__(self, index):\n \"\"\" Load data for data i\"\"\"\n with open(os.path.join(self.root, self.info_files[index]), \"r\") as f:\n info = json.loads(f.read())\n\n name = info['name']\n svgs = info['svgs']\n\n linestrings = [shapely.from_geojson(svg) for svg in svgs]\n\n views = np.array(info['views'], dtype='long')\n types = np.array(info['types'], dtype='long')\n\n planks = np.array(info['coords']).flatten()\n attach = np.array(info['attach']).flatten()\n\n sidefaces, faceviews = [], []\n\n if self.augmentation and np.random.random() < self.aug_ratio:\n\n noisy_linestrings, noisy_views, _ = add_noise(\n linestrings, views, types, self.noise_ratio, self.noise_length)\n\n sidefaces, faceviews = self.extract_sideface(noisy_linestrings, noisy_views)\n\n # detect degenerated case\n if len(sidefaces) == 0:\n linestrings = [shapely.from_geojson(svg) for svg in svgs]\n views = np.array(info['views'], dtype='long')\n\n sidefaces, faceviews = self.extract_sideface(linestrings, views)\n\n inputs = self.prepare_input_sequence(sidefaces, faceviews)\n\n outputs = self.prepare_output_sequence(planks, attach)\n\n # construct batch data\n batch = {'name': name, **inputs, **outputs}\n\n return batch\n", "repo_name": "manycore-research/PlankAssembly", "sub_path": "plankassembly/datasets/sideface_data.py", "file_name": "sideface_data.py", "file_ext": "py", "file_size_in_byte": 8500, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 49, "dataset": "github-code", "pt": "24", "api": [{"api_name": "shapely.buffer", "line_number": 18, "usage_type": "call"}, {"api_name": "shapely.bounds", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.diff", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 27, "usage_type": "call"}, {"api_name": "shapely.linestrings", "line_number": 30, "usage_type": "call"}, {"api_name": "shapely.linestrings", "line_number": 34, "usage_type": "call"}, {"api_name": "shapely.STRtree", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 51, "usage_type": "call"}, {"api_name": "shapely.get_coordinates", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 57, "usage_type": "call"}, {"api_name": "shapely.multilinestrings", "line_number": 63, "usage_type": "call"}, {"api_name": "shapely.bounds", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 66, "usage_type": "call"}, {"api_name": "shapely.linestrings", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 82, "usage_type": "attribute"}, {"api_name": "shapely.get_parts", "line_number": 120, "usage_type": "call"}, {"api_name": "shapely.polygonize", "line_number": 120, "usage_type": "call"}, {"api_name": "shapely.bounds", "line_number": 132, "usage_type": "call"}, {"api_name": "plankassembly.datasets.data_utils.quantize_values", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 143, "usage_type": "attribute"}, {"api_name": "numpy.lexsort", "line_number": 144, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 158, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 173, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 174, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 175, "usage_type": "call"}, {"api_name": "plankassembly.datasets.data_utils.quantize_values", "line_number": 190, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 193, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 197, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 201, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 216, "usage_type": "call"}, {"api_name": "os.path", "line_number": 216, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 217, "usage_type": "call"}, {"api_name": "shapely.from_geojson", "line_number": 222, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 224, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 225, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 228, "usage_type": "call"}, {"api_name": "numpy.random.random", "line_number": 232, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 232, "usage_type": "attribute"}, {"api_name": "plankassembly.datasets.data_utils.add_noise", "line_number": 234, "usage_type": "call"}, {"api_name": "shapely.from_geojson", "line_number": 241, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 242, "usage_type": "call"}]} +{"seq_id": "33043540698", "text": "import urllib.request\nfrom bs4 import BeautifulSoup\nfrom datetime import date\nimport re\nimport csv\n\nfrom backend import createGlobalEstatesCsv, updateOffers\nfrom consts import OFFICE_PROPERTY, NEWLINE, WRITING_MODE, DELIMITER, ENCODING, HEADERS\nfrom progressBar import ProgressBar\nfrom scrapers.american.myhelpers import TEMP_ARR, TEMPLATE, LINKS, FIELD_NAMES, APARTMENT, PLOT, HOUSE, TYPES\nfrom helpers import getFileName\n\n\nclass Searcher:\n progressBar = None\n today = date.today()\n result = []\n offers_len = 0\n offers = {\n 'mieszkanie': {\n 'count': 1,\n 'links': []\n },\n 'dom': {\n 'count': 1,\n 'links': []\n },\n 'dzialka': {\n 'count': 1,\n 'links': []\n },\n 'lokal': {\n 'count': 2,\n 'links': []\n },\n }\n\n def getValue(self, value):\n value = dict(zip(range(len(value)), value))\n if value.get(1):\n temp_text = str(value.get(1))\n temp_text = temp_text.replace('', '')\n temp_text = temp_text.replace('', '')\n return str(value.get(0)) + temp_text\n else:\n return str(value.get(0))\n\n def findValues(self, offer, key, temp_arr):\n temp = temp_arr.copy()\n r = urllib.request.urlopen(offer)\n soup = BeautifulSoup(r, \"html.parser\")\n photos = ''\n count_photos = 0\n temp['typ'] = key\n temp['link'] = offer\n temp['nazwa_biura'] = 'American Home'\n for values in soup.findAll('div', class_='area'):\n if values.strong.previous_sibling.find(''):\n if 'Piętro' == values.strong.previous_sibling.get_text():\n if re.findall(\"(.*)/.\", self.getValue(values.strong.contents)):\n temp['pietro'] = re.findall(\"(.*)/.\", self.getValue(values.strong.contents))[0]\n if re.findall(\".*/(.*)\", self.getValue(values.strong.contents)):\n temp['budynek_pietra'] = re.findall(\".*/(.*)\", self.getValue(values.strong.contents))[0]\n elif 'dzialka' == key and 'Powierzchnia' == values.strong.previous_sibling.get_text():\n temp['powierzchnia_dzialki'] = self.getValue(values.strong.contents)\n elif 'Cena' == values.strong.previous_sibling.get_text():\n temp['cena'] = ''.join(re.findall(\"(\\d*\\d)\", self.getValue(values.strong.contents)))\n elif 'Numer oferty' == values.strong.previous_sibling.get_text():\n temp['numer_oferty'] = self.getValue(values.strong.contents)\n temp['nr_oferty'] = self.getValue(values.strong.contents)\n elif values.strong.previous_sibling.get_text() in FIELD_NAMES:\n temp[FIELD_NAMES[values.strong.previous_sibling.get_text()]] = self.getValue(\n values.strong.contents)\n else:\n if values.strong.previous_sibling.previous_sibling + values.strong.previous_sibling.get_text() in FIELD_NAMES:\n temp[FIELD_NAMES[\n values.strong.previous_sibling.previous_sibling + values.strong.previous_sibling.get_text()]] = self.getValue(\n values.strong.contents)\n\n for values in soup.findAll('div', class_='tab-pane fade active in'):\n temp['opis'] = values.find_next(class_='property-detail_overview').get_text()\n for values in soup.findAll('i', class_='fa fa-phone'):\n temp['telefon'] = values.find_next('a').get_text()\n for values in soup.findAll('i', class_='fa fa-envelope-o'):\n temp['email'] = values.find_next('a').get_text()\n for values in soup.findAll('a', class_='blueimp'):\n photos += \"https://www.americanhome.pl/\" + values['href'] + ','\n count_photos = count_photos + 1\n temp['zdjecia_linki'] = photos\n temp['zdjecie_glowne'] = photos.split(',')[0]\n temp['zdjecie_glowne_link'] = photos.split(',')[0]\n temp['liczba_zdjec'] = count_photos\n temp['data_skanowania'] = self.today.strftime(\"%d/%m/%Y\")\n self.progressBar.progress()\n return temp\n\n def searchOffers(self):\n for link in LINKS:\n if len(self.offers[TYPES[(link.split('/'))[4]]]['links']) >= 5:\n continue\n r = urllib.request.urlopen(link)\n soup = BeautifulSoup(r, \"html.parser\", from_encoding=\"iso-8859-1\")\n for offer in soup.findAll('a', href=True):\n if len(self.offers[TYPES[(link.split('/'))[4]]]['links']) == 5:\n continue\n if TEMPLATE in offer['href']:\n if offer['href'] not in self.offers[TYPES[(link.split('/'))[4]]]['links']:\n self.offers[TYPES[(link.split('/'))[4]]]['links'].append(offer['href'])\n\n def getOffers(self):\n for key in self.offers.keys():\n for offer in self.offers[key]['links']:\n self.result.append(self.findValues(offer, key, TEMP_ARR))\n\n def saveToFile(self):\n with open(getFileName(OFFICE_PROPERTY['american']), WRITING_MODE, newline=NEWLINE, encoding=ENCODING) as f:\n writer = csv.DictWriter(f, delimiter=DELIMITER, fieldnames=HEADERS)\n writer.writerows(self.result)\n\n def run(self, root):\n self.progressBar = ProgressBar(root, 20)\n self.searchOffers()\n self.getOffers()\n self.saveToFile()\n\n\ndef startAmerican(root, loader, updateOfferLabel, updateNewOffers):\n searcher = Searcher()\n searcher.run(root)\n updateOffers(root, loader, updateOfferLabel, updateNewOffers)\n\n", "repo_name": "dilejt/Scraper", "sub_path": "scrapers/american/american.py", "file_name": "american.py", "file_ext": "py", "file_size_in_byte": 5724, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "datetime.date.today", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 16, "usage_type": "name"}, {"api_name": "urllib.request.request.urlopen", "line_number": 50, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 50, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 50, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 51, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 60, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 61, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 62, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 63, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 67, "usage_type": "call"}, {"api_name": "scrapers.american.myhelpers.FIELD_NAMES", "line_number": 71, "usage_type": "name"}, {"api_name": "scrapers.american.myhelpers.FIELD_NAMES", "line_number": 72, "usage_type": "name"}, {"api_name": "scrapers.american.myhelpers.FIELD_NAMES", "line_number": 75, "usage_type": "name"}, {"api_name": "scrapers.american.myhelpers.FIELD_NAMES", "line_number": 76, "usage_type": "name"}, {"api_name": "scrapers.american.myhelpers.LINKS", "line_number": 98, "usage_type": "name"}, {"api_name": "scrapers.american.myhelpers.TYPES", "line_number": 99, "usage_type": "name"}, {"api_name": "urllib.request.request.urlopen", "line_number": 101, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 101, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 101, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 102, "usage_type": "call"}, {"api_name": "scrapers.american.myhelpers.TYPES", "line_number": 104, "usage_type": "name"}, {"api_name": "scrapers.american.myhelpers.TEMPLATE", "line_number": 106, "usage_type": "name"}, {"api_name": "scrapers.american.myhelpers.TYPES", "line_number": 107, "usage_type": "name"}, {"api_name": "scrapers.american.myhelpers.TYPES", "line_number": 108, "usage_type": "name"}, {"api_name": "scrapers.american.myhelpers.TEMP_ARR", "line_number": 113, "usage_type": "argument"}, {"api_name": "consts.WRITING_MODE", "line_number": 116, "usage_type": "argument"}, {"api_name": "helpers.getFileName", "line_number": 116, "usage_type": "call"}, {"api_name": "consts.OFFICE_PROPERTY", "line_number": 116, "usage_type": "name"}, {"api_name": "consts.NEWLINE", "line_number": 116, "usage_type": "name"}, {"api_name": "consts.ENCODING", "line_number": 116, "usage_type": "name"}, {"api_name": "csv.DictWriter", "line_number": 117, "usage_type": "call"}, {"api_name": "consts.DELIMITER", "line_number": 117, "usage_type": "name"}, {"api_name": "consts.HEADERS", "line_number": 117, "usage_type": "name"}, {"api_name": "progressBar.ProgressBar", "line_number": 121, "usage_type": "call"}, {"api_name": "backend.updateOffers", "line_number": 130, "usage_type": "call"}]} +{"seq_id": "40174553337", "text": "#!/usr/bin/env python\n\"\"\"\nexample creation of PNGs for use with this program:\n./FigureMaker.py in/apr14T085454.ini\n\nFor a real video root directory, finds all the time results and makes multipage GIFs or TIFFs as you like from the PNGs\nif you have very many PNGs, you might like to use FFV1 in an .avi instead of .gif.\n\nMotivation: I have two separate programs (histfeas, histutils) that each create complicated figures. There is NOT currently\nhttp://stackoverflow.com/questions/22521560/how-to-combine-several-matplotlib-figures-into-one-figure\na good way to combine two figures into one, even by grabbing axes.\n\nRecommendation was to do this--create PNGs and smash together in post-processing.\n\"\"\"\nfrom pathlib import Path\nfrom wand.image import Image\nfrom tempfile import NamedTemporaryFile\nimport subprocess\n\n# from wand.exceptions import WandError\n# from wand.display import display\n\nMINHEIGHT = 500 # each element of canvas will be scaled up to at least this height--avoids widely disparate image sizes\n\n\ndef pngsmash(rdir, impat, fpat, outfn):\n rdir = Path(rdir).expanduser()\n outfn = Path(outfn).expanduser()\n\n if not outfn.suffix:\n raise ValueError(\n \"you must specify a suffix e.g. .gif to the output filename so that Wand knows what format to write\"\n )\n\n ilist = sorted(rdir.glob(impat))\n flist = sorted(rdir.glob(fpat))\n\n assert len(ilist) == len(flist), \"unequal len() {} & {} {} != {}\".format(\n ilist, flist, len(ilist), len(flist)\n )\n\n with Image() as anim:\n for i, f in zip(ilist, flist):\n with Image(filename=str(i)) as I, Image(filename=str(f)) as F, Image() as J:\n #%% enforce minimum height (aspect-preserving scale increase if needed)\n for im in (I, F):\n if im.height < MINHEIGHT:\n im.transform(resize=\"x\" + str(MINHEIGHT))\n #%% compose composite canvas\n J.blank(\n max(I.width, F.width), I.height + F.height\n ) # blank canvas on which to place images\n J.composite(F, 0, 0) # add data to canvas\n J.composite(I, 0, F.height) # add video frame to canvas\n anim.sequence.append(J)\n\n if outfn.suffix == \".gif\":\n print(\"writing\", outfn)\n anim.save(filename=str(outfn))\n elif outfn.suffix in (\".avi\", \".mp4\", \".ogv\", \".webm\"):\n with NamedTemporaryFile(\n suffix=\".gif\"\n ) as f: # forcing .gif temp since it's what Wand can handle\n print(\"using tempfile\", f.name)\n anim.save(filename=f.name) # the handle didn't work for some reason\n print(\"writing\", outfn)\n # NOTE: -c:v ffv\n subprocess.call([\"ffmpeg\", \"-i\", f.name, \"-c:v\", \"ffv1\", outfn])\n\n\nif __name__ == \"__main__\":\n from argparse import ArgumentParser\n\n p = ArgumentParser()\n p.add_argument(\"rdir\", help=\"directory where the sim/inversion output PNGs are\")\n p.add_argument(\"ofn\", help=\"output GIF filename\")\n p.add_argument(\"-i\", \"--impat\", help=\"glob pattern for raw image PNG\", default=\"rawFrame*.png\")\n p.add_argument(\"-f\", \"--fpat\", help=\"glob pattern for inversion PNG\", default=\"est*.png\")\n p = p.parse_args()\n\n pngsmash(p.rdir, p.impat, p.fpat, p.ofn)\n\n\n\"\"\"\nold way\n#!/bin/sh\n\ntmpfn=/tmp/$(printf \"%03d\" $i)tmp.png\necho \"${flist[i]} ${glist[i]} -> $tmpfn\"\nconvert -append \"${flist[i]}\" \"${glist[i]}\" tmpfn\ndone\n\nconvert -convert -delay 30 /tmp/*tmp.png $rdir/$outfn\nrm /tmp/*tmp.png\n\"\"\"\n", "repo_name": "space-physics/histfeas", "sub_path": "Plots/CombineTimePlots.py", "file_name": "CombineTimePlots.py", "file_ext": "py", "file_size_in_byte": 3598, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pathlib.Path", "line_number": 27, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 28, "usage_type": "call"}, {"api_name": "wand.image.Image", "line_number": 42, "usage_type": "call"}, {"api_name": "wand.image.Image", "line_number": 44, "usage_type": "call"}, {"api_name": "tempfile.NamedTemporaryFile", "line_number": 61, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 68, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 74, "usage_type": "call"}]} +{"seq_id": "11610500510", "text": "import collections\nimport math\ndef numberOfBoomerangs(points):\n nums = 0\n for x1, y1 in points:\n distance = collections.defaultdict(int)\n for x2, y2 in points:\n \tdx = abs(x2-x1)\n \tdy = abs(y2-y1)\n \td = dx*dx+dy*dy\n \tdistance[d]+=1\n\n print(distance)\n nums += sum(n * (n-1) for n in distance.values())\n\n return nums\n\n\n\nprint(numberOfBoomerangs([[0,0],[1,0],[1,0]]))\n\n\n\n\t\t\n\n\n", "repo_name": "ted801008/Practice", "sub_path": "leetcode/numberOfBoomerangs.py", "file_name": "numberOfBoomerangs.py", "file_ext": "py", "file_size_in_byte": 437, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "collections.defaultdict", "line_number": 6, "usage_type": "call"}]} +{"seq_id": "9868402619", "text": "import gym\nfrom gym import spaces\nimport numpy as np\n\nLEN_LOOKBACK = 10\nLEN_EPISODE = 500\n\n\n\nclass InsuranceEnv(gym.Env):\n\n def __init__(self, num_agents, num_insurances):\n super(InsuranceEnv, self).__init__()\n\n self.NUM_AGENTS = num_agents\n self.NUM_INSURANCES = num_insurances\n\n self.safe_mu = 0\n self.safe_sigma = 0.1\n self.risky_mu = 0\n self.risky_sigma = 1\n self.insurance_return = 0\n\n self.action_space = spaces.Discrete(2+2*self.NUM_INSURANCES)\n \"\"\"\n 0: Safe non-insured\n 1: Risky non-insured\n 2: Safe insured\n 3: Risky insured\n 4: Safe insured2\n ...\n \"\"\"\n\n self.action_switcher = {\n 0: (self.safe_mu, self.safe_sigma, 0.),\n 1: (self.risky_mu, self.risky_sigma, 0.),\n }\n\n for i in range(self.NUM_INSURANCES*2):\n if i % 2 == 0:\n self.action_switcher[i+2] = (self.safe_mu, self.safe_sigma, 1.)\n else:\n self.action_switcher[i+2] = (self.risky_mu, self.risky_sigma, 1.)\n\n\n self.observation_space = spaces.Dict({\n 'was_insured': spaces.MultiBinary(LEN_LOOKBACK),\n 'insurance_costs': spaces.Box(low=0.0, high=1.0, shape=(LEN_LOOKBACK,), dtype=np.float32),\n 'new_cost': spaces.Box(low=0.0, high=1.0, shape=(1,), dtype=np.float32)\n })\n\n self.reset()\n\n def step(self, agent_actions):\n agent_rewards = [0.0 for _ in range(self.NUM_AGENTS)]\n insurance_rewards = [-.01 for _ in range(self.NUM_INSURANCES)]\n\n if not type(agent_actions) == list or type(agent_actions) == np.array:\n agent_actions = [agent_actions]\n\n for agent_id, agent_action in enumerate(agent_actions):\n\n mu, sigma, insured = self.action_switcher.get(agent_action, (0, 0, 0.0))\n\n insurance_id = agent_action//2 - 1\n insurance_cost = self.current_cost[insurance_id]\n\n self.action_counter[agent_id, agent_action] += 1\n\n agent_reward = np.random.normal(mu, sigma)\n insurer_reward = 0\n if insured == 1.:\n if agent_reward < self.insurance_return:\n insurer_reward = agent_reward - self.insurance_return + insurance_cost\n agent_reward = self.insurance_return - insurance_cost\n else:\n agent_reward -= insurance_cost\n insurer_reward = insurance_cost\n\n self.was_insured[agent_id].pop(0)\n self.was_insured[agent_id].append(insured)\n self.insurance_costs[insurance_id].pop(0)\n self.insurance_costs[insurance_id].append(self.get_insurance_cost(insurance_id))\n\n agent_rewards[agent_id] = agent_reward\n insurance_rewards[insurance_id] += insurer_reward\n\n self.num_trials -= 1\n\n done = self.num_trials == 0\n\n observation = self.get_obs()\n\n \"\"\"Try to force insurance to make price competitive\"\"\"\n # insurer_reward -= .01\n\n return [observation for _ in range(self.NUM_INSURANCES+self.NUM_AGENTS)], (*insurance_rewards, *agent_rewards),\\\n done, None\n\n \"\"\"Get action from insurance\"\"\"\n\n \"\"\"Get action from agent\"\"\"\n\n \"\"\"\"Calculate rewards\"\"\"\n\n \"\"\"Save rewards in replay memory\"\"\"\n\n \"\"\"Train insurance and agent\"\"\"\n\n def get_obs(self):\n obs = np.zeros((self.NUM_INSURANCES, 21), dtype=np.float32)\n\n obs[:, :10] = self.was_insured\n obs[:, 10:20] = self.insurance_costs\n obs[:, 20] = self.current_cost\n return obs\n\n def reset(self):\n self.was_insured = [[0.0 for _ in range(LEN_LOOKBACK)] for _ in range(self.NUM_AGENTS)]\n self.insurance_costs = [[0.0 for _ in range(LEN_LOOKBACK)] for _ in range(self.NUM_INSURANCES)]\n self.set_insurance_cost()\n self.num_trials = LEN_EPISODE\n\n self.action_counter = np.zeros((self.NUM_AGENTS, self.NUM_INSURANCES*2+2))\n\n return [self.get_obs() for _ in range(self.NUM_INSURANCES+self.NUM_AGENTS)]\n\n def set_insurance_cost(self, insurance_cost: float = 0.0, insurance_id=None):\n if insurance_id is None:\n self.current_cost = [insurance_cost for _ in range(self.NUM_INSURANCES)]\n else:\n if insurance_id > self.NUM_INSURANCES:\n raise Exception('Insurance ID higher than number of insurances (ID: {}, insurances: {}'.format(\n insurance_id, self.NUM_INSURANCES\n ))\n self.current_cost[insurance_id] = insurance_cost\n\n def get_insurance_cost(self, insurance_id=None):\n if insurance_id is None:\n return self.current_cost\n else:\n if insurance_id > self.NUM_INSURANCES:\n raise Exception('Insurance ID higher than number of insurances (ID: {}, insurances: {}'.format(\n insurance_id, self.NUM_INSURANCES\n ))\n return self.current_cost[insurance_id]\n\n def render(self, mode='human', close=False):\n pass\n", "repo_name": "valko073/rl_insurance", "sub_path": "insurance_env.py", "file_name": "insurance_env.py", "file_ext": "py", "file_size_in_byte": 5107, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "gym.Env", "line_number": 10, "usage_type": "attribute"}, {"api_name": "gym.spaces.Discrete", "line_number": 24, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 24, "usage_type": "name"}, {"api_name": "gym.spaces.Dict", "line_number": 46, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 46, "usage_type": "name"}, {"api_name": "gym.spaces.MultiBinary", "line_number": 47, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 47, "usage_type": "name"}, {"api_name": "gym.spaces.Box", "line_number": 48, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 48, "usage_type": "name"}, {"api_name": "numpy.float32", "line_number": 48, "usage_type": "attribute"}, {"api_name": "gym.spaces.Box", "line_number": 49, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 49, "usage_type": "name"}, {"api_name": "numpy.float32", "line_number": 49, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 58, "usage_type": "attribute"}, {"api_name": "numpy.random.normal", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 70, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 111, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 124, "usage_type": "call"}]} +{"seq_id": "27877853094", "text": "import io\nimport os\nfrom setuptools import setup\n\nimport monkeypatch # pylint: disable=W0611\n\ndef read_contents(*names, **kwargs):\n return io.open(\n os.path.join(*names),\n encoding=kwargs.get(\"encoding\", \"utf8\")\n ).read()\n\ndescription = 'Environment variable editor.'\ntry:\n long_description = read_contents(os.path.dirname(__file__), 'README.rst')\nexcept:\n long_description = description\n\nsetup(name='enveditor',\n version='0.1',\n description=description,\n long_description=long_description,\n author='Simon Kennedy',\n author_email='sffjunkie+code@gmail.com',\n url=\"https://github.com/sffjunkie/astral\",\n license='Apache-2.0',\n classifiers=[\n \"Intended Audience :: Developers\",\n \"Programming Language :: Python :: 3\",\n ],\n package_dir={'': 'src'},\n packages=['enveditor'],\n tests_require=['pytest-runner'],\n)\n", "repo_name": "sffjunkie/enveditor", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 907, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "io.open", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "setuptools.setup", "line_number": 19, "usage_type": "call"}]} +{"seq_id": "3069640037", "text": "from django.shortcuts import render,get_object_or_404,reverse,redirect\nfrom .models import Post\nfrom .froms import CreatePostForm, PostEditForm\n\n# Create your views here.\n\n\n\n\ndef PostList(request):\n postlist = Post.objects.all()\n context = {\n \"postlist\":postlist\n }\n template_name = \"postlist.html\"\n return render(request,template_name,context)\n\n\n\n\ndef PostDetail(request,id):\n post = get_object_or_404(Post,id=id)\n context = {\n 'post':post\n }\n template_name = \"postdetail.html\"\n return render(request,template_name,context)\n\n\ndef PostUpdateis(request,id):\n post = get_object_or_404(Post,id=id)\n if request.user != post.Author :\n return redirect(\"home\")\n else :\n if request.method == \"POST\" :\n form = PostEditForm(request.POST ,instance=post)\n if form.is_valid():\n form.save()\n return redirect(\"home\")\n else:\n form = PostEditForm(instance=post)\n return render(request,\"update-post.html\",context={\"form\":form})\n\ndef CreatPost(request):\n if request.method == \"POST\":\n form = CreatePostForm(request.POST or None)\n if form.is_valid():\n new_post= form.save(commit=False)\n new_post.Author = request.user\n new_post.save()\n return redirect(\"home\")\n else:\n form = CreatePostForm()\n context = {\"form\":form }\n template_name=\"CreatePostForm.html\"\n return render(request,template_name,context)\n\n\n\n\n", "repo_name": "riddick1368/Create_shop_online_Postgres", "sub_path": "ecommerce/blog/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1505, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "models.Post.objects.all", "line_number": 11, "usage_type": "call"}, {"api_name": "models.Post.objects", "line_number": 11, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 11, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 16, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 22, "usage_type": "call"}, {"api_name": "models.Post", "line_number": 22, "usage_type": "argument"}, {"api_name": "django.shortcuts.render", "line_number": 27, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 31, "usage_type": "call"}, {"api_name": "models.Post", "line_number": 31, "usage_type": "argument"}, {"api_name": "django.shortcuts.redirect", "line_number": 33, "usage_type": "call"}, {"api_name": "froms.PostEditForm", "line_number": 36, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 39, "usage_type": "call"}, {"api_name": "froms.PostEditForm", "line_number": 41, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 42, "usage_type": "call"}, {"api_name": "froms.CreatePostForm", "line_number": 46, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 51, "usage_type": "call"}, {"api_name": "froms.CreatePostForm", "line_number": 53, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 56, "usage_type": "call"}]} +{"seq_id": "412468980", "text": "import logging\nfrom datetime import datetime\nimport os\n\n# Creating logs directory to store log in files\nLOG_DIR = \"Insurance_log\"\n\n# Creating file name for log file based on current timestamp\nCURRENT_TIME_STAMP = f\"{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}\"\n\n# Here, We are going to define the path to store log with folder_name\nLOG_FIlE_NAME = f\"log_{CURRENT_TIME_STAMP}.log\"\n\n\n#Creating LOG_DIR if it does not exists.\nos.makedirs(LOG_DIR, exist_ok=True)\n\n#Creating file path for projects.\nLOG_FIlE_PATH = os.path.join(LOG_DIR, LOG_FIlE_NAME)\n\n# If you want to read log select baseconfig and press f12 from your system.\nlogging.basicConfig(filename=LOG_FIlE_PATH,\nfilemode = \"w\",\nformat = '[%(asctime)s] %(name)s - %(levelname)s - %(message)s',\n#level=logging.INFO,\nlevel=logging.DEBUG,\n)", "repo_name": "Shivan118/Project-EWB", "sub_path": "Insurance/logger/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 794, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "24", "api": [{"api_name": "datetime.datetime.now", "line_number": 9, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 9, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "logging.basicConfig", "line_number": 22, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 26, "usage_type": "attribute"}]} +{"seq_id": "34460065110", "text": "import serial\nimport serial.tools.list_ports\nimport os\nimport subprocess\nimport time\nimport stream\nfrom utils import parsers\nfrom tkinter import messagebox\n\n\ndef pre_test():\n \"\"\" Runs the pre-test to check if what is required for etching is ready\n\n This pre-test runs the homing.gcode file, which attemps to home the stage\n first, then home the stage to the origin point of the 3D glass cube\n \"\"\"\n mcu_serial = parsers.get_from_config('serial_number', os.path.dirname(os.path.realpath(__file__)))\n device_path = _get_device_path(mcu_serial)\n reason = ''\n\n # Some spaghetti logic up in here\n if device_path is False:\n reason = 'Could not find correct serial port'\n result = False\n else:\n result = _home_stage(device_path)\n if result is False:\n reason = 'Error in streaming'\n\n ret_dict = dict()\n ret_dict['device'] = device_path\n ret_dict['result'] = result\n ret_dict['reason'] = reason\n return ret_dict\n\n\ndef _get_device_path(target_serial=None):\n \"\"\" Returns the device path for first match of given serial \"\"\"\n if target_serial is None:\n return False\n\n ports = list(serial.tools.list_ports.comports())\n for p in ports:\n if p.serial_number == target_serial:\n return p.device\n\n return False\n\n\ndef _home_stage(device_path):\n \"\"\" Homes the stage to begin etching process \"\"\"\n homing_gcode = os.path.dirname(os.path.realpath(__file__)) + '\\\\homing.gcode'\n# streaming_file = os.path.dirname(os.path.realpath(__file__)) + '\\\\stream.py'\n return stream.start_stream(homing_gcode, device_path)\n\n\ndef full_test(filename, device_path):\n \"\"\" Initiates the stream for the given gcode file\n\n Requires the gcode file to be passed in and the device path\n \"\"\"\n result = stream.start_stream(filename, device_path)\n if result is False:\n reason = 'CRITICAL ERROR STREAMING GCODE'\n else:\n reason =''\n\n return result, reason\n\n\ndef start_laser():\n \"\"\" Establishes a connection and fires the laser \"\"\"\n laser_serial = parsers.get_from_config('laser_number', os.path.dirname(os.path.realpath(__file__)))\n device_path = _get_device_path(laser_serial)\n\n if device_path is False:\n message = 'Could not find laser to turn on! Turn it on manually!\\n' \\\n 'Etching process will continue after this is closed'\n messagebox.showerror(title='Error', message=message)\n return\n\n s = serial.Serial(device_path, 9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)\n s.write('$FIRE 01\\r'.encode())\n s.close()\n\n\ndef stop_laser():\n \"\"\" Stops the laser \"\"\"\n laser_serial = parsers.get_from_config('laser_number', os.path.dirname(os.path.realpath(__file__)))\n device_path = _get_device_path(laser_serial)\n\n if device_path is False:\n message = 'Could not find laser to turn off! Turn it off manually!\\n'\n messagebox.showerror(title='Error', message=message)\n return\n\n s = serial.Serial(device_path, 9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)\n s.write('$STOP 00\\r'.encode())\n s.close()\n\n\nif __name__ == \"__main__\":\n print('starting')\n start_laser()\n print('stopping')\n time.sleep(2)\n stop_laser()\n\n", "repo_name": "Kommotion/Senior-Design", "sub_path": "gui/serials.py", "file_name": "serials.py", "file_ext": "py", "file_size_in_byte": 3323, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "utils.parsers.get_from_config", "line_number": 17, "usage_type": "call"}, {"api_name": "utils.parsers", "line_number": 17, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 17, "usage_type": "call"}, {"api_name": "serial.tools.list_ports.comports", "line_number": 42, "usage_type": "call"}, {"api_name": "serial.tools", "line_number": 42, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path", "line_number": 52, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 52, "usage_type": "call"}, {"api_name": "stream.start_stream", "line_number": 54, "usage_type": "call"}, {"api_name": "stream.start_stream", "line_number": 62, "usage_type": "call"}, {"api_name": "utils.parsers.get_from_config", "line_number": 73, "usage_type": "call"}, {"api_name": "utils.parsers", "line_number": 73, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path", "line_number": 73, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 73, "usage_type": "call"}, {"api_name": "tkinter.messagebox.showerror", "line_number": 79, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 79, "usage_type": "name"}, {"api_name": "serial.Serial", "line_number": 82, "usage_type": "call"}, {"api_name": "serial.PARITY_NONE", "line_number": 82, "usage_type": "attribute"}, {"api_name": "serial.STOPBITS_ONE", "line_number": 82, "usage_type": "attribute"}, {"api_name": "serial.EIGHTBITS", "line_number": 82, "usage_type": "attribute"}, {"api_name": "utils.parsers.get_from_config", "line_number": 89, "usage_type": "call"}, {"api_name": "utils.parsers", "line_number": 89, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 89, "usage_type": "call"}, {"api_name": "os.path", "line_number": 89, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 89, "usage_type": "call"}, {"api_name": "tkinter.messagebox.showerror", "line_number": 94, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 94, "usage_type": "name"}, {"api_name": "serial.Serial", "line_number": 97, "usage_type": "call"}, {"api_name": "serial.PARITY_NONE", "line_number": 97, "usage_type": "attribute"}, {"api_name": "serial.STOPBITS_ONE", "line_number": 97, "usage_type": "attribute"}, {"api_name": "serial.EIGHTBITS", "line_number": 97, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 106, "usage_type": "call"}]} +{"seq_id": "3039574006", "text": "from __future__ import print_function\nimport os.path\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom google.oauth2.credentials import Credentials\n\nimport os\nimport pickle\n# Gmail API utils\n# for encoding/decoding messages in base64\nfrom base64 import urlsafe_b64decode, urlsafe_b64encode\n# for dealing with attachement MIME types\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.image import MIMEImage\nfrom email.mime.audio import MIMEAudio\nfrom email.mime.base import MIMEBase\nfrom mimetypes import guess_type as guess_mime_type\n\n# Request all access (permission to read/send/receive emails, manage the inbox, and more)\nSCOPES = ['https://mail.google.com/']\nour_email = 'xandernaumenko@gmail.com'\n\n\ndef search_messages(service, query):\n result = service.users().messages().list(userId='me',q=query).execute()\n messages = [ ]\n if 'messages' in result:\n messages.extend(result['messages'])\n while 'nextPageToken' in result:\n page_token = result['nextPageToken']\n result = service.users().messages().list(userId='me',q=query, pageToken=page_token).execute()\n if 'messages' in result:\n messages.extend(result['messages'])\n return messages\n\n# utility functions\ndef get_size_format(b, factor=1024, suffix=\"B\"):\n \"\"\"\n Scale bytes to its proper byte format\n e.g:\n 1253656 => '1.20MB'\n 1253656678 => '1.17GB'\n \"\"\"\n for unit in [\"\", \"K\", \"M\", \"G\", \"T\", \"P\", \"E\", \"Z\"]:\n if b < factor:\n return f\"{b:.2f}{unit}{suffix}\"\n b /= factor\n return f\"{b:.2f}Y{suffix}\"\n\n\ndef clean(text):\n # clean text for creating a folder\n return \"\".join(c if c.isalnum() else \"_\" for c in text)\n\ndef parse_parts(service, parts, folder_name, message):\n \"\"\"\n Utility function that parses the content of an email partition\n \"\"\"\n ret = ''\n if parts:\n for part in parts:\n filename = part.get(\"filename\")\n mimeType = part.get(\"mimeType\")\n body = part.get(\"body\")\n data = body.get(\"data\")\n file_size = body.get(\"size\")\n part_headers = part.get(\"headers\")\n if part.get(\"parts\"):\n # recursively call this function when we see that a part\n # has parts inside\n parse_parts(service, part.get(\"parts\"), folder_name, message)\n if mimeType == \"text/plain\":\n # if the email part is text plain\n if data:\n text = urlsafe_b64decode(data).decode()\n ret += '\\n'.join([line for line in text.splitlines() if 'http' not in line]) + '\\n'\n elif mimeType == \"text/html\":\n # if the email part is an HTML content\n # save the HTML file and optionally open it in the browser\n if not filename:\n filename = \"index.html\"\n filepath = os.path.join(folder_name, filename)\n # print(\"Saving HTML to\", filepath)\n # with open(filepath, \"wb\") as f:\n # f.write(urlsafe_b64decode(data))\n else:\n # attachment other than a plain text or HTML\n for part_header in part_headers:\n part_header_name = part_header.get(\"name\")\n part_header_value = part_header.get(\"value\")\n if part_header_name == \"Content-Disposition\":\n if \"attachment\" in part_header_value:\n # we get the attachment ID \n # and make another request to get the attachment itself\n print(\"Saving the file:\", filename, \"size:\", get_size_format(file_size))\n attachment_id = body.get(\"attachmentId\")\n attachment = service.users().messages() \\\n .attachments().get(id=attachment_id, userId='me', messageId=message['id']).execute()\n data = attachment.get(\"data\")\n # filepath = os.path.join(folder_name, filename)\n # if data:\n # with open(filepath, \"wb\") as f:\n # f.write(urlsafe_b64decode(data))\n return ret\n\ndef read_message(service, message):\n \"\"\"\n This function takes Gmail API `service` and the given `message_id` and does the following:\n - Downloads the content of the email\n - Prints email basic information (To, From, Subject & Date) and plain/text parts\n - Creates a folder for each email based on the subject\n - Downloads text/html content (if available) and saves it under the folder created as index.html\n - Downloads any file that is attached to the email and saves it in the folder created\n \"\"\"\n msg = service.users().messages().get(userId='me', id=message['id'], format='full').execute()\n # parts can be the message body, or attachments\n payload = msg['payload']\n headers = payload.get(\"headers\")\n parts = payload.get(\"parts\")\n folder_name = \"email\"\n has_subject = False\n ret = ''\n if headers:\n # this section prints email basic info & creates a folder for the email\n for header in headers:\n name = header.get(\"name\")\n value = header.get(\"value\")\n if name.lower() == 'from':\n # we print the From address\n ret += \"From: \" + value + '\\n'\n if name.lower() == \"to\":\n # we print the To address\n ret += \"To:\" + value + '\\n'\n if name.lower() == \"subject\":\n # make our boolean True, the email has \"subject\"\n has_subject = True\n # make a directory with the name of the subject\n folder_name = clean(value)\n # we will also handle emails with the same subject name\n folder_counter = 0\n while os.path.isdir(folder_name):\n folder_counter += 1\n # we have the same folder name, add a number next to it\n if folder_name[-1].isdigit() and folder_name[-2] == \"_\":\n folder_name = f\"{folder_name[:-2]}_{folder_counter}\"\n elif folder_name[-2:].isdigit() and folder_name[-3] == \"_\":\n folder_name = f\"{folder_name[:-3]}_{folder_counter}\"\n else:\n folder_name = f\"{folder_name}_{folder_counter}\"\n # os.mkdir(folder_name)\n ret += \"Subject: \" + value + '\\n'\n if name.lower() == \"date\":\n # we print the date when the message was sent\n ret += \"Date:\" + value + '\\n'\n if not has_subject:\n # if the email does not have a subject, then make a folder with \"email\" name\n # since folders are created based on subjects\n if not os.path.isdir(folder_name):\n os.mkdir(folder_name)\n ret += parse_parts(service, parts, folder_name, message)\n ret += \"=\"*50 + '\\n'\n return ret\n\ndef mark_as_read(service, query):\n messages_to_mark = search_messages(service, query)\n return service.users().messages().batchModify(\n userId='me',\n body={\n 'ids': [ msg['id'] for msg in messages_to_mark ],\n 'removeLabelIds': ['UNREAD']\n }\n ).execute()\n\n\ndef register():\n creds = None\n # The file token.json stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists('token.json'):\n creds = Credentials.from_authorized_user_file('token.json', SCOPES)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n 'credentials.json', SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open('token.json', 'w') as token:\n token.write(creds.to_json())\n\n service = build('gmail', 'v1', credentials=creds)\n return service\n\ndef main():\n \"\"\"Shows basic usage of the Gmail API.\n Lists the user's Gmail labels.\n \"\"\"\n service = register()\n\n # Call the Gmail API\n results = service.users().labels().list(userId='me').execute()\n labels = results.get('labels', [])\n\n if not labels:\n print('No labels found.')\n else:\n print('Labels:')\n for label in labels:\n print(label['name'])\n\n # get emails that match the query you specify\n results = search_messages(service, \"in:UNREAD\")\n # for each email matched, read it (output plain/text to console & save HTML and attachments)\n for msg in results:\n print(read_message(service, msg))\n\n mark_as_read(service, 'in:UNREAD')\n\n\n\nif __name__ == '__main__':\n main()", "repo_name": "misprit7/messenger-spam", "sub_path": "gmail.py", "file_name": "gmail.py", "file_ext": "py", "file_size_in_byte": 9239, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "base64.urlsafe_b64decode", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 84, "usage_type": "call"}, {"api_name": "os.path", "line_number": 84, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 143, "usage_type": "call"}, {"api_name": "os.path", "line_number": 143, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 160, "usage_type": "call"}, {"api_name": "os.path", "line_number": 160, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 161, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 182, "usage_type": "call"}, {"api_name": "os.path", "line_number": 182, "usage_type": "attribute"}, {"api_name": "google.oauth2.credentials.Credentials.from_authorized_user_file", "line_number": 183, "usage_type": "call"}, {"api_name": "google.oauth2.credentials.Credentials", "line_number": 183, "usage_type": "name"}, {"api_name": "google.auth.transport.requests.Request", "line_number": 187, "usage_type": "call"}, {"api_name": "google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file", "line_number": 189, "usage_type": "call"}, {"api_name": "google_auth_oauthlib.flow.InstalledAppFlow", "line_number": 189, "usage_type": "name"}, {"api_name": "googleapiclient.discovery.build", "line_number": 196, "usage_type": "call"}]} +{"seq_id": "73112115583", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# ## Параллельная обработка изображений в многозадачной среде\n\n# In[13]:\n\n\nimport os\nfrom concurrent.futures import ThreadPoolExecutor\nfrom PIL import Image, ImageEnhance, ImageOps\n\n\n# ### Фильтры\n\n# 1. Фильтр сепии\n\n# In[14]:\n\n\ndef sepia(inp, out_path):\n try:\n image = Image.open(inp)\n sepia_image = ImageOps.colorize(image.convert('L'), '#704214', '#C0C080')\n sepia_image.save(out_path)\n except Exception as e:\n print(f'К файлу {inp} невозможно применить фильтр в виду ошибки: {str(e)}')\n\n\n# 2. Фильтр резкости\n\n# In[15]:\n\n\ndef sharpen(inp, out_path):\n try:\n image = Image.open(inp)\n sharpened_image = ImageEnhance.Sharpness(image).enhance(2.0)\n sharpened_image.save(out_path)\n except Exception as e:\n print(f'К файлу {inp} невозможно применить фильтр в виду ошибки: {str(e)}')\n\n\n# 3. Фильтр уменьшения размера\n\n# In[16]:\n\n\ndef resize(inp, out_path):\n try:\n image = Image.open(inp)\n resized_image = image.resize((300, 300))\n resized_image.save(out_path)\n except Exception as e:\n print(f'К файлу {inp} невозможно применить фильтр в виду ошибки: {str(e)}')\n\n\n# ### Обработка изображений\n\n# In[18]:\n\n\ndef process(inp, out_folder):\n image_name = os.path.basename(inp)\n filename, _ = os.path.splitext(image_name)\n\n sharpen(inp, os.path.join(out_folder, f'{filename}_f1.jpg'))\n sepia(inp, os.path.join(out_folder, f'{filename}_f2.jpg'))\n resize(inp, os.path.join(out_folder, f'{filename}_f3.jpg'))\n\ndef parallel_images(image_folder, out_folder):\n if not os.path.exists(out_folder):\n os.makedirs(out_folder)\n tasks = []\n for image_name in os.listdir(image_folder):\n image_path = os.path.join(image_folder, image_name)\n if os.path.isfile(image_path) and image_name.lower().endswith(('.png', '.jpg', '.jpeg')):\n tasks.append((image_path, out_folder))\n\n with ThreadPoolExecutor() as executor:\n executor.map(lambda args: process(*args), tasks)\n \nimage_folder = r'C:\\Users\\sibfl\\OneDrive\\photo'\nout_folder = r'C:\\Users\\sibfl\\OneDrive\\photo\\new'\n\nparallel_images(image_folder, out_folder)\n\n", "repo_name": "LisaNota/Parallel_processing", "sub_path": "parallel.py", "file_name": "parallel.py", "file_ext": "py", "file_size_in_byte": 2445, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "PIL.Image.open", "line_number": 23, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 23, "usage_type": "name"}, {"api_name": "PIL.ImageOps.colorize", "line_number": 24, "usage_type": "call"}, {"api_name": "PIL.ImageOps", "line_number": 24, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 37, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 37, "usage_type": "name"}, {"api_name": "PIL.ImageEnhance.Sharpness", "line_number": 38, "usage_type": "call"}, {"api_name": "PIL.ImageEnhance", "line_number": 38, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 51, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 51, "usage_type": "name"}, {"api_name": "os.path.basename", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path", "line_number": 64, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 67, "usage_type": "call"}, {"api_name": "os.path", "line_number": 67, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path", "line_number": 68, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 69, "usage_type": "call"}, {"api_name": "os.path", "line_number": 69, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path", "line_number": 72, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 73, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path", "line_number": 76, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path", "line_number": 77, "usage_type": "attribute"}, {"api_name": "concurrent.futures.ThreadPoolExecutor", "line_number": 80, "usage_type": "call"}]} +{"seq_id": "31132787966", "text": "import cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef measure_object(image):\n gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)\n ret, binary = cv.threshold(gray,0,255,cv.THRESH_BINARY_INV | cv.THRESH_OTSU)\n contours,hericahy = cv.findContours(binary,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)\n cv.imshow(\"binary image\",binary)\n for i,contour in enumerate(contours):\n arae = cv.contourArea(contour)\n x,y,w,h = cv.boundingRect(contour)\n rate = min(w,h)/max(w,h)\n #print(\"rectang rate : %s\"%rate)\n #输出宽高比\n #外接矩形的大小\n mm = cv.moments(contour)\n #求取几何矩\n print(type(mm))\n #是一个字典类型\n cx = mm['m10']/mm['m00']\n cy = mm['m01']/mm['m00']\n #即可得到矩形的中芯位置\n #cv.circle(image,(np.int(cx),np.int(cy)),3,(0,255,255),-1)\n #cv.rectangle(image,(x,y),(x+w,y+h),(0,0,255),2)\n #绘制外接矩形\n #print(\"contour arae :%s\"%arae)\n approxCurve = cv.approxPolyDP(contour,4,True)\n if approxCurve.shape[0] ==4:\n cv.drawContours(image,contours,i,(0,255,0),2)\n cv.imshow('measure',image)\n\nscr = cv.imread(\"D:/opencvtupian/12.jpg\")\n#读取一张图片\ncv.namedWindow(\"input image\",cv.WINDOW_AUTOSIZE)\n#创建GUI显示图片\ncv.imshow(\"input image\",scr)\nmeasure_object(scr)\ncv.waitKey(0)\ncv.destroyAllWindows()", "repo_name": "1YangTao1/YT_study-note", "sub_path": "opencv/tutorial_20对象测量.py", "file_name": "tutorial_20对象测量.py", "file_ext": "py", "file_size_in_byte": 1424, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "cv2.cvtColor", "line_number": 6, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 6, "usage_type": "attribute"}, {"api_name": "cv2.threshold", "line_number": 7, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY_INV", "line_number": 7, "usage_type": "attribute"}, {"api_name": "cv2.THRESH_OTSU", "line_number": 7, "usage_type": "attribute"}, {"api_name": "cv2.findContours", "line_number": 8, "usage_type": "call"}, {"api_name": "cv2.RETR_EXTERNAL", "line_number": 8, "usage_type": "attribute"}, {"api_name": "cv2.CHAIN_APPROX_SIMPLE", "line_number": 8, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 9, "usage_type": "call"}, {"api_name": "cv2.contourArea", "line_number": 11, "usage_type": "call"}, {"api_name": "cv2.boundingRect", "line_number": 12, "usage_type": "call"}, {"api_name": "cv2.moments", "line_number": 17, "usage_type": "call"}, {"api_name": "cv2.approxPolyDP", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.drawContours", "line_number": 30, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 31, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.namedWindow", "line_number": 35, "usage_type": "call"}, {"api_name": "cv2.WINDOW_AUTOSIZE", "line_number": 35, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 37, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 39, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 40, "usage_type": "call"}]} +{"seq_id": "30655850968", "text": "\"\"\"\nSubmodule for creating Iogas XML templates from matplotlib axes.\n\"\"\"\nimport numpy as np\nfrom lxml.etree import ElementTree\nfrom pyrolite.util.text import int_to_alpha\nfrom pyrolite.util.plot import get_contour_paths\nfrom pyrolite.util.meta import subkwargs\n\nfrom ..util.xml import prettify_xml\nfrom .common import Poly, Polygon, RegionPolygon\nfrom . import freediagram\nfrom . import geochemdiagram\nfrom . import freeternary\n\nfrom pyrolite.geochem.ind import common_elements, common_oxides\n\n__els__ = common_elements(as_set=True)\n__ox__ = common_oxides(as_set=True)\n__chem__ = __els__ | __ox__\n\n\ndef contours_to_XYDiagram(\n ax,\n xvar=\"X\",\n yvar=\"Y\",\n logscalex=False,\n logscaley=False,\n logxdata=False,\n logydata=False,\n filename=\"element.xml\",\n contournames=None,\n allow_free_func=True,\n resolution=100,\n description_prefix=\"\",\n encoding=\"utf-8\",\n):\n \"\"\"\n Take the contour lines from an axis and convert them to an iogas xml diagram\n template.\n\n Parameters\n ------------\n\n Note\n ------\n\n The polygons need not return to the same point.\n\n If the diagram is for log, the coordinates need to be log.\n \"\"\"\n filename = str(filename)\n if all([i in __chem__ for i in xvar.split(\"/\")]) and all(\n [i in __chem__ for i in yvar.split(\"/\")]\n ):\n dg = geochemdiagram.XYDiagram\n poly = Poly\n else:\n dg = freediagram.XYDiagram\n if allow_free_func and any([\"/\" in v for v in [xvar, yvar]]):\n poly = RegionPolygon\n else:\n poly = Poly\n sk = subkwargs(\n dict(\n logscalex=logscalex,\n logscaley=logscaley,\n logxdata=logxdata,\n logydata=logydata,\n allow_free_func=allow_free_func,\n ),\n dg,\n )\n diagram = dg(xvar, yvar, **sk)\n cpaths, cnames, styles = get_contour_paths(ax, resolution=resolution)\n if contournames is not None:\n assert len(contournames) == len(cpaths)\n cnames = contournames\n # create contours\n contours = []\n for ix, (p, name, sty) in enumerate(zip(cpaths, cnames, styles)):\n for six, subpath in enumerate(p):\n if logxdata:\n subpath[0] = np.log(subpath[0])\n if logydata:\n subpath[1] = np.log(subpath[1])\n if len(p) != 1:\n suffix = \"-\" + int_to_alpha(six)\n else:\n suffix = \"\"\n cname = [\"Countour-{}\".format(name), \"Countour-{}\".format(ix)][\n name is None\n ] + suffix\n c = poly(\n subpath,\n color=sty[\"color\"],\n name=str(name),\n description=description_prefix,\n )\n contours.append(c)\n diagram.extend(contours)\n version_poly = Polygon(\n name=\"_ v6.1 required to open diagram _\",\n visible=\"true\",\n xpoints=[30, 200, 200, 30],\n ypoints=[30, 30, 40, 40],\n )\n\n diagram.extend([version_poly])\n ElementTree(diagram).write(filename, method=\"xml\", encoding=encoding)\n return prettify_xml(diagram)\n\n\ndef contours_to_FreeTernaryDiagram():\n pass\n", "repo_name": "morganjwilliams/gas-templates", "sub_path": "pyogas/writer/mpl2iogas.py", "file_name": "mpl2iogas.py", "file_ext": "py", "file_size_in_byte": 3186, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pyrolite.geochem.ind.common_elements", "line_number": 18, "usage_type": "call"}, {"api_name": "pyrolite.geochem.ind.common_oxides", "line_number": 19, "usage_type": "call"}, {"api_name": "common.Poly", "line_number": 57, "usage_type": "name"}, {"api_name": "common.RegionPolygon", "line_number": 61, "usage_type": "name"}, {"api_name": "common.Poly", "line_number": 63, "usage_type": "name"}, {"api_name": "pyrolite.util.meta.subkwargs", "line_number": 64, "usage_type": "call"}, {"api_name": "pyrolite.util.plot.get_contour_paths", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 86, "usage_type": "call"}, {"api_name": "pyrolite.util.text.int_to_alpha", "line_number": 88, "usage_type": "call"}, {"api_name": "common.Polygon", "line_number": 102, "usage_type": "call"}, {"api_name": "lxml.etree.ElementTree", "line_number": 110, "usage_type": "call"}, {"api_name": "util.xml.prettify_xml", "line_number": 111, "usage_type": "call"}]} +{"seq_id": "73775367741", "text": "# Imports\nimport itertools\nimport tarfile\nimport pandas\nimport pickle\n\n# Sklearn imports\nimport nltk\nimport nltk.collocations\n\n# LexNLP imports\nimport lexnlp.nlp.en.segments.sentences\nimport lexnlp.nlp.en.tokens\n\n# Setup default path for documents\ntar_input_path = \"agreements-text.tar.gz\"\n\n# Store tokens\ntokens = []\nbigrams = []\n\n# Set sample size in docs\nnum_samples = 1000\n\n# Set parameters\ncutoff_amount = 0.5\ntop_n_list = [100, 1000, 10000]\nmin_freq = 100\n\nif __name__ == \"__main__\":\n # Set number of samples\n num_samples = 10000\n\n # Initialize frequency distributions\n token_fd = nltk.FreqDist()\n wildcard_fd = nltk.FreqDist()\n bigram_fd = nltk.FreqDist()\n trigram_fd = nltk.FreqDist()\n\n # Iterate through files\n with tarfile.open(tar_input_path, \"r:gz\") as corpus_tar_file:\n # Get list of files\n member_list = corpus_tar_file.getmembers()[0:num_samples]\n num_members = len(member_list)\n\n # Iterate through all\n for i, tar_member in enumerate(member_list):\n # Output\n if i % 100 == 0:\n print((tar_input_path, i, float(i)/num_members * 100., tar_member.name, len(member_list)))\n\n # Read buffer\n member_file = corpus_tar_file.extractfile(tar_member.name)\n if member_file is None:\n print((tar_input_path, tar_member.name, \"invalid file\"))\n continue\n member_buffer = member_file.read().decode(\"utf-8\")\n if len(member_buffer.strip()) == 0:\n continue\n\n # Parse into sentence data\n try:\n for sentence in lexnlp.nlp.en.segments.sentences.get_sentence_list(member_buffer):\n sentence_tokens = lexnlp.nlp.en.tokens.get_token_list(sentence, lowercase=True)\n sentence_tokens = [t for t in sentence_tokens if t.isalpha()]\n\n for window in nltk.ngrams(sentence_tokens, 3, pad_right=True):\n w1 = window[0]\n for w2, w3 in itertools.combinations(window[1:], 2):\n token_fd[w1] += 1\n if w2 is None:\n continue\n bigram_fd[(w1, w2)] += 1\n if w3 is None:\n continue\n wildcard_fd[(w1, w3)] += 1\n trigram_fd[(w1, w2, w3)] += 1\n \n except Exception as e:\n print(e)\n continue\n \n # Create measure objects\n bigram_measures = nltk.collocations.BigramAssocMeasures()\n trigram_measures = nltk.collocations.TrigramAssocMeasures()\n\n for n in top_n_list:\n # Apply filter and output\n bigram_finder = nltk.collocations.BigramCollocationFinder(token_fd, bigram_fd)\n bigram_finder.apply_freq_filter(min_freq)\n bigram_collocations = list(bigram_finder.nbest(bigram_measures.pmi, n))\n print((n, len(bigram_collocations), bigram_collocations[-1]))\n\n # Save the tokenizer\n with open(\"collocation_bigrams_{0}.pickle\".format(n), \"wb\") as out_file:\n pickle.dump(bigram_collocations, out_file)\n\n # Apply filter and output\n trigram_finder = nltk.collocations.TrigramCollocationFinder(token_fd, bigram_fd, wildcard_fd, trigram_fd)\n trigram_finder.apply_freq_filter(min_freq)\n trigram_collocations = list(trigram_finder.nbest(trigram_measures.pmi, n))\n print((n, len(trigram_collocations), trigram_collocations[-1]))\n\n # Save the tokenizer\n with open(\"collocation_trigrams_{0}.pickle\".format(n), \"wb\") as out_file:\n pickle.dump(trigram_collocations, out_file)", "repo_name": "LexPredict/lexpredict-lexnlp", "sub_path": "notebooks/nlp/en/build_collocation_pickle.py", "file_name": "build_collocation_pickle.py", "file_ext": "py", "file_size_in_byte": 3922, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 654, "dataset": "github-code", "pt": "24", "api": [{"api_name": "nltk.FreqDist", "line_number": 35, "usage_type": "call"}, {"api_name": "nltk.FreqDist", "line_number": 36, "usage_type": "call"}, {"api_name": "nltk.FreqDist", "line_number": 37, "usage_type": "call"}, {"api_name": "nltk.FreqDist", "line_number": 38, "usage_type": "call"}, {"api_name": "tarfile.open", "line_number": 41, "usage_type": "call"}, {"api_name": "lexnlp.nlp.en.segments.sentences.nlp.en.segments.sentences.get_sentence_list", "line_number": 63, "usage_type": "call"}, {"api_name": "lexnlp.nlp.en.segments.sentences.nlp", "line_number": 63, "usage_type": "attribute"}, {"api_name": "lexnlp.nlp.en.segments.sentences", "line_number": 63, "usage_type": "name"}, {"api_name": "lexnlp.nlp.en.segments.sentences.nlp.en.tokens.get_token_list", "line_number": 64, "usage_type": "call"}, {"api_name": "lexnlp.nlp.en.segments.sentences.nlp", "line_number": 64, "usage_type": "attribute"}, {"api_name": "lexnlp.nlp.en.segments.sentences", "line_number": 64, "usage_type": "name"}, {"api_name": "nltk.ngrams", "line_number": 67, "usage_type": "call"}, {"api_name": "itertools.combinations", "line_number": 69, "usage_type": "call"}, {"api_name": "nltk.collocations.BigramAssocMeasures", "line_number": 84, "usage_type": "call"}, {"api_name": "nltk.collocations", "line_number": 84, "usage_type": "attribute"}, {"api_name": "nltk.collocations.TrigramAssocMeasures", "line_number": 85, "usage_type": "call"}, {"api_name": "nltk.collocations", "line_number": 85, "usage_type": "attribute"}, {"api_name": "nltk.collocations.BigramCollocationFinder", "line_number": 89, "usage_type": "call"}, {"api_name": "nltk.collocations", "line_number": 89, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 96, "usage_type": "call"}, {"api_name": "nltk.collocations.TrigramCollocationFinder", "line_number": 99, "usage_type": "call"}, {"api_name": "nltk.collocations", "line_number": 99, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 106, "usage_type": "call"}]} +{"seq_id": "6479911924", "text": "import openpyxl as xl\nfrom openpyxl.chart import BarChart, Reference\n\n\ndef process_workbook(filename):\n workbook = xl.load_workbook(filename) # get Excel file\n sheet = workbook['Sheet1'] # get sheet from transactions.xlsx\n\n cell = sheet['a1']\n print(cell) # \n\n # the same as\n cell = sheet.cell(1, 1)\n print(cell) # \n print(cell.value) # transaction_id\n\n print(sheet.max_row) # 4\n\n for row in range(2, sheet.max_row + 1):\n cell = sheet.cell(row, 3)\n corrected_price = cell.value * 0.9 # calc new value\n corrected_price_cell = sheet.cell(row, 4) # get new cell in 4th column\n corrected_price_cell.value = corrected_price # set value to this cell\n\n values = Reference( # collect values\n sheet,\n min_row=2,\n max_row=sheet.max_row,\n min_col=4,\n max_col=4\n )\n chart = BarChart() # create chart\n chart.add_data(values) # added data to the chart\n sheet.add_chart(chart, 'e2') # added chart to the sheet\n\n workbook.save(filename) # save changes into file\n\n\nprocess_workbook('transactions.xlsx')\n", "repo_name": "vlfed-mage/python-excel-spreadsheets", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1147, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "openpyxl.load_workbook", "line_number": 6, "usage_type": "call"}, {"api_name": "openpyxl.chart.Reference", "line_number": 25, "usage_type": "call"}, {"api_name": "openpyxl.chart.BarChart", "line_number": 32, "usage_type": "call"}]} +{"seq_id": "19632231149", "text": "'''\n Code adapted from https://gist.github.com/rusty1s/159eeff0d95e0786d220a164c6edd021\n'''\n\nimport os\nimport os.path as osp\nfrom six.moves import urllib\nimport errno\nimport tarfile\n\ndef makedirs(path):\n try:\n os.makedirs(osp.expanduser(osp.normpath(path)))\n except OSError as e:\n if e.errno != errno.EEXIST and osp.isdir(path):\n raise e\n\n\ndef download_url(url, folder, log=True):\n print('Downloading', url)\n makedirs(folder)\n\n data = urllib.request.urlopen(url)\n filename = url.rpartition('/')[2]\n path = osp.join(folder, filename)\n\n with open(path, 'wb') as f:\n f.write(data.read())\n\n return path\n\n\ndef extract_tar(path, folder, mode='r:gz', log=True):\n print('Extracting', path)\n with tarfile.open(path, mode) as f:\n f.extractall(folder)\n\n\ncwd = os.getcwd()\npath = os.path.join( cwd, 'datasets/QM9/qm9' )\nurl = 'http://deepchem.io.s3-website-us-west-1.amazonaws.com/' \\\n 'datasets/gdb9.tar.gz'\n\nfile_path = download_url(url, path)\nextract_tar(file_path, path, mode='r')", "repo_name": "olsson-group/transBG", "sub_path": "preprocessing/download_qm9.py", "file_name": "download_qm9.py", "file_ext": "py", "file_size_in_byte": 1052, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "os.makedirs", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path.expanduser", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path", "line_number": 13, "usage_type": "name"}, {"api_name": "os.path.normpath", "line_number": 13, "usage_type": "call"}, {"api_name": "errno.EEXIST", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "name"}, {"api_name": "six.moves.urllib.request.urlopen", "line_number": 23, "usage_type": "call"}, {"api_name": "six.moves.urllib.request", "line_number": 23, "usage_type": "attribute"}, {"api_name": "six.moves.urllib", "line_number": 23, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "name"}, {"api_name": "tarfile.open", "line_number": 35, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}]} +{"seq_id": "42118414507", "text": "import glob\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom prettytable import PrettyTable\n\ndef sumzip(*items):\n return [sum(values) for values in zip(*items)]\n\nfiles = sorted(glob.glob('results/*.csv'))\nLOC = []\nNOFC = []\nLOF = []\nANDAVG = [] \nANDSTDEV = []\t\nSDEGMEAN = \t[]\nSDEGSTD = []\nTDEGMEAN = []\nTDEGSTD = []\nHOM\t = []\nHET = []\nHOHE = []\nNOFPFCMEAN = []\nNOFPFCSTD = []\nGRANGL = []\nGRANFL = []\nGRANBL = []\nGRANSL = []\nGRANEL = []\nGRANML = []\nGRANERR = []\nNDMAX = []\nFileCOUNT = []\n\n# Skip 2.2.11 Version\nfor file in files:\n\n\tlines = open(file, 'rt').readlines()\n\tl2 = lines[-1].split(',')\n\tdata2 = l2[2:13] + l2[21:23]\n\tdata2 = [d.rstrip() for d in data2]\n\tNOFC.append(float(data2[0]))\n\tLOF.append(float(data2[1]))\n\tANDAVG.append(float(data2[2]))\n\tANDSTDEV.append(float(data2[3]))\n\tSDEGMEAN.append(float(data2[4]))\n\tSDEGSTD.append(float(data2[5]))\n\tTDEGMEAN.append(float(data2[6]))\n\tTDEGSTD.append(float(data2[7]))\n\tHOM.append(float(data2[8]))\n\tHET.append(float(data2[9]))\n\tHOHE.append(float(data2[10]))\n\tNOFPFCMEAN.append(float(data2[11]))\n\tNOFPFCSTD.append(float(data2[12]))\n\tLOCT = []\n\tGRANGLT = []\n\tGRANFLT = []\n\tGRANBLT = []\n\tGRANSLT = []\n\tGRANELT = []\n\tGRANMLT = []\n\tGRANERRT = []\n\tNDMAXT = []\n\tFileCOUNTT = 0\n\tVP = []\n\t\n\tfor line in lines:\n\t\tif line.count(',') > 5 and line.split(',')[0][0] == '/':\n\t\t\tFileCOUNTT = FileCOUNTT + 1\n\t\t\tLOCT.append(float(line.split(',')[1]))\n\t\t\tGRANGLT.append(float(line.split(',')[13]))\n\t\t\tGRANFLT.append(float(line.split(',')[14]))\n\t\t\tGRANBLT.append(float(line.split(',')[15]))\n\t\t\tGRANSLT.append(float(line.split(',')[16]))\n\t\t\tGRANELT.append(float(line.split(',')[17]))\n\t\t\tGRANMLT.append(float(line.split(',')[18]))\n\t\t\tGRANERRT.append(float(line.split(',')[19]))\n\t\t\tNDMAXT.append(float(line.split(',')[20]))\n\tLOC.append(sum(LOCT))\n\tGRANGL.append(sum(GRANGLT))\n\tGRANFL.append(sum(GRANFLT))\n\tGRANBL.append(sum(GRANBLT))\n\tGRANSL.append(sum(GRANSLT))\n\tGRANEL.append(sum(GRANELT))\n\tGRANML.append(sum(GRANMLT))\n\tGRANERR.append(sum(GRANERRT))\n\tNDMAX.append(max(NDMAXT))\n\tFileCOUNT.append(FileCOUNTT)\n\t\n\t\n# Compare Originial results to ours\nt = PrettyTable(['name', 'LOC', 'NOFC', 'LOF', 'AND-MEAN', 'AND-STD', 'SD-MEAN', 'SD-STD', 'TD-MEAN', 'TD-STD'])\nt.add_row(['original', 214607, 1158, 40075, 1.18, 0.18, 5.58, 15.35, 1.73, 1.35])\nt.add_row(['ours', int(LOC[0]), int(NOFC[0]), int(LOF[0]), round(ANDAVG[0], 2), round(ANDSTDEV[0], 2), round(SDEGMEAN[0], 2), round(SDEGSTD[0], 2), round(TDEGMEAN[0], 2), round(TDEGMEAN[0], 2)])\n\nprint(t)\n\nt = PrettyTable(['name', 'HOM', 'HET', 'HOHE', 'GL', 'FL', 'BL', 'SL', 'EL', 'ML'])\nt.add_row(['original', 134, 2041, 98, 2015, 2186, 828, 43, 35, 13])\nt.add_row(['ours', int(HOM[0]), int(HET[0]), int(HOHE[0]), int(GRANGL[0]), int(GRANFL[0]), int(GRANBL[0]), int(GRANSL[0]), int(GRANEL[0]), int(GRANML[0])])\n\nprint(t)\n\t\n# Calculate some extra metrics\n\nPLOF = np.divide(LOF, LOC)\n\nVP = map(sum, zip(GRANGL, GRANFL, GRANBL, GRANSL, GRANEL, GRANML, GRANERR))\nLOFperVP = np.divide(LOF, VP)\n\nSD_FILE = np.divide(np.multiply(SDEGMEAN, NOFC), FileCOUNT)\nTD_FILE = np.divide(np.multiply(TDEGMEAN, NOFC), FileCOUNT)\n\n\nversions = ['2.4.25','2.4.26','2.4.27','2.4.28','2.4.29']\nnumberVersions = range(len(versions))\nwidthBar = 0.35\n\n# Global Metrics\n\nfig, ax1 = plt.subplots()\nax1.plot(LOC[1:], 'r-', label='LOC')\nax1.set_ylabel('LOC', color='r')\nax2 = ax1.twinx()\nax2.plot(LOF[1:], 'b-', label='LOF')\nax2.set_ylabel('LOF', color='b')\nfig.tight_layout()\nplt.xticks(numberVersions, versions)\nplt.title('LOC vs LOF')\nplt.show()\n\nplt.plot(PLOF[1:])\nplt.title('PLOF (LOF / LOC)')\nplt.xticks(numberVersions, versions)\nplt.show()\n\nplt.plot(NOFC[1:])\nplt.title('NOFC')\nplt.xticks(numberVersions, versions)\nplt.show()\n\nplt.plot(VP[1:])\nplt.title('VP (number of #ifdefs out of GRAN)')\nplt.xticks(numberVersions, versions)\nplt.show()\n\n\nplt.plot(LOFperVP[1:])\nplt.title('LOF per VP')\nplt.xticks(numberVersions, versions)\nplt.show()\n\n\n# SD, TD Metric\n\nplt.errorbar(numberVersions, SDEGMEAN[1:], SDEGSTD[1:], linestyle='None', marker='s')\nx1,x2,y1,y2 = plt.axis()\nplt.axis((x1,x2,-10,20))\nplt.title('SD Mean + SD')\nplt.xticks(numberVersions, versions)\nplt.show()\n\nplt.plot(SDEGMEAN[1:])\nplt.title('SDEGMEAN')\nplt.xticks(numberVersions, versions)\nplt.show()\n\nplt.plot(SDEGSTD[1:])\nplt.title('SDEGSTD')\nplt.xticks(numberVersions, versions)\nplt.show()\n\nplt.plot(SD_FILE[1:])\nplt.title('SD per File')\nplt.xticks(numberVersions, versions)\nplt.show()\n\nplt.errorbar(numberVersions, TDEGMEAN[1:], TDEGSTD[1:], linestyle='None', marker='s')\nx1,x2,y1,y2 = plt.axis()\nplt.axis((x1,x2,-4,4))\nplt.title('TD Mean + SD')\nplt.xticks(numberVersions, versions)\nplt.show()\n\nplt.plot(TDEGMEAN[1:])\nplt.title('TDEGMEAN')\nplt.xticks(numberVersions, versions)\nplt.show()\n\nplt.plot(TDEGSTD[1:])\nplt.title('TDEGSTD')\nplt.xticks(numberVersions, versions)\nplt.show()\n\nplt.plot(TD_FILE[1:])\nplt.title('TD per File')\nplt.xticks(numberVersions, versions)\nplt.show()\n\n# TYPE\n\np1 = plt.bar(numberVersions, HOM[1:], widthBar, color='#d62728')\np2 = plt.bar(numberVersions, HOHE[1:], widthBar, bottom=HOM[1:])\np3 = plt.bar(numberVersions, HET[1:], widthBar, bottom=list(map(sum, zip(HOM[1:], HOHE[1:]))))\n\nplt.title('TYPE')\nplt.legend((p1[0], p2[0], p3[0]), ('HOM', 'HOHE', 'HET'))\nplt.xticks(numberVersions, versions)\nplt.show()\n\n# GRAN\n\np1 = plt.bar(numberVersions, GRANGL[1:], widthBar, color='#d62728')\np2 = plt.bar(numberVersions, GRANFL[1:], widthBar, bottom=GRANGL[1:])\np3 = plt.bar(numberVersions, GRANBL[1:], widthBar, bottom=list(map(sum, zip(GRANGL[1:], GRANFL[1:]))))\np4 = plt.bar(numberVersions, GRANSL[1:], widthBar, bottom=list(map(sum, zip(GRANGL[1:], GRANFL[1:], GRANBL[1:]))))\np5 = plt.bar(numberVersions, GRANEL[1:], widthBar, bottom=list(map(sum, zip(GRANGL[1:], GRANFL[1:], GRANBL[1:], GRANSL[1:]))))\np6 = plt.bar(numberVersions, GRANML[1:], widthBar, bottom=list(map(sum, zip(GRANGL[1:], GRANFL[1:], GRANBL[1:], GRANSL[1:], GRANEL[1:]))))\np7 = plt.bar(numberVersions, GRANERR[1:], widthBar, bottom=list(map(sum, zip(GRANGL[1:], GRANFL[1:], GRANBL[1:], GRANSL[1:], GRANEL[1:], GRANML[1:]))))\n\nplt.title('GRAN')\nplt.legend((p1[0], p2[0], p3[0], p4[0], p5[0], p6[0], p7[0]), ('GL', 'FL', 'BL', 'SL', 'EL', 'ML', 'ERR'))\nplt.xticks(numberVersions, versions)\nplt.show()\n\n# AND\n\nplt.errorbar(numberVersions, ANDAVG[1:], ANDSTDEV[1:], linestyle='None', marker='s')\nplt.title('AND Mean + SD')\nx1,x2,y1,y2 = plt.axis()\nplt.axis((x1,x2,0,4))\nplt.xticks(numberVersions, versions)\nplt.show()\n\n\nplt.plot(ANDAVG[1:])\nplt.title('ANDAVG')\nplt.xticks(numberVersions, versions)\nplt.show()\n\nplt.plot(ANDSTDEV[1:])\nplt.title('ANDSTDEV')\nplt.xticks(numberVersions, versions)\nplt.show()\n\nplt.plot(NDMAX[1:])\nplt.title('NDMAX')\nplt.xticks(numberVersions, versions)\nplt.show()\n\n", "repo_name": "jodokae/cmput663-cpp-replic", "sub_path": "plot.py", "file_name": "plot.py", "file_ext": "py", "file_size_in_byte": 6707, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "glob.glob", "line_number": 9, "usage_type": "call"}, {"api_name": "prettytable.PrettyTable", "line_number": 91, "usage_type": "call"}, {"api_name": "prettytable.PrettyTable", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.divide", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.divide", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.divide", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.multiply", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.divide", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.multiply", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 129, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 129, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 131, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 131, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 132, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 132, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 133, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 134, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 134, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 136, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 136, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 137, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 137, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 138, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 138, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 139, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 139, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 141, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 141, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 142, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 142, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 143, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 143, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 144, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 144, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 147, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 147, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 148, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 148, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 149, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 149, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 150, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 150, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.errorbar", "line_number": 155, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 155, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 156, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 156, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 157, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 157, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 158, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 158, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 159, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 159, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 160, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 160, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 162, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 162, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 163, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 163, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 164, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 164, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 165, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 165, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 167, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 167, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 168, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 168, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 169, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 169, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 170, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 170, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 172, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 172, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 173, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 173, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 174, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 174, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 175, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 175, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.errorbar", "line_number": 177, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 177, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 178, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 178, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 179, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 179, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 180, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 180, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 181, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 181, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 182, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 182, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 184, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 184, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 185, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 185, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 186, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 186, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 187, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 187, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 189, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 189, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 190, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 190, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 191, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 191, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 192, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 192, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 194, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 194, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 195, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 195, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 196, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 196, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 197, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 197, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 201, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 201, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 202, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 202, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 203, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 203, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 205, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 205, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 206, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 206, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 207, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 207, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 208, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 208, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 212, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 212, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 213, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 213, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 214, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 214, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 215, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 215, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 216, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 216, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 217, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 217, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 218, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 218, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 220, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 220, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 221, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 221, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 222, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 222, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 223, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 223, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.errorbar", "line_number": 227, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 227, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 228, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 228, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 229, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 229, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 230, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 230, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 231, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 231, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 232, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 232, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 235, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 235, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 236, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 236, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 237, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 237, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 238, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 238, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 240, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 240, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 241, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 241, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 242, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 242, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 243, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 243, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 245, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 245, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 246, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 246, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 247, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 247, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 248, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 248, "usage_type": "name"}]} +{"seq_id": "2831612790", "text": "\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\nif __name__ == '__main__':\n x = np.arange(0, 11) # x轴数据\n # y = x * x + 5 # 函数关系\n y = x * x # 函数关系\n # plt.title(\"y=x*x+5\") # 图像标题\n plt.title(\"y=x*x\") # 图像标题\n plt.xlabel(\"x\") # x轴标签\n plt.ylabel(\"y\") # y轴标签\n plt.plot(x, y) # 生成图像\n plt.show() # 显示图像", "repo_name": "ArtistRuan/webspide", "sub_path": "csdnParactise/6_math_func/math_funct.py", "file_name": "math_funct.py", "file_ext": "py", "file_size_in_byte": 405, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "numpy.arange", "line_number": 7, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 14, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 15, "usage_type": "name"}]} +{"seq_id": "6905910909", "text": "from django import forms\nfrom .models import ChatMessage\n\nclass ChatMessageForm(forms.ModelForm):\n class Meta:\n model = ChatMessage\n fields = ('content', )\n widgets = {\n 'content': forms.Textarea(attrs={\n 'class': 'w-full py-4 px-6 rounded-xl border'\n })\n }", "repo_name": "TharunKumarReddyPolu/Graduate-Market-Place", "sub_path": "gmp_env/gmp/chat/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 325, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 12, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.forms.ModelForm", "line_number": 4, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 4, "usage_type": "name"}, {"api_name": "models.ChatMessage", "line_number": 6, "usage_type": "name"}, {"api_name": "django.forms.Textarea", "line_number": 9, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 9, "usage_type": "name"}]} +{"seq_id": "75238501182", "text": "import csv\n\nfrom stop_words import StopWords\n\nclass GetTranscriptions:\n def __init__(self):\n self.stop_words = StopWords()\n self.transcriptions = []\n self.transcriptions_NOstopwords = []\n\n # ======================================================================\n\n '''\n * Agrega mas stop words desde un archivo\n\n Input:\n self.stop_words.stop_words = [de, su]\n path_stopwords = ./stopwords.txt\n \n stopwords.txt:\n el\n la\n ...\n\n Output:\n self.stop_words.stop_words = [de, su, el, la, ...]\n '''\n\n def AddStopWords(self, path_stopwords):\n self.stop_words.ReadFile(path_stopwords)\n\n # ======================================================================\n\n '''\n Input:\n sentence = ' el perro come su comida'\n \n Output:\n return 'el perro come su comida'\n '''\n\n def DeleteExtraSeparations(self, sentence):\n words = sentence.split()\n separator = ' '\n\n return separator.join(words)\n\n # ======================================================================\n\n '''\n Input:\n path_data = './data.csv'\n \n data.csv:\n ,conid,sequence,etiqueta,transcription\n 0,31321,0,label1,el perro come su comida\n 1,15216,1,label2,el gato duerme\n \n Output:\n self.transcriptions = ['el perro come su comida', 'el gato duerme']\n self.transcriptions_NOstopwords = ['perro come comida', 'gato duerme']\n '''\n\n def ReadData(self, path_data):\n with open(path_data, 'r') as file_csv:\n data_csv = csv.reader(file_csv, delimiter=',')\n\n count_row = 0\n index_transcription = 4\n \n for row in data_csv:\n if count_row != 0:\n transcription = row[index_transcription]\n self.transcriptions.append(transcription)\n\n transcription_NOstopwords = self.stop_words.DeleteStopWords(row[index_transcription])\n self.transcriptions_NOstopwords.append(transcription_NOstopwords)\n\n count_row += 1\n\n # ======================================================================\n\n def WriteFile(self, path, transcriptions):\n with open(path, 'w') as file_txt:\n for transcription in transcriptions:\n transcription = self.DeleteExtraSeparations(transcription)\n\n if transcription != '':\n file_txt.write(transcription + '\\n')\n\n # ======================================================================\n\n def ExportData(self):\n name_transcriptions = 'transcriptions.txt'\n path_transcriptions = './data/' + name_transcriptions\n self.WriteFile(path_transcriptions, self.transcriptions)\n\n name_transcriptions_NOstopwords = 'transcriptions_NOstopwords.txt'\n path_transcriptions_NOstopwords = './data/' + name_transcriptions_NOstopwords\n self.WriteFile(path_transcriptions_NOstopwords, self.transcriptions_NOstopwords)\n", "repo_name": "JonMollUCSP/AT-BiLSTM", "sub_path": "utilities/train_fasttext/get_transcriptions.py", "file_name": "get_transcriptions.py", "file_ext": "py", "file_size_in_byte": 2822, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "stop_words.StopWords", "line_number": 7, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 66, "usage_type": "call"}]} +{"seq_id": "27979244570", "text": "import argparse\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom easydict import EasyDict as edict\nfrom PIL import Image\nimport cv2\nimport time\nfrom . import models\n\ndef load_model():\n height = 228\n width = 304\n channels = 3\n batch_size = 1\n # Create a placeholder for the input image\n\n input_node = tf.placeholder(tf.float32, shape=(None, height, width, channels))\n # Construct the network\n\n net = models.ResNet50UpProj({'data': input_node}, batch_size, 1, False)\n return net, input_node\n\ndef plot_image(img_ori, pred):\n fig = plt.figure()\n plt.subplot(121)\n ii = plt.imshow(img_ori, interpolation='nearest')\n\n plt.subplot(122)\n\n ax = plt.gca()\n ii = ax.imshow(pred, interpolation='nearest')\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n plt.colorbar(ii, cax=cax)\n plt.show()\n \ndef predict_image(model_data_path, image_path, net, input_node):\n\n \n # Default input size\n height = 228\n width = 304\n \n # Read image\n img = Image.open(image_path)\n img = img.resize([width,height], Image.ANTIALIAS)\n img_ori = img.copy() \n img = np.array(img).astype('float32')\n img = np.expand_dims(np.asarray(img), axis = 0)\n\n with tf.Session() as sess:\n\n # Load the converted parameters\n print('Loading the model')\n\n # Use to load from ckpt file\n saver = tf.train.Saver() \n saver.restore(sess, model_data_path)\n\n # Use to load from npy file\n# net.load(model_data_path, sess) \n\n # Evalute the network for the given image\n pred = sess.run(net.get_output(), feed_dict={input_node: img})\n \n # Plot result\n print(img.shape, pred.shape)\n plot_image(img_ori, pred[0,:,:,0])\n \n return pred\n \ndef read_video(filename):\n cap = cv2.VideoCapture(filename)\n i = 0\n while(cap.isOpened()):\n ret, frame = cap.read()\n print('get frame %d'%i)\n yield frame\n i+=1\n\n cap.release()\n\ndef predict_video(model_data_path, video_path, net, input_node):\n\n \n # Default input size\n height = 228\n width = 304\n fig = plt.figure(figsize=(20, 16))\n ax1 = fig.add_subplot(121)\n ax2 = fig.add_subplot(122)\n\n plt.ion()\n fig.show()\n fig.canvas.draw()\n for data in read_video(video_path):\n # Read image\n# img = Image.open(image_path)\n \n# import pdb\n# pdb.set_trace()\n img = Image.fromarray(data, 'RGB')\n img = img.resize([width,height], Image.ANTIALIAS)\n img_ori = img.copy()\n\n img = np.array(img).astype('float32')\n img = np.expand_dims(np.asarray(img), axis = 0)\n\n with tf.Session() as sess:\n\n # Load the converted parameters\n print('Loading the model')\n\n # Use to load from ckpt file\n saver = tf.train.Saver() \n saver.restore(sess, model_data_path)\n\n # Use to load from npy file\n # net.load(model_data_path, sess) \n\n # Evalute the network for the given image\n pred = sess.run(net.get_output(), feed_dict={input_node: img})\n out = np.zeros((height, width * 2, 3), dtype=np.uint8)\n out[:height,:width,:] = img_ori\n pic = cv2.resize(pred[0, :, :, 0], (width, height), interpolation=cv2.INTER_CUBIC)\n npic = np.minimum(pic / 10 * 255, 255).astype(np.uint8)\n# out[:height,width:, 0] = npic\n# out[:height,width:, 1] = npic\n# out[:height,width:, 2] = npic\n\n # Plot result\n ax1.imshow(img_ori)\n ii = ax2.imshow(npic)\n divider = make_axes_locatable(ax2)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n bar = plt.colorbar(ii, cax=cax)\n fig.canvas.draw()\n ax1.clear()\n ax2.clear()\n bar.remove()\n\n \ndef main():\n # Parse arguments\n# parser = argparse.ArgumentParser()\n# parser.add_argument('model_path', help='Converted parameters for the model')\n# parser.add_argument('image_paths', help='Directory of images to predict')\n# args = parser.parse_args()\n args = edict()\n tf.reset_default_graph()\n args.model_path = 'model/NYU_FCRN.ckpt'\n args.image_paths = 'images/test3.jpg'\n args.video_paths = 'images/test.mov'\n\n # Predict the image\n net, input_node = load_model()\n# pred = predict_image(args.model_path, args.image_paths, net, input_node)\n pred = predict_video(args.model_path, args.video_paths, net, input_node)\n# os._exit(0)\n\nif __name__ == '__main__':\n main()\n\n \n\n\n\n\n", "repo_name": "THVi-xTHU/xthu", "sub_path": "fcrn_depth_prediction/predict_video.py", "file_name": "predict_video.py", "file_ext": "py", "file_size_in_byte": 4781, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "tensorflow.placeholder", "line_number": 20, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 20, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "mpl_toolkits.axes_grid1.make_axes_locatable", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 48, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 48, "usage_type": "name"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 49, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 49, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 52, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 54, "usage_type": "call"}, {"api_name": "tensorflow.train.Saver", "line_number": 60, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 60, "usage_type": "attribute"}, {"api_name": "cv2.VideoCapture", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 92, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 92, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ion", "line_number": 96, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 96, "usage_type": "name"}, {"api_name": "PIL.Image.fromarray", "line_number": 105, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 105, "usage_type": "name"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 106, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 106, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 110, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 112, "usage_type": "call"}, {"api_name": "tensorflow.train.Saver", "line_number": 118, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 118, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 126, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 128, "usage_type": "call"}, {"api_name": "cv2.INTER_CUBIC", "line_number": 128, "usage_type": "attribute"}, {"api_name": "numpy.minimum", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 129, "usage_type": "attribute"}, {"api_name": "mpl_toolkits.axes_grid1.make_axes_locatable", "line_number": 137, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 139, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 139, "usage_type": "name"}, {"api_name": "easydict.EasyDict", "line_number": 152, "usage_type": "call"}, {"api_name": "tensorflow.reset_default_graph", "line_number": 153, "usage_type": "call"}]} +{"seq_id": "1046222132", "text": "import json\nimport logging\nimport shutil\nimport signal\nfrom abc import abstractmethod\nfrom collections import defaultdict\nfrom copy import deepcopy\nfrom enum import Enum\nfrom multiprocessing import Process, Manager\nfrom multiprocessing.managers import SyncManager\nfrom pathlib import Path\nfrom typing import Dict, Tuple, Optional\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nfrom clearml import Task, Logger, OutputModel\nfrom clearml.storage.helper import StorageHelper\nfrom torch.optim.optimizer import Optimizer\nfrom tqdm import tqdm\n\nfrom ..config import BaseExperimentConfig\nfrom ...dataset import WolfDataset\nfrom ...logger import logger\nfrom ...losses import Loss\nfrom ...plotting_service.classification import plot_confusion_matrix\n\n__all__ = ['BaseExperimentLogger']\n\nlogging.getLogger(\"clearml.storage\").setLevel(\"WARNING\")\n\n\nclass ConfigEncoder(json.JSONEncoder):\n \"\"\"Special class for encoding Config object.\"\"\"\n\n def default(self, obj):\n if isinstance(obj, Enum):\n return obj.name\n return json.JSONEncoder.default(self, obj)\n\n\nclass NumpyEncoder(json.JSONEncoder):\n \"\"\"Special json encoder for numpy types.\"\"\"\n\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n elif isinstance(obj, np.floating):\n return float(obj)\n elif isinstance(obj, np.bool_):\n return bool(obj)\n elif isinstance(obj, np.ndarray):\n return obj.tolist()\n return json.JSONEncoder.default(self, obj)\n\n\ndef _mgr_init():\n \"\"\"Special initializer for SyncManager to ignore signals.\"\"\"\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n signal.signal(signal.SIGQUIT, signal.SIG_IGN)\n\n\nclass BaseExperimentLogger:\n \"\"\"Base Class for storing and saving experiments results.\"\"\"\n\n RUN_CONFIG_FILENAME = 'run_config.JSON'\n INFERENCE_CONFIG_FILENAME = 'inference_config.JSON'\n RESULTS_FILENAME = 'results.JSON'\n SELECTION_METRIC_FILENAME = 'selection_metric.JSON'\n MODEL_FILENAME = 'model.pt'\n MODEL_WEIGHTS_FILENAME = 'model_weights.pt'\n IMAGES_FOLDER = 'images'\n IMAGES_FILENAME = 'images.csv'\n DATASET_FILENAME = 'dataset.pkl'\n\n # TENSORBOARD_FOLDER = 'tensorboard'\n\n @property\n @abstractmethod\n def FIG_SIZE(self) -> Tuple[int, int]:\n \"\"\"Defines the figure size for saving debug images.\"\"\"\n\n def __init__(self, saving_dir: str or Path, n_debug_samples: int, clearml_config: Optional[Dict] = None):\n \"\"\"\n Args:\n saving_dir: the directory to store all results\n n_debug_samples: the number of debug samples to save for each epoch\n clearml_config: the config for clearml\n \"\"\"\n\n self.saving_dir = Path(saving_dir)\n self.n_debug_samples = n_debug_samples\n self._cleaned_up = False\n\n self.saving_dir.mkdir(parents=True, exist_ok=True)\n\n self.images_dir = self.saving_dir.joinpath(self.IMAGES_FOLDER)\n self.images_dir.mkdir(exist_ok=True)\n\n self._metrics_keeper = defaultdict(list)\n\n # multiprocessing staff\n manager = SyncManager()\n manager.start(_mgr_init) # fire up the child manager process\n self._debug_samples_mp_manager = manager.list()\n self._debug_samples_processes = []\n\n self.clearml_task: Task = None\n self.clearml_logger: Logger = None\n self.clearml_model: OutputModel = None\n if clearml_config:\n clearml_config['auto_connect_frameworks'] = False\n Task.force_requirements_env_freeze(force=True, requirements_file='requirements.txt')\n self.clearml_task = Task.init(task_name=self.saving_dir.name, **clearml_config)\n self.clearml_logger = self.clearml_task.get_logger()\n self.clearml_model = OutputModel(self.clearml_task)\n destination = self.clearml_task.get_output_destination()\n self.clearml_logger.set_default_upload_destination(f'{destination}')\n\n @property\n def folder(self) -> Path:\n \"\"\"Returns the folder where the results are stored.\"\"\"\n return self.saving_dir\n\n def clean_up(self, stopped_by_user: bool = False):\n \"\"\"Removes logged data due to errors.\"\"\"\n if not self.results_path.exists():\n shutil.rmtree(self.saving_dir)\n self._cleaned_up = True\n if self.clearml_task is not None:\n self.clearml_task.delete(raise_on_error=True)\n else:\n if not stopped_by_user:\n logger.warning(f\"Failed to remove experiment folder, since it contains results data.\")\n\n @property\n def cleaned_up(self) -> bool:\n \"\"\"If clean_up is called returns True\"\"\"\n return self._cleaned_up\n\n @property\n def run_config_path(self) -> Path:\n \"\"\"Returns the run config file path.\"\"\"\n return self.saving_dir.joinpath(self.RUN_CONFIG_FILENAME)\n\n @property\n def inference_config_path(self) -> Path:\n \"\"\"Returns the inference config file path.\"\"\"\n return self.saving_dir.joinpath(self.INFERENCE_CONFIG_FILENAME)\n\n @property\n def results_path(self) -> Path:\n \"\"\"Returns the JSON file path, where the metrics will be stored.\"\"\"\n return self.saving_dir.joinpath(self.RESULTS_FILENAME)\n\n @property\n def selection_metric_path(self) -> Path:\n \"\"\"Returns the JSON file path, where the selection metric values will be stored.\"\"\"\n return self.saving_dir.joinpath(self.SELECTION_METRIC_FILENAME)\n\n @property\n def model_path(self) -> Path:\n \"\"\"Returns the file path, where the model will be stored.\"\"\"\n return self.saving_dir.joinpath(self.MODEL_FILENAME)\n\n @property\n def model_weights_path(self) -> Path:\n \"\"\"Returns the file path, where the model will be stored.\"\"\"\n return self.saving_dir.joinpath(self.MODEL_WEIGHTS_FILENAME)\n\n @property\n def train_dataset_path(self) -> Path:\n \"\"\"Returns the pickle file path, where the dataset will be saved.\"\"\"\n return self.saving_dir.joinpath(f'train_{self.DATASET_FILENAME}')\n\n @property\n def valid_dataset_path(self) -> Path:\n \"\"\"Returns the pickle file path, where the dataset will be saved.\"\"\"\n return self.saving_dir.joinpath(f'valid_{self.DATASET_FILENAME}')\n\n def _save_debug_samples_data(self):\n \"\"\"After each epoch saves saved images info.\"\"\"\n df = pd.DataFrame(list(self._debug_samples_mp_manager))\n if df.empty:\n logger.debug(f\"No information about saved images\")\n else:\n if self.saving_dir.exists():\n df = df.sort_values(by=['epoch', 'mode', 'batch', 'image_index'])\n saving_path = self.saving_dir.joinpath(self.IMAGES_FILENAME)\n df.to_csv(saving_path)\n logger.debug(f\"Information about saved images is saved in {saving_path} file.\")\n if self.clearml_logger is not None:\n self.clearml_logger.report_table(\"DebugSamples\", \"all\", csv=saving_path.as_posix())\n\n def finalize(self):\n \"\"\"Waits until all processes are finished.\"\"\"\n for p in self._debug_samples_processes:\n p.join()\n\n self._save_debug_samples_data()\n\n if self.clearml_model is not None:\n try:\n self.register_best_epoch_results()\n\n self.clearml_model.update_weights(\n weights_filename=self.model_weights_path.as_posix(),\n auto_delete_file=False\n )\n # waiting to finish all threads\n pool = StorageHelper._upload_pool\n if pool:\n pool.close()\n pool.join()\n except Exception as e:\n logger.warning(f\"Failed to log final results into clearml, due to error: {e}\")\n\n try:\n self.clearml_task.close()\n except Exception as e:\n logger.warning(f\"Failed to close clearml task due to error: {e}.\", exc_info=True)\n else:\n logger.info(f\"clearml task is closed.\")\n\n def register_run_config(self, config: BaseExperimentConfig):\n \"\"\"Registers the experiment config.\"\"\"\n with open(self.run_config_path, 'w') as f:\n json.dump(config.all_configs, f, cls=ConfigEncoder)\n\n if self.clearml_task is not None:\n self.clearml_task.connect_configuration(name='run_config', configuration=config.all_configs)\n self.clearml_model.update_design(config_dict=config.model)\n hparams = config.get_hyper_params_to_log()\n self.clearml_task.set_parameters_as_dict(hparams)\n\n epochs = hparams['early_stopping_patience']\n self.clearml_logger.set_default_debug_sample_history(epochs)\n\n print()\n for k, v in config.all_configs.items():\n print(f'{k} config: {v}')\n print()\n\n logger.debug(f\"Experiment run config is saved in {self.run_config_path} file.\")\n\n def register_inference_config(self, config: Dict):\n \"\"\"Registers the inference config.\"\"\"\n if not self._cleaned_up:\n with open(self.inference_config_path, 'w') as f:\n json.dump(config, f, cls=ConfigEncoder)\n\n if self.clearml_task is not None:\n self.clearml_task.upload_artifact(name='inference_config', artifact_object=config)\n\n logger.debug(f\"Experiment inference config is saved in {self.inference_config_path} file.\")\n\n @staticmethod\n def _format_results(results: Dict[str, float or int]) -> str:\n return ' | '.join(\n [\n f'{k} - {v:.4}' for k, v in results.items()\n if isinstance(v, (float, int, np.floating, np.integer)) and not np.isnan(v)\n ]\n )\n\n def _clearml_log_metrics(self, metrics: Dict, epoch_mode: str, epoch: int):\n \"\"\"Uses clearml to log metrics.\"\"\"\n if self.clearml_logger is not None:\n for k, v in metrics.items():\n if isinstance(v, (float, int, np.floating, np.integer)):\n self.clearml_logger.report_scalar(k, epoch_mode, v, epoch)\n elif isinstance(v, (list, np.ndarray)) and k in ('confusion_matrix', 'class_names'):\n pass\n else:\n raise TypeError(f\"Metrics should be scalar or matrix, got {type(v)}\")\n\n cm = metrics.get('confusion_matrix')\n class_names = metrics.get('class_names')\n if cm is not None:\n fig = plot_confusion_matrix(np.array(cm), class_names, annotate_samples=False, return_figure=True)\n self.clearml_logger.report_matplotlib_figure(\n title=f'{epoch_mode}/CFM',\n series=f'epoch={epoch}',\n figure=fig,\n iteration=epoch,\n report_image=False,\n report_interactive=True,\n )\n plt.close(fig=fig)\n\n def register_epoch_results(self,\n epoch: int,\n epoch_mode: str,\n epoch_loss_metrics: Dict,\n lr: float = None,\n progress_bar: tqdm = None):\n \"\"\"Registers the experiment single epoch results.\"\"\"\n if progress_bar is not None:\n progress_bar.write(\"\")\n progress_bar.write(f' Epoch {epoch_mode.upper()} Results: {self._format_results(epoch_loss_metrics)}')\n\n serializable = {k: (v.tolist() if isinstance(v, np.ndarray) else v) for k, v in epoch_loss_metrics.items()}\n if lr:\n serializable['lr'] = lr\n\n self._clearml_log_metrics(serializable, epoch_mode, epoch)\n\n serializable['epoch'] = epoch\n self._metrics_keeper[epoch_mode].append(serializable)\n\n with open(self.results_path, 'w') as f:\n json.dump(dict(self._metrics_keeper), f, cls=NumpyEncoder)\n logger.debug(f\"Experiment results are saved in {self.results_path} file.\")\n\n def register_selection_metric(self, selection_metric: Dict):\n \"\"\"Registers the selection_metric data.\"\"\"\n with open(self.selection_metric_path, 'w') as f:\n json.dump(selection_metric, f, cls=NumpyEncoder)\n logger.debug(f\"Experiment selection metric data is saved in {self.selection_metric_path} file.\")\n\n def register_best_epoch_results(self):\n \"\"\"Registers the best epoch results.\"\"\"\n with open(self.selection_metric_path) as f:\n selection_metric = json.load(f)\n\n selection_metric = pd.DataFrame(selection_metric['history'])\n best_epoch = int(selection_metric['epoch'].max())\n\n logger.info(f\"The best_epoch={best_epoch}. Logging its values.\")\n self.clearml_logger.report_text(f'BestEpoch={best_epoch}', print_console=False)\n for mode, mode_metrics in self._metrics_keeper.items():\n [best_epoch_metrics] = [item for item in mode_metrics if item['epoch'] == best_epoch]\n best_epoch_metrics = deepcopy(best_epoch_metrics)\n best_epoch_metrics.pop('epoch')\n serializable = {k: (v.tolist() if isinstance(v, np.ndarray) else v) for k, v in best_epoch_metrics.items()}\n serializable.pop('lr', None)\n self._clearml_log_metrics(serializable, f'best_{mode}', best_epoch)\n logger.info(\"Best Epoch results are logged.\")\n\n def register_model(self, epoch: int, network: nn.Module, optimizer: Optimizer, loss: Loss):\n \"\"\"Registers the model.\"\"\"\n try:\n state_dict = network.module.state_dict()\n except AttributeError:\n state_dict = network.state_dict()\n\n torch.save(\n {\n 'epoch': epoch,\n 'model_state_dict': state_dict,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'loss': loss\n },\n self.model_path,\n )\n torch.save(state_dict, self.model_weights_path)\n logger.debug(f\"Training checkpoint is saved in {self.model_path} file.\")\n logger.debug(f\"Model weights are saved in {self.model_weights_path} file.\")\n\n def register_dataset(self, dataset: WolfDataset, mode: str):\n \"\"\"Registers dataset DataFrame.\"\"\"\n if mode == 'train':\n saving_path = str(self.train_dataset_path)\n elif mode == 'valid':\n saving_path = str(self.valid_dataset_path)\n else:\n raise ValueError(f\"mode must be train or valid, got: '{mode}'\")\n\n dataset.df.to_pickle(saving_path)\n logger.debug(f\"{mode.upper()} dataset pickle is saved in {saving_path} file.\")\n\n if self.clearml_task is not None:\n self.clearml_task.upload_artifact(f\"{mode}_dataset\", saving_path)\n\n def register_epoch_debug_samples(self, epoch: int, epoch_mode: str, epoch_images: Dict):\n \"\"\"Registers the experiment single epoch results.\"\"\"\n if self.n_debug_samples <= 0:\n return\n\n for batch, batch_images in epoch_images.items():\n if 'debug_image' not in batch_images or batch_images['debug_image'] is None:\n continue\n else:\n p = Process(\n target=self.save_epoch_images,\n kwargs=dict(\n images_dir=self.images_dir,\n epoch_mode=epoch_mode,\n epoch_number=epoch,\n batch_number=batch,\n n_images_to_save=self.n_debug_samples,\n info=dict(mode=epoch_mode, epoch=epoch, batch=batch),\n mp_manager=self._debug_samples_mp_manager,\n clearml_logger=self.clearml_logger,\n **batch_images\n )\n )\n p.start()\n self._debug_samples_processes.append(p)\n\n @classmethod\n def save_epoch_images(cls,\n input_image: np.ndarray,\n y_true: np.ndarray,\n y_pred: np.ndarray,\n info: Dict,\n mp_manager: Manager,\n mode: str = None,\n epoch_number: int = None,\n batch_number: int = None,\n images_dir: str = None,\n clearml_logger: Optional[Logger] = None,\n n_images_to_save: int = 10):\n \"\"\"Please implement this method in subclasses, depending on the task.\"\"\"\n raise NotImplementedError\n\n @staticmethod\n def save_image(image: np.ndarray, saving_path: str or Path, as_uint8: bool = True) -> None:\n \"\"\"Saves single debug image.\"\"\"\n if as_uint8:\n cv2.imwrite(str(saving_path), (image * 255).astype(np.uint8))\n else:\n cv2.imwrite(str(saving_path), image)\n", "repo_name": "razmikmelikbekyan/WolfPyTorch", "sub_path": "wolf/experiment/experiment_logging/base_logger.py", "file_name": "base_logger.py", "file_ext": "py", "file_size_in_byte": 17098, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 33, "usage_type": "call"}, {"api_name": "json.JSONEncoder", "line_number": 36, "usage_type": "attribute"}, {"api_name": "enum.Enum", "line_number": 40, "usage_type": "argument"}, {"api_name": "json.JSONEncoder.default", "line_number": 42, "usage_type": "call"}, {"api_name": "json.JSONEncoder", "line_number": 42, "usage_type": "attribute"}, {"api_name": "json.JSONEncoder", "line_number": 45, "usage_type": "attribute"}, {"api_name": "numpy.integer", "line_number": 49, "usage_type": "attribute"}, {"api_name": "numpy.floating", "line_number": 51, "usage_type": "attribute"}, {"api_name": "numpy.bool_", "line_number": 53, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 55, "usage_type": "attribute"}, {"api_name": "json.JSONEncoder.default", "line_number": 57, "usage_type": "call"}, {"api_name": "json.JSONEncoder", "line_number": 57, "usage_type": "attribute"}, {"api_name": "signal.signal", "line_number": 62, "usage_type": "call"}, {"api_name": "signal.SIGINT", "line_number": 62, "usage_type": "attribute"}, {"api_name": "signal.SIG_IGN", "line_number": 62, "usage_type": "attribute"}, {"api_name": "signal.signal", "line_number": 63, "usage_type": "call"}, {"api_name": "signal.SIGQUIT", "line_number": 63, "usage_type": "attribute"}, {"api_name": "signal.SIG_IGN", "line_number": 63, "usage_type": "attribute"}, {"api_name": "abc.abstractmethod", "line_number": 82, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 83, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 86, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 86, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 86, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 94, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 103, "usage_type": "call"}, {"api_name": "multiprocessing.managers.SyncManager", "line_number": 106, "usage_type": "call"}, {"api_name": "clearml.Task", "line_number": 111, "usage_type": "name"}, {"api_name": "clearml.Logger", "line_number": 112, "usage_type": "name"}, {"api_name": "clearml.OutputModel", "line_number": 113, "usage_type": "name"}, {"api_name": "clearml.Task.force_requirements_env_freeze", "line_number": 116, "usage_type": "call"}, {"api_name": "clearml.Task", "line_number": 116, "usage_type": "name"}, {"api_name": "clearml.Task.init", "line_number": 117, "usage_type": "call"}, {"api_name": "clearml.Task", "line_number": 117, "usage_type": "name"}, {"api_name": "clearml.OutputModel", "line_number": 119, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 124, "usage_type": "name"}, {"api_name": "shutil.rmtree", "line_number": 131, "usage_type": "call"}, {"api_name": "logger.logger.warning", "line_number": 137, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 137, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 145, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 150, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 155, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 160, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 165, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 170, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 175, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 180, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 186, "usage_type": "call"}, {"api_name": "logger.logger.debug", "line_number": 188, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 188, "usage_type": "name"}, {"api_name": "logger.logger.debug", "line_number": 194, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 194, "usage_type": "name"}, {"api_name": "clearml.storage.helper.StorageHelper._upload_pool", "line_number": 214, "usage_type": "attribute"}, {"api_name": "clearml.storage.helper.StorageHelper", "line_number": 214, "usage_type": "name"}, {"api_name": "logger.logger.warning", "line_number": 219, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 219, "usage_type": "name"}, {"api_name": "logger.logger.warning", "line_number": 224, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 224, "usage_type": "name"}, {"api_name": "logger.logger.info", "line_number": 226, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 226, "usage_type": "name"}, {"api_name": "config.BaseExperimentConfig", "line_number": 228, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 231, "usage_type": "call"}, {"api_name": "config.all_configs", "line_number": 231, "usage_type": "attribute"}, {"api_name": "config.all_configs", "line_number": 234, "usage_type": "attribute"}, {"api_name": "config.model", "line_number": 235, "usage_type": "attribute"}, {"api_name": "config.get_hyper_params_to_log", "line_number": 236, "usage_type": "call"}, {"api_name": "config.all_configs.items", "line_number": 243, "usage_type": "call"}, {"api_name": "config.all_configs", "line_number": 243, "usage_type": "attribute"}, {"api_name": "logger.logger.debug", "line_number": 247, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 247, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 249, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 253, "usage_type": "call"}, {"api_name": "logger.logger.debug", "line_number": 258, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 258, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 261, "usage_type": "name"}, {"api_name": "numpy.floating", "line_number": 265, "usage_type": "attribute"}, {"api_name": "numpy.integer", "line_number": 265, "usage_type": "attribute"}, {"api_name": "numpy.isnan", "line_number": 265, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 269, "usage_type": "name"}, {"api_name": "numpy.floating", "line_number": 273, "usage_type": "attribute"}, {"api_name": "numpy.integer", "line_number": 273, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 275, "usage_type": "attribute"}, {"api_name": "plotting_service.classification.plot_confusion_matrix", "line_number": 283, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 283, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.close", "line_number": 292, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 292, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 297, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 299, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 305, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 315, "usage_type": "call"}, {"api_name": "logger.logger.debug", "line_number": 316, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 316, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 318, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 321, "usage_type": "call"}, {"api_name": "logger.logger.debug", "line_number": 322, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 322, "usage_type": "name"}, {"api_name": "json.load", "line_number": 327, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 329, "usage_type": "call"}, {"api_name": "logger.logger.info", "line_number": 332, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 332, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 336, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 338, "usage_type": "attribute"}, {"api_name": "logger.logger.info", "line_number": 341, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 341, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 343, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 343, "usage_type": "name"}, {"api_name": "torch.optim.optimizer.Optimizer", "line_number": 343, "usage_type": "name"}, {"api_name": "losses.Loss", "line_number": 343, "usage_type": "name"}, {"api_name": "torch.save", "line_number": 350, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 359, "usage_type": "call"}, {"api_name": "logger.logger.debug", "line_number": 360, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 360, "usage_type": "name"}, {"api_name": "logger.logger.debug", "line_number": 361, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 361, "usage_type": "name"}, {"api_name": "dataset.WolfDataset", "line_number": 363, "usage_type": "name"}, {"api_name": "dataset.df.to_pickle", "line_number": 372, "usage_type": "call"}, {"api_name": "dataset.df", "line_number": 372, "usage_type": "attribute"}, {"api_name": "logger.logger.debug", "line_number": 373, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 373, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 378, "usage_type": "name"}, {"api_name": "multiprocessing.Process", "line_number": 387, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 406, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 407, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 408, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 409, "usage_type": "name"}, {"api_name": "multiprocessing.Manager", "line_number": 410, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 415, "usage_type": "name"}, {"api_name": "clearml.Logger", "line_number": 415, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 421, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 421, "usage_type": "name"}, {"api_name": "cv2.imwrite", "line_number": 424, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 424, "usage_type": "attribute"}, {"api_name": "cv2.imwrite", "line_number": 426, "usage_type": "call"}]} +{"seq_id": "8915502306", "text": "from flask import request, make_response, jsonify\nfrom flask_expects_json import expects_json\nfrom flask_jwt_extended import jwt_required, get_jwt_identity\n\nfrom api.v1.common.constants import get_indicator_type_by_id\nfrom api.v1.researches.schemas import create_research_schema, ResearchDataSchema, create_indicator_schema, \\\n IndicatorDataSchema\nfrom api.v1.researches.services import get_research, create_research, get_researches, update_research, create_indicator, \\\n update_indicator, get_my_research\nfrom api.v1.users.services import get_user_by_email\n\n\n@jwt_required()\n@expects_json(create_research_schema)\ndef create_research_view():\n data = request.json\n research = create_research(data)\n return make_response(jsonify(ResearchDataSchema().dump(research, many=False)), 200)\n\n\ndef get_place_view(place_id):\n pass\n\n\n@jwt_required()\ndef get_my_places_view():\n user_email = get_jwt_identity()\n user = get_user_by_email(user_email)\n # places = places.get_my_places(user)\n researches = get_researches()\n return make_response(jsonify(ResearchDataSchema().dump(researches, many=True)), 200)\n\n\n@jwt_required()\ndef get_places_view():\n places = get_researches()\n\n return make_response(jsonify(ResearchDataSchema().dump(places, many=True)), 200)\n\n\n@jwt_required()\ndef get_research_view(research_id=None):\n user_email = get_jwt_identity()\n user = get_user_by_email(user_email)\n research = get_research(research_id, owner_id=user.id)\n return make_response(jsonify(ResearchDataSchema().dump(research, many=False)), 200)\n\n\n@jwt_required()\ndef update_research_view(research_id=None):\n user_email = get_jwt_identity()\n user = get_user_by_email(user_email)\n\n data = request.json\n update_research(research_id, data)\n research = get_research(research_id, owner_id=user.id)\n return make_response(jsonify(ResearchDataSchema().dump(research, many=False)), 200)\n\n\n@jwt_required()\n@expects_json(create_indicator_schema)\ndef create_indicator_view():\n data = request.json\n indicator = create_indicator(data)\n indicator.type = get_indicator_type_by_id(indicator.type_id)\n\n return make_response(jsonify(IndicatorDataSchema().dump(indicator, many=False)), 200)\n\n\n@jwt_required()\n@expects_json(create_indicator_schema)\ndef update_indicator_view(indicator_id=None):\n data = request.json\n update_indicator(indicator_id, data)\n\n return make_response(jsonify({\"status\": \"ok\"}), 200)\n\n\n@jwt_required()\ndef get_my_researches_view():\n user_email = get_jwt_identity()\n user = get_user_by_email(user_email)\n research = get_my_research(owner_id=user.id)\n return make_response(jsonify(ResearchDataSchema().dump(research, many=True)), 200)\n", "repo_name": "boooogyman/fish_king", "sub_path": "api/v1/researches/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2706, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.request.json", "line_number": 16, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 16, "usage_type": "name"}, {"api_name": "api.v1.researches.services.create_research", "line_number": 17, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 18, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 18, "usage_type": "call"}, {"api_name": "api.v1.researches.schemas.ResearchDataSchema", "line_number": 18, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 13, "usage_type": "call"}, {"api_name": "flask_expects_json.expects_json", "line_number": 14, "usage_type": "call"}, {"api_name": "api.v1.researches.schemas.create_research_schema", "line_number": 14, "usage_type": "argument"}, {"api_name": "flask_jwt_extended.get_jwt_identity", "line_number": 27, "usage_type": "call"}, {"api_name": "api.v1.users.services.get_user_by_email", "line_number": 28, "usage_type": "call"}, {"api_name": "api.v1.researches.services.get_researches", "line_number": 30, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 31, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 31, "usage_type": "call"}, {"api_name": "api.v1.researches.schemas.ResearchDataSchema", "line_number": 31, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 25, "usage_type": "call"}, {"api_name": "api.v1.researches.services.get_researches", "line_number": 36, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 38, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 38, "usage_type": "call"}, {"api_name": "api.v1.researches.schemas.ResearchDataSchema", "line_number": 38, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 34, "usage_type": "call"}, {"api_name": "flask_jwt_extended.get_jwt_identity", "line_number": 43, "usage_type": "call"}, {"api_name": "api.v1.users.services.get_user_by_email", "line_number": 44, "usage_type": "call"}, {"api_name": "api.v1.researches.services.get_research", "line_number": 45, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 46, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 46, "usage_type": "call"}, {"api_name": "api.v1.researches.schemas.ResearchDataSchema", "line_number": 46, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 41, "usage_type": "call"}, {"api_name": "flask_jwt_extended.get_jwt_identity", "line_number": 51, "usage_type": "call"}, {"api_name": "api.v1.users.services.get_user_by_email", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 54, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 54, "usage_type": "name"}, {"api_name": "api.v1.researches.services.update_research", "line_number": 55, "usage_type": "call"}, {"api_name": "api.v1.researches.services.get_research", "line_number": 56, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 57, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 57, "usage_type": "call"}, {"api_name": "api.v1.researches.schemas.ResearchDataSchema", "line_number": 57, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 49, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 63, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 63, "usage_type": "name"}, {"api_name": "api.v1.researches.services.create_indicator", "line_number": 64, "usage_type": "call"}, {"api_name": "api.v1.common.constants.get_indicator_type_by_id", "line_number": 65, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 67, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 67, "usage_type": "call"}, {"api_name": "api.v1.researches.schemas.IndicatorDataSchema", "line_number": 67, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 60, "usage_type": "call"}, {"api_name": "flask_expects_json.expects_json", "line_number": 61, "usage_type": "call"}, {"api_name": "api.v1.researches.schemas.create_indicator_schema", "line_number": 61, "usage_type": "argument"}, {"api_name": "flask.request.json", "line_number": 73, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 73, "usage_type": "name"}, {"api_name": "api.v1.researches.services.update_indicator", "line_number": 74, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 76, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 76, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 70, "usage_type": "call"}, {"api_name": "flask_expects_json.expects_json", "line_number": 71, "usage_type": "call"}, {"api_name": "api.v1.researches.schemas.create_indicator_schema", "line_number": 71, "usage_type": "argument"}, {"api_name": "flask_jwt_extended.get_jwt_identity", "line_number": 81, "usage_type": "call"}, {"api_name": "api.v1.users.services.get_user_by_email", "line_number": 82, "usage_type": "call"}, {"api_name": "api.v1.researches.services.get_my_research", "line_number": 83, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 84, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 84, "usage_type": "call"}, {"api_name": "api.v1.researches.schemas.ResearchDataSchema", "line_number": 84, "usage_type": "call"}, {"api_name": "flask_jwt_extended.jwt_required", "line_number": 79, "usage_type": "call"}]} +{"seq_id": "71515663742", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCopies s3 kv store into local directory structure\n\n(c) 2021 by aidan@latch.bio\n(c) copied and modified from https://stackoverflow.com/questions/31918960/boto3-to-download-all-files-from-a-s3-bucket\n\"\"\"\nimport os\n\nimport boto3\n\ns3_client = boto3.client(\"s3\")\n\n\ndef download_dir(prefix, local, bucket, client=s3_client):\n \"\"\"\n params:\n - prefix: pattern to match in s3\n - local: local path to folder in which to place files\n - bucket: s3 bucket with target contents\n - client: initialized s3 client object\n \"\"\"\n keys = []\n dirs = []\n next_token = \"\"\n base_kwargs = {\n \"Bucket\": bucket,\n \"Prefix\": prefix,\n }\n while next_token is not None:\n kwargs = base_kwargs.copy()\n if next_token != \"\":\n kwargs.update({\"ContinuationToken\": next_token})\n results = client.list_objects_v2(**kwargs)\n contents = results.get(\"Contents\")\n if contents is not None:\n for i in contents:\n k = i.get(\"Key\")\n if k[-1] != \"/\":\n keys.append(k)\n else:\n dirs.append(k)\n next_token = results.get(\"NextContinuationToken\")\n for d in dirs:\n dest_pathname = local + d.replace(prefix, \"\")\n if not os.path.exists(os.path.dirname(dest_pathname)):\n os.makedirs(os.path.dirname(dest_pathname))\n for k in keys:\n dest_pathname = local + k.replace(prefix, \"\")\n if not os.path.exists(os.path.dirname(dest_pathname)):\n os.makedirs(os.path.dirname(dest_pathname))\n client.download_file(bucket, k, dest_pathname)\n\n\ndef ensure_dir(file_path):\n directory = os.path.dirname(file_path)\n if not os.path.exists(directory):\n os.makedirs(directory)\n", "repo_name": "latchbio/wf-core-guideseq", "sub_path": "latch/s3_dir_download.py", "file_name": "s3_dir_download.py", "file_ext": "py", "file_size_in_byte": 1802, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "boto3.client", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path", "line_number": 46, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 46, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 47, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 47, "usage_type": "call"}, {"api_name": "os.path", "line_number": 47, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 50, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path", "line_number": 51, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path", "line_number": 56, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path", "line_number": 57, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 58, "usage_type": "call"}]} +{"seq_id": "11005815325", "text": "# Abstract graph of 3D transformations through time\n# Has a list of nodes and a list of edges\n# Allows getting transforms (edges) for a given node in a given time (frame)\n# Edge could be:\n# - rigid and known (so its pre-calibrated and given)\n# - rigid and unknown (needs solving, and can use multiple frames for better results)\n# - non-rigid and known (live tracking, so its given)\n# - non-rigid and unknown (needs solving, only possible if it is a loop)\n\n# Abstract class for the above, we will implement a test class and a real class\n# Transformations are 4x4 matrices\n# The whole transformation graph can be solved by solving each node's transformation\n\n# In the future we can use networkx to perform graph operations, but for now we use matrices for representation\n\n# We will first need to define the type of each edge: \"rigid-unknown\", \"rigid-known\", \"non-rigid-unknown\", \"non-rigid-known\"\n# We will also need to define the noise of each edge\n# Then, we create a empty matrix of matrices, where each matrix is a 4x4 transformation matrix\n\n# === Implementation ===\n# We will create a custom class for the matrix of matrices, we will implement so that it can be indexed by a tuple (node, node)\n# Each edge will also be associated with a type and a noise\n# Also, setting a value will also set the inverse of the value in the other direction\n\n# We will wrap around the matrix of matrices to create a graph class, which will have a list of nodes and a list of edges\n# We model the transformation noise as a gaussian distribution\n\n# ======================\n\n# Then, we populate the matrix with the known transformations (rigid and known, non-rigid and known)\n\n# Then, we estimate the non-rigid and unknown transformations, which will only work if the graph is a loop\n# We combine multiple potential paths and use weighted least squares to estimate the transformation. The optimal weight will be the one that minimizes the error.\n# The unsolvable nodes will be marked as such\n\n# Next, we estimate the rigid and unknown transformations with a time window of n frames\n# We can then similarly use weighted least squares to estimate the transformation. The optimal weight will be the one that minimizes the error.\n# The unsolvable nodes will be marked as such\n# This will also allow for potentially solving problems where the graph is not a loop, like AX = XB, where X is unknown\n\n# Finally, we can use the graph to solve for the transformations of any node in any frame\n\nimport json\nimport math\nfrom typing import Literal\nimport numpy as np\nfrom tools import *\n\n# These implementations are used for testing mostly, and online variants will be implemented later that uses only an iterative interface for solving; since in the online case, we will not know the whole graph at once\n\nclass TransformationGraph:\n def __init__(self, num_nodes: int, edges: list[tuple[int, int, Literal[\"rigid-unknown\", \"rigid-known\", \"non-rigid-unknown\", \"non-rigid-known\"], float]], frames: int=1):\n \"\"\"Initialize the transformation graph\n\n Parameters:\n num_nodes (int): Number of nodes in the graph\n edges (list[tuple[int, int, Literal[\"rigid-unknown\", \"rigid-known\", \"non-rigid-unknown\", \"non-rigid-known\"], float]]): List of edges, where each edge is a tuple of (node1, node2, type, noise)\n frames (int): Number of frames in the graph\n \"\"\"\n if frames < 1:\n raise Exception(\"Number of frames must be at least 1\")\n # TODO: Have better representation of noise. Look into Kalman filters.\n\n # Create a matrix of matrices\n self._matrix = np.nan * np.ones((num_nodes, num_nodes, frames, 4, 4))\n\n # Create a seperate np object matrix for the edge types, set to None (not np.nan) initially\n self._types = np.empty((num_nodes, num_nodes), dtype=object)\n\n # Create a seperate matrix for the noise of each edge\n self._noise = np.nan * np.ones((num_nodes, num_nodes))\n\n # Set the matrix edge types and noise\n for edge in edges:\n # Set edge type\n self._types[edge[0], edge[1]] = edge[2]\n self._types[edge[1], edge[0]] = edge[2]\n # Set noise\n self._noise[edge[0], edge[1]] = edge[3]\n self._noise[edge[1], edge[0]] = edge[3]\n\n # TODO: This should be in test class instead\n # # Validate intra-group edges are rigid\n # for group in self._groups:\n # for node1 in group:\n # for node2 in group:\n # if self._types[node1, node2, 0] != \"rigid-known\" and self._types[node1, node2, 0] != \"rigid-unknown\":\n # raise Exception(\"Inconsistent edge type in group\")\n\n # Fill the identity matrices\n for i in range(num_nodes):\n for j in range(frames):\n self._matrix[i, i, j] = np.eye(4)\n\n def __getitem__(self, key: tuple[int, int, int]) -> np.ndarray:\n \"\"\"Get the transformation matrix for a given edge and frame\n\n Parameters:\n key (tuple[int, int, int]): Tuple of (node1, node2, frame)\n\n Returns:\n np.ndarray: Transformation matrix\n \"\"\"\n # Throw an error if there is no connection type\n if self._types[key[0], key[1]] == None:\n raise Exception(\"No connection type defined for edge\")\n return self._matrix[key[0], key[1], key[2]]\n\n def __setitem__(self, key: tuple[int, int, int], value: np.ndarray):\n \"\"\"Set the transformation matrix for a given edge and frame\n\n Parameters:\n key (tuple[int, int, int]): Tuple of (node1, node2, frame)\n value (np.ndarray): Transformation matrix\n \"\"\"\n # Throw an error if there is no connection type\n if self._types[key[0], key[1]] == None:\n raise Exception(\"No connection type defined for edge\")\n\n # Set the value\n self._matrix[key[0], key[1], key[2]] = value\n\n # Set the inverse\n self._matrix[key[1], key[0], key[2]] = np.linalg.inv(value)\n\n def get_type(self, key: tuple[int, int]) -> Literal[\"rigid-unknown\", \"rigid-known\", \"non-rigid-unknown\", \"non-rigid-known\"]:\n \"\"\"Get the type of a given edge\n\n Parameters:\n key (tuple[int, int]): Tuple of (node1, node2)\n\n Returns:\n Literal[\"rigid-unknown\", \"rigid-known\", \"non-rigid-unknown\", \"non-rigid-known\"]: Type of the edge\n \"\"\"\n return self._types[key[0], key[1]]\n\n def get_noise(self, key: tuple[int, int]) -> float:\n \"\"\"Get the noise of a given edge\n\n Parameters:\n key (tuple[int, int]): Tuple of (node1, node2)\n\n Returns:\n float: Noise of the edge\n \"\"\"\n return self._noise[key[0], key[1]]\n\n def get_nodes(self) -> list[int]:\n \"\"\"Get the list of nodes in the graph\n\n Returns:\n list[int]: List of nodes\n \"\"\"\n return list(range(self._matrix.shape[0]))\n\n def get_edges(self, node:int) -> list[tuple[int, Literal[\"rigid-unknown\", \"rigid-known\", \"non-rigid-unknown\", \"non-rigid-known\"], float]]:\n \"\"\"Get the list of edges for a given node\n\n Parameters:\n node (int): Node\n\n Returns:\n list[tuple[int, Literal[\"rigid-unknown\", \"rigid-known\", \"non-rigid-unknown\", \"non-rigid-known\"], float]]: List of edges, where each edge is a tuple of (node, type, noise)\n \"\"\"\n # print(f'Checking edges for node {node}')\n edges = []\n for i in range(self._matrix.shape[0]):\n edge_type = self._types[node, i]\n if edge_type != None:\n edges.append((i, self._types[node, i], self._noise[node, i]))\n # print(f'Found edges {edges}')\n return edges\n\n @property\n def num_nodes(self) -> int:\n \"\"\"Get the number of nodes in the graph\n\n Returns:\n int: Number of nodes\n \"\"\"\n return self._matrix.shape[0]\n\n @property\n def num_frames(self) -> int:\n \"\"\"Get the number of frames in the graph\n\n Returns:\n int: Number of frames\n \"\"\"\n return self._matrix.shape[2]\n\nclass TestTransformationGraph(TransformationGraph):\n \"\"\"\n Specialized transformation graph for testing. Generates random ground truth transformations for each node and frame.\n \"\"\"\n\n def __init__(self, num_nodes: int, edges: list[tuple[int, int, Literal[\"rigid-unknown\", \"rigid-known\", \"non-rigid-unknown\", \"non-rigid-known\"], float]], frames: int):\n \"\"\"Initialize the transformation graph\n\n Parameters:\n num_nodes (int): Number of nodes in the graph\n edges (list[tuple[int, int, Literal[\"rigid-unknown\", \"rigid-known\", \"non-rigid-unknown\", \"non-rigid-known\"], float]]): List of edges, where each edge is a tuple of (node1, node2, type, noise)\n frames (int): Number of frames in the graph\n \"\"\"\n super().__init__(num_nodes, edges, frames)\n # Identify node groups that are rigidly connected\n nodes = set(range(num_nodes))\n self._groups = []\n self._groupMap = dict()\n # For each node, use BFS to find all nodes that are rigidly connected. After that, remove all those nodes from the set. Repeat until all nodes are removed.\n while len(nodes) > 0:\n # Get a random node\n node = nodes.pop()\n\n # Add the node to the group\n group = set([node])\n\n # Add all rigidly connected nodes to the group\n queue = [node]\n while len(queue) > 0:\n # Get the next node\n node = queue.pop(0)\n\n # Add all rigidly connected nodes to the group\n for i in range(num_nodes):\n if self._types[node, i] == \"rigid-known\" or self._types[node, i] == \"rigid-unknown\":\n if i not in group:\n group.add(i)\n queue.append(i)\n\n # Remove all nodes in the group from the set\n nodes = nodes - group\n self._groups.append(group)\n for node in group:\n self._groupMap[node] = len(self._groups) - 1\n\n # Generate ground truth transformations \n self._worldTransforms = np.zeros((num_nodes, frames, 4, 4))\n # Generate random transformations within groups, which stays the same for all frames\n # Since we assume a node can only be in one group, we can generate a random transform for every node\n # Individual nodes can be considered as a group of size 1\n intra_group_transforms = []\n for node in range(num_nodes):\n intra_group_transforms.append(generate_random_transform())\n # Generate random group transforms per frame\n group_transforms = []\n for i in range(frames):\n group_transforms.append([]) # Add a new frame\n for group in self.groups:\n group_transforms[i].append(generate_random_transform())\n # Now we can generate per node transforms for each frame\n for frame in range(frames):\n for node in range(num_nodes):\n group_id = self.get_group_id(node)\n # Set the ground truth transform\n self._worldTransforms[node, frame] = group_transforms[frame][group_id] @ intra_group_transforms[node]\n # print(f'Ground truth transform for node {node} in frame {frame}:')\n # print(self._worldTransforms[node, frame])\n # Second pass to generate relative transforms\n for frame in range(frames):\n for node in range(num_nodes):\n # For each edge, derive the relative transform from the ground truth\n for (neighbor, edge_type, noise) in self.get_edges(node):\n # print(f'Calculating relative transform for edge ({node}, {neighbor}) in frame {frame}')\n # Skip if edge is not known\n if edge_type == \"rigid-unknown\" or edge_type == \"non-rigid-unknown\":\n continue\n # Get the relative transform using calc_relative_transform(from, to)\n # print(node, neighbor, frame)\n # print(self._worldTransforms[node, frame], self._worldTransforms[neighbor, frame])\n relative_transform = calc_relative_transform(self._worldTransforms[node, frame], self._worldTransforms[neighbor, frame])\n # print(relative_transform)\n self[node, neighbor, frame] = relative_transform\n # Now we should be done!\n # Note, mentally we can think of the world origin as a separate node with an unknown non-rigid transformation to every other node\n\n def get_group_id(self, node: int) -> int:\n \"\"\"Get the group id of a node\n\n Parameters:\n node (int): Node\n\n Returns:\n int: Group id\n \"\"\"\n return self._groupMap[node]\n\n def get_group(self, group_id: int) -> set[int]:\n \"\"\"Get the group of a node\n\n Parameters:\n group_id (int): Group id\n\n Returns:\n set[int]: Group\n \"\"\"\n return self._groups[group_id]\n\n @property\n def groups(self) -> list[set[int]]:\n \"\"\"Gets a copy of the list of groups\n\n Returns:\n list[set[int]]: List of groups\n \"\"\"\n return self._groups.copy()\n\n def world_transform_to_dict(self) -> dict[int, dict[int, np.ndarray]]:\n \"\"\"Converts the world transforms to a json compatible dictionary\n\n Returns:\n dict[int, dict[int, np.ndarray]]: Dictionary of world transforms\n \"\"\"\n world_transforms = dict()\n for node in range(self.num_nodes):\n world_transforms[node] = dict()\n for frame in range(self.num_frames):\n # Remember to convert nan to None\n world_transforms[node][frame] = self._worldTransforms[node, frame].tolist()\n world_transforms[node][frame] = [[None if math.isnan(x) else x for x in row] for row in world_transforms[node][frame]]\n \n return world_transforms\n # Local transform matrix and world transforms could be merged into a single matrix if we treat the world origin as a node\n\n def local_transforms_to_dict(self) -> dict[int, dict[int, dict[int, np.ndarray]]]:\n \"\"\"Converts the local transforms to a json compatible dictionary\n\n Returns:\n dict[int, dict[int, dict[int, np.ndarray]]]: Dictionary of local transforms\n \"\"\"\n local_transforms = dict()\n for node in range(self.num_nodes):\n local_transforms[node] = dict()\n for neighbor in range(self.num_nodes):\n local_transforms[node][neighbor] = dict()\n for frame in range(self.num_frames):\n try:\n local_transforms[node][neighbor][frame] = self[node, neighbor, frame].tolist()\n local_transforms[node][neighbor][frame] = [[None if math.isnan(x) else x for x in row] for row in local_transforms[node][neighbor][frame]]\n except Exception:\n # No connection\n pass\n return local_transforms\n\n # Local transform also serializes unknown transforms since they are meant to be solved\n # World transforms on the other hand only serializes known transforms\n\n def edges_to_dict(self) -> dict[int, dict[int, dict[str, str]]]:\n \"\"\"Converts the edges to a json compatible dictionary\n\n Returns:\n dict[int, dict[int, dict[str, str]]]: Dictionary of edges\n \"\"\"\n edges = dict()\n for node in range(self.num_nodes):\n edges[node] = dict()\n for neighbor in range(self.num_nodes):\n edges[node][neighbor] = dict()\n edges[node][neighbor][\"type\"] = self._types[node, neighbor]\n edges[node][neighbor][\"noise\"] = self._noise[node, neighbor]\n if np.isnan(edges[node][neighbor][\"noise\"]):\n edges[node][neighbor][\"noise\"] = None\n return edges\n\n def to_dict(self) -> dict[str, dict]:\n \"\"\"Converts the graph to a json compatible dictionary\n\n Returns:\n dict[str, dict]: Dictionary of graph\n \"\"\"\n graph = dict()\n graph[\"world_transforms\"] = self.world_transform_to_dict()\n graph[\"local_transforms\"] = self.local_transforms_to_dict()\n graph[\"edges\"] = self.edges_to_dict()\n return graph\n\n def to_json_string(self) -> str:\n \"\"\"Converts the graph to a json string\n\n Returns:\n str: Json string\n \"\"\"\n return json.dumps(self.to_dict())\n\n# TODO: Reimplement TransformationGraphs using iterators so that we can use the same solvers for real time and offline", "repo_name": "shiukaheng/transforms-solver", "sub_path": "server/graphs.py", "file_name": "graphs.py", "file_ext": "py", "file_size_in_byte": 16807, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "typing.Literal", "line_number": 52, "usage_type": "name"}, {"api_name": "numpy.nan", "line_number": 65, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 71, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 95, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 109, "usage_type": "attribute"}, {"api_name": "numpy.linalg.inv", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 124, "usage_type": "attribute"}, {"api_name": "typing.Literal", "line_number": 126, "usage_type": "name"}, {"api_name": "typing.Literal", "line_number": 156, "usage_type": "name"}, {"api_name": "typing.Literal", "line_number": 197, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 238, "usage_type": "call"}, {"api_name": "math.isnan", "line_number": 320, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 308, "usage_type": "attribute"}, {"api_name": "math.isnan", "line_number": 339, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 325, "usage_type": "attribute"}, {"api_name": "numpy.isnan", "line_number": 361, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 383, "usage_type": "call"}]} +{"seq_id": "70165285182", "text": "# imports\nimport cv2 as cv\nimport numpy as np\nimport time\n\n# definitions\nwriter = None\nh, w, = None, None\n\n# load yolo labels\nwith open('yolo-coco-data/coco.names') as f:\n labels = [line.strip() for line in f]\n\nprint('List with labels names:')\nprint(labels)\n\n# load yolo network\nnetwork = cv.dnn.readNetFromDarknet(\"./yolo-coco-data/yolov3.cfg\", \"./yolo-coco-data/yolov3.weights\")\n\n# create a list with all the output layers names\nlayers_names_all = network.getLayerNames()\n\nlayers_names_output = [\\\n layers_names_all[i - 1] for i in network.getUnconnectedOutLayers()]\n\n# setting minimum probability to eliminate weak predictions\nprobability_minimum = 0.5\n# setting threshold for non-maximum suppression\nthreshold = 0.3\n\n# generate colors for representing every detected object\ncolors = np.random.randint(0, 255, size=(len(labels), 3), dtype='uint8')\n\nf = 0 # Counting frames\nt = 0 # Counting total time\n\nvideo = cv.VideoCapture(\"./videos/traffic-cars.mp4\")\nwhile True:\n ret, frame = video.read()\n \n if not ret:\n break;\n \n if w is None or h is None:\n h, w = frame.shape[:2]\n \n # the image has to be converted to a blob \n blob = cv.dnn.blobFromImage(\n frame, # input image\n 1/255.0, # normalization factor\n (416, 416), # size (416, 416) is recommended for yolo\n swapRB=True,# swap red and blue channels\n crop=False # no cropping\n )\n \n network.setInput(blob) # set the blob as input to the network\n start = time.time() # start the timer\n # You can get all outputs from the network by calling forward() method\n # and passing names of the layers you want to get outputs from\n # In this case, we will get the names of the output layers\n output_from_network = network.forward(layers_names_output) # forward pass\n end = time.time() # stop the timer\n \n f += 1\n f += end - start\n \n print('Frame number {0} took {1:.5f} seconds'.format(f, end - start))\n\n bounding_boxes = []\n confidences = []\n class_numbers = []\n \n# the YOLO model has multiple output layers because it detects objects at multiple scales. The output from each of these layers includes information on bounding boxes, objectness score, and class probabilities for multiple grid cells of a particular scale.\n# Specifically, for YOLOv3, there are three output layers corresponding to three different scales. For each scale, the model divides the input image into a grid (e.g., 13x13, 26x26, 52x52), and each grid cell predicts a fixed number of bounding boxes. For each bounding box, the model predicts coordinates (x, y, width, height), an objectness score, and class probabilities for all classes (e.g., 80 classes in the COCO dataset).\n# After the forward pass through the network, the output includes the predictions from all of these layers. The script processes these outputs to extract the class with the highest probability for each bounding box and uses this information to draw bounding boxes and labels on the video frames.\n \n for result in output_from_network:\n for detected_objects in result:\n scores = detected_objects[5:]\n class_current = np.argmax(scores)\n confidence_current = scores[class_current]\n \n if confidence_current > probability_minimum:\n box_current = detected_objects[0:4] * np.array([w, h, w, h])\n x_center, y_center, box_width, box_height = box_current\n x_min = int(x_center - (box_width / 2))\n y_min = int(y_center - (box_height / 2))\n \n bounding_boxes.append([x_min, y_min, int(box_width), int(box_height)])\n confidences.append(float(confidence_current))\n class_numbers.append(class_current)\n \n# Suppression of non-maximum boxes\n results = cv.dnn.NMSBoxes(bounding_boxes, confidences, probability_minimum, threshold)\n\n if len(results) > 0:\n for i in results.flatten():\n x_min, y_min = bounding_boxes[i][0], bounding_boxes[i][1]\n box_width, box_height = bounding_boxes[i][2], bounding_boxes[i][3]\n \n color_box_current = colors[class_numbers[i]].tolist()\n \n cv.rectangle(frame, (x_min, y_min), (x_min + box_width, y_min + box_height), color_box_current, 2)\n \n text_box_current = '{}: {:.4f}'.format(labels[int(class_numbers[i])], confidences[i])\n \n cv.putText(frame, text_box_current, (x_min, y_min - 5), cv.FONT_HERSHEY_SIMPLEX, 0.5, color_box_current, 2)\n \n # Initializing writer\n # we do it only once from the very beginning\n # when we get spatial dimensions of the frames\n if writer is None:\n # Constructing code of the codec\n # to be used in the function VideoWriter\n fourcc = cv.VideoWriter_fourcc(*'mp4v')\n\n # Writing current processed frame into the video file\n # Pay attention! If you're using Windows, yours path might looks like:\n # r'videos\\result-traffic-cars.mp4'\n # or:\n # 'videos\\\\result-traffic-cars.mp4'\n writer = cv.VideoWriter('videos/result-traffic-cars.mp4', fourcc, 30,\n (frame.shape[1], frame.shape[0]), True)\n\n # Write processed current frame to the file\n writer.write(frame)\n \n # Printing final results\nprint()\nprint('Total number of frames', f)\nprint('Total amount of time {:.5f} seconds'.format(t))\nprint('FPS:', round((f / t), 1))\n\n\n# Releasing video reader and writer\nvideo.release()\nwriter.release()", "repo_name": "felipedepauli/crz-docs", "sub_path": "docs-ai/computer-vision/courses/UY_03_Train_YOLO_for_Object_Detection/02_Class/02_Yolo_on_Video_2.py", "file_name": "02_Yolo_on_Video_2.py", "file_ext": "py", "file_size_in_byte": 5634, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "cv2.dnn.readNetFromDarknet", "line_number": 18, "usage_type": "call"}, {"api_name": "cv2.dnn", "line_number": 18, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 32, "usage_type": "attribute"}, {"api_name": "cv2.VideoCapture", "line_number": 37, "usage_type": "call"}, {"api_name": "cv2.dnn.blobFromImage", "line_number": 48, "usage_type": "call"}, {"api_name": "cv2.dnn", "line_number": 48, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 57, "usage_type": "call"}, {"api_name": "time.time", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 84, "usage_type": "call"}, {"api_name": "cv2.dnn.NMSBoxes", "line_number": 94, "usage_type": "call"}, {"api_name": "cv2.dnn", "line_number": 94, "usage_type": "attribute"}, {"api_name": "cv2.rectangle", "line_number": 103, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 107, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 107, "usage_type": "attribute"}, {"api_name": "cv2.VideoWriter_fourcc", "line_number": 115, "usage_type": "call"}, {"api_name": "cv2.VideoWriter", "line_number": 122, "usage_type": "call"}]} +{"seq_id": "74603593662", "text": "from itertools import combinations\n\nclass place:\n def __init__(self, r, c):\n self.r, self.c = r,c\n def cal_dist(self, other):\n return abs(other.r-self.r)+abs(other.c-self.c)\n\nn, m = map(int, input().split())\ntown = [list(map(int, input().split())) for _ in range(n)]\nchicken_list = []\nhome_list = []\n\nfor i in range(n):\n for j in range(n):\n if town[i][j] == 0x01:\n home_list.append(place(i, j))\n elif town[i][j] == 0x02:\n chicken_list.append(place(i, j))\n\ncom_list = combinations(chicken_list, m)\nchicken_dist = 10000\nfor com in com_list:\n ch = sum([min([h.cal_dist(x) for x in com]) for h in home_list])\n chicken_dist = ch if ch < chicken_dist else chicken_dist\n \nprint(chicken_dist)", "repo_name": "d2h10s/cote", "sub_path": "baekjoon/b_15686_치킨배달.py", "file_name": "b_15686_치킨배달.py", "file_ext": "py", "file_size_in_byte": 756, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "itertools.combinations", "line_number": 21, "usage_type": "call"}]} +{"seq_id": "550377033", "text": "import large_image\nimport mysql.connector\nimport numpy as np\nimport cv2\nfrom scipy.misc import imsave\n\n\ninputImageFile =\"/home/sanghoon/docker-py/hmlWeb/TCGA-3C-AALJ-01Z-00-DX1.svs.dzi.tif\"\nslideName = 'TCGA-3C-AALJ-01Z-00-DX1'\n\nleft = 50000\ntop = 35000\nwidth = 2000\nheight = 2000\nbottom = top + height\nright = left + width\n\nbold = 512\nbold_left = left - bold\nbold_top = top - bold\nbold_bottom = bottom + bold\nbold_right = right + bold\nbold_width = width + 2*bold\nbold_height = height + 2*bold\n\nts = large_image.getTileSource(inputImageFile)\n\nregion = dict(\n left=left, top=top,\n width=width, height=height,\n)\n\nim_region = ts.getRegion(\n region=region, format=large_image.tilesource.TILE_FORMAT_NUMPY\n)[0]\n\nmydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"guest\",\n passwd=\"guest\",\n database=\"nuclei\",\n charset='utf8',\n use_unicode=True\n)\n\nboundaryTablename = 'sregionboundaries'\n\nruncursor = mydb.cursor()\n\nquery = 'SELECT boundary from ' + boundaryTablename + ' where slide=\"' + slideName + \\\n'\" AND centroid_x BETWEEN ' + str(left) + ' AND ' + str(right) + \\\n' AND centroid_y BETWEEN ' + str(top) + ' AND ' + str(bottom)\n\nruncursor.execute(query)\n\nboundarySet = runcursor.fetchall()\n\n# set an array for boundary points in a region to zero\n# boundaryPoints = np.zeros((1, 2), dtype=np.int32)\nboundaryPoints = []\n# b_index = 0\nfor b in boundarySet:\n object = b[0].encode('utf-8').split(' ')\n object_points = []\n for p in range(len(object)-1):\n intP = map(int, object[p].split(','))\n intP[0] = intP[0] - left + bold\n intP[1] = intP[1] - top + bold\n object_points.append(intP)\n boundaryPoints.append(np.asarray(object_points))\n\nim_bold = np.zeros((bold_width, bold_height), dtype=np.uint8)\n\ncv2.fillPoly(im_bold, boundaryPoints, 255)\n\nim_out = im_bold[bold:bold+width, bold:bold+width]\n\nimsave('./test.png', im_out)\n", "repo_name": "slee172/HistomicsML-TA-old", "sub_path": "predict-rest-api/validate.py", "file_name": "validate.py", "file_ext": "py", "file_size_in_byte": 1863, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "large_image.getTileSource", "line_number": 26, "usage_type": "call"}, {"api_name": "large_image.tilesource", "line_number": 34, "usage_type": "attribute"}, {"api_name": "mysql.connector.connector.connect", "line_number": 37, "usage_type": "call"}, {"api_name": "mysql.connector.connector", "line_number": 37, "usage_type": "attribute"}, {"api_name": "mysql.connector", "line_number": 37, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 72, "usage_type": "attribute"}, {"api_name": "cv2.fillPoly", "line_number": 74, "usage_type": "call"}, {"api_name": "scipy.misc.imsave", "line_number": 78, "usage_type": "call"}]} +{"seq_id": "25570126385", "text": "from PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.uic import loadUi\nfrom splitter_module import group, member\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport os, sys\nimport pickle\nimport pandas as pd\nimport numpy as np\nimport splitter_module as SM\n\n######################################################################################################################################################################################\n#GUI class for Change/Delete group window\nclass CDGwindow(QWidget):\n def __init__(self):\n super(CDGwindow,self).__init__();\n loadUi('./gui/qtgui/cdgw.ui',self);\n self.setWindowTitle(\"Select Group\");\n self.setStyleSheet(\"QWidget {background: \"+color+\";}\");\n######################################################################################################################################################################################\n#GUI class for payment window\nclass Pwindow(QWidget):\n def __init__(self):\n super(Pwindow,self).__init__();\n loadUi('./gui/qtgui/payment.ui',self);\n self.setWindowTitle(\"Payment\");\n self.setStyleSheet(\"QWidget {background: \"+color+\";}\");\n######################################################################################################################################################################################\n#GUI class for expense window\nclass Ewindow(QWidget):\n def __init__(self):\n super(Ewindow,self).__init__();\n loadUi('./gui/qtgui/expense.ui',self);\n self.setWindowTitle(\"New Expense\");\n self.setStyleSheet(\"QWidget {background: \"+color+\";}\");\n######################################################################################################################################################################################\n#GUI class for Empty window\nclass EmptyWindow(QWidget):\n def __init__(self):\n super(EmptyWindow,self).__init__();\n loadUi('./gui/qtgui/empty.ui',self);\n self.setStyleSheet(\"QWidget {background: \"+color+\";}\");\n######################################################################################################################################################################################\n#GUI class for Settings window\nclass SettingsWindow(QDialog):\n def __init__(self):\n super(SettingsWindow,self).__init__();\n loadUi('./gui/qtgui/settings.ui',self);\n self.setWindowTitle(\"Settings\");\n self.setStyleSheet(\"QDialog {background: \"+color+\";}\");\n######################################################################################################################################################################################\n#GUI class for main window\nclass mainWindow(QMainWindow):\n def __init__(self):\n #Load UI file\n super(mainWindow, self).__init__();\n loadUi('./gui/qtgui/splitter.ui',self);\n\n #Set startup text\n self.setWindowTitle(\"SpLiTtEr!!!\");\n self.disclaimer.setText(\"Welcome!!!\");\n\n #Mapping button to functions\n self.newGroupButton.clicked.connect(self.newGroup);\n self.changeGroupButton.clicked.connect(self.selectGroup);\n self.deleteGroupButton.clicked.connect(self.selectGroup);\n self.newMemberButton.clicked.connect(self.newMember);\n self.newExpenseButton.clicked.connect(self.newExpense);\n self.newPaymentButton.clicked.connect(self.newPayment);\n self.suggestedPaymentsButton.clicked.connect(self.suggPayments);\n self.statsButton.clicked.connect(self.stats);\n self.settingsButton.clicked.connect(self.settings);\n self.historyButton.clicked.connect(self.history);\n\n #Set current group name in display\n if(current_group != None):\n self.groupName.setText(current_group.name.upper());\n \n #Pre-exit function before closing\n def closeEvent(self, event):\n global color, currency, current_group;\n setting_data = {};\n #Confirmation message box\n reply = QMessageBox.question(self, 'Quit', 'Are You Sure to Quit?', QMessageBox.No | QMessageBox.Yes);\n if reply == QMessageBox.Yes:\n #Store the objects into memory\n with open('./data/record.pkl', 'wb') as output:\n pickle.dump(record, output, pickle.HIGHEST_PROTOCOL);\n\n #Get the objects to be stored in a dict\n setting_data['current_group'] = current_group;\n setting_data['currency'] = currency;\n setting_data['color'] = color;\n\n #Store the settings data into memory\n with open(\"./data/settings.pkl\",'wb') as output:\n pickle.dump(setting_data, output, pickle.HIGHEST_PROTOCOL);\n #Close all windows\n plt.close();\n event.accept();\n else:\n #Ignore if No is clicked\n event.ignore();\n\n #Group creation button API\n def newGroup(self):\n window.disclaimer.setText(\"\");\n input_window = QInputDialog();\n input_window.setOkButtonText(\"Create\");\n name, okPressed = input_window.getText(self,\"New Group\",\"Group Name: \");\n if(okPressed == True):\n #Condition check for empty input\n if (bool(name) == False):\n self.disclaimer.setText(\"Please enter a name\");\n #Condition check for same group name\n elif SM.isGroupPresent(name, group_list) == True:\n self.disclaimer.setText(\"Group Already Exists\");\n else:\n #Create group API call\n createGroup(name.lower());\n self.disclaimer.setText(\"Group \"+name+\" Added Successfully\");\n \n #Group change/delete button API\n def selectGroup(self):\n global group_list;\n window.disclaimer.setText(\"\");\n #Check if no groups are added\n if (SM.isGroupListEmpty(group_list) == True):\n self.disclaimer.setText(\"No Groups found!!!\");\n else:\n #Load change group UI\n self.nw = CDGwindow();\n #Map buttons to functions depending on the button clicked\n if (self.sender().objectName() == \"changeGroupButton\"):\n self.nw.buttonBox.accepted.connect(changeGroup);\n if (self.sender().objectName() == \"deleteGroupButton\"):\n self.nw.buttonBox.accepted.connect(delGroup);\n self.nw.buttonBox.rejected.connect(self.nw.close);\n #Add elements dynamically to the list box\n for ele in group_list:\n self.nw.cb.addItem(ele.name);\n #Display GUI box\n self.nw.show();\n\n #Member addition button API\n def newMember(self):\n window.disclaimer.setText(\"\");\n #Check if no groups are added\n if (SM.isGroupListEmpty(group_list) == True):\n self.disclaimer.setText(\"No Groups found!!!\");\n else:\n input_window = QInputDialog();\n input_window.setOkButtonText(\"Add\");\n name, okPressed = input_window.getText(self,\"New Member\",\"Member Name: \");\n if(okPressed == True):\n #Condition check for empty input\n if (bool(name) == False):\n self.disclaimer.setText(\"Please enter a name\");\n #Condition check for same member name\n elif (SM.isMemberPresent(name.lower(),current_group)):\n self.disclaimer.setText(\"Member Already Exists\");\n else:\n #Member addition API call\n current_group.addMember(name.lower());\n #Set display element text\n self.disclaimer.setText(name+\" added to Group \"+current_group.name);\n self.displaySummary();\n\n #New expense addition button API\n def newExpense(self):\n window.disclaimer.setText(\"\");\n #List to hold all credits of all members\n creds = {};\n #Function for placeholder text\n def updatePlaceholder():\n #Read amount entered\n amt = self.nw.amtInput.text();\n #Amount validation\n if (SM.isAmountValid(amt) == True):\n amt = float(amt);\n equal = round(amt/(current_group.size),2);\n #Check if checkbox is selected\n if (window.nw.edCheckBox.isChecked() == True):\n for (k,v) in self.lines.items():\n v.setPlaceholderText(str(equal)+\"+\");\n elif (window.nw.perCheckBox.isChecked() == True):\n for (k,v) in self.lines.items():\n v.setPlaceholderText(str(round(100.0/(current_group.size),2))+\"%\");\n else:\n for (k,v) in self.lines.items():\n v.setPlaceholderText(str(equal));\n \n\n #Function to change the label when check box is selected\n def state_changed(self):\n #Update plcaeholder text if selection is changed\n updatePlaceholder();\n #If equal+delta is selected\n if (window.nw.sender().objectName() == \"edCheckBox\"):\n if (window.nw.edCheckBox.isChecked() == True):\n window.nw.perCheckBox.setChecked(False);\n window.nw.layoutTitle.setText(\"Delta Difference\");\n #Set the placeholder text\n window.nw.amtInput.setPlaceholderText(\"Amount to be shared equally\");\n return;\n elif (window.nw.sender().objectName() == \"perCheckBox\"):\n if (window.nw.perCheckBox.isChecked() == True):\n window.nw.edCheckBox.setChecked(False);\n window.nw.layoutTitle.setText(\"Percentage Share\");\n #Clear the placeholder text\n window.nw.amtInput.setPlaceholderText(\"\");\n return;\n #If both of the options are not selected\n window.nw.layoutTitle.setText(\"Individual Share\");\n #Clear the placeholder text\n window.nw.amtInput.setPlaceholderText(\"\");\n return;\n \n #Function to perform the pre condition checks and prepare data to send to add expense API\n def getDebits(creds, amt):\n #List to hold all debits of all members\n debts = {};\n #Get the description\n des = self.nw.descripInput.text();\n #Loop through all Line Edits\n for mem in current_group.members:\n #Read data in each Line Edit\n ind_amt = self.lines[mem.name].text();\n #Check for empty LineEdit \n if (ind_amt == \"\"):\n debts[mem.name+\"_debit\"] = 0;\n #Check for numeric value of the LineEdit\n elif (ind_amt.isnumeric() == True):\n debts[mem.name+\"_debit\"] = (-1*float(ind_amt));\n #Invalid amount disclaimer\n else:\n self.disclaimer.setText(\"Invalid amount\");\n del(self.nw);\n return;\n\n #Check if all LineEdits are empty, if empty then equal share\n if (all(val == 0 for val in list(debts.values()))):\n #Check if the percentage option is selected\n if (self.nw.perCheckBox.isChecked() == True):\n debts = debts.fromkeys(debts.keys(),(-1*(100/current_group.size)));\n else:\n debts = debts.fromkeys(debts.keys(),(-1*(amt/current_group.size)));\n\n #Check if the equal+delta option is selected\n if (self.nw.edCheckBox.isChecked() == True):\n #Create a temp dict with equal shares\n temp_debts = dict.fromkeys(debts.keys(),(-1*(amt/current_group.size)));\n #Add all the delta differences to respective members\n for k in debts.keys():\n temp_debts[k] += debts[k]; \n #Copy the temp dict to debts\n debts = temp_debts.copy();\n #Modify the amount\n amt = abs(sum(debts.values()));\n #Check if the percentage option is selected\n elif (self.nw.perCheckBox.isChecked() == True):\n #Share the amount percentage-wise\n for key in debts.keys():\n debts[key] = (debts[key]*amt)/100;\n\n #Check if all values add up to the entered amount\n if ((abs(abs(sum(list(debts.values()))) - amt) > 0.1) or (abs(sum(list(creds.values())) - amt) > 0.1)):\n msg = QMessageBox();\n msg.setIcon(QMessageBox.Critical)\n msg.setText(\"Shares do not add up to the total amount given.\");\n msg.setWindowTitle(\"Error!\")\n msg.exec_();\n else:\n #Call add expense API by passing all the required processed data\n current_group.addExpense(des, creds, amt, debts);\n self.disclaimer.setText(\"Expense added successfully.\");\n self.displaySummary();\n del(self.nw);\n return;\n\n def getPayers():\n #Lists to hold all checkbox and lineedit objects\n self.checkboxes = [];\n self.lineedits = [];\n #Create a settle window\n self.pw = EmptyWindow();\n self.pw.setWindowTitle(\"Paid by\");\n #Add checkbox for each member\n for mem in current_group.members:\n #Create a checkbox\n self.pw.cb = QCheckBox(self.pw);\n self.pw.cb.setText(mem.name);\n #Create a LineEdit\n self.pw.le = QLineEdit(self.pw);\n self.pw.formLayout.addRow(self.pw.cb,self.pw.le);\n #Collect the checkboxes and lineedits for future reference\n self.checkboxes.append(self.pw.cb);\n self.lineedits.append(self.pw.le);\n\n #Map buttons and signals to the APIs\n self.pw.buttonBox.accepted.connect(getCreds);\n self.pw.buttonBox.rejected.connect(self.pw.close);\n #Display GUI box\n self.pw.show();\n\n def getCreds():\n #Get the amount\n amt = self.nw.amtInput.text();\n #Validate the amount\n if (SM.isAmountValid(amt) == False):\n self.disclaimer.setText(\"Invalid amount\");\n del(self.nw);\n return;\n #Convert amount to float\n amt = float(amt);\n\n #Create a credit library\n for mem in current_group.members:\n creds[mem.name+\"_credit\"] = 0;\n\n #Choose only the checkboxes which are selected\n for ele in self.checkboxes:\n if (ele.isChecked() == True):\n #Get and validate the individual amount\n num = self.lineedits[self.checkboxes.index(ele)].text();\n if (SM.isAmountValid(num) == False):\n self.disclaimer.setText(\"Invalid amount\");\n del(self.pw);\n return;\n else:\n #Convert the number to float\n num = float(num);\n #Update the credit dictionary\n creds[ele.text()+\"_credit\"] = num;\n\n #Get debits API\n getDebits(creds, amt); \n del(self.pw);\n return; \n\n #Variable to hold all lineedits\n self.lines = {};\n #Check if no groups are added\n if (SM.isGroupListEmpty(group_list) == True):\n self.disclaimer.setText(\"No Groups found!!!\");\n #Check if no members are present in a group\n elif SM.isMemberListEmpty(current_group):\n self.disclaimer.setText(\"No Members in the group\");\n else:\n #Load change group UI\n self.nw = Ewindow();\n self.nw.buttonBox.button(QDialogButtonBox.Ok).setText(\"Add\");\n #Dynamically add row for each member\n for mem in current_group.members:\n #Add LineEdit for each member\n self.lines[mem.name] = QLineEdit();\n self.nw.formLayout.addRow(QLabel(mem.name),self.lines[mem.name]);\n #Assigning placeholder text\n self.nw.amtInput.textChanged.connect(updatePlaceholder);\n\n #Map button to APIs\n self.nw.buttonBox.accepted.connect(getPayers);\n self.nw.buttonBox.rejected.connect(self.nw.close);\n self.nw.perCheckBox.stateChanged.connect(state_changed);\n self.nw.edCheckBox.stateChanged.connect(state_changed);\n \n #Display GUI box\n self.nw.show();\n\n #Method to call payment API\n def newPayment(self):\n window.disclaimer.setText(\"\");\n #Pre process data to call payment API\n def processPayment():\n #Get the payer and check if the member exists\n frm = self.nw.fromInput.currentText().lower();\n if (SM.isMemberPresent(frm, current_group) == False):\n self.disclaimer.setText(frm+\" not found in group \"+current_group.name);\n del(self.nw);\n return;\n\n #Get the payee and check if the member exists\n to = self.nw.toInput.currentText().lower();\n if (SM.isMemberPresent(to, current_group) == False):\n self.disclaimer.setText(to+\" not found in group \"+current_group.name);\n del(self.nw);\n return;\n\n #validate the amount entered\n amt = self.nw.amtInput.text();\n if (SM.isAmountValid(amt) == False):\n self.disclaimer.setText(\"Invalid amount\");\n del(self.nw);\n return;\n #Convert amount to float\n amt = float(amt);\n\n #Call payment addition API\n current_group.addPayment(frm,to,amt);\n self.displaySummary();\n #Set display elements after successful transaction\n self.disclaimer.setText(\"Payment from \"+frm+\" to \"+to+\" successfull\");\n del(self.nw);\n\n #Method to update the comboBox with members other than from member\n def updateComboBox():\n #Clear the combo box\n self.nw.toInput.clear();\n #Include all members except the selected one\n for mem in current_group.members:\n if(self.nw.fromInput.currentText().lower() != mem.name):\n self.nw.toInput.addItem(mem.name);\n \n #Check if no groups are added\n if (SM.isGroupListEmpty(group_list) == True):\n self.disclaimer.setText(\"No Groups found!!!\");\n #Check if no members are present in a group\n elif SM.isMemberListEmpty(current_group):\n self.disclaimer.setText(\"No Members in the group\");\n else:\n #Open the payment window\n self.nw = Pwindow();\n self.nw.buttonBox.button(QDialogButtonBox.Ok).setText(\"Pay\");\n #Add all member names into the from combobox\n for mem in current_group.members:\n self.nw.fromInput.addItem(mem.name);\n #Initial call to the function\n updateComboBox();\n #Map buttons and signals to the APIs\n self.nw.fromInput.currentIndexChanged.connect(updateComboBox);\n self.nw.buttonBox.accepted.connect(processPayment);\n self.nw.buttonBox.rejected.connect(self.nw.close);\n #Display GUI box\n self.nw.show();\n\n #Summary display function\n def displaySummary(self):\n disp_data = current_group.summary(); \n disp = \"\";\n for (k,v) in disp_data.items():\n disp += (k+\"\\t\\t\\t\\t \"+str(v)+\" \"+currency+\"\\n\");\n self.displayText.setText(\"\");\n self.displayText.setText(disp);\n\n #Settle API\n def suggPayments(self):\n window.disclaimer.setText(\"\");\n global settle_data;\n self.settle_lines = [];\n #Check if no groups are added\n if (SM.isGroupListEmpty(group_list) == True):\n self.disclaimer.setText(\"No Groups found!!!\");\n #Check if no members are present in a group\n elif SM.isMemberListEmpty(current_group):\n self.disclaimer.setText(\"No Members in the group\");\n else:\n #Get the settle status\n message, settle_data = current_group.suggestedPayments();\n #Condition check if the accounts are settled\n if (message == None):\n msg = QMessageBox();\n msg.setWindowTitle(\"Suggested Payments\");\n msg.setText(\"Dues already settled\");\n msg.exec_();\n else:\n #Create a settle window\n self.nw = EmptyWindow();\n self.nw.setWindowTitle(\"Suggested Payments\");\n #Add checkbox for each of the transactions\n for ele in settle_data:\n self.nw.cb = QCheckBox(self.nw);\n self.nw.cb.setText(ele['From'].upper()+ \" pays to \"+ele['To'].upper()+\"\\t \"+currency+\" \"+str(ele['amount']));\n self.nw.formLayout.addRow(self.nw.cb);\n #Collect the checkboxes for future reference\n self.settle_lines.append(self.nw.cb);\n\n #Map buttons and signals to the APIs\n self.nw.buttonBox.button(QDialogButtonBox.Ok).setText(\"Settle\");\n self.nw.buttonBox.accepted.connect(settleUp);\n self.nw.buttonBox.rejected.connect(self.nw.close);\n #Display GUI box\n self.nw.show();\n \n #Function to plot statistics\n def stats(self):\n window.disclaimer.setText(\"\");\n #Check if no groups are added\n if (SM.isGroupListEmpty(group_list) == True):\n self.disclaimer.setText(\"No Groups found!!!\");\n else:\n global file;\n #Read the csv file\n csv_data = SM.getCsvFile(file);\n #Collect all members as labels\n labels = [mem.name for mem in current_group.members];\n #Collect expenses of each member\n expenses = [mem.expenses for mem in current_group.members];\n \n #Pie-Chart\n plt.subplot(221);\n #Add all relevant titles to the plot\n plt.title(\"Total spends\\n\"+str(sum(expenses)));\n #Collect the data to be visualised\n sizes = [((val/sum(expenses))*100) for val in expenses]; \n explode = [0.05 for s in sizes];\n #Plotting a pie chart\n plt.pie(sizes, labels=labels, explode=explode, autopct='%1.1f%%', startangle=90);\n\n #Bar-Graph\n plt.subplot(222);\n #Add all relevant titles to the plot\n plt.title('Expenses per member');\n plt.xlabel('Members');\n plt.ylabel('Expenses');\n #Collect the data to be visualised\n x = np.arange(len(labels));\n plt.xticks(x, labels);\n spends_all = [mem.spend_count for mem in current_group.members];\n #Plot the bars\n plt.bar(x, spends_all, width=0.4, edgecolor='white');\n\n #Multiple Bar-Graph\n plt.subplot(212);\n #Add all relevant titles to the plot\n plt.title(\"Personal expenditure\");\n plt.xlabel('Months');\n plt.ylabel('Amount');\n #Collect the data to be visualised\n months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];\n data = {};\n bars = [];\n x = np.arange(len(months));\n plt.xticks(x, months);\n width = 0.15;\n #Create a dictionary for each member for all months\n for mem in labels:\n data[mem] = {};\n for m in months:\n data[mem][m] = 0; \n \n #Loop through all rows and collect expenses for all members in a selected month\n for idx, row in csv_data.iterrows():\n #Get the current month\n curr_month = datetime.strptime(row['Timestamp'],\"%Y-%m-%d %H:%M:%S.%f\").strftime(\"%b\");\n #Check debit and add it to the dictionary for corresponding month\n for mem in labels:\n data[mem][curr_month] += abs(row[mem+\"_debit\"]);\n \n #Position adjust for plotting the bars\n pos_adjust = x-(int(len(labels)/2)*width);\n #Plot all bars and collect then in bars\n for (k,v) in data.items():\n bars.append(plt.bar(pos_adjust,list(v.values()),width,edgecolor='white'));\n pos_adjust += width;\n\n #Show legend\n plt.legend(bars,labels);\n\n #Display the plot\n plt.show();\n\n #Method to apply settings\n def settings(self):\n window.disclaimer.setText(\"\");\n self.nw = SettingsWindow();\n #Map buttons and signals to the APIs\n self.nw.buttonBox.button(QDialogButtonBox.Ok).setText(\"Apply\");\n self.nw.colorButton.clicked.connect(openColorDialog);\n self.nw.buttonBox.accepted.connect(applySettings);\n self.nw.buttonBox.rejected.connect(self.nw.close);\n #Display GUI box\n self.nw.show();\n\n #Method to show transaction history\n def history(self):\n #Define exiting method\n def closeHistory():\n self.nw.close;\n del(self.nw);\n\n window.disclaimer.setText(\"\");\n #Check if no groups are added\n if (SM.isGroupListEmpty(group_list) == True):\n self.disclaimer.setText(\"No Groups found!!!\");\n else:\n #Create a new window\n self.nw = EmptyWindow();\n self.nw.resize(830,500);\n self.nw.setWindowTitle(\"Transaction History\");\n #Delete unwanted elements\n del(self.nw.formLayout);\n del(self.nw.buttonBox);\n #Create a table widget and a button widget\n self.tableWidget = QTableWidget();\n self.button = QPushButton(\"OK\");\n #Read csv file\n csv_data = SM.getCsvFile(file);\n #Add columns - Date, Description, Amount, Paid by, Shares\n self.tableWidget.setRowCount(csv_data[\"Timestamp\"].count());\n self.tableWidget.setColumnCount(5);\n self.tableWidget.setHorizontalHeaderLabels([\"Date\",\"Description\",\"Amount\",\"Paid by\",\"Shares(\"+\",\".join([mem.name for mem in current_group.members])+\")\"]);\n\n #Loop through all rows and collect expenses for all members in a selected month\n for idx, row in csv_data.iterrows():\n #Local temp varaibles\n shares = [];\n payers = [];\n temp_row = dict(row);\n #Loop through all elements to get the share and amount\n for ele in row:\n #Enter only if the string is float\n try:\n ele = float(ele);\n #Check only for debit transactions\n if ele < 0:\n shares.append(abs(ele));\n #Check for credit transactions\n elif ele > 0:\n #Get payers names\n p = list(temp_row.keys())[list(temp_row.values()).index(ele)];\n #Set the element to 0 to avoid duplicate condition\n temp_row[p] = 0;\n #Append payers name to the list\n payers.append(p[:-7]);\n except:\n pass;\n\n #Add the data into the respective fields and set column width\n self.tableWidget.setColumnWidth(0, 100);\n self.tableWidget.setItem(idx,0, QTableWidgetItem(str(row[\"Timestamp\"][:10])));\n self.tableWidget.setColumnWidth(1, 200);\n self.tableWidget.setItem(idx,1, QTableWidgetItem(row[\"Description\"]));\n self.tableWidget.setColumnWidth(2, 100);\n self.tableWidget.setItem(idx,2, QTableWidgetItem(str(sum(shares))));\n self.tableWidget.setColumnWidth(3, 150);\n self.tableWidget.setItem(idx,3, QTableWidgetItem(\",\".join(payers)));\n self.tableWidget.setColumnWidth(4, 200);\n self.tableWidget.setItem(idx,4, QTableWidgetItem(\",\".join([str(s) for s in shares])));\n\n # Add box layout, add table to box layout and add box layout and button to widget\n self.nw.layout = QVBoxLayout();\n self.nw.layout.addWidget(self.tableWidget);\n self.nw.layout.addWidget(self.button);\n self.nw.setLayout(self.nw.layout);\n\n #Link button to function\n self.button.clicked.connect(closeHistory);\n\n # Show widget\n self.nw.show();\n\n######################################################################################################################################################################################\n#Method to create a new group\ndef createGroup(name):\n global object_count, current_group, file;\n #Creating new group object\n new_Group = group(name);\n #Add group object to the lists\n group_list.append(new_Group);\n #Get appropriate file name for the group\n file = \"./reports/\"+name+\".csv\";\n #Add group object and data file into a dictionary for storage\n record[object_count] = new_Group;\n #Update object_counter\n object_count += 1;\n #Create a fresh csv file for the group\n columns = ['Timestamp', 'Description'];\n df = pd.DataFrame(columns=columns);\n df.to_csv(file, index=False);\n #Load the new group as current group\n current_group = new_Group;\n #Set current group name in display text\n window.groupName.setText(current_group.name.upper());\n window.displayText.setText(\"\");\n\n#Method to carryout object loading functionality\ndef initilize_data():\n global group_list, current_group, record, object_count, file, currency, color;\n #Condition check for file existence\n if(os.path.exists('./data/record.pkl')):\n #Read the pickle file\n with open('./data/record.pkl', 'rb') as infile:\n #Try-catch block to handle empty file errors\n try:\n loaded_data = pickle.load(infile);\n except EOFError:\n return;\n #Condition check to handle empty record dictionary\n if bool(loaded_data):\n #Load all data to current session\n group_list = [val for (key,val) in loaded_data.items()];\n record = loaded_data;\n object_count = len(record.keys());\n\n #Condition check for file existence\n if(os.path.exists('./data/settings.pkl')):\n #Read the pickle file\n with open('./data/settings.pkl', 'rb') as infile:\n #Try-catch block to handle empty file errors\n try:\n loaded_data = pickle.load(infile);\n except EOFError:\n return;\n #Condition check to handle empty record dictionary\n if bool(loaded_data):\n currency = loaded_data['currency'];\n current_group = loaded_data['current_group'];\n color = loaded_data['color'];\n if (current_group != None):\n file = \"./reports/\"+current_group.name+\".csv\"; \n\n#Method to change group context\ndef changeGroup():\n #Get group name from the GUI\n name = window.nw.cb.currentText().lower();\n global current_group, file, group_list;\n #Change group context\n for obj in group_list:\n if (obj.name == name):\n #Load the respective object\n current_group = obj;\n #Load the working csv file\n file = \"./reports/\"+name+\".csv\"; \n break;\n \n #Close the CDGwindow post operation\n window.nw.close();\n del(window.nw);\n #Set display elements in the GUI\n window.groupName.setText(current_group.name.upper());\n window.disclaimer.setText(\"Group changed to \"+current_group.name);\n #Call Summary to update the info\n window.displaySummary();\n\n#Method to delete a group\ndef delGroup():\n global current_group, file, group_list, record, object_count;\n #Get group name from the GUI\n name = window.nw.cb.currentText().lower();\n #Delete group confirmation message box\n reply = QMessageBox.question(window, 'Delete Group', 'Are You Sure to Delete the group?', QMessageBox.No | QMessageBox.Yes);\n if reply == QMessageBox.Yes:\n #Deleting the group and respective data\n for obj in group_list:\n if (obj.name == name):\n #Remove object from the list\n deleted_obj = group_list.pop(group_list.index(obj));\n #Update the record dictionary\n record = {key: value for key, value in record.items() if value is not deleted_obj};\n #Re-assign appropriate key values\n object_count = 0;\n keys = list(record.keys());\n for i in range(len(keys)):\n record[object_count] = record.pop(keys[i]);\n object_count += 1;\n #Delete the group object and csv file\n os.remove(\"./reports/\"+name+\".csv\");\n del(deleted_obj);\n #Disclaimer if group is empty after deletion\n if (SM.isGroupListEmpty(group_list) == True):\n current_group = None;\n else: \n #Change active group\n current_group = group_list[0];\n file = \"./reports/\"+current_group.name+\".csv\"; \n #current_group.summary();\n break;\n #Close CDG window\n del(window.nw);\n #Set display element in GUI post deletion\n window.disclaimer.setText(\"Group \"+name+ \" deleted\");\n if(current_group != None):\n window.groupName.setText(current_group.name.upper());\n #Call Summary to update the info\n window.displaySummary();\n else:\n window.groupName.setText(\"\");\n window.displayText.setText(\"\");\n\n#Method to settle up\ndef settleUp():\n global settle_data;\n #Collect indices of payments made\n to_rem = [];\n #Add individual payments to settle all\n for line in window.settle_lines:\n #Add payments to only selected choices\n if (line.isChecked() == True):\n #Get the selected line\n selected_line = settle_data[window.settle_lines.index(line)];\n #Payment API call\n current_group.addPayment(selected_line['From'], selected_line['To'], selected_line['amount']);\n #Track the index to remove later\n to_rem.append(window.settle_lines.index(line));\n #Update the disclaimer text\n window.disclaimer.setText(\"Payment from \"+selected_line['From']+\" To \"+selected_line['To']+\" successful.\");\n #Remove the data after the accounts ahve been settled\n for i in range(len(to_rem)-1,-1,-1):\n del settle_data[to_rem[i]];\n del window.settle_lines[to_rem[i]];\n #Call Summary to update the info\n window.displaySummary();\n #Delete the new window\n del(window.nw);\n\n#Method to open color Dialog\ndef openColorDialog():\n global color;\n #Get the selected color\n color = (QColorDialog.getColor()).name();\n\n#Method to apply the settings\ndef applySettings():\n global currency, color;\n #Check if any group is selected\n if (current_group != None):\n #Get the amount debit/credit for each member\n amt_data = list(current_group.summary().values());\n #Check if all accounts are settled\n if (SM.duesSettled(amt_data) == True):\n #Get selected currency\n currency = window.nw.currencyBox.currentText();\n window.displaySummary();\n else:\n window.disclaimer.setText(\"Currency cannot be changed\");\n\n #Apply the color theme\n window.setStyleSheet(\"QMainWindow {background: \"+color+\";}\");\n window.disclaimer.setText(\"Settings Applied\");\n #Close and delete the window\n del(window.nw);\n\n######################################################################################################################################################################################\n#Main function\nif __name__ == '__main__':\n \"\"\"Global declarations\"\"\"\n #Dictionary to hold objects to be saved\n record = {};\n object_count = 0;\n #Group instances monitoring lists\n group_list = [];\n #Active group\n current_group = None;\n currency = \"\";\n color = \"#F0F0F0\";\n #Settle data list\n settle_data = [];\n #global object_count, current_group, group_list, group_name_list;\n initilize_data();\n \n #Start GUI\n app = QApplication(sys.argv);\n window = mainWindow();\n #Apply color to the GUI\n window.setStyleSheet(\"QMainWindow {background: \"+color+\";}\");\n #Display GUI\n window.show();\n #Call summary to initiate display\n if (current_group != None):\n window.displaySummary();\n sys.exit(app.exec_());", "repo_name": "sourabh061295/Splitter", "sub_path": "src/splitter_gui.py", "file_name": "splitter_gui.py", "file_ext": "py", "file_size_in_byte": 37567, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "PyQt5.uic.loadUi", "line_number": 19, "usage_type": "call"}, {"api_name": "PyQt5.uic.loadUi", "line_number": 27, "usage_type": "call"}, {"api_name": "PyQt5.uic.loadUi", "line_number": 35, "usage_type": "call"}, {"api_name": "PyQt5.uic.loadUi", "line_number": 43, "usage_type": "call"}, {"api_name": "PyQt5.uic.loadUi", "line_number": 50, "usage_type": "call"}, {"api_name": "PyQt5.uic.loadUi", "line_number": 59, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 90, "usage_type": "call"}, {"api_name": "pickle.HIGHEST_PROTOCOL", "line_number": 90, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 99, "usage_type": "call"}, {"api_name": "pickle.HIGHEST_PROTOCOL", "line_number": 99, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.close", "line_number": 101, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 101, "usage_type": "name"}, {"api_name": "splitter_module.isGroupPresent", "line_number": 118, "usage_type": "call"}, {"api_name": "splitter_module.isGroupListEmpty", "line_number": 130, "usage_type": "call"}, {"api_name": "splitter_module.isGroupListEmpty", "line_number": 151, "usage_type": "call"}, {"api_name": "splitter_module.isMemberPresent", "line_number": 162, "usage_type": "call"}, {"api_name": "splitter_module.isAmountValid", "line_number": 181, "usage_type": "call"}, {"api_name": "splitter_module.isAmountValid", "line_number": 312, "usage_type": "call"}, {"api_name": "splitter_module.isAmountValid", "line_number": 328, "usage_type": "call"}, {"api_name": "splitter_module.isGroupListEmpty", "line_number": 346, "usage_type": "call"}, {"api_name": "splitter_module.isMemberListEmpty", "line_number": 349, "usage_type": "call"}, {"api_name": "splitter_module.isMemberPresent", "line_number": 379, "usage_type": "call"}, {"api_name": "splitter_module.isMemberPresent", "line_number": 386, "usage_type": "call"}, {"api_name": "splitter_module.isAmountValid", "line_number": 393, "usage_type": "call"}, {"api_name": "splitter_module.isGroupListEmpty", "line_number": 417, "usage_type": "call"}, {"api_name": "splitter_module.isMemberListEmpty", "line_number": 420, "usage_type": "call"}, {"api_name": "splitter_module.isGroupListEmpty", "line_number": 453, "usage_type": "call"}, {"api_name": "splitter_module.isMemberListEmpty", "line_number": 456, "usage_type": "call"}, {"api_name": "splitter_module.isGroupListEmpty", "line_number": 490, "usage_type": "call"}, {"api_name": "splitter_module.getCsvFile", "line_number": 495, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 502, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 502, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 504, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 504, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.pie", "line_number": 509, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 509, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 512, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 512, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 514, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 514, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 515, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 515, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 516, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 516, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 518, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 519, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 519, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 522, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 522, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 525, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 525, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 527, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 527, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 528, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 528, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 529, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 529, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 534, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 535, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 535, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 546, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 546, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 555, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 555, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 559, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 559, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 562, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 562, "usage_type": "name"}, {"api_name": "splitter_module.isGroupListEmpty", "line_number": 585, "usage_type": "call"}, {"api_name": "splitter_module.getCsvFile", "line_number": 599, "usage_type": "call"}, {"api_name": "splitter_module.group", "line_number": 659, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 670, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 682, "usage_type": "call"}, {"api_name": "os.path", "line_number": 682, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 687, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 698, "usage_type": "call"}, {"api_name": "os.path", "line_number": 698, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 703, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 759, "usage_type": "call"}, {"api_name": "splitter_module.isGroupListEmpty", "line_number": 762, "usage_type": "call"}, {"api_name": "splitter_module.duesSettled", "line_number": 822, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 854, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 863, "usage_type": "call"}]} +{"seq_id": "73157270142", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Nov 8 18:09:39 2020\r\n\r\n@author: NISHANT\r\n\"\"\"\r\n\r\n\r\n#Face Detection using haarcascade file \r\nimport cv2\r\nimport numpy\r\nface=cv2.CascadeClassifier(\"Data\\\\cascades\\\\haarcascade_frontalface_default.xml\") #for detecting face\r\neye = cv2.CascadeClassifier('Data\\\\cascades\\\\haarcascade_eye.xml') #for detecting eyes\r\n\r\nimage=cv2.imread(\"Data\\\\a.jpg\")\r\ngray= cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) #convert into gray \r\n\r\n#parameters(img,scale_factor[reduce image size],min_neighbour)\r\nfaces = face.detectMultiScale(gray,4,4) #for faces\r\n\r\nfor(x,y,w,h) in faces:\r\n \r\n image=cv2.rectangle(image,(x,y),(x+w,y+h),(127,0,205),3)\r\n \r\n #Now detect eyes\r\n roi_gray = gray[y:y+h, x:x+w]\r\n roi_color = image[y:y+h, x:x+w]\r\n eyes = eye.detectMultiScale(roi_gray,1.2,1)\r\n for (ex,ey,ew,eh) in eyes:\r\n cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(255,0,0),2)\r\n \r\nimage = cv2.resize(image,(800,700))\r\ncv2.imshow(\"Face Detected\",image)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows() \r\n", "repo_name": "askitlouder/Image-Processing-Tutorials", "sub_path": "43 - Face and Eyes Detection using Image.py", "file_name": "43 - Face and Eyes Detection using Image.py", "file_ext": "py", "file_size_in_byte": 1042, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 42, "dataset": "github-code", "pt": "24", "api": [{"api_name": "cv2.CascadeClassifier", "line_number": 12, "usage_type": "call"}, {"api_name": "cv2.CascadeClassifier", "line_number": 13, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 15, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 16, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 16, "usage_type": "attribute"}, {"api_name": "cv2.rectangle", "line_number": 23, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 30, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 32, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 34, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 35, "usage_type": "call"}]} +{"seq_id": "4362104436", "text": "from os.path import basename, isdir, isfile\nfrom pathlib import Path\nfrom shutil import copy2, copytree\n\nfrom util.build_info import BuildInfo\nfrom util.config import get_config_value, get_list_from_config_yaml\nfrom util.logger import LOGGER\n\n\ndef extract_single_worded_key(dictionary, key):\n \"\"\" verify that key is in dictionary and its value is a single word \"\"\"\n if key in dictionary:\n value = dictionary[key]\n if len(value.split()) == 1:\n return value\n raise RuntimeError('\\'{}\\' of injected file must be a single word, but got {}: \\'{}\\''\n .format(key, len(value.split()), value))\n\n raise RuntimeError('\\'{}\\' is not specified for injected file \\'{}\\' !'\n .format(key, dictionary))\n\n\ndef read_injected_files(overall_dest_dir):\n \"\"\"\n Copy file that need to be injected to temporary location,\n which will be accessible during post-install.\n One mandatory argument: a path to initrd directory that will be available during post_install\n \"\"\"\n artifacts_dir = get_config_value(\"ARTIFACTS_DIR\")\n\n # location used by post-install, should be created only if there are files to inject\n injected_files = 'etc/injected_files' # location used by post-install\n overall_dest_dir = overall_dest_dir + '/' + injected_files\n LOGGER.info('temporary location for injected files: %s', overall_dest_dir)\n\n # include user-specified files\n files_to_inject = get_list_from_config_yaml('UPDATE_IMAGE_FILES')\n\n # include information about installed software on the build machine\n build_info_file_name = \"build_info.json\"\n build_info_source = artifacts_dir + \"/\" + build_info_file_name\n build_info_destination = \"/\" + build_info_file_name\n files_to_inject.append({'source': build_info_source, 'destination': build_info_destination})\n build_info = BuildInfo()\n build_info.to_file(build_info_source)\n\n # each injected file directory to be stored in a separate directory \"file\"\n count = 0\n LOGGER.trace(\"files_to_inject: %s\", files_to_inject)\n for file in files_to_inject:\n LOGGER.trace(\"file: %s\", file)\n src = extract_single_worded_key(file, 'source')\n dest = extract_single_worded_key(file, 'destination')\n LOGGER.info('inject %s to temporary location %s', src, dest)\n\n file_holder = overall_dest_dir + '/file' + str(count) + '/'\n # copy source to \"src\"\n # source file name does not need to be preserved;\n # it will be copied to destination path on BIG-IP\n source_holder = file_holder + 'src'\n if isfile(src):\n Path(file_holder).mkdir(parents=True, exist_ok=True)\n copy2(src, source_holder)\n elif isdir(src):\n copytree(src, source_holder)\n else:\n raise RuntimeError('\\'{}\\' is neither a file nor a directory, cannot inject it!'\n .format(src))\n\n # store destination\n if dest[0] != '/':\n raise RuntimeError('injected file destination \\'{}\\' must be an absolute path!'\n .format(dest))\n with open(file_holder + 'dest', 'w') as dest_holder:\n print(\"{}\".format(dest), file=dest_holder)\n\n count += 1\n # end of for loop\n\n LOGGER.debug('leaving %s', basename(__file__))\n return 0\n", "repo_name": "perbonielsen/f5-bigip-image-generator", "sub_path": "src/lib/python/util/injected_files.py", "file_name": "injected_files.py", "file_ext": "py", "file_size_in_byte": 3366, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "24", "api": [{"api_name": "util.config.get_config_value", "line_number": 29, "usage_type": "call"}, {"api_name": "util.logger.LOGGER.info", "line_number": 34, "usage_type": "call"}, {"api_name": "util.logger.LOGGER", "line_number": 34, "usage_type": "name"}, {"api_name": "util.config.get_list_from_config_yaml", "line_number": 37, "usage_type": "call"}, {"api_name": "util.build_info.BuildInfo", "line_number": 44, "usage_type": "call"}, {"api_name": "util.logger.LOGGER.trace", "line_number": 49, "usage_type": "call"}, {"api_name": "util.logger.LOGGER", "line_number": 49, "usage_type": "name"}, {"api_name": "util.logger.LOGGER.trace", "line_number": 51, "usage_type": "call"}, {"api_name": "util.logger.LOGGER", "line_number": 51, "usage_type": "name"}, {"api_name": "util.logger.LOGGER.info", "line_number": 54, "usage_type": "call"}, {"api_name": "util.logger.LOGGER", "line_number": 54, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 61, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 62, "usage_type": "call"}, {"api_name": "shutil.copy2", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 64, "usage_type": "call"}, {"api_name": "shutil.copytree", "line_number": 65, "usage_type": "call"}, {"api_name": "util.logger.LOGGER.debug", "line_number": 80, "usage_type": "call"}, {"api_name": "util.logger.LOGGER", "line_number": 80, "usage_type": "name"}, {"api_name": "os.path.basename", "line_number": 80, "usage_type": "call"}]} +{"seq_id": "72396044543", "text": "import logging\nimport os\nimport sys\nimport json\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\nimport datasets\nimport nltk # Here to have a nice missing dependency error message early on\nimport numpy as np\nfrom datasets import load_dataset\n\nimport transformers\nfrom filelock import FileLock\nfrom transformers import (\n AutoConfig,\n AutoModelForSeq2SeqLM,\n AutoModelForCausalLM, # add\n AutoTokenizer,\n HfArgumentParser,\n Seq2SeqTrainingArguments,\n set_seed, )\nfrom transformers.file_utils import is_offline_mode\nfrom transformers.trainer_utils import get_last_checkpoint\n\nfrom model.bloom import BloomForCausalLM_WithLoss\nfrom model.codegen import CodeGenForCausalLM_WithLoss\nfrom model.gpt_neox import GPTNeoXForCausalLM_WithLoss\n\nfrom uie_collator import DataCollatorForUIE\nfrom uie_dataset import gen_cache_path\n\nfrom uie_trainer import UIETrainer, DenserEvalCallback, skip_instructions\nfrom compute_metrics import compute_metrics, compute_grouped_metrics\n\n# off wandb\nos.environ['WANDB_DISABLED'] = \"True\"\n# os.environ['CUDA_VISIBLE_DEVICES'] = '0'\nlogger = logging.getLogger(__name__)\nCURRENT_DIR = os.path.dirname(__file__)\n\ntry:\n nltk.data.find(\"tokenizers/punkt\")\nexcept (LookupError, OSError):\n if is_offline_mode():\n raise LookupError(\n \"Offline mode: run this script without TRANSFORMERS_OFFLINE first to download nltk data files\"\n )\n with FileLock(\".lock\") as lock:\n nltk.download(\"punkt\", quiet=True)\n\n\n@dataclass\nclass ModelArguments:\n \"\"\"\n Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.\n \"\"\"\n\n model_name_or_path: str = field(\n metadata={\"help\": \"Path to pretrained model or model identifier from huggingface.co/models\"}\n )\n config_name: Optional[str] = field(\n default=None, metadata={\"help\": \"Pretrained config name or path if not the same as model_name\"}\n )\n tokenizer_name: Optional[str] = field(\n default=None, metadata={\"help\": \"Pretrained tokenizer name or path if not the same as model_name\"}\n )\n cache_dir: Optional[str] = field(\n default=None,\n metadata={\"help\": \"Where to store the pretrained models downloaded from huggingface.co\"},\n )\n use_fast_tokenizer: bool = field(\n default=True,\n metadata={\"help\": \"Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.\"},\n )\n model_revision: str = field(\n default=\"main\",\n metadata={\"help\": \"The specific model version to use (can be a branch name, tag name or commit id).\"},\n )\n use_auth_token: bool = field(\n default=False,\n metadata={\n \"help\": \"Will use the token generated when running `transformers-cli login` (necessary to use this script \"\n \"with private models).\"\n },\n )\n resize_position_embeddings: Optional[bool] = field(\n default=None,\n metadata={\n \"help\": \"Whether to automatically resize the position embeddings if `max_source_length` exceeds \"\n \"the model's position embeddings.\"\n },\n )\n\n\n@dataclass\nclass DataTrainingArguments:\n \"\"\"\n Arguments pertaining to what data we are going to input our model for training and eval.\n \"\"\"\n lang: str = field(default=None, metadata={\"help\": \"Language id for multilingual model.\"})\n data_dir: str = field(\n default=None, metadata={\"help\": \"The directory for saving the UIE train/dev/test splits.\"}\n )\n task_config_dir: str = field(\n default=None, metadata={\"help\": \"The json file for config training and testing tasks\"}\n )\n instruction_file: str = field(\n default=None, metadata={\"help\": \"The instruction file for different tasks.\"}\n )\n instruction_strategy: Optional[str] = field(\n default='single', metadata={\n \"help\": \"How many different instructions to use? Support 'single' and 'multiple' mode.\"\n }\n )\n overwrite_cache: bool = field(\n default=False, metadata={\"help\": \"Overwrite the cached training and evaluation sets\"}\n )\n input_record_file: str = field(\n default=None, metadata={\"help\": \"file to record model input\"}\n )\n preprocessing_num_workers: Optional[int] = field(\n default=None,\n metadata={\"help\": \"The number of processes to use for the preprocessing.\"},\n )\n max_source_length: Optional[int] = field(\n default=512,\n metadata={\n \"help\": \"The maximum total input sequence length after tokenization. Sequences longer \"\n \"than this will be truncated, sequences shorter will be padded.\"\n },\n )\n # for decoder model, it means max_new_tokens\n max_target_length: Optional[int] = field(\n default=50,\n metadata={\n \"help\": \"The maximum total sequence length for target text after tokenization. Sequences longer \"\n \"than this will be truncated, sequences shorter will be padded.\"\n },\n )\n repetition_penalty: Optional[float] = field(\n default=1.0,\n metadata={\n \"help\": \"Penalty for repeat tokens in decode stage.\"\n },\n )\n num_beams: Optional[int] = field(\n default=1,\n metadata={\n \"help\": \"Number of beams to use for evaluation. This argument will be passed to ``model.generate``, \"\n \"which is used during ``evaluate`` and ``predict``.\"\n },\n )\n max_num_instances_per_task: int = field(\n default=10000, metadata={\"help\": \"The maximum number of instances we will consider for each training task.\"}\n )\n max_num_instances_per_eval_task: int = field(\n default=200,\n metadata={\"help\": \"The maximum number of instances we will consider for each validation/test task.\"}\n )\n max_train_samples: Optional[int] = field(\n default=None,\n metadata={\n \"help\": \"For debugging purposes or quicker training, truncate the number of training examples to this \"\n \"value if set.\"\n },\n )\n max_eval_samples: Optional[int] = field(\n default=None,\n metadata={\n \"help\": \"For debugging purposes or quicker training, truncate the number of evaluation examples to this \"\n \"value if set.\"\n },\n )\n max_predict_samples: Optional[int] = field(\n default=None,\n metadata={\n \"help\": \"For debugging purposes or quicker training, truncate the number of prediction examples to this \"\n \"value if set.\"\n },\n )\n num_examples: Optional[int] = field(\n default=0,\n metadata={\"help\": \"number of in-context positive examples.\"}\n )\n ignore_pad_token_for_loss: bool = field(\n default=True,\n metadata={\n \"help\": \"Whether to ignore the tokens corresponding to padded labels in the loss computation or not.\"\n },\n )\n add_task_name: Optional[bool] = field(\n default=False,\n metadata={\"help\": \"whether to preappend task name before the task input.\"}\n )\n add_dataset_name: Optional[bool] = field(\n default=False,\n metadata={\"help\": \"whether to preappend dataset name before the task input.\"}\n )\n common_dataset_name: Optional[str] = field(\n default=None,\n metadata={\"help\": \"common dataset name for zero shot.\"}\n )\n over_sampling: Optional[str] = field(\n default=False,\n metadata={\"help\": \"Whether to over sampling the dataset to max_num_instances_per_task\"}\n )\n\n\n@dataclass\nclass UIETrainingArguments(Seq2SeqTrainingArguments):\n gradient_checkpointing: Optional[bool] = field(\n default=False,\n metadata={\"help\": \"Whether to use computing time to gain more memory\"}\n )\n denser_evaluation: Optional[bool] = field(\n default=False,\n metadata={\"help\": \"If specifid, the model will do more evaluation at the beginning of training.\"}\n )\n do_demo: bool = field(default=False, metadata={\"help\": \"Whether to run the model as a demo in the terminal.\"})\n\n\ndef main():\n # See all possible arguments in src/transformers/training_args.py\n # or by passing the --help flag to this script.\n # We now keep distinct sets of args, for a cleaner separation of concerns.\n\n parser = HfArgumentParser((ModelArguments, DataTrainingArguments, UIETrainingArguments))\n if len(sys.argv) == 2 and sys.argv[1].endswith(\".json\"):\n # If we pass only one argument to the script and it's the path to a json file,\n # let's parse it to get our arguments.\n model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))\n else:\n model_args, data_args, training_args = parser.parse_args_into_dataclasses()\n\n # Setup logging\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt=\"%m/%d/%Y %H:%M:%S\",\n handlers=[logging.StreamHandler(sys.stdout)],\n )\n log_level = training_args.get_process_log_level()\n logger.setLevel(log_level)\n datasets.utils.logging.set_verbosity(log_level)\n transformers.utils.logging.set_verbosity(log_level)\n transformers.utils.logging.enable_default_handler()\n transformers.utils.logging.enable_explicit_format()\n\n # Log on each process the small summary:\n logger.warning(\n f\"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}\"\n + f\"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}\"\n )\n logger.info(f\"Training/evaluation parameters {training_args}\")\n\n # Detecting last checkpoint.\n last_checkpoint = None\n if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:\n last_checkpoint = get_last_checkpoint(training_args.output_dir)\n if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:\n raise ValueError(\n f\"Output directory ({training_args.output_dir}) already exists and is not empty. \"\n \"Use --overwrite_output_dir to overcome.\"\n )\n elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:\n logger.info(\n f\"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change \"\n \"the `--output_dir` or add `--overwrite_output_dir` to train from scratch.\"\n )\n\n # Set seed before initializing model.\n set_seed(training_args.seed)\n data_cache_dir = gen_cache_path(training_args.output_dir, data_args)\n\n # Get the UIE dataset\n raw_datasets = load_dataset(\n os.path.join(CURRENT_DIR, \"uie_dataset.py\"),\n data_dir=data_args.data_dir,\n task_config_dir=data_args.task_config_dir,\n instruction_file=data_args.instruction_file,\n instruction_strategy=data_args.instruction_strategy,\n cache_dir=data_cache_dir, # for debug, change dataset size, otherwise open it\n max_num_instances_per_task=data_args.max_num_instances_per_task,\n max_num_instances_per_eval_task=data_args.max_num_instances_per_eval_task,\n num_examples=data_args.num_examples,\n over_sampling=data_args.over_sampling\n )\n raw_datasets.cleanup_cache_files()\n\n # Load pretrained model and tokenizer\n #\n # Distributed training:\n # The .from_pretrained methods guarantee that only one local process can concurrently\n # download model & vocab.\n config = AutoConfig.from_pretrained(\n model_args.config_name if model_args.config_name else model_args.model_name_or_path,\n cache_dir=model_args.cache_dir,\n revision=model_args.model_revision,\n use_auth_token=True if model_args.use_auth_token else None,\n )\n tokenizer = AutoTokenizer.from_pretrained(\n model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,\n cache_dir=model_args.cache_dir,\n use_fast=model_args.use_fast_tokenizer,\n revision=model_args.model_revision,\n use_auth_token=True if model_args.use_auth_token else None,\n )\n\n if 'bloom' in model_args.model_name_or_path.lower():\n model_class = BloomForCausalLM_WithLoss\n if tokenizer.pad_token is None:\n tokenizer.pad_token = tokenizer.eos_token\n tokenizer.padding_side = 'left'\n elif 'codegen' in model_args.model_name_or_path.lower():\n model_class = CodeGenForCausalLM_WithLoss\n tokenizer.pad_token = tokenizer.eos_token\n tokenizer.padding_side = 'left'\n\n elif 'neox' in model_args.model_name_or_path.lower(): # add neox\n model_class = GPTNeoXForCausalLM_WithLoss\n if tokenizer.pad_token is None:\n tokenizer.pad_token = tokenizer.eos_token\n tokenizer.padding_side = 'left'\n else:\n model_class = AutoModelForSeq2SeqLM\n model = model_class.from_pretrained(\n model_args.model_name_or_path,\n from_tf=bool(\".ckpt\" in model_args.model_name_or_path),\n config=config,\n cache_dir=model_args.cache_dir,\n revision=model_args.model_revision,\n use_auth_token=True if model_args.use_auth_token else None,\n )\n model.resize_token_embeddings(len(tokenizer))\n\n if (\n hasattr(model.config, \"max_position_embeddings\")\n and model.config.max_position_embeddings < data_args.max_source_length\n ):\n if model_args.resize_position_embeddings is None:\n logger.warning(\n f\"Increasing the model's number of position embedding vectors from {model.config.max_position_embeddings} \"\n f\"to {data_args.max_source_length}.\"\n )\n model.resize_position_embeddings(data_args.max_source_length)\n elif model_args.resize_position_embeddings:\n model.resize_position_embeddings(data_args.max_source_length)\n else:\n raise ValueError(\n f\"`--max_source_length` is set to {data_args.max_source_length}, but the model only has {model.config.max_position_embeddings}\"\n f\" position encodings. Consider either reducing `--max_source_length` to {model.config.max_position_embeddings} or to automatically \"\n \"resize the model's position encodings by passing `--resize_position_embeddings`.\"\n )\n\n if training_args.label_smoothing_factor > 0 and not hasattr(model, \"prepare_decoder_input_ids_from_labels\"):\n logger.warning(\n \"label_smoothing is enabled but the `prepare_decoder_input_ids_from_labels` method is not defined for\"\n f\"`{model.__class__.__name__}`. This will lead to loss being calculated twice and will take up more memory\"\n )\n\n if training_args.do_train:\n if \"train\" not in raw_datasets:\n raise ValueError(\"--do_train requires a train dataset\")\n train_dataset = raw_datasets[\"train\"]\n if data_args.max_train_samples is not None:\n train_dataset = train_dataset.select(range(data_args.max_train_samples))\n\n if training_args.do_eval:\n if \"validation\" not in raw_datasets:\n raise ValueError(\"--do_eval requires a validation dataset\")\n eval_dataset = raw_datasets[\"validation\"]\n if data_args.max_eval_samples is not None:\n eval_dataset = eval_dataset.select(range(data_args.max_eval_samples))\n\n if training_args.do_predict:\n if \"test\" not in raw_datasets:\n raise ValueError(\"--do_predict requires a test dataset\")\n predict_dataset = raw_datasets[\"test\"]\n if data_args.max_predict_samples is not None:\n predict_dataset = predict_dataset.select(range(data_args.max_predict_samples))\n\n # Data collator\n label_pad_token_id = -100 if data_args.ignore_pad_token_for_loss else tokenizer.pad_token_id\n data_collator = DataCollatorForUIE(\n tokenizer,\n model=model,\n padding=\"longest\",\n max_source_length=data_args.max_source_length,\n max_target_length=data_args.max_target_length,\n label_pad_token_id=label_pad_token_id,\n pad_to_multiple_of=8 if training_args.fp16 else None,\n add_task_name=data_args.add_task_name,\n add_dataset_name=data_args.add_dataset_name,\n common_dataset_name=data_args.common_dataset_name,\n num_examples=data_args.num_examples,\n input_record_file=data_args.input_record_file\n )\n # we don't want to remove unused columns because we will prepare each batch during training,\n # and some of the information will also be used in evaluation.\n training_args.remove_unused_columns = False\n\n # Metric\n def compute_rouge_metrics(dataset, preds, save_prefix=None):\n decoded_preds = skip_instructions(model, preds, tokenizer)\n references = [e[\"Instance\"][\"label\"] for e in dataset]\n result = compute_metrics(predictions=decoded_preds, references=references)\n result_per_task = compute_grouped_metrics(predictions=decoded_preds, references=references,\n groups=dataset[\"Task\"])\n result.update(result_per_task)\n categories = dataset[\"Dataset\"]\n result_per_category = compute_grouped_metrics(predictions=decoded_preds, references=references,\n groups=categories)\n result.update(result_per_category)\n prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds]\n result[\"gen_len\"] = np.mean(prediction_lens)\n result = {k: round(v, 4) for k, v in result.items()}\n if save_prefix is not None:\n with open(os.path.join(training_args.output_dir, f\"{save_prefix}_eval_predictions.jsonl\"), \"w\") as fout:\n for example, pred in zip(dataset, decoded_preds):\n fout.write(json.dumps({\n \"Task\": example[\"Task\"],\n \"Dataset\": example[\"Dataset\"],\n \"Instance\": example[\"Instance\"],\n \"Prediction\": pred\n }) + \"\\n\")\n return result\n\n print(f\"-----Gradient checkpointing: {training_args.gradient_checkpointing} -----\")\n if training_args.gradient_checkpointing:\n model.gradient_checkpointing_enable()\n\n trainer = UIETrainer(\n model=model,\n args=training_args,\n train_dataset=train_dataset if training_args.do_train else None,\n eval_dataset=eval_dataset if training_args.do_eval else None,\n tokenizer=tokenizer,\n data_collator=data_collator,\n compute_metrics=compute_rouge_metrics,\n callbacks=[DenserEvalCallback] if training_args.denser_evaluation else None\n )\n\n all_metrics = {\"run_name\": training_args.run_name}\n\n # Training\n # 训练epoch数,按照 num_train_epochs 传入,在trainer中解析\n # TODO, train debug, bloomz, flan-t5\n if training_args.do_train:\n checkpoint = None\n if training_args.resume_from_checkpoint is not None:\n checkpoint = training_args.resume_from_checkpoint\n elif last_checkpoint is not None:\n checkpoint = last_checkpoint\n train_result = trainer.train(resume_from_checkpoint=checkpoint)\n trainer.save_model() # Saves the tokenizer too for easy upload\n\n metrics = train_result.metrics\n max_train_samples = (\n data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)\n )\n metrics[\"train_samples\"] = min(max_train_samples, len(train_dataset))\n\n trainer.log_metrics(\"train\", metrics)\n trainer.save_metrics(\"train\", metrics)\n trainer.save_state()\n logger.info(f\"Metrics {metrics}\")\n all_metrics.update(metrics)\n\n # Evaluation\n results = {}\n # in case the batch is shorter than max length, the output should be padded\n max_new_tokens = (\n training_args.generation_max_length\n if training_args.generation_max_length is not None\n else data_args.max_target_length\n )\n\n num_beams = data_args.num_beams if data_args.num_beams is not None else training_args.generation_num_beams\n repetition_penalty = data_args.repetition_penalty\n\n if training_args.do_predict:\n logger.info(\"*** Prediction ***\")\n logger.info(\"*** Loading CheckPoint ***\")\n checkpoint = None\n if os.path.isdir(training_args.output_dir):\n checkpoint = get_last_checkpoint(training_args.output_dir)\n if training_args.resume_from_checkpoint is not None:\n checkpoint = training_args.resume_from_checkpoint\n # without last ckpt and resume ckpt, would predict with current model\n if checkpoint:\n model = model_class.from_pretrained(checkpoint)\n trainer = UIETrainer(\n model=model,\n args=training_args,\n train_dataset=train_dataset if training_args.do_train else None,\n eval_dataset=eval_dataset if training_args.do_eval else None,\n tokenizer=tokenizer,\n data_collator=data_collator,\n compute_metrics=compute_rouge_metrics,\n callbacks=[DenserEvalCallback] if training_args.denser_evaluation else None\n )\n\n if data_args.max_predict_samples is not None:\n predict_dataset = predict_dataset.select(range(data_args.max_predict_samples))\n\n predict_results = trainer.predict(\n predict_dataset,\n metric_key_prefix=\"predict\",\n max_new_tokens=max_new_tokens,\n num_beams=num_beams,\n repetition_penalty=repetition_penalty,\n pad_token_id=tokenizer.pad_token_id\n )\n metrics = predict_results.metrics\n max_predict_samples = (\n data_args.max_predict_samples if data_args.max_predict_samples is not None else len(predict_dataset)\n )\n metrics[\"predict_samples\"] = min(max_predict_samples, len(predict_dataset))\n\n trainer.log(metrics)\n trainer.log_metrics(\"predict\", metrics)\n trainer.save_metrics(\"predict\", metrics)\n all_metrics.update(metrics)\n\n if training_args.do_demo:\n logger.info(\"Serving the model as a demo...\")\n user_input = ''\n while True:\n user_input = input(\"Please enter your input to the model, or enter 'quit' to exit: \")\n if user_input.lower() == \"quit\":\n break\n inputs = tokenizer([user_input], return_tensors=\"pt\")\n _, preds, _ = trainer.prediction_step(model, inputs=inputs, prediction_loss_only=False)\n print(f\"Model generates: {tokenizer.decode(preds[0], skip_special_tokens=True)}\\n\\n\")\n\n return results\n\n\nif __name__ == \"__main__\":\n main()", "repo_name": "BeyonderXX/InstructUIE", "sub_path": "src/run_uie.py", "file_name": "run_uie.py", "file_ext": "py", "file_size_in_byte": 22942, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 253, "dataset": "github-code", "pt": "24", "api": [{"api_name": "os.environ", "line_number": 37, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "nltk.data.find", "line_number": 43, "usage_type": "call"}, {"api_name": "nltk.data", "line_number": 43, "usage_type": "attribute"}, {"api_name": "transformers.file_utils.is_offline_mode", "line_number": 45, "usage_type": "call"}, {"api_name": "filelock.FileLock", "line_number": 49, "usage_type": "call"}, {"api_name": "nltk.download", "line_number": 50, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 59, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 62, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 62, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 65, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 65, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 68, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 68, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 72, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 76, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 80, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 87, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 87, "usage_type": "call"}, {"api_name": "dataclasses.dataclass", "line_number": 53, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 101, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 102, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 105, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 108, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 111, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 111, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 116, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 119, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 122, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 122, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 126, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 126, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 134, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 134, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 141, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 141, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 147, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 147, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 154, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 157, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 161, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 161, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 168, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 168, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 175, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 175, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 182, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 182, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 186, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 192, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 192, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 196, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 196, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 200, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 200, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 204, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 204, "usage_type": "call"}, {"api_name": "dataclasses.dataclass", "line_number": 96, "usage_type": "name"}, {"api_name": "transformers.Seq2SeqTrainingArguments", "line_number": 211, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 212, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 212, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 216, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 216, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 220, "usage_type": "call"}, {"api_name": "dataclasses.dataclass", "line_number": 210, "usage_type": "name"}, {"api_name": "transformers.HfArgumentParser", "line_number": 228, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 229, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 232, "usage_type": "call"}, {"api_name": "os.path", "line_number": 232, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 232, "usage_type": "attribute"}, {"api_name": "logging.basicConfig", "line_number": 237, "usage_type": "call"}, {"api_name": "logging.StreamHandler", "line_number": 240, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 240, "usage_type": "attribute"}, {"api_name": "datasets.utils.logging.set_verbosity", "line_number": 244, "usage_type": "call"}, {"api_name": "datasets.utils", "line_number": 244, "usage_type": "attribute"}, {"api_name": "transformers.utils.logging.set_verbosity", "line_number": 245, "usage_type": "call"}, {"api_name": "transformers.utils", "line_number": 245, "usage_type": "attribute"}, {"api_name": "transformers.utils.logging.enable_default_handler", "line_number": 246, "usage_type": "call"}, {"api_name": "transformers.utils", "line_number": 246, "usage_type": "attribute"}, {"api_name": "transformers.utils.logging.enable_explicit_format", "line_number": 247, "usage_type": "call"}, {"api_name": "transformers.utils", "line_number": 247, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 258, "usage_type": "call"}, {"api_name": "os.path", "line_number": 258, "usage_type": "attribute"}, {"api_name": "transformers.trainer_utils.get_last_checkpoint", "line_number": 259, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 260, "usage_type": "call"}, {"api_name": "transformers.set_seed", "line_number": 272, "usage_type": "call"}, {"api_name": "uie_dataset.gen_cache_path", "line_number": 273, "usage_type": "call"}, {"api_name": "datasets.load_dataset", "line_number": 276, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 277, "usage_type": "call"}, {"api_name": "os.path", "line_number": 277, "usage_type": "attribute"}, {"api_name": "transformers.AutoConfig.from_pretrained", "line_number": 295, "usage_type": "call"}, {"api_name": "transformers.AutoConfig", "line_number": 295, "usage_type": "name"}, {"api_name": "transformers.AutoTokenizer.from_pretrained", "line_number": 301, "usage_type": "call"}, {"api_name": "transformers.AutoTokenizer", "line_number": 301, "usage_type": "name"}, {"api_name": "model.bloom.BloomForCausalLM_WithLoss", "line_number": 310, "usage_type": "name"}, {"api_name": "model.codegen.CodeGenForCausalLM_WithLoss", "line_number": 315, "usage_type": "name"}, {"api_name": "model.gpt_neox.GPTNeoXForCausalLM_WithLoss", "line_number": 320, "usage_type": "name"}, {"api_name": "transformers.AutoModelForSeq2SeqLM", "line_number": 325, "usage_type": "name"}, {"api_name": "model.bloom", "line_number": 326, "usage_type": "name"}, {"api_name": "model.bloom.resize_token_embeddings", "line_number": 334, "usage_type": "call"}, {"api_name": "model.bloom", "line_number": 334, "usage_type": "name"}, {"api_name": "model.bloom.config", "line_number": 337, "usage_type": "attribute"}, {"api_name": "model.bloom", "line_number": 337, "usage_type": "name"}, {"api_name": "model.bloom.config", "line_number": 338, "usage_type": "attribute"}, {"api_name": "model.bloom", "line_number": 338, "usage_type": "name"}, {"api_name": "model.bloom.config", "line_number": 342, "usage_type": "attribute"}, {"api_name": "model.bloom", "line_number": 342, "usage_type": "name"}, {"api_name": "model.bloom.resize_position_embeddings", "line_number": 345, "usage_type": "call"}, {"api_name": "model.bloom", "line_number": 345, "usage_type": "name"}, {"api_name": "model.bloom.resize_position_embeddings", "line_number": 347, "usage_type": "call"}, {"api_name": "model.bloom", "line_number": 347, "usage_type": "name"}, {"api_name": "model.bloom.config", "line_number": 350, "usage_type": "attribute"}, {"api_name": "model.bloom", "line_number": 350, "usage_type": "name"}, {"api_name": "model.bloom.config", "line_number": 351, "usage_type": "attribute"}, {"api_name": "model.bloom", "line_number": 351, "usage_type": "name"}, {"api_name": "model.bloom", "line_number": 355, "usage_type": "argument"}, {"api_name": "model.bloom.__class__", "line_number": 358, "usage_type": "attribute"}, {"api_name": "model.bloom", "line_number": 358, "usage_type": "name"}, {"api_name": "uie_collator.DataCollatorForUIE", "line_number": 384, "usage_type": "call"}, {"api_name": "model.bloom", "line_number": 386, "usage_type": "name"}, {"api_name": "uie_trainer.skip_instructions", "line_number": 404, "usage_type": "call"}, {"api_name": "model.bloom", "line_number": 404, "usage_type": "argument"}, {"api_name": "compute_metrics.compute_metrics", "line_number": 406, "usage_type": "call"}, {"api_name": "compute_metrics.compute_grouped_metrics", "line_number": 407, "usage_type": "call"}, {"api_name": "compute_metrics.compute_grouped_metrics", "line_number": 411, "usage_type": "call"}, {"api_name": "numpy.count_nonzero", "line_number": 414, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 415, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 418, "usage_type": "call"}, {"api_name": "os.path", "line_number": 418, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 420, "usage_type": "call"}, {"api_name": "model.bloom.gradient_checkpointing_enable", "line_number": 430, "usage_type": "call"}, {"api_name": "model.bloom", "line_number": 430, "usage_type": "name"}, {"api_name": "uie_trainer.UIETrainer", "line_number": 432, "usage_type": "call"}, {"api_name": "model.bloom", "line_number": 433, "usage_type": "name"}, {"api_name": "uie_trainer.DenserEvalCallback", "line_number": 440, "usage_type": "name"}, {"api_name": "os.path.isdir", "line_number": 485, "usage_type": "call"}, {"api_name": "os.path", "line_number": 485, "usage_type": "attribute"}, {"api_name": "transformers.trainer_utils.get_last_checkpoint", "line_number": 486, "usage_type": "call"}, {"api_name": "model.bloom", "line_number": 491, "usage_type": "name"}, {"api_name": "uie_trainer.UIETrainer", "line_number": 492, "usage_type": "call"}, {"api_name": "model.bloom", "line_number": 493, "usage_type": "name"}, {"api_name": "uie_trainer.DenserEvalCallback", "line_number": 500, "usage_type": "name"}, {"api_name": "model.bloom", "line_number": 533, "usage_type": "argument"}]} +{"seq_id": "35823515997", "text": "import os, sys\nfrom flask import Flask, request\nfrom utils import wit_response\nfrom pymessenger import Bot\n\napp = Flask(__name__)\n\nPAGE_ACCESS_TOKEN=\"EAAHLxMxj2OoBAC4gJIsp8fbtFKR3ICG3SRoV7UUZAq5cW8IsvA5TIlZBbTpLhe34cxGfxcgxT84gxsY324ZA12Yph3WF9Uaon51ZB0dLbqZAAc7q7K5wZAkPFGZCZCUlf5tcrSZBmYw7ZBp4LzCZAAZB5VCHcuh0Gi725kbKfJ61uGlw6AZDZD\"\nbot = Bot(PAGE_ACCESS_TOKEN)\n\n@app.route('/', methods=['GET'])\ndef verify():\n #Webhook verification\n #print(\"HELLO****************************\")\n if request.args.get(\"hub.mode\")==\"subscribe\" and request.args.get(\"hub.challenge\"):\n if not request.args.get(\"hub.verify_token\")==\"hello\":\n return \"Verification token mismatch\", 403\n return request.args[\"hub.challenge\"], 200\n return \"Hello World\", 200\n\n@app.route('/', methods=['POST'])\ndef webhook():\n #print(\"HI****************************\")\n data = request.get_json()\n print(\"data\")\n log(data)\n if data['object']=='page':\n for entry in data['entry']:\n for messaging_event in entry['messaging']:\n sender_id=messaging_event['sender']['id']\n recipient_id=messaging_event['recipient']['id']\n if messaging_event.get('message'):\n if 'text' in messaging_event['message']:\n messaging_text= messaging_event['message']['text']\n else:\n messaging_text='no text'\n response = None\n entity, value = wit_response(messaging_text)\n if entity == 'books':\n response = \"Ok. I will show you {} books.\".format(str(value))\n elif entity == \"greetings\":\n response = \"Hello, how can I help you?\"\n elif entity == \"intent\":\n response = \"Which subject books do you want?\"\n else:\n response = \"Sorry, I din't get you.\"\n bot.send_text_message(sender_id,response)\n return \"ok\", 200\n\ndef log(message):\n\tprint(message)\n\tsys.stdout.flush()\n\nif __name__=='__main__':\n\tapp.run(debug=True)\n", "repo_name": "Akshansh93/Education-Bot", "sub_path": "app_wit.py", "file_name": "app_wit.py", "file_ext": "py", "file_size_in_byte": 2161, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 6, "usage_type": "call"}, {"api_name": "pymessenger.Bot", "line_number": 9, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 15, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 15, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 15, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 16, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 16, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 16, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 18, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 18, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 24, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 24, "usage_type": "name"}, {"api_name": "utils.wit_response", "line_number": 38, "usage_type": "call"}, {"api_name": "sys.stdout.flush", "line_number": 52, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 52, "usage_type": "attribute"}]} +{"seq_id": "72273549821", "text": "import concurrent.futures\nfrom concurrent.futures import ThreadPoolExecutor\n\nfrom tabulate import tabulate\n\nfrom .Config import Config\nfrom .Pull import Pull\nfrom ..model import (\n UpdateJson,\n TrackJson\n)\nfrom ..track import BaseTracks, LocalTracks, GithubTracks\nfrom ..utils import Log\n\n\nclass Sync:\n def __init__(self, root_folder, config, tracks=None):\n self._log = Log(\"Sync\", enable_log=config.enable_log, log_dir=config.log_dir)\n self._root_folder = root_folder\n self._pull = Pull(root_folder, config)\n\n self._json_folder = Config.get_json_folder(root_folder)\n self._modules_folder = Config.get_modules_folder(root_folder)\n self._config = config\n\n if tracks is None:\n self._tracks = BaseTracks()\n else:\n self._tracks = tracks\n\n self._updated_diff = list()\n\n def _update_jsons(self, track, force):\n module_folder = self._modules_folder.joinpath(track.id)\n\n if not track.enable:\n self._log.i(f\"_update_jsons: [{track.id}] -> update check has been disabled\")\n return None\n\n online_module, timestamp = self._pull.from_track(track)\n if online_module is None:\n return None\n\n update_json_file = module_folder.joinpath(UpdateJson.filename())\n track_json_file = module_folder.joinpath(TrackJson.filename())\n\n if force:\n for file in module_folder.glob(\"*\"):\n if file.name not in [\n TrackJson.filename(),\n online_module.zipfile_name,\n online_module.changelog_filename\n ]:\n file.unlink()\n\n if update_json_file.exists():\n update_json = UpdateJson.load(update_json_file)\n update_json.update(id=track.id)\n else:\n update_json = UpdateJson(\n id=track.id,\n timestamp=timestamp,\n versions=list()\n )\n\n version_item = online_module.to_VersionItem(timestamp)\n update_json.versions.append(version_item)\n\n max_num = self._config.max_num\n if track.max_num is not None:\n max_num = track.max_num\n\n if len(update_json.versions) > max_num:\n old_item = update_json.versions.pop(0)\n zipfile = module_folder.joinpath(old_item.zipfile_name)\n changelog = module_folder.joinpath(old_item.changelog_filename)\n\n for path in [zipfile, changelog]:\n if not (path.exists() and path.is_file()):\n continue\n\n self._log.d(f\"_update_jsons: [{track.id}] -> remove {path.name}\")\n path.unlink()\n\n track.last_update = timestamp\n track.versions = len(update_json.versions)\n\n update_json.write(update_json_file)\n track.write(track_json_file)\n\n if len(update_json.versions) >= 2:\n self._updated_diff.append(\n (update_json.versions[-2], online_module)\n )\n else:\n self._updated_diff.append(\n (None, online_module)\n )\n\n return online_module\n\n @staticmethod\n def _check_tracks(obj, cls):\n if type(obj) is BaseTracks:\n raise RuntimeError(\"tracks interface has not been created\")\n\n return isinstance(obj, cls)\n\n def create_github_tracks(self, api_token, after_date=None):\n self._tracks = GithubTracks(\n modules_folder=self._modules_folder,\n config=self._config,\n api_token=api_token,\n after_date=after_date\n )\n return self._tracks\n\n def create_local_tracks(self):\n self._tracks = LocalTracks(\n modules_folder=self._modules_folder,\n config=self._config\n )\n return self._tracks\n\n def update(self, module_ids=None, force=False, single=False, **kwargs):\n user_name = kwargs.get(\"user_name\")\n if user_name is not None:\n if self._check_tracks(self._tracks, GithubTracks):\n tracks = self._tracks.get_tracks(\n user_name=user_name,\n repo_names=module_ids,\n single=single,\n cover=kwargs.get(\"cover\", False),\n use_ssh=kwargs.get(\"use_ssh\", True)\n )\n else:\n msg = f\"unsupported tracks interface type [{type(self._tracks).__name__}]\"\n raise RuntimeError(msg)\n else:\n tracks = self._tracks.get_tracks(module_ids)\n\n with ThreadPoolExecutor(max_workers=1 if single else None) as executor:\n futures = []\n for track in tracks:\n futures.append(\n executor.submit(self._update_jsons, track=track, force=force)\n )\n\n for future in concurrent.futures.as_completed(futures):\n online_module = future.result()\n if online_module is not None:\n self._log.i(f\"update: [{online_module.id}] -> update to {online_module.version_display}\")\n\n def get_versions_diff(self):\n headers = [\"id\", \"name\", \"version\"]\n table = []\n\n if len(self._updated_diff) == 0:\n return None\n\n for last, new in self._updated_diff:\n version = new.version_display\n if last is not None:\n version = f\"{last.version_display} -> {version}\"\n\n name = new.name.replace(\"|\", \"_\")\n table.append(\n [new.id, name, version]\n )\n\n markdown_text = tabulate(table, headers, tablefmt=\"github\")\n return markdown_text\n", "repo_name": "ya0211/magisk-modules-repo-util", "sub_path": "sync/core/Sync.py", "file_name": "Sync.py", "file_ext": "py", "file_size_in_byte": 5698, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 34, "dataset": "github-code", "pt": "24", "api": [{"api_name": "utils.Log", "line_number": 18, "usage_type": "call"}, {"api_name": "Pull.Pull", "line_number": 20, "usage_type": "call"}, {"api_name": "Config.Config.get_json_folder", "line_number": 22, "usage_type": "call"}, {"api_name": "Config.Config", "line_number": 22, "usage_type": "name"}, {"api_name": "Config.Config.get_modules_folder", "line_number": 23, "usage_type": "call"}, {"api_name": "Config.Config", "line_number": 23, "usage_type": "name"}, {"api_name": "track.BaseTracks", "line_number": 27, "usage_type": "call"}, {"api_name": "track.id", "line_number": 34, "usage_type": "attribute"}, {"api_name": "track.enable", "line_number": 36, "usage_type": "attribute"}, {"api_name": "track.id", "line_number": 37, "usage_type": "attribute"}, {"api_name": "model.UpdateJson.filename", "line_number": 44, "usage_type": "call"}, {"api_name": "model.UpdateJson", "line_number": 44, "usage_type": "name"}, {"api_name": "model.TrackJson.filename", "line_number": 45, "usage_type": "call"}, {"api_name": "model.TrackJson", "line_number": 45, "usage_type": "name"}, {"api_name": "model.TrackJson.filename", "line_number": 50, "usage_type": "call"}, {"api_name": "model.TrackJson", "line_number": 50, "usage_type": "name"}, {"api_name": "model.UpdateJson.load", "line_number": 57, "usage_type": "call"}, {"api_name": "model.UpdateJson", "line_number": 57, "usage_type": "name"}, {"api_name": "track.id", "line_number": 58, "usage_type": "attribute"}, {"api_name": "model.UpdateJson", "line_number": 60, "usage_type": "call"}, {"api_name": "track.id", "line_number": 61, "usage_type": "attribute"}, {"api_name": "track.max_num", "line_number": 70, "usage_type": "attribute"}, {"api_name": "track.max_num", "line_number": 71, "usage_type": "attribute"}, {"api_name": "track.id", "line_number": 82, "usage_type": "attribute"}, {"api_name": "track.last_update", "line_number": 85, "usage_type": "attribute"}, {"api_name": "track.versions", "line_number": 86, "usage_type": "attribute"}, {"api_name": "track.write", "line_number": 89, "usage_type": "call"}, {"api_name": "track.BaseTracks", "line_number": 104, "usage_type": "name"}, {"api_name": "track.GithubTracks", "line_number": 110, "usage_type": "call"}, {"api_name": "track.LocalTracks", "line_number": 119, "usage_type": "call"}, {"api_name": "track.GithubTracks", "line_number": 128, "usage_type": "argument"}, {"api_name": "concurrent.futures.ThreadPoolExecutor", "line_number": 142, "usage_type": "call"}, {"api_name": "concurrent.futures.futures.as_completed", "line_number": 149, "usage_type": "call"}, {"api_name": "concurrent.futures.futures", "line_number": 149, "usage_type": "attribute"}, {"api_name": "concurrent.futures", "line_number": 149, "usage_type": "name"}, {"api_name": "tabulate.tabulate", "line_number": 171, "usage_type": "call"}]} +{"seq_id": "12872667250", "text": "from flask import Flask, render_template, request, redirect, flash\napp = Flask(__name__)\napp.secret_key = 'RobBoss'\n\n@app.route('/')\ndef index():\n\treturn render_template(\"index.html\")\n@app.route('/results', methods=['POST'])\ndef create():\n\tnamer = request.form['name']\n\tlocaler = request.form['locale']\n\tlingor = request.form['lingo']\n\tcommentr = request.form['comment']\n\n\t## validations yay ##\n\tif len(namer) < 1:\n\t\tflash('Yo dawg, gotta have a name! AMIRITE?')\n\t\treturn redirect('/')\n\telif len(commentr) > 120:\n\t\tflash('more register less comment young one')\n\t\treturn redirect('/')\n\telse:\n\t\tflash('thanks for registering broski!')\n\n\treturn render_template('result.html', named=namer, locale=localer, lingo=lingor, comment=commentr)\n\n\n\napp.run(debug=True)", "repo_name": "pinkshrub/numberGame", "sub_path": "server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 756, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 2, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 7, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 10, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 10, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 11, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 11, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 12, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 12, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 13, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 13, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 17, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 18, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 20, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 21, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 23, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "38143770035", "text": "import matplotlib, sys\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as m_plot\n\nif __name__=='__main__':\n data = []\n with open(sys.argv[1], 'r') as f:\n for line in f:\n data.append(map(float, line.strip().split(',')))\n\n fig = m_plot.figure(figsize=(14, 7))\n fig.suptitle('Seek time vs Hour', fontsize=20)\n\n colors = ('b','g','r','c','m','y','k')\n weekdays = ('Mon', 'Tues','Wed','Thurs','Fri','Sat','Sun')\n for i in range(0,7):\n hr_ave_by_wkday = [(h,s/c) for w,h,s,c in data if w==i]\n hr_ave_by_wkday.sort()\n values = zip(*hr_ave_by_wkday)\n\n ax = fig.add_axes([.1,.1,.7,.7])\n ax.plot(values[0], values[1], color=colors[i], label=weekdays[i])\n \n ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n ax.set_xlim([0,23])\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.get_xaxis().tick_bottom()\n ax.get_yaxis().tick_left()\n ax.set_ylabel('seek time')\n ax.set_xlabel('hour of day')\n fig.savefig(sys.argv[2])\n", "repo_name": "yinkelly/nyc-taxi", "sub_path": "1-seek-time/plot_results.py", "file_name": "plot_results.py", "file_ext": "py", "file_size_in_byte": 1054, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "matplotlib.use", "line_number": 2, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 7, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 32, "usage_type": "attribute"}]} +{"seq_id": "2088839320", "text": "import sys\nfrom itertools import combinations\n\ninput = sys.stdin.readline\n\nN, M = map(int, input().split())\n\n\ndef calc_dist(home, chicken):\n # min dist 최댓값 초기화\n min_dist = 1e9\n\n # 치킨집을 순회하면서 계산\n for c in chicken:\n # abs를 이용한 최솟값 계산\n min_dist = min(min_dist, abs(c[0] - home[0]) + abs(c[1] - home[1]))\n # min dist 대입\n return min_dist\n\n\n# M : 치킨 집 개수\ngraph = [list(map(int, input().split())) for _ in range(N)]\n\n# 치킨과 집 집계\nchicken = [[c, j] for c in range(N) for j in range(N) if graph[c][j] == 2]\nhome = [[i, j] for i in range(N) for j in range(N) if graph[i][j] == 1]\n\n# 치킨에 대해서 많은 케이스 생성\nchicken_select = list(combinations(chicken, M))\n\n# 최소 치킨거리 계산\nmin_chicken_dist = int(10e9)\nfor chickens in chicken_select:\n dist = 0\n # 모든 집을 순회하며 치킨 거리 계산\n for h in home:\n dist += calc_dist(h, chickens)\n min_chicken_dist = min(dist, min_chicken_dist)\n\nprint(min_chicken_dist)\n", "repo_name": "hjun-park/Coding-test-self-study", "sub_path": "--2022backup/[02]구현/[G5]15686-치킨 배달.py", "file_name": "[G5]15686-치킨 배달.py", "file_ext": "py", "file_size_in_byte": 1065, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sys.stdin", "line_number": 4, "usage_type": "attribute"}, {"api_name": "itertools.combinations", "line_number": 29, "usage_type": "call"}]} +{"seq_id": "15188593159", "text": "# -*- coding: utf-8 -*-\r\n\r\n# __title__ = 'MyForms.py'\r\n# __author__ = 'YangYang'\r\n# __mtime__ = '2018.07.17'\r\n\r\nfrom django import forms\r\nfrom django.forms import widgets\r\n\r\nfrom blog.models import UserInfo\r\nfrom django.core.exceptions import ValidationError\r\n\r\nwid_01=widgets.TextInput(attrs={\"class\":\"form-control\"})\r\nwid_02=widgets.PasswordInput(attrs={\"class\":\"form-control\"})\r\nwid_03=widgets.EmailInput(attrs={\"class\":\"form-control\"})\r\n\r\n\r\nclass UserForm(forms.Form):\r\n\tuser=forms.CharField(max_length=32,\r\n\t error_messages={\"required\":\"该字段不能为空\"},\r\n\t label=\"用户名\", widget=wid_01)\r\n\tpwd=forms.CharField(max_length=32,\r\n\t error_messages={\"required\": \"该字段不能为空\"},\r\n\t label=\"密码\",\r\n\t widget=wid_02)\r\n\tre_pwd=forms.CharField(max_length=32,\r\n\t error_messages={\"required\": \"该字段不能为空\"},\r\n\t label=\"确认密码\",widget=wid_02)\r\n\temail=forms.EmailField(max_length=32,\r\n\t error_messages={\"required\": \"该字段不能为空\"},\r\n\t label=\"邮箱\",widget=wid_03)\r\n\r\n\r\n\tdef clean_user(self):\r\n\t\tuser = self.cleaned_data.get(\"user\")\r\n\t\tuser_obj = UserInfo.objects.filter(username=user).first()\r\n\t\tif not user_obj:\r\n\t\t\treturn user\r\n\t\telse:\r\n\t\t\traise ValidationError(\"该用户已注册\")\r\n\r\n\r\n\tdef clean(self):\r\n\t\tpwd=self.cleaned_data.get(\"pwd\")\r\n\t\tre_pwd=self.cleaned_data.get(\"re_pwd\")\r\n\r\n\t\tif pwd and re_pwd:\r\n\r\n\t\t\tif pwd==re_pwd:\r\n\t\t\t\treturn self.cleaned_data\r\n\t\t\telse:\r\n\t\t\t\traise ValidationError(\"两次密码不一致\")\r\n\t\telse:\r\n\t\t\treturn self.cleaned_data\r\n\r\n\r\n", "repo_name": "ryan-yang-2049/myblog", "sub_path": "myblog/blog/utils/MyForms.py", "file_name": "MyForms.py", "file_ext": "py", "file_size_in_byte": 1692, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.forms.widgets.TextInput", "line_number": 13, "usage_type": "call"}, {"api_name": "django.forms.widgets", "line_number": 13, "usage_type": "name"}, {"api_name": "django.forms.widgets.PasswordInput", "line_number": 14, "usage_type": "call"}, {"api_name": "django.forms.widgets", "line_number": 14, "usage_type": "name"}, {"api_name": "django.forms.widgets.EmailInput", "line_number": 15, "usage_type": "call"}, {"api_name": "django.forms.widgets", "line_number": 15, "usage_type": "name"}, {"api_name": "django.forms.Form", "line_number": 18, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 18, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 19, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 22, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 22, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 26, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 26, "usage_type": "name"}, {"api_name": "django.forms.EmailField", "line_number": 29, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 29, "usage_type": "name"}, {"api_name": "blog.models.UserInfo.objects.filter", "line_number": 36, "usage_type": "call"}, {"api_name": "blog.models.UserInfo.objects", "line_number": 36, "usage_type": "attribute"}, {"api_name": "blog.models.UserInfo", "line_number": 36, "usage_type": "name"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 40, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 52, "usage_type": "call"}]} +{"seq_id": "74456429182", "text": "from datetime import datetime, timezone\nfrom dataclasses import dataclass\nfrom enum import Enum\n\nimport numpy as np\nfrom numpy import arcsin, pi, log10\nfrom numpy.polynomial import Polynomial\nfrom blocksim.satellite.Satellite import (\n CircleSatellite,\n generateWalkerDeltaConstellation,\n)\nfrom blocksim.utils import llavpa_to_itrf, itrf_to_azeld\nfrom blocksim.constants import Req, kb, c as clum\n\n\nclass EventType(Enum):\n RISE = \"rise\"\n SET = \"set\"\n\n\n@dataclass\nclass Event:\n satellite: int\n type: EventType\n date: float\n\n\ndef analyse_timeline(init, events, total_sim_time):\n tl = []\n for ksat, sat in enumerate(events):\n for e in sat:\n tl.append(Event(satellite=ksat, type=EventType.RISE, date=e[\"rise\"]))\n tl.append(Event(satellite=ksat, type=EventType.SET, date=e[\"set\"]))\n tl.sort(key=lambda x: x.date)\n\n nsat = len(np.where(init > 0)[0])\n blind_e = Event(satellite=-1, type=EventType.RISE, date=0)\n t_blind = 0\n e: Event\n nsat_max = nsat\n for e in tl:\n if e.type == EventType.RISE:\n if nsat == 0:\n t_blind += e.date - blind_e.date\n nsat += 1\n else:\n nsat -= 1\n if nsat == 0:\n blind_e = e\n elif nsat < 0:\n raise AssertionError\n if nsat_max < nsat:\n nsat_max = nsat\n print(e, nsat, t_blind)\n\n if nsat_max == 0:\n t_blind = total_sim_time\n\n return t_blind, nsat_max\n\n\ndef compute_elevation_mask(alt_km):\n # Parametres du probleme\n # ======================\n px = 36 # dBm\n NF = 3 # dB\n z1_J1 = 1.616339347\n eta = 0.7\n wl = clum / (2e9)\n cn0_lim = 46.46595211\n alpha = 0.0305\n\n # Calculs des constantes K et Q\n # =============================\n sma = Req + alt_km * 1e3\n K = (\n -36\n + px\n - NF\n + 10\n * log10((eta**2 * wl**2 * z1_J1**4 * sma**4) / (16 * pi**2 * kb * 290 * Req**4))\n )\n Q = 10 ** ((K - cn0_lim) / 20)\n\n # Calcul de l'élévation\n # =====================\n p = Polynomial(\n [\n alpha,\n 2,\n -(\n (2 * alpha**2 - 1) * sma**2\n + (1 - 2 * alpha**2) * Req**2\n + 2 * alpha * Q * Req\n + Q**2\n )\n / (alpha * sma**2 - alpha * Req**2),\n -(4 * alpha * sma**2 - 4 * alpha * Req**2 + 2 * Q * Req)\n / (alpha * sma**2 - alpha * Req**2),\n ((alpha**2 - 2) * sma**2 + (2 - alpha**2) * Req**2 + 2 * alpha * Q * Req)\n / (alpha * sma**2 - alpha * Req**2),\n (2 * alpha * sma**2 - 2 * alpha * Req**2 + 2 * Q * Req)\n / (alpha * sma**2 - alpha * Req**2),\n 1 / alpha,\n ]\n )\n\n rts = p.roots()\n r0 = rts[np.where((rts > arcsin(alpha)) & (rts < 1) & (np.abs(np.imag(rts)) < 1e-9))[0]]\n assert len(r0) == 1\n elev_mask = arcsin(r0[0])\n\n return elev_mask\n\n\ndef simulate(lat, inc, nsat, npla, pha, alt_km):\n elev_mask = compute_elevation_mask(alt_km)\n\n t0 = datetime(2023, 6, 27, 12, 0, 0, tzinfo=timezone.utc)\n firstraan = 0.0\n lon = 0.0\n # tps_max = 5 * 86400\n tps_max = 20000\n sma = Req + alt_km * 1e3\n\n satellites = generateWalkerDeltaConstellation(\n \"sim\", sma, inc, firstraan, nsat, npla, pha, t0, prop=CircleSatellite\n )\n obs = llavpa_to_itrf((lon, lat, 0, 0, 0, 0))\n events = list()\n init = list()\n sat: CircleSatellite\n for sat in satellites:\n pv_sat = sat.getGeocentricITRFPositionAt(0)\n _, el0, _, _, _, _ = itrf_to_azeld(obs, pv_sat)\n init.append(el0 - elev_mask)\n events.append(\n sat.find_events(obs, t0=0, t1=tps_max, elevation=elev_mask),\n )\n\n t_blind, nsat_max = analyse_timeline(np.array(init), events, tps_max)\n\n return t_blind, nsat_max, tps_max, elev_mask\n", "repo_name": "ydethe/constellation_design", "sub_path": "tests/simulate.py", "file_name": "simulate.py", "file_ext": "py", "file_size_in_byte": 3899, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "enum.Enum", "line_number": 16, "usage_type": "name"}, {"api_name": "dataclasses.dataclass", "line_number": 21, "usage_type": "name"}, {"api_name": "numpy.where", "line_number": 36, "usage_type": "call"}, {"api_name": "blocksim.constants.c", "line_number": 69, "usage_type": "name"}, {"api_name": "blocksim.constants.Req", "line_number": 75, "usage_type": "name"}, {"api_name": "numpy.log10", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 81, "usage_type": "name"}, {"api_name": "blocksim.constants.kb", "line_number": 81, "usage_type": "name"}, {"api_name": "blocksim.constants.Req", "line_number": 81, "usage_type": "name"}, {"api_name": "numpy.polynomial.Polynomial", "line_number": 87, "usage_type": "call"}, {"api_name": "blocksim.constants.Req", "line_number": 93, "usage_type": "name"}, {"api_name": "blocksim.constants.Req", "line_number": 94, "usage_type": "name"}, {"api_name": "blocksim.constants.Req", "line_number": 97, "usage_type": "name"}, {"api_name": "blocksim.constants.Req", "line_number": 98, "usage_type": "name"}, {"api_name": "blocksim.constants.Req", "line_number": 99, "usage_type": "name"}, {"api_name": "blocksim.constants.Req", "line_number": 100, "usage_type": "name"}, {"api_name": "blocksim.constants.Req", "line_number": 101, "usage_type": "name"}, {"api_name": "blocksim.constants.Req", "line_number": 102, "usage_type": "name"}, {"api_name": "blocksim.constants.Req", "line_number": 103, "usage_type": "name"}, {"api_name": "numpy.where", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.arcsin", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.imag", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.arcsin", "line_number": 111, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 119, "usage_type": "call"}, {"api_name": "datetime.timezone.utc", "line_number": 119, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 119, "usage_type": "name"}, {"api_name": "blocksim.constants.Req", "line_number": 124, "usage_type": "name"}, {"api_name": "blocksim.satellite.Satellite.generateWalkerDeltaConstellation", "line_number": 126, "usage_type": "call"}, {"api_name": "blocksim.satellite.Satellite.CircleSatellite", "line_number": 127, "usage_type": "name"}, {"api_name": "blocksim.utils.llavpa_to_itrf", "line_number": 129, "usage_type": "call"}, {"api_name": "blocksim.satellite.Satellite.CircleSatellite", "line_number": 132, "usage_type": "name"}, {"api_name": "blocksim.utils.itrf_to_azeld", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 141, "usage_type": "call"}]} +{"seq_id": "16791852081", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nThis module constructs and populates the deployment dictionary data\nstructure ``deploy_dict``. Below is an overview of the deployment dictionary:\n\n* Testing organization\n * Organization name, contact information\n* Testing Location\n * Site name, address, coordinates, and AQS site identifier\n* Deployment Information and Statistics\n * Unique deployment groups\n * Description of sensor uptime for each sensor unit\n * Evaluation parameter statistics\n * Precision\n * Error\n * Description of reference monitor, measured range during\n deployment period at 1-hour and 24-hour averages\n * Meteorological conditions\n * Description of temperature instrument, measured range during\n deployment period at 1-hour and 24-hour averages\n * Description of relative humidity instrument, measured range during\n deployment period at 1-hour and 24-hour averages\n\n================================================================================\n\n@Author:\n | Samuel Frederick, NSSC Contractor (ORAU)\n | U.S. EPA / ORD / CEMM / AMCD / SFSB\n\nCreated:\n Mon Nov 9 10:47:56 2020\nLast Updated:\n Tue Jul 12 13:38:00 2021\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nfrom sensortoolkit.calculate import uptime\nfrom sensortoolkit.lib_utils import _get_version\nfrom sensortoolkit.param import Parameter\nfrom sensortoolkit.datetime_utils import (deploy_timestamp_index,\n get_timestamp_interval)\n\ndef construct_deploy_dict(deploy_df, full_df_list, hourly_df_list,\n daily_df_list, sensor_name, testing_loc,\n testing_org, **kwargs):\n \"\"\"Create the deployment dictionary, initialize with sensor group info,\n time period of deployment, testing agency and location, and library version\n and time at which the dictionary were constructed.\n\n Determines which sensors match the beginning and end dates for deployment\n (provided a timedelta padding window of 1 day around the begin and end\n timestamps). Sensors measuring concurrently are grouped together as a\n `deployment group`. Sensors with beginning and end deployment dates that\n differ from the identified deployment group are assigned ``True`` for the\n ``deploy_dict`` sensor unit entry ``deploy_issues``.\n\n Args:\n deploy_df (pandas dataframe):\n A data frame containing the start time (`Begin`), end time (`End`),\n and total duration of evaluation period for each sensor in a\n deployment group.\n full_df_list (list):\n List of sensor data frames of length N (where N is the number of\n sensor units in a testing group). Data frames indexed by\n at recorded sampling frequency.\n hourly_df_list (list):\n List of sensor data frames of length N (where N is the number of\n sensor units in a testing group). Data frames indexed by\n DateTime at 1-hour averaged sampling frequency.\n daily_df_list (list):\n List of sensor data frames of length N (where N is the number of\n sensor units in a testing group). Data frames indexed by\n DateTime at 24-hour averaged sampling frequency.\n sensor_name (str):\n The make and model of the sensor being evaluated.\n testing_org (dict):\n A dictionary containing the information about the testing\n organization.\n testing_loc (dict):\n A dictionary containing information about the testing site. If the\n site is part of U.S. EPA’s Air Quality System (AQS), the AQS Site\n ID should be specified.\n\n Returns:\n deploy_dict (dict):\n Dictionary containing separate deployment group start and\n end times (based on the latest (max) start timestamp and earliest\n (min) end timestamp in group), deployment duration, and sensor\n serial IDs for devices within each deployment group.\n\n \"\"\"\n current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S %p')\n deploy_dict = {'sensortoolkit Version': _get_version(),\n 'Date of Analysis': current_time,\n 'Sensor Name': sensor_name,\n 'Sensor Firmware Version': kwargs.get('sensor_firmware', 'Unspecified'),\n 'Deployment Groups': {},\n 'Testing Organization': testing_org,\n 'Testing Location': testing_loc}\n\n deploy_grp_n = 1\n\n while deploy_df.empty is False:\n i = deploy_df.index[0]\n\n match_begin = abs(deploy_df.loc[i, 'Begin'] - deploy_df.loc[:, 'Begin']\n ) < pd.Timedelta('1 day')\n\n deploy = deploy_df[match_begin]\n\n # Date (YYYY-MM-DD) of deployment group end, calculate mode\n end_date = deploy.loc[:, \"End\"].dt.strftime(\"%Y-%m-%d\")\n end_date_mode = end_date.mode()[0]\n\n # Sensors that concluded deployment before end of majority of group\n deploy['Issues'] = end_date != end_date_mode\n\n serials = {str(i): serial for i, serial in zip(\n deploy.Sensor_Number, deploy.Sensor_Serial)}\n\n deployments = deploy_dict['Deployment Groups']\n\n deployments['Group ' + str(deploy_grp_n)] = {}\n deployments['Group ' + str(deploy_grp_n)]['sensors'] = {}\n\n sensor_info = {i: {'serial_id': j} for i, j in zip(serials.keys(),\n serials.values())}\n\n deployments['Group ' + str(deploy_grp_n)]['sensors'] = sensor_info\n\n deployments['Group ' + str(deploy_grp_n)]['eval_start'] = \\\n deploy.Begin.min().strftime(\"%Y-%m-%dT%H:%M:%S%z\")\n deployments['Group ' + str(deploy_grp_n)]['eval_end'] = \\\n deploy.End.max().strftime(\"%Y-%m-%dT%H:%M:%S%z\")\n deployments['Group ' + str(deploy_grp_n)]['eval_duration'] = \\\n str(abs(deploy.Begin.min() - deploy.End.max()))\n\n start = deployments['Group ' + str(deploy_grp_n)]['eval_start']\n end = deployments['Group ' + str(deploy_grp_n)]['eval_end']\n\n # round timestamp down to nearest hour\n start = pd.to_datetime(start).floor(freq='H')\n # round timestamp up to nearest hour\n end = pd.to_datetime(end).ceil(freq='H')\n\n for sensor_n in list(sensor_info.keys()):\n i = int(sensor_n) - 1\n\n full_df = full_df_list[i]\n hourly_df = hourly_df_list[i]\n daily_df = daily_df_list[i]\n\n # Record whether sensor encountered issues during deployment, ended\n # deployment early\n sensor_df = deploy[deploy.Sensor_Number == sensor_n]\n sensor_df = sensor_df.reset_index(drop=True)\n sensor_info[sensor_n]['deploy_issues'] = str(bool(\n sensor_df.Issues[0]))\n\n # Compute recording interval for data\n time_delta = get_timestamp_interval(full_df)\n sensor_info[sensor_n]['recording_interval'] = time_delta\n\n # 1-hr uptime\n sensor_h_uptime = uptime(hourly_df.loc[start:end, :], key=sensor_n)\n sensor_info[sensor_n]['uptime_1-hour'] = sensor_h_uptime[sensor_n]['Uptime']\n\n # 24-hr uptime\n sensor_d_uptime = uptime(daily_df.loc[start:end, :], key=sensor_n)\n sensor_info[sensor_n]['uptime_24-hour'] = sensor_d_uptime[sensor_n]['Uptime']\n\n deploy_df = deploy_df.drop(deploy.index, axis=0)\n deploy_grp_n += 1\n\n return deploy_dict\n\n\ndef deploy_ref_stats(deploy_dict, ref_df, cal_check_dict=None, param=None,\n ref_name=None):\n \"\"\"Add reference monitor statistics to the parameter statistics subfield in\n the deployment dictionary.\n\n Details added include:\n\n * The FRM/FEM monitor name\n * The minimum concentration recorded at the specified interval\n averaging.\n * The maximum concentration recorded at the specified interval\n averaging.\n * The number of intervals during which the FRM/FEM exceeds the goal\n concentration recommended by the performance targets testing report\n for elevated concentrations (goal :math:`\\\\geq`` three days).\n\n Args:\n deploy_dict (dict):\n Dictionary containing separate deployment group start and end times\n (based on the latest (max) start timestamp and earliest (min)\n end timestamp in group), deployment duration, and sensor serial IDs\n for devices within each deployment group.\n \tref_df (pandas dataframe):\n Dataframe for reference concentrations at either 1-hour or 24-hour\n averaging depending on the performance targets recommeneded\n averaging interval.\n \tcal_check_dict (dict):\n [Future feature] Dictionary for housing dates and descriptions of QC\n calibration checks as part of regularly scheduled and cataloged QC\n procedures.\n param_obj (str):\n The evaluation parameter\n ref_name (str):\n The name of the FRM/FEM monitor (make and model).\n\n Returns:\n deploy_dict:\n Dictionary containing separate deployment group start and end times\n (based on the latest (max) start timestamp and earliest (min)\n end timestamp in group), deployment duration, and sensor serial IDs\n for devices within each deployment group.\n\n \"\"\"\n param_obj = Parameter(param)\n param_name = param_obj.name\n\n date_index, avg_suffix = deploy_timestamp_index(ref_df,\n averaging_suffix=True)\n\n if param_name == 'PM25':\n conc_goal = 25 # Concentration goal: 25 ug/m^3 for at least one day\n elif param_name == 'O3':\n conc_goal = 60 # Concentration goal: 60 ppbv for at least one day\n ref_df[f'{param_name}_rolling_8-hour_Value'] = ref_df[f'{param_name}_Value'].rolling(window=8).mean()\n\n else:\n conc_goal = None\n\n for group in deploy_dict['Deployment Groups']:\n deploy = deploy_dict['Deployment Groups'][group]\n start = deploy['eval_start']\n end = deploy['eval_end']\n\n ref_data = ref_df.loc[start:end, param_name + '_Value']\n\n if param_name not in deploy:\n deploy[param_name] = {}\n deploy[param_name]['Reference'] = {}\n\n if 'Reference' not in deploy[param_name]:\n deploy[param_name]['Reference'] = {}\n\n stats_loc = deploy[param_name]['Reference']\n\n stats_loc['reference_name'] = ref_name\n stats_loc['conc_min' + avg_suffix] = \\\n float(\"{0:.3f}\".format(ref_data.min()))\n stats_loc['conc_max' + avg_suffix] = \\\n float(\"{0:.3f}\".format(ref_data.max()))\n stats_loc['conc_mean' + avg_suffix] = \\\n float(\"{0:.3f}\".format(ref_data.mean()))\n stats_loc['n_exceed_conc_goal' + avg_suffix] = \\\n int(ref_data.where(ref_data > conc_goal).count())\n\n if ref_data.dropna().empty:\n stats_loc['conc_min' + avg_suffix] = None\n stats_loc['conc_max' + avg_suffix] = None\n stats_loc['n_exceed_conc_goal' + avg_suffix] = None\n\n # add 8-hr rolling statistics\n if param_name =='O3':\n avg_suffix = '_rolling_8-hour'\n ref_data = ref_df.loc[start:end, f'{param_name}{avg_suffix}_Value']\n\n stats_loc['conc_min' + avg_suffix] = \\\n float(\"{0:.3f}\".format(ref_data.min()))\n stats_loc['conc_max' + avg_suffix] = \\\n float(\"{0:.3f}\".format(ref_data.max()))\n stats_loc['conc_mean' + avg_suffix] = \\\n float(\"{0:.3f}\".format(ref_data.mean()))\n\n return deploy_dict\n\n\ndef deploy_met_stats(deploy_dict, df_list, met_ref_df, operational_range):\n \"\"\"Add meteorological instrument statistics to the parameter statistics\n subfield in the deployment dictionary.\n\n Details added include:\n\n * The name of the instrument collocated nearby sensor deployment location.\n * The minimum value recorded at the specified interval averaging.\n * The maximum value recorded at the specified interval averaging.\n * The number of intervals during which the instrument exceeds the\n manufacturer's recommended target range for instrument performance.\n This is provisionally set for RH (exceedence when :math:`\\\\leq` 10% or\n :math:`\\\\geq` 90%) and Temp (exceedence when :math:`\\\\leq` -20 C or\n :math:`\\\\geq` 40 C).\n\n Args:\n \tdeploy_dict (dict):\n Dictionary containing separate deployment group start and end times\n (based on the latest (max) start timestamp and earliest (min)\n end timestamp in group), deployment duration, and sensor serial IDs\n for devices within each deployment group.\n \tdf_list (list):\n List of pandas dataframes for sensor measurements at either 1-hr or\n 24-hr averaging intervals.\n met_ref_df (pandas dataframe):\n A dataframe containing meteorological parameters recorded at the\n testing site during the evaluation period (either 1-hr or 24-hr\n averaging intervals).\n \toperational_range (dict):\n Dictionary for listing the operational range indicated by the\n sensor manufacturer for meteorological parameters, such as temp\n and RH.\n\n Returns:\n deploy_dict:\n Dictionary containing separate deployment group start and end times\n (based on the latest (max) start timestamp and earliest (min)\n end timestamp in group), deployment duration, and sensor serial IDs\n for devices within each deployment group.\n\n \"\"\"\n met_str = 'Meteorological Conditions'\n date_index, avg_suffix = deploy_timestamp_index(met_ref_df,\n averaging_suffix=True)\n\n #cal_check_dict = cal_check_dict['Met cal checks']\n for name in ['Temp', 'RH']:\n param_obj = Parameter(name)\n param_name = param_obj.name\n fmt_param = param_obj.format_name\n #fmt_param_units = param_obj.units\n\n no_data = False\n try:\n ref_name = met_ref_df.loc[:, param_name + '_Method'].dropna().apply(\n lambda x: str(x)).unique()[0]\n except IndexError:\n ref_name = 'Unknown Reference'\n except KeyError:\n # No met parameter data in passed reference dataframe\n no_data = True\n\n max_criterion = operational_range[param_name][1]\n min_criterion = operational_range[param_name][0]\n\n for group in deploy_dict['Deployment Groups']:\n deploy = deploy_dict['Deployment Groups'][group]\n start = deploy['eval_start']\n end = deploy['eval_end']\n\n if met_str not in deploy:\n deploy[met_str] = {}\n\n if fmt_param not in deploy[met_str]:\n deploy[met_str][fmt_param] = {}\n\n stats_loc = deploy[met_str][fmt_param]\n\n if not no_data:\n ref_data = met_ref_df.loc[start:end, param_name + '_Value']\n\n grp_idx = [int(i) - 1 for i in deploy['sensors'].keys()]\n data_pairs = []\n for idx in grp_idx:\n df = df_list[idx]\n start = df.index.min()\n end = df.index.max()\n data_pairs.append(\n met_ref_df.loc[start:end,\n param_name + '_Value'].dropna().size)\n\n stats_loc['instrument_name'] = ref_name\n stats_loc['min' + avg_suffix] = \\\n float(\"{0:.3f}\".format(ref_data.min()))\n stats_loc['max' + avg_suffix] = \\\n float(\"{0:.3f}\".format(ref_data.max()))\n\n if (max_criterion and min_criterion):\n value = int(ref_data.where((ref_data > max_criterion) |\n (ref_data < min_criterion)).count())\n else:\n value = None\n\n stats_loc['n_exceed_target_criteria' + avg_suffix] = value\n stats_loc['n_measurement_pairs' + avg_suffix] = np.mean(data_pairs)\n\n #deploy[met_str]['cal_check_dates'] = cal_check_dict\n else:\n stats_loc['instrument_name'] = ''\n stats_loc['min' + avg_suffix] = ''\n stats_loc['max' + avg_suffix] = ''\n stats_loc['n_exceed_target_criteria' + avg_suffix] = ''\n stats_loc['n_measurement_pairs' + avg_suffix] = ''\n\n return deploy_dict\n", "repo_name": "praful-dodda/sensortoolkit", "sub_path": "sensortoolkit/deploy/_create_deploy_dict.py", "file_name": "_create_deploy_dict.py", "file_ext": "py", "file_size_in_byte": 16818, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "24", "api": [{"api_name": "datetime.datetime.now", "line_number": 93, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 93, "usage_type": "name"}, {"api_name": "sensortoolkit.lib_utils._get_version", "line_number": 94, "usage_type": "call"}, {"api_name": "pandas.Timedelta", "line_number": 108, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 143, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 145, "usage_type": "call"}, {"api_name": "sensortoolkit.datetime_utils.get_timestamp_interval", "line_number": 162, "usage_type": "call"}, {"api_name": "sensortoolkit.calculate.uptime", "line_number": 166, "usage_type": "call"}, {"api_name": "sensortoolkit.calculate.uptime", "line_number": 170, "usage_type": "call"}, {"api_name": "sensortoolkit.param.Parameter", "line_number": 222, "usage_type": "call"}, {"api_name": "sensortoolkit.datetime_utils.deploy_timestamp_index", "line_number": 225, "usage_type": "call"}, {"api_name": "sensortoolkit.datetime_utils.deploy_timestamp_index", "line_number": 325, "usage_type": "call"}, {"api_name": "sensortoolkit.param.Parameter", "line_number": 330, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 387, "usage_type": "call"}]} +{"seq_id": "26492379439", "text": "import logging\n\nclass PerfLogger:\n def __init__(self):\n logging.basicConfig(level=logging.DEBUG)\n \n def get_logger(self, name=None, log_file='./logs/output.log'):\n logger = logging.getLogger(name)\n formatter = logging.Formatter(u'%(asctime)s [%(levelname)8s] | %(message)s')\n file_handler = logging.FileHandler(log_file)\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n\n return logger\n", "repo_name": "jinwonkim93/perf_stats", "sub_path": "perf_stats/logger.py", "file_name": "logger.py", "file_ext": "py", "file_size_in_byte": 466, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "logging.basicConfig", "line_number": 5, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 5, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 8, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 9, "usage_type": "call"}, {"api_name": "logging.FileHandler", "line_number": 10, "usage_type": "call"}]} +{"seq_id": "36786804815", "text": "import json\nfrom typing import Tuple, Callable, Any\n\nimport geopandas\nimport numpy as np\nimport pandas as pd\nimport requests\nfrom dotenv import dotenv_values\nfrom geopandas import GeoDataFrame, GeoSeries, points_from_xy\nfrom pandas import DataFrame\nfrom scipy.spatial import cKDTree\n\nfrom date_range import DateRange\n\nsecrets = dotenv_values('.env')\n\n\ndef get_waterlevel_flow_observations(ids: str, date_range: DateRange):\n parameters = {\n 'StationId': ids,\n 'Parameter': '1000,1001',\n 'ResolutionTime': 60,\n 'ReferenceTime': date_range\n }\n url = f\"https://hydapi.nve.no/api/v1/Observations\"\n request_headers = {\n \"Accept\": \"application/json\",\n \"X-API-Key\": \"JkbAM/hEkk+5Z7mJIlC3fQ==\",\n }\n nve_stations = requests.get(url, parameters, headers=request_headers)\n parsed_result = nve_stations.json()\n df = pd.json_normalize(parsed_result['data'])\n return df\n\n\ndef get_nearest_station_obesrvation(shape: GeoDataFrame, date_range: DateRange):\n url = f'https://hydapi.nve.no/api/v1/Stations?Active=1'\n request_headers = {\n \"Accept\": \"application/json\",\n \"X-API-Key\": \"JkbAM/hEkk+5Z7mJIlC3fQ==\",\n }\n nve_stations = requests.get(url, headers=request_headers)\n parsed_result = nve_stations.json()\n df = pd.json_normalize(parsed_result['data'])\n df['parameters'] = [[x['parameter'] for x in i] for i in df.seriesList]\n df = df[df['parameters'].apply(lambda x: 1000 in x or 1001 in x)]\n df['seriesList'] = [[x for x in i if x['parameter'] == 1000 or x['parameter'] == 1001] for i in df.seriesList]\n df['dateRange'] = [[[DateRange(f\"{y['dataFromTime'][:10]}/{y['dataToTime'][:10]}\") for y in x['resolutionList'] if\n y['resTime'] == 60] for x in i] for i in df.seriesList]\n df = df[df['dateRange'].apply(lambda x: bool(list(filter(None, x))))]\n gdf = geopandas.GeoDataFrame(\n df[[\"stationId\", \"stationName\", \"latitude\", \"longitude\", \"seriesList\"]],\n geometry=geopandas.points_from_xy(df.longitude, df.latitude), crs=4326)\n culvert = shape.sjoin_nearest(gdf).merge(gdf, left_on=\"index_right\", right_index=True)\n culvert_id = culvert.iloc[0]['stationId_x']\n observations = get_waterlevel_flow_observations(culvert_id, date_range)\n return observations\n", "repo_name": "Xevorius/7Analytics-API", "sub_path": "NVE/nve_api.py", "file_name": "nve_api.py", "file_ext": "py", "file_size_in_byte": 2305, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "dotenv.dotenv_values", "line_number": 15, "usage_type": "call"}, {"api_name": "date_range.DateRange", "line_number": 18, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 30, "usage_type": "call"}, {"api_name": "pandas.json_normalize", "line_number": 32, "usage_type": "call"}, {"api_name": "geopandas.GeoDataFrame", "line_number": 36, "usage_type": "name"}, {"api_name": "date_range.DateRange", "line_number": 36, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 42, "usage_type": "call"}, {"api_name": "pandas.json_normalize", "line_number": 44, "usage_type": "call"}, {"api_name": "date_range.DateRange", "line_number": 48, "usage_type": "call"}, {"api_name": "geopandas.GeoDataFrame", "line_number": 51, "usage_type": "call"}, {"api_name": "geopandas.points_from_xy", "line_number": 53, "usage_type": "call"}]} +{"seq_id": "71720900542", "text": "from django.views.generic import ListView, DetailView\n\nfrom .models import Post, Tag\n\n\nclass PostList(ListView):\n model = Post\n paginate_by = 15\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['tags'] = Tag.objects.all()[:15]\n return context\n\n\nclass PostDetail(DetailView):\n model = Post\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['tags'] = Tag.objects.all()[:15]\n return context\n", "repo_name": "python-krasnodar/python-krasnodar.ru", "sub_path": "src/blog/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 536, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.views.generic.ListView", "line_number": 6, "usage_type": "name"}, {"api_name": "models.Post", "line_number": 7, "usage_type": "name"}, {"api_name": "models.Tag.objects.all", "line_number": 12, "usage_type": "call"}, {"api_name": "models.Tag.objects", "line_number": 12, "usage_type": "attribute"}, {"api_name": "models.Tag", "line_number": 12, "usage_type": "name"}, {"api_name": "django.views.generic.DetailView", "line_number": 16, "usage_type": "name"}, {"api_name": "models.Post", "line_number": 17, "usage_type": "name"}, {"api_name": "models.Tag.objects.all", "line_number": 21, "usage_type": "call"}, {"api_name": "models.Tag.objects", "line_number": 21, "usage_type": "attribute"}, {"api_name": "models.Tag", "line_number": 21, "usage_type": "name"}]} +{"seq_id": "19300503039", "text": "import keras.backend as K\nfrom keras.engine import Layer\nfrom keras.layers import Input, Embedding, Bidirectional, GRU, Convolution1D, GlobalMaxPooling1D, TimeDistributed, \\\n concatenate, Dense, Activation, Dropout\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.utils.training_utils import multi_gpu_model\n\nfrom custom_layers import Squeeze, BetterTimeDistributed, RepeatToMatch, ElementAt, AttentionWeightedAverage\n\n__author__ = 'sjebbara'\n\n\ndef pairwise_ranking_metric(labels, diffs):\n return K.mean(diffs > 0)\n\n\ndef margin_ranking_loss(label, diff, margin=1.0):\n ranking_loss = K.maximum(0, margin - diff)\n\n return ranking_loss\n\n\ndef batch_margin_ranking_loss(dummy, scores, margin=1.0):\n pos_score = scores[:, :1]\n neg_scores = scores[:, 1:]\n\n ranking_losses = K.maximum(0.0, margin + neg_scores - pos_score) # pos score broadcasted\n\n ranking_loss = K.sum(ranking_losses, axis=-1) # todo: sum or mean?\n return ranking_loss\n\n\n# def batch_pairwise_margin_ranking_loss(labels, scores, margin=1.0):\n# pos_scores = K.expand_dims(scores[(labels >= 0.5).nonzero()], dim=-1)\n# neg_scores = K.expand_dims(scores[(labels <= 0.5).nonzero()], dim=-1)\n#\n# pos_tmp = K.variable(numpy.array([[margin]]))\n# pos_scores = K.concatenate((pos_scores, pos_tmp), axis=0)\n#\n# neg_tmp = K.variable(numpy.array([[0.]]))\n# neg_scores = K.concatenate((neg_scores, neg_tmp), axis=0)\n#\n# n_p = K.shape(pos_scores)[0]\n# n_n = K.shape(neg_scores)[0]\n# repeated_pos_scores = K.repeat(pos_scores, n_n, )\n# repeated_neg_scores = K.transpose(K.repeat(neg_scores, n_p))\n#\n# ranking_losses = K.maximum(0, margin - repeated_pos_scores + repeated_neg_scores)\n#\n# return K.sum(ranking_losses)\n\n\n### GENERAL COMPONENTS ###\ndef apply_sequence_model(layer_type, input_sequence, embedding_size, depth, kernel_size, dropout):\n # if pooling == \"last\":\n # return_sequences = False\n # else:\n # return_sequences = True\n\n embedding_sequence = input_sequence\n\n for d in range(depth):\n if layer_type == \"rnn\":\n embedding_sequence = Bidirectional(GRU(embedding_size, activation=\"selu\", kernel_initializer=\"he_normal\",\n return_sequences=True if d < depth - 1 else False))(\n embedding_sequence)\n elif layer_type == \"cnn\":\n embedding_sequence = Convolution1D(embedding_size, kernel_size=kernel_size, activation=\"selu\",\n kernel_initializer=\"he_normal\", padding=\"same\")(embedding_sequence)\n embedding_sequence = Dropout(dropout)(embedding_sequence)\n\n if layer_type == \"cnn\":\n embedding = GlobalMaxPooling1D()(embedding_sequence)\n else:\n embedding = embedding_sequence\n\n return embedding\n\n\n### GENERAL COMPONENTS ###\ndef apply_sequence_attention_model(layer_type, input_sequence, relative_position_embeddings, embedding_size, depth,\n kernel_size, dropout):\n # if pooling == \"last\":\n # return_sequences = False\n # else:\n # return_sequences = True\n\n embedding_sequence = input_sequence\n\n for d in range(depth):\n if layer_type == \"rnn\":\n forward_embedding_sequence, backward_embedding_sequence = Bidirectional(\n GRU(embedding_size, activation=\"selu\", kernel_initializer=\"he_normal\",\n return_sequences=True), merge_mode=None)(\n embedding_sequence)\n embedding_sequence = concatenate([forward_embedding_sequence, backward_embedding_sequence])\n elif layer_type == \"cnn\":\n embedding_sequence = Convolution1D(embedding_size, kernel_size=kernel_size, activation=\"selu\",\n kernel_initializer=\"he_normal\", padding=\"same\")(embedding_sequence)\n embedding_sequence = Dropout(dropout)(embedding_sequence)\n\n if layer_type == \"cnn\":\n summary_embedding = GlobalMaxPooling1D()(embedding_sequence)\n else:\n forward_embedding = ElementAt(-1)(forward_embedding_sequence)\n backward_embedding = ElementAt(0)(backward_embedding_sequence)\n\n summary_embedding = concatenate([forward_embedding, backward_embedding])\n\n repeated_summary_embedding = RepeatToMatch()([summary_embedding, input_sequence])\n concatenated_attention_inputs = concatenate(\n [embedding_sequence, relative_position_embeddings, repeated_summary_embedding])\n\n attention_embedding = AttentionWeightedAverage()([embedding_sequence, concatenated_attention_inputs])\n return attention_embedding\n\n\ndef get_text_encoder(vocab_size, embedding_size, kernel_size, depth, dropout, embedding_layer=None, layer_type=None):\n text_input = Input(shape=(None,), dtype='int32', name='text_input')\n\n if embedding_layer is None:\n embedding_layer = Embedding(input_dim=vocab_size, output_dim=embedding_size, name=\"word_embeddings\")\n\n embedding_sequence = embedding_layer(text_input)\n\n if layer_type is None:\n layer_type = \"cnn\"\n\n text_embedding = apply_sequence_model(layer_type, input_sequence=embedding_sequence, embedding_size=embedding_size,\n depth=depth, kernel_size=kernel_size, dropout=dropout)\n\n model = Model(inputs=[text_input], outputs=[text_embedding])\n\n return model\n\n\n### SPECIFIC COMPONENTS ###\n#\n# def get_question_encoder(word_vocab_size, word_embedding_size, question_embedding_size):\n# question_input = Input(shape=(None,), dtype='int32', name='question_input')\n#\n# word_embedding_sequence = Embedding(input_dim=word_vocab_size, output_dim=word_embedding_size,\n# name=\"word_embeddings\")(question_input)\n#\n# question_embedding = apply_sequence_model(\"cnn\", input_sequence=word_embedding_sequence,\n# embedding_size=question_embedding_size, depth=5, pooling=\"max\",\n# kernel_size=3)\n#\n# model = Model(inputs=[question_input], outputs=[question_embedding])\n# return model\n#\n#\n# def get_predicate_label_encoder(word_vocab_size, word_embedding_size, predicate_vocab_size, predicate_embedding_size):\n# predicate_label_input = Input(shape=(None,), dtype='int32', name='predicate_label_input')\n#\n# predicate_word_embedding_sequence = Embedding(input_dim=word_vocab_size, output_dim=word_embedding_size,\n# name=\"predicate_word_embeddings\")(predicate_label_input)\n#\n# predicate_label_embedding = apply_sequence_model(\"cnn\", input_sequence=predicate_word_embedding_sequence,\n# embedding_size=predicate_embedding_size, depth=2, pooling=\"max\",\n# kernel_size=3)\n#\n# model = Model(inputs=[predicate_label_input], outputs=[predicate_label_embedding])\n# return model\n#\n#\n# def get_entity_label_encoder(char_vocab_size, char_embedding_size, char_kernel_size, entity_embedding_size):\n# entity_label_input = Input(shape=(None,), dtype='int32', name='predicate_hierarchy_input')\n#\n# entity_label_embedding_sequence = Embedding(input_dim=char_vocab_size, output_dim=char_embedding_size,\n# name=\"entity_char_embeddings\")(entity_label_input)\n#\n# entity_label_embedding = apply_sequence_model(\"cnn\", input_sequence=entity_label_embedding_sequence,\n# embedding_size=entity_embedding_size, depth=2, pooling=\"max\",\n# kernel_size=3)\n#\n# model = Model(inputs=[entity_label_input], outputs=[entity_label_embedding])\n# return model\n#\n\ndef simple_joint_qa(conf, res, **kwargs):\n ### setup inputs ###\n # word_vocab_size = conf., word_embedding_size, word_embedding_weights, char_vocab_size, char_embedding_size,\n # match_embedding_size,\n\n ### INPUT LIST####\n inputs = []\n\n question_char_input = Input(shape=(None,), dtype='int32', name='question_char_input')\n question_token_input = Input(shape=(None,), dtype='int32', name='question_token_input')\n\n candidate_subject_labels_input = Input(shape=(None, None), dtype='int32', name='candidate_subject_labels_input')\n candidate_predicate_labels_input = Input(shape=(None, None), dtype='int32', name='candidate_predicate_labels_input')\n\n ## add to inputs\n inputs.append(question_char_input)\n inputs.append(question_token_input)\n inputs.append(candidate_subject_labels_input)\n inputs.append(candidate_predicate_labels_input)\n\n ### setup encoders ###\n word_embedding_layer = Embedding(input_dim=conf.word_vocab_size, output_dim=conf.word_embedding_size,\n weights=[res.word_embeddings.W], name=\"word_embeddings\")\n\n char_sequence_encoder = get_text_encoder(vocab_size=conf.char_vocab_size, embedding_size=conf.char_embedding_size,\n kernel_size=conf.question_char_kernel_size,\n depth=conf.question_char_cnn_depth, dropout=conf.dropout,\n layer_type=conf.layer_type)\n predicate_token_sequence_encoder = get_text_encoder(vocab_size=conf.word_vocab_size,\n embedding_size=conf.word_embedding_size,\n kernel_size=conf.predicate_token_kernel_size,\n depth=conf.predicate_token_cnn_depth,\n embedding_layer=word_embedding_layer, dropout=conf.dropout,\n layer_type=conf.layer_type)\n\n question_token_sequence_encoder = get_text_encoder(vocab_size=conf.word_vocab_size,\n embedding_size=conf.word_embedding_size,\n kernel_size=conf.question_token_kernel_size,\n depth=conf.question_token_cnn_depth,\n embedding_layer=word_embedding_layer, dropout=conf.dropout,\n layer_type=conf.layer_type)\n\n ### encode inputs ###\n question_char_embedding = char_sequence_encoder(question_char_input)\n question_token_embedding = question_token_sequence_encoder(question_token_input)\n\n subject_label_embeddings = BetterTimeDistributed(char_sequence_encoder)(candidate_subject_labels_input)\n predicate_label_embeddings = BetterTimeDistributed(predicate_token_sequence_encoder)(\n candidate_predicate_labels_input)\n\n repeated_question_char_embedding = RepeatToMatch()([question_char_embedding, subject_label_embeddings])\n repeated_question_token_embedding = RepeatToMatch()([question_token_embedding, predicate_label_embeddings])\n\n ### compute partial matches ###\n ## use graph embeddings\n if conf.use_graph_embeddings:\n candidate_subject_graph_embedding_input = Input(shape=(None,), dtype='int32',\n name='candidate_subject_graph_embeddings_input')\n\n candidate_predicate_graph_embedding_input = Input(shape=(None,), dtype='int32',\n name='candidate_predicate_graph_embeddings_input')\n\n ## add to inputs\n inputs.append(candidate_subject_graph_embedding_input)\n inputs.append(candidate_predicate_graph_embedding_input)\n\n graph_embedding_layer = Embedding(input_dim=conf.graph_vocab_size, output_dim=conf.graph_embedding_size,\n weights=[res.graph_embeddings.W], name=\"graph_embeddings\")\n\n subject_graph_embeddings = graph_embedding_layer(candidate_subject_graph_embedding_input)\n predicate_graph_embeddings = graph_embedding_layer(candidate_predicate_graph_embedding_input)\n\n subject_match_embeddings = concatenate(\n [repeated_question_char_embedding, subject_label_embeddings, subject_graph_embeddings])\n\n predicate_match_embeddings = concatenate(\n [repeated_question_token_embedding, predicate_label_embeddings, predicate_graph_embeddings])\n\n else:\n subject_match_embeddings = concatenate([repeated_question_char_embedding, subject_label_embeddings])\n predicate_match_embeddings = concatenate([repeated_question_token_embedding, predicate_label_embeddings])\n\n subject_match_embeddings = BetterTimeDistributed(\n Dense(conf.match_embedding_size, activation=\"selu\", kernel_initializer=\"he_normal\"))(subject_match_embeddings)\n subject_match_embeddings = Dropout(conf.dropout)(subject_match_embeddings)\n\n predicate_match_embeddings = BetterTimeDistributed(\n Dense(conf.match_embedding_size, activation=\"selu\", kernel_initializer=\"he_normal\"))(predicate_match_embeddings)\n predicate_match_embeddings = Dropout(conf.dropout)(predicate_match_embeddings)\n\n if conf.use_predicate_and_subject_outputs:\n ### SUBJECT output\n subject_match_scores = BetterTimeDistributed(Dense(1, activation=\"linear\"))(subject_match_embeddings)\n subject_match_scores = Squeeze()(subject_match_scores)\n subject_match_scores = Activation(\"sigmoid\")(subject_match_scores)\n subject_answer_scores = Layer(name=\"subject_answer_scores\")(subject_match_scores)\n\n ### PREDICATE output\n predicate_match_scores = BetterTimeDistributed(Dense(1, activation=\"linear\"))(predicate_match_embeddings)\n predicate_match_scores = Squeeze()(predicate_match_scores)\n predicate_match_scores = Activation(\"sigmoid\")(predicate_match_scores)\n predicate_answer_scores = Layer(name=\"predicate_answer_scores\")(predicate_match_scores)\n\n ### compute overall matches ###\n overall_match_embedding = concatenate([subject_match_embeddings, predicate_match_embeddings])\n overall_match_embedding = BetterTimeDistributed(\n Dense(conf.match_embedding_size, activation=\"selu\", kernel_initializer=\"he_normal\"))(\n overall_match_embedding)\n overall_match_embedding = Dropout(conf.dropout)(overall_match_embedding)\n\n overall_match_scores = BetterTimeDistributed(Dense(1, activation=\"linear\"))(overall_match_embedding)\n overall_match_scores = Squeeze()(overall_match_scores)\n\n overall_match_scores = Activation(\"softmax\")(overall_match_scores)\n\n answer_scores = Layer(name=\"answer_scores\")(overall_match_scores)\n\n #### 3 OUTPUTS -: pair, subject and predicate alone\n outputs = [answer_scores, subject_answer_scores, predicate_answer_scores]\n\n model = Model(inputs=inputs, outputs=outputs)\n model.compile(Adam(), {\"answer_scores\": \"categorical_crossentropy\",\n \"predicate_answer_scores\": \"binary_crossentropy\",\n \"subject_answer_scores\": \"binary_crossentropy\"},\n metrics=[\"accuracy\", \"crossentropy\"],\n loss_weights={\"answer_scores\": conf.answer_loss_weight,\n \"predicate_answer_scores\": conf.predicate_answer_loss_weight,\n \"subject_answer_scores\": conf.subject_answer_loss_weight})\n\n #### SINGLE OUTPUT : CandidatePAIR Scores\n else:\n ### compute overall matches ###\n overall_match_embedding = concatenate([subject_match_embeddings, predicate_match_embeddings])\n overall_match_embedding = BetterTimeDistributed(\n Dense(conf.match_embedding_size, activation=\"selu\", kernel_initializer=\"he_normal\"))(\n overall_match_embedding)\n overall_match_embedding = Dropout(conf.dropout)(overall_match_embedding)\n\n overall_match_scores = BetterTimeDistributed(Dense(1, activation=\"linear\"))(overall_match_embedding)\n overall_match_scores = Squeeze()(overall_match_scores)\n\n overall_match_scores = Activation(\"softmax\")(overall_match_scores)\n\n answer_scores = Layer(name=\"answer_scores\")(overall_match_scores)\n\n outputs = [answer_scores]\n\n model = Model(inputs=inputs, outputs=outputs)\n model.compile(Adam(), \"categorical_crossentropy\", metrics=[\"accuracy\", \"crossentropy\"])\n\n return model\n\n\ndef simple_joint_qa_predicate_model(conf, res, **kwargs):\n ### INPUT LIST####\n inputs = []\n\n ### setup encoders ###\n word_embedding_layer = Embedding(input_dim=conf.word_vocab_size, output_dim=conf.word_embedding_size,\n weights=[res.word_embeddings.W], name=\"word_embeddings\")\n\n\n\n if conf.predicate_encoder_embedding_type == \"word\":\n question_token_input = Input(shape=(None,), dtype='int32', name='question_token_input')\n inputs.append(question_token_input)\n token_embeddings = word_embedding_layer(question_token_input)\n\n resulting_embeddings = token_embeddings\n\n elif conf.predicate_encoder_embedding_type == \"char\":\n question_char_input = Input(shape=(None, None), dtype='int32', name='question_char_input')\n inputs.append(question_char_input)\n char_sequence_encoder = get_text_encoder(vocab_size=conf.char_vocab_size,\n embedding_size=conf.char_embedding_size,\n kernel_size=conf.question_char_kernel_size,\n depth=conf.question_char_cnn_depth, dropout=conf.dropout,\n layer_type=conf.layer_type)\n\n token_char_embeddings = BetterTimeDistributed(char_sequence_encoder)(question_char_input)\n\n resulting_embeddings = token_char_embeddings\n\n ### combination OF WORD and CHAR embeddings\n else:\n question_char_input = Input(shape=(None, None), dtype='int32', name='question_char_input')\n question_token_input = Input(shape=(None,), dtype='int32', name='question_token_input')\n\n ## add to inputs\n inputs.append(question_char_input)\n inputs.append(question_token_input)\n\n char_sequence_encoder = get_text_encoder(vocab_size=conf.char_vocab_size,\n embedding_size=conf.char_embedding_size,\n kernel_size=conf.question_char_kernel_size,\n depth=conf.question_char_cnn_depth, dropout=conf.dropout,\n layer_type=conf.layer_type)\n\n token_char_embeddings = BetterTimeDistributed(char_sequence_encoder)(question_char_input)\n\n token_embeddings = word_embedding_layer(question_token_input)\n\n ## concatenate\n resulting_embeddings = concatenate([token_embeddings, token_char_embeddings])\n\n if \"att\" in conf.predicate_encoder_embedding_type:\n relative_position_input = Input(shape=(None,), dtype='int32', name='relative_position_input')\n\n inputs.append(relative_position_input)\n\n relative_position_embeddings = Embedding(input_dim=conf.subject_position_max_distance * 2 + 1,\n output_dim=conf.distance_embedding_size, name=\"distance_embeddings\")(\n relative_position_input)\n\n text_embedding = apply_sequence_attention_model(conf.layer_type, input_sequence=resulting_embeddings,\n relative_position_embeddings=relative_position_embeddings,\n embedding_size=conf.predicate_embedding_size,\n depth=conf.predicate_embedding_depth,\n kernel_size=conf.predicate_embedding_kernel_size,\n dropout=conf.dropout)\n else:\n text_embedding = apply_sequence_model(conf.layer_type, input_sequence=resulting_embeddings,\n embedding_size=conf.predicate_embedding_size,\n depth=conf.predicate_embedding_depth,\n kernel_size=conf.predicate_embedding_kernel_size, dropout=conf.dropout)\n\n\n ### add DROPOUT\n text_embedding = Dropout(conf.dropout)(text_embedding)\n\n #### Different outputs based on predicate_model_type ####\n if conf.predicate_model_type == \"predict_all_predicates\":\n answer_scores = Dense(conf.predicate_vocab_size, activation=\"softmax\")(text_embedding)\n answer_scores = Layer(name=\"answer_scores\")(answer_scores)\n # loss_function = \"categorical_crossentropy\"\n # metrics = \"accuracy\"\n\n elif conf.predicate_model_type == \"predict_graph_embedding\":\n answer_scores = Dense(conf.graph_embedding_size, activation=\"selu\")(text_embedding)\n answer_scores = Dense(conf.graph_embedding_size, activation=\"linear\")(answer_scores)\n answer_scores = Layer(name=\"answer_scores\")(answer_scores)\n # loss_function = \"cosine_proximity\"\n # metrics = \"cosine_proximity\"\n else:\n #### BINARY classification for candidate predicate\n\n graph_embedding_layer = Embedding(input_dim=conf.graph_vocab_size, output_dim=conf.graph_embedding_size,\n weights=[res.graph_embeddings.W], name=\"graph_embeddings\")\n\n predicate_graph_embedding_input = Input(shape=(None,), dtype='int32', name='predicate_graph_embedding_input')\n\n inputs.append(predicate_graph_embedding_input)\n\n predicate_graph_embedding = graph_embedding_layer(predicate_graph_embedding_input)\n predicate_graph_embedding = ElementAt(0)(predicate_graph_embedding)\n\n concatenated = concatenate([predicate_graph_embedding, text_embedding])\n\n concatenated_layer_output = Dense(200, activation=\"selu\")(concatenated)\n answer_scores = Dense(1, activation=\"sigmoid\")(concatenated_layer_output)\n answer_scores = Layer(name=\"answer_scores\")(answer_scores)\n # loss_function = \"binary_crossentropy\"\n # metrics = \"accuracy\"\n\n outputs = [answer_scores]\n\n model = Model(inputs=inputs, outputs=outputs)\n\n # if conf.gpus > 1:\n # model = multi_gpu_model(model, gpus=conf.gpus)\n\n model.compile(Adam(), conf.predicate_model_loss_function, metrics=[conf.predicate_model_metrics])\n\n return model\n", "repo_name": "ag-sc/SimpleQA", "sub_path": "src/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 22709, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "keras.backend.mean", "line_number": 15, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 15, "usage_type": "name"}, {"api_name": "keras.backend.maximum", "line_number": 19, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 19, "usage_type": "name"}, {"api_name": "keras.backend.maximum", "line_number": 28, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 28, "usage_type": "name"}, {"api_name": "keras.backend.sum", "line_number": 30, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 30, "usage_type": "name"}, {"api_name": "keras.layers.Bidirectional", "line_number": 65, "usage_type": "call"}, {"api_name": "keras.layers.GRU", "line_number": 65, "usage_type": "call"}, {"api_name": "keras.layers.Convolution1D", "line_number": 69, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 71, "usage_type": "call"}, {"api_name": "keras.layers.GlobalMaxPooling1D", "line_number": 74, "usage_type": "call"}, {"api_name": "keras.layers.Bidirectional", "line_number": 93, "usage_type": "call"}, {"api_name": "keras.layers.GRU", "line_number": 94, "usage_type": "call"}, {"api_name": "keras.layers.concatenate", "line_number": 97, "usage_type": "call"}, {"api_name": "keras.layers.Convolution1D", "line_number": 99, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 101, "usage_type": "call"}, {"api_name": "keras.layers.GlobalMaxPooling1D", "line_number": 104, "usage_type": "call"}, {"api_name": "custom_layers.ElementAt", "line_number": 106, "usage_type": "call"}, {"api_name": "custom_layers.ElementAt", "line_number": 107, "usage_type": "call"}, {"api_name": "keras.layers.concatenate", "line_number": 109, "usage_type": "call"}, {"api_name": "custom_layers.RepeatToMatch", "line_number": 111, "usage_type": "call"}, {"api_name": "keras.layers.concatenate", "line_number": 112, "usage_type": "call"}, {"api_name": "custom_layers.AttentionWeightedAverage", "line_number": 115, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 120, "usage_type": "call"}, {"api_name": "keras.layers.Embedding", "line_number": 123, "usage_type": "call"}, {"api_name": "keras.models.Model", "line_number": 133, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 190, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 191, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 193, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 194, "usage_type": "call"}, {"api_name": "keras.layers.Embedding", "line_number": 203, "usage_type": "call"}, {"api_name": "custom_layers.BetterTimeDistributed", "line_number": 228, "usage_type": "call"}, {"api_name": "custom_layers.BetterTimeDistributed", "line_number": 229, "usage_type": "call"}, {"api_name": "custom_layers.RepeatToMatch", "line_number": 232, "usage_type": "call"}, {"api_name": "custom_layers.RepeatToMatch", "line_number": 233, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 238, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 241, "usage_type": "call"}, {"api_name": "keras.layers.Embedding", "line_number": 248, "usage_type": "call"}, {"api_name": "keras.layers.concatenate", "line_number": 254, "usage_type": "call"}, {"api_name": "keras.layers.concatenate", "line_number": 257, "usage_type": "call"}, {"api_name": "keras.layers.concatenate", "line_number": 261, "usage_type": "call"}, {"api_name": "keras.layers.concatenate", "line_number": 262, "usage_type": "call"}, {"api_name": "custom_layers.BetterTimeDistributed", "line_number": 264, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 265, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 266, "usage_type": "call"}, {"api_name": "custom_layers.BetterTimeDistributed", "line_number": 268, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 269, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 270, "usage_type": "call"}, {"api_name": "custom_layers.BetterTimeDistributed", "line_number": 274, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 274, "usage_type": "call"}, {"api_name": "custom_layers.Squeeze", "line_number": 275, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 276, "usage_type": "call"}, {"api_name": "keras.engine.Layer", "line_number": 277, "usage_type": "call"}, {"api_name": "custom_layers.BetterTimeDistributed", "line_number": 280, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 280, "usage_type": "call"}, {"api_name": "custom_layers.Squeeze", "line_number": 281, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 282, "usage_type": "call"}, {"api_name": "keras.engine.Layer", "line_number": 283, "usage_type": "call"}, {"api_name": "keras.layers.concatenate", "line_number": 286, "usage_type": "call"}, {"api_name": "custom_layers.BetterTimeDistributed", "line_number": 287, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 288, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 290, "usage_type": "call"}, {"api_name": "custom_layers.BetterTimeDistributed", "line_number": 292, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 292, "usage_type": "call"}, {"api_name": "custom_layers.Squeeze", "line_number": 293, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 295, "usage_type": "call"}, {"api_name": "keras.engine.Layer", "line_number": 297, "usage_type": "call"}, {"api_name": "keras.models.Model", "line_number": 302, "usage_type": "call"}, {"api_name": "keras.optimizers.Adam", "line_number": 303, "usage_type": "call"}, {"api_name": "keras.layers.concatenate", "line_number": 314, "usage_type": "call"}, {"api_name": "custom_layers.BetterTimeDistributed", "line_number": 315, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 316, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 318, "usage_type": "call"}, {"api_name": "custom_layers.BetterTimeDistributed", "line_number": 320, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 320, "usage_type": "call"}, {"api_name": "custom_layers.Squeeze", "line_number": 321, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 323, "usage_type": "call"}, {"api_name": "keras.engine.Layer", "line_number": 325, "usage_type": "call"}, {"api_name": "keras.models.Model", "line_number": 329, "usage_type": "call"}, {"api_name": "keras.optimizers.Adam", "line_number": 330, "usage_type": "call"}, {"api_name": "keras.layers.Embedding", "line_number": 340, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 346, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 353, "usage_type": "call"}, {"api_name": "custom_layers.BetterTimeDistributed", "line_number": 361, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 367, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 368, "usage_type": "call"}, {"api_name": "custom_layers.BetterTimeDistributed", "line_number": 380, "usage_type": "call"}, {"api_name": "keras.layers.concatenate", "line_number": 385, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 388, "usage_type": "call"}, {"api_name": "keras.layers.Embedding", "line_number": 392, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 410, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 414, "usage_type": "call"}, {"api_name": "keras.engine.Layer", "line_number": 415, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 420, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 421, "usage_type": "call"}, {"api_name": "keras.engine.Layer", "line_number": 422, "usage_type": "call"}, {"api_name": "keras.layers.Embedding", "line_number": 428, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 431, "usage_type": "call"}, {"api_name": "custom_layers.ElementAt", "line_number": 436, "usage_type": "call"}, {"api_name": "keras.layers.concatenate", "line_number": 438, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 440, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 441, "usage_type": "call"}, {"api_name": "keras.engine.Layer", "line_number": 442, "usage_type": "call"}, {"api_name": "keras.models.Model", "line_number": 448, "usage_type": "call"}, {"api_name": "keras.optimizers.Adam", "line_number": 453, "usage_type": "call"}]} +{"seq_id": "8941011676", "text": "import torch\n\nfrom megatron import get_args, print_rank_last\nfrom megatron import mpu\nfrom megatron.model.enums import AttnMaskType\nfrom megatron.model.bert_model import bert_extended_attention_mask, bert_position_ids\nfrom megatron.model.language_model import get_language_model\nfrom megatron.model.utils import get_linear_layer\nfrom megatron.model.utils import init_method_normal\nfrom megatron.model.utils import scaled_init_method_normal\nfrom .module import MegatronModule\n\n\nclass Classification(MegatronModule):\n\n def __init__(self,\n num_classes,\n num_tokentypes=2,\n pre_process=True,\n post_process=True):\n super(Classification, self).__init__(share_word_embeddings=False)\n args = get_args()\n\n self.num_classes = num_classes\n self.pre_process = pre_process\n self.post_process = post_process\n init_method = init_method_normal(args.init_method_std)\n\n self.language_model, self._language_model_key = get_language_model(\n num_tokentypes=num_tokentypes,\n add_pooler=True,\n encoder_attn_mask_type=AttnMaskType.padding,\n init_method=init_method,\n scaled_init_method=scaled_init_method_normal(args.init_method_std,\n args.num_layers),\n pre_process=self.pre_process,\n post_process=self.post_process)\n\n # Multi-choice head.\n if self.post_process:\n self.classification_dropout = torch.nn.Dropout(args.hidden_dropout)\n self.classification_head = get_linear_layer(args.hidden_size,\n self.num_classes,\n init_method)\n self._classification_head_key = 'classification_head'\n\n def set_input_tensor(self, input_tensor):\n \"\"\"See megatron.model.transformer.set_input_tensor()\"\"\"\n self.language_model.set_input_tensor(input_tensor)\n\n def forward(self, model_input, attention_mask, tokentype_ids=None):\n\n extended_attention_mask = bert_extended_attention_mask(attention_mask)\n input_ids = model_input\n position_ids = bert_position_ids(input_ids)\n\n lm_output = self.language_model(\n input_ids,\n position_ids,\n extended_attention_mask,\n tokentype_ids=tokentype_ids\n )\n\n if self.post_process:\n _, pooled_output = lm_output\n classification_output = self.classification_dropout(pooled_output)\n classification_logits = self.classification_head(classification_output)\n\n # Reshape back to separate choices.\n classification_logits = classification_logits.view(-1, self.num_classes)\n\n return classification_logits\n return lm_output\n\n def state_dict_for_save_checkpoint(self, destination=None, prefix='',\n keep_vars=False):\n \"\"\"For easy load when model is combined with other heads,\n add an extra key.\"\"\"\n\n state_dict_ = {}\n state_dict_[self._language_model_key] \\\n = self.language_model.state_dict_for_save_checkpoint(\n destination, prefix, keep_vars)\n if self.post_process:\n state_dict_[self._classification_head_key] \\\n = self.classification_head.state_dict(\n destination, prefix, keep_vars)\n return state_dict_\n\n def load_state_dict(self, state_dict, strict=True):\n \"\"\"Customized load.\"\"\"\n\n self.language_model.load_state_dict(\n state_dict[self._language_model_key], strict=strict)\n if self.post_process:\n if self._classification_head_key in state_dict:\n self.classification_head.load_state_dict(\n state_dict[self._classification_head_key], strict=strict)\n else:\n print_rank_last('***WARNING*** could not find {} in the checkpoint, '\n 'initializing to random'.format(\n self._classification_head_key))\n", "repo_name": "mlcommons/training", "sub_path": "large_language_model/megatron-lm/megatron/model/classification.py", "file_name": "classification.py", "file_ext": "py", "file_size_in_byte": 4184, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1501, "dataset": "github-code", "pt": "24", "api": [{"api_name": "module.MegatronModule", "line_number": 14, "usage_type": "name"}, {"api_name": "megatron.get_args", "line_number": 22, "usage_type": "call"}, {"api_name": "megatron.model.utils.init_method_normal", "line_number": 27, "usage_type": "call"}, {"api_name": "megatron.model.language_model.get_language_model", "line_number": 29, "usage_type": "call"}, {"api_name": "megatron.model.enums.AttnMaskType.padding", "line_number": 32, "usage_type": "attribute"}, {"api_name": "megatron.model.enums.AttnMaskType", "line_number": 32, "usage_type": "name"}, {"api_name": "megatron.model.utils.scaled_init_method_normal", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.nn.Dropout", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 41, "usage_type": "attribute"}, {"api_name": "megatron.model.utils.get_linear_layer", "line_number": 42, "usage_type": "call"}, {"api_name": "megatron.model.bert_model.bert_extended_attention_mask", "line_number": 53, "usage_type": "call"}, {"api_name": "megatron.model.bert_model.bert_position_ids", "line_number": 55, "usage_type": "call"}, {"api_name": "megatron.print_rank_last", "line_number": 100, "usage_type": "call"}]} +{"seq_id": "71845732863", "text": "from rest_framework.authentication import TokenAuthentication\nfrom rest_framework import HTTP_HEADER_ENCODING, exceptions\n\n\n\nclass SyncClientAuthentication(TokenAuthentication):\n def __init__(self):\n from .client import Client\n self.client = Client()\n super(SyncClientAuthentication, self).__init__()\n\n def authenticate_credentials(self, key):\n if key:\n is_valid, client_errors = self.client.run_validation(key)\n if is_valid:\n return super(SyncClientAuthentication, self).authenticate_credentials(key)\n else:\n raise exceptions.AuthenticationFailed(client_errors)\n else:\n return exceptions.AuthenticationFailed('Authorization token not set')\n", "repo_name": "letsolexandr/django-single-auth-client", "sub_path": "single_sync/sync_client/authentication.py", "file_name": "authentication.py", "file_ext": "py", "file_size_in_byte": 757, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "rest_framework.authentication.TokenAuthentication", "line_number": 6, "usage_type": "name"}, {"api_name": "client.Client", "line_number": 9, "usage_type": "call"}, {"api_name": "rest_framework.exceptions.AuthenticationFailed", "line_number": 18, "usage_type": "call"}, {"api_name": "rest_framework.exceptions", "line_number": 18, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.AuthenticationFailed", "line_number": 20, "usage_type": "call"}, {"api_name": "rest_framework.exceptions", "line_number": 20, "usage_type": "name"}]} +{"seq_id": "36895911218", "text": "from django.contrib import admin\nfrom .models import Asset, Task, Worker, Allocation\nfrom uuid import UUID\n# Register your models here.\n# admin.site.register([Asset, Task, Worker, Allocation])\n@admin.register(Asset, Task, Worker)\nclass Admin(admin.ModelAdmin):\n list_display = ('name', 'id')\n\ndef allocation_details(obj):\n worker = Worker.objects.filter(id = UUID(str(obj.worker_id))).values()[0]['name']\n task = Task.objects.filter(id = UUID(str(obj.task_id))).values()[0]['name']\n asset = Asset.objects.filter(id = UUID(str(obj.asset_id))).values()[0]['name']\n return worker+' - '+task+' - '+asset\n@admin.register(Allocation)\nclass AllocAdmin(admin.ModelAdmin):\n list_display = (allocation_details,)\n", "repo_name": "mihirkawatra/housekeeping-portal", "sub_path": "household/admin.py", "file_name": "admin.py", "file_ext": "py", "file_size_in_byte": 720, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.contrib.admin.ModelAdmin", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 7, "usage_type": "name"}, {"api_name": "django.contrib.admin.register", "line_number": 6, "usage_type": "call"}, {"api_name": "models.Asset", "line_number": 6, "usage_type": "argument"}, {"api_name": "models.Task", "line_number": 6, "usage_type": "argument"}, {"api_name": "models.Worker", "line_number": 6, "usage_type": "argument"}, {"api_name": "django.contrib.admin", "line_number": 6, "usage_type": "name"}, {"api_name": "models.Worker.objects.filter", "line_number": 11, "usage_type": "call"}, {"api_name": "models.Worker.objects", "line_number": 11, "usage_type": "attribute"}, {"api_name": "models.Worker", "line_number": 11, "usage_type": "name"}, {"api_name": "uuid.UUID", "line_number": 11, "usage_type": "call"}, {"api_name": "models.Task.objects.filter", "line_number": 12, "usage_type": "call"}, {"api_name": "models.Task.objects", "line_number": 12, "usage_type": "attribute"}, {"api_name": "models.Task", "line_number": 12, "usage_type": "name"}, {"api_name": "uuid.UUID", "line_number": 12, "usage_type": "call"}, {"api_name": "models.Asset.objects.filter", "line_number": 13, "usage_type": "call"}, {"api_name": "models.Asset.objects", "line_number": 13, "usage_type": "attribute"}, {"api_name": "models.Asset", "line_number": 13, "usage_type": "name"}, {"api_name": "uuid.UUID", "line_number": 13, "usage_type": "call"}, {"api_name": "django.contrib.admin.ModelAdmin", "line_number": 16, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 16, "usage_type": "name"}, {"api_name": "django.contrib.admin.register", "line_number": 15, "usage_type": "call"}, {"api_name": "models.Allocation", "line_number": 15, "usage_type": "argument"}, {"api_name": "django.contrib.admin", "line_number": 15, "usage_type": "name"}]} +{"seq_id": "44305486722", "text": "from __future__ import print_function # __future__模块可以引用未来版本python库中的函数,其实我的版本已经是3.x,所以没有必要走这一步\nfrom numpy import *\nimport operator\nfrom os import listdir\nfrom collections import Counter\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfr=open(\"E:\\MachineLearning\\KNN\\dataset\\datingTestSet2.txt\")\nnumberOfLines=len(fr.readlines())\nfr.seek(0)\nreturnMat=zeros((numberOfLines,3))\nclassLabelVector=[]\nindex=0\nfor line in fr.readlines():\n line=line.strip()\n listFromLine=line.split('\\t')\n returnMat[index,:]=listFromLine[0:3]\n classLabelVector.append(int(listFromLine[-1])) # classLabelVector 与 returnMat 一一对应,前者为所属标签,后者为具体数据\n index+=1\n\nlabels=classLabelVector\n\nplt.figure(figsize=(8, 5), dpi=80)\naxes = plt.subplot(111)\n# 将三类数据分别取出来\n# x轴代表飞行的里程数\n# y轴代表玩视频游戏的百分比\ntype1_x = []\ntype1_y = []\ntype2_x = []\ntype2_y = []\ntype3_x = []\ntype3_y = []\n\nfor i in range(len(labels)):\n if labels[i] == 1: # 不喜欢\n type1_x.append(returnMat[i][0])\n type1_y.append(returnMat[i][1])\n\n if labels[i] == 2: # 魅力一般\n type2_x.append(returnMat[i][0])\n type2_y.append(returnMat[i][1])\n\n if labels[i] == 3: # 极具魅力\n type3_x.append(returnMat[i][0])\n type3_y.append(returnMat[i][1])\n\ntype1 = axes.scatter(type1_x, type1_y, s=20, c='red')\ntype2 = axes.scatter(type2_x, type2_y, s=40, c='green')\ntype3 = axes.scatter(type3_x, type3_y, s=50, c='blue')\n\nplt.xlabel('Miles earned per year')\nplt.ylabel('Percentage of events spent playing video games')\naxes.legend((type1, type2, type3), (u'dislike', u'Charismatic', u'Very attractive'), loc=2,)\n\nplt.show()\n\n\"\"\"\n下面进行归一化操作\n公式:线性转换: newValue=(oldValue-min)/(max-min) max和min为该组数据集中的最大最小特征值\n 对数转换: y=log10(x)\n 反余切转换:y=arctan(x)*2/PI \n\"\"\"\n\nnormMat=zeros((numberOfLines,3))\nfor i in [0,1,2]:\n max=returnMat[:,i].max()\n min=returnMat[:,i].min()\n for j in range(1000):\n normMat[j,i]=(returnMat[j,i]-min)/(max-min)\n# done\n\n\"\"\"\n对于每一个在数据集中的数据点:\n 计算目标的数据点(需要分类的数据点)与该数据点的距离\n 将距离排序:从小到大\n 选取前K个最短距离\n 选取这K个中最多的分类类别\n 返回该类别来作为目标数据点的预测值\n\"\"\"\n\ninx=[0.40166314, 0.56719748, 0.52034602] # 作为输入的样本\ndataSetSize=normMat.shape[0]\ndiffMat = tile(inx, (dataSetSize,1))-normMat\nsqDiffMat = diffMat**2\ndistances=(sqDiffMat.sum(axis=1))**0.5\nsortedDistIndicies = distances.argsort() # argsort()函数是将x中的元素从小到大排列,提取其对应的index(索引号),所以并不会影响对应的label的值\n# k取5\nclassCount={}\nfor i in range(5):\n voteIlabel = labels[sortedDistIndicies[i]]\n classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1\nsortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)\n", "repo_name": "xiuzheDorothy/DL_exercise", "sub_path": "KNN/test_for.py", "file_name": "test_for.py", "file_ext": "py", "file_size_in_byte": 3129, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "matplotlib.pyplot.figure", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 53, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 53, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}, {"api_name": "operator.itemgetter", "line_number": 94, "usage_type": "call"}]} +{"seq_id": "73188657983", "text": "#!/usr/bin/python\n#-*- encoding: utf-8 -*-\n\nfrom zope.i18n import translate\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\nfrom plone.app.layout.viewlets.common import TitleViewlet\nfrom plone.app.layout.viewlets.common import LogoViewlet\nfrom plone.app.layout.links.viewlets import FaviconViewlet\n\n\nclass TitleViewlet(TitleViewlet):\n \"\"\"Custom Title\n \"\"\"\n def update(self):\n super(TitleViewlet, self).update()\n self.site_title = u\"%s — %s\" % (\n translate('portal_title',\n domain='plone',\n context=self.request,\n default='TNCR GIS'),\n self.page_title)\n\n\nclass FaviconViewlet(FaviconViewlet):\n \"\"\"Custom Favicon\n \"\"\"\n _template = ViewPageTemplateFile('favicon.pt')\n\n\nclass LogoViewlet(LogoViewlet):\n \"\"\"Custom Logo\n \"\"\"\n def update(self):\n super(LogoViewlet, self).update()\n self.logo_tag = '\"Logo'\n\n", "repo_name": "l34marr/tncr.theme", "sub_path": "src/tncr/theme/browser/viewlets.py", "file_name": "viewlets.py", "file_ext": "py", "file_size_in_byte": 1051, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "zope.i18n.translate", "line_number": 17, "usage_type": "call"}, {"api_name": "Products.Five.browser.pagetemplatefile.ViewPageTemplateFile", "line_number": 27, "usage_type": "call"}]} +{"seq_id": "27830003279", "text": "from selenium import webdriver\nfrom bs4 import BeautifulSoup\nimport time\n\ndriver = webdriver.Chrome()\n\ndriver.get(\"https://localprod.pandateacher.com/python-manuscript/hello-spiderman/\")\nprint(\"页面请求成功\")\ntime.sleep(1)\n\nprint(\"点击提交按钮,进入禅页面\")\ndriver.find_element_by_css_selector(\"#div2 .sub\").click()\ntime.sleep(1)\n\npageSource = driver.page_source\nsoup = BeautifulSoup(pageSource, \"html.parser\")\n# print(soup)\ncontents = soup.find_all(class_=\"content\")\nfor c in contents:\n print(type(c))\n print(c.find(id=\"p\").text)\n\ntime.sleep(2)\ndriver.close()\nprint(\"浏览器关闭\")\n", "repo_name": "picktsh/python", "sub_path": "code2/day09/练习2_python禅2selenium&beautifulsoup.py", "file_name": "练习2_python禅2selenium&beautifulsoup.py", "file_ext": "py", "file_size_in_byte": 608, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "selenium.webdriver.Chrome", "line_number": 5, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 5, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 9, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 13, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 16, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 23, "usage_type": "call"}]} +{"seq_id": "13970561162", "text": "from bearlibterminal import terminal\nfrom loguru import logger\n\nfrom utilities import configUtilities, armourManagement, common, display, input_handlers, mobileHelp\n\n\ndef shopkeeper_armour(gameworld, shopkeeper_id):\n game_config = configUtilities.load_config()\n selected_menu_option = 0\n flavour_column_text = []\n player_entity = mobileHelp.MobileUtilities.get_player_entity(gameworld=gameworld)\n player_names = mobileHelp.MobileUtilities.get_mobile_name_details(gameworld=gameworld, entity=player_entity)\n player_first_name = player_names[0]\n\n mobileHelp.MobileUtilities.clear_talk_to_me_flag(gameworld=gameworld, target_entity=shopkeeper_id)\n mobileHelp.MobileUtilities.set_spoken_to_before_flag_to_true(gameworld=gameworld, target_entity=shopkeeper_id)\n\n dialog_frame_start_x = configUtilities.get_config_value_as_integer(configfile=game_config,\n section='gui', parameter='DIALOG_FRAME_START_X')\n dialog_frame_start_y = configUtilities.get_config_value_as_integer(configfile=game_config,\n section='gui', parameter='DIALOG_FRAME_START_Y')\n dialog_frame_width = configUtilities.get_config_value_as_integer(configfile=game_config,\n section='gui', parameter='DIALOG_FRAME_WIDTH')\n\n common.CommonUtils.draw_dialog_ui(gameworld=gameworld, game_config=game_config, entity_speaking=shopkeeper_id)\n\n armour_details, as_prefix_list, px_att_bonus, px_att_name, px_flavour = armourManagement.ArmourUtilities.get_all_armour_modifiers()\n\n as_display_name = armour_details[0]\n as_material = armour_details[1]\n flavour_column_text.append(px_flavour)\n\n starter_text = \"Ahhh if it isn't $1\"\n return_text = common.CommonUtils.replace_value_in_event(event_string=starter_text, par1=player_first_name)\n intro_text = return_text + \", and, I see you're wearing some \" + as_material + ' ' + as_display_name + ' armour, ' + 'tell me, what kind of modifier would you like adding?'\n\n menu_options = as_prefix_list\n max_menu_option = len(menu_options) - 1\n\n # armour column titles\n flavour_colour_string = '[color=SHOPKEEPER_ARMOUR_COLUMN_FLAVOUR]'\n flavour_coloumn_one_title = 'Flavour'\n flavour_column_one_string = flavour_colour_string + flavour_coloumn_one_title\n\n valid_event = False\n while not valid_event:\n\n # intro text\n terminal.print_(x=dialog_frame_start_x + 2, y=dialog_frame_start_y + 2, width=dialog_frame_width - 5,\n s=intro_text)\n\n display.pointy_vertical_menu(header='', menu_options=menu_options, menu_start_x=dialog_frame_start_x + 3,\n menu_start_y=dialog_frame_start_y + 9, blank_line=True, selected_option=selected_menu_option)\n\n # display flavour columns\n terminal.printf(x=dialog_frame_start_x + 15, y=dialog_frame_start_y + 8, s=flavour_column_one_string)\n\n # display attribute to be modified\n fg = \"[color=SHOPKEEPER_ARMOUR_ATTRIBUTE_FLAVOUR]\"\n\n # display flavour text\n display.coloured_list(list_options=flavour_column_text[0],\n list_x=dialog_frame_start_x + 17, list_y=dialog_frame_start_y + 9,\n selected_option='nothing', blank_line=True, fg=fg)\n\n # blit the console\n terminal.refresh()\n\n event_to_be_processed, event_action = input_handlers.handle_game_keys()\n if event_action == 'quit':\n valid_event = True\n if event_action in ('up', 'down'):\n selected_menu_option = common.CommonUtils.move_menu_selection(event_action=event_action,\n selected_menu_option=selected_menu_option,\n max_menu_option=max_menu_option)\n if event_action == 'enter':\n valid_event = True\n # apply shopkeeper bonus\n logger.debug('Armour modifier chosen is {}', as_prefix_list[selected_menu_option])\n logger.debug('Attribute to be modified is {}', px_att_name[selected_menu_option])\n logger.debug('Attribute bonus is {}', px_att_bonus[selected_menu_option])\n\n armour_set = armourManagement.ArmourUtilities.create_full_armour_set(gameworld=gameworld, prefix=as_prefix_list[selected_menu_option],\n armourset='Embroided')\n armourManagement.ArmourUtilities.equip_full_set_of_armour(gameworld=gameworld, entity=player_entity, armourset=armour_set)\n\n armourManagement.ArmourUtilities.apply_major_attribute_bonus_to_full_armourset(gameworld=gameworld,\n player_entity=player_entity,\n attribute_name=as_prefix_list[selected_menu_option],\n attribute_bonus=px_att_bonus[\n selected_menu_option])\n\n armourManagement.ArmourUtilities.set_mobile_derived_armour_attribute(gameworld=gameworld, entity=player_entity)\n mobileHelp.MobileUtilities.set_mobile_derived_attributes(gameworld=gameworld, entity=player_entity)\n", "repo_name": "devonps/talesfromticronem", "sub_path": "ui/shopkeeper_armour.py", "file_name": "shopkeeper_armour.py", "file_ext": "py", "file_size_in_byte": 5482, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "24", "api": [{"api_name": "utilities.configUtilities.load_config", "line_number": 8, "usage_type": "call"}, {"api_name": "utilities.configUtilities", "line_number": 8, "usage_type": "name"}, {"api_name": "utilities.mobileHelp.MobileUtilities.get_player_entity", "line_number": 11, "usage_type": "call"}, {"api_name": "utilities.mobileHelp.MobileUtilities", "line_number": 11, "usage_type": "attribute"}, {"api_name": "utilities.mobileHelp", "line_number": 11, "usage_type": "name"}, {"api_name": "utilities.mobileHelp.MobileUtilities.get_mobile_name_details", "line_number": 12, "usage_type": "call"}, {"api_name": "utilities.mobileHelp.MobileUtilities", "line_number": 12, "usage_type": "attribute"}, {"api_name": "utilities.mobileHelp", "line_number": 12, "usage_type": "name"}, {"api_name": "utilities.mobileHelp.MobileUtilities.clear_talk_to_me_flag", "line_number": 15, "usage_type": "call"}, {"api_name": "utilities.mobileHelp.MobileUtilities", "line_number": 15, "usage_type": "attribute"}, {"api_name": "utilities.mobileHelp", "line_number": 15, "usage_type": "name"}, {"api_name": "utilities.mobileHelp.MobileUtilities.set_spoken_to_before_flag_to_true", "line_number": 16, "usage_type": "call"}, {"api_name": "utilities.mobileHelp.MobileUtilities", "line_number": 16, "usage_type": "attribute"}, {"api_name": "utilities.mobileHelp", "line_number": 16, "usage_type": "name"}, {"api_name": "utilities.configUtilities.get_config_value_as_integer", "line_number": 18, "usage_type": "call"}, {"api_name": "utilities.configUtilities", "line_number": 18, "usage_type": "name"}, {"api_name": "utilities.configUtilities.get_config_value_as_integer", "line_number": 20, "usage_type": "call"}, {"api_name": "utilities.configUtilities", "line_number": 20, "usage_type": "name"}, {"api_name": "utilities.configUtilities.get_config_value_as_integer", "line_number": 22, "usage_type": "call"}, {"api_name": "utilities.configUtilities", "line_number": 22, "usage_type": "name"}, {"api_name": "utilities.common.CommonUtils.draw_dialog_ui", "line_number": 25, "usage_type": "call"}, {"api_name": "utilities.common.CommonUtils", "line_number": 25, "usage_type": "attribute"}, {"api_name": "utilities.common", "line_number": 25, "usage_type": "name"}, {"api_name": "utilities.armourManagement.ArmourUtilities.get_all_armour_modifiers", "line_number": 27, "usage_type": "call"}, {"api_name": "utilities.armourManagement.ArmourUtilities", "line_number": 27, "usage_type": "attribute"}, {"api_name": "utilities.armourManagement", "line_number": 27, "usage_type": "name"}, {"api_name": "utilities.common.CommonUtils.replace_value_in_event", "line_number": 34, "usage_type": "call"}, {"api_name": "utilities.common.CommonUtils", "line_number": 34, "usage_type": "attribute"}, {"api_name": "utilities.common", "line_number": 34, "usage_type": "name"}, {"api_name": "bearlibterminal.terminal.print_", "line_number": 49, "usage_type": "call"}, {"api_name": "bearlibterminal.terminal", "line_number": 49, "usage_type": "name"}, {"api_name": "utilities.display.pointy_vertical_menu", "line_number": 52, "usage_type": "call"}, {"api_name": "utilities.display", "line_number": 52, "usage_type": "name"}, {"api_name": "bearlibterminal.terminal.printf", "line_number": 56, "usage_type": "call"}, {"api_name": "bearlibterminal.terminal", "line_number": 56, "usage_type": "name"}, {"api_name": "utilities.display.coloured_list", "line_number": 62, "usage_type": "call"}, {"api_name": "utilities.display", "line_number": 62, "usage_type": "name"}, {"api_name": "bearlibterminal.terminal.refresh", "line_number": 67, "usage_type": "call"}, {"api_name": "bearlibterminal.terminal", "line_number": 67, "usage_type": "name"}, {"api_name": "utilities.input_handlers.handle_game_keys", "line_number": 69, "usage_type": "call"}, {"api_name": "utilities.input_handlers", "line_number": 69, "usage_type": "name"}, {"api_name": "utilities.common.CommonUtils.move_menu_selection", "line_number": 73, "usage_type": "call"}, {"api_name": "utilities.common.CommonUtils", "line_number": 73, "usage_type": "attribute"}, {"api_name": "utilities.common", "line_number": 73, "usage_type": "name"}, {"api_name": "loguru.logger.debug", "line_number": 79, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 79, "usage_type": "name"}, {"api_name": "loguru.logger.debug", "line_number": 80, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 80, "usage_type": "name"}, {"api_name": "loguru.logger.debug", "line_number": 81, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 81, "usage_type": "name"}, {"api_name": "utilities.armourManagement.ArmourUtilities.create_full_armour_set", "line_number": 83, "usage_type": "call"}, {"api_name": "utilities.armourManagement.ArmourUtilities", "line_number": 83, "usage_type": "attribute"}, {"api_name": "utilities.armourManagement", "line_number": 83, "usage_type": "name"}, {"api_name": "utilities.armourManagement.ArmourUtilities.equip_full_set_of_armour", "line_number": 85, "usage_type": "call"}, {"api_name": "utilities.armourManagement.ArmourUtilities", "line_number": 85, "usage_type": "attribute"}, {"api_name": "utilities.armourManagement", "line_number": 85, "usage_type": "name"}, {"api_name": "utilities.armourManagement.ArmourUtilities.apply_major_attribute_bonus_to_full_armourset", "line_number": 87, "usage_type": "call"}, {"api_name": "utilities.armourManagement.ArmourUtilities", "line_number": 87, "usage_type": "attribute"}, {"api_name": "utilities.armourManagement", "line_number": 87, "usage_type": "name"}, {"api_name": "utilities.armourManagement.ArmourUtilities.set_mobile_derived_armour_attribute", "line_number": 93, "usage_type": "call"}, {"api_name": "utilities.armourManagement.ArmourUtilities", "line_number": 93, "usage_type": "attribute"}, {"api_name": "utilities.armourManagement", "line_number": 93, "usage_type": "name"}, {"api_name": "utilities.mobileHelp.MobileUtilities.set_mobile_derived_attributes", "line_number": 94, "usage_type": "call"}, {"api_name": "utilities.mobileHelp.MobileUtilities", "line_number": 94, "usage_type": "attribute"}, {"api_name": "utilities.mobileHelp", "line_number": 94, "usage_type": "name"}]} +{"seq_id": "33768748557", "text": "import logging\nimport argparse\n\nimport numpy as np\nimport onnx\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt = '%m/%d/%Y %H:%M:%S',\n level = logging.WARN)\n\nclass Dataloader:\n def __init__(self, batch_size):\n self.batch_size = batch_size\n shape = [[batch_size, 4, 64, 64], [batch_size], [batch_size, 77, 768]]\n dtype = ['float32', 'int64', 'float32']\n self.dataset = []\n for idx in range(0, len(shape)):\n tensor = np.random.uniform(size=shape[idx])\n tensor = tensor.astype(dtype[idx])\n self.dataset.append(tensor)\n\n def __iter__(self):\n yield self.dataset, 0\n\nif __name__ == \"__main__\":\n logger.info(\"Evaluating ONNXRuntime full precision accuracy and performance:\")\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n parser.add_argument(\n '--model_path',\n type=str,\n help=\"Pre-trained model on onnx file\"\n )\n parser.add_argument(\n '--benchmark',\n action='store_true', \\\n default=False\n )\n parser.add_argument(\n '--tune',\n action='store_true', \\\n default=False,\n help=\"whether quantize the model\"\n )\n parser.add_argument(\n '--output_model',\n type=str,\n help=\"output model path\"\n )\n parser.add_argument(\n '--mode',\n type=str,\n help=\"benchmark mode of performance or accuracy\"\n )\n parser.add_argument(\n '--quant_format',\n type=str,\n default='default', \n choices=['default', 'QDQ', 'QOperator'],\n help=\"quantization format\"\n )\n parser.add_argument(\n \"--batch_size\",\n default=1,\n type=int,\n )\n args = parser.parse_args()\n\n dataloader = Dataloader(args.batch_size)\n\n if args.benchmark and args.mode == 'performance':\n from neural_compressor.benchmark import fit\n from neural_compressor.config import BenchmarkConfig\n conf = BenchmarkConfig(warmup=10, iteration=1000, cores_per_instance=4, num_of_instance=1)\n fit(args.model_path, conf, b_dataloader=dataloader)\n if args.tune:\n from neural_compressor import quantization, PostTrainingQuantConfig\n config = PostTrainingQuantConfig(quant_format=args.quant_format, recipes={'graph_optimization_level':'ENABLE_EXTENDED'})\n q_model = quantization.fit(args.model_path, config, calib_dataloader=dataloader)\n\n q_model.save(args.output_model)\n", "repo_name": "intel/neural-compressor", "sub_path": "examples/onnxrt/image_recognition/unet/quantization/ptq_static/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2623, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1596, "dataset": "github-code", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 7, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 8, "usage_type": "call"}, {"api_name": "logging.WARN", "line_number": 10, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 19, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 28, "usage_type": "call"}, {"api_name": "argparse.ArgumentDefaultsHelpFormatter", "line_number": 29, "usage_type": "attribute"}, {"api_name": "neural_compressor.config.BenchmarkConfig", "line_number": 76, "usage_type": "call"}, {"api_name": "neural_compressor.benchmark.fit", "line_number": 77, "usage_type": "call"}, {"api_name": "neural_compressor.PostTrainingQuantConfig", "line_number": 80, "usage_type": "call"}, {"api_name": "neural_compressor.quantization.fit", "line_number": 81, "usage_type": "call"}, {"api_name": "neural_compressor.quantization", "line_number": 81, "usage_type": "name"}]} +{"seq_id": "41108860274", "text": "import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pylab as plt\r\ndata = pd.read_csv('a.csv')# -*- coding: utf-8 -*-\r\ndateparse = lambda dates: pd.datetime.strptime(dates, '%d.%m.%Y')\r\ndata = pd.read_csv('a.csv', parse_dates=['Date'],index_col='Date', date_parser=dateparse)\r\nprint (data.head)\r\nprint (data.dtypes)\r\ndata.index\r\nts = data\r\nplt.plot(ts)\r\n \r\n\"\"\"\r\nРедактор Spyder\r\n\r\nЭто временный скриптовый файл.\r\n\"\"\"\r\n\r\n", "repo_name": "sergeyivanov01/PHBS_MLF_2018", "sub_path": "1987-2018 bp.py", "file_name": "1987-2018 bp.py", "file_ext": "py", "file_size_in_byte": 460, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pandas.read_csv", "line_number": 4, "usage_type": "call"}, {"api_name": "pandas.datetime.strptime", "line_number": 5, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 5, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 6, "usage_type": "call"}, {"api_name": "matplotlib.pylab.plot", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pylab", "line_number": 11, "usage_type": "name"}]} +{"seq_id": "17566722638", "text": "import random\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import status\nfrom rest_framework.decorators import (\n api_view,\n authentication_classes,\n permission_classes,\n)\nfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom .models import Genre, Movie, Review\nfrom .serializers import (\n GenreListSerializer,\n MovieListSerializer,\n MovieSerializer,\n MovieBackdropSerializer,\n ReviewSerializer\n)\n\n\n@api_view(['GET'])\ndef genre_list(request):\n genres = Genre.objects.all()\n serializer = GenreListSerializer(genres, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef movie_list(request, genre_pk):\n # print(genre_pk)\n movies = Movie.objects.all().filter(genres__id__icontains=genre_pk).order_by('-vote_average')[:10]\n serializer = MovieListSerializer(movies, many=True)\n # print('clear')\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef movie(request, movie_pk):\n movie = get_object_or_404(Movie, pk=movie_pk)\n serializer = MovieSerializer(movie)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef movie_category(request, where):\n movies = Movie.objects.all().filter(where=where).order_by('-vote_average')[:10]\n serializer = MovieListSerializer(movies, many=True)\n # print(serializer.data)\n return Response(serializer.data)\n\n\n@api_view(['GET','POST'])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef like(request, movie_pk):\n movie = get_object_or_404(Movie, pk=movie_pk)\n if request.method == 'GET':\n if movie.like_users.filter(pk=request.user.pk).exists():\n return Response(True)\n else:\n return Response(False)\n else:\n if movie.like_users.filter(pk=request.user.pk).exists():\n # 좋아요 취소\n movie.like_users.remove(request.user)\n return Response({'like': False})\n else:\n # 좋아요\n movie.like_users.add(request.user)\n return Response({'like': True})\n\n\n# 리뷰 작성, 리뷰 리스트\n@api_view(['POST', 'GET'])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef review_list_create(request, movie_pk):\n if request.method == 'GET':\n reviews = Review.objects.all()\n serializer = ReviewSerializer(reviews, many=True)\n return Response(serializer.data)\n else:\n movie = get_object_or_404(Movie, pk=movie_pk)\n serializer = ReviewSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save(movie=movie, user=request.user)\n return Response(serializer.data) \n\n\n# 내가 좋아요한 영화들\n@api_view(['GET'])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef my_movie(request):\n movies = request.user.like_movies\n # movies = Movie.objects.all()\n # print(request.method)\n serializer = MovieListSerializer(movies, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef recommend(request):\n movies = request.user.like_movies.all()\n genres = dict()\n for movie in movies:\n for g in movie.genres.all():\n # print(g)\n if g.name in genres:\n val = genres[g.id]\n genres[g.id] = val + 1\n else:\n genres[g.id] = 1\n # print(genres)\n max_v = max_g = 0\n for (key, val) in genres.items():\n if val > max_v:\n max_g = key\n max_v = val\n\n \n movies = Movie.objects.all().filter(genres__id__icontains=max_g).order_by('-vote_average')[:10]\n serializer = MovieListSerializer(movies, many=True)\n \n return Response(serializer.data)", "repo_name": "SaltCastle77/LuvLuvMovie", "sub_path": "final-pjt-back/movies/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 3978, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "models.Genre.objects.all", "line_number": 24, "usage_type": "call"}, {"api_name": "models.Genre.objects", "line_number": 24, "usage_type": "attribute"}, {"api_name": "models.Genre", "line_number": 24, "usage_type": "name"}, {"api_name": "serializers.GenreListSerializer", "line_number": 25, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 26, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 22, "usage_type": "call"}, {"api_name": "models.Movie.objects.all", "line_number": 32, "usage_type": "call"}, {"api_name": "models.Movie.objects", "line_number": 32, "usage_type": "attribute"}, {"api_name": "models.Movie", "line_number": 32, "usage_type": "name"}, {"api_name": "serializers.MovieListSerializer", "line_number": 33, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 35, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 29, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 40, "usage_type": "call"}, {"api_name": "models.Movie", "line_number": 40, "usage_type": "argument"}, {"api_name": "serializers.MovieSerializer", "line_number": 41, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 42, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 38, "usage_type": "call"}, {"api_name": "models.Movie.objects.all", "line_number": 47, "usage_type": "call"}, {"api_name": "models.Movie.objects", "line_number": 47, "usage_type": "attribute"}, {"api_name": "models.Movie", "line_number": 47, "usage_type": "name"}, {"api_name": "serializers.MovieListSerializer", "line_number": 48, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 50, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 45, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 57, "usage_type": "call"}, {"api_name": "models.Movie", "line_number": 57, "usage_type": "argument"}, {"api_name": "rest_framework.response.Response", "line_number": 60, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 62, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 67, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 71, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 53, "usage_type": "call"}, {"api_name": "rest_framework.decorators.authentication_classes", "line_number": 54, "usage_type": "call"}, {"api_name": "rest_framework_jwt.authentication.JSONWebTokenAuthentication", "line_number": 54, "usage_type": "name"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 55, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 55, "usage_type": "name"}, {"api_name": "models.Review.objects.all", "line_number": 80, "usage_type": "call"}, {"api_name": "models.Review.objects", "line_number": 80, "usage_type": "attribute"}, {"api_name": "models.Review", "line_number": 80, "usage_type": "name"}, {"api_name": "serializers.ReviewSerializer", "line_number": 81, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 82, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 84, "usage_type": "call"}, {"api_name": "models.Movie", "line_number": 84, "usage_type": "argument"}, {"api_name": "serializers.ReviewSerializer", "line_number": 85, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 88, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 75, "usage_type": "call"}, {"api_name": "rest_framework.decorators.authentication_classes", "line_number": 76, "usage_type": "call"}, {"api_name": "rest_framework_jwt.authentication.JSONWebTokenAuthentication", "line_number": 76, "usage_type": "name"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 77, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 77, "usage_type": "name"}, {"api_name": "serializers.MovieListSerializer", "line_number": 99, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 100, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 92, "usage_type": "call"}, {"api_name": "rest_framework.decorators.authentication_classes", "line_number": 93, "usage_type": "call"}, {"api_name": "rest_framework_jwt.authentication.JSONWebTokenAuthentication", "line_number": 93, "usage_type": "name"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 94, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 94, "usage_type": "name"}, {"api_name": "models.Movie.objects.all", "line_number": 125, "usage_type": "call"}, {"api_name": "models.Movie.objects", "line_number": 125, "usage_type": "attribute"}, {"api_name": "models.Movie", "line_number": 125, "usage_type": "name"}, {"api_name": "serializers.MovieListSerializer", "line_number": 126, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 128, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 103, "usage_type": "call"}, {"api_name": "rest_framework.decorators.authentication_classes", "line_number": 104, "usage_type": "call"}, {"api_name": "rest_framework_jwt.authentication.JSONWebTokenAuthentication", "line_number": 104, "usage_type": "name"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 105, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 105, "usage_type": "name"}]} +{"seq_id": "20021065187", "text": "import collections\nimport copy\nimport tempfile\nimport time\n\nfrom urllib.parse import urlparse\n\n## django imports\nfrom django.core.exceptions import ObjectDoesNotExist\n\n### apps imports\nfrom grabbers.utils import miners\n\nfrom grabbers.utils.confs import GrabberConf, MapperConf\n\nfrom information.models import PageData, make_control_key\nfrom urlocators.models import Page, Locator, make_url_id\nfrom workers.models import Job\nfrom drivers.models import Header\nfrom grabbers.models import Target, ElementAction, PostElementAction, Extractor, PageAction\nfrom workers.utils.tasksProducer import TaskFromUrls\n\nGrabis=miners.Grabis()\n\n# --- extract page & response data\n#########################\nclass Pythoness:\n '''\n '''\n\n def __init__(self):\n '''\n '''\n self._conf={}\n self._job=None\n self._data={\n 'page_data':[],\n }\n\n def set_job(self, job):\n '''\n '''\n self._job=job\n\n def set_task(self, task):\n '''\n '''\n self._task=task\n\n\n def set_grabber(self, grabber):\n '''\n '''\n self._conf=GrabberConf.toDict(grabber)\n print('[+] Setting Grabber Configuration')\n\n def map_targets(self, mapper, browser):\n '''\n action\n ------\n maps urls on target pages\n creates tasks with diferent taskconfigs\n save url with field name on information db\n\n obs\n ---\n this guy here is an hybric fellow\n so he is kind out place here...\n '''\n #set vars\n field_name=mapper.field_name\n print('[+] Starting Mapper [{}]'.format(field_name))\n selector=mapper.field_selector\n task_configs=TaskConfig.objects.filter(mapper=mapper)\n page_object=Grabis.load_page(self._job, browser, save_source=False)\n #mine target links\n try:\n gb=Grabis\n gb.set_selector(selector)\n gb.set_page_object(page_object)\n gb.grab()\n #mapper element attr is always generic link\n data=gb.get_data(field_name, ['generic_link',])\n except Exception as e:\n print('[-] Fail to extract link in mapper: [{}]'.format(e))\n return\n #create mapper tasks\n current_url = urlparse(browser.current_url)\n #-- build page obj\n page=self._build_urllocators_objs(current_url)\n urls=[]\n for element in data:\n element_index=element['index']\n for mined_url in element[field_name]:\n if not mined_url:continue\n full_url=self._map_url(mined_url, current_url)\n urls.append(full_url)\n self._save_field(field_name, full_url, element_index, page)\n #build tasks for next crawling\n for task_config in task_configs:\n TaskFromUrls._job=self._job\n TaskFromUrls._config=task_config\n TaskFromUrls.set_urls(urls)\n TaskFromUrls.build_tasks()\n print('[+] Done creating [{}] tasks for job [{}]'.format(\n task_configs*len(urls), self._job))\n\n #---- mapper helper\n ###################\n def _map_url(self, u, current_url):\n parsed_url = urlparse(u)\n if not parsed_url.netloc:\n parsed_url = parsed_url._replace(\n netloc=current_url.netloc.lower(),\n scheme=current_url.scheme)\n return parsed_url.geturl()\n\n def session(self, browser, element_index=-1):\n '''\n '''\n #get general vals\n browser_name=browser.__class__.__name__\n\n # set base values\n if 'target' in self._conf:\n selector=self._conf['target']['selector']\n print('[+] Start targeting selector [{0}]'.format(selector))\n page_object=Grabis.load_page(self._job, browser)\n try:\n gb=Grabis\n gb.set_selector(selector)\n gb.set_page_object(page_object)\n except Exception as e:\n print('[-] Fail to load conf in Grabis', e)\n return\n\n if 'extractors' in self._conf:\n field_name=self._conf['target']['name']\n attrs=self._conf['extractors']\n gb.grab()\n data=gb.get_data(field_name, attrs)\n self._data['page_data']=data\n\n #will deal with elements list to action and post action\n if 'element_action' in self._conf:\n #test browser type\n if browser_name == 'LeanRequests':\n raise TypeError('[-] Lean Requests has no action')\n #grab target elements\n toAction=browser.xpathToaction(selector)\n actionType=self._conf['element_action']\n #apply action\n for targetAction in toAction:\n if actionType == \"jsClick\":\n browser.clickByJS(targetAction)\n else:\n getattr(targetAction, actionType)()\n if not self._conf['post_action']:continue\n postAction=Pythoness()\n postAction.set_task(self._task)\n postAction.set_job(self._job)\n postAction.set_grabber(self._conf['post_action'])\n postAction.session(browser)\n postAction.save_data(browser)\n\n\n if 'page_action' in self._conf:\n #it's dirty - needs to improve\n page_action=self._conf['page_action']\n action_data={}\n\n #legacy - now is required\n if page_action == 'get_header_field':\n if browser_name != 'LeanRequests':\n raise TypeError('[-] Only Lean Requests has get header field')\n #target header field is passed as extractor\n action_data.update({'header_field':self._conf['extractors']})\n\n elif page_action == 'execute_script':\n if browser_name == 'LeanRequests':\n raise TypeError('[-] Lean Requests has no execute script')\n if not selector: #for now script is send by selector ---------\n raise TypeError('[-] Script in target is required')\n field_name=field_name=self._conf['target']['name']\n action_data={'field_name':field_name, 'script':selector}\n\n elif page_action == 'switch_to_frame':\n if browser_name == 'LeanRequests':\n raise TypeError('[-] Lean Requests has no execute script')\n if not selector: #for now script is send by selector ---------\n raise TypeError('[-] Frame set_selector is required')\n field_name=field_name=self._conf['target']['name']\n action_data={'field_name':field_name, 'xpath':selector}\n\n elif page_action == 'page_source':\n action_data={'job':self._job}\n\n elif page_action == 'take_screenshot':\n action_data={'job':self._job}\n\n print('[+] Start page action [{0}]'.format(page_action))\n getattr(browser, page_action)(page_data=self._data,\n action_data=action_data)\n\n #will call a post-action\n if self._conf['post_action'] and not 'element_action' in self._conf:\n postAction=Pythoness()\n postAction.set_task(self._task)\n postAction.set_job(self._job)\n postAction.set_grabber(self._conf['post_action'])\n postAction.session(browser)\n postAction.save_data(browser)\n\n\n def save_data(self, browser, target_url=None):\n '''\n '''\n url=target_url\n if not url:\n url=browser.current_url\n page=self._build_urllocators_objs(url)\n for dict_item in self._data['page_data']:\n element_index = dict_item.pop('index')\n for field_name, values in dict_item.items():\n for value in values:\n if not value:continue\n self._save_field(field_name, value, element_index, page)\n time.sleep(0.001)\n\n def save_condition(self, browser, condition):\n '''\n '''\n condition_type = condition.save_type\n condition_confs = condition.taskconfig_set.all()\n if condition_type == 'page_data':\n msg='[-] Condition::Page Data save was'' not implemented yet'\n raise NotImplemented(msg)\n if condition_type == 'silent':return\n headers=browser.get_headers()\n print(\"H======>{}\".format(headers))\n for k,v in headers.items():\n hea=Header()\n hea.field_name=k\n hea.field_value=v\n hea.header_name=browser._header_name\n hea.save()\n for conf in condition_confs:\n has_headers = conf.driver.headers.filter(\n field_name=hea.field_name)\n for h_header in has_headers:\n conf.driver.headers.remove(h_header)\n time.sleep(0.001)\n conf.driver.headers.add(hea)\n time.sleep(0.001)\n\n print('[+] Done saving condition::{}'.format(condition_type))\n\n\n\n # --- save data helpers\n ########################\n def _build_urllocators_objs(self, url):\n '''\n obs\n ---------\n this function is very similar\n to save page source in browser\n the only difference is html source persistence\n\n *** soon will merge both ****\n '''\n #build url relations\n url_id=make_url_id(url)\n try:\n locs=Locator.objects.get(url_id=url_id)\n except ObjectDoesNotExist:\n locs=Locator()\n locs.url=url\n locs.save()\n #build page relation\n try:\n page=Page.objects.get(addr=locs.id, job=self._job)\n except Page.DoesNotExist:\n page=Page()\n page.job=self._job\n page.task=self._task\n page.addr=locs\n page.save()\n return page\n\n def _save_field(self, field_name, value, element_index, page):\n '''\n '''\n control_key=make_control_key(field_name, value, page.id)\n is_duplicate=PageData.objects.filter(control_key=control_key)\n if is_duplicate.count():return\n pd=PageData()\n pd.field_name=field_name\n pd.field_value=value\n pd.element_index = element_index\n pd.page=page\n pd.job=self._job\n pd.task=self._task\n pd.save()\n\n @staticmethod\n def save_proxy_data(browser):\n '''\n '''\n print(browser.get_proxy_data())\n", "repo_name": "VulcanoAhab/delphi", "sub_path": "grabbers/utils/crushers.py", "file_name": "crushers.py", "file_ext": "py", "file_size_in_byte": 10796, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "grabbers.utils.miners.Grabis", "line_number": 23, "usage_type": "call"}, {"api_name": "grabbers.utils.miners", "line_number": 23, "usage_type": "name"}, {"api_name": "grabbers.utils.confs.GrabberConf.toDict", "line_number": 54, "usage_type": "call"}, {"api_name": "grabbers.utils.confs.GrabberConf", "line_number": 54, "usage_type": "name"}, {"api_name": "urllib.parse.urlparse", "line_number": 88, "usage_type": "call"}, {"api_name": "workers.utils.tasksProducer.TaskFromUrls._job", "line_number": 101, "usage_type": "attribute"}, {"api_name": "workers.utils.tasksProducer.TaskFromUrls", "line_number": 101, "usage_type": "name"}, {"api_name": "workers.utils.tasksProducer.TaskFromUrls._config", "line_number": 102, "usage_type": "attribute"}, {"api_name": "workers.utils.tasksProducer.TaskFromUrls", "line_number": 102, "usage_type": "name"}, {"api_name": "workers.utils.tasksProducer.TaskFromUrls.set_urls", "line_number": 103, "usage_type": "call"}, {"api_name": "workers.utils.tasksProducer.TaskFromUrls", "line_number": 103, "usage_type": "name"}, {"api_name": "workers.utils.tasksProducer.TaskFromUrls.build_tasks", "line_number": 104, "usage_type": "call"}, {"api_name": "workers.utils.tasksProducer.TaskFromUrls", "line_number": 104, "usage_type": "name"}, {"api_name": "urllib.parse.urlparse", "line_number": 111, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 228, "usage_type": "call"}, {"api_name": "drivers.models.Header", "line_number": 242, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 252, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 254, "usage_type": "call"}, {"api_name": "urlocators.models.make_url_id", "line_number": 273, "usage_type": "call"}, {"api_name": "urlocators.models.Locator.objects.get", "line_number": 275, "usage_type": "call"}, {"api_name": "urlocators.models.Locator.objects", "line_number": 275, "usage_type": "attribute"}, {"api_name": "urlocators.models.Locator", "line_number": 275, "usage_type": "name"}, {"api_name": "django.core.exceptions.ObjectDoesNotExist", "line_number": 276, "usage_type": "name"}, {"api_name": "urlocators.models.Locator", "line_number": 277, "usage_type": "call"}, {"api_name": "urlocators.models.Page.objects.get", "line_number": 282, "usage_type": "call"}, {"api_name": "urlocators.models.Page.objects", "line_number": 282, "usage_type": "attribute"}, {"api_name": "urlocators.models.Page", "line_number": 282, "usage_type": "name"}, {"api_name": "urlocators.models.Page.DoesNotExist", "line_number": 283, "usage_type": "attribute"}, {"api_name": "urlocators.models.Page", "line_number": 283, "usage_type": "name"}, {"api_name": "urlocators.models.Page", "line_number": 284, "usage_type": "call"}, {"api_name": "information.models.make_control_key", "line_number": 294, "usage_type": "call"}, {"api_name": "information.models.PageData.objects.filter", "line_number": 295, "usage_type": "call"}, {"api_name": "information.models.PageData.objects", "line_number": 295, "usage_type": "attribute"}, {"api_name": "information.models.PageData", "line_number": 295, "usage_type": "name"}, {"api_name": "information.models.PageData", "line_number": 297, "usage_type": "call"}]} +{"seq_id": "26836613360", "text": "from cell import Cell\nfrom random import randint\nimport pygame\n\nclass Grid:\n\n\tdef __init__(self, length, height):\n\t\tself.board = [[Cell() for k in range(height)] for i in range(length)]\n\t\t\n\tdef generate(self, quota):\n\t\tmines = []\n\t\twhile quota > 0:\n\t\t\tfor i in range(len(self.board)):\n\t\t\t\tfor k in range(len(self.board[i])):\n\t\t\t\t\tif quota > 0:\n\t\t\t\t\t\tif self.board[i][k].value != \"×\":\n\t\t\t\t\t\t\trandom_value = randint(0, 100)\n\t\t\t\t\t\t\tif random_value > 99:\n\t\t\t\t\t\t\t\tquota -= 1\n\t\t\t\t\t\t\t\tself.board[i][k].value = \"×\"\n\t\t\t\t\t\t\t\tmines.append((i, k))\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif self.board[i][k] == \" \":\n\t\t\t\t\t\t\t\t\tself.board[i][k].value = \" \"\n\n\t\tfor coords in mines:\n\t\t\tfor i in range(max(0, coords[0]-1), min(len(self.board), coords[0]+2)):\n\t\t\t\tfor k in range(max(0, coords[1]-1), min(len(self.board[i]), coords[1]+2)):\n\t\t\t\t\tif self.board[i][k].value == \" \":\n\t\t\t\t\t\tself.board[i][k].value = \"1\"\n\t\t\t\t\telse:\n\t\t\t\t\t\tif self.board[i][k].value != \"×\":\n\t\t\t\t\t\t\tself.board[i][k].value = str(int(self.board[i][k].value)+1)\n\t\n\tdef display(self, window, font):\n\t\tcouleurs = { \"×\": (0, 0, 0), \"1\": (0, 0, 255), \"2\": (0, 128, 0), \"3\": (255, 0, 0), \"4\": (200, 0, 200), \"5\": (255, 255, 0), \"6\": (0, 255, 255), \"7\": (106, 230, 201), \"8\": (106, 230, 201), \" \": (255, 255, 255)}\n\t\tcell_false = pygame.image.load(\"./assets/cell_false.png\")\n\t\tcell_true = pygame.image.load(\"./assets/cell_true.png\")\n\t\tcell_flag = pygame.image.load(\"./assets/cell_flag.png\")\n\n\t\tfor i in range(len(self.board)):\n\t\t\tfor k in range(len(self.board[i])):\n\t\t\t\tif self.board[i][k].display == True:\n\t\t\t\t\tpygame.draw.rect(window, (192, 192, 192), (25*k, 25*i, 25, 25))\n\t\t\t\t\ttexte = font.render(self.board[i][k].value, True, couleurs[self.board[i][k].value])\n\t\t\t\t\twindow.blit(cell_true, (25*k, 25*i))\n\t\t\t\t\twindow.blit(texte, (25*k+8, 25*i+5))\n\t\t\t\telse:\n\t\t\t\t\tif self.board[i][k].flag == True:\n\t\t\t\t\t\twindow.blit(cell_flag, (25*k, 25*i))\n\t\t\t\t\telse:\n\t\t\t\t\t\twindow.blit(cell_false, (25*k, 25*i))\n\t\n\tdef game_end(self):\n\t\tfor i in range(len(self.board)):\n\t\t\tfor k in range(len(self.board[i])):\n\t\t\t\tif (self.board[i][k].value == \"×\" and self.board[i][k].flag == False) or (self.board[i][k].value != \"×\" and self.board[i][k].flag == True) or (self.board[i][k].value != \"×\" and self.board[i][k].display != True):\n\t\t\t\t\treturn False\n\t\treturn True\n\n\n\tdef game_over(self):\n\t\tfor i in range(len(self.board)):\n\t\t\tfor k in range(len(self.board[i])):\n\t\t\t\tself.board[i][k].display = True\n\n\tdef flood_fill(self, coords):\n\t\tmovements = [[0,-1], [0,1], [-1,0], [1,0], [-1,-1], [-1,1], [1,1], [1,-1]]\n\t\tremains_to_be_done = [coords]\n\t\tcell_edges = []\n\t\twhile len(remains_to_be_done) > 0:\n\t\t\tcurrent_cell = remains_to_be_done[0]\n\t\t\tdel remains_to_be_done[0]\n\t\t\tself.board[current_cell[0]][current_cell[1]].display = True\n\t\t\tcell_edges.extend(correct_cell_edges(self, current_cell))\n\t\t\tfor movement in movements:\n\t\t\t\tneighbour_cell = [current_cell[0]+movement[0], current_cell[1]+movement[1]]\n\t\t\t\tif correct_cell(self, neighbour_cell):\n\t\t\t\t\tremains_to_be_done.append(neighbour_cell)\n\t\tfor k in range(len(cell_edges)):\n\t\t\tself.board[cell_edges[k][0]][cell_edges[k][1]].display = True\n\ndef correct_cell(grid, cell):\n\treturn (0 <= cell[0] < len(grid.board)) and (0 <= cell[1] < len(grid.board[0])) and (grid.board[cell[0]][cell[1]].value == \" \") and (grid.board[cell[0]][cell[1]].display == False)\n\ndef correct_cell_edges(grid, cell):\n\tmovements = [[0,-1],[0,1],[-1,0],[1,0],[-1,-1],[-1,1],[1,1],[1,-1]]\n\tcell_edges = []\n\tcell_visited = cell\n\tfor movement in movements:\n\t\tcell = [cell_visited[0]+movement[0], cell_visited[1]+movement[1]]\n\t\tif 0 <= cell[0] < len(grid.board) and 0 <= cell[1] < len(grid.board[0]):\n\t\t\tif grid.board[cell[0]][cell[1]].value != \" \" and grid.board[cell[0]][cell[1]].value != \"X\":\n\t\t\t\tcell_edges.append(cell)\n\treturn cell_edges\n", "repo_name": "vosketalor/minesweeper", "sub_path": "grid.py", "file_name": "grid.py", "file_ext": "py", "file_size_in_byte": 3766, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "cell.Cell", "line_number": 8, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 17, "usage_type": "call"}, {"api_name": "pygame.image.load", "line_number": 37, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 37, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 38, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 38, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 39, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 39, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 44, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 44, "usage_type": "attribute"}]} +{"seq_id": "71128056703", "text": "\n# Example Azure function which reacts to a file landing in a queue\n\n## Import Azure packages\nimport logging\nimport azure.functions as func\nfrom azure.identity import DefaultAzureCredential\nfrom azure.storage.blob import BlobServiceClient\n\n## Import Snowpark session module\nfrom snowflake.snowpark import Session\n\n## Import other packages\nimport os\nimport json\nfrom io import BytesIO\n\n## Define function to retrieve the desired\n## information from the input message\ndef parse_input_message(msg: func.QueueMessage):\n\n ### Retrieve message as JSON\n msg_json = msg.get_json()\n logging.info('Message JSON:')\n logging.info(msg_json)\n \n ### Retrieve message ID\n msg_id = msg_json[\"id\"]\n logging.info(f'Message ID: {msg_id}')\n\n ### Retrieve full file URL from input blob.\n ### The specific key varies depending on the type\n ### of storage container\n if \"url\" in msg_json[\"data\"] :\n file_path_url = msg_json[\"data\"][\"url\"]\n elif \"blobUrl\" in msg_json[\"data\"] :\n file_path_url = msg_json[\"data\"][\"blobUrl\"]\n else :\n logging.error(\"Function abort - Path URL does not match expected storage blob service URI\")\n raise ValueError(\"Function abort - Path URL does not match expected storage blob service URI\")\n \n logging.info(f'File path URL: {file_path_url}')\n \n '''\n Expected file URL format:\n https://.blob.core.windows.net//path/to/file.json\n \n Example expected file URL:\n https://my-storage-account.blob.core.windows.net/automated-function-trigger-demo/example_file.json\n '''\n\n ### Retrieve storage blob service uri\n storage_blob_service_uri = os.getenv(\"AZURE_STORAGE_IDENTITY__blobServiceUri\")\n\n ### Parse storage queue service URI from file path URL\n if file_path_url.startswith(storage_blob_service_uri) :\n file_path = file_path_url[1 + len(storage_blob_service_uri):]\n else :\n logging.info(f'Function abort - Path URL does not match expected storage blob service URI')\n return\n \n ### Split file path into container and relative file path\n container, relative_file_path = file_path.split('/', 1)\n\n return storage_blob_service_uri, container, relative_file_path\n\n## Define function to download full JSON file from blob\ndef azure_download_json_file(storage_blob_service_uri=None, container=None, relative_file_path=None):\n default_azure_credential = DefaultAzureCredential()\n blob_service_client = BlobServiceClient(storage_blob_service_uri, credential=default_azure_credential)\n blob_client = blob_service_client.get_blob_client(container=container, blob=relative_file_path)\n with BytesIO() as input_blob:\n blob_client.download_blob().download_to_stream(input_blob)\n input_blob.seek(0)\n json_input = json.load(input_blob)\n \n return json_input\n\n## Define function that retrieve the SQL statement\n## to execute from the JSON input\ndef retrieve_sql_statement_to_execute(json_input: dict):\n\n '''\n Expected format of JSON file:\n json_input = {\n \"sql_statement_to_execute\" : \"\"\n }\n '''\n\n ### Error if JSON file is not in expected format\n if \"sql_statement_to_execute\" not in json_input.keys() :\n logging.error(f\"Manual log - Downloaded file did not include the key 'sql_statement_to_execute'\")\n raise ValueError(\"Manual log - Downloaded file did not include the key 'sql_statement_to_execute'\")\n\n ### Retrieve the value as its own variable\n sql_statement_to_execute = json_input[\"sql_statement_to_execute\"]\n\n return sql_statement_to_execute\n \n## Function to create Snowpark session\ndef build_snowpark_session() :\n\n ### Retrieve connection parameters from app settings\n snowflake_connection_parameters = {\n \"account\": os.getenv(\"SNOWFLAKE_ACCOUNT\")\n , \"user\": os.getenv(\"SNOWFLAKE_USER\")\n , \"password\": os.getenv(\"SNOWFLAKE_PASSWORD\")\n , \"role\": os.getenv(\"SNOWFLAKE_ROLE\")\n , \"warehouse\": os.getenv(\"SNOWFLAKE_WAREHOUSE\")\n }\n\n ### Create Snowflake Snowpark session \n snowpark_session = Session.builder.configs(snowflake_connection_parameters).create()\n\n return snowpark_session\n\n## Define function that executes given SQL in Snowflake\ndef execute_sql_in_snowflake(sql_statement_to_execute: str):\n\n ### Create Snowflake Snowpark session \n snowpark_session = build_snowpark_session()\n\n ### Execute the SQL command in Snowflake\n ### and log the result\n sf_df_statement_result = snowpark_session.sql(sql_statement_to_execute).collect()\n \n logging.info(\"SQL statement result:\")\n logging.info(sf_df_statement_result)\n\n ### Close the Snowflake Snowpark Session\n snowpark_session.close()\n \n return\n\n## Define main function for Azure\ndef main(msg: func.QueueMessage):\n logging.info('Received new message from queue')\n logging.info(msg)\n\n ### Parse the input message for required information\n storage_blob_service_uri, container, relative_file_path = parse_input_message(msg)\n\n ### Retrieve JSON input from Azure storage\n json_input = azure_download_json_file(storage_blob_service_uri=storage_blob_service_uri, container=container, relative_file_path=relative_file_path)\n\n ### Retrieve the value as its own variable\n sql_statement_to_execute = retrieve_sql_statement_to_execute(json_input)\n \n ### Attempt to execute the SQL in Snowflake\n execute_sql_in_snowflake(sql_statement_to_execute)\n \n return", "repo_name": "interworks/Example-Snowpark-Azure-Functions", "sub_path": "azure_storage_trigger_leveraging_app_settings_directly/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 5268, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "azure.functions.QueueMessage", "line_number": 20, "usage_type": "attribute"}, {"api_name": "azure.functions", "line_number": 20, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 24, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 25, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 29, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 39, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 42, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 53, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 59, "usage_type": "call"}, {"api_name": "azure.identity.DefaultAzureCredential", "line_number": 69, "usage_type": "call"}, {"api_name": "azure.storage.blob.BlobServiceClient", "line_number": 70, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 72, "usage_type": "call"}, {"api_name": "json.load", "line_number": 75, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 92, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 105, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 106, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 107, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 108, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 109, "usage_type": "call"}, {"api_name": "snowflake.snowpark.Session.builder.configs", "line_number": 113, "usage_type": "call"}, {"api_name": "snowflake.snowpark.Session.builder", "line_number": 113, "usage_type": "attribute"}, {"api_name": "snowflake.snowpark.Session", "line_number": 113, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 127, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 128, "usage_type": "call"}, {"api_name": "azure.functions.QueueMessage", "line_number": 136, "usage_type": "attribute"}, {"api_name": "azure.functions", "line_number": 136, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 137, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 138, "usage_type": "call"}]} +{"seq_id": "24661075680", "text": "from django.urls import path\n\nfrom . import views\nfrom contact_us.views import create_contact, faq\n\n\napp_name='adminpage'\n\nurlpatterns=[\n path('garbage_collectors_list', views.garbage_collectors_list, name='collectors_list'),\n path('accept_collector', views.create_garbage_collector, name=\"accept_collector\"),\n path(\"accept_list\", views.unaccepted_collectors_list, name=\"accept_list\"),\n path(\"accept_detail/\", views.unaccepted_collector_detail, name=\"accept_detail\"),\n path(\"accepted_collector/\", views.unaccepted_collector_changed, name=\"accepted_collector\"),\n path(\"contact\", create_contact, name=\"contact_create\"),\n path('faq', faq, name=\"faq\")\n\n]", "repo_name": "adebusola-prog/IN_OUT", "sub_path": "garbage_project/admin_page/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 680, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 14, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "contact_us.views.create_contact", "line_number": 15, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 16, "usage_type": "call"}, {"api_name": "contact_us.views.faq", "line_number": 16, "usage_type": "argument"}]} +{"seq_id": "31483919047", "text": "import os \nimport datetime\nimport shutil #using copy2('src,'dst') cammand only\nass_list=[] #for associating the date to the image name\n\nos.chdir('G:\\\\DCIM\\\\100CANON')\nfor image in os.listdir(): #listing all files of the Card\n\t\n\ttimestamp=os.stat(image)[8] #gettingtimestamp\n\tdate_time=datetime.datetime.fromtimestamp(timestamp).strftime('%d-%b') #creating a date_time from the timestamp \n\t#fromtimestamp() returns a string\n\tloc_ass=[image,date_time] #list with image and date\n\tass_list.append(loc_ass) #appending to the ass_list\n\t\nos.chdir('F:\\\\LatestDSLR')\ncurrent_folders=[folder for folder in os.listdir() ] #listing current destination folders\nfor i in range(len(ass_list)):\n\tdate=ass_list[i][1] #getting the dates for each image\n\tsrc=f\"G:\\\\DCIM\\\\100CANON\\\\{ass_list[i][0]}\" #assigning the source to image location\n\n\n\tif os.path.exists(f\"F:\\\\LatestDSLR\\\\{date}\") ==True: #checking if there's already a date folder or not\n\t des=f\"F:\\\\LatestDSLR\\\\{date}\"\n\n\telse:\n\t\tos.mkdir(f\"{date}\")\n\t\tdes=f\"F:\\\\LatestDSLR\\\\{date}\" #creating the date foldee if not already present\n\t\n\n\tshutil.copy(src,des) #copying the file\n\n\nprint(\"DONE!!\")\n\t\n", "repo_name": "jitendrayt/DSLR-auto-photo-import", "sub_path": "main_code.py", "file_name": "main_code.py", "file_ext": "py", "file_size_in_byte": 1132, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "os.chdir", "line_number": 6, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 7, "usage_type": "call"}, {"api_name": "os.stat", "line_number": 9, "usage_type": "call"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 10, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.chdir", "line_number": 15, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 26, "usage_type": "call"}, {"api_name": "shutil.copy", "line_number": 30, "usage_type": "call"}]} +{"seq_id": "40091510168", "text": "#! python3\n# pretty_stopwatch.py\n# Author: Michael Koundouros\n\"\"\"\nA stopwatch program that:\n1. Tracks the amount of time elapsed between presses of the ENTER key, with each key press starting a new “lap”\n on the timer.\n2. Prints the lap number, total time, and lap time.\n\"\"\"\n\n\nimport time\nimport pyperclip\n\n\n# Display the program's instructions.\nprint('Press ENTER to begin. Afterward, press ENTER to \"click\" the stopwatch. Press Ctrl-C to quit.')\ninput() # press Enter to begin\nprint('Started.')\nstartTime = time.time() # get the first lap's start time\nlastTime = startTime\nlapNum = 1\n\nclipboard = []\ntry:\n while True:\n input()\n lapTime = round(time.time() - lastTime, 2)\n totalTime = round(time.time() - startTime, 2)\n output_str = f'Lap #{lapNum:2}: {totalTime:5} ({lapTime:5})'\n print(output_str, end='')\n clipboard.append(output_str)\n lapNum += 1\n lastTime = time.time() # reset the last lap time\nexcept KeyboardInterrupt:\n # Handle the Ctrl-C exception to keep its error message from displaying.\n print('\\nDone.')\n pyperclip.copy('\\n'.join(clipboard))\n", "repo_name": "mkoundo/Automate_the_Boring_Stuff", "sub_path": "chapter_17_Time/pretty_stopwatch.py", "file_name": "pretty_stopwatch.py", "file_ext": "py", "file_size_in_byte": 1249, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "time.time", "line_number": 20, "usage_type": "call"}, {"api_name": "time.time", "line_number": 28, "usage_type": "call"}, {"api_name": "time.time", "line_number": 29, "usage_type": "call"}, {"api_name": "time.time", "line_number": 34, "usage_type": "call"}, {"api_name": "pyperclip.copy", "line_number": 38, "usage_type": "call"}]} +{"seq_id": "37520989208", "text": "import datetime\nimport random\nimport secrets\nimport typing\n\nfrom google.protobuf.descriptor import EnumDescriptor, FieldDescriptor\nfrom google.protobuf.message import Message\nfrom google.protobuf.timestamp_pb2 import Timestamp\nfrom google.type.date_pb2 import Date\nfrom google.type.timeofday_pb2 import TimeOfDay\n\nfrom protarrow.common import M\nfrom protarrow.proto_to_arrow import is_map\n\nEPOCH_RATIO = 24 * 60 * 60\n\nUNIT_IN_NANOS = {\"s\": 1_000_000_000, \"ms\": 1_000_000, \"us\": 1_000, \"ns\": 1}\n\n\ndef random_string(count: int) -> str:\n return secrets.token_urlsafe(random.randint(0, count))\n\n\ndef random_bytes(count: int) -> bytes:\n return secrets.token_bytes(random.randint(0, count))\n\n\ndef random_timestamp() -> Timestamp:\n return Timestamp(\n seconds=random.randint(-9223372036, 9223372035),\n nanos=random.randint(0, 999_999_999),\n )\n\n\ndef random_date() -> Date:\n date = datetime.date.min + datetime.timedelta(days=random.randint(0, 3652058))\n return Date(year=date.year, month=date.month, day=date.day)\n\n\ndef random_time_of_day() -> TimeOfDay:\n return TimeOfDay(\n hours=random.randint(0, 23),\n minutes=random.randint(0, 59),\n seconds=random.randint(0, 59),\n nanos=random.randint(0, 999_999_999),\n )\n\n\nCPP_TYPE_GENERATOR = {\n FieldDescriptor.CPPTYPE_INT32: lambda: random.randint(-(2**31), 2**31 - 1),\n FieldDescriptor.CPPTYPE_INT64: lambda: random.randint(-(2**63), 2**63 - 1),\n FieldDescriptor.CPPTYPE_UINT32: lambda: random.randint(0, 2**32 - 1),\n FieldDescriptor.CPPTYPE_UINT64: lambda: random.randint(0, 2**64 - 1),\n FieldDescriptor.CPPTYPE_DOUBLE: lambda: random.uniform(-1, 1),\n FieldDescriptor.CPPTYPE_FLOAT: lambda: random.uniform(-1, 1),\n FieldDescriptor.CPPTYPE_BOOL: lambda: bool(random.getrandbits(1)),\n}\n\nTYPE_GENERATOR = {\n FieldDescriptor.TYPE_BYTES: random_bytes,\n FieldDescriptor.TYPE_STRING: random_string,\n}\n\nMESSAGE_GENERATORS = {\n Date.DESCRIPTOR: random_date,\n Timestamp.DESCRIPTOR: random_timestamp,\n TimeOfDay.DESCRIPTOR: random_time_of_day,\n}\n\n\ndef generate_message(message_type: typing.Type[M], repeated_count: int) -> M:\n message = message_type()\n for one_of in message_type.DESCRIPTOR.oneofs:\n one_of_index = random.randint(0, len(one_of.fields))\n if one_of_index < len(one_of.fields):\n field = one_of.fields[one_of_index]\n set_field(message, field, repeated_count)\n\n for field in message_type.DESCRIPTOR.fields:\n if field.containing_oneof is None:\n if (\n field.label == FieldDescriptor.LABEL_REPEATED\n or field.type != FieldDescriptor.TYPE_MESSAGE\n or random.getrandbits(1) == 1\n ):\n set_field(message, field, repeated_count)\n return message\n\n\ndef generate_messages(\n message_type: typing.Type[M], count: int, repeated_count: int = 10\n) -> typing.List[M]:\n return [generate_message(message_type, repeated_count) for _ in range(count)]\n\n\ndef set_field(message: Message, field: FieldDescriptor, count: int) -> None:\n data = generate_field_data(field, count)\n\n if field.label == FieldDescriptor.LABEL_REPEATED:\n field_value = getattr(message, field.name)\n if is_map(field):\n if (\n field.message_type.fields_by_name[\"value\"].type\n == FieldDescriptor.TYPE_MESSAGE\n ):\n for entry in data:\n field_value[entry.key].MergeFrom(entry.value)\n else:\n for entry in data:\n field_value[entry.key] = entry.value\n else:\n field_value.extend(data)\n elif field.type == FieldDescriptor.TYPE_MESSAGE:\n if random.getrandbits(1) == 1:\n getattr(message, field.name).CopyFrom(data)\n else:\n setattr(message, field.name, data)\n\n\ndef generate_field_data(field: FieldDescriptor, count: int):\n if field.label == FieldDescriptor.LABEL_REPEATED:\n size = random.randint(0, count)\n return [_generate_data(field, count) for _ in range(size)]\n else:\n return _generate_data(field, count)\n\n\ndef _generate_data(field: FieldDescriptor, count: int) -> typing.Any:\n if field.type == FieldDescriptor.TYPE_ENUM:\n return _generate_enum(field.enum_type)\n elif field.message_type in MESSAGE_GENERATORS:\n return MESSAGE_GENERATORS[field.message_type]()\n elif field.type == FieldDescriptor.TYPE_MESSAGE:\n return generate_message(field.message_type._concrete_class, count)\n elif field.type in TYPE_GENERATOR:\n return TYPE_GENERATOR[field.type](count)\n else:\n return CPP_TYPE_GENERATOR[field.cpp_type]()\n\n\ndef _generate_enum(enum: EnumDescriptor) -> int:\n return random.choice(enum.values).index\n\n\ndef truncate_nanos(message: Message, timestamp_unit: str, time_unit: str) -> Message:\n if message.DESCRIPTOR == Timestamp.DESCRIPTOR:\n message.nanos = (\n message.nanos // UNIT_IN_NANOS[timestamp_unit]\n ) * UNIT_IN_NANOS[timestamp_unit]\n elif message.DESCRIPTOR == TimeOfDay.DESCRIPTOR:\n message.nanos = (message.nanos // UNIT_IN_NANOS[time_unit]) * UNIT_IN_NANOS[\n time_unit\n ]\n else:\n for field in message.DESCRIPTOR.fields:\n if field.type == FieldDescriptor.TYPE_MESSAGE:\n if field.label == FieldDescriptor.LABEL_REPEATED:\n field_value = getattr(message, field.name)\n if (\n field.message_type is not None\n and field.message_type.GetOptions().map_entry\n ):\n if (\n field.message_type.fields_by_name[\"value\"].type\n == FieldDescriptor.TYPE_MESSAGE\n ):\n for key, value in field_value.items():\n truncate_nanos(value, timestamp_unit, time_unit)\n\n else:\n for item in field_value:\n truncate_nanos(item, timestamp_unit, time_unit)\n elif message.HasField(field.name):\n truncate_nanos(\n getattr(message, field.name), timestamp_unit, time_unit\n )\n return message\n", "repo_name": "tradewelltech/protarrow", "sub_path": "tests/random_generator.py", "file_name": "random_generator.py", "file_ext": "py", "file_size_in_byte": 6354, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "24", "api": [{"api_name": "secrets.token_urlsafe", "line_number": 21, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 21, "usage_type": "call"}, {"api_name": "secrets.token_bytes", "line_number": 25, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 25, "usage_type": "call"}, {"api_name": "google.protobuf.timestamp_pb2.Timestamp", "line_number": 29, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 30, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 31, "usage_type": "call"}, {"api_name": "google.protobuf.timestamp_pb2.Timestamp", "line_number": 28, "usage_type": "name"}, {"api_name": "datetime.date", "line_number": 36, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 36, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 36, "usage_type": "call"}, {"api_name": "google.type.date_pb2.Date", "line_number": 37, "usage_type": "call"}, {"api_name": "google.type.date_pb2.Date", "line_number": 35, "usage_type": "name"}, {"api_name": "google.type.timeofday_pb2.TimeOfDay", "line_number": 41, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 42, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 43, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 44, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 45, "usage_type": "call"}, {"api_name": "google.type.timeofday_pb2.TimeOfDay", "line_number": 40, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.CPPTYPE_INT32", "line_number": 50, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 50, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.CPPTYPE_INT64", "line_number": 51, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 51, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.CPPTYPE_UINT32", "line_number": 52, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 52, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.CPPTYPE_UINT64", "line_number": 53, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 53, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.CPPTYPE_DOUBLE", "line_number": 54, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 54, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.CPPTYPE_FLOAT", "line_number": 55, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 55, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.CPPTYPE_BOOL", "line_number": 56, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 56, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 50, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 51, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 52, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 53, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 54, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 55, "usage_type": "call"}, {"api_name": "random.getrandbits", "line_number": 56, "usage_type": "call"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.TYPE_BYTES", "line_number": 60, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 60, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.TYPE_STRING", "line_number": 61, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 61, "usage_type": "name"}, {"api_name": "google.type.date_pb2.Date.DESCRIPTOR", "line_number": 65, "usage_type": "attribute"}, {"api_name": "google.type.date_pb2.Date", "line_number": 65, "usage_type": "name"}, {"api_name": "google.protobuf.timestamp_pb2.Timestamp.DESCRIPTOR", "line_number": 66, "usage_type": "attribute"}, {"api_name": "google.protobuf.timestamp_pb2.Timestamp", "line_number": 66, "usage_type": "name"}, {"api_name": "google.type.timeofday_pb2.TimeOfDay.DESCRIPTOR", "line_number": 67, "usage_type": "attribute"}, {"api_name": "google.type.timeofday_pb2.TimeOfDay", "line_number": 67, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 71, "usage_type": "attribute"}, {"api_name": "protarrow.common.M", "line_number": 71, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 74, "usage_type": "call"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.LABEL_REPEATED", "line_number": 82, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 82, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.TYPE_MESSAGE", "line_number": 83, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 83, "usage_type": "name"}, {"api_name": "random.getrandbits", "line_number": 84, "usage_type": "call"}, {"api_name": "typing.Type", "line_number": 91, "usage_type": "attribute"}, {"api_name": "protarrow.common.M", "line_number": 91, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 92, "usage_type": "attribute"}, {"api_name": "protarrow.common.M", "line_number": 92, "usage_type": "name"}, {"api_name": "google.protobuf.message.Message", "line_number": 96, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 96, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.LABEL_REPEATED", "line_number": 99, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 99, "usage_type": "name"}, {"api_name": "protarrow.proto_to_arrow.is_map", "line_number": 101, "usage_type": "call"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.TYPE_MESSAGE", "line_number": 104, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 104, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.TYPE_MESSAGE", "line_number": 113, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 113, "usage_type": "name"}, {"api_name": "random.getrandbits", "line_number": 114, "usage_type": "call"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 120, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.LABEL_REPEATED", "line_number": 121, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 121, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 122, "usage_type": "call"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 128, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.TYPE_ENUM", "line_number": 129, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 129, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.TYPE_MESSAGE", "line_number": 133, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 133, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 128, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.EnumDescriptor", "line_number": 141, "usage_type": "name"}, {"api_name": "random.choice", "line_number": 142, "usage_type": "call"}, {"api_name": "google.protobuf.message.Message", "line_number": 145, "usage_type": "name"}, {"api_name": "google.protobuf.timestamp_pb2.Timestamp.DESCRIPTOR", "line_number": 146, "usage_type": "attribute"}, {"api_name": "google.protobuf.timestamp_pb2.Timestamp", "line_number": 146, "usage_type": "name"}, {"api_name": "google.type.timeofday_pb2.TimeOfDay.DESCRIPTOR", "line_number": 150, "usage_type": "attribute"}, {"api_name": "google.type.timeofday_pb2.TimeOfDay", "line_number": 150, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.TYPE_MESSAGE", "line_number": 156, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 156, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.LABEL_REPEATED", "line_number": 157, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 157, "usage_type": "name"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor.TYPE_MESSAGE", "line_number": 165, "usage_type": "attribute"}, {"api_name": "google.protobuf.descriptor.FieldDescriptor", "line_number": 165, "usage_type": "name"}]} +{"seq_id": "12305424168", "text": "# Tamar Saad 207256991\r\n# Rachel Weinberger 208812628\r\nimport os.path\r\nimport random\r\nimport sys\r\nimport re\r\nimport math\r\nimport numpy as np\r\nfrom Bio.Seq import Seq\r\nfrom Bio import SeqIO\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom multiprocessing import Pool\r\n\r\n\r\nclass SequenceClassifier:\r\n def __init__(self, pattern_file):\r\n self.regex_dict = self.__patterns_to_domains(pattern_file)\r\n\r\n def __prosite_to_python(self, pattern_dict):\r\n # dictionary that translate prosite format to python format\r\n dic = {\"-\": None, \"x\": \".\", \"(\": \"{\", \")\": \"}\", \"{\": \"[^\", \"}\": \"]\", \"<\": \"^\", \">\": \"$\", \",\": \",\"}\r\n RE_patterns = {}\r\n # going through each pattern and domain\r\n for pattern, domain in pattern_dict.items():\r\n # check if the format is valid\r\n if self.__check_prosite_format(pattern):\r\n # translate the pattern and pair it with its domain\r\n trans = str(pattern).maketrans(dic)\r\n re_pattern = str(pattern).translate(trans)\r\n RE_patterns[re_pattern] = domain\r\n return RE_patterns\r\n\r\n def __check_prosite_format(self, pattern):\r\n # create regexes that represent correct prosite format\r\n occurrences = \"(\\([\\d](,[\\d])?\\))?\"\r\n prefix = \"(<)?\"\r\n suffix = \"(>)?\"\r\n amino_group = \"(\\[[A-Z]*\\])\"\r\n amino_single = \"[A-Z]\"\r\n amino_any = \"x\"\r\n avoid = \"(\\{[A-Z]*\\})\"\r\n correct_format_once = \"((\" + amino_group + \"|\" + amino_single + \"|\" + amino_any + \"|\" + avoid + \")\" + occurrences + \")\"\r\n correct_format_repeat = \"((\" + amino_group + \"|\" + amino_single + \"|\" + amino_any + \"|\" + avoid + \")\" + occurrences + \"-)*\"\r\n correct_format = prefix + correct_format_repeat + correct_format_once + suffix\r\n\r\n # check if the pattern is a valid prosite format\r\n check = re.search(correct_format, pattern)\r\n # return boolean value\r\n return check.group() is pattern and re.compile(check.group())\r\n\r\n def __patterns_to_domains(self, pattern_file):\r\n # initialize empty dictionary\r\n dict_from_csv = {}\r\n # read file into dictionary\r\n try:\r\n dict_from_csv = pd.read_csv(pattern_file, header=0, index_col=0, squeeze=True).to_dict()\r\n except ValueError:\r\n print(\"File is not in wanted format\")\r\n # turn the prosite regex to python regex\r\n regex_dict = self.__prosite_to_python(dict_from_csv)\r\n return regex_dict\r\n\r\n def classify(self, seq_list, csv_file):\r\n protein_domains = dict()\r\n # for every protein in the list\r\n protein_domains[\"Sequence\"] = \"Domains\"\r\n for seq in seq_list:\r\n domains = \"\"\r\n flag = False\r\n # go through each regex\r\n for reg in self.regex_dict:\r\n # check if the pattern fits any of the proteins\r\n if re.search(reg, seq):\r\n domains += self.regex_dict[reg] + \";\"\r\n flag = True\r\n if not flag:\r\n domains = \"NA\"\r\n if flag:\r\n domains = domains[:-1]\r\n protein_domains[seq] = domains\r\n # turn dictionary into dataframe, and write it to csv file\r\n df = pd.DataFrame.from_dict(protein_domains, orient='index')\r\n df.to_csv(csv_file, index=True, header=False)\r\n\r\n\r\n# define DNA and RNA polymerase\r\nclass Polymerase:\r\n # constructor\r\n def __init__(self, type, error_rate=0):\r\n self.type = type\r\n self.error_rate = error_rate\r\n # define translation differently for RNA/DNA polymerase\r\n A_translation = \"\"\r\n if type == \"RNA\":\r\n A_translation = \"U\"\r\n elif type == \"DNA\":\r\n A_translation = \"T\"\r\n # initialize a dictionary for transcribing\r\n self.transcribing_dictionary = {\"T\": \"A\", \"t\": \"A\", \"C\": \"G\", \"c\": \"G\", \"G\": \"C\", \"g\": \"C\",\r\n \"A\": A_translation,\r\n \"a\": A_translation}\r\n\r\n # this function receive a DNA sequence and translate it to RNA\r\n def transcribe(self, dna_seq):\r\n\r\n # find the indices of the mutations\r\n num_of_mutants = math.ceil(self.error_rate * len(dna_seq))\r\n # locations = np.random.choice(range(1, len(dna_seq)), num_of_mutants)\r\n locations = random.sample(range(0, len(dna_seq)), num_of_mutants)\r\n # initialize an empty list\r\n rna = \"\"\r\n # translate the letter according to the dictionary\r\n for ind, nuc in enumerate(dna_seq):\r\n if nuc in self.transcribing_dictionary.keys():\r\n # if we need to insert mutation\r\n if ind in locations:\r\n # create a random mutation. if it's synonym- replace it\r\n nucleotides = set(self.transcribing_dictionary.values()) # unique trans dic values\r\n nucleotides = list(nucleotides)\r\n nucleotides.remove(self.transcribing_dictionary[nuc])\r\n mut = np.random.choice(nucleotides)\r\n # while mut == self.transcribing_dictionary[nuc]:\r\n # mut = np.random.choice(list(self.transcribing_dictionary.values()))\r\n # add the mutation to the sequence\r\n rna += mut\r\n else:\r\n rna += self.transcribing_dictionary[nuc]\r\n else:\r\n break\r\n # revers the sequence so it will be 5'-3', and cut the last character to fit the format\r\n if rna:\r\n return rna[::-1]\r\n else:\r\n return None\r\n\r\n\r\n# define ribosome\r\nclass Ribosome:\r\n # constructor\r\n def __init__(self, genetic_code, start_codons):\r\n self.genetic_code = genetic_code\r\n self.start_codons = start_codons\r\n\r\n # turn RNA sequence to the biggest protein available\r\n def synthesize(self, rna_seq):\r\n # calls to translate\r\n protein = self.translate(rna_seq)\r\n if protein:\r\n return protein\r\n else:\r\n return None\r\n\r\n # this function receives rna sequence and returns the codons of the longest reading frame\r\n def translate(self, rna_seq):\r\n # initialize the biggest protein with empty string\r\n max_protein = \"\"\r\n # go through every nucleotide and look for start codon (AUG)\r\n for i in range(len(rna_seq)):\r\n if rna_seq[i:i + 3] in self.start_codons:\r\n # initialize the protein we will go through\r\n protein = \"\"\r\n # go through each codon and add it to the protein. stop in stop codon or at the end of the sequence\r\n for j in range(i, len(rna_seq) - 2, 3):\r\n codon = rna_seq[j:j + 3]\r\n # check for stop codon\r\n if not self.genetic_code[codon]:\r\n i += 4\r\n break\r\n else:\r\n # add the codon to the protein\r\n protein += self.genetic_code[codon]\r\n # when the protein is done, check if it's bigger than the biggest protein, and replace it if so\r\n if len(protein) > len(max_protein):\r\n max_protein = protein\r\n return max_protein\r\n\r\n\r\nclass Cell:\r\n # constructor\r\n def __init__(self, name, genome, num_copies, genetic_code, start_codons, division_rate):\r\n self.name = name\r\n self.genome = []\r\n self.genome.append(genome)\r\n # input check\r\n if type(num_copies) is int and num_copies > 0:\r\n self.num_copies = num_copies\r\n self.genetic_code = genetic_code\r\n self.start_codons = start_codons\r\n # input check\r\n if type(division_rate) is int and division_rate > 1:\r\n self.division_rate = division_rate\r\n # initialize RNA+DNA polymerases\r\n self.RNA_Polymerase = Polymerase(\"RNA\", 0)\r\n self.DNA_Polymerase = Polymerase(\"DNA\", 0)\r\n # initialize Ribosome\r\n self.Ribosome = Ribosome(genetic_code, start_codons)\r\n\r\n # define a printing method\r\n def __str__(self):\r\n return \"<\" + str(self.name) + \", \" + str(self.num_copies) + \", \" + str(self.division_rate) + \">\"\r\n\r\n # returns a list of n identical cells, while n is the division rate\r\n def mitosis(self):\r\n return self * self.division_rate\r\n\r\n # define the * operator\r\n def __mul__(self, num):\r\n cells = [self]\r\n return cells * num\r\n\r\n # return 2 cells: one identical to the original, one with the complimentary genome. both with n/2 genome copies\r\n def meiosis(self):\r\n if self.num_copies % 2 != 0:\r\n return None\r\n new_cell = Cell(self.name, self.genome, (self.num_copies / 2), self.genetic_code, self.start_codons,\r\n self.division_rate)\r\n # find the complementary strands of the genome\r\n comp_genome = []\r\n for seq in self.genome:\r\n comp_genome.append(self.DNA_Polymerase.transcribe(seq))\r\n # define the complementary cell\r\n new_comp = Cell(self.name, comp_genome, self.num_copies / 2, self.genetic_code, self.start_codons,\r\n self.division_rate)\r\n return [new_cell, new_comp]\r\n\r\n # this function find microsatellites in repeats of 3-6\r\n def find_srr(self, dna_seq):\r\n # flag to know if there are satellites\r\n satellites = {}\r\n # looking for microsatellites in increasing sizes of nucleotides\r\n for size_of_match in range(1, 7):\r\n # looking for satellite in different reading frames\r\n for i in range(len(dna_seq) - (len(dna_seq) % size_of_match)):\r\n count = 1 # number of repeats\r\n # checking for repeats\r\n for j in range(i, len(dna_seq) - (len(dna_seq) % size_of_match), size_of_match):\r\n # if the sequences are the same- increase the counter\r\n if dna_seq[j: j + size_of_match] == dna_seq[j + size_of_match: j + 2 * size_of_match]:\r\n count += 1\r\n else:\r\n # if the sequences are different and there are more than 3 repeats- add it to the dictionary\r\n if count >= 3:\r\n satellite = dna_seq[j: j + size_of_match]\r\n # if the satellite exists already- check if the count is bigger\r\n if satellite in satellites.keys():\r\n if count <= satellites[satellite]:\r\n break\r\n # if the satellite didn't exist/the count is smaller- update the dictionary\r\n satellites[satellite] = count\r\n break\r\n size_of_match += 1\r\n if satellites:\r\n sat_list = \"\"\r\n for satellite, count in sorted(satellites.items(), key=lambda t: t[0]):\r\n sat_list += satellite + \",\" + str(count) + \";\"\r\n return sat_list[:-1]\r\n else:\r\n return None\r\n\r\n # returns tuple for every strand. each tuple contains: satellites, RNA transcribe, translated protein\r\n def repertoire(self):\r\n list_of_tuples = []\r\n for sequence in self.genome:\r\n # find the satellites\r\n satellites = self.find_srr(sequence)\r\n if not satellites:\r\n satellites = \"No simple repeats in DNA sequence\"\r\n # find RNA transcribe\r\n rna_seq = self.RNA_Polymerase.transcribe(sequence)\r\n # find the biggest protein available\r\n protein = self.Ribosome.synthesize(rna_seq)\r\n if not protein:\r\n protein = \"Non-coding RNA\"\r\n seq = (satellites, rna_seq, protein)\r\n # returns list of tuples\r\n list_of_tuples.append(seq)\r\n return list_of_tuples\r\n\r\n\r\n# inherit class from cell\r\nclass ProkaryoticCell(Cell):\r\n # constructor\r\n def __init__(self, genome):\r\n prokaryotic_genetic_code = {\r\n 'AUA': 'I', 'AUC': 'I', 'AUU': 'I', 'AUG': 'M',\r\n 'ACA': 'T', 'ACC': 'T', 'ACG': 'T', 'ACU': 'T',\r\n 'AAC': 'N', 'AAU': 'N', 'AAA': 'K', 'AAG': 'K',\r\n 'AGC': 'S', 'AGU': 'S', 'AGA': 'R', 'AGG': 'R',\r\n 'CUA': 'L', 'CUC': 'L', 'CUG': 'L', 'CUU': 'L',\r\n 'CCA': 'P', 'CCC': 'P', 'CCG': 'P', 'CCU': 'P',\r\n 'CAC': 'H', 'CAU': 'H', 'CAA': 'Q', 'CAG': 'Q',\r\n 'CGA': 'R', 'CGC': 'R', 'CGG': 'R', 'CGU': 'R',\r\n 'GUA': 'V', 'GUC': 'V', 'GUG': 'V', 'GUU': 'V',\r\n 'GCA': 'A', 'GCC': 'A', 'GCG': 'A', 'GCU': 'A',\r\n 'GAC': 'D', 'GAU': 'D', 'GAA': 'E', 'GAG': 'E',\r\n 'GGA': 'G', 'GGC': 'G', 'GGG': 'G', 'GGU': 'G',\r\n 'UCA': 'S', 'UCC': 'S', 'UCG': 'S', 'UCU': 'S',\r\n 'UUC': 'F', 'UUU': 'F', 'UUA': 'L', 'UUG': 'L',\r\n 'UAC': 'Y', 'UAU': 'Y', 'UAA': None, 'UAG': None,\r\n 'UGC': 'C', 'UGU': 'C', 'UGA': 'U', 'UGG': 'W'}\r\n start_codons = (\"AUG\", \"GUG\", \"UUG\")\r\n division_rate = 4\r\n num_copies = 1\r\n # calls parent's constructor\r\n super().__init__(\"ProKaryoticCell\", genome, num_copies, prokaryotic_genetic_code, start_codons, division_rate)\r\n\r\n\r\n# inherit class from cell\r\nclass EukaryoticCell(Cell):\r\n # constructor\r\n def __init__(self, name, genome, division_rate):\r\n standard_genetic_code = {\r\n 'AUA': 'I', 'AUC': 'I', 'AUU': 'I', 'AUG': 'M',\r\n 'ACA': 'T', 'ACC': 'T', 'ACG': 'T', 'ACU': 'T',\r\n 'AAC': 'N', 'AAU': 'N', 'AAA': 'K', 'AAG': 'K',\r\n 'AGC': 'S', 'AGU': 'S', 'AGA': 'R', 'AGG': 'R',\r\n 'CUA': 'L', 'CUC': 'L', 'CUG': 'L', 'CUU': 'L',\r\n 'CCA': 'P', 'CCC': 'P', 'CCG': 'P', 'CCU': 'P',\r\n 'CAC': 'H', 'CAU': 'H', 'CAA': 'Q', 'CAG': 'Q',\r\n 'CGA': 'R', 'CGC': 'R', 'CGG': 'R', 'CGU': 'R',\r\n 'GUA': 'V', 'GUC': 'V', 'GUG': 'V', 'GUU': 'V',\r\n 'GCA': 'A', 'GCC': 'A', 'GCG': 'A', 'GCU': 'A',\r\n 'GAC': 'D', 'GAU': 'D', 'GAA': 'E', 'GAG': 'E',\r\n 'GGA': 'G', 'GGC': 'G', 'GGG': 'G', 'GGU': 'G',\r\n 'UCA': 'S', 'UCC': 'S', 'UCG': 'S', 'UCU': 'S',\r\n 'UUC': 'F', 'UUU': 'F', 'UUA': 'L', 'UUG': 'L',\r\n 'UAC': 'Y', 'UAU': 'Y', 'UAA': None, 'UAG': None,\r\n 'UGC': 'C', 'UGU': 'C', 'UGA': None, 'UGG': 'W'}\r\n start_codons = \"AUG\"\r\n num_copies = 2\r\n # calls parent's constructor\r\n super().__init__(name, genome, num_copies, standard_genetic_code, start_codons, division_rate)\r\n\r\n\r\n# inherit from EukaryoticCell\r\nclass NeuronCell(EukaryoticCell):\r\n # constructor\r\n def __init__(self, genome):\r\n division_rate = 2\r\n # calls parent's constructor\r\n super().__init__(\"NeuronCell\", genome, division_rate)\r\n\r\n\r\n# inherit from EukaryoticCell\r\nclass StemCell(EukaryoticCell):\r\n def __init__(self, genome):\r\n division_rate = 3\r\n # calls parent's constructor\r\n super().__init__(\"StemCell\", genome, division_rate)\r\n\r\n\r\n# inherit from stem cell\r\nclass MutantCell(StemCell):\r\n def __init__(self, genome, num_mutations=0, error_rate=0.05):\r\n # call father's constructor\r\n super().__init__(genome)\r\n # override the name\r\n self.name = \"MutantCell\"\r\n # default mutation rate is 1:20\r\n self.DNA_Polymerase.error_rate = error_rate\r\n self.RNA_Polymerase.error_rate = 0\r\n # initialize num of muts to 0\r\n self.num_of_mutations = num_mutations\r\n self.num_of_new_mutations_per_generation = self.calculate_num_of_muts_per_generation()\r\n\r\n def calculate_num_of_muts_per_generation(self):\r\n num_of_new_mutations_per_generation = 0\r\n for g in self.genome:\r\n num_of_new_mutations_per_generation += math.ceil(len(g) * self.DNA_Polymerase.error_rate)\r\n return num_of_new_mutations_per_generation\r\n\r\n # returns a list of n identical cells, while n is the division rate\r\n def mitosis(self):\r\n # get a list of mutants\r\n mutants = self * self.division_rate\r\n mutants[0] = self\r\n return mutants\r\n\r\n # define the * operator\r\n def __mul__(self, num):\r\n # create mutant genome\r\n t_genome = self.get_mutant_genome()\r\n # check if the number of mutations is under 10\r\n if self.num_of_mutations + self.num_of_new_mutations_per_generation > 10:\r\n # create cancer cell\r\n mutant = CancerCell(t_genome,\r\n num_mutations=self.num_of_mutations + self.num_of_new_mutations_per_generation,\r\n error_rate=self.DNA_Polymerase.error_rate)\r\n else:\r\n # create mutant cell\r\n mutant = MutantCell(t_genome,\r\n num_mutations=self.num_of_mutations + self.num_of_new_mutations_per_generation,\r\n error_rate=self.DNA_Polymerase.error_rate)\r\n\r\n # def the number of mutations the cell has\r\n cells = [mutant]\r\n return cells * num\r\n\r\n def get_mutant_genome(self):\r\n # t_genome = []\r\n complement = None\r\n for dna in self.genome:\r\n complement = Seq(self.DNA_Polymerase.transcribe(dna))\r\n # t_genome.append(str(complement.reverse_complement()))\r\n complement = str(complement.reverse_complement())\r\n return complement\r\n\r\n\r\nclass CancerCell(MutantCell):\r\n def __init__(self, genome, num_mutations, error_rate=0.05):\r\n super().__init__(genome, num_mutations, error_rate=error_rate)\r\n self.division_rate = 10\r\n self.name = \"CancerCell\"\r\n\r\n\r\n# factory to initialize each cell\r\nclass CellFactory:\r\n def create_cell_object(self, name, genome):\r\n if name == \"NeuronCell\":\r\n return NeuronCell(genome)\r\n if name == \"StemCell\":\r\n return StemCell(genome)\r\n if name == \"ProkaryoticCell\":\r\n return ProkaryoticCell(genome)\r\n if name == \"MutantCell\":\r\n return MutantCell(genome)\r\n if name == \"CancerCell\":\r\n return CancerCell(genome, num_mutations=10)\r\n else:\r\n raise AssertionError(name)\r\n\r\n\r\n# check if the input sequences are valid as genome\r\ndef is_genome_valid(sequences):\r\n genome = (\"A\", \"T\", \"G\", \"C\",)\r\n for seq in sequences:\r\n matched_list = [characters in genome for characters in seq.upper()]\r\n assert all(matched_list), \"Invalid input \" + seq\r\n\r\n\r\ndef cells_divisions(cell, divisions_num, max_cell_num):\r\n divs = 0\r\n num_of_cells = 1\r\n cells = [cell]\r\n # while we didn't do maximum num of divisions:\r\n while divs < int(divisions_num):\r\n # go through each cell in the list\r\n for c in range(num_of_cells):\r\n # if we will not exceed from the max number of cells- do mitosis\r\n # the -1 is because we exclude the cell that actually is going through mitosis\r\n if len(cells) <= max_cell_num - (cells[c].division_rate - 1):\r\n # adding the new cells to the list, excluding the original cell that actually did mitosis\r\n cells += (cells[c].mitosis()[1:])\r\n else: # we have the max number of cells and can exit both loops\r\n break\r\n # after all the cells went through mitosis once- we increase the number of divisions\r\n divs += 1\r\n num_of_cells = len(cells)\r\n return cells\r\n\r\n\r\ndef get_different_proteins_from_cells(cells):\r\n proteins = []\r\n for cell in cells:\r\n for sequence in cell.genome:\r\n # rep = cell.repertoire()\r\n rna_seq = cell.RNA_Polymerase.transcribe(sequence)\r\n # find the biggest protein available\r\n cell_proteins = cell.Ribosome.synthesize(rna_seq)\r\n if not cell_proteins:\r\n cell_proteins = \"Non-coding RNA\"\r\n proteins += [cell_proteins]\r\n proteins = np.array(proteins)\r\n unique_proteins = np.unique(proteins)\r\n unique_proteins = np.delete(unique_proteins, np.where(unique_proteins == \"Non-coding RNA\"))\r\n return unique_proteins\r\n\r\n\r\ndef get_most_mutant_cell(mutant_cells):\r\n most_mutant = None\r\n muts_num = 0\r\n for cell in mutant_cells:\r\n if cell.num_of_mutations > muts_num:\r\n most_mutant = cell\r\n muts_num = cell.num_of_mutations\r\n return most_mutant\r\n\r\n\r\ndef get_genome_from_fasta(fastaFile):\r\n GenomicSequences = []\r\n # records = list(SeqIO.parse(fastaFile, \"fasta\"))\r\n # for r in records:\r\n # genome.append(r.seq)\r\n for record in SeqIO.parse(fastaFile, \"fasta\"):\r\n GenomicSequences.append(record.seq)\r\n return GenomicSequences\r\n\r\n\r\n\"\"\"\r\nthis function gets a sequence and returns a df that contains the number of cancer cells,\r\nmutant cells and different proteins, as a function of different error rates and divisions numbers\r\n\"\"\"\r\ndef get_results(seq):\r\n # initialize a list of error rates\r\n error_rates = np.arange(0.05, 0.5, 0.05)\r\n error_rates = np.concatenate(([0.01], error_rates, [0.5]))\r\n # initialize a list of divisions number\r\n division_numbers = range(1, 6)\r\n # initialize an empty dataframe\r\n df = pd.DataFrame(\r\n columns=['division_number', 'error_rate', 'number_of_cancer_cells', 'number_of_mutant_cells',\r\n 'number_of_proteins'])\r\n # go through each division number\r\n for div_num in division_numbers:\r\n # go through each error rate\r\n for error_rate in error_rates:\r\n # initialize a mutant cell\r\n mut_cell = MutantCell(str(seq), error_rate=error_rate)\r\n # get all the cells after mitosis\r\n cells = cells_divisions(mut_cell, div_num, float('inf'))\r\n # get number of cancer cells\r\n cancer_cells_num = len([c for c in cells if c.name == \"CancerCell\"])\r\n # number of mutant cells\r\n mutant_cell_num = len(cells) - cancer_cells_num\r\n # get a list of the different proteins\r\n proteins = get_different_proteins_from_cells(cells)\r\n df = df.append({'division_number': div_num, 'error_rate': error_rate,\r\n 'number_of_cancer_cells': cancer_cells_num, 'number_of_mutant_cells': mutant_cell_num,\r\n 'number_of_proteins': len(proteins)}, ignore_index=True)\r\n return df\r\n\r\n\r\n# option number 1 for the combined graphs- linear graphs\r\n\"\"\"\r\ndef create_combined_graphs(data_df, sequences):\r\n # the different options for x axis\r\n x_axes = [\"division_number\", \"error_rate\"]\r\n # go through each kind of x axis\r\n for ind, x in enumerate(x_axes):\r\n # initialize a new plot\r\n plt.figure()\r\n curves = []\r\n # create a curve for each sequence\r\n for num, seq in enumerate(sequences):\r\n # get the relevant data of the current sequence from the df\r\n data_df_seq = data_df[data_df['Sequence'].str.contains(str(seq))]\r\n y_axis = data_df_seq['number_of_proteins']\r\n x_axis = data_df_seq[x]\r\n curves.append(x_axis)\r\n plt.plot(x_axis, y_axis, label=(\"seq \" + str(num + 1)))\r\n plt.xlabel(x)\r\n plt.ylabel('number_of_proteins')\r\n title = \"number of proteins as a function of \" + x\r\n plt.title(title)\r\n plt.legend()\r\n plt.savefig(\"exercise4_207256991_208812628_\" + title + \".png\")\r\n\"\"\"\r\n\r\n\r\n\"\"\"\r\nthis function creates a plot for each sequence:\r\nx axis: error rate\r\ny axis: divisions number\r\nsize+color of points: number of proteins\r\n\"\"\"\r\n# option number 2 to combined graphs: scatter plots\r\ndef create_combined_graphs_2(data_df, sequences):\r\n # go through each kind of x axis\r\n for ind, seq in enumerate(sequences):\r\n # initialize a new plot\r\n plt.figure()\r\n # get the data of one sequence\r\n data_df_seq = data_df[data_df['Sequence'].str.contains(str(seq))]\r\n # set the axes\r\n x_axis = data_df_seq[\"error_rate\"]\r\n y_axis = data_df_seq[\"division_number\"]\r\n # number of proteins\r\n prot_num = data_df_seq['number_of_proteins']\r\n # create scatter plot:\r\n # define the sizes and colors to represent the number of protein\r\n plt.scatter(x_axis, y_axis, c=prot_num, cmap='viridis', s=prot_num, alpha=0.7)\r\n # labels and titles\r\n plt.xlabel(\"error rate\")\r\n plt.ylabel(\"division number\")\r\n title = f\"sequence {ind+1} protein number ~ division number and error rate\"\r\n plt.suptitle(f\"sequence {seq}\")\r\n plt.title(\"number of proteins is represented by size and color\")\r\n plt.colorbar()\r\n plt.savefig(\"exercise4_207256991_208812628_\" + title + \".png\")\r\n\r\n\r\n# gets the required plots: a plot for number of proteins, number of mutant cells\r\n# and number of cancer cells as a function of error rate\r\ndef get_graphs_per_seq(sequences):\r\n # read the csv file we created\r\n data_df = pd.read_csv('exercise4_207256991_208812628.csv', sep=',')\r\n # keep only the rows of division_number = 5\r\n data_df_max_divs = data_df[data_df['division_number'].astype(str).str.contains('5')]\r\n plot_num = 1\r\n # go through each sequence\r\n for ind, seq in enumerate(sequences):\r\n # keep only the data for this sequence\r\n data_df_seq = data_df_max_divs[data_df_max_divs['Sequence'].str.contains(str(seq))]\r\n # define the x axis as error rate\r\n x_axis = data_df_seq['error_rate']\r\n # define the different options for y axis\r\n y_axes = [\"number_of_cancer_cells\", \"number_of_mutant_cells\", \"number_of_proteins\"]\r\n # go through each option\r\n for y in y_axes:\r\n # define a specific plot and clear it from previous plots\r\n plt.figure(plot_num)\r\n # define the y axis\r\n y_axis = data_df_seq[y]\r\n plt.plot(x_axis, y_axis)\r\n # create labels\r\n plt.xlabel('error_rate')\r\n plt.ylabel(y)\r\n plt.title(str(seq))\r\n # save the plot\r\n plt.savefig(\"exercise4_207256991_208812628_\" + f\"seq_{ind+1}_\" + y + \".png\")\r\n plot_num += 1\r\n plt.clf()\r\n # create_combined_graphs(data_df, sequences)\r\n # create the combined graphs\r\n create_combined_graphs_2(data_df, sequences)\r\n\r\n\r\ndef main():\r\n random.seed(1)\r\n # input checkups\r\n assert len(sys.argv) == 2, \"Wrong number of inputs\"\r\n fastaFile = sys.argv[1]\r\n assert os.path.isfile(fastaFile), \"input is not a file \" + fastaFile\r\n name, extension = os.path.splitext(fastaFile)\r\n assert extension == \".fa\", \"input must be fasta file \" + fastaFile\r\n # get list of the sequences from the input fasta file\r\n # get the sequences names from the file\r\n seqs = []\r\n seq_names = []\r\n for seq_record in SeqIO.parse(fastaFile, \"fasta\"):\r\n seqs.append(str(seq_record.seq))\r\n seq_names.append(seq_record.id)\r\n sequences = pd.DataFrame(list(zip(seq_names, seqs)), columns=['Name', 'Seq'])\r\n\r\n # check input sequences\r\n is_genome_valid(seqs)\r\n\r\n # initialize the results dataframe\r\n df = pd.DataFrame(\r\n columns=['Sequence', 'division_number', 'error_rate', 'number_of_cancer_cells', 'number_of_mutant_cells',\r\n 'number_of_proteins'])\r\n # go through each sequence\r\n for index, seq in sequences.iterrows():\r\n # create an iterable list of the sequence for the map function\r\n # it's just a list with the same sequence 3 times\r\n itr_seq = [seq[\"Seq\"]] * 3\r\n # create 3 processes\r\n with Pool(3) as p:\r\n # the output is a list of 3 dataframes, one from each process\r\n results = p.map(get_results, itr_seq)\r\n # calculate the average result\r\n results = (results[0] + results[1] + results[2]) / 3\r\n # create a list with the sequence name, for the csv file\r\n seq_list = [seq['Name']] * len(results.index)\r\n # insert the list to the dataframe in the first column\r\n results.insert(0, \"Sequence\", seq_list)\r\n # concatenate the results dataframe to the df of all the sequences\r\n df = pd.concat([df, results])\r\n # save results to csv\r\n df.to_csv('exercise4_207256991_208812628.csv', index=False)\r\n # create the required graphs\r\n get_graphs_per_seq(sequences['Name'])\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n", "repo_name": "TamarSaad/University-Assignments", "sub_path": "Lamut/ex4/exercise4_207256991_208812628.py", "file_name": "exercise4_207256991_208812628.py", "file_ext": "py", "file_size_in_byte": 28627, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "re.search", "line_number": 48, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 50, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 57, "usage_type": "call"}, {"api_name": "re.search", "line_number": 74, "usage_type": "call"}, {"api_name": "pandas.DataFrame.from_dict", "line_number": 83, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 83, "usage_type": "attribute"}, {"api_name": "math.ceil", "line_number": 108, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 122, "usage_type": "attribute"}, {"api_name": "math.ceil", "line_number": 370, "usage_type": "call"}, {"api_name": "Bio.Seq.Seq", "line_number": 404, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 474, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 475, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 476, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 476, "usage_type": "call"}, {"api_name": "Bio.SeqIO.parse", "line_number": 495, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 495, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 506, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 507, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 511, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 572, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 572, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 582, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 582, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 584, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 584, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 585, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 585, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.suptitle", "line_number": 587, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 587, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 588, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 588, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 589, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 589, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 590, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 590, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 597, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 612, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 612, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 615, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 615, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 617, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 617, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 618, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 618, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 619, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 619, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 621, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 621, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 623, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 623, "usage_type": "name"}, {"api_name": "random.seed", "line_number": 630, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 632, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 633, "usage_type": "attribute"}, {"api_name": "os.path.path.isfile", "line_number": 634, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 634, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 634, "usage_type": "name"}, {"api_name": "os.path.path.splitext", "line_number": 635, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 635, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 635, "usage_type": "name"}, {"api_name": "Bio.SeqIO.parse", "line_number": 641, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 641, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 644, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 650, "usage_type": "call"}, {"api_name": "multiprocessing.Pool", "line_number": 659, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 669, "usage_type": "call"}]} +{"seq_id": "39124116231", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # COMPUTER VISION AND IOT INTERN\n# \n# # SPARKS FOUNDATION\n# \n# ## TASK 1 : Object Detection\n# \n# ## Detect the object in a photo/video\n# \n# ## By: Swati Namdev\n\n# In[1]:\n\n\nimport numpy as np\nimport cv2\n\n\n# In[2]:\n\n\nnet=cv2.dnn.readNet(\"yolov3.weights\",\"yolov3.cfg\")\n\n\n# In[3]:\n\n\nclasses=[]\nwith open(\"coco.names\",\"r\") as f:\n classes=[line.strip()for line in f.readlines()]\nprint(classes)\n\n\n# In[4]:\n\n\nlayer_names=net.getLayerNames()\noutput_layers=[layer_names[i[0]-1] for i in net.getUnconnectedOutLayers()]\n\n\n# In[5]:\n\n\ncolors=np.random.uniform(0,255, size=(len(classes),3))\n\n\n# In[6]:\n\n\nimg=cv2.imread(\"room_ser.jpg\")\nimg=cv2.resize(img,None,fx=0.4,fy=0.4)\nheight,width,channels=img.shape\nblob=cv2.dnn.blobFromImage(img,0.00392,(416,416),(0,0,0),True,crop=False)\n\n\n# In[7]:\n\n\n''''for b in blob:\n for n,img_blob in enumerate(b):\n cv2.imshow(str(n),img_blob)'''\n\n\n# In[8]:\n\n\nnet.setInput(blob)\nouts=net.forward(output_layers)\n\n\n# In[9]:\n\n\nclass_ids=[]\nconfidences=[]\nboxes=[]\n\n\n# In[10]:\n\n\nfor out in outs:\n for detection in out:\n scores=detection[5:]\n class_id=np.argmax(scores)\n confidence=scores[class_id]\n if confidence>0.5:\n center_x=int(detection[0]*width)\n center_y=int(detection[1]*height)\n w=int(detection[2]*width)\n h=int(detection[1]*height)\n \n x=int(center_x-w/2)\n y=int(center_y-h/2)\n \n boxes.append([x,y,w,h])\n confidences.append(float(confidence))\n class_ids.append(class_id)\n\n\n# In[11]:\n\n\nprint(len(boxes))\n\n\n# In[12]:\n\n\n#number_objects_detected=len(boxes)\nindexes=cv2.dnn.NMSBoxes(boxes,confidences,0.5,0.4)\n#print(indexes)\nfont=cv2.FONT_HERSHEY_PLAIN\nfor i in range(len(boxes)):\n if i in indexes:\n x,y,w,h=boxes[i]\n label=str(classes[class_ids[i]])\n color=colors[i]\n cv2.rectangle(img,(x,y),(x+w,y+h),color,2)\n cv2.putText(img,label,(x,y+30),font,3,color,3)\n #print(label)\n\n\n# In[ ]:\n\n\n\n\n\n# In[13]:\n\n\ncv2.imshow(\"Image\",img)\ncv2.waitKey(0)\n\n\n# In[14]:\n\n\ncv2.destroyAllWindows()\n\n\n# In[ ]:\n\n\n\n\n", "repo_name": "swati0806/OBJECT_DETECTION", "sub_path": "photo_Object_detection1.py", "file_name": "photo_Object_detection1.py", "file_ext": "py", "file_size_in_byte": 2162, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "cv2.dnn.readNet", "line_number": 24, "usage_type": "call"}, {"api_name": "cv2.dnn", "line_number": 24, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 46, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 52, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 53, "usage_type": "call"}, {"api_name": "cv2.dnn.blobFromImage", "line_number": 55, "usage_type": "call"}, {"api_name": "cv2.dnn", "line_number": 55, "usage_type": "attribute"}, {"api_name": "numpy.argmax", "line_number": 87, "usage_type": "call"}, {"api_name": "cv2.dnn.NMSBoxes", "line_number": 113, "usage_type": "call"}, {"api_name": "cv2.dnn", "line_number": 113, "usage_type": "attribute"}, {"api_name": "cv2.FONT_HERSHEY_PLAIN", "line_number": 115, "usage_type": "attribute"}, {"api_name": "cv2.rectangle", "line_number": 121, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 122, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 135, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 136, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 142, "usage_type": "call"}]} +{"seq_id": "71540964543", "text": "import unittest\nfrom jettools import validation\nimport typing\n\n\ndef _verify_dict_list(d) -> bool:\n for key in d:\n if not isinstance(key, str):\n return False\n if not isinstance(d[key], list):\n return False\n for item in d[key]:\n if not isinstance(item, int):\n return False\n return True\n\n\nclass TestAreValidArgs(unittest.TestCase):\n def test_should_raise_exception_if_not_all_args_are_validators(self):\n with self.assertRaises(ValueError):\n validation.are_valid_args([validation.Validator('test', 2, int), 3])\n\n def test_should_return_true_if_none(self):\n self.assertTrue(validation.are_valid_args([]))\n\n def test_should_return_false_if_an_arg_doesnt_validate(self):\n args = [\n validation.Validator('name', 4, str),\n validation.Validator('test3', 6.2, [str, int])\n ]\n self.assertFalse(validation.are_valid_args(args))\n\n def test_should_return_true_if_valid(self):\n args = [\n validation.Validator('name', 4, int),\n validation.Validator('test2', 'tst', str),\n validation.Validator('test3', 6.2, [str, int, float]),\n validation.Validator('test4', (2,), typing.Tuple),\n ]\n result = validation.are_valid_args(args)\n print(result.message)\n self.assertTrue(result)\n\n def test_should_raise_exception_if_parameterized_type(self):\n args = [\n validation.Validator('test4', (2,), typing.Tuple[str]),\n ]\n with self.assertRaises(ValueError):\n result = validation.are_valid_args(args)\n\n def test_should_validate_with_functions(self):\n d = {'test': [1, 2, 3, 4]}\n args = [\n validation.Validator('name', d, _verify_dict_list),\n validation.Validator('test2', d['test'], lambda x: isinstance(x, typing.List))\n ]\n result = validation.are_valid_args(args)\n print(result.message)\n self.assertTrue(result)\n", "repo_name": "jettdc/jetts-tools", "sub_path": "test/test_validation.py", "file_name": "test_validation.py", "file_ext": "py", "file_size_in_byte": 2027, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "unittest.TestCase", "line_number": 18, "usage_type": "attribute"}, {"api_name": "jettools.validation.are_valid_args", "line_number": 21, "usage_type": "call"}, {"api_name": "jettools.validation", "line_number": 21, "usage_type": "name"}, {"api_name": "jettools.validation.Validator", "line_number": 21, "usage_type": "call"}, {"api_name": "jettools.validation.are_valid_args", "line_number": 24, "usage_type": "call"}, {"api_name": "jettools.validation", "line_number": 24, "usage_type": "name"}, {"api_name": "jettools.validation.Validator", "line_number": 28, "usage_type": "call"}, {"api_name": "jettools.validation", "line_number": 28, "usage_type": "name"}, {"api_name": "jettools.validation.Validator", "line_number": 29, "usage_type": "call"}, {"api_name": "jettools.validation", "line_number": 29, "usage_type": "name"}, {"api_name": "jettools.validation.are_valid_args", "line_number": 31, "usage_type": "call"}, {"api_name": "jettools.validation", "line_number": 31, "usage_type": "name"}, {"api_name": "jettools.validation.Validator", "line_number": 35, "usage_type": "call"}, {"api_name": "jettools.validation", "line_number": 35, "usage_type": "name"}, {"api_name": "jettools.validation.Validator", "line_number": 36, "usage_type": "call"}, {"api_name": "jettools.validation", "line_number": 36, "usage_type": "name"}, {"api_name": "jettools.validation.Validator", "line_number": 37, "usage_type": "call"}, {"api_name": "jettools.validation", "line_number": 37, "usage_type": "name"}, {"api_name": "jettools.validation.Validator", "line_number": 38, "usage_type": "call"}, {"api_name": "jettools.validation", "line_number": 38, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 38, "usage_type": "attribute"}, {"api_name": "jettools.validation.are_valid_args", "line_number": 40, "usage_type": "call"}, {"api_name": "jettools.validation", "line_number": 40, "usage_type": "name"}, {"api_name": "jettools.validation.Validator", "line_number": 46, "usage_type": "call"}, {"api_name": "jettools.validation", "line_number": 46, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 46, "usage_type": "attribute"}, {"api_name": "jettools.validation.are_valid_args", "line_number": 49, "usage_type": "call"}, {"api_name": "jettools.validation", "line_number": 49, "usage_type": "name"}, {"api_name": "jettools.validation.Validator", "line_number": 54, "usage_type": "call"}, {"api_name": "jettools.validation", "line_number": 54, "usage_type": "name"}, {"api_name": "jettools.validation.Validator", "line_number": 55, "usage_type": "call"}, {"api_name": "jettools.validation", "line_number": 55, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 55, "usage_type": "attribute"}, {"api_name": "jettools.validation.are_valid_args", "line_number": 57, "usage_type": "call"}, {"api_name": "jettools.validation", "line_number": 57, "usage_type": "name"}]} +{"seq_id": "17842867359", "text": "import os\nfrom unittest.mock import patch\n\nimport pytest\nimport shutil\nimport unittest\nfrom typing import Optional\n\nimport ray.air\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.utils import shuffle\n\nfrom ray import tune\nfrom ray.air.config import RunConfig, ScalingConfig\nfrom ray.air.examples.pytorch.torch_linear_example import (\n train_func as linear_train_func,\n)\nfrom ray.data import Dataset, Datasource, ReadTask, from_pandas, read_datasource\nfrom ray.data.block import BlockMetadata\nfrom ray.train.torch import TorchTrainer\nfrom ray.train.trainer import BaseTrainer\nfrom ray.train.xgboost import XGBoostTrainer\nfrom ray.tune import Callback, TuneError, CLIReporter\nfrom ray.tune.result import DEFAULT_RESULTS_DIR\nfrom ray.tune.tune_config import TuneConfig\nfrom ray.tune.tuner import Tuner\n\n\nclass DummyTrainer(BaseTrainer):\n _scaling_config_allowed_keys = BaseTrainer._scaling_config_allowed_keys + [\n \"num_workers\",\n \"use_gpu\",\n \"resources_per_worker\",\n \"placement_strategy\",\n ]\n\n def training_loop(self) -> None:\n for i in range(5):\n with tune.checkpoint_dir(step=i) as checkpoint_dir:\n path = os.path.join(checkpoint_dir, \"checkpoint\")\n with open(path, \"w\") as f:\n f.write(str(i))\n tune.report(step=i)\n\n\nclass FailingTrainer(DummyTrainer):\n def training_loop(self) -> None:\n raise RuntimeError(\"There is an error in trainer!\")\n\n\nclass TestDatasource(Datasource):\n def __init__(self, do_shuffle: bool):\n self._shuffle = do_shuffle\n\n def prepare_read(self, parallelism: int, **read_args):\n import pyarrow as pa\n\n def load_data():\n data_raw = load_breast_cancer(as_frame=True)\n dataset_df = data_raw[\"data\"]\n dataset_df[\"target\"] = data_raw[\"target\"]\n if self._shuffle:\n dataset_df = shuffle(dataset_df)\n return [pa.Table.from_pandas(dataset_df)]\n\n meta = BlockMetadata(\n num_rows=None,\n size_bytes=None,\n schema=None,\n input_files=None,\n exec_stats=None,\n )\n return [ReadTask(load_data, meta)]\n\n\ndef gen_dataset_func(do_shuffle: Optional[bool] = False) -> Dataset:\n test_datasource = TestDatasource(do_shuffle)\n return read_datasource(test_datasource)\n\n\ndef gen_dataset_func_eager():\n data_raw = load_breast_cancer(as_frame=True)\n dataset_df = data_raw[\"data\"]\n dataset_df[\"target\"] = data_raw[\"target\"]\n dataset = from_pandas(dataset_df)\n return dataset\n\n\nclass TunerTest(unittest.TestCase):\n \"\"\"The e2e test for hparam tuning using Tuner API.\"\"\"\n\n def test_tuner_with_xgboost_trainer(self):\n \"\"\"Test a successful run.\"\"\"\n shutil.rmtree(\n os.path.join(DEFAULT_RESULTS_DIR, \"test_tuner\"), ignore_errors=True\n )\n trainer = XGBoostTrainer(\n label_column=\"target\",\n params={},\n datasets={\"train\": gen_dataset_func_eager()},\n )\n # prep_v1 = StandardScaler([\"worst radius\", \"worst area\"])\n # prep_v2 = StandardScaler([\"worst concavity\", \"worst smoothness\"])\n param_space = {\n \"scaling_config\": ScalingConfig(num_workers=tune.grid_search([1, 2])),\n # \"preprocessor\": tune.grid_search([prep_v1, prep_v2]),\n \"datasets\": {\n \"train\": tune.grid_search(\n [gen_dataset_func(), gen_dataset_func(do_shuffle=True)]\n ),\n },\n \"params\": {\n \"objective\": \"binary:logistic\",\n \"tree_method\": \"approx\",\n \"eval_metric\": [\"logloss\", \"error\"],\n \"eta\": tune.loguniform(1e-4, 1e-1),\n \"subsample\": tune.uniform(0.5, 1.0),\n \"max_depth\": tune.randint(1, 9),\n },\n }\n tuner = Tuner(\n trainable=trainer,\n run_config=RunConfig(name=\"test_tuner\"),\n param_space=param_space,\n tune_config=TuneConfig(mode=\"min\", metric=\"train-error\"),\n # limiting the number of trials running at one time.\n # As the unit test only has access to 4 CPUs on Buildkite.\n _tuner_kwargs={\"max_concurrent_trials\": 1},\n )\n results = tuner.fit()\n assert len(results) == 4\n\n def test_tuner_with_xgboost_trainer_driver_fail_and_resume(self):\n # So that we have some global checkpointing happening.\n os.environ[\"TUNE_GLOBAL_CHECKPOINT_S\"] = \"1\"\n shutil.rmtree(\n os.path.join(DEFAULT_RESULTS_DIR, \"test_tuner_driver_fail\"),\n ignore_errors=True,\n )\n trainer = XGBoostTrainer(\n label_column=\"target\",\n params={},\n datasets={\"train\": gen_dataset_func_eager()},\n )\n # prep_v1 = StandardScaler([\"worst radius\", \"worst area\"])\n # prep_v2 = StandardScaler([\"worst concavity\", \"worst smoothness\"])\n param_space = {\n \"scaling_config\": ScalingConfig(num_workers=tune.grid_search([1, 2])),\n # \"preprocessor\": tune.grid_search([prep_v1, prep_v2]),\n \"datasets\": {\n \"train\": tune.grid_search(\n [gen_dataset_func(), gen_dataset_func(do_shuffle=True)]\n ),\n },\n \"params\": {\n \"objective\": \"binary:logistic\",\n \"tree_method\": \"approx\",\n \"eval_metric\": [\"logloss\", \"error\"],\n \"eta\": tune.loguniform(1e-4, 1e-1),\n \"subsample\": tune.uniform(0.5, 1.0),\n \"max_depth\": tune.randint(1, 9),\n },\n }\n\n class FailureInjectionCallback(Callback):\n \"\"\"Inject failure at the configured iteration number.\"\"\"\n\n def __init__(self, num_iters=10):\n self.num_iters = num_iters\n\n def on_step_end(self, iteration, trials, **kwargs):\n if iteration == self.num_iters:\n print(f\"Failing after {self.num_iters} iters.\")\n raise RuntimeError\n\n tuner = Tuner(\n trainable=trainer,\n run_config=RunConfig(\n name=\"test_tuner_driver_fail\", callbacks=[FailureInjectionCallback()]\n ),\n param_space=param_space,\n tune_config=TuneConfig(mode=\"min\", metric=\"train-error\"),\n # limiting the number of trials running at one time.\n # As the unit test only has access to 4 CPUs on Buildkite.\n _tuner_kwargs={\"max_concurrent_trials\": 1},\n )\n with self.assertRaises(TuneError):\n tuner.fit()\n\n # Test resume\n restore_path = os.path.join(DEFAULT_RESULTS_DIR, \"test_tuner_driver_fail\")\n tuner = Tuner.restore(restore_path)\n # A hack before we figure out RunConfig semantics across resumes.\n tuner._local_tuner._run_config.callbacks = None\n results = tuner.fit()\n assert len(results) == 4\n\n def test_tuner_trainer_fail(self):\n trainer = FailingTrainer()\n param_space = {\n \"scaling_config\": ScalingConfig(num_workers=tune.grid_search([1, 2]))\n }\n tuner = Tuner(\n trainable=trainer,\n run_config=RunConfig(name=\"test_tuner_trainer_fail\"),\n param_space=param_space,\n tune_config=TuneConfig(mode=\"max\", metric=\"iteration\"),\n )\n results = tuner.fit()\n assert len(results) == 2\n for i in range(2):\n assert results[i].error\n\n def test_tuner_with_torch_trainer(self):\n \"\"\"Test a successful run using torch trainer.\"\"\"\n shutil.rmtree(\n os.path.join(DEFAULT_RESULTS_DIR, \"test_tuner_torch\"), ignore_errors=True\n )\n # The following two should be tunable.\n config = {\"lr\": 1e-2, \"hidden_size\": 1, \"batch_size\": 4, \"epochs\": 10}\n scaling_config = ScalingConfig(num_workers=1, use_gpu=False)\n trainer = TorchTrainer(\n train_loop_per_worker=linear_train_func,\n train_loop_config=config,\n scaling_config=scaling_config,\n )\n param_space = {\n \"scaling_config\": ScalingConfig(num_workers=tune.grid_search([1, 2])),\n \"train_loop_config\": {\n \"batch_size\": tune.grid_search([4, 8]),\n \"epochs\": tune.grid_search([5, 10]),\n },\n }\n tuner = Tuner(\n trainable=trainer,\n run_config=RunConfig(name=\"test_tuner\"),\n param_space=param_space,\n tune_config=TuneConfig(mode=\"min\", metric=\"loss\"),\n )\n results = tuner.fit()\n assert len(results) == 8\n\n def test_tuner_run_config_override(self):\n trainer = DummyTrainer(run_config=RunConfig(stop={\"metric\": 4}))\n tuner = Tuner(trainer)\n\n assert tuner._local_tuner._run_config.stop == {\"metric\": 4}\n\n\n@pytest.mark.parametrize(\n \"params_expected\",\n [\n (\n {\"run_config\": RunConfig(progress_reporter=CLIReporter())},\n lambda kw: isinstance(kw[\"progress_reporter\"], CLIReporter),\n ),\n (\n {\"tune_config\": TuneConfig(reuse_actors=True)},\n lambda kw: kw[\"reuse_actors\"] is True,\n ),\n (\n {\"run_config\": RunConfig(log_to_file=\"some_file\")},\n lambda kw: kw[\"log_to_file\"] == \"some_file\",\n ),\n (\n {\"tune_config\": TuneConfig(max_concurrent_trials=3)},\n lambda kw: kw[\"max_concurrent_trials\"] == 3,\n ),\n (\n {\"tune_config\": TuneConfig(time_budget_s=60)},\n lambda kw: kw[\"time_budget_s\"] == 60,\n ),\n ],\n)\ndef test_tuner_api_kwargs(params_expected):\n tuner_params, assertion = params_expected\n\n tuner = Tuner(lambda config: 1, **tuner_params)\n\n caught_kwargs = {}\n\n def catch_kwargs(**kwargs):\n caught_kwargs.update(kwargs)\n\n with patch(\"ray.tune.impl.tuner_internal.run\", catch_kwargs):\n tuner.fit()\n\n assert assertion(caught_kwargs)\n\n\ndef test_tuner_fn_trainable_checkpoint_at_end_true():\n tuner = Tuner(\n lambda config, checkpoint_dir: 1,\n run_config=ray.air.RunConfig(\n checkpoint_config=ray.air.CheckpointConfig(checkpoint_at_end=True)\n ),\n )\n with pytest.raises(TuneError):\n tuner.fit()\n\n\ndef test_tuner_fn_trainable_checkpoint_at_end_false():\n tuner = Tuner(\n lambda config, checkpoint_dir: 1,\n run_config=ray.air.RunConfig(\n checkpoint_config=ray.air.CheckpointConfig(checkpoint_at_end=False)\n ),\n )\n tuner.fit()\n\n\ndef test_tuner_fn_trainable_checkpoint_at_end_none():\n tuner = Tuner(\n lambda config, checkpoint_dir: 1,\n run_config=ray.air.RunConfig(\n checkpoint_config=ray.air.CheckpointConfig(checkpoint_at_end=None)\n ),\n )\n tuner.fit()\n\n\nif __name__ == \"__main__\":\n import sys\n\n sys.exit(pytest.main([\"-v\", __file__] + sys.argv[1:]))\n", "repo_name": "spacegoing/myray_2.0.0", "sub_path": "tune/tests/test_tuner.py", "file_name": "test_tuner.py", "file_ext": "py", "file_size_in_byte": 11050, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "ray.train.trainer.BaseTrainer", "line_number": 29, "usage_type": "name"}, {"api_name": "ray.train.trainer.BaseTrainer._scaling_config_allowed_keys", "line_number": 30, "usage_type": "attribute"}, {"api_name": "ray.train.trainer.BaseTrainer", "line_number": 30, "usage_type": "name"}, {"api_name": "ray.tune.checkpoint_dir", "line_number": 39, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 39, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "ray.tune.report", "line_number": 43, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 43, "usage_type": "name"}, {"api_name": "ray.data.Datasource", "line_number": 51, "usage_type": "name"}, {"api_name": "sklearn.datasets.load_breast_cancer", "line_number": 59, "usage_type": "call"}, {"api_name": "sklearn.utils.shuffle", "line_number": 63, "usage_type": "call"}, {"api_name": "pyarrow.Table.from_pandas", "line_number": 64, "usage_type": "call"}, {"api_name": "pyarrow.Table", "line_number": 64, "usage_type": "attribute"}, {"api_name": "ray.data.block.BlockMetadata", "line_number": 66, "usage_type": "call"}, {"api_name": "ray.data.ReadTask", "line_number": 73, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 76, "usage_type": "name"}, {"api_name": "ray.data.read_datasource", "line_number": 78, "usage_type": "call"}, {"api_name": "ray.data.Dataset", "line_number": 76, "usage_type": "name"}, {"api_name": "sklearn.datasets.load_breast_cancer", "line_number": 82, "usage_type": "call"}, {"api_name": "ray.data.from_pandas", "line_number": 85, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 89, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 94, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 95, "usage_type": "call"}, {"api_name": "ray.tune.result.DEFAULT_RESULTS_DIR", "line_number": 95, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 95, "usage_type": "attribute"}, {"api_name": "ray.train.xgboost.XGBoostTrainer", "line_number": 97, "usage_type": "call"}, {"api_name": "ray.air.config.ScalingConfig", "line_number": 105, "usage_type": "call"}, {"api_name": "ray.tune.grid_search", "line_number": 105, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 105, "usage_type": "name"}, {"api_name": "ray.tune.grid_search", "line_number": 108, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 108, "usage_type": "name"}, {"api_name": "ray.tune.loguniform", "line_number": 116, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 116, "usage_type": "name"}, {"api_name": "ray.tune.uniform", "line_number": 117, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 117, "usage_type": "name"}, {"api_name": "ray.tune.randint", "line_number": 118, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 118, "usage_type": "name"}, {"api_name": "ray.tune.tuner.Tuner", "line_number": 121, "usage_type": "call"}, {"api_name": "ray.air.config.RunConfig", "line_number": 123, "usage_type": "call"}, {"api_name": "ray.tune.tune_config.TuneConfig", "line_number": 125, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 135, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 136, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 137, "usage_type": "call"}, {"api_name": "ray.tune.result.DEFAULT_RESULTS_DIR", "line_number": 137, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 137, "usage_type": "attribute"}, {"api_name": "ray.train.xgboost.XGBoostTrainer", "line_number": 140, "usage_type": "call"}, {"api_name": "ray.air.config.ScalingConfig", "line_number": 148, "usage_type": "call"}, {"api_name": "ray.tune.grid_search", "line_number": 148, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 148, "usage_type": "name"}, {"api_name": "ray.tune.grid_search", "line_number": 151, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 151, "usage_type": "name"}, {"api_name": "ray.tune.loguniform", "line_number": 159, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 159, "usage_type": "name"}, {"api_name": "ray.tune.uniform", "line_number": 160, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 160, "usage_type": "name"}, {"api_name": "ray.tune.randint", "line_number": 161, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 161, "usage_type": "name"}, {"api_name": "ray.tune.Callback", "line_number": 165, "usage_type": "name"}, {"api_name": "ray.tune.tuner.Tuner", "line_number": 176, "usage_type": "call"}, {"api_name": "ray.air.config.RunConfig", "line_number": 178, "usage_type": "call"}, {"api_name": "ray.tune.tune_config.TuneConfig", "line_number": 182, "usage_type": "call"}, {"api_name": "ray.tune.TuneError", "line_number": 187, "usage_type": "argument"}, {"api_name": "os.path.join", "line_number": 191, "usage_type": "call"}, {"api_name": "ray.tune.result.DEFAULT_RESULTS_DIR", "line_number": 191, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 191, "usage_type": "attribute"}, {"api_name": "ray.tune.tuner.Tuner.restore", "line_number": 192, "usage_type": "call"}, {"api_name": "ray.tune.tuner.Tuner", "line_number": 192, "usage_type": "name"}, {"api_name": "ray.air.config.ScalingConfig", "line_number": 201, "usage_type": "call"}, {"api_name": "ray.tune.grid_search", "line_number": 201, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 201, "usage_type": "name"}, {"api_name": "ray.tune.tuner.Tuner", "line_number": 203, "usage_type": "call"}, {"api_name": "ray.air.config.RunConfig", "line_number": 205, "usage_type": "call"}, {"api_name": "ray.tune.tune_config.TuneConfig", "line_number": 207, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 216, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 217, "usage_type": "call"}, {"api_name": "ray.tune.result.DEFAULT_RESULTS_DIR", "line_number": 217, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 217, "usage_type": "attribute"}, {"api_name": "ray.air.config.ScalingConfig", "line_number": 221, "usage_type": "call"}, {"api_name": "ray.train.torch.TorchTrainer", "line_number": 222, "usage_type": "call"}, {"api_name": "ray.air.examples.pytorch.torch_linear_example.train_func", "line_number": 223, "usage_type": "name"}, {"api_name": "ray.air.config.ScalingConfig", "line_number": 228, "usage_type": "call"}, {"api_name": "ray.tune.grid_search", "line_number": 228, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 228, "usage_type": "name"}, {"api_name": "ray.tune.grid_search", "line_number": 230, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 230, "usage_type": "name"}, {"api_name": "ray.tune.grid_search", "line_number": 231, "usage_type": "call"}, {"api_name": "ray.tune", "line_number": 231, "usage_type": "name"}, {"api_name": "ray.tune.tuner.Tuner", "line_number": 234, "usage_type": "call"}, {"api_name": "ray.air.config.RunConfig", "line_number": 236, "usage_type": "call"}, {"api_name": "ray.tune.tune_config.TuneConfig", "line_number": 238, "usage_type": "call"}, {"api_name": "ray.air.config.RunConfig", "line_number": 244, "usage_type": "call"}, {"api_name": "ray.tune.tuner.Tuner", "line_number": 245, "usage_type": "call"}, {"api_name": "ray.tune.tuner.Tuner", "line_number": 278, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 285, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 250, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 250, "usage_type": "attribute"}, {"api_name": "ray.air.config.RunConfig", "line_number": 254, "usage_type": "call"}, {"api_name": "ray.tune.CLIReporter", "line_number": 254, "usage_type": "call"}, {"api_name": "ray.tune.CLIReporter", "line_number": 255, "usage_type": "argument"}, {"api_name": "ray.tune.tune_config.TuneConfig", "line_number": 258, "usage_type": "call"}, {"api_name": "ray.air.config.RunConfig", "line_number": 262, "usage_type": "call"}, {"api_name": "ray.tune.tune_config.TuneConfig", "line_number": 266, "usage_type": "call"}, {"api_name": "ray.tune.tune_config.TuneConfig", "line_number": 270, "usage_type": "call"}, {"api_name": "ray.tune.tuner.Tuner", "line_number": 292, "usage_type": "call"}, {"api_name": "ray.air.air.RunConfig", "line_number": 294, "usage_type": "call"}, {"api_name": "ray.air.air", "line_number": 294, "usage_type": "attribute"}, {"api_name": "ray.air", "line_number": 294, "usage_type": "name"}, {"api_name": "ray.air.air.CheckpointConfig", "line_number": 295, "usage_type": "call"}, {"api_name": "ray.air.air", "line_number": 295, "usage_type": "attribute"}, {"api_name": "ray.air", "line_number": 295, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 298, "usage_type": "call"}, {"api_name": "ray.tune.TuneError", "line_number": 298, "usage_type": "argument"}, {"api_name": "ray.tune.tuner.Tuner", "line_number": 303, "usage_type": "call"}, {"api_name": "ray.air.air.RunConfig", "line_number": 305, "usage_type": "call"}, {"api_name": "ray.air.air", "line_number": 305, "usage_type": "attribute"}, {"api_name": "ray.air", "line_number": 305, "usage_type": "name"}, {"api_name": "ray.air.air.CheckpointConfig", "line_number": 306, "usage_type": "call"}, {"api_name": "ray.air.air", "line_number": 306, "usage_type": "attribute"}, {"api_name": "ray.air", "line_number": 306, "usage_type": "name"}, {"api_name": "ray.tune.tuner.Tuner", "line_number": 313, "usage_type": "call"}, {"api_name": "ray.air.air.RunConfig", "line_number": 315, "usage_type": "call"}, {"api_name": "ray.air.air", "line_number": 315, "usage_type": "attribute"}, {"api_name": "ray.air", "line_number": 315, "usage_type": "name"}, {"api_name": "ray.air.air.CheckpointConfig", "line_number": 316, "usage_type": "call"}, {"api_name": "ray.air.air", "line_number": 316, "usage_type": "attribute"}, {"api_name": "ray.air", "line_number": 316, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 325, "usage_type": "call"}, {"api_name": "pytest.main", "line_number": 325, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 325, "usage_type": "attribute"}]} +{"seq_id": "43225683062", "text": "from torch.utils.data import Dataset, DataLoader\nimport pytorch_lightning as pl\nimport torch\nimport math\nimport numpy as np\nimport json\nfrom .chunking_data_util import ChunkingDataset\nimport nltk\n\ngiga_path = './dataset/ggw_data/org_data/'\ngiga_train_src_path = giga_path + 'train.src.txt'\ngiga_train_tgt_path = giga_path + 'train.tgt.txt'\ngiga_dev_src_path = giga_path + 'selected_dev.src.txt'\ngiga_dev_tgt_path = giga_path + 'selected_dev.tgt.txt'\ngiga_test_src_path = giga_path + 'test.src.txt'\ngiga_test_tgt_path = giga_path + 'test.tgt.txt'\n\nconll_train_src_path = \"./dataset/conll_2000/conll_pretrain_src.txt\" \nconll_train_tgt_path = \"./dataset/conll_2000/conll_pretrain_tgt.txt\" # word level\nconll_test_src_path = \"./dataset/conll_2000/test_conll_src.txt\"\nconll_test_tgt_path = \"./dataset/conll_2000/test_conll_tgt.txt\"\nconll_dev_src_path = \"./dataset/conll_2000/dev_conll_src.txt\"\n\nsnli_path = './dataset/snli_1.0/'\nsnli_train_path = snli_path + 'snli_1.0_train.jsonl'\nsnli_dev_path = snli_path + 'snli_1.0_dev.jsonl'\nsnli_test_path = snli_path + 'snli_1.0_test.jsonl'\n\nmnli_path = './dataset/multinli_1.0/'\nmnli_train_path = mnli_path + 'multinli_1.0_train.jsonl'\nmnli_dev_path = mnli_path + 'multinli_1.0_dev_mismatched.jsonl'\nmnli_test_path = mnli_path + 'multinli_1.0_dev_matched.jsonl'\n\nwmt_train_src_path = './translation/WMT14-en-de/train.en'\nwmt_train_tgt_path = './translation/WMT14-en-de/train.de'\nwmt_test_src_path = './translation/WMT14-en-de/newstest2014.en'\nwmt_test_tgt_path = './translation/WMT14-en-de/newstest2014.de'\n\ndef create_wmt_dict(src_path, tgt_path):\n data = []\n with open(src_path) as sf:\n with open(tgt_path) as tf:\n for id, line in enumerate(zip(sf, tf)):\n dict = {}\n src, tgt = line[0], line[1]\n dict['src'] = src.strip().replace(\" ##AT##-##AT## \", \"-\")\n dict['tgt'] = tgt.strip().replace(\" ##AT##-##AT## \", \"-\")\n data.append(dict)\n return data\n\ndef create_giga_dict(src_path, tgt_path, replace_unk=True):\n data = []\n with open(src_path) as sf:\n with open(tgt_path) as tf:\n for id, line in enumerate(zip(sf, tf)):\n dict = {}\n src, tgt = line[0], line[1]\n if replace_unk:\n src = src.strip().replace(\"UNK\", \"\")\n tgt = tgt.strip().replace(\"UNK\", \"\")\n else:\n src = src.strip()\n tgt = tgt.strip()\n dict['src'] = src\n dict['tgt'] = tgt\n data.append(dict)\n return data\n\ndef read_snli_entailment_data(data_path):\n data = []\n with open(data_path) as f:\n lines = f.readlines()\n for line in lines:\n this_data = {}\n tmp = json.loads(line)\n if tmp['gold_label'] == 'entailment':\n this_data['src'] = ' '.join(nltk.word_tokenize(tmp['sentence1'].strip()))\n this_data['tgt'] = ' '.join(nltk.word_tokenize(tmp['sentence2'].strip()))\n data.append(this_data)\n return data\n\nclass SummarizationDataset(Dataset):\n def __init__(self, data, tokenizer, max_src_len, max_tgt_len, cut_rate):\n self.data = data\n self.tokenizer = tokenizer\n self.max_src_len = max_src_len\n self.max_tgt_len = max_tgt_len\n self.cut_rate = cut_rate\n \n def __len__(self):\n return len(self.data)\n \n def __getitem__(self, index: int):\n this_data = self.data[index]\n source = this_data['src']\n target = this_data['tgt']\n encoded_src = self.tokenizer(source, max_length=self.max_src_len, padding=\"max_length\", truncation=True, return_tensors=\"pt\")\n encoded_tgt = self.tokenizer(target, max_length=self.max_tgt_len, padding=\"max_length\", truncation=True, return_tensors=\"pt\")\n\n # cut_rate = np.clip(np.random.normal(0.6, 0.1), 0, 1)\n a = math.ceil((torch.sum(encoded_src[\"attention_mask\"].flatten(), dim=-1) * self.cut_rate).item())\n mes_label = torch.zeros(encoded_src[\"attention_mask\"].flatten().shape)\n mes_label[0:a] = 1\n\n return dict(\n src_text=source, \n tgt_text=target, \n src_input_ids=encoded_src[\"input_ids\"].flatten(),\n src_attention_mask=encoded_src[\"attention_mask\"].flatten(),\n tgt_input_ids=encoded_tgt[\"input_ids\"].flatten(),\n tgt_attention_mask=encoded_tgt[\"attention_mask\"].flatten(),\n mse_label=mes_label,\n )\n\nclass DataModule(pl.LightningDataModule):\n def __init__(self, tokenizer, hparams, max_src_len=128, max_tgt_len=64):\n super().__init__()\n self.tokenizer = tokenizer\n self.batch_size = hparams.batch_size\n self.max_src_len = max_src_len\n self.max_tgt_len = max_tgt_len\n self.train_dataset = hparams.train_dataset\n self.test_dataset = hparams.test_dataset\n self.predict_dataset = hparams.predict_dataset\n self.cut_rate = hparams.cut_rate\n self.predict_mode = None\n\n if self.train_dataset == 'giga':\n self.train_data = create_giga_dict(giga_train_src_path, giga_train_tgt_path)\n elif self.train_dataset == 'mnli':\n self.train_data = read_snli_entailment_data(mnli_train_path)\n else:\n exit('No such train dataset')\n \n if self.test_dataset == 'giga':\n self.test_data = create_giga_dict(giga_test_src_path, giga_test_tgt_path)\n elif self.test_dataset == 'mnli':\n self.test_data = read_snli_entailment_data(mnli_test_path)\n else:\n exit('No such test dataset')\n \n if self.predict_dataset == 'wmt' :\n self.predcit_data = create_wmt_dict(wmt_test_src_path, wmt_test_tgt_path) \n elif self.predict_dataset == 'giga' :\n self.predcit_data = create_giga_dict(giga_test_src_path, giga_test_tgt_path)\n elif self.predict_dataset == 'mnli':\n self.predcit_data= read_snli_entailment_data(mnli_test_path)\n else:\n exit('No such predict dataset')\n \n self.conll_test_data = []\n with open(conll_test_src_path) as f:\n # with open(conll_dev_src_path) as f:\n data = f.readlines()\n for d in data:\n this_data = {}\n this_data['src'] = d.strip()\n self.conll_test_data.append(this_data)\n print('Done!')\n \n def setup(self, stage):\n if stage == \"fit\" or stage is None:\n self.train_dataset = SummarizationDataset(self.train_data, self.tokenizer, self.max_src_len, self.max_tgt_len, self.cut_rate)\n # self.dev_dataset = SummarizationDataset(self.dev_data, self.tokenizer, self.max_src_len, self.max_tgt_len, self.cut_rate)\n if stage == \"test\" or stage is None:\n self.test_dataset = SummarizationDataset(self.test_data, self.tokenizer, self.max_src_len, self.max_tgt_len, self.cut_rate)\n if stage == \"predict\" or stage is None:\n self.predict_dataset = ChunkingDataset(self.predcit_data, self.tokenizer, self.max_src_len)\n self.predict_conll_dataset = ChunkingDataset(self.conll_test_data, self.tokenizer, self.max_src_len)\n\n def train_dataloader(self):\n # torch.manual_seed(42)\n torch.manual_seed(59)\n return DataLoader(self.train_dataset, batch_size=self.batch_size, shuffle=True, num_workers=6)\n \n # def val_dataloader(self):\n # return DataLoader(self.dev_dataset, batch_size=self.batch_size)\n\n def test_dataloader(self):\n return DataLoader(self.test_dataset, batch_size=self.batch_size)\n \n def predict_dataloader(self):\n if self.predict_mode == 'test':\n return DataLoader(self.predict_dataset, batch_size=1)\n elif self.predict_mode == 'conll':\n return DataLoader(self.predict_conll_dataset, batch_size=1)\n # elif self.predict_mode == 'dev':\n # return DataLoader(self.predict_val_dataset, batch_size=1)\n else:\n print('predict: No such option!')\n", "repo_name": "MANGA-UOFA/UCHRNN", "sub_path": "data_util/generation_data_util.py", "file_name": "generation_data_util.py", "file_ext": "py", "file_size_in_byte": 8182, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "json.loads", "line_number": 75, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 77, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.utils.data.Dataset", "line_number": 82, "usage_type": "name"}, {"api_name": "math.ceil", "line_number": 101, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 101, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 102, "usage_type": "call"}, {"api_name": "pytorch_lightning.LightningDataModule", "line_number": 115, "usage_type": "attribute"}, {"api_name": "chunking_data_util.ChunkingDataset", "line_number": 168, "usage_type": "call"}, {"api_name": "chunking_data_util.ChunkingDataset", "line_number": 169, "usage_type": "call"}, {"api_name": "torch.manual_seed", "line_number": 173, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 174, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 180, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 184, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 186, "usage_type": "call"}]} +{"seq_id": "24565120784", "text": "from datetime import datetime\nimport webob\nimport webob.dec\nfrom xml.dom import minidom\n\nimport nova.api.openstack.views.versions\nfrom nova.api.openstack import wsgi\n\n\nVERSIONS = {\n \"v1.0\": {\n \"id\": \"v1.0\",\n \"status\": \"DEPRECATED\",\n \"updated\": \"2011-01-21T11:33:21Z\",\n \"links\": [\n {\n \"rel\": \"describedby\",\n \"type\": \"application/pdf\",\n \"href\": \"http://docs.rackspacecloud.com/\"\n \"servers/api/v1.0/cs-devguide-20110125.pdf\",\n },\n {\n \"rel\": \"describedby\",\n \"type\": \"application/vnd.sun.wadl+xml\",\n \"href\": \"http://docs.rackspacecloud.com/\"\n \"servers/api/v1.0/application.wadl\",\n },\n ],\n \"media-types\": [\n {\n \"base\": \"application/xml\",\n \"type\": \"application/vnd.openstack.compute-v1.0+xml\",\n },\n {\n \"base\": \"application/json\",\n \"type\": \"application/vnd.openstack.compute-v1.0+json\",\n }\n ],\n },\n \"v1.1\": {\n \"id\": \"v1.1\",\n \"status\": \"CURRENT\",\n \"updated\": \"2011-01-21T11:33:21Z\",\n \"links\": [\n {\n \"rel\": \"describedby\",\n \"type\": \"application/pdf\",\n \"href\": \"http://docs.rackspacecloud.com/\"\n \"servers/api/v1.1/cs-devguide-20110125.pdf\",\n },\n {\n \"rel\": \"describedby\",\n \"type\": \"application/vnd.sun.wadl+xml\",\n \"href\": \"http://docs.rackspacecloud.com/\"\n \"servers/api/v1.1/application.wadl\",\n },\n ],\n \"media-types\": [\n {\n \"base\": \"application/xml\",\n \"type\": \"application/vnd.openstack.compute-v1.1+xml\",\n },\n {\n \"base\": \"application/json\",\n \"type\": \"application/vnd.openstack.compute-v1.1+json\",\n }\n ],\n },\n}\n\n\nclass Versions(wsgi.Resource):\n def __init__(self):\n metadata = {\n \"attributes\": {\n \"version\": [\"status\", \"id\"],\n \"link\": [\"rel\", \"href\"],\n }\n }\n\n headers_serializer = VersionsHeadersSerializer()\n\n body_serializers = {\n 'application/atom+xml': VersionsAtomSerializer(metadata=metadata),\n 'application/xml': VersionsXMLSerializer(metadata=metadata),\n }\n serializer = wsgi.ResponseSerializer(\n body_serializers=body_serializers,\n headers_serializer=headers_serializer)\n\n supported_content_types = ('application/json',\n 'application/xml',\n 'application/atom+xml')\n deserializer = VersionsRequestDeserializer(\n supported_content_types=supported_content_types)\n\n wsgi.Resource.__init__(self, None, serializer=serializer,\n deserializer=deserializer)\n\n def dispatch(self, request, *args):\n \"\"\"Respond to a request for all OpenStack API versions.\"\"\"\n builder = nova.api.openstack.views.versions.get_view_builder(request)\n if request.path == '/':\n # List Versions\n return builder.build_versions(VERSIONS)\n else:\n # Versions Multiple Choice\n return builder.build_choices(VERSIONS, request)\n\n\nclass VersionV10(object):\n def show(self, req):\n builder = nova.api.openstack.views.versions.get_view_builder(req)\n return builder.build_version(VERSIONS['v1.0'])\n\n\nclass VersionV11(object):\n def show(self, req):\n builder = nova.api.openstack.views.versions.get_view_builder(req)\n return builder.build_version(VERSIONS['v1.1'])\n\n\nclass VersionsRequestDeserializer(wsgi.RequestDeserializer):\n def get_expected_content_type(self, request):\n supported_content_types = list(self.supported_content_types)\n if request.path != '/':\n # Remove atom+xml accept type for 300 responses\n if 'application/atom+xml' in supported_content_types:\n supported_content_types.remove('application/atom+xml')\n\n return request.best_match_content_type(supported_content_types)\n\n def get_action_args(self, request_environment):\n \"\"\"Parse dictionary created by routes library.\"\"\"\n args = {}\n if request_environment['PATH_INFO'] == '/':\n args['action'] = 'index'\n else:\n args['action'] = 'multi'\n\n return args\n\n\nclass VersionsXMLSerializer(wsgi.XMLDictSerializer):\n #TODO(wwolf): this is temporary until we get rid of toprettyxml\n # in the base class (XMLDictSerializer), which I plan to do in\n # another branch\n def to_xml_string(self, node, has_atom=False):\n self._add_xmlns(node, has_atom)\n return node.toxml(encoding='UTF-8')\n\n def _versions_to_xml(self, versions, name=\"versions\", xmlns=None):\n root = self._xml_doc.createElement(name)\n root.setAttribute(\"xmlns\", wsgi.XMLNS_V11)\n root.setAttribute(\"xmlns:atom\", wsgi.XMLNS_ATOM)\n\n for version in versions:\n root.appendChild(self._create_version_node(version))\n\n return root\n\n def _create_media_types(self, media_types):\n base = self._xml_doc.createElement('media-types')\n for type in media_types:\n node = self._xml_doc.createElement('media-type')\n node.setAttribute('base', type['base'])\n node.setAttribute('type', type['type'])\n base.appendChild(node)\n\n return base\n\n def _create_version_node(self, version, create_ns=False):\n version_node = self._xml_doc.createElement('version')\n if create_ns:\n xmlns = wsgi.XMLNS_V11\n xmlns_atom = wsgi.XMLNS_ATOM\n version_node.setAttribute('xmlns', xmlns)\n version_node.setAttribute('xmlns:atom', xmlns_atom)\n\n version_node.setAttribute('id', version['id'])\n version_node.setAttribute('status', version['status'])\n if 'updated' in version:\n version_node.setAttribute('updated', version['updated'])\n\n if 'media-types' in version:\n media_types = self._create_media_types(version['media-types'])\n version_node.appendChild(media_types)\n\n link_nodes = self._create_link_nodes(self._xml_doc, version['links'])\n for link in link_nodes:\n version_node.appendChild(link)\n\n return version_node\n\n def index(self, data):\n self._xml_doc = minidom.Document()\n node = self._versions_to_xml(data['versions'])\n\n return self.to_xml_string(node)\n\n def show(self, data):\n self._xml_doc = minidom.Document()\n node = self._create_version_node(data['version'], True)\n\n return self.to_xml_string(node)\n\n def multi(self, data):\n self._xml_doc = minidom.Document()\n node = self._versions_to_xml(data['choices'], 'choices',\n xmlns=wsgi.XMLNS_V11)\n\n return self.to_xml_string(node)\n\n\nclass VersionsAtomSerializer(wsgi.XMLDictSerializer):\n #TODO(wwolf): this is temporary until we get rid of toprettyxml\n # in the base class (XMLDictSerializer), which I plan to do in\n # another branch\n def to_xml_string(self, node, has_atom=False):\n self._add_xmlns(node, has_atom)\n return node.toxml(encoding='UTF-8')\n\n def __init__(self, metadata=None, xmlns=None):\n self.metadata = metadata or {}\n if not xmlns:\n self.xmlns = wsgi.XMLNS_ATOM\n else:\n self.xmlns = xmlns\n\n def _create_text_elem(self, name, text, type=None):\n elem = self._xml_doc.createElement(name)\n if type:\n elem.setAttribute('type', type)\n elem_text = self._xml_doc.createTextNode(text)\n elem.appendChild(elem_text)\n return elem\n\n def _get_most_recent_update(self, versions):\n recent = None\n for version in versions:\n updated = datetime.strptime(version['updated'],\n '%Y-%m-%dT%H:%M:%SZ')\n if not recent:\n recent = updated\n elif updated > recent:\n recent = updated\n\n return recent.strftime('%Y-%m-%dT%H:%M:%SZ')\n\n def _get_base_url(self, link_href):\n # Make sure no trailing /\n link_href = link_href.rstrip('/')\n return link_href.rsplit('/', 1)[0] + '/'\n\n def _create_detail_meta(self, root, version):\n title = self._create_text_elem('title', \"About This Version\",\n type='text')\n\n updated = self._create_text_elem('updated', version['updated'])\n\n uri = version['links'][0]['href']\n id = self._create_text_elem('id', uri)\n\n link = self._xml_doc.createElement('link')\n link.setAttribute('rel', 'self')\n link.setAttribute('href', uri)\n\n author = self._xml_doc.createElement('author')\n author_name = self._create_text_elem('name', 'Rackspace')\n author_uri = self._create_text_elem('uri', 'http://www.rackspace.com/')\n author.appendChild(author_name)\n author.appendChild(author_uri)\n\n root.appendChild(title)\n root.appendChild(updated)\n root.appendChild(id)\n root.appendChild(author)\n root.appendChild(link)\n\n def _create_list_meta(self, root, versions):\n title = self._create_text_elem('title', \"Available API Versions\",\n type='text')\n # Set this updated to the most recently updated version\n recent = self._get_most_recent_update(versions)\n updated = self._create_text_elem('updated', recent)\n\n base_url = self._get_base_url(versions[0]['links'][0]['href'])\n id = self._create_text_elem('id', base_url)\n\n link = self._xml_doc.createElement('link')\n link.setAttribute('rel', 'self')\n link.setAttribute('href', base_url)\n\n author = self._xml_doc.createElement('author')\n author_name = self._create_text_elem('name', 'Rackspace')\n author_uri = self._create_text_elem('uri', 'http://www.rackspace.com/')\n author.appendChild(author_name)\n author.appendChild(author_uri)\n\n root.appendChild(title)\n root.appendChild(updated)\n root.appendChild(id)\n root.appendChild(author)\n root.appendChild(link)\n\n def _create_version_entries(self, root, versions):\n for version in versions:\n entry = self._xml_doc.createElement('entry')\n\n id = self._create_text_elem('id', version['links'][0]['href'])\n title = self._create_text_elem('title',\n 'Version %s' % version['id'],\n type='text')\n updated = self._create_text_elem('updated', version['updated'])\n\n entry.appendChild(id)\n entry.appendChild(title)\n entry.appendChild(updated)\n\n for link in version['links']:\n link_node = self._xml_doc.createElement('link')\n link_node.setAttribute('rel', link['rel'])\n link_node.setAttribute('href', link['href'])\n if 'type' in link:\n link_node.setAttribute('type', link['type'])\n\n entry.appendChild(link_node)\n\n content = self._create_text_elem('content',\n 'Version %s %s (%s)' %\n (version['id'],\n version['status'],\n version['updated']),\n type='text')\n\n entry.appendChild(content)\n root.appendChild(entry)\n\n def index(self, data):\n self._xml_doc = minidom.Document()\n node = self._xml_doc.createElementNS(self.xmlns, 'feed')\n self._create_list_meta(node, data['versions'])\n self._create_version_entries(node, data['versions'])\n\n return self.to_xml_string(node)\n\n def show(self, data):\n self._xml_doc = minidom.Document()\n node = self._xml_doc.createElementNS(self.xmlns, 'feed')\n self._create_detail_meta(node, data['version'])\n self._create_version_entries(node, [data['version']])\n\n return self.to_xml_string(node)\n\n\nclass VersionsHeadersSerializer(wsgi.ResponseHeadersSerializer):\n def multi(self, response, data):\n response.status_int = 300\n\n\ndef create_resource(version='1.0'):\n controller = {\n '1.0': VersionV10,\n '1.1': VersionV11,\n }[version]()\n\n body_serializers = {\n 'application/xml': VersionsXMLSerializer(),\n 'application/atom+xml': VersionsAtomSerializer(),\n }\n serializer = wsgi.ResponseSerializer(body_serializers)\n\n supported_content_types = ('application/json',\n 'application/xml',\n 'application/atom+xml')\n deserializer = wsgi.RequestDeserializer(\n supported_content_types=supported_content_types)\n\n return wsgi.Resource(controller, serializer=serializer,\n deserializer=deserializer)\n", "repo_name": "nii-cloud/dodai-compute", "sub_path": "nova/api/openstack/versions.py", "file_name": "versions.py", "file_ext": "py", "file_size_in_byte": 13246, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 12, "dataset": "github-code", "pt": "24", "api": [{"api_name": "nova.api.openstack.wsgi.Resource", "line_number": 72, "usage_type": "attribute"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 72, "usage_type": "name"}, {"api_name": "nova.api.openstack.wsgi.ResponseSerializer", "line_number": 87, "usage_type": "call"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 87, "usage_type": "name"}, {"api_name": "nova.api.openstack.wsgi.Resource.__init__", "line_number": 97, "usage_type": "call"}, {"api_name": "nova.api.openstack.wsgi.Resource", "line_number": 97, "usage_type": "attribute"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 97, "usage_type": "name"}, {"api_name": "nova.api.openstack.views.versions.api.openstack.views.versions.get_view_builder", "line_number": 102, "usage_type": "call"}, {"api_name": "nova.api.openstack.views.versions.api", "line_number": 102, "usage_type": "attribute"}, {"api_name": "nova.api.openstack.views.versions", "line_number": 102, "usage_type": "name"}, {"api_name": "nova.api.openstack.views.versions.api.openstack.views.versions.get_view_builder", "line_number": 113, "usage_type": "call"}, {"api_name": "nova.api.openstack.views.versions.api", "line_number": 113, "usage_type": "attribute"}, {"api_name": "nova.api.openstack.views.versions", "line_number": 113, "usage_type": "name"}, {"api_name": "nova.api.openstack.views.versions.api.openstack.views.versions.get_view_builder", "line_number": 119, "usage_type": "call"}, {"api_name": "nova.api.openstack.views.versions.api", "line_number": 119, "usage_type": "attribute"}, {"api_name": "nova.api.openstack.views.versions", "line_number": 119, "usage_type": "name"}, {"api_name": "nova.api.openstack.wsgi.RequestDeserializer", "line_number": 123, "usage_type": "attribute"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 123, "usage_type": "name"}, {"api_name": "nova.api.openstack.wsgi.XMLDictSerializer", "line_number": 144, "usage_type": "attribute"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 144, "usage_type": "name"}, {"api_name": "nova.api.openstack.wsgi.XMLNS_V11", "line_number": 154, "usage_type": "attribute"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 154, "usage_type": "name"}, {"api_name": "nova.api.openstack.wsgi.XMLNS_ATOM", "line_number": 155, "usage_type": "attribute"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 155, "usage_type": "name"}, {"api_name": "nova.api.openstack.wsgi.XMLNS_V11", "line_number": 175, "usage_type": "attribute"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 175, "usage_type": "name"}, {"api_name": "nova.api.openstack.wsgi.XMLNS_ATOM", "line_number": 176, "usage_type": "attribute"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 176, "usage_type": "name"}, {"api_name": "xml.dom.minidom.Document", "line_number": 196, "usage_type": "call"}, {"api_name": "xml.dom.minidom", "line_number": 196, "usage_type": "name"}, {"api_name": "xml.dom.minidom.Document", "line_number": 202, "usage_type": "call"}, {"api_name": "xml.dom.minidom", "line_number": 202, "usage_type": "name"}, {"api_name": "xml.dom.minidom.Document", "line_number": 208, "usage_type": "call"}, {"api_name": "xml.dom.minidom", "line_number": 208, "usage_type": "name"}, {"api_name": "nova.api.openstack.wsgi.XMLNS_V11", "line_number": 210, "usage_type": "attribute"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 210, "usage_type": "name"}, {"api_name": "nova.api.openstack.wsgi.XMLDictSerializer", "line_number": 215, "usage_type": "attribute"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 215, "usage_type": "name"}, {"api_name": "nova.api.openstack.wsgi.XMLNS_ATOM", "line_number": 226, "usage_type": "attribute"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 226, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 241, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 241, "usage_type": "name"}, {"api_name": "xml.dom.minidom.Document", "line_number": 340, "usage_type": "call"}, {"api_name": "xml.dom.minidom", "line_number": 340, "usage_type": "name"}, {"api_name": "xml.dom.minidom.Document", "line_number": 348, "usage_type": "call"}, {"api_name": "xml.dom.minidom", "line_number": 348, "usage_type": "name"}, {"api_name": "nova.api.openstack.wsgi.ResponseHeadersSerializer", "line_number": 356, "usage_type": "attribute"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 356, "usage_type": "name"}, {"api_name": "nova.api.openstack.wsgi.ResponseSerializer", "line_number": 371, "usage_type": "call"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 371, "usage_type": "name"}, {"api_name": "nova.api.openstack.wsgi.RequestDeserializer", "line_number": 376, "usage_type": "call"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 376, "usage_type": "name"}, {"api_name": "nova.api.openstack.wsgi.Resource", "line_number": 379, "usage_type": "call"}, {"api_name": "nova.api.openstack.wsgi", "line_number": 379, "usage_type": "name"}]} +{"seq_id": "13159953774", "text": "from flask import Flask, render_template, request\nimport hashlib\n\napp = Flask(__name__)\n\ndef get_gravatar_url(email):\n # Convert the email address to lowercase and encode it\n email_bytes = email.lower().encode('utf-8')\n # Generate the MD5 hash of the email\n digest = hashlib.md5(email_bytes).hexdigest()\n # Return the Gravatar URL\n return f'https://www.gravatar.com/avatar/{digest}'\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n gravatar_url = None\n if request.method == 'POST':\n email = request.form.get('email')\n if email:\n gravatar_url = get_gravatar_url(email)\n return render_template('index.html', gravatar_url=gravatar_url)\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "repo_name": "sivori/chatgpt-projects", "sub_path": "gravatar-retrieval/gravatar-retrieve.py", "file_name": "gravatar-retrieve.py", "file_ext": "py", "file_size_in_byte": 744, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 4, "usage_type": "call"}, {"api_name": "hashlib.md5", "line_number": 10, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 17, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 17, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 18, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 18, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 18, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 21, "usage_type": "call"}]} +{"seq_id": "36174619998", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 26 22:01:16 2017\n\n@author: Jonas Stein\n\"\"\"\n\nimport datetime\n\ndef CreateLogfile():\n MyLogTime = datetime.datetime.now()\n MyFileName = MyLogTime.strftime(\"protokoll_%Y-%m-%dT%H_%M_%S.csv\")\n f = open(MyFileName, 'w')\n f.write('\"Nr.\",\"Datum Uhrzeit\",\"Dauer (s)\",\"Geschwindigkeit (km/h)\"\\n')\n f.close\n return(MyFileName)\n\ndef LogThis(MyFileName, Text):\n f = open(MyFileName, 'a')\n f.write(Text + '\\n')\n f.close\n\n\ndef measure(Distance_meter, FzID, MyFileName):\n Tstart = datetime.datetime.now()\n input(\"# (Messung läuft...) Stopp mit Return\")\n Tstop = datetime.datetime.now()\n \n TdifferenceSeconds = (Tstop-Tstart).total_seconds()\n \n Speed_m_s = Distance_meter / TdifferenceSeconds\n Speed_km_h = Speed_m_s /1000 * 3600\n StrTimeStamp = Tstart.strftime(\"%Y-%m-%d %H:%M:%S\")\n \n print('%03d, %s, %.6f, %.1f'%(FzID,StrTimeStamp,TdifferenceSeconds,Speed_km_h))\n LogThis(MyFileName,'%03d,%s,%.6f,%.1f'%(FzID,StrTimeStamp,TdifferenceSeconds,Speed_km_h))\n\ndef main():\n FzID = 0\n\n MyLogFile = CreateLogfile()\n\n Distance_meter = 86.5\n print('Geschwindigkeitsmessung.\\n Distanz zwischen Start- und Stoppsignal: %f (m)\\n\\n'%Distance_meter)\n print('Nr., Datum Uhrzeit, Dauer (s), Geschwindigkeit (km/h)')\n while True:\n KeyByUser = input(\"# (Standby) Start mit Return, Quit mit q\")\n if KeyByUser != '':\n print('Ende der Messserie.\\n')\n print('Protokoll öffnen mit')\n print('libreoffice %s'%(MyLogFile))\n break\n elif KeyByUser == '':\n FzID = FzID + 1\n measure(Distance_meter, FzID, MyLogFile)\n \n\nif __name__ == '__main__':\n main()\n", "repo_name": "jonasstein/speed", "sub_path": "speed.py", "file_name": "speed.py", "file_ext": "py", "file_size_in_byte": 1831, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "datetime.datetime.now", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 12, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 26, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 26, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 28, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 28, "usage_type": "attribute"}]} +{"seq_id": "42568766138", "text": "from django.contrib import admin\nimport api.models\n\n\n@admin.register(api.models.Reading)\nclass MeterReadingAdmin(admin.ModelAdmin):\n list_display = (\n \"mpan_core\",\n \"register_id\",\n \"meter_id\",\n \"reading_value\",\n \"reading_taken_at\",\n \"reading_flag\",\n \"reading_method\",\n \"file_name\",\n )\n search_fields = (\n \"mpan_core__mpan_core__startswith\",\n \"meter_id__id__startswith\",\n )\n", "repo_name": "ryjinh/meter_reading", "sub_path": "api/admin.py", "file_name": "admin.py", "file_ext": "py", "file_size_in_byte": 455, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.contrib.admin.ModelAdmin", "line_number": 6, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 6, "usage_type": "name"}, {"api_name": "django.contrib.admin.register", "line_number": 5, "usage_type": "call"}, {"api_name": "django.contrib.admin", "line_number": 5, "usage_type": "name"}, {"api_name": "api.models.models", "line_number": 5, "usage_type": "attribute"}, {"api_name": "api.models", "line_number": 5, "usage_type": "name"}]} +{"seq_id": "34550182891", "text": "import sys\n\nfrom PyQt6.QtCore import (\n QSize, Qt,\n QSortFilterProxyModel,\n\n)\nfrom PyQt6.QtWidgets import (\n QApplication, QMainWindow, \n QWidget, QTabWidget, \n QTableWidget, QTableWidgetItem,\n QPushButton, QLineEdit, QCheckBox, QLabel,\n QGridLayout, QVBoxLayout, QHBoxLayout,\n QFileDialog, QHeaderView, \n QInputDialog, QFormLayout, QDialog, QMessageBox, QErrorMessage,\n \n)\n\nfrom PyQt6.QtGui import (\n QAction, QIcon,\n)\n\n# from pyroGamer.DataManager.Configs import (\n# LocalConfig, CloudConfig,\n# )\n\nimport subprocess\nimport multiprocessing\nfrom pathlib import Path\nimport json\nimport argparse\nimport pprint\nimport textwrap\nfrom colorama import Fore, Back, Style, init\ninit(autoreset=True)\n\n\nfrom pyroGamer.GUI.Hub.Elements.Tables import ProjectTable\n\nclass LocalTab(QWidget):\n def __init__(self):\n super().__init__()\n\n self.layout = QVBoxLayout()\n\n buttonsLayout = QHBoxLayout()\n buttonsLayout.addWidget(QLineEdit())\n openProjectButton = QPushButton(\"Open\")\n buttonsLayout.addWidget(openProjectButton)\n openProjectButton.clicked.connect(self.open_project)\n newProjectButton = QPushButton(\"New\")\n buttonsLayout.addWidget(newProjectButton)\n newProjectButton.clicked.connect(self.new_project)\n self.layout.addLayout(buttonsLayout)\n\n self.layout.addWidget(ProjectTable.Local())\n \n self.setLayout(self.layout)\n\n\n \n\n def open_project(self):\n fname = QFileDialog.getOpenFileName(self, 'Open file', '' ,\"Json files (*.json)\")\n if fname[0] == \"\":\n return\n path = Path(fname[0])\n\n # LocalConfig.AddProject(path)\n print(Fore.BLUE + \"Calling \" + \"pyroGamer.GUI.Hub.Configs --AddExistingProject\" + \" to open project...\")\n result = subprocess.run(['python', '-m', 'pyroGamer.GUI.Hub.Configs',\n '--AddExistingProject', str(path.as_posix())],\n capture_output=True, text=True)\n \n if result.returncode != 0:\n print(Fore.LIGHTBLACK_EX + textwrap.indent(pprint.pformat(result.stdout, width=100), '>'))\n print(Fore.RED + Style.BRIGHT + \"Error: \" + str(result.stderr))\n sys.exit(1)\n\n self.RefreshTable()\n\n\n def new_project(self):\n inputDialog = QDialog()\n inputDialog.setWindowTitle(\"Create new project\")\n inputDialog.setFixedSize(200, 200)\n mainLayout = QVBoxLayout()\n \n nameLayout = QHBoxLayout()\n # label = QLabel(\"Project Name:\")\n # nameLayout.addWidget(label)\n NameInput = QLineEdit()\n NameInput.setPlaceholderText(\"Project Name\")\n nameLayout.addWidget(NameInput)\n mainLayout.addLayout(nameLayout)\n\n pathLayout = QHBoxLayout()\n # label = QLabel(\"Parent Folder Path:\")\n # label.setAlignment(Qt.AlignmentFlag.AlignCenter)\n # pathLayout.addWidget(label)\n PathInput = QLineEdit()\n PathInput.setPlaceholderText(\"Parent Folder Path\")\n PathInput.setReadOnly(True)\n pathLayout.addWidget(PathInput)\n\n def browse():\n return PathInput.setText(QFileDialog.getExistingDirectory(self, \"Select Directory\"))\n \n browseAction = QAction(\"Browse\")\n browseAction.setIcon(QIcon(\"pyroGamer/Hub/icons/blue-document-search-result.png\"))\n browseAction.triggered.connect(browse)\n PathInput.addAction(browseAction, QLineEdit.ActionPosition.TrailingPosition)\n\n mainLayout.addLayout(pathLayout)\n\n buttonsLayout = QVBoxLayout()\n CreateButton = QPushButton(\"Create\")\n buttonsLayout.addWidget(CreateButton)\n def fields_filled():\n return NameInput.text() != \"\" and PathInput.text() != \"\"\n \n def createProject():\n if not fields_filled():\n QMessageBox.critical(None, \"Error\", \"Please fill in all fields\")\n return\n \n print(Fore.BLUE + \"Calling \" + \"pyroGamer.GUI.Hub.Configs AddNewProject --name --path\" + \" to add new project...\")\n result = subprocess.run(['python', '-m', 'pyroGamer.GUI.Hub.Configs',\n 'AddNewProject', '--name', NameInput.text(), '--path', Path(PathInput.text()).as_posix()],\n capture_output=True, text=True)\n \n if(result.returncode != 0):\n print(Fore.LIGHTBLACK_EX + textwrap.indent(pprint.pformat(result.stdout, width=100), '>'))\n print(Fore.RED + Style.BRIGHT + \"Error: \" + str(result.stderr))\n sys.exit(1)\n \n self.RefreshTable()\n inputDialog.close()\n \n CreateButton.clicked.connect(createProject)\n\n CancelButton = QPushButton(\"Cancel\")\n buttonsLayout.addWidget(CancelButton)\n CancelButton.clicked.connect(lambda: inputDialog.close())\n mainLayout.addLayout(buttonsLayout)\n\n inputDialog.setLayout(mainLayout)\n\n inputDialog.exec()\n\n def RefreshTable(self):\n for i in range(self.layout.count()):\n widget = self.layout.itemAt(i).widget()\n if widget is not None:\n widget.deleteLater()\n self.layout.removeWidget(widget)\n\n self.layout.addWidget(ProjectTable.Local())\n self.setLayout(self.layout)\n \n\n\n\n# class Local(QWidget):\n# def __init__(self, ProjectListPath):\n# super().__init__()\n# layout = QVBoxLayout()\n# buttonsLayout = QHBoxLayout()\n# buttonsLayout.addWidget(QLineEdit())\n \n# openProjectButton = QPushButton(\"Open\")\n# buttonsLayout.addWidget(openProjectButton)\n# openProjectButton.clicked.connect(self.open_project)\n\n# newProjectButton = QPushButton(\"New\")\n# buttonsLayout.addWidget(newProjectButton)\n# newProjectButton.clicked.connect(self.new_project)\n# layout.addLayout(buttonsLayout)\n\n# layout.addWidget(Projects_Table.Local(ProjectListPath))\n\n# self.setLayout(layout)\n\n# def open_project(self):\n# fname = QFileDialog.getOpenFileName(self, 'Open file', '' ,\"Json files (*.json)\")\n# if fname[0] == \"\":\n# return\n# path = Path(fname[0])\n\n# LocalConfig.AddProject(path)\n# Local.RefreshTable()\n\n# def new_project(self): \n# inputDialog = QDialog()\n\n# mainLayout = QVBoxLayout()\n# mainLayout.addWidget(QLabel(\"Create new project\"))\n \n# nameLayout = QHBoxLayout()\n# nameLayout.addWidget(QLabel(\"Project Name:\"))\n# NameInput = QLineEdit()\n# nameLayout.addWidget(NameInput)\n# mainLayout.addLayout(nameLayout)\n\n# pathLayout = QHBoxLayout()\n# pathLayout.addWidget(QLabel(\"Parent Folder Path:\"))\n# PathInput = QLineEdit()\n# PathInput.setReadOnly(True)\n# pathLayout.addWidget(PathInput)\n# BrowsePathButton = QPushButton(\"Browse\")\n# pathLayout.addWidget(BrowsePathButton)\n# def browse():\n# return PathInput.setText(QFileDialog.getExistingDirectory(self, \"Select Directory\"))\n# BrowsePathButton.clicked.connect(browse)\n# mainLayout.addLayout(pathLayout)\n\n# buttonsLayout = QHBoxLayout()\n# CreateButton = QPushButton(\"Create\")\n# buttonsLayout.addWidget(CreateButton)\n# def fields_filled():\n# return NameInput.text() != \"\" and PathInput.text() != \"\"\n# def createProject():\n# if not fields_filled():\n# QMessageBox.critical(None, \"Error\", \"Please fill in all fields\")\n# return\n# LocalConfig.AddEmptyProject(name = NameInput.text(), path = Path(PathInput.text())) \n# Local.RefreshTable() \n# inputDialog.close()\n \n# CreateButton.clicked.connect(createProject)\n\n# CancelButton = QPushButton(\"Cancel\")\n# buttonsLayout.addWidget(CancelButton)\n# CancelButton.clicked.connect(lambda: inputDialog.close())\n# mainLayout.addLayout(buttonsLayout)\n\n# inputDialog.setLayout(mainLayout)\n\n# inputDialog.exec()\n\n \n# def RefreshTable():\n# Local.clearTable()\n# Projects_Table.populateTable(Projects_Table.table, LocalConfig.GetProjectList())\n\n# def clearTable():\n# Projects_Table.table.clearContents()\n# Projects_Table.table.setRowCount(0)\n\n\n# class Cloud(QWidget):\n# def __init__(self):\n# super().__init__()\n# layout = QGridLayout()\n\n# layout.addWidget(Projects_Table.Cloud())\n\n# self.setLayout(layout)\n\n# class Projects_Table(QTableWidget):\n# LocalTable = QTableWidget()\n\n# def Cloud():\n# return Projects_Table.From(CloudConfig)\n\n \n# def Local(ProjectListPath):\n# Projects_Table.initTable(Projects_Table.LocalTable)\n\n# headers = []\n# for col in range(Projects_Table.table.columnCount()):\n# header_item = Projects_Table.table.horizontalHeaderItem(col)\n# if header_item is not None:\n# headers.append(header_item.text())\n\n\n# def item_changed(item):\n# project_list = configClass.GetProjectList()\n\n# if (item.column() == headers.index(\"Name\")):\n# configClass.SetName(project_list[item.row()][\"ID\"], item.text())\n# # elif (item.column() == headers.index(\"Path\")):\n# # configClass.SetPath(project_list[item.row()][\"ID\"], item.text())\n# # elif (item.column() == headers.index(\"Created\")):\n# # configClass.SetCreated(project_list[item.row()][\"ID\"], item.text())\n# else:\n# pass\n\n# Projects_Table.table.itemChanged.connect(item_changed)\n\n# Projects_Table.populateTable(Projects_Table.table, configClass.GetProjectList())\n\n# return Projects_Table.table\n \n\n\n\n# def populateTable(table, project_list):\n# if(table is None):\n# table = Projects_Table.table\n# table.setRowCount(len(project_list))\n\n# for row, project in enumerate(project_list):\n# table.setCellWidget(row, 0, Buttons.Star(project))\n\n# project_name = QTableWidgetItem(project[\"Project Name\"])\n# project_name.setFlags(Qt.ItemFlag.ItemIsEditable | Qt.ItemFlag.ItemIsEnabled)\n# table.setItem(row, 1, project_name)\n\n# project_path = QTableWidgetItem(project[\"Project Path\"])\n# project_path.setFlags(Qt.ItemFlag.ItemIsEnabled)\n# table.setItem(row, 2, project_path)\n\n# created_date = QTableWidgetItem(project[\"Created\"])\n# created_date.setFlags(Qt.ItemFlag.ItemIsEnabled)\n# table.setItem(row, 3, created_date)\n\n# table.setCellWidget(row, 4, Buttons.Play(project))\n# table.setCellWidget(row, 5, Buttons.Options(project))\n\n# return table\n \n# def initTable(table):\n# # headers = tableConfig['TABLE_HEADERS']\n# # table.setColumnCount(len(headers))\n# # table.setHorizontalHeaderLabels(headers)\n\n# table.setSortingEnabled(True)\n# table.setStyleSheet(\n# \"QTableWidget::item:selected {\"\n# \" background-color: transparent;\"\n# \" color: black;\"\n# \"}\"\n \n# \"QTableWidget {\"\n# \" gridline-color: transparent;\"\n# \" border: none;\" # Remove the border around the table\n# \"}\"\n# \"QHeaderView::section {\"\n# \" background-color: lightgray;\"\n# \" border: none;\" # Remove the header borders\n# \" padding: 4px;\" # Add padding to headers\n# \"}\"\n# ) \n# # table_unit = tableConfig['TABLE_UNIT']\n# table.setColumnWidth(0, 25)\n# table.setColumnWidth(1, 25 * 5)\n# table.setColumnWidth(2, 25 * 7)\n# table.setColumnWidth(3, 25 * 3)\n# table.setColumnWidth(4, 25)\n# table.setColumnWidth(5, 25)\n\n# return table\n\n\n# # Only Local for now\n# class Buttons(QPushButton):\n# class Star(QPushButton):\n# def __init__(self, project):\n# super().__init__()\n# self.setCheckable(True)\n# self.toggled.connect(self.buttonClicked(project))\n# self.setStyleSheet(\n# \"QPushButton {\"\n# \" border: none;\" # Remove the button border\n# \"}\"\n# \"QPushButton:checked {\"\n# \" color: black;\"\n# \"}\"\n# \"QPushButton:hover {\"\n# \" color: grey;\"\n# \"}\"\n# )\n# if(project[\"Star\"]):\n# self.setChecked(True)\n# self.setText(\"★\")\n# else:\n# self.setChecked(False)\n# self.setText(\"☆\")\n\n# font = self.font()\n# font.setPointSize(15)\n# self.setFont(font)\n\n# def buttonClicked(self, project):\n# def toggle():\n# if(self.isChecked()):\n# # print(f\"Starred + {project['Project Name']}\")\n# # project[\"Star\"] = True\n# self.setText(\"★\")\n# LocalConfig.SetStar(project[\"ID\"], True)\n# else:\n# # print(f\"Unstarred + {project['Project Name']}\")\n# # project[\"Star\"] = False\n# self.setText(\"☆\")\n# LocalConfig.SetStar(project[\"ID\"], False)\n# return toggle\n \n# class Play(QPushButton):\n# def __init__(self, project):\n# super().__init__()\n# self.setText(\"▶\")\n# self.activeProjectPath = project[\"Project Path\"]\n# self.clicked.connect(self.buttonClicked)\n# self.setStyleSheet(\n# \"QPushButton {\"\n# \" border: none;\"\n# \" text-align: center;\"\n# \" vertical-align: middle;\"\n# \"}\"\n# \"QPushButton:hover {\"\n# \" color: green;\"\n# \"}\"\n# )\n# font = self.font()\n# font.setPointSize(25)\n# self.setFont(font)\n\n# def buttonClicked(self, project):\n# subprocess.Popen([\"python\", \"-m\", \"pyroGamer.Editor\"] + [\"--projectPath\", self.activeProjectPath])\n\n# class Options(QPushButton):\n# def __init__(self, project):\n# super().__init__()\n# self.setText(\"⋮\")\n# self.clicked.connect(lambda: print(\"Options\"))\n# # hide the button's border\n# self.setStyleSheet(\n# \"QPushButton {\"\n# \" border: none;\"\n# \" text-align: center;\"\n# \" vertical-align: middle;\"\n# \"}\"\n# \"QPushButton:hover {\"\n# \" color: green;\"\n# \"}\"\n# )\n# font = self.font()\n# font.setPointSize(25)\n# self.setFont(font)\n", "repo_name": "BobuDragos/pyroGamer", "sub_path": "GUI/Hub/Elements/Tabs.py", "file_name": "Tabs.py", "file_ext": "py", "file_size_in_byte": 15247, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "colorama.init", "line_number": 35, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QWidget", "line_number": 40, "usage_type": "name"}, {"api_name": "PyQt6.QtWidgets.QVBoxLayout", "line_number": 44, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QHBoxLayout", "line_number": 46, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QLineEdit", "line_number": 47, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QPushButton", "line_number": 48, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QPushButton", "line_number": 51, "usage_type": "call"}, {"api_name": "pyroGamer.GUI.Hub.Elements.Tables.ProjectTable.Local", "line_number": 56, "usage_type": "call"}, {"api_name": "pyroGamer.GUI.Hub.Elements.Tables.ProjectTable", "line_number": 56, "usage_type": "name"}, {"api_name": "PyQt6.QtWidgets.QFileDialog.getOpenFileName", "line_number": 64, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QFileDialog", "line_number": 64, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 67, "usage_type": "call"}, {"api_name": "colorama.Fore.BLUE", "line_number": 70, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 70, "usage_type": "name"}, {"api_name": "subprocess.run", "line_number": 71, "usage_type": "call"}, {"api_name": "colorama.Fore.LIGHTBLACK_EX", "line_number": 76, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 76, "usage_type": "name"}, {"api_name": "textwrap.indent", "line_number": 76, "usage_type": "call"}, {"api_name": "pprint.pformat", "line_number": 76, "usage_type": "call"}, {"api_name": "colorama.Fore.RED", "line_number": 77, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 77, "usage_type": "name"}, {"api_name": "colorama.Style.BRIGHT", "line_number": 77, "usage_type": "attribute"}, {"api_name": "colorama.Style", "line_number": 77, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 78, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QDialog", "line_number": 84, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QVBoxLayout", "line_number": 87, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QHBoxLayout", "line_number": 89, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QLineEdit", "line_number": 92, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QHBoxLayout", "line_number": 97, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QLineEdit", "line_number": 101, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QFileDialog.getExistingDirectory", "line_number": 107, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QFileDialog", "line_number": 107, "usage_type": "name"}, {"api_name": "PyQt6.QtGui.QAction", "line_number": 109, "usage_type": "call"}, {"api_name": "PyQt6.QtGui.QIcon", "line_number": 110, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QLineEdit.ActionPosition", "line_number": 112, "usage_type": "attribute"}, {"api_name": "PyQt6.QtWidgets.QLineEdit", "line_number": 112, "usage_type": "name"}, {"api_name": "PyQt6.QtWidgets.QVBoxLayout", "line_number": 116, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QPushButton", "line_number": 117, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QMessageBox.critical", "line_number": 124, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QMessageBox", "line_number": 124, "usage_type": "name"}, {"api_name": "colorama.Fore.BLUE", "line_number": 127, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 127, "usage_type": "name"}, {"api_name": "subprocess.run", "line_number": 128, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 129, "usage_type": "call"}, {"api_name": "colorama.Fore.LIGHTBLACK_EX", "line_number": 133, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 133, "usage_type": "name"}, {"api_name": "textwrap.indent", "line_number": 133, "usage_type": "call"}, {"api_name": "pprint.pformat", "line_number": 133, "usage_type": "call"}, {"api_name": "colorama.Fore.RED", "line_number": 134, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 134, "usage_type": "name"}, {"api_name": "colorama.Style.BRIGHT", "line_number": 134, "usage_type": "attribute"}, {"api_name": "colorama.Style", "line_number": 134, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 135, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QPushButton", "line_number": 142, "usage_type": "call"}, {"api_name": "pyroGamer.GUI.Hub.Elements.Tables.ProjectTable.Local", "line_number": 158, "usage_type": "call"}, {"api_name": "pyroGamer.GUI.Hub.Elements.Tables.ProjectTable", "line_number": 158, "usage_type": "name"}]} +{"seq_id": "40812497598", "text": "from django.conf import settings\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\n\nclass ConfigView(APIView):\n def get(self, request):\n return Response(\n {\n key.lower(): value\n for key, value in settings.LICO.items()\n }\n )\n\n\nclass VersionView(APIView):\n def get(self, request):\n from ._version import build_date, version\n from .subapp import iter_sub_apps\n\n return Response(\n {\n 'version': version,\n 'build_date': build_date,\n 'subapps': [\n {\n 'name': app.dist.project_name,\n 'version': app.dist.version\n }\n for app in iter_sub_apps()\n ]\n }\n )\n\n\nclass ApplicationConfigView(APIView):\n app = None\n\n def get(self, request):\n return Response(\n self.app.on_show_config(settings)\n if self.app is not None else {}\n )\n", "repo_name": "lenovo/openlico", "sub_path": "core/base/lico/core/base/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1076, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "24", "api": [{"api_name": "rest_framework.views.APIView", "line_number": 6, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 8, "usage_type": "call"}, {"api_name": "django.conf.settings.LICO.items", "line_number": 11, "usage_type": "call"}, {"api_name": "django.conf.settings.LICO", "line_number": 11, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 11, "usage_type": "name"}, {"api_name": "rest_framework.views.APIView", "line_number": 16, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 21, "usage_type": "call"}, {"api_name": "_version.version", "line_number": 23, "usage_type": "name"}, {"api_name": "_version.build_date", "line_number": 24, "usage_type": "name"}, {"api_name": "subapp.iter_sub_apps", "line_number": 30, "usage_type": "call"}, {"api_name": "rest_framework.views.APIView", "line_number": 36, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 40, "usage_type": "call"}, {"api_name": "django.conf.settings", "line_number": 41, "usage_type": "argument"}]} +{"seq_id": "10243213772", "text": "import pygame\nfrom pygame import Rect, Color\nfrom pygame.constants import K_LEFT, K_RIGHT\n\nfrom pymunk import Body, Poly\nimport pymunk\n\nfrom config import GRAVITY, WIDTH, HEIGHT\n\n\nclass Player:\n\n def __init__ (self, space):\n \n # size\n self.w = 25\n self.h = 25\n\n # position\n self.x = WIDTH // 2 - self.w // 2\n self.y = HEIGHT // 2 - self.h // 2\n\n # pygame rectangle\n self.rect = Rect (self.x, self.y, self.w, self.h)\n self.color = Color (209, 87, 0)\n\n # physics\n self.rigidbody = Body (0, 5, body_type=Body.DYNAMIC)\n self.rigidbody.position = self.x, self.y\n \n self.hitbox = pymunk.Circle (self.rigidbody, self.w / 2)\n self.hitbox.mass = 10\n self.hitbox.elasticity = 0\n self.hitbox.friction = 0\n\n space.add (self.rigidbody, self.hitbox)\n\n \n\n \n def update (self, dt):\n\n keys = pygame.key.get_pressed()\n\n if keys [K_LEFT] or keys [K_RIGHT]:\n\n if keys [K_LEFT]:\n self.rigidbody.apply_force_at_world_point ( (-1000,0), (0,0) )\n\n if keys [K_RIGHT]:\n self.rigidbody.apply_force_at_world_point ( (1000,0), (0,0) )\n\n\n\n\n x = int (self.rigidbody.position.x)\n y = int (self.rigidbody.position.y)\n self.x = x\n self.y = y\n self.rect.update(x, y, self.w, self.h)\n\n return\n\n\n\n def draw (self, window):\n \n pygame.draw.rect (window, self.color, self.rect)\n\n return", "repo_name": "CSnackerman/pymunk_test", "sub_path": "player.py", "file_name": "player.py", "file_ext": "py", "file_size_in_byte": 1523, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "config.WIDTH", "line_number": 20, "usage_type": "name"}, {"api_name": "config.HEIGHT", "line_number": 21, "usage_type": "name"}, {"api_name": "pygame.Rect", "line_number": 24, "usage_type": "call"}, {"api_name": "pygame.Color", "line_number": 25, "usage_type": "call"}, {"api_name": "pymunk.Body", "line_number": 28, "usage_type": "call"}, {"api_name": "pymunk.Body.DYNAMIC", "line_number": 28, "usage_type": "attribute"}, {"api_name": "pymunk.Circle", "line_number": 31, "usage_type": "call"}, {"api_name": "pygame.key.get_pressed", "line_number": 43, "usage_type": "call"}, {"api_name": "pygame.key", "line_number": 43, "usage_type": "attribute"}, {"api_name": "pygame.constants.K_LEFT", "line_number": 45, "usage_type": "name"}, {"api_name": "pygame.constants.K_RIGHT", "line_number": 45, "usage_type": "name"}, {"api_name": "pygame.constants.K_LEFT", "line_number": 47, "usage_type": "name"}, {"api_name": "pygame.constants.K_RIGHT", "line_number": 50, "usage_type": "name"}, {"api_name": "pygame.draw.rect", "line_number": 68, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 68, "usage_type": "attribute"}]} +{"seq_id": "21436718121", "text": "import subprocess\nimport inquirer\nimport re\n\n# commands\ncreate_list = \"adb shell pm list packages > ~/package_list.txt\"\npackage_list = \"adb shell pm list packages\"\nremove = \"adb shell pm uninstall --user 0 \" # Space needed at the end. -k: Keep data and cache directories after package removal.\nadb_shell = \"adb shell\"\nsearch_command = \"adb shell pm list packages \" # Space needed at the end.\ntext_append = \" > ~/package_list.txt\" # Space needed in front.\n\n\ndef remove_packs(list_file): # CREATE TEXT FILE:\n with open('package_list.txt', 'w+'):\n subprocess.call(list_file, shell=True)\n\n with open('package_list.txt', 'r') as f: # READ TEXT FILE:\n lines = f.readlines()\n\n items = [] # CLEANUP STRINGS AND GET LIST OF PACKAGES\n for i in lines:\n the_list = i.split(\":\")\n items.append(the_list[1].replace(\"\\n\", \"\"))\n\n if len(items) == 0:\n print(\"\\n***Nothing found\")\n else:\n print(\"### TOTAL PACKAGES:\", len(items))\n\n package_object = [\n inquirer.Checkbox('packages_name',\n message=\"Select the packages you would like to remove with the space bar\",\n choices=items,\n ),\n ]\n package_selections = inquirer.prompt(package_object)\n packs_for_removal = package_selections.get('packages_name')\n i = 0\n\n # This is just confirmation that at least one package has been selected:\n if len(packs_for_removal) == 0:\n print(\"\\n***No selection: back to menu...\\n\")\n elif packs_for_removal:\n selection = input(\"\\n***Are you sure you want to remove these package(s)? y/N: \").lower()\n if selection == \"y\":\n while i < len(packs_for_removal):\n print(\"Removing package: \", i, \":\", packs_for_removal[i], \"...\")\n subprocess.call(remove + packs_for_removal[i], shell=True)\n i += 1\n elif selection == \"n\":\n print(\"\\n***Nothing to remove, back to menu...\\n\")\n elif selection != \"y\" or selection != \"n\":\n print(\"\\n***Bad input, only 'y' or 'n'.\\n\")\n\n\nprint(\"### Package Remover Interface for ADB ###\")\nresults = 0\nwhile results != 4:\n choose = [\n inquirer.List('menu',\n message=\"Please, choose an option\",\n choices=[('List all packages and select for removal', '1'), ('Search packages by keyword', '2'),\n ('Spawn ADB shell', '3'), ('Exit', '4')],\n ),\n ]\n choice = inquirer.prompt(choose)\n results = choice['menu'][0] # Option selected by user\n\n if results == \"1\":\n remove_packs(create_list)\n\n elif results == \"2\":\n search_filter = input(\"Search any part of the package hierarchy:\").lower()\n while True:\n if not re.match(\"^[A-Za-z0-9_]*$\", search_filter):\n print(\"\\n***Only alphanumeric and underscore characters!\\n\")\n break\n elif not search_filter:\n print(\"\\n***Please search for something.\\n\")\n break\n else:\n triumvirate = search_command + search_filter + text_append\n remove_packs(triumvirate)\n break\n\n elif results == \"3\":\n subprocess.call(adb_shell, shell=True)\n\n elif results == \"4\":\n print(\"Bye!\")\n break\n", "repo_name": "fercastt/Android-Package-Remover-Interface", "sub_path": "pack_remover.py", "file_name": "pack_remover.py", "file_ext": "py", "file_size_in_byte": 3368, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "subprocess.call", "line_number": 16, "usage_type": "call"}, {"api_name": "inquirer.Checkbox", "line_number": 32, "usage_type": "call"}, {"api_name": "inquirer.prompt", "line_number": 37, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 49, "usage_type": "call"}, {"api_name": "inquirer.List", "line_number": 61, "usage_type": "call"}, {"api_name": "inquirer.prompt", "line_number": 67, "usage_type": "call"}, {"api_name": "re.match", "line_number": 76, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 88, "usage_type": "call"}]} +{"seq_id": "70969524541", "text": "import logging\nfrom aiogram.utils.exceptions import BotBlocked\nfrom aiogram import Bot, Dispatcher, types\nfrom aiogram.contrib.fsm_storage.memory import MemoryStorage\nimport asyncio\nimport config as conf\nfrom navigate import register_navigate\nfrom aiogram.types import BotCommand\n\nlogger = logging.getLogger(__name__)\n\nasync def set_commands(bot: Bot):\n commands = [\n BotCommand(command='/menu', description=\"Меню\")\n ]\n await bot.set_my_commands(commands)\n\nasync def main():\n # Настройка логирования в stdout\n logging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n )\n logger.error(\"Starting bot\")\n\n # Парсинг файла конфигурации\n config = conf.load_config(\"bot.ini\")\n\n # Объявление и инициализация объектов бота и диспетчера\n bot = Bot(token=config.tg_bot.token)\n dp = Dispatcher(bot, storage=MemoryStorage())\n register_navigate(dp)\n\n @dp.errors_handler(exception=BotBlocked)\n async def error_bot_blocked(update: types.Update, exception: BotBlocked):\n # Update: объект события от Telegram. Exception: объект исключения\n # Здесь можно как-то обработать блокировку, например, удалить пользователя из БД\n print(f\"Error: {exception}\")\n return True\n\n await set_commands(bot)\n await dp.start_polling()\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n", "repo_name": "zhakos/tgbot_for_ali", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1593, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 10, "usage_type": "call"}, {"api_name": "aiogram.Bot", "line_number": 12, "usage_type": "name"}, {"api_name": "aiogram.types.BotCommand", "line_number": 14, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 20, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 21, "usage_type": "attribute"}, {"api_name": "config.load_config", "line_number": 27, "usage_type": "call"}, {"api_name": "aiogram.Bot", "line_number": 30, "usage_type": "call"}, {"api_name": "config.tg_bot", "line_number": 30, "usage_type": "attribute"}, {"api_name": "aiogram.Dispatcher", "line_number": 31, "usage_type": "call"}, {"api_name": "aiogram.contrib.fsm_storage.memory.MemoryStorage", "line_number": 31, "usage_type": "call"}, {"api_name": "navigate.register_navigate", "line_number": 32, "usage_type": "call"}, {"api_name": "aiogram.types.Update", "line_number": 35, "usage_type": "attribute"}, {"api_name": "aiogram.types", "line_number": 35, "usage_type": "name"}, {"api_name": "aiogram.utils.exceptions.BotBlocked", "line_number": 35, "usage_type": "name"}, {"api_name": "aiogram.utils.exceptions.BotBlocked", "line_number": 34, "usage_type": "name"}, {"api_name": "asyncio.run", "line_number": 46, "usage_type": "call"}]} +{"seq_id": "37079197239", "text": "import time\nimport tempfile\nimport shutil\nimport simplejson as json\nimport subprocess\nfrom os import remove\nfrom oio.common.http import get_pool_manager\n\nfrom tests.utils import BaseTestCase, random_str, random_id\n\n\ndef _key(rec):\n return '|'.join((rec['container_id'], rec['content_id'], rec['chunk_id']))\n\n\nclass TestRdirServer(BaseTestCase):\n def setUp(self):\n super(TestRdirServer, self).setUp()\n self.http_pool = get_pool_manager(max_retries=10)\n self.num, self.db_path, self.host, self.port = self.get_service('rdir')\n self.vol = self._volume()\n\n def tearDown(self):\n super(TestRdirServer, self).tearDown()\n self.http_pool.clear()\n\n def _volume(self):\n return random_id(8)\n\n def _record(self):\n return {\"container_id\": random_id(64),\n \"content_id\": random_id(32),\n \"chunk_id\": random_id(64),\n \"mtime\": 17}\n\n def _rdir_url(self, tail):\n return 'http://{0}:{1}{2}'.format(self.host, self.port, tail)\n\n def _get(self, url, **kwargs):\n return self.request('GET', self._rdir_url(url), **kwargs)\n\n def _post(self, url, **kwargs):\n return self.request('POST', self._rdir_url(url), **kwargs)\n\n def _delete(self, url, **kwargs):\n return self.request('DELETE', self._rdir_url(url), **kwargs)\n\n def test_explicit_create(self):\n rec = self._record()\n\n # try to push on unknown volume\n resp = self._post(\n \"/v1/rdir/push\", params={'vol': self.vol},\n data=json.dumps(rec))\n self.assertEqual(resp.status, 404)\n\n # The fetch fails\n resp = self._post(\"/v1/rdir/fetch\", params={'vol': self.vol})\n self.assertEqual(resp.status, 404)\n\n # create volume\n resp = self._post(\"/v1/rdir/create\", params={'vol': self.vol})\n self.assertEqual(resp.status, 201)\n\n # the fetch returns an empty array\n resp = self._post(\"/v1/rdir/fetch\", params={'vol': self.vol})\n self.assertEqual(resp.status, 200)\n self.assertEqual(self.json_loads(resp.data), [])\n\n # now the push must succeed\n resp = self._post(\n \"/v1/rdir/push\", params={'vol': self.vol},\n data=json.dumps(rec))\n self.assertEqual(resp.status, 204)\n\n # we must fetch the same data\n resp = self._post(\"/v1/rdir/fetch\", params={'vol': self.vol})\n self.assertEqual(resp.status, 200)\n reference = [\n [_key(rec), {'mtime': rec['mtime'], 'rtime': 0}]\n ]\n self.assertListEqual(self.json_loads(resp.data), reference)\n\n # deleting must succeed\n resp = self._delete(\n \"/v1/rdir/delete\", params={'vol': self.vol},\n data=json.dumps(rec))\n self.assertEqual(resp.status, 204)\n\n # fetching must return an empty array\n resp = self._post(\"/v1/rdir/fetch\", params={'vol': self.vol})\n self.assertEqual(resp.status, 200)\n self.assertEqual(self.json_loads(resp.data), [])\n\n def test_implicit_create(self):\n rec = self._record()\n\n # try to push on unknown volume\n resp = self._post(\n \"/v1/rdir/push\", params={'vol': self.vol},\n data=json.dumps(rec))\n self.assertEqual(resp.status, 404)\n\n # try to push on unknown volume WITH create flag\n resp = self._post(\n \"/v1/rdir/push\", params={'vol': self.vol, 'create': True},\n data=json.dumps(rec))\n self.assertEqual(resp.status, 204)\n\n # We must fetch the same data\n resp = self._post(\"/v1/rdir/fetch\", params={'vol': self.vol})\n self.assertEqual(resp.status, 200)\n self.assertEqual(self.json_loads(resp.data), [\n [_key(rec), {'mtime': rec['mtime'], 'rtime': 0}]\n ])\n\n def test_push_missing_fields(self):\n rec = self._record()\n\n # DB creation\n resp = self._post(\"/v1/rdir/create\", params={'vol': self.vol})\n self.assertEqual(resp.status, 201)\n\n for k in ['container_id', 'content_id', 'chunk_id']:\n save = rec.pop(k)\n # push an incomplete record\n resp = self._post(\n \"/v1/rdir/push\", params={'vol': self.vol},\n data=json.dumps(rec))\n self.assertEqual(resp.status, 400)\n # check we list nothing\n resp = self._post(\"/v1/rdir/fetch\", params={'vol': self.vol})\n self.assertEqual(resp.status, 200)\n self.assertListEqual(self.json_loads(resp.data), [])\n rec[k] = save\n\n def test_lock_unlock(self):\n who = random_str(64)\n\n # lock without who, DB not created\n resp = self._post(\n \"/v1/rdir/admin/lock\", params={'vol': self.vol},\n data=json.dumps({}))\n self.assertEqual(resp.status, 400)\n\n # lock with who, DB not created\n resp = self._post(\n \"/v1/rdir/admin/lock\", params={'vol': self.vol},\n data=json.dumps({'who': who}))\n self.assertEqual(resp.status, 404)\n\n # DB creation\n resp = self._post(\"/v1/rdir/create\", params={'vol': self.vol})\n self.assertEqual(resp.status, 201)\n\n # lock without who\n resp = self._post(\n \"/v1/rdir/admin/lock\", params={'vol': self.vol},\n data=json.dumps({}))\n self.assertEqual(resp.status, 400)\n\n # lock\n resp = self._post(\n \"/v1/rdir/admin/lock\", params={'vol': self.vol},\n data=json.dumps({'who': who}))\n self.assertEqual(resp.status, 204)\n\n # double lock, different who\n resp = self._post(\n \"/v1/rdir/admin/lock\", params={'vol': self.vol},\n data=json.dumps({'who': random_str(64)}))\n self.assertEqual(resp.status, 403)\n body = self.json_loads(resp.data)\n self.assertEqual(body['message'], \"Already locked by %s\" % who)\n\n # unlock\n resp = self._post(\"/v1/rdir/admin/unlock\", params={'vol': self.vol})\n self.assertEqual(resp.status, 204)\n\n def test_rdir_clear_and_lock(self):\n rec = self._record()\n who = random_id(32)\n\n # push with autocreate\n resp = self._post(\n \"/v1/rdir/push\", params={'vol': self.vol, 'create': True},\n data=json.dumps(rec))\n self.assertEqual(resp.status, 204)\n\n # lock\n resp = self._post(\n \"/v1/rdir/admin/lock\", params={'vol': self.vol},\n data=json.dumps({'who': who}))\n self.assertEqual(resp.status, 204)\n\n # try to clear while the lock is held\n resp = self._post(\"/v1/rdir/admin/clear\", params={'vol': self.vol})\n self.assertEqual(resp.status, 403)\n\n # unlock\n resp = self._post(\"/v1/rdir/admin/unlock\", params={'vol': self.vol})\n self.assertEqual(resp.status, 204)\n\n # clear all entries\n resp = self._post(\n \"/v1/rdir/admin/clear\", params={'vol': self.vol},\n data=json.dumps({'all': True}))\n self.assertEqual(resp.status, 200)\n self.assertEqual(self.json_loads(resp.data), {'removed': 1})\n\n def test_vol_status(self):\n # Status on inexistant DB\n resp = self._post(\"/v1/rdir/status\", params={'vol': self.vol})\n self.assertEqual(resp.status, 404)\n\n # DB creation\n resp = self._post(\"/v1/rdir/create\", params={'vol': self.vol})\n self.assertEqual(resp.status, 201)\n\n # Status on an empty DB\n resp = self._get(\"/v1/rdir/status\", params={'vol': self.vol})\n self.assertEqual(resp.status, 200)\n self.assertEqual(self.json_loads(resp.data),\n {'chunk': {'total': 0}, 'container': {}})\n\n\nclass TestRdirServer2(TestRdirServer):\n def setUp(self):\n super(TestRdirServer2, self).setUp()\n self.host = '127.0.0.1'\n self.port = 5999\n self.db_path = tempfile.mkdtemp()\n self.cfg_path = tempfile.mktemp()\n with open(self.cfg_path, 'w') as f:\n f.write(\"[rdir-server]\\n\")\n f.write(\"bind_addr = {0}\\n\".format(self.host))\n f.write(\"bind_port = {0}\\n\".format(self.port))\n f.write(\"namespace = {0}\\n\".format(self.ns))\n f.write(\"db_path = {0}\\n\".format(self.db_path))\n f.write(\"syslog_prefix = OIO,OPENIO,rdir,1\\n\")\n\n self.child = subprocess.Popen(['oio-rdir-server', self.cfg_path],\n close_fds=True)\n if not self._wait_for_that_fucking_slow_startup_on_travis():\n self.child.kill()\n raise Exception(\"The RDIR server is too long to start\")\n\n def tearDown(self):\n super(TestRdirServer2, self).tearDown()\n self.http_pool.clear()\n self._kill_and_watch_it_die()\n shutil.rmtree(self.db_path)\n remove(self.cfg_path)\n\n def _kill_and_watch_it_die(self):\n self.child.terminate()\n self.child.wait()\n\n def _wait_for_that_fucking_slow_startup_on_travis(self):\n for i in range(5):\n if self._check_for_server():\n return True\n time.sleep(i * 0.2)\n return False\n\n def _check_for_server(self):\n hexport = \"%04X\" % self.port\n with open(\"/proc/net/tcp\", \"r\") as f:\n for line in f:\n tokens = line.strip().split()\n port = tokens[1][9:13]\n if port == hexport:\n return True\n return False\n\n def test_status(self):\n\n # check the service has no opened DB\n resp = self._get('/status')\n self.assertEqual(resp.status, 200)\n self.assertEqual(self.json_loads(resp.data), {'opened_db_count': 0})\n\n # DB creation\n resp = self._post(\"/v1/rdir/create\", params={'vol': self.vol})\n self.assertEqual(resp.status, 201)\n\n # The base remains open after it has been created\n resp = self._get('/status')\n self.assertEqual(resp.status, 200)\n self.assertEqual(self.json_loads(resp.data), {'opened_db_count': 1})\n", "repo_name": "kamel-rahim/oio-sds", "sub_path": "tests/functional/rdir/test_server.py", "file_name": "test_server.py", "file_ext": "py", "file_size_in_byte": 10148, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "24", "api": [{"api_name": "tests.utils.BaseTestCase", "line_number": 16, "usage_type": "name"}, {"api_name": "oio.common.http.get_pool_manager", "line_number": 19, "usage_type": "call"}, {"api_name": "tests.utils.random_id", "line_number": 28, "usage_type": "call"}, {"api_name": "tests.utils.random_id", "line_number": 31, "usage_type": "call"}, {"api_name": "tests.utils.random_id", "line_number": 32, "usage_type": "call"}, {"api_name": "tests.utils.random_id", "line_number": 33, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 54, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 73, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 87, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 101, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 107, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 129, "usage_type": "call"}, {"api_name": "tests.utils.random_str", "line_number": 138, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 143, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 149, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 159, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 165, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 171, "usage_type": "call"}, {"api_name": "tests.utils.random_str", "line_number": 171, "usage_type": "call"}, {"api_name": "tests.utils.random_id", "line_number": 182, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 187, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 193, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 207, "usage_type": "call"}, {"api_name": "tempfile.mkdtemp", "line_number": 232, "usage_type": "call"}, {"api_name": "tempfile.mktemp", "line_number": 233, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 242, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 252, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 253, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 263, "usage_type": "call"}]} +{"seq_id": "71450409982", "text": "from flask import Flask, render_template, request\nfrom scrape import scrape_page\n\n\napp = Flask(__name__) \n\n\n@app.route('/')\ndef home():\n\treturn render_template('home.html')\n\n\n@app.route('/search', methods=['POST'])\ndef search():\n\tquery = str(request.form['query'])\n\tdata = scrape_page(query)\n\treturn render_template('result.html', data=data)\n\n\nif __name__ == '__main__':\n\tapp.run(host=\"0.0.0.0\", port=3167)", "repo_name": "AlexMathew/people-search", "sub_path": "routes.py", "file_name": "routes.py", "file_ext": "py", "file_size_in_byte": 406, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 5, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 10, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 15, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 15, "usage_type": "name"}, {"api_name": "scrape.scrape_page", "line_number": 16, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 17, "usage_type": "call"}]} +{"seq_id": "2303183809", "text": "import torch\nimport numpy as np\n\nKERNEL_SIZE = 1\n\n\ndef create_conv_1x1(weight, bias, in_c, out_c):\n assert weight.shape == (out_c, in_c, 1, 1)\n assert bias.shape == (out_c,)\n torch_conv_float = torch.nn.Conv2d(in_c, out_c, KERNEL_SIZE, 1, 0)\n torch_conv_float.weight.data = torch.from_numpy(weight)\n torch_conv_float.bias.data = torch.from_numpy(bias)\n return torch_conv_float\n\n\ndef do_np_conv_1x1(weight, bias, input):\n \"\"\"Do simplist 1x1 conv with out dilation and padding\n\n Args:\n weight(np.array): conv weight, shape: (out_c, in_c, kernel_size, kernel_size)\n bias(np.array): conv bias, shape: (out_c, )\n input(np.array): input, shape: (n, c, h, w)\n \"\"\"\n out_c = weight.shape[0]\n in_c = weight.shape[1]\n input_h = input.shape[2]\n input_w = input.shape[3]\n\n assert weight.shape[2] == KERNEL_SIZE\n assert weight.shape[3] == KERNEL_SIZE\n assert out_c == bias.shape[0]\n assert in_c == input.shape[1]\n reshape_input = input.reshape((in_c, -1))\n multi_result = np.matmul(weight.reshape((out_c, in_c)), reshape_input)\n return (\n multi_result + np.tile(bias.reshape(-1, 1), (1, input_h * input_w))\n ).reshape((1, out_c, input_h, input_w))\n", "repo_name": "GouMinghao/naive_ptq", "sub_path": "py/naive_ptq/float_op/conv.py", "file_name": "conv.py", "file_ext": "py", "file_size_in_byte": 1225, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "torch.nn.Conv2d", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 10, "usage_type": "attribute"}, {"api_name": "torch.from_numpy", "line_number": 11, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.tile", "line_number": 36, "usage_type": "call"}]} +{"seq_id": "3970609811", "text": "from django import forms\nfrom django.forms import ModelForm\nfrom .models import Task, Course\n\n\n# Creates a widget to be used for inputting dates\nclass DateInput(forms.DateInput):\n input_type = 'date'\n\n\n# Uses the Course model so the entered fields can be registered to the Course table\nclass CourseForm(ModelForm):\n\n class Meta:\n model = Course\n fields = ['course_name']\n\n\n# Uses the Task model so the entered fields can be registered to the Task table\nclass TaskForm(ModelForm):\n\n # Displays only the courses registered by the logged in user\n def __init__(self, user, *args, **kwargs):\n super(TaskForm, self).__init__(*args, **kwargs)\n self.fields['course'].queryset = Course.objects.filter(user=user)\n\n class Meta:\n model = Task\n fields = ['title', 'type', 'date_assigned',\n 'date_due', 'course', 'description']\n # Date input widgets used for 'date assigned' and 'date due'\n widgets = {\n 'date_assigned': DateInput(),\n 'date_due': DateInput(),\n }\n", "repo_name": "karsteneugene/Django_Planner", "sub_path": "Django Planner/planner/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 1066, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.forms.DateInput", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 7, "usage_type": "name"}, {"api_name": "django.forms.ModelForm", "line_number": 12, "usage_type": "name"}, {"api_name": "models.Course", "line_number": 15, "usage_type": "name"}, {"api_name": "django.forms.ModelForm", "line_number": 20, "usage_type": "name"}, {"api_name": "models.Course.objects.filter", "line_number": 25, "usage_type": "call"}, {"api_name": "models.Course.objects", "line_number": 25, "usage_type": "attribute"}, {"api_name": "models.Course", "line_number": 25, "usage_type": "name"}, {"api_name": "models.Task", "line_number": 28, "usage_type": "name"}]} +{"seq_id": "1168571491", "text": "\"\"\"Countdown Calendar\n\nHacks and Tweaks\nsort it!\n sort by the date list.sort(key=lambda x: x[1]\n lambda function is a small anonymous function\n lambda arguments: expression\n x = lambda a : a + 10\n print(x(5)) _> OUTPUT 15\nrestyle the text\n make it look pretty\nset reminders\n\n\"\"\"\n\nfrom tkinter import Tk, Canvas\nfrom datetime import date,datetime\n\n\"\"\"make sure students use the proper format for %d/%m/%y' there can be no spaces and year must be 2 digits not 4\"\"\"\ndef get_events():\n list_events = []\n with open('events.txt') as file: #opens text file\n for line in file: #runs loop for each line in the text file\n line = line.rstrip('\\n') #you must remove \\n or else line will look like this ['Halloween','31/10/22\\n']\n current_event =line.split(',') #turn string line into an array with two string items\n event_date = datetime.strptime(current_event[1],'%d/%m/%y').date() #(string content, format)\n # print(current_event[1])\n current_event[1]=event_date #second item in list is now an actual date (not a string anymore)\n print(current_event[1])\n list_events.append(current_event) #this is will add the formated date of event to our list\n return list_events #returns a 2d list [['Halloween,date],[christmas, date],...]\n\ndef days_between_dates(date1,date2): #function that counts the number of days between two dates\n time_between = str(date1-date2) #variable stores difference of dates as a string\n #if a Hallowen is 27 days away, the string in time_between -> '27 days, 0:00:00 h:m:s all we need is the 27\n number_of_days = time_between.split(' ')\n return number_of_days[0]\n\n\n\nroot = Tk() #Tkinter window\nc = Canvas(root,width=800,height=800, bg='green')\nc.pack() #Tkinter window\nc.create_text(100,50, anchor='w', fill='pink', font='Courier 36 bold underline', text='Ms.T\\'s Calendar')\n\"\"\" \nThis line adds text onto the c canvas. The text starts at x=100 , y=50. \nThe starting coordinate is at the left (west) of the text \nnow we want to loop through every special event in our txt list and calculate how many days away we are\n\"\"\"\nevents = get_events()\ntoday = date.today()\n\nevents.sort(key=lambda x: x[1]) #use the second item in the list (date) to sort function\n\nvertical_space = 100 #moves the y coordinate so eevery date is on its own line\nfor event in events:\n event_name = event[0]\n days_until = days_between_dates(event[1],today)\n\n if int(days_until) <= 7:\n text_color = 'red'\n else:\n text_color = 'black'\n\n display = 'It is %s days until %s' % (days_until, event_name)\n c.create_text(100,vertical_space,anchor='w',fill=text_color, font='Arial 28 bold', text=display)\n vertical_space +=30\n\nroot.mainloop()\n\n\n\n\n\n\n", "repo_name": "thturin/countdown_Calendar", "sub_path": "countdown_calendar_update.py", "file_name": "countdown_calendar_update.py", "file_ext": "py", "file_size_in_byte": 2776, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "datetime.datetime.strptime", "line_number": 26, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 26, "usage_type": "name"}, {"api_name": "tkinter.Tk", "line_number": 41, "usage_type": "call"}, {"api_name": "tkinter.Canvas", "line_number": 42, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 51, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 51, "usage_type": "name"}]} +{"seq_id": "8265130339", "text": "from django.urls import path\n\nfrom rest_framework.authtoken.views import obtain_auth_token\n\nfrom .views import AddEmployeeAPI, CreateProfileAPI, ProfileAPI, ListOfPayrollsAPI, Logout, ListOfProfilesAPI, \\\n PayrollsAPI\n\nurlpatterns = [\n path(\"login/\", obtain_auth_token),\n path(\"add_employee/\", AddEmployeeAPI.as_view()),\n path(\"create_profile//\", CreateProfileAPI.as_view(), name=\"create_profile\"),\n path(\"profile/\", ProfileAPI.as_view()),\n path(\"list_of_profiles/\", ListOfProfilesAPI.as_view()),\n path(\"salaries/\", PayrollsAPI.as_view()),\n path(\"list_of_salaries/\", ListOfPayrollsAPI.as_view()),\n path(\"logout/\", Logout.as_view())\n]\n", "repo_name": "hmpsl99/hr_solution", "sub_path": "hr_solution_back/Hr/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 672, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "rest_framework.authtoken.views.obtain_auth_token", "line_number": 9, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "views.AddEmployeeAPI.as_view", "line_number": 10, "usage_type": "call"}, {"api_name": "views.AddEmployeeAPI", "line_number": 10, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "views.CreateProfileAPI.as_view", "line_number": 11, "usage_type": "call"}, {"api_name": "views.CreateProfileAPI", "line_number": 11, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "views.ProfileAPI.as_view", "line_number": 12, "usage_type": "call"}, {"api_name": "views.ProfileAPI", "line_number": 12, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "views.ListOfProfilesAPI.as_view", "line_number": 13, "usage_type": "call"}, {"api_name": "views.ListOfProfilesAPI", "line_number": 13, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 14, "usage_type": "call"}, {"api_name": "views.PayrollsAPI.as_view", "line_number": 14, "usage_type": "call"}, {"api_name": "views.PayrollsAPI", "line_number": 14, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "views.ListOfPayrollsAPI.as_view", "line_number": 15, "usage_type": "call"}, {"api_name": "views.ListOfPayrollsAPI", "line_number": 15, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 16, "usage_type": "call"}, {"api_name": "views.Logout.as_view", "line_number": 16, "usage_type": "call"}, {"api_name": "views.Logout", "line_number": 16, "usage_type": "name"}]} +{"seq_id": "22241722053", "text": "import warnings\n\n# Dependency imports\nimport numpy as np\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.internal import broadcast_util as bu\nfrom tensorflow_probability.python.internal import distribution_util as dist_util\nfrom tensorflow_probability.python.internal import dtype_util\nfrom tensorflow_probability.python.internal import prefer_static as ps\nfrom tensorflow_probability.python.internal import tensorshape_util\nfrom tensorflow_probability.python.math.gradient import value_and_gradient as tfp_math_value_and_gradients\nfrom tensorflow.python.util import deprecation # pylint: disable=g-direct-tensorflow-import\n\n\n__all__ = [\n 'choose',\n 'choose_from',\n 'enable_store_parameters_in_results',\n 'index_remapping_gather',\n 'is_list_like',\n 'is_namedtuple_like',\n 'make_name',\n 'maybe_call_fn_and_grads',\n 'prepare_state_parts',\n 'PrettyNamedTupleMixin',\n 'safe_sum',\n 'SEED_CTOR_ARG_DEPRECATION_MSG',\n 'set_doc',\n 'strip_seeds',\n 'warn_if_parameters_are_not_simple_tensors',\n]\n\n\nJAX_MODE = False\n\nSEED_CTOR_ARG_DEPRECATION_MSG = (\n 'Seeding `tfp.mcmc.TransitionKernel` instances by constructor argument is '\n 'deprecated. Use the `seed` argument to `tfp.mcmc.sample_chain` or '\n 'directly on `one_step`. The legacy behavior is still supported and should '\n 'be through 2020-09-20.')\n\n\nclass PrettyNamedTupleMixin(object):\n \"\"\"Mixin adding a nicer `__repr__` for `namedtuple`s.\"\"\"\n __slots__ = ()\n\n def __repr__(self):\n return '{}(\\n{}\\n)'.format(\n type(self).__name__,\n ',\\n'.join(' {}={}'.format(k, repr(v).replace('\\n', '\\n '))\n for (k, v) in self._asdict().items()))\n\n\ndef prepare_state_parts(state_or_state_part, dtype=None, name=None):\n \"\"\"Calls c2t on each element or the entirety if not iterable; returns list.\"\"\"\n # Don't use tf.name_scope since this function has ct2-like semantics.\n is_multipart = is_list_like(state_or_state_part)\n state_parts = state_or_state_part if is_multipart else [state_or_state_part]\n state_parts = [tf.convert_to_tensor(x, dtype=dtype, name=name)\n for x in state_parts]\n return state_parts, is_multipart\n\n\ndef is_list_like(x):\n \"\"\"Helper which returns `True` if input is `list`-like.\"\"\"\n return isinstance(x, (tuple, list))\n\n\ndef is_namedtuple_like(x):\n \"\"\"Helper which returns `True` if input is `collections.namedtuple`-like.\"\"\"\n try:\n for fn in x._fields:\n _ = getattr(x, fn)\n return True\n except AttributeError:\n return False\n\n\ndef make_name(super_name, default_super_name, sub_name):\n \"\"\"Helper which makes a `str` name; useful for tf.name_scope.\"\"\"\n name = super_name if super_name is not None else default_super_name\n if sub_name is not None:\n name += '_' + sub_name\n return name\n\n\ndef _choose_base_case(is_accepted,\n proposed,\n current,\n name=None,\n addr=None,):\n \"\"\"Helper to `choose` which expand_dims `is_accepted` and applies tf.where.\"\"\"\n def _where(proposed, current):\n \"\"\"Wraps `tf.where`.\"\"\"\n if proposed is current:\n return proposed\n\n # Handle CompositeTensor types at the leafmost `addr`.\n flat_p = tf.nest.flatten(proposed, expand_composites=True)\n flat_c = tf.nest.flatten(current, expand_composites=True)\n\n res = []\n for p, c in zip(flat_p, flat_c):\n # Preserve the name from `current` so names can propagate from\n # `bootstrap_results`.\n name = getattr(c, 'name', None)\n if name is not None:\n name = name.rpartition('/')[2].rsplit(':', 1)[0]\n # Since this is an internal utility it is ok to assume\n # tf.shape(proposed) == tf.shape(current).\n res.append(\n tf.where(bu.left_justified_expand_dims_like(is_accepted, p), p, c,\n name=name))\n return tf.nest.pack_sequence_as(current, res, expand_composites=True)\n\n with tf.name_scope(name or 'choose'):\n if not is_list_like(proposed):\n return _where(proposed, current)\n return tf.nest.pack_sequence_as(\n current,\n [(_choose_recursive(is_accepted, p, c, name=name, addr=f'{addr}[i]')\n if is_namedtuple_like(p) else\n _where(p, c)) for i, (p, c) in enumerate(zip(proposed, current))])\n\n\ndef _choose_recursive(is_accepted, proposed, current, name=None, addr=''):\n \"\"\"Recursion helper which also reports the address of any failures.\"\"\"\n with tf.name_scope(name or 'choose'):\n if not is_namedtuple_like(proposed):\n return _choose_base_case(is_accepted, proposed, current, name=name,\n addr=addr)\n if not isinstance(proposed, type(current)):\n raise TypeError(\n f'Type of `proposed` ({type(proposed).__name__}) must be identical '\n f'to type of `current` ({type(current).__name__}). (At \"{addr}\".)')\n items = {}\n for fn in proposed._fields:\n items[fn] = _choose_recursive(is_accepted,\n getattr(proposed, fn),\n getattr(current, fn),\n name=name,\n addr=f'{addr}/{fn}')\n return type(proposed)(**items)\n\n\ndef choose(is_accepted, proposed, current, name=None):\n \"\"\"Helper which expand_dims `is_accepted` then applies tf.where.\"\"\"\n return _choose_recursive(is_accepted, proposed, current, name=name)\n\n\ndef _nest_choose(is_accepted, proposed, current):\n \"\"\"Like `choose` but not limited to list, tuple, namedtuple.\"\"\"\n result_parts = choose(is_accepted,\n tf.nest.flatten(proposed, expand_composites=True),\n tf.nest.flatten(current, expand_composites=True))\n return tf.nest.pack_sequence_as(\n proposed, result_parts, expand_composites=True)\n\n\ndef choose_from(n, options):\n \"\"\"Helper to select the n-th option from a list of options.\n\n This is useful when `n` is not a concrete value. Also note that\n the value of `n` will be clipped to the edges of the interval\n `[0, len(options) - 1]`.\n\n Args:\n n: Scalar `int` `Tensor` option.\n options: List of options to choose from. All the options should have the\n same nested structure.\n\n Returns:\n The n-th option among `options`.\n \"\"\"\n if len(options) == 1:\n return options[0]\n m = len(options) // 2\n return _nest_choose(n < m, choose_from(n, options[:m]),\n choose_from(n - m, options[m:]))\n\n\ndef strip_seeds(obj):\n if not is_namedtuple_like(obj):\n return obj\n return type(obj)(**{fn: strip_seeds(fv) if fn != 'seed' else []\n for fn, fv in obj._asdict().items()})\n\n\ndef safe_sum(x, alt_value=-np.inf, name=None):\n \"\"\"Elementwise adds list members, replacing non-finite results with alt_value.\n\n Typically the `alt_value` is chosen so the `MetropolisHastings`\n `TransitionKernel` always rejects the proposal.\n\n Args:\n x: Python `list` of `Tensors` to elementwise add.\n alt_value: Python scalar used to replace any elementwise sums which would\n otherwise be non-finite.\n name: Python `str` name prefixed to Ops created by this function.\n Default value: `None` (i.e., \"safe_sum\").\n\n Returns:\n safe_sum: `Tensor` representing the elementwise sum of list of `Tensor`s\n `x` or `alt_value` where sums are non-finite.\n\n Raises:\n TypeError: if `x` is not list-like.\n ValueError: if `x` is empty.\n \"\"\"\n with tf.name_scope(name or 'safe_sum'):\n if not is_list_like(x):\n raise TypeError('Expected list input.')\n if not x:\n raise ValueError('Input should not be empty.')\n in_shape = x[0].shape\n x = tf.add_n(x)\n x = tf.where(tf.math.is_finite(x), x, tf.constant(alt_value, dtype=x.dtype))\n tensorshape_util.set_shape(x, in_shape)\n return x\n\n\ndef set_doc(value):\n \"\"\"Decorator to programmatically set a function docstring.\"\"\"\n def _doc(func):\n func.__doc__ = value\n return func\n return _doc\n\n\ndef _value_and_gradients(fn, fn_arg_list, result=None, grads=None, name=None):\n \"\"\"Helper to `maybe_call_fn_and_grads`.\"\"\"\n with tf.name_scope(name or 'value_and_gradients'):\n\n def _convert_to_tensor(x, name):\n ctt = lambda x_: None if x_ is None else tf.convert_to_tensor( # pylint: disable=g-long-lambda\n x_, name=name)\n return [ctt(x_) for x_ in x] if is_list_like(x) else ctt(x)\n\n fn_arg_list = (list(fn_arg_list) if is_list_like(fn_arg_list)\n else [fn_arg_list])\n fn_arg_list = _convert_to_tensor(fn_arg_list, 'fn_arg')\n\n if result is None and grads is None and (JAX_MODE or\n not tf.executing_eagerly()):\n # Currently, computing gradient is not working well with caching in\n # tensorflow eager mode (see below), so we will handle that case\n # separately.\n return tfp_math_value_and_gradients(fn, fn_arg_list)\n\n if result is None:\n result = fn(*fn_arg_list)\n if grads is None:\n assert tf.executing_eagerly()\n # Ensure we disable bijector cacheing in eager mode.\n # TODO(b/72831017): Remove this once bijector cacheing is fixed for\n # eager mode.\n fn_arg_list = [0 + x for x in fn_arg_list]\n\n result = _convert_to_tensor(result, 'fn_result')\n\n if grads is not None:\n grads = _convert_to_tensor(grads, 'fn_grad')\n return result, grads\n\n _, grads = tfp_math_value_and_gradients(fn, fn_arg_list)\n\n return result, grads\n\n\ndef maybe_call_fn_and_grads(fn,\n fn_arg_list,\n result=None,\n grads=None,\n check_non_none_grads=True,\n name=None):\n \"\"\"Calls `fn` and computes the gradient of the result wrt `args_list`.\"\"\"\n with tf.name_scope(name or 'maybe_call_fn_and_grads'):\n fn_arg_list = (list(fn_arg_list) if is_list_like(fn_arg_list)\n else [fn_arg_list])\n result, grads = _value_and_gradients(fn, fn_arg_list, result, grads)\n if not all(dtype_util.is_floating(r.dtype)\n for r in (result if is_list_like(result) else [result])): # pylint: disable=superfluous-parens\n raise TypeError('Function result must be a `Tensor` with `float` '\n '`dtype`.')\n if len(fn_arg_list) != len(grads):\n raise ValueError('Function args must be in one-to-one correspondence '\n 'with grads.')\n if check_non_none_grads and any(g is None for g in grads):\n raise ValueError('Encountered `None` gradient.\\n'\n ' fn_arg_list: {}\\n'\n ' grads: {}'.format(fn_arg_list, grads))\n return result, grads\n\n\ndef enable_store_parameters_in_results(kernel):\n \"\"\"Enables the `store_parameters_in_results` parameter in a chain of kernels.\n\n This is a temporary utility for use during the transition period of the\n parameter storage methods.\n\n Args:\n kernel: A TransitionKernel.\n\n Returns:\n kernel: The same kernel, but recreated with `store_parameters_in_results`\n recursively set to `True` in its parameters and its inner kernels (as\n appropriate).\n \"\"\"\n kernel_stack = []\n while hasattr(kernel, 'parameters') and 'inner_kernel' in kernel.parameters:\n kernel_stack.append(kernel)\n kernel = kernel.parameters['inner_kernel']\n\n def _recreate_kernel(kernel, parameters):\n new_parameters = kernel.parameters.copy()\n new_parameters.update(parameters)\n if 'store_parameters_in_results' in new_parameters:\n new_parameters['store_parameters_in_results'] = True\n with deprecation.silence():\n return type(kernel)(**new_parameters)\n\n if hasattr(kernel, 'parameters'):\n kernel = _recreate_kernel(kernel, {})\n\n for outer_kernel in reversed(kernel_stack):\n outer_kernel = _recreate_kernel(outer_kernel, {'inner_kernel': kernel})\n kernel = outer_kernel\n\n return kernel\n\n\ndef _is_tensor_like(param):\n if is_list_like(param):\n return all([_is_tensor_like(p) for p in param])\n if isinstance(param, tf.Tensor):\n return True\n elif isinstance(param, tf.Variable):\n return False\n else:\n return np.array(param).dtype != np.object_\n\n\ndef warn_if_parameters_are_not_simple_tensors(params_dict):\n for param_name, param in params_dict.items():\n if not _is_tensor_like(param):\n warnings.warn(\n '`{}` is not a `tf.Tensor`, Python number, or Numpy array. If this '\n 'parameter is mutable (e.g., a `tf.Variable`), then the '\n 'behavior implied by `store_parameters_in_results` will silently '\n 'change on 2019-08-01. Please consult the docstring for '\n '`store_parameters_in_results` details and use '\n '`store_parameters_in_results=True` to silence this warning.'.format(\n param_name))\n\n\ndef index_remapping_gather(params,\n indices,\n axis=0,\n indices_axis=0,\n name='index_remapping_gather'):\n \"\"\"Gather values from `axis` of `params` using `indices_axis` of `indices`.\n\n The shape of `indices` must broadcast to that of `params` when\n their `indices_axis` and `axis` (respectively) are aligned:\n\n ```python\n # params.shape:\n [p[0], ..., ..., p[axis], ..., ..., p[rank(params)] - 1])\n # indices.shape:\n [i[0], ..., i[indices_axis], ..., i[rank(indices)] - 1])\n ```\n\n In particular, `params` must have at least as many\n leading dimensions as `indices` (`axis >= indices_axis`), and at least as many\n trailing dimensions (`rank(params) - axis >= rank(indices) - indices_axis`).\n\n The `result` has the same shape as `params`, except that the dimension\n of size `p[axis]` is replaced by one of size `i[indices_axis]`:\n\n ```python\n # result.shape:\n [p[0], ..., ..., i[indices_axis], ..., ..., p[rank(params) - 1]]\n ```\n\n In the case where `rank(params) == 5`, `rank(indices) == 3`, `axis = 2`, and\n `indices_axis = 1`, the result is given by\n\n ```python\n # alignment is: v axis\n # params.shape == [p[0], p[1], p[2], p[3], p[4]]\n # indices.shape == [i[0], i[1], i[2]]\n # ^ indices_axis\n result[i, j, k, l, m] = params[i, j, indices[j, k, l], l, m]\n ```\n\n Args:\n params: `N-D` `Tensor` (`N > 0`) from which to gather values.\n Number of dimensions must be known statically.\n indices: `Tensor` with values in `{0, ..., params.shape[axis] - 1}`, whose\n shape broadcasts to that of `params` as described above.\n axis: Python `int` axis of `params` from which to gather.\n indices_axis: Python `int` axis of `indices` to align with the `axis`\n over which `params` is gathered.\n name: String name for scoping created ops.\n\n Returns:\n `Tensor` composed of elements of `params`.\n\n Raises:\n ValueError: If shape/rank requirements are not met.\n \"\"\"\n with tf.name_scope(name):\n params = tf.convert_to_tensor(params, name='params')\n indices = tf.convert_to_tensor(indices, name='indices')\n\n params_ndims = tensorshape_util.rank(params.shape)\n indices_ndims = tensorshape_util.rank(indices.shape)\n # `axis` dtype must match ndims, which are 64-bit Python ints.\n axis = tf.get_static_value(ps.convert_to_shape_tensor(axis, dtype=tf.int64))\n indices_axis = tf.get_static_value(\n ps.convert_to_shape_tensor(indices_axis, dtype=tf.int64))\n\n if params_ndims is None:\n raise ValueError(\n 'Rank of `params`, must be known statically. This is due to '\n 'tf.gather not accepting a `Tensor` for `batch_dims`.')\n\n if axis is None:\n raise ValueError(\n '`axis` must be known statically. This is due to '\n 'tf.gather not accepting a `Tensor` for `batch_dims`.')\n\n if indices_axis is None:\n raise ValueError(\n '`indices_axis` must be known statically. This is due to '\n 'tf.gather not accepting a `Tensor` for `batch_dims`.')\n\n if indices_axis > axis:\n raise ValueError(\n '`indices_axis` should be <= `axis`, but was {} > {}'.format(\n indices_axis, axis))\n\n if params_ndims < 1:\n raise ValueError(\n 'Rank of params should be `> 0`, but was {}'.format(params_ndims))\n\n if indices_ndims is not None and indices_ndims < 1:\n raise ValueError(\n 'Rank of indices should be `> 0`, but was {}'.format(indices_ndims))\n\n if (indices_ndims is not None and\n (indices_ndims - indices_axis > params_ndims - axis)):\n raise ValueError(\n '`rank(params) - axis` ({} - {}) must be >= `rank(indices) - '\n 'indices_axis` ({} - {}), but was not.'.format(\n params_ndims, axis, indices_ndims, indices_axis))\n\n # `tf.gather` requires the axis to be the rightmost batch ndim. So, we\n # transpose `indices_axis` to be the rightmost dimension of `indices`...\n transposed_indices = dist_util.move_dimension(indices,\n source_idx=indices_axis,\n dest_idx=-1)\n\n # ... and `axis` to be the corresponding (aligned as in the docstring)\n # dimension of `params`.\n broadcast_indices_ndims = indices_ndims + (axis - indices_axis)\n transposed_params = dist_util.move_dimension(\n params,\n source_idx=axis,\n dest_idx=broadcast_indices_ndims - 1)\n\n # Next we broadcast `indices` so that its shape has the same prefix as\n # `params.shape`.\n transposed_params_shape = ps.shape(transposed_params)\n result_shape = ps.concat([\n transposed_params_shape[:broadcast_indices_ndims - 1],\n ps.shape(indices)[indices_axis:indices_axis + 1],\n transposed_params_shape[broadcast_indices_ndims:]], axis=0)\n broadcast_indices = ps.broadcast_to(\n transposed_indices,\n result_shape[:broadcast_indices_ndims])\n\n result_t = tf.gather(transposed_params,\n broadcast_indices,\n batch_dims=broadcast_indices_ndims - 1,\n axis=broadcast_indices_ndims - 1)\n return dist_util.move_dimension(result_t,\n source_idx=broadcast_indices_ndims - 1,\n dest_idx=axis)\n", "repo_name": "tensorflow/probability", "sub_path": "tensorflow_probability/python/mcmc/internal/util.py", "file_name": "util.py", "file_ext": "py", "file_size_in_byte": 18283, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3997, "dataset": "github-code", "pt": "24", "api": [{"api_name": "tensorflow.compat.v2.convert_to_tensor", "line_number": 60, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 60, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.nest.flatten", "line_number": 100, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.nest", "line_number": 100, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 100, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.nest.flatten", "line_number": 101, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.nest", "line_number": 101, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 101, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.where", "line_number": 113, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 113, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.broadcast_util.left_justified_expand_dims_like", "line_number": 113, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.broadcast_util", "line_number": 113, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.nest.pack_sequence_as", "line_number": 115, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.nest", "line_number": 115, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 115, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.name_scope", "line_number": 117, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 117, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.nest.pack_sequence_as", "line_number": 120, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.nest", "line_number": 120, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 120, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.name_scope", "line_number": 129, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 129, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.nest.flatten", "line_number": 155, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.nest", "line_number": 155, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 155, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.nest.flatten", "line_number": 156, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.nest", "line_number": 156, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 156, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.nest.pack_sequence_as", "line_number": 157, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.nest", "line_number": 157, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 157, "usage_type": "name"}, {"api_name": "numpy.inf", "line_number": 190, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2.name_scope", "line_number": 211, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 211, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.add_n", "line_number": 217, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 217, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.where", "line_number": 218, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 218, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.is_finite", "line_number": 218, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 218, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2.constant", "line_number": 218, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.tensorshape_util.set_shape", "line_number": 219, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.tensorshape_util", "line_number": 219, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.name_scope", "line_number": 233, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 233, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.convert_to_tensor", "line_number": 236, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 236, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.executing_eagerly", "line_number": 245, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 245, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.math.gradient.value_and_gradient", "line_number": 249, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.executing_eagerly", "line_number": 254, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 254, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.math.gradient.value_and_gradient", "line_number": 266, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.name_scope", "line_number": 278, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 278, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.dtype_util.is_floating", "line_number": 282, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.dtype_util", "line_number": 282, "usage_type": "name"}, {"api_name": "tensorflow.python.util.deprecation.silence", "line_number": 320, "usage_type": "call"}, {"api_name": "tensorflow.python.util.deprecation", "line_number": 320, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.Tensor", "line_number": 336, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 336, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.Variable", "line_number": 338, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 338, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 341, "usage_type": "call"}, {"api_name": "numpy.object_", "line_number": 341, "usage_type": "attribute"}, {"api_name": "warnings.warn", "line_number": 347, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.name_scope", "line_number": 413, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 413, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.convert_to_tensor", "line_number": 414, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 414, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.convert_to_tensor", "line_number": 415, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 415, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.tensorshape_util.rank", "line_number": 417, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.tensorshape_util", "line_number": 417, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.tensorshape_util.rank", "line_number": 418, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.tensorshape_util", "line_number": 418, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.get_static_value", "line_number": 420, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 420, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.prefer_static.convert_to_shape_tensor", "line_number": 420, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.prefer_static", "line_number": 420, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.int64", "line_number": 420, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2.get_static_value", "line_number": 421, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 421, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.prefer_static.convert_to_shape_tensor", "line_number": 422, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.prefer_static", "line_number": 422, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.int64", "line_number": 422, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 422, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.distribution_util.move_dimension", "line_number": 461, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.distribution_util", "line_number": 461, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.distribution_util.move_dimension", "line_number": 468, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.distribution_util", "line_number": 468, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.prefer_static.shape", "line_number": 475, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.prefer_static", "line_number": 475, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.prefer_static.concat", "line_number": 476, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.prefer_static", "line_number": 476, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.prefer_static.shape", "line_number": 478, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.prefer_static", "line_number": 478, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.prefer_static.broadcast_to", "line_number": 480, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.prefer_static", "line_number": 480, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.gather", "line_number": 484, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 484, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.distribution_util.move_dimension", "line_number": 488, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.distribution_util", "line_number": 488, "usage_type": "name"}]} +{"seq_id": "6134198425", "text": "#using CNN with edge detection + contours\n\n\nimport tensorflow as tf\nimport numpy as np\nimport cv2\nimport time\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Sequential\nfrom b_serial import sendColor\nimport json\nimport pathlib\nprint(tf.__version__)\n# colors 0 red, 1 green, 2, yellow, 3, emergency\nfrom keras.models import load_model\nmodel = load_model(r'models/vehicles_light_new.h5')\nSerialDump=dict()\nimport threading\n\nminArea=10000\nfilepath=r\"D:\\Python\\SmartVehicleGuidance\\testImages\\test_new\\test1.jpg\"\nimg_height = 120\nimg_width = 180\nmodel.summary()\n\ndef nothing(value):\n pass\n \nclass_names = ['car', 'otherStuff', 'truck']\n\nlane1= [0 , 250]\n\nlaneColors=[1,1,1]\ncolorsChanged=False\nready=True\nimg=cv2.imread(filepath)\n\ndef colorUpdate(SerialDump):\n y=json.dumps(SerialDump)\n sendColor(y)\n time.sleep(1)\n colorsChanged=False\n ready=True\n\n#Uncomment to use Live Video Feed\ncap= cv2.VideoCapture(1)\nOnce=True\nt1 = threading.Thread(target=colorUpdate, args=(SerialDump,))\niterations_Dilate=0\niterations_Erode=0\n\n\n\ncv2.namedWindow(\"Settings\", cv2.WINDOW_AUTOSIZE)\ncv2.createTrackbar('MinArea', \"Settings\", 5, 100, nothing)\ncv2.createTrackbar('Dilation', \"Settings\", 0, 5, nothing)\ncv2.createTrackbar('Erosion', \"Settings\", 0, 5, nothing)\ncv2.createTrackbar('Brightness', \"Settings\", 0, 200, nothing)\ncv2.createTrackbar('Blur', \"Settings\", 1, 9, nothing)\ncv2.createTrackbar('TopLine', \"Settings\", 0, 50, nothing)\ncv2.createTrackbar('FirstLane', \"Settings\", 100, 300, nothing)\n\n\nprevColors=[0,0,0]\nwhile Once:\n start=time.time()\n #Uncomment to use a single file\n #img=cv2.imread(filepath)\n\n #Uncomment to use live video Feed\n _,img=cap.read()\n \n img= cv2.resize(img, (600,600),interpolation=cv2.INTER_AREA)\n gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n matrix = np.ones(img.shape, dtype = \"uint8\") * cv2.getTrackbarPos('Brightness','Settings')\n blurIndex=cv2.getTrackbarPos('Blur','Settings')\n if blurIndex>0:\n img = cv2.blur(img,(blurIndex,blurIndex))\n l1Endpoint=cv2.getTrackbarPos('FirstLane','Settings')\n lane1[1]=l1Endpoint \n y=cv2.getTrackbarPos('TopLine','Settings')\n img= cv2.line(img, (l1Endpoint,500),(l1Endpoint,y), (255,255,255), 5)\n img= cv2.line(img, (0,y),(500,y), (255,255,255), 5)\n kernel = np.array([[-1,-1,-1], \n [-1,9,-1], \n [-1,-1,-1]])\n #img = cv2.filter2D(img, -1, kernel)\n \n img = cv2.add(img, matrix)\n canny= cv2.Canny(gray, 50, 100)\n kernel = np.ones((3,3), np.uint8)\n kernel2 = np.ones((3,3), np.uint8)\n \n \n dilated = cv2.dilate(canny, kernel2, iterations=cv2.getTrackbarPos('Dilation','Settings'))\n eroded = cv2.erode(dilated, kernel, iterations=cv2.getTrackbarPos('Erosion','Settings'))\n eroded[y+1]=0\n eroded[y]=0\n eroded[y-1]=0\n \n cv2.imshow(\"binary\", eroded)\n contours, hierarchies= cv2.findContours(eroded, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n \n for i,contour in enumerate(contours):\n if (hierarchies[0][i][3])<0:\n (x,y,w,h) = cv2.boundingRect(contour)\n if w*h > (cv2.getTrackbarPos('MinArea','Settings')*1000):\n d_object=img[y:y+h,x:x+w]\n d_object=cv2.resize(d_object, (img_width,img_height),interpolation=cv2.INTER_AREA)\n d_object=cv2.cvtColor(d_object, cv2.COLOR_BGR2RGB)\n img_array = tf.expand_dims(d_object, 0)\n predictions = model.predict(img_array)\n score = tf.nn.softmax(predictions[0])\n cv2.rectangle(img, (x,y), (x+w,y+h), (255, 0, 0), 2)\n objectDetected= class_names[np.argmax(score)]\n \n img = cv2.putText(img, \"{} {:.2f}\".format(class_names[np.argmax(score)], 100 * np.max(score)), (x,y+15), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255),2, cv2.LINE_AA)\n if objectDetected==\"truck\":\n if ((x+w)/2)>lane1[0] and ((x+w)/2)lane1[0] and ((x+w)/2) threshold else 0\n return avg_loss, score\n\n\n def compute_L2_loss(self, predict_points, label_points, threshold = 0.):\n # label = rect.rectify(label_points)\n label = label_points\n predicted_label = rect.rectify(predict_points)\n\n diff = label - predicted_label\n \n square_diff = diff**2\n dists = square_diff.sum(axis=1, dtype=np.int32)\n dists = np.sqrt(dists)\n avg_loss = np.sum(dists)/4\n\n score = 1 if avg_loss > threshold else 0\n return avg_loss, score\n\n def compute_overlap(self, predict_points, label_points, threshold = 0.):\n # label_points = rect.rectify(label_points)\n # predict_points = rect.rectify(predict_points)\n\n predicted_polygon = Polygon(predict_points)\n labeled_polygon = Polygon(label_points)\n # print(predicted_polygon)\n # print(labeled_polygon)\n intersection = predicted_polygon.intersection(labeled_polygon)\n union = predicted_polygon.union(labeled_polygon)\n \n overlap = intersection.area / union.area\n\n score = 1 if overlap > threshold else 0\n return overlap, score\n \n\nif __name__ == '__main__':\n fake_labeled_points = np.array([[0, 0], [0, 2], [2, 0], [2, 2]])\n fake_predicted_points = np.array([[1, 1], [1, 3], [3, 1], [3, 3]])\n\n evaluator = Evaluator(sys.argv[1])\n\n print( 'L1_loss = {}'.format(evaluator.error_func['L1'](fake_labeled_points,\n fake_predicted_points)) )\n\n print( 'L2_loss = {}'.format(evaluator.error_func['L2'](fake_labeled_points,\n fake_predicted_points)) )\n\n print( 'overlap = {}'.format(evaluator.error_func['overlap'](fake_labeled_points,\n fake_predicted_points)) )\n\n\n", "repo_name": "ZhengPhoenix/ObjectDetect", "sub_path": "Evaluation/Evaluator.py", "file_name": "Evaluator.py", "file_ext": "py", "file_size_in_byte": 3209, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "os.path.dirname", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 10, "usage_type": "call"}, {"api_name": "sys.path.append", "line_number": 11, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 29, "usage_type": "call"}, {"api_name": "rect.rectify", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 40, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 41, "usage_type": "call"}, {"api_name": "rect.rectify", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 55, "usage_type": "attribute"}, {"api_name": "numpy.sqrt", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 57, "usage_type": "call"}, {"api_name": "shapely.geometry.Polygon", "line_number": 66, "usage_type": "call"}, {"api_name": "shapely.geometry.Polygon", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 81, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 83, "usage_type": "attribute"}]} +{"seq_id": "22239995073", "text": "import itertools\n# Dependency imports\nfrom absl.testing import parameterized\nimport numpy as np\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.bijectors import ascending as tfb\nfrom tensorflow_probability.python.distributions import categorical\nfrom tensorflow_probability.python.distributions import kullback_leibler\nfrom tensorflow_probability.python.distributions import logistic\nfrom tensorflow_probability.python.distributions import ordered_logistic as ol\nfrom tensorflow_probability.python.internal import test_util\n\n\n@test_util.test_all_tf_execution_regimes\nclass OrderedLogisticTest(test_util.TestCase):\n\n def _random_cutpoints(self, shape):\n return self._ordered.forward(self._rng.randn(*shape))\n\n def _random_location(self, shape):\n return self._rng.randn(*shape)\n\n def setUp(self):\n self._ordered = tfb.Ascending()\n self._rng = test_util.test_np_rng()\n super(OrderedLogisticTest, self).setUp()\n\n @parameterized.parameters(\n itertools.product(['cutpoints', 'loc', 'both'], [[], [1], [1, 2, 3]])\n )\n def testBatchShapes(self, test, batch_shape):\n\n if test == 'cutpoints':\n cutpoints = self._random_cutpoints(batch_shape + [2])\n loc = tf.constant(0., dtype=tf.float64)\n elif test == 'loc':\n cutpoints = tf.constant([1., 2.], dtype=tf.float64)\n loc = self._random_location(batch_shape)\n elif test == 'both':\n cutpoints = self._random_cutpoints(batch_shape + [2])\n loc = self._random_location(batch_shape)\n\n dist = ol.OrderedLogistic(cutpoints=cutpoints, loc=loc)\n\n self.assertAllEqual(dist.batch_shape, batch_shape)\n self.assertAllEqual(\n self.evaluate(dist.batch_shape_tensor()), batch_shape)\n\n self.assertAllEqual(dist.event_shape, [])\n self.assertAllEqual(self.evaluate(dist.event_shape_tensor()), [])\n\n categorical_probs = dist.categorical_probs()\n categorical_probs_shape = tf.shape(categorical_probs)\n self.assertAllEqual(\n self.evaluate(categorical_probs_shape), batch_shape + [3])\n\n sample = dist.sample(seed=test_util.test_seed())\n sample_shape = tf.shape(sample)\n self.assertAllEqual(self.evaluate(sample_shape), batch_shape)\n\n prob_sample_shape = tf.shape(dist.prob(sample))\n survival_prob_sample_shape = tf.shape(dist.survival_function(sample))\n self.assertAllEqual(self.evaluate(prob_sample_shape), batch_shape)\n self.assertAllEqual(self.evaluate(survival_prob_sample_shape), batch_shape)\n\n n = [4, 5]\n sample_n = dist.sample(n, seed=test_util.test_seed())\n sample_n_shape = tf.shape(sample_n)\n self.assertAllEqual(self.evaluate(sample_n_shape), n + batch_shape)\n\n prob_sample_n_shape = tf.shape(dist.prob(sample_n))\n survival_prob_sample_n_shape = tf.shape(dist.survival_function(sample_n))\n self.assertAllEqual(self.evaluate(prob_sample_n_shape), n + batch_shape)\n self.assertAllEqual(\n self.evaluate(survival_prob_sample_n_shape), n + batch_shape)\n\n def testProbs(self):\n # survival functions\n # P(Y > 0) = sigmoid(1) = 0.7310586\n # P(Y > 1) = sigmoid(0) = 0.5\n # P(Y > 2) = sigmoid(-1) = 0.26894143\n\n # probs\n # P(Y = 0) = 1. - sigmoid(1) = 0.2689414\n # P(Y = 1) = sigmoid(1) - sigmoid(0) = 0.2310586\n # P(Y = 2) = sigmoid(0) - sigmoid(-1) = 0.23105857\n # P(Y = 3) = sigmoid(-1) = 0.26894143\n expected_probs = [0.2689414, 0.2310586, 0.23105857, 0.26894143]\n expected_survival_probs = 1. - np.cumsum(expected_probs)\n dist = ol.OrderedLogistic(cutpoints=[-1., 0., 1.], loc=0.)\n\n categorical_probs = self.evaluate(dist.categorical_probs())\n self.assertAllClose(expected_probs, categorical_probs, atol=1e-6)\n\n probs = np.flip(self.evaluate(dist.prob([3, 2, 1, 0])))\n self.assertAllClose(expected_probs, probs, atol=1e-6)\n\n survival_probs = self.evaluate(dist.survival_function([0, 1, 2, 3]))\n self.assertAllClose(expected_survival_probs, survival_probs, atol=1e-6)\n\n zero_probs = self.evaluate(dist.prob([-1, 4]))\n self.assertAllClose([0., 0.], zero_probs, atol=1e-6)\n\n out_of_bounds_survival_probs = self.evaluate(\n dist.survival_function([-2, -1, 4, 5]))\n self.assertAllClose(\n [1., 1., 0., 0.], out_of_bounds_survival_probs, atol=1e-6)\n\n def testMode(self):\n # 2 cutpoints i.e. 3 possible outcomes. 3 \"batched\" distributions with the\n # logistic distribution location well within the large cutpoint spacing so\n # mode is obvious\n dist = ol.OrderedLogistic(cutpoints=[-10., 10.], loc=[-20., 0., 20.])\n mode = self.evaluate(dist.mode())\n self.assertAllEqual([0, 1, 2], mode)\n\n def testSample(self):\n # as per `testProbs`\n dist = ol.OrderedLogistic(cutpoints=[-1., 0., 1.], loc=0.)\n samples = self.evaluate(dist.sample(int(1e5), seed=test_util.test_seed()))\n expected_probs = [0.2689414, 0.2310586, 0.23105857, 0.26894143]\n for k, p in enumerate(expected_probs):\n self.assertAllClose(np.mean(samples == k), p, atol=0.01)\n\n def testEntropyAgainstCategoricalDistribution(self):\n cutpoints = self._random_cutpoints([3])\n loc = self._random_location([2])\n dist = ol.OrderedLogistic(cutpoints=cutpoints, loc=loc)\n categorical_dist = categorical.Categorical(dist.categorical_log_probs())\n expected_entropy = self.evaluate(categorical_dist.entropy())\n entropy = self.evaluate(dist.entropy())\n self.assertAllClose(expected_entropy, entropy)\n\n def testEntropyAgainstSampling(self):\n cutpoints = self._random_cutpoints([4])\n loc = self._random_location([])\n dist = ol.OrderedLogistic(cutpoints=cutpoints, loc=loc)\n samples = dist.sample(int(1e5), seed=test_util.test_seed())\n entropy_samples = self.evaluate(-dist.log_prob(samples))\n entropy = self.evaluate(dist.entropy())\n self.assertAllMeansClose(entropy_samples, entropy, axis=0, atol=0.01)\n\n @parameterized.parameters(1, 10, 25)\n def testKLAgainstCategoricalDistribution(self, batch_size):\n cutpoints = self._random_cutpoints([100])\n a_loc = self._random_location([batch_size])\n b_loc = self._random_location([batch_size])\n\n a = ol.OrderedLogistic(cutpoints=cutpoints, loc=a_loc, validate_args=True)\n b = ol.OrderedLogistic(cutpoints=cutpoints, loc=b_loc, validate_args=True)\n\n a_cat = categorical.Categorical(\n logits=a.categorical_log_probs(), validate_args=True)\n b_cat = categorical.Categorical(\n logits=b.categorical_log_probs(), validate_args=True)\n\n kl = self.evaluate(kullback_leibler.kl_divergence(a, b))\n self.assertEqual(kl.shape, (batch_size,))\n\n kl_expected = self.evaluate(kullback_leibler.kl_divergence(a_cat, b_cat))\n self.assertAllClose(kl, kl_expected)\n\n kl_same = self.evaluate(kullback_leibler.kl_divergence(a, a))\n self.assertAllClose(kl_same, np.zeros_like(kl_expected))\n\n def testKLAgainstSampling(self):\n a_cutpoints = self._random_cutpoints([4])\n b_cutpoints = self._random_cutpoints([4])\n loc = self._random_location([])\n\n a = ol.OrderedLogistic(cutpoints=a_cutpoints, loc=loc)\n b = ol.OrderedLogistic(cutpoints=b_cutpoints, loc=loc)\n\n samples = a.sample(int(1e5), seed=test_util.test_seed())\n kl_samples = self.evaluate(a.log_prob(samples) - b.log_prob(samples))\n kl = self.evaluate(kullback_leibler.kl_divergence(a, b))\n\n self.assertAllMeansClose(kl_samples, kl, axis=0, atol=2e-2)\n\n def testLatentLogistic(self):\n loc = self._random_location([2])\n cutpoints = self._random_cutpoints([2])\n latent = logistic.Logistic(loc=loc, scale=1.)\n ordered = ol.OrderedLogistic(cutpoints=cutpoints, loc=loc)\n ordered_cdf = self.evaluate(ordered.cdf([0, 1]))\n latent_cdf = self.evaluate(latent.cdf(cutpoints))\n self.assertAllClose(ordered_cdf, latent_cdf)\n\n def testUnorderedCutpointsFails(self):\n with self.assertRaisesRegexp(\n ValueError, 'Argument `cutpoints` must be non-decreasing.'):\n dist = ol.OrderedLogistic(\n cutpoints=[1., 0.9], loc=0.0, validate_args=True)\n self.evaluate(dist.mode())\n\nif __name__ == '__main__':\n test_util.main()\n", "repo_name": "tensorflow/probability", "sub_path": "tensorflow_probability/python/distributions/ordered_logistic_test.py", "file_name": "ordered_logistic_test.py", "file_ext": "py", "file_size_in_byte": 8003, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3997, "dataset": "github-code", "pt": "24", "api": [{"api_name": "tensorflow_probability.python.internal.test_util.TestCase", "line_number": 16, "usage_type": "attribute"}, {"api_name": "tensorflow_probability.python.internal.test_util", "line_number": 16, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.bijectors.ascending.Ascending", "line_number": 25, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.bijectors.ascending", "line_number": 25, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.test_util.test_np_rng", "line_number": 26, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.test_util", "line_number": 26, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.constant", "line_number": 36, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 36, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.float64", "line_number": 36, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2.constant", "line_number": 38, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 38, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.float64", "line_number": 38, "usage_type": "attribute"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic.OrderedLogistic", "line_number": 44, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic", "line_number": 44, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.shape", "line_number": 54, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 54, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.test_util.test_seed", "line_number": 58, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.test_util", "line_number": 58, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.shape", "line_number": 59, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 59, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.shape", "line_number": 62, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 62, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.shape", "line_number": 63, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 63, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.test_util.test_seed", "line_number": 68, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.test_util", "line_number": 68, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.shape", "line_number": 69, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 69, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.shape", "line_number": 72, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 72, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.shape", "line_number": 73, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 73, "usage_type": "name"}, {"api_name": "absl.testing.parameterized.parameters", "line_number": 29, "usage_type": "call"}, {"api_name": "absl.testing.parameterized", "line_number": 29, "usage_type": "name"}, {"api_name": "itertools.product", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 90, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic.OrderedLogistic", "line_number": 91, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic", "line_number": 91, "usage_type": "name"}, {"api_name": "numpy.flip", "line_number": 96, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic.OrderedLogistic", "line_number": 114, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic", "line_number": 114, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic.OrderedLogistic", "line_number": 120, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic", "line_number": 120, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.test_util.test_seed", "line_number": 121, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.test_util", "line_number": 121, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 124, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic.OrderedLogistic", "line_number": 129, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic", "line_number": 129, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.categorical.Categorical", "line_number": 130, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.categorical", "line_number": 130, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic.OrderedLogistic", "line_number": 138, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic", "line_number": 138, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.test_util.test_seed", "line_number": 139, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.test_util", "line_number": 139, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic.OrderedLogistic", "line_number": 150, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic", "line_number": 150, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic.OrderedLogistic", "line_number": 151, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic", "line_number": 151, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.categorical.Categorical", "line_number": 153, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.categorical", "line_number": 153, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.categorical.Categorical", "line_number": 155, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.categorical", "line_number": 155, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.kullback_leibler.kl_divergence", "line_number": 158, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.kullback_leibler", "line_number": 158, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.kullback_leibler.kl_divergence", "line_number": 161, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.kullback_leibler", "line_number": 161, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.kullback_leibler.kl_divergence", "line_number": 164, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.kullback_leibler", "line_number": 164, "usage_type": "name"}, {"api_name": "numpy.zeros_like", "line_number": 165, "usage_type": "call"}, {"api_name": "absl.testing.parameterized.parameters", "line_number": 144, "usage_type": "call"}, {"api_name": "absl.testing.parameterized", "line_number": 144, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic.OrderedLogistic", "line_number": 172, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic", "line_number": 172, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic.OrderedLogistic", "line_number": 173, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic", "line_number": 173, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.test_util.test_seed", "line_number": 175, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.test_util", "line_number": 175, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.kullback_leibler.kl_divergence", "line_number": 177, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.kullback_leibler", "line_number": 177, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.logistic.Logistic", "line_number": 184, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.logistic", "line_number": 184, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic.OrderedLogistic", "line_number": 185, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic", "line_number": 185, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic.OrderedLogistic", "line_number": 193, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.distributions.ordered_logistic", "line_number": 193, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.test_util.test_all_tf_execution_regimes", "line_number": 15, "usage_type": "attribute"}, {"api_name": "tensorflow_probability.python.internal.test_util", "line_number": 15, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.test_util.main", "line_number": 198, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.test_util", "line_number": 198, "usage_type": "name"}]} +{"seq_id": "26639298985", "text": "import sys\nfrom PyQt5.QtWidgets import QWidget, QProgressBar, QVBoxLayout, QPushButton,QApplication, QLabel\nfrom PyQt5.QtCore import Qt\n\n\n\nclass ProgressWindow(QWidget):\n def __init__(self):\n super().__init__()\n self.setWindowFlag(Qt.FramelessWindowHint)\n self.setWindowModality(Qt.ApplicationModal)\n self.setWindowFlag(Qt.Tool) #hides window from taskbar\n\n layout = QVBoxLayout()\n\n self.label = QLabel(\"Please wait until the computation is completed.\")\n self.label.setStyleSheet('font-size: 24px; height: 24px;')\n layout.addWidget(self.label)\n\n self.label2 = QLabel()\n self.label2.setStyleSheet('font-size: 12px; height: 12px;')\n layout.addWidget(self.label2)\n\n self.progressBar = QProgressBar()\n self.progressBar.setMinimum(0)\n self.progressBar.setValue(0)\n layout.addWidget(self.progressBar)\n\n self.setLayout(layout)\n\n\n def increasebar_by(self, value):\n self.progressBar.setValue(self.progressBar.value()+value)\n if self.progressBar.value() >= self.progressBar.maximum(): self.close()\n\n def updatetext(self, text):\n self.label2.setText(self.label2.text() + '\\n' + text)\n \n def closeself(self):\n self.close()\n \n\n#if __name__ == \"__main__\":\n# app = QApplication(sys.argv)\n# MainWindow = ProgressWindow()\n# MainWindow.show()\n # sys.exit(app.exec_())", "repo_name": "HSPR-Software/HSPR", "sub_path": "src/ui/computation_progressBar.py", "file_name": "computation_progressBar.py", "file_ext": "py", "file_size_in_byte": 1426, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "24", "api": [{"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 7, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt.FramelessWindowHint", "line_number": 10, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 10, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt.ApplicationModal", "line_number": 11, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 11, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt.Tool", "line_number": 12, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 12, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QVBoxLayout", "line_number": 14, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 16, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 20, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QProgressBar", "line_number": 24, "usage_type": "call"}]} +{"seq_id": "30718987960", "text": "import argparse\nimport pickle\n\nimport torch\nfrom datasets import load_dataset\nfrom tqdm import tqdm\n\nfrom AttentionsAnalysis.AnalysisGenerator import AnalysisGenerator\nfrom DataModels.DataType import DataType\nfrom DataModels.ModelMetadata import ModelMetadata\nfrom DataModels.Sample import Sample\n\n\nclass AttentionsDataCreator:\n \"\"\"\n This class is used to create pipeline of comparisons with standard deviation between attentions of two models.\n \"\"\"\n\n def __init__(self, model1_metadata: ModelMetadata, model2_metadata: ModelMetadata, use_dummy_dataset: bool = False,\n start_example=None, end_example=None,\n metric: str = \"Cosine\"):\n self.model1_metadata = model1_metadata\n self.model2_metadata = model2_metadata\n self.metric = metric\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n self.analysis_generator = AnalysisGenerator(model1_metadata, model2_metadata, metric=metric)\n self.start_example = start_example\n self.end_example = end_example\n self.dataset = self.load_dummy_dataset() if use_dummy_dataset else self.load_dataset(self.start_example,\n self.end_example)\n\n def get_correlations_attentions_comparisons(self, sample1: Sample, sample2: Sample):\n attention_model1, attention_model2 = self.analysis_generator.get_attentions(sample1, sample2)\n correlations_attentions_comparisons = self.analysis_generator.get_correlations_of_attentions(attention_model1,\n attention_model2)\n return correlations_attentions_comparisons\n\n def run(self):\n correlations = {}\n for i in tqdm(range(len(self.dataset))):\n sample1 = Sample(id=self.dataset[i][\"id\"], text=self.dataset[i][\"text\"], audio=self.dataset[i][\"audio\"])\n sample2 = sample1\n try:\n correlations_attentions_comparisons = self.get_correlations_attentions_comparisons(\n sample1, sample2)\n correlations[sample1.id] = correlations_attentions_comparisons\n except AssertionError as e:\n example = f\"{sample1.text}\" if sample1.text == sample2.text else f\"{sample1.text} and {sample2.text}\"\n print(f\"Failed to calculate for sample {example}\")\n # save results to pickle file\n self.save_correlations(correlations)\n\n def load_dataset(self, start_example=None, end_example=None):\n if start_example is not None and end_example is not None:\n dataset = load_dataset(\"librispeech_asr\", 'clean', split=f'validation[{start_example}:{end_example}]')\n else:\n dataset = load_dataset(\"librispeech_asr\", 'clean', split='validation')\n return dataset\n\n def load_dummy_dataset(self):\n dataset = load_dataset(\"patrickvonplaten/librispeech_asr_dummy\", 'clean', split='validation')\n return dataset\n\n def save_correlations(self, correlations):\n model_name1 = self.model1_metadata.model_name\n model_name2 = self.model2_metadata.model_name\n # if the model name is 'facebook/wav2vec2-base-960h' we need to remove the '/' from the name\n if '/' in model_name1:\n model_name1 = model_name1.replace('/', '')\n if '/' in model_name2:\n model_name2 = model_name2.replace('/', '')\n path = f'correlations_for_{model_name1}_and_{model_name2}_{self.start_example}_{self.end_example}_{self.metric}.pkl'\n with open(path, 'wb') as handle:\n pickle.dump(correlations, handle)\n\n\nif __name__ == \"__main__\":\n # add arguments from command line with argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--experiment_name\", type=str, choices=[\"text_to_text\", \"audio_to_audio\", \"text_to_audio\"],\n default=\"text_to_audio\", help=\"The name of the experiment to run\")\n parser.add_argument(\"--use_dummy_dataset\", type=bool, default=False,\n help=\"Whether to use a dummy dataset for the experiment\")\n parser.add_argument(\"--start_example\", type=int, default=0)\n parser.add_argument(\"--end_example\", type=int, default=2703)\n parser.add_argument(\"--metric\", type=str, default='jaccard',\n help=\"Which metric to use\")\n args = parser.parse_args()\n\n if args.experiment_name == \"text_to_text\":\n model1_metadata = ModelMetadata(model_name=\"bert-base-uncased\", data_type=DataType.Text,\n align_tokens_to_bert_tokens=False, use_cls_and_sep=True)\n model2_metadata = ModelMetadata(model_name=\"roberta-base\", data_type=DataType.Text,\n align_tokens_to_bert_tokens=False, use_cls_and_sep=True)\n\n elif args.experiment_name == \"text_to_audio\":\n model1_metadata = ModelMetadata(model_name=\"bert-base-uncased\", data_type=DataType.Text,\n align_tokens_to_bert_tokens=False, use_cls_and_sep=True)\n model2_metadata = ModelMetadata(model_name=\"facebook/wav2vec2-base-960h\", data_type=DataType.Audio,\n align_tokens_to_bert_tokens=True, use_cls_and_sep=True)\n\n elif args.experiment_name == \"audio_to_audio\":\n raise Exception(\"Experiment audio_to_audio currently not supported\")\n\n else:\n raise Exception(\"Experiment name is not valid\")\n\n attention_similarity = AttentionsDataCreator(model1_metadata, model2_metadata,\n use_dummy_dataset=args.use_dummy_dataset,\n start_example=args.start_example, end_example=args.end_example,\n metric=args.metric)\n\n attention_similarity.run()\n", "repo_name": "eliyahabba/SoundOfAttention", "sub_path": "AttentionsStatisticsExperiments/CorrelationsAttentionsDataCreator.py", "file_name": "CorrelationsAttentionsDataCreator.py", "file_ext": "py", "file_size_in_byte": 5948, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "DataModels.ModelMetadata.ModelMetadata", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.device", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 25, "usage_type": "attribute"}, {"api_name": "AttentionsAnalysis.AnalysisGenerator.AnalysisGenerator", "line_number": 26, "usage_type": "call"}, {"api_name": "DataModels.Sample.Sample", "line_number": 32, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 40, "usage_type": "call"}, {"api_name": "DataModels.Sample.Sample", "line_number": 41, "usage_type": "call"}, {"api_name": "datasets.load_dataset", "line_number": 55, "usage_type": "call"}, {"api_name": "datasets.load_dataset", "line_number": 57, "usage_type": "call"}, {"api_name": "datasets.load_dataset", "line_number": 61, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 74, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 79, "usage_type": "call"}, {"api_name": "DataModels.ModelMetadata.ModelMetadata", "line_number": 91, "usage_type": "call"}, {"api_name": "DataModels.DataType.DataType.Text", "line_number": 91, "usage_type": "attribute"}, {"api_name": "DataModels.DataType.DataType", "line_number": 91, "usage_type": "name"}, {"api_name": "DataModels.ModelMetadata.ModelMetadata", "line_number": 93, "usage_type": "call"}, {"api_name": "DataModels.DataType.DataType.Text", "line_number": 93, "usage_type": "attribute"}, {"api_name": "DataModels.DataType.DataType", "line_number": 93, "usage_type": "name"}, {"api_name": "DataModels.ModelMetadata.ModelMetadata", "line_number": 97, "usage_type": "call"}, {"api_name": "DataModels.DataType.DataType.Text", "line_number": 97, "usage_type": "attribute"}, {"api_name": "DataModels.DataType.DataType", "line_number": 97, "usage_type": "name"}, {"api_name": "DataModels.ModelMetadata.ModelMetadata", "line_number": 99, "usage_type": "call"}, {"api_name": "DataModels.DataType.DataType.Audio", "line_number": 99, "usage_type": "attribute"}, {"api_name": "DataModels.DataType.DataType", "line_number": 99, "usage_type": "name"}]} +{"seq_id": "25088368821", "text": "########### Kismet to Wigle CSV Conversion Scipt ###########\n\nimport os \nimport pathlib\nimport requests\n\n# Define path of .kismet files\npath = pathlib.Path(__file__).parent.resolve()\nfiles = os.listdir(path)\n\n# Define .kismet file list\nKismet = []\n\n# Append all .kismet files to list \nfor file in files:\n length = len(file)\n len1 = length - 7\n ext = file[len1:length]\n if ext == '.kismet':\n Kismet.append(file)\n\ntotal = len(Kismet)\ni = 0 \n\n# Convert Kismet to Wigle CSV\nfor kis in Kismet:\n i = i + 1\n command = 'kismetdb_to_wiglecsv --in ' + kis + ' --out ' + kis[0:len(kis) - 7] + '.csv'\n print(str(i) + '/' + str(total))\n print(\"Converting *\" + kis + '*')\n os.system(command)\n print('Done!' + '\\n')\n\n# Upload CSV Files to Wigle\ndef upload_files():\n url = 'https://api.wigle.net/api/v2/file/upload' \n path = pathlib.Path(__file__).parent.resolve()\n files = os.listdir(path)\n\n x = 0\n csv = []\n for file in files:\n length = len(file)\n len1 = length - 4\n ext = file[len1:length]\n if ext == '.csv':\n csv.append(file)\n\n Total = len(csv)\n\n for file_csv in csv:\n x = x + 1\n data = {'file': (file_csv, open(file_csv, 'rb'), 'multipart/form-data', {'Expires': '0'})}\n print(str(x) + '/' + str(Total))\n print('Uploading *' + file_csv + '*')\n r = requests.post(url, files = data, headers = {'Authorization': 'Basic YOUR API TOKEN HERE'})\n status = r.status_code\n if status == 200:\n print('Done!' + '\\n')\n elif status != 200:\n print('Failed...')\n print('Status Code: ' + str(status) + '\\n')\n\ndef ask_upload():\n upload = input('Upload CSVs to Wigle?(y/n)')\n\n if upload == 'Y' or upload == 'N':\n print('\\n' + 'Please enter y or n')\n ask_upload()\n elif upload == 'y':\n upload_files()\n return upload\n\nask_upload()\n", "repo_name": "TWinston-66/Kismet-to-Wigle-CSV", "sub_path": "Kismet_To_CSV.py", "file_name": "Kismet_To_CSV.py", "file_ext": "py", "file_size_in_byte": 1921, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pathlib.Path", "line_number": 8, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 9, "usage_type": "call"}, {"api_name": "os.system", "line_number": 31, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 37, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 38, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 56, "usage_type": "call"}]} +{"seq_id": "30954817750", "text": "import pytest\n\nfrom .solution import frequency_sort\n\n\ndef checkio_main(items, solution):\n assert frequency_sort(items) == solution\n\n\n@pytest.mark.parametrize(\n \"items, solution\",\n [\n ([4, 6, 2, 2, 6, 4, 4, 4], [4, 4, 4, 4, 6, 6, 2, 2]),\n ([\"bob\", \"bob\", \"carl\", \"alex\", \"bob\"], [\"bob\", \"bob\", \"bob\", \"carl\", \"alex\"]),\n ([17, 99, 42], [17, 99, 42]),\n ([], []),\n ([1], [1]),\n ],\n)\ndef test(items, solution):\n checkio_main(items, solution)\n", "repo_name": "LachlanMarnham/competitive_programming", "sub_path": "checkio/home/sort_array_by_element_frequency/test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 487, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "solution.frequency_sort", "line_number": 7, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 10, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 10, "usage_type": "attribute"}]} +{"seq_id": "21052505242", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[17]:\n\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport plotly.offline as pyo\nimport plotly.graph_objs as go\nimport plotly.express as px\nimport plotly.io as pio\nimport chart_studio\nimport chart_studio.plotly as py\nimport chart_studio.tools as tls\n\nusername ='yashkaransingh'\napi_key='sTvu3qg24uYodX2dC47M'\n#set credentials to import to plotly\nchart_studio.tools.set_credentials_file(username= username, api_key= api_key)\nchart_studio.tools.set_config_file(sharing='public')\n\n\n# In[18]:\n\n\ncg= pd.read_csv(\"cgl2-edited.csv\")\ncg.columns\ncg.head\n\n\n# In[19]:\n\n\nlength =cg.LENGTH\ntcg=cg.T_CG_COAT\nbcg=cg.B_CG_COAT\n\n\n# In[20]:\n\n\ntrace0 = go.Box(\n y= length,\n name= 'length'\n)\ntrace1 =go.Box(\n y= tcg,\n name= 'coating weight-top'\n)\ntrace2 =go.Box(\n y= bcg,\n name= 'Coating weight-bottom'\n)\n\n\n# In[21]:\n\n\ndata = [trace0,trace1,trace2]\nlayout = go.Layout(title = 'COATING GAUGE')\n\n\n# In[24]:\n\n\nfig = go.Figure(data = data,layout = layout)\n\n\n# In[ ]:\n\n\n\n\n\n# In[25]:\n\n\npy.plot(fig, filename='boxplot2')\n\n\n# In[ ]:\n\n\n\n\n", "repo_name": "yashkaransingh/Exploring-Google-Data-Studio", "sub_path": "coating_gauge.py", "file_name": "coating_gauge.py", "file_ext": "py", "file_size_in_byte": 1131, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "chart_studio.tools.set_credentials_file", "line_number": 21, "usage_type": "call"}, {"api_name": "chart_studio.tools", "line_number": 21, "usage_type": "attribute"}, {"api_name": "chart_studio.tools.set_config_file", "line_number": 22, "usage_type": "call"}, {"api_name": "chart_studio.tools", "line_number": 22, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 28, "usage_type": "call"}, {"api_name": "plotly.graph_objs.Box", "line_number": 44, "usage_type": "call"}, {"api_name": "plotly.graph_objs", "line_number": 44, "usage_type": "name"}, {"api_name": "plotly.graph_objs.Box", "line_number": 48, "usage_type": "call"}, {"api_name": "plotly.graph_objs", "line_number": 48, "usage_type": "name"}, {"api_name": "plotly.graph_objs.Box", "line_number": 52, "usage_type": "call"}, {"api_name": "plotly.graph_objs", "line_number": 52, "usage_type": "name"}, {"api_name": "plotly.graph_objs.Layout", "line_number": 62, "usage_type": "call"}, {"api_name": "plotly.graph_objs", "line_number": 62, "usage_type": "name"}, {"api_name": "plotly.graph_objs.Figure", "line_number": 68, "usage_type": "call"}, {"api_name": "plotly.graph_objs", "line_number": 68, "usage_type": "name"}, {"api_name": "chart_studio.plotly.plot", "line_number": 80, "usage_type": "call"}, {"api_name": "chart_studio.plotly", "line_number": 80, "usage_type": "name"}]} +{"seq_id": "3554084927", "text": "# coding: utf-8\n# pylint: disable= invalid-name, unused-import\n\"\"\"For compatibility.\"\"\"\nfrom pykrige.ok import OrdinaryKriging\nfrom pykrige.ok3d import OrdinaryKriging3D\nfrom pykrige.uk import UniversalKriging\nfrom pykrige.uk3d import UniversalKriging3D\n\n# sklearn\ntry:\n # keep train_test_split here for backward compatibility\n from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin\n from sklearn.model_selection import train_test_split\n\n SKLEARN_INSTALLED = True\n\nexcept ImportError:\n SKLEARN_INSTALLED = False\n\n train_test_split = None\n\n class RegressorMixin:\n \"\"\"Mock RegressorMixin.\"\"\"\n\n class ClassifierMixin:\n \"\"\"Mock ClassifierMixin.\"\"\"\n\n class BaseEstimator:\n \"\"\"Mock BaseEstimator.\"\"\"\n\n\nkrige_methods = {\n \"ordinary\": OrdinaryKriging,\n \"universal\": UniversalKriging,\n \"ordinary3d\": OrdinaryKriging3D,\n \"universal3d\": UniversalKriging3D,\n}\n\nthreed_krige = (\"ordinary3d\", \"universal3d\")\n\nkrige_methods_kws = {\n \"ordinary\": [\n \"anisotropy_scaling\",\n \"anisotropy_angle\",\n \"enable_statistics\",\n \"coordinates_type\",\n ],\n \"universal\": [\n \"anisotropy_scaling\",\n \"anisotropy_angle\",\n \"drift_terms\",\n \"point_drift\",\n \"external_drift\",\n \"external_drift_x\",\n \"external_drift_y\",\n \"functional_drift\",\n ],\n \"ordinary3d\": [\n \"anisotropy_scaling_y\",\n \"anisotropy_scaling_z\",\n \"anisotropy_angle_x\",\n \"anisotropy_angle_y\",\n \"anisotropy_angle_z\",\n ],\n \"universal3d\": [\n \"anisotropy_scaling_y\",\n \"anisotropy_scaling_z\",\n \"anisotropy_angle_x\",\n \"anisotropy_angle_y\",\n \"anisotropy_angle_z\",\n \"drift_terms\",\n \"functional_drift\",\n ],\n}\n\n\nclass SklearnException(Exception):\n \"\"\"Exception for missing scikit-learn.\"\"\"\n\n\ndef validate_method(method):\n \"\"\"Validate the kriging method in use.\"\"\"\n if method not in krige_methods.keys():\n raise ValueError(\n \"Kriging method must be one of {}\".format(krige_methods.keys())\n )\n\n\ndef validate_sklearn():\n \"\"\"Validate presence of scikit-learn.\"\"\"\n if not SKLEARN_INSTALLED:\n raise SklearnException(\n \"sklearn needs to be installed in order to use this module\"\n )\n\n\nclass Krige(RegressorMixin, BaseEstimator):\n \"\"\"\n A scikit-learn wrapper class for Ordinary and Universal Kriging.\n\n This works with both Grid/RandomSearchCv for finding the best\n Krige parameters combination for a problem.\n\n Parameters\n ----------\n method: str, optional\n type of kriging to be performed\n variogram_model: str, optional\n variogram model to be used during Kriging\n nlags: int\n see OK/UK class description\n weight: bool\n see OK/UK class description\n n_closest_points: int\n number of closest points to be used during Ordinary Kriging\n verbose: bool\n see OK/UK class description\n exact_values : bool\n see OK/UK class description\n variogram_parameters : list or dict\n see OK/UK class description\n variogram_function : callable\n see OK/UK class description\n anisotropy_scaling : tuple\n single value for 2D (UK/OK) and two values in 3D (UK3D/OK3D)\n anisotropy_angle : tuple\n single value for 2D (UK/OK) and three values in 3D (UK3D/OK3D)\n enable_statistics : bool\n see OK class description\n coordinates_type : str\n see OK/UK class description\n drift_terms : list of strings\n see UK/UK3D class description\n point_drift : array_like\n see UK class description\n ext_drift_grid : tuple\n Holding the three values external_drift, external_drift_x and\n external_drift_z for the UK class\n functional_drift : list of callable\n see UK/UK3D class description\n \"\"\"\n\n def __init__(\n self,\n method=\"ordinary\",\n variogram_model=\"linear\",\n nlags=6,\n weight=False,\n n_closest_points=10,\n verbose=False,\n exact_values=True,\n pseudo_inv=False,\n pseudo_inv_type=\"pinv\",\n variogram_parameters=None,\n variogram_function=None,\n anisotropy_scaling=(1.0, 1.0),\n anisotropy_angle=(0.0, 0.0, 0.0),\n enable_statistics=False,\n coordinates_type=\"euclidean\",\n drift_terms=None,\n point_drift=None,\n ext_drift_grid=(None, None, None),\n functional_drift=None,\n ):\n validate_method(method)\n self.variogram_model = variogram_model\n self.variogram_parameters = variogram_parameters\n self.variogram_function = variogram_function\n self.nlags = nlags\n self.weight = weight\n self.verbose = verbose\n self.exact_values = exact_values\n self.pseudo_inv = pseudo_inv\n self.pseudo_inv_type = pseudo_inv_type\n self.anisotropy_scaling = anisotropy_scaling\n self.anisotropy_angle = anisotropy_angle\n self.enable_statistics = enable_statistics\n self.coordinates_type = coordinates_type\n self.drift_terms = drift_terms\n self.point_drift = point_drift\n self.ext_drift_grid = ext_drift_grid\n self.functional_drift = functional_drift\n self.model = None # not trained\n self.n_closest_points = n_closest_points\n self.method = method\n\n def fit(self, x, y, *args, **kwargs):\n \"\"\"\n Fit the current model.\n\n Parameters\n ----------\n x: ndarray\n array of Points, (x, y) pairs of shape (N, 2) for 2d kriging\n array of Points, (x, y, z) pairs of shape (N, 3) for 3d kriging\n y: ndarray\n array of targets (N, )\n \"\"\"\n val_kw = \"val\" if self.method in threed_krige else \"z\"\n setup = dict(\n variogram_model=self.variogram_model,\n variogram_parameters=self.variogram_parameters,\n variogram_function=self.variogram_function,\n nlags=self.nlags,\n weight=self.weight,\n verbose=self.verbose,\n exact_values=self.exact_values,\n pseudo_inv=self.pseudo_inv,\n pseudo_inv_type=self.pseudo_inv_type,\n )\n add_setup = dict(\n anisotropy_scaling=self.anisotropy_scaling[0],\n anisotropy_angle=self.anisotropy_angle[0],\n enable_statistics=self.enable_statistics,\n coordinates_type=self.coordinates_type,\n anisotropy_scaling_y=self.anisotropy_scaling[0],\n anisotropy_scaling_z=self.anisotropy_scaling[1],\n anisotropy_angle_x=self.anisotropy_angle[0],\n anisotropy_angle_y=self.anisotropy_angle[1],\n anisotropy_angle_z=self.anisotropy_angle[2],\n drift_terms=self.drift_terms,\n point_drift=self.point_drift,\n external_drift=self.ext_drift_grid[0],\n external_drift_x=self.ext_drift_grid[1],\n external_drift_y=self.ext_drift_grid[2],\n functional_drift=self.functional_drift,\n )\n for kw in krige_methods_kws[self.method]:\n setup[kw] = add_setup[kw]\n input_kw = self._dimensionality_check(x)\n input_kw.update(setup)\n input_kw[val_kw] = y\n self.model = krige_methods[self.method](**input_kw)\n\n def _dimensionality_check(self, x, ext=\"\"):\n if self.method in (\"ordinary\", \"universal\"):\n if x.shape[1] != 2:\n raise ValueError(\"2d krige can use only 2d points\")\n else:\n return {\"x\" + ext: x[:, 0], \"y\" + ext: x[:, 1]}\n if self.method in (\"ordinary3d\", \"universal3d\"):\n if x.shape[1] != 3:\n raise ValueError(\"3d krige can use only 3d points\")\n else:\n return {\n \"x\" + ext: x[:, 0],\n \"y\" + ext: x[:, 1],\n \"z\" + ext: x[:, 2],\n }\n\n def predict(self, x, *args, **kwargs):\n \"\"\"\n Predict.\n\n Parameters\n ----------\n x: ndarray\n array of Points, (x, y) pairs of shape (N, 2) for 2d kriging\n array of Points, (x, y, z) pairs of shape (N, 3) for 3d kriging\n Returns\n -------\n Prediction array\n \"\"\"\n if not self.model:\n raise Exception(\"Not trained. Train first\")\n points = self._dimensionality_check(x, ext=\"points\")\n return self.execute(points, *args, **kwargs)[0]\n\n def execute(self, points, *args, **kwargs):\n # TODO array of Points, (x, y) pairs of shape (N, 2)\n \"\"\"\n Execute.\n\n Parameters\n ----------\n points: dict\n\n Returns\n -------\n Prediction array\n Variance array\n \"\"\"\n default_kw = dict(style=\"points\", backend=\"loop\")\n default_kw.update(kwargs)\n points.update(default_kw)\n if isinstance(self.model, (OrdinaryKriging, OrdinaryKriging3D)):\n points.update(dict(n_closest_points=self.n_closest_points))\n else:\n print(\"n_closest_points will be ignored for UniversalKriging\")\n prediction, variance = self.model.execute(**points)\n return prediction, variance\n\n\ndef check_sklearn_model(model, task=\"regression\"):\n \"\"\"Check the sklearn method in use.\"\"\"\n if task == \"regression\":\n if not (isinstance(model, BaseEstimator) and isinstance(model, RegressorMixin)):\n raise RuntimeError(\n \"Needs to supply an instance of a scikit-learn regression class.\"\n )\n elif task == \"classification\":\n if not (\n isinstance(model, BaseEstimator) and isinstance(model, ClassifierMixin)\n ):\n raise RuntimeError(\n \"Needs to supply an instance of a scikit-learn classification class.\"\n )\n", "repo_name": "GeoStat-Framework/PyKrige", "sub_path": "src/pykrige/compat.py", "file_name": "compat.py", "file_ext": "py", "file_size_in_byte": 9889, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 682, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sklearn.model_selection.train_test_split", "line_number": 20, "usage_type": "name"}, {"api_name": "pykrige.ok.OrdinaryKriging", "line_number": 33, "usage_type": "name"}, {"api_name": "pykrige.uk.UniversalKriging", "line_number": 34, "usage_type": "name"}, {"api_name": "pykrige.ok3d.OrdinaryKriging3D", "line_number": 35, "usage_type": "name"}, {"api_name": "pykrige.uk3d.UniversalKriging3D", "line_number": 36, "usage_type": "name"}, {"api_name": "pykrige.ok.OrdinaryKriging", "line_number": 286, "usage_type": "name"}, {"api_name": "pykrige.ok3d.OrdinaryKriging3D", "line_number": 286, "usage_type": "name"}]} +{"seq_id": "26875790435", "text": "from torchstudio.modules import Analyzer\r\nfrom typing import List\r\nimport numpy as np\r\nfrom random import randint\r\nimport zlib\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.patches import Circle\r\nimport PIL\r\nimport sys\r\n\r\nclass Multiclass(Analyzer):\r\n \"\"\"Analyze the distribution of multiclass datasets\r\n (single integer output, single label prediction)\r\n https://en.wikipedia.org/wiki/Multiclass_classification\r\n\r\n Args:\r\n train: If True, analyze the training set.\r\n If False, analyze the validation set.\r\n If None, analyze the entire dataset.\r\n \"\"\"\r\n def __init__(self, train=True):\r\n super().__init__(train)\r\n\r\n def start_analysis(self, num_samples: int, input_tensors_id: List[int], output_tensors_id: List[int], labels: List[str]):\r\n self.num_samples=num_samples\r\n self.input_tensors_id=input_tensors_id\r\n self.output_tensors_id=output_tensors_id\r\n self.labels=labels\r\n\r\n self.classes_weight=[]\r\n self.classes_label=[]\r\n self.classes_randomness=0\r\n\r\n self.tensor_id=None\r\n self.classes={}\r\n self.classes_sequence=bytearray()\r\n\r\n\r\n def analyze_sample(self, sample: List[np.array], training_sample: bool):\r\n if self.tensor_id is None:\r\n for id in self.output_tensors_id:\r\n if \"int\" in str(sample[id].dtype) and len(sample[id].shape)==0:\r\n self.tensor_id=id\r\n break\r\n if self.tensor_id is None:\r\n raise ValueError('Multiclass analysis requires a single integer output tensor')\r\n\r\n class_id=sample[self.tensor_id].item()\r\n self.classes_sequence.extend(class_id.to_bytes(2,'little'))\r\n if class_id not in self.classes:\r\n self.classes[class_id]=1\r\n else:\r\n self.classes[class_id]+=1\r\n\r\n def finish_analysis(self):\r\n num_registered_classes=len(self.classes)\r\n random_sequence=bytearray()\r\n for i in range(self.num_samples):\r\n random_sequence.extend(randint(0, num_registered_classes).to_bytes(2,'little'))\r\n self.classes_randomness=len(zlib.compress(self.classes_sequence))/len(zlib.compress(random_sequence))\r\n\r\n #prepare weights and labels\r\n last_class_id=0\r\n for class_id in self.classes:\r\n last_class_id=max(last_class_id,class_id)\r\n self.classes_weight=[]\r\n self.classes_label=[]\r\n for class_id in range(last_class_id+1):\r\n if class_id not in self.classes:\r\n self.classes_weight.append(0)\r\n else:\r\n self.classes_weight.append(self.classes[class_id])\r\n if class_id>=len(self.labels):\r\n self.classes_label.append(str(class_id))\r\n else:\r\n self.classes_label.append(self.labels[class_id])\r\n\r\n return self.classes_weight\r\n\r\n def generate_report(self, size, dpi):\r\n if not self.classes_weight:\r\n raise ValueError(\"Nothing to report\")\r\n\r\n #set up matplotlib renderer, style, figure and axis\r\n mpl.use('agg') #https://www.namingcrisis.net/post/2019/03/11/interactive-matplotlib-ipython/\r\n plt.style.use('dark_background')\r\n plt.rcParams.update({'font.size': 8})\r\n fig, [ax1, ax2] = plt.subplots(1 if size[0]>size[1] else 2, 2 if size[0]>size[1] else 1, figsize=(size[0]/dpi, size[1]/dpi), dpi=dpi)\r\n\r\n ax1.set_title(\"Class Distribution\")\r\n ax1.pie(self.classes_weight, labels=self.classes_label, autopct='%1.1f%%', colors=plt.cm.tab10.colors, startangle=90, counterclock=False)\r\n\r\n ax2.set_title(\"Class Randomness\")\r\n _, _, autopct = ax2.pie([self.classes_randomness,max(0,1-self.classes_randomness)], autopct='%1.1f%%', textprops={'fontsize': 16}, pctdistance=0, colors=[\"#b03070\",\"black\"], startangle=90, counterclock=False)\r\n autopct[1].set_visible(False)\r\n ax2.add_patch(Circle( (0,0), 0.6, color='black'))\r\n\r\n plt.tight_layout(pad=0)\r\n\r\n canvas = plt.get_current_fig_manager().canvas\r\n canvas.draw()\r\n img = PIL.Image.frombytes('RGB',canvas.get_width_height(),canvas.tostring_rgb())\r\n plt.close()\r\n return img\r\n\r\n", "repo_name": "TorchStudio/torchstudio", "sub_path": "torchstudio/analyzers/multiclass.py", "file_name": "multiclass.py", "file_ext": "py", "file_size_in_byte": 4272, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 362, "dataset": "github-code", "pt": "24", "api": [{"api_name": "torchstudio.modules.Analyzer", "line_number": 12, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 25, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 40, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 40, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 60, "usage_type": "call"}, {"api_name": "zlib.compress", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.use", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style.use", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 87, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 87, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams.update", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 88, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 88, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 89, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 89, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 92, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 92, "usage_type": "name"}, {"api_name": "matplotlib.patches.Circle", "line_number": 97, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 99, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 99, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.get_current_fig_manager", "line_number": 101, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 101, "usage_type": "name"}, {"api_name": "PIL.Image.frombytes", "line_number": 103, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 103, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.close", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 104, "usage_type": "name"}]} +{"seq_id": "30307436787", "text": "# from datetime import date # released min date(1, 1, 1)\nfrom mimetypes import MimeTypes\nfrom os.path import basename, getsize # posixpath\nfrom random import randrange\nfrom re import IGNORECASE, sub\nfrom subprocess import call, check_output\n# extremely fast C++ JSON parser and serialization library\nfrom rapidjson import loads\nfrom sxtools.logging import get_basic_logger\nlogger = get_basic_logger() # sXtools.log\nfrom sxtools.utils import cache # keep thumbnails in one place\n\n\nclass Scene:\n\n def __init__(self, path: str) -> None:\n\n self.path, self.ext = path, path[-3:].lower()\n self.size = getsize(path) # os.stat()\n self.performers = list()\n self.title, self.paysite = '', ''\n self.released = None # not set yet | date.min\n self.ffprobed = False # get metadata using ffprobe, e.g. bitrate, resolution, duration\n\n def __str__(self) -> str:\n\n return self.sanitize()\n\n def is_valid(self) -> bool:\n '''\n check if scene well-parsed is\n '''\n return bool(self.released and self.performers and self.paysite)\n\n def basename(self) -> str:\n '''\n return the final component of a pathname\n '''\n return basename(self.path)\n\n def viewname(self) -> str:\n '''\n return the viewname of a scene\n '''\n return f'd=\"{self.released or \"\"}\" p=\"{self.perfs_as_string()}\" s=\"{self.paysite}\" t=\"{self.title}\"'\n\n def set_title(self, title: str = '') -> None:\n '''\n clean title, remove multiple spaces and assign it to the title\n '''\n t = ' '.join((title or '').split())\n t = sub(' part (\\d+)', ' (Part \\g<1>)', t, flags=IGNORECASE)\n # t = sub('\\'[A-Z]', lambda x: x.group(0).lower(), m.group('title'))\n self.title = t # assign a fmt'd string\n\n def resolution(self) -> str:\n '''\n return scene's resolution\n '''\n return f'{self.w}x{self.h}' if self.ffprobed else 'not yet scanned'\n\n def perfs_as_string(self) -> str:\n '''\n return performers as a well-formed string\n '''\n return ', '.join(self.performers[:-2] + [' & '.join(self.performers[-2:])])\n\n def mimetype(self) -> str:\n '''\n return scene's mimetype, e.g. video-mp4\n '''\n mt = MimeTypes().guess_type(self.path)[0]\n if not mt:\n mt = 'video'\n return mt.replace(chr(47), chr(45)) # return mimetype\n\n def scan(self) -> None:\n '''\n read out video file's metadata using \"ffprobe\" (part of \"ffmpeg\")\n '''\n logger.debug(f'Scanning {self.viewname()}')\n try:\n meta = loads(check_output(['ffprobe',\n '-v', 'fatal',\n '-select_streams',\n 'v:0',\n '-show_entries',\n 'format=duration,bit_rate:stream=width,height',\n '-of', 'json', self.path]))\n # get width & height of the scene\n self.h = meta['streams'][0]['height']\n self.w = meta['streams'][0]['width'] # v:0\n # get scene's bitrate\n self.bitrate = meta['format']['bit_rate']\n # get duration in seconds as float\n self.duration = meta['format']['duration']\n # check for suspicious resolutions\n if self.w != 1920: # 1080p\n logger.debug(\n f'Suspicious Resolution {self.w}x{self.h}')\n if not cache(self.basename()):\n call(['ffmpeg',\n '-ss', str(randrange(int(float(self.duration)))),\n '-v',\n 'error',\n '-i', self.path,\n '-vframes', '1',\n cache(self.basename(), True), '-y'])\n side = min(self.w, self.h)\n call(['convert',\n cache(self.basename()),\n '-gravity', 'Center',\n '-crop', f'{side}x{side}+0+0',\n #'-unsharp', '0.25x0.25+8+0.065',\n '-resize', '49',\n '-quality', '90', cache(self.basename())])\n self.ffprobed = True\n except (FileNotFoundError) as e:\n logger.warning(f'No such file or directory: {e.filename}')\n\n # be sure \"ffprobe\" is installed, run \"apt install ffmpeg\" otherwise\n\n def sanitize(self) -> str:\n '''\n return sanitized scene's name as a string\n '''\n name = basename(self.path)[:-4] # .lower()\n sep = '.' if name.count('.') > name.count(' ') else ' '\n for ss in list(['[pt]', '[', ']']):\n name = name.replace(ss, sep)\n droplist = ['720p','1080p','1920p','2160p','bj','int','mp4','mp4-gush','mp4-ktr','mp4-nbq','mp4-wrb','repack','xxx']\n return sep.join(\n x for x in name.split(sep) if x and x.lower() not in droplist)\n", "repo_name": "nschepsen/sxtools-manager", "sub_path": "src/sxtools/core/videoscene.py", "file_name": "videoscene.py", "file_ext": "py", "file_size_in_byte": 4913, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sxtools.logging.get_basic_logger", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path.getsize", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 39, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 52, "usage_type": "call"}, {"api_name": "re.IGNORECASE", "line_number": 52, "usage_type": "name"}, {"api_name": "mimetypes.MimeTypes", "line_number": 72, "usage_type": "call"}, {"api_name": "rapidjson.loads", "line_number": 83, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 83, "usage_type": "call"}, {"api_name": "sxtools.utils.cache", "line_number": 101, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 102, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 103, "usage_type": "call"}, {"api_name": "sxtools.utils.cache", "line_number": 108, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 110, "usage_type": "call"}, {"api_name": "sxtools.utils.cache", "line_number": 111, "usage_type": "call"}, {"api_name": "sxtools.utils.cache", "line_number": 116, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 127, "usage_type": "call"}]} +{"seq_id": "8715247946", "text": "import numpy as np\r\nimport pandas as pd\r\nimport scipy.stats\r\n\r\nfrom scipy.optimize import curve_fit \r\n\r\nimport plot_asymptotes_library as pal\r\n\r\ndef fit_to_line(xarray, yarray, alpha = 0.05):\r\n \"\"\"\r\n Purpose: Fit (x,y) data using linear regression; return intercept, slope,\r\n and their confidence intervals. Confidence intervals are based on desired \r\n type 1 error. \r\n\r\n Parameters\r\n ----------\r\n xarray : Collection (list, numpy array, ...) of Floats\r\n x-values\r\n yarray : Collection (list, numpy array, ...) of Floats\r\n y-values\r\n alpha : Float\r\n Desired Type 1 Error for the confidence intervals, the default is 0.05.\r\n\r\n Returns\r\n -------\r\n list\r\n [[y0, y0_lower, y0_upper],[slope, slope_lower, slope_upper], p_value]\r\n\r\n \"\"\"\r\n\r\n #For confidence intervals, calculate Z-score based on desired T1E\r\n z_score = scipy.stats.norm.ppf(1 - alpha/2)\r\n\r\n #Linear regression; returns slope, intercept, and their standard errors\r\n r = scipy.stats.linregress(xarray,yarray)\r\n\r\n #Get estimated parameters\r\n y0 = r[1]\r\n slope = r[0]\r\n p_value = r.pvalue\r\n\r\n #Calculate the ends of the confidence intervals\r\n y0_upper = y0 + z_score*r.intercept_stderr\r\n y0_lower = y0 - z_score*r.intercept_stderr\r\n slope_lower = slope - 1.96*r.stderr\r\n slope_upper = slope + 1.96*r.stderr\r\n\r\n #Return information on the [intercept], [slope], and p value \r\n return [[y0, y0_lower, y0_upper],\r\n [slope, slope_lower, slope_upper], \r\n p_value]\r\n \r\n\r\ndef calc_asympt_fx(x, lamb, gamma):\r\n \"\"\"\r\n Purpose: Calculate f(x) = lambda*(1- exp(-x/gamma))\r\n\r\n Parameters\r\n ----------\r\n x : Float\r\n x-value\r\n lamb : Float\r\n \"Lambda\": Asymptote value as x approaches infinity\r\n gamma : Float\r\n Decay parameter; same units as x\r\n\r\n Returns\r\n -------\r\n Float\r\n f(x)\r\n\r\n \"\"\"\r\n \r\n return lamb*(1 - np.exp(-x/gamma))\r\n\r\n\r\ndef fit_to_asymp(xarray, yarray):\r\n \"\"\"\r\n Purpose: Fit (x,y) values to an asymptote function. \r\n Return lambda and gamma. \r\n\r\n Parameters\r\n ----------\r\n xarray : Collection (list, numpy array, ...) of Floats\r\n x values\r\n yarray : Collection (list, numpy array, ...) of Floats\r\n y values\r\n\r\n Returns\r\n -------\r\n list\r\n [lambda, gamma]\r\n\r\n \"\"\"\r\n \r\n parameters, covariance = curve_fit(calc_asympt_fx, xarray, yarray)\r\n \r\n return [parameters[0], parameters[1]]\r\n\r\n\r\ndef fit_to_asymp_get_CI(xarray, yarray, alpha = 0.05):\r\n \"\"\"\r\n Purpose: Purpose: Fit (x,y) values to an asymptote function. \r\n Return lambda, gamma, and their confidence intervals.\r\n\r\n Parameters\r\n ----------\r\n xarray : Collection (list, numpy array, ...) of Floats\r\n x-values\r\n yarray : Collection (list, numpy array, ...) of Floats\r\n y-values\r\n alpha : Float, optional\r\n Desired Type 1 Error for the confidence intervals. The default is 0.05.\r\n\r\n Returns\r\n -------\r\n list of lists\r\n [lambda, lambda lower, lambda upper], \r\n [gamma, gamma lower, gamma upper]\r\n\r\n \"\"\"\r\n \r\n #For confidence intervals, calculate Z-score based on desired T1E\r\n z_score = scipy.stats.norm.ppf(1 - alpha/2)\r\n\r\n #Curve fit outputs parameters and covariance \r\n popt, pcov = curve_fit(calc_asympt_fx, xarray, yarray) \r\n \r\n #Get relative error from covariance\r\n sigma = np.sqrt(np.diag(pcov))\r\n \r\n #Calculate confidence intervals for lambda and gamma\r\n lambCI = popt[0], popt[0] - z_score*sigma[0], popt[0] + z_score*sigma[0]\r\n gammaCI = popt[1], popt[1] - z_score*sigma[1], popt[1] + z_score*sigma[1]\r\n \r\n return [lambCI, gammaCI]\r\n\r\n\r\ndef fit_asympt_bootstrap(xarray, yarray, simuls, plot_each = False):\r\n \"\"\"\r\n Purpose: Perform bootstrap simulations on (x,y) data; return the \r\n asymptote parameters for every simulation.\r\n\r\n Parameters\r\n ----------\r\n xarray : Collection (list, numpy array, ...) of Floats\r\n x-values \r\n yarray : Collection (list, numpy array, ...) of Floats\r\n y-values \r\n simuls : Integer \r\n Number of bootstrap simulations\r\n plot_each : Boolean, optional\r\n Option whether to plot each bootstrap and fit. The default is False.\r\n\r\n Returns\r\n -------\r\n list of lists\r\n Lists of each estimand from each bootstrap simulation \r\n [lambda results], [gamma results]\r\n\r\n \"\"\"\r\n \r\n #N: Number of data points\r\n N = len(xarray)\r\n \r\n #Create a Pandas dataframe to take advantage of pandas' sample-function.\r\n xarray = np.array(xarray)\r\n yarray = np.array(yarray)\r\n df = pd.DataFrame({'x': xarray, 'y':yarray})\r\n \r\n #Collection to keep the results from each simulation\r\n lambda_c = []\r\n gamma_c = []\r\n \r\n #For each bootstrap simulation\r\n for s in range(0,simuls):\r\n \r\n #Randomly draw (with replacement) N data points\r\n sampled = df.sample(n = N, replace = True)\r\n \r\n #Fit to asymptote\r\n r = fit_to_asymp(sampled[\"x\"], sampled[\"y\"])\r\n \r\n #Update the collections of results\r\n lambda_c.append(r[0])\r\n gamma_c.append(r[1])\r\n \r\n #Plot option\r\n if plot_each:\r\n pal.plot_asymptote(sampled[\"x\"], sampled[\"y\"], \r\n limits = [[0,18],[0,1]], \r\n ax_labels = [\"Area (mm$^{2}$)\", \"Accuracy\"],\r\n fit=\"none\",\r\n graph_filename = \"bootstrap.jpg\")\r\n pal.plot_asymptote(sampled[\"x\"], sampled[\"y\"], \r\n limits = [[0,18],[0,1]], \r\n ax_labels = [\"Area (mm$^{2}$)\", \"Accuracy\"],\r\n fit=\"asymptote\",\r\n graph_filename = \"bootstrap_fitted.jpg\")\r\n \r\n return [lambda_c, gamma_c]\r\n\r\n\r\ndef get_percentiles_from_list(rlist, alpha = 0.05):\r\n \"\"\"\r\n Purpose: Take a list of values, sort, and get percentile values.\r\n\r\n Parameters\r\n ----------\r\n rlist : List of Floats\r\n \r\n alpha: Float, optional\r\n Desired Type 1 Error for the confidence intervals. The default is 0.05.\r\n \r\n\r\n Returns\r\n -------\r\n list of Floats\r\n [median, lowerbound, upperbound]\r\n\r\n \"\"\"\r\n \r\n #Number of values in the list\r\n n = len(rlist)\r\n \r\n #Sort the list\r\n rlist = np.sort(np.array(rlist))\r\n \r\n #Calculate percentiles\r\n median = rlist[int(0.5*n)]\r\n lowerbound = rlist[int(alpha/2*n)]\r\n upperbound = rlist[int((1-alpha/2)*n)]\r\n \r\n return [median, lowerbound, upperbound]\r\n \r\n\r\ndef simulate_binomial_error(prob, n):\r\n \"\"\"\r\n Purpose: Take an observed probability, from n observations -> \r\n simulate a new probability with error from the binomial distribution.\r\n\r\n Parameters\r\n ----------\r\n prob : Float\r\n Probability (0 to 1)\r\n n : Integer\r\n Number of observations from which prob was calculated.\r\n\r\n Returns\r\n -------\r\n prob_new : Float\r\n Probability with error simulated from the binomial distribution.\r\n\r\n \"\"\"\r\n prob_new = np.random.normal(loc = prob, scale = (prob*(1-prob)/n)**0.5)\r\n \r\n return prob_new \r\n \r\n\r\ndef monteCarlo_asymptotes_with_error(xarray, lamb, gamma, n, \r\n simuls, plot_each=False):\r\n \"\"\"\r\n Purpose: Obtain a collection of asymptote fit parameters from \r\n Monte Carlo simulations. In each simulation, error from the binomial\r\n distribution is added to a perfect asympote at each of the specified \r\n x-values. Return fit parameters from each simulation.\r\n\r\n Parameters\r\n ----------\r\n xarray : Collection (list, numpy array, ...) of Floats\r\n x-values at which you want to simulate each point of the asymptote.\r\n lamb : Float\r\n \"Lambda\": Asymptote value as x approaches infinity\r\n gamma : Float\r\n Decay parameter; same units as x\r\n n : Integer\r\n Number of observations from which the probabilities were calculated.\r\n simuls : Integer \r\n Number of bootstrap simulations\r\n plot_each : Boolean, optional\r\n Option whether to plot each bootstrap and fit. The default is False.\r\n\r\n Returns\r\n -------\r\n list of lists (Floats)\r\n [simulation results for lambda], [simulations results for gamma]\r\n\r\n \"\"\"\r\n #Collections for the results of each MC simulation\r\n lamb_c = []\r\n gamma_c = []\r\n \r\n #Calculate the errorless asymptote, at each x, given the lamb and gamma.\r\n vectorized = np.vectorize(calc_asympt_fx) \r\n yarray = vectorized(xarray, lamb, gamma)\r\n\r\n #Vectorize the function that adds binomial error.\r\n vectorized_binomial = np.vectorize(simulate_binomial_error)\r\n\r\n #For each MC simulation...\r\n for s in range(0,simuls):\r\n #Simulate binomial-distribution error for each y point.\r\n yMC = vectorized_binomial(yarray, n)\r\n \r\n #Fit the (x,y) data to an asymptote\r\n r = fit_to_asymp(xarray, yMC)\r\n \r\n #Plot option \r\n if plot_each:\r\n pal.plot_asymptote(xarray, yMC, \r\n limits = [[0,18],[0,1]], \r\n ax_labels = [\"Area (mm$^{2}$)\", \"Accuracy\"],\r\n fit=\"none\",\r\n graph_filename = \"output_perfect.jpg\")\r\n pal.plot_asymptote(xarray, yMC, \r\n limits = [[0,18],[0,1]], \r\n ax_labels = [\"Area (mm$^{2}$)\", \"Accuracy\"],\r\n fit=\"asymptote\",\r\n graph_filename = \"output_perfect.jpg\") \r\n \r\n #Update collections of results.\r\n lamb_c.append(r[0])\r\n gamma_c.append(r[1])\r\n \r\n return [lamb_c, gamma_c]\r\n\r\n\r\ndef simulate_T1E(simuls, xarray, yarray = [],\r\n n = 1, simulation = \"binomialMC\", \r\n fit = \"linear\", plot_each = False):\r\n \"\"\"\r\n Purpose: Simulate type 1 error. Data can be simulated by either\r\n using the binomial distribution (\"binomialMC\") or random drawing \r\n with replacement from experimental data (bootstrap).\r\n\r\n Parameters\r\n ----------\r\n simuls : Integer\r\n Number of simulations to run\r\n xarray : Collection (list, numpy array, ...) of Floats\r\n x-values at which to simulate\r\n yarray : Collection (list, numpy array, ...) of Floats, optional\r\n If \"bootstrap\" simulation chosen, y values from which to draw\r\n randomly. The default is [].\r\n n : Integer, optional\r\n If \"binomialMC\" is chosen, the number of observations to use\r\n in the simulation of binomial error. The default is 1.\r\n simulation : String, optional\r\n Two options: \"binomialMC\" and \"bootstrap\". The default is \"binomialMC\".\r\n fit : String, optional\r\n Two options: \"linear\" and \"asymptote\" fit. The default is \"linear\".\r\n plot_each : Boolean, optional\r\n If true, plots every simulation and its fit. The default is False.\r\n\r\n Returns\r\n -------\r\n Float\r\n Type 1 Error\r\n\r\n \"\"\"\r\n \r\n #If an invalid option was selected for simulation type...\r\n if simulation not in [\"binomialMC\", \"bootstrap\"]:\r\n print(\"Error in simulate_T1E. For simulation, \\\r\n choose either: binomialMC or bootstrap\")\r\n return\r\n \r\n #If an invalid option was selected for fit...\r\n if fit not in [\"linear\", \"asymptote\"]:\r\n print(\"Error in simulate_T1E. For fit, \\\r\n choose either: linear or asymptote\")\r\n return\r\n \r\n #Number of data points and average y-value\r\n n_points = len(xarray) \r\n av_y = np.mean(yarray)\r\n \r\n #Keep track of the number of positive results.\r\n pos = 0\r\n \r\n #For each simulation...\r\n for s in range(0,simuls):\r\n #----------------------------------------------------------------------\r\n #Simulate the data using specified method\r\n #----------------------------------------------------------------------\r\n if simulation == \"binomialMC\":\r\n #Make y values array, all equal to the average-y of the input\r\n simulated = np.repeat(av_y, n_points)\r\n \r\n #Simulate the error for each using the binomial distribution\r\n vectorized = np.vectorize(simulate_binomial_error) \r\n simulated = vectorized(simulated, n)\r\n \r\n if simulation == \"bootstrap\":\r\n if len(yarray) == 0:\r\n print(\"Error in simulate_T1E. yarray must not be empty\")\r\n return\r\n \r\n #Make a dataframe to take advantadge of sample\r\n df = pd.DataFrame({'x': xarray, 'y':yarray})\r\n simulated = df.sample(n = n_points, replace = True)\r\n \r\n #Control the type by turning it into a numpy array\r\n simulated = np.array(simulated.y)\r\n\r\n #----------------------------------------------------------------------\r\n #Fit using specified method\r\n #----------------------------------------------------------------------\r\n if fit == \"linear\":\r\n\r\n fline = fit_to_line(xarray, simulated)\r\n\r\n #A positive result if both lower and upper bound are the same sign\r\n if fline[1][1]*fline[1][2] > 0:\r\n pos = pos + 1\r\n \r\n if fit == \"asymptote\":\r\n fasymp = fit_to_asymp_get_CI(xarray, simulated)\r\n \r\n #Positive result if the lower bound is above zero\r\n if fasymp[1][1] > 0:\r\n pos = pos + 1\r\n \r\n #----------------------------------------------------------------------\r\n #If plotting option was chosen\r\n #----------------------------------------------------------------------\r\n if plot_each:\r\n if fit == \"linear\": \r\n pal.plot_asymptote(xarray, simulated, \r\n limits = [[0,18],[0,1]], \r\n ax_labels = [\"Area (mm$^{2}$)\", \"Accuracy\"],\r\n fit=\"none\",\r\n graph_filename = \"output_none.jpg\")\r\n\r\n pal.plot_asymptote(xarray, simulated, \r\n limits = [[0,18],[0,1]], \r\n ax_labels = [\"Area (mm$^{2}$)\", \"Accuracy\"],\r\n fit=\"linear\",\r\n graph_filename = \"output_linear.jpg\")\r\n \r\n if fit == \"asymptote\":\r\n pal.plot_asymptote(xarray, simulated, \r\n limits = [[0,18],[0,1]], \r\n ax_labels = [\"Area (mm$^{2}$)\", \"Accuracy\"],\r\n fit=\"none\",\r\n graph_filename = \"output_none.jpg\")\r\n\r\n pal.plot_asymptote(xarray, simulated, \r\n limits = [[0,18],[0,1]], \r\n ax_labels = [\"Area (mm$^{2}$)\", \"Accuracy\"],\r\n fit=\"asymptote\",\r\n graph_filename = \"output_linear.jpg\") \r\n #Done with simulations\r\n \r\n #Return the ratio of positive results to total simulations\r\n return pos/simuls", "repo_name": "djarenas/accuracy_asymptote", "sub_path": "asymptote_functions_library.py", "file_name": "asymptote_functions_library.py", "file_ext": "py", "file_size_in_byte": 15385, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "scipy.stats.stats.norm.ppf", "line_number": 32, "usage_type": "call"}, {"api_name": "scipy.stats.stats", "line_number": 32, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 32, "usage_type": "name"}, {"api_name": "scipy.stats.stats.linregress", "line_number": 35, "usage_type": "call"}, {"api_name": "scipy.stats.stats", "line_number": 35, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 35, "usage_type": "name"}, {"api_name": "numpy.exp", "line_number": 74, "usage_type": "call"}, {"api_name": "scipy.optimize.curve_fit", "line_number": 96, "usage_type": "call"}, {"api_name": "scipy.stats.stats.norm.ppf", "line_number": 124, "usage_type": "call"}, {"api_name": "scipy.stats.stats", "line_number": 124, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 124, "usage_type": "name"}, {"api_name": "scipy.optimize.curve_fit", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 167, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 168, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 169, "usage_type": "call"}, {"api_name": "plot_asymptotes_library.plot_asymptote", "line_number": 190, "usage_type": "call"}, {"api_name": "plot_asymptotes_library.plot_asymptote", "line_number": 195, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 255, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 255, "usage_type": "attribute"}, {"api_name": "numpy.vectorize", "line_number": 294, "usage_type": "call"}, {"api_name": "numpy.vectorize", "line_number": 298, "usage_type": "call"}, {"api_name": "plot_asymptotes_library.plot_asymptote", "line_number": 310, "usage_type": "call"}, {"api_name": "plot_asymptotes_library.plot_asymptote", "line_number": 315, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 376, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 388, "usage_type": "call"}, {"api_name": "numpy.vectorize", "line_number": 391, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 400, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 404, "usage_type": "call"}, {"api_name": "plot_asymptotes_library.plot_asymptote", "line_number": 429, "usage_type": "call"}, {"api_name": "plot_asymptotes_library.plot_asymptote", "line_number": 435, "usage_type": "call"}, {"api_name": "plot_asymptotes_library.plot_asymptote", "line_number": 442, "usage_type": "call"}, {"api_name": "plot_asymptotes_library.plot_asymptote", "line_number": 448, "usage_type": "call"}]} +{"seq_id": "21046191987", "text": "from setuptools import setup, find_packages\n\nwith open(\"requirements.txt\") as f:\n\tinstall_requires = f.read().strip().split(\"\\n\")\n\n# get version from __version__ variable in antoryum_gayrimenkul/__init__.py\nfrom antoryum_gayrimenkul import __version__ as version\n\nsetup(\n\tname=\"antoryum_gayrimenkul\",\n\tversion=version,\n\tdescription=\"Antoryum Website & Uygulama\",\n\tauthor=\"Harpiya Software Technologies\",\n\tauthor_email=\"info@harpiya.cloud\",\n\tpackages=find_packages(),\n\tzip_safe=False,\n\tinclude_package_data=True,\n\tinstall_requires=install_requires\n)\n", "repo_name": "harpiyacloud/antoryum_gayrimenkul", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 549, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "setuptools.setup", "line_number": 9, "usage_type": "call"}, {"api_name": "antoryum_gayrimenkul.__version__", "line_number": 11, "usage_type": "name"}, {"api_name": "setuptools.find_packages", "line_number": 15, "usage_type": "call"}]} +{"seq_id": "33450231135", "text": "from aiogram import Dispatcher\nfrom aiogram.types import BotCommand\nfrom loguru import logger\n\ncommands = {\n \"/help\": \"Получить справочник.\",\n \"/settings\": \"Настройки аккаунта\",\n \"/start\": \"Получить клавиатуру|Начать диалог.\",\n}\n\n\nasync def set_bot_commands(dispatcher: Dispatcher):\n await dispatcher.bot.set_my_commands(\n commands=[\n BotCommand(\n command, description\n ) for command, description in commands.items()\n ]\n )\n logger.info(\"Installed bot commands\")\n", "repo_name": "ExissBrr/Telegram-Bot-Template", "sub_path": "utils/misc/set_bot_commands.py", "file_name": "set_bot_commands.py", "file_ext": "py", "file_size_in_byte": 596, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "aiogram.Dispatcher", "line_number": 12, "usage_type": "name"}, {"api_name": "aiogram.types.BotCommand", "line_number": 15, "usage_type": "call"}, {"api_name": "loguru.logger.info", "line_number": 20, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 20, "usage_type": "name"}]} +{"seq_id": "3005241536", "text": "import argparse\r\nimport pathlib\r\nimport os\r\n\r\nparser = argparse.ArgumentParser(description='Training resusable components')\r\nparser.add_argument('--input_path', type=str, help='The text to reverse.')\r\nparser.add_argument('--output_path', type=str, help='Path of the local file where the Output data should be written')\r\nargs = parser.parse_args()\r\n\r\nprint(args.input_path)\r\n\r\nwith open(args.input_path + '.txt', 'r') as input_file:\r\n input_string = input_file.read()\r\n\r\nreversed_string = input_string[::-1]\r\n\r\npath = pathlib.PurePath(args.output_path)\r\nos.makedirs(path.parent)\r\n\r\nwith open(args.output_path + '.txt', 'w') as ouput_file:\r\n ouput_file.write(reversed_string)\r\n", "repo_name": "juansebashr/VertexPipelinesCICD", "sub_path": "src/reverse.py", "file_name": "reverse.py", "file_ext": "py", "file_size_in_byte": 679, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 5, "usage_type": "call"}, {"api_name": "pathlib.PurePath", "line_number": 17, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 18, "usage_type": "call"}]} +{"seq_id": "4631505243", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Forest Fire analysis and prediction\n\n# - Data Collection\n# - Data Pre-Processing\n# - Exploratory Data Analysis\n# - Feature Engineering\n# - Feature Selection\n# - Model Building\n# - Model Selection\n# - Hyperparameter Tuning\n# - Regression\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\n\n\n# In[2]:\n\n\ndata = pd.read_csv(\"./DATA/Algerian_forest_fires_dataset.csv\")\n\n\n# In[3]:\n\n\ndata\n\n\n# In[4]:\n\n\ndata.shape\n\n\n# In[5]:\n\n\ndata.columns\n\n\n# In[6]:\n\n\ndata.head()\n\n\n# In[7]:\n\n\ndata.tail()\n\n\n# In[8]:\n\n\ndata.describe()\n\n\n# In[9]:\n\n\ndata.info()\n\n\n# In[10]:\n\n\ndata.day.unique()\n\n\n# In[11]:\n\n\ndata[data.isnull().any(axis=1)] # inorder to check the row which is having the missing values\n\n\n# # Here after 123 we have the data set of new region\n\n# In[12]:\n\n\ndata.loc[:122,'Region']=1 #upto 122 ,Region =1 but intialize as 1.0\ndata.loc[122:,'Region']=2 #After 122 , Region = 2 this as 2.0\ndata[['Region']] = data[['Region']].astype(int) #1.0 is coverted to 1 astype integer\n#It is used to convert the data in the \"Region\" column of a pandas DataFrame to integer type.\ndata.head()\n\n\n# In[13]:\n\n\ndata.tail()\n\n\n# In[14]:\n\n\ndata.drop([122,123,168], axis=0, inplace=True)#.reset_index(drop=True)\ndata.day.unique()\n# Drop rows at index labels 122 and 123,168\n\n\n# In[15]:\n\n\nfiltered_rows = data[data['day'] == 'day']\nfiltered_rows\n\n\n# In[16]:\n\n\ndata.drop([124], axis=0, inplace=True)#.reset_index(drop=True)\ndata.day.unique()\n\n\n# In[17]:\n\n\ndata.shape\n\n\n# In[18]:\n\n\ndata.month.unique()\n\n\n# In[19]:\n\n\ndata.year.unique()\n\n\n# In[20]:\n\n\ndata.columns.unique()\n\n\n# In[21]:\n\n\ndata\n\n\n# In[22]:\n\n\ndata.shape\n\n\n# In[23]:\n\n\ndata.columns\n\n\n# In[24]:\n\n\n# Spaces were fixed in the column names\n# The str.strip() function is applied to each column name using the str accessor, which allows you to perform string operations on the elements of a column.\n# After applying the strip() function, the modified column names are assigned back to the data.columns attribute, updating the column names in the DataFrame.\ndata.columns = data.columns.str.strip()\ndata.columns \n\n\n# In[25]:\n\n\ndata.isna().sum()\n\n\n# In[26]:\n\n\ndata.reset_index()\n\n\n# In[27]:\n\n\ndata.reset_index(drop=True, inplace=True)\ndata\n\n\n# In[28]:\n\n\n# Check if the default index is in proper format without gaps\nis_proper_index = data.index.equals(pd.RangeIndex(len(data)))\n\nprint(is_proper_index)\n\n\n# \n\n# In[29]:\n\n\ndata.isna().sum()\n\n\n# In[30]:\n\n\nprint(data.duplicated())\nprint(data[data.duplicated()])\n\n\n# In[31]:\n\n\ndata.shape\n\n\n# ### ANALYSE\n\n# In[32]:\n\n\ndata.describe(include = 'all')\n\n\n# In[33]:\n\n\ndata[\"Classes\"].value_counts()\n\n\n# our dependent feature(Classes) containig only two categories but due to misspace it is showing multiple category so need to change the spaceing in order to make two category\n\n# In[34]:\n\n\ndata.Classes = data.Classes.str.strip()\n\n\n# In[35]:\n\n\ndata[\"Classes\"].value_counts()\n\n\n# In[36]:\n\n\ndata[\"Region\"].value_counts()\n\n\n# In[37]:\n\n\ndata.describe(include='all')\n\n\n# In[38]:\n\n\ndata[['month', 'day', 'year', 'Temperature', 'RH', 'Ws']] = data[['month', 'day', 'year', 'Temperature', 'RH', 'Ws']].astype(int)\n\nobjects = [features for features in data.columns if data[features].dtypes == 'O'] #\"o\" object type\nfor i in objects:\n if i != 'Classes': #exxcept classes\n data[i] = data[i].astype(float)\n\n\n# In[39]:\n\n\nprint(data.dtypes)\n\n\n# In pandas, the object data type is commonly used to represent categorical data. While the object data type can also be used to store other types of data (such as strings), it is often used to represent variables with a limited number of discrete categories or labels.\n\n# In[40]:\n\n\ndata.describe(include=\"all\")\n\n\n# In[41]:\n\n\ndata[:122]\n\n\n# In[42]:\n\n\ndata[122:]\n\n\n# In[43]:\n\n\n# Encoding Not fire as 0 and Fire as 1\ndata['Classes']= np.where(data['Classes']== 'not fire',0,1)\ndata.head(10)\n#If the condition is true, \n# the corresponding element in the 'Classes' column is assigned the value 0.\n# Otherwise, it is assigned the value 1.\n\n\n# In[44]:\n\n\ndata.tail()\n\n\n# In[45]:\n\n\n# Check counts\ndata.Classes.value_counts()\n\n\n# In[46]:\n\n\ncorrelation = data.corr()\ncorrelation\n\n\n# The value of correlation helps in determining the strength and direction of the relationship between two variables. When using correlation for feature selection, the value of correlation can guide you in selecting relevant features\n\n# # Visualize\n\n# In[47]:\n\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n# In[48]:\n\n\nplt.figure(figsize=(20,15)) #size of figure\nsns.heatmap(correlation,annot= True,linewidths=1, linecolor=\"white\", cbar=True, cmap = \"Paired\",xticklabels=\"auto\", yticklabels=\"auto\")\n \n\n\n# In[49]:\n\n\ndata.to_csv('./DATA/ForestFireDataCleaned.csv', index=False)\n\n\n# In[50]:\n\n\nsns.countplot(x='Classes',data=data)\nplt.title('Class Distributions \\n 0: No Fire || 1: Fire', fontsize=14)\nplt.show()\n\n\n# In[51]:\n\n\nsns.countplot(x='Region',hue='Classes',data=data)\nplt.title('Region Distributions \\n 1: Region 1 || 2: Region 2', fontsize=14)\nplt.show()\n\n\n# In[52]:\n\n\n# PLot density plot for all features\n#plt.style.use('seaborn')\ndata.hist(bins=50, figsize=(20,15), ec = 'b')\nplt.show()\n\n\n# In[53]:\n\n\n# countplot over target variable\n\nsns.countplot(x='Temperature',hue='Classes', data=data)\nplt.title('Class Distribution \\n 0: No Fire || 1: Fire', fontsize=14)\n\n\n# In[54]:\n\n\ndata.month.unique()\n\n\n# In[55]:\n\n\n#month wise fire analysis for region 1\ndftemp= data.loc[data['Region']== 1]\nplt.subplots(figsize=(13,6))\nsns.set_style('whitegrid')\nsns.countplot(x='month',hue='Classes',data= dftemp,ec = 'black', palette= 'Set2')#ec='black' sets the edge color of the categorical plot elements to black, and palette='Set2' sets the color palette to the 'Set2' palette.\nplt.title('Fire Analysis Month wise for Region-1', fontsize=18, weight='bold')\nplt.ylabel('Count', weight = 'bold')\nplt.xlabel('Months', weight= 'bold')\nplt.legend(loc='upper right')\nplt.xticks(np.arange(4), ['June','July', 'August', 'September',])\nplt.grid(alpha = 0.5,axis = 'y')\nplt.show()\n\n\n# In[56]:\n\n\n#month wise fire analysis for region 2\ndftemp= data.loc[data['Region']== 2]\nplt.subplots(figsize=(13,6))\nsns.set_style('whitegrid')\nsns.countplot(x='month',hue='Classes',data= dftemp,ec = 'black', palette= 'Set2')#ec='black' sets the edge color of the categorical plot elements to black, and palette='Set2' sets the color palette to the 'Set2' palette.\nplt.title('Fire Analysis Month wise for Region-2', fontsize=18, weight='bold')\nplt.ylabel('Count', weight = 'bold')\nplt.xlabel('Months', weight= 'bold')\nplt.legend(loc='upper right')\nplt.xticks(np.arange(4), ['June','July', 'August', 'September',])\nplt.grid(alpha = 0.5,axis = 'y')\nplt.show()\n\n\n# Yearly plot\n\n# In[57]:\n\n\nplt.subplots(figsize=(13,6))\nsns.set_style('whitegrid')\nsns.countplot(x='year',hue='Classes',data= data,ec = 'black', palette= 'Set2')#ec='black' sets the edge color of the categorical plot elements to black, and palette='Set2' sets the color palette to the 'Set2' palette.\nplt.title('Fire Analysis of Year 2012', fontsize=18, weight='bold')\nplt.ylabel('Count', weight = 'bold')\nplt.xlabel('Year', weight= 'bold')\nplt.legend(loc='upper right')\nplt.grid(alpha = 0.5,axis = 'y')\nplt.show()\n\n\n# In[58]:\n\n\n# ! pip install scikit-learn\n\n\n# In[59]:\n\n\nplt.subplots(figsize=(15,6))\nsns.set_style('whitegrid')\nsns.countplot(x='Rain', hue='Classes', data=data)\n\n# Set the labels and title\nplt.xlabel('Rain')\nplt.ylabel('Count')\nplt.title('Distribution of Classes by Rain')\n\n# Show the plot\nplt.show()\n\n\n# ### With the increase in Rain Fire chance is descreases\n\n# In[60]:\n\n\nplt.subplots(figsize=(15,6))\nsns.set_style('whitegrid')\nsns.countplot(x='Ws', hue='Classes', data=data)\n\n# Set the labels and title\nplt.xlabel('WS')\nplt.ylabel('Count')\nplt.title('Distribution of Classes by Wind Speed:6 to 29')\n\n# Show the plot\nplt.show()\n\n\n# In[61]:\n\n\nplt.subplots(figsize=(15,6))\nsns.set_style('whitegrid')\nsns.countplot(x='RH', hue='Classes', data=data)\n\n# Set the labels and title\nplt.xlabel('RH')\nplt.ylabel('Count')\nplt.title('Distribution of Classes by humidity rate')\n\n# Show the plot\nplt.show()\n\n\n# In[62]:\n\n\nplt.subplots(figsize=(15,6))\nsns.set_style('whitegrid')\nsns.countplot(x='month', hue='Classes', data=data)\n\n# Set the labels and title\nplt.xlabel('Month')\nplt.ylabel('Count')\nplt.title('Distribution of Classes by Month')\n\n# Show the plot\nplt.show()\n\n\n# In[63]:\n\n\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\n\n# Assuming 'data' is the DataFrame containing the dataset\n# Splitting the features and target variable\nX = data.drop('Classes', axis=1)\ny = data['Classes']\n\n# Calculate the correlation matrix\ncorrelation_matrix = X.corr()\n\n# Display the correlation matrix\nprint(correlation_matrix)\n\n# Train a Random Forest classifier\nrfmodel = RandomForestClassifier()\nrfmodel.fit(X, y)\n\n# Get feature importances\nfeature_importances = pd.Series(rfmodel.feature_importances_, index=X.columns).sort_values(ascending=False)\n\n# Display feature importances\nprint(feature_importances)\n\n\n# In[64]:\n\n\nplt.subplots(figsize=(18,10))\n\nsns.heatmap(correlation_matrix , annot=True, cmap=plt.cm.CMRmap_r)\nplt.show()\n\n\n# From above anlysis we find some non importance features:\n# - Year (due to missing values)\n# - Ws (wind speed) low correlation\n# - DAY(low corr)\n# - Month(low corr)\n\n# In[65]:\n\n\ndf = data.drop(['day','month','year','Ws'], axis=1)\ndf.head(10)\n\n\n# Spliting Data Set \n\n# In[66]:\n\n\nfrom sklearn.model_selection import train_test_split\n\n\n# In[67]:\n\n\ny = df['Classes']\nX = df.drop('Classes',axis=1)\ny.tail()\n\n\n# In[68]:\n\n\nX.head()\n\n\n# In[69]:\n\n\nX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42)\nX_train.head()\n\n\n# In[70]:\n\n\nX_train.info()\n\n\n# In[71]:\n\n\ndel data,X,y,df\n\n\n# In[72]:\n\n\nfrom sklearn.model_selection import GridSearchCV\n#TRain Function is defined\ndef train(X_train, y_train, model, hyperparameters):\n grid_search = GridSearchCV(estimator=model,param_grid=hyperparameters, cv = 5)\n grid_search.fit(X_train, y_train)\n \n \n #print the best hyperparameters found\n best_params = grid_search.best_params_\n print(\"Best Hyperparameters:\", best_params)\n \n # Train the model with best hyperparametres\n best_model = model.set_params(**best_params)\n best_model.fit(X_train, y_train)\n\n # Print the intercept and coefficients of the best model\n # print('Intercept is :', best_model.best_estimator_.intercept_)\n # print('Coefficient is :', best_model.best_estimator_.coef_)\n\n # Evaluate the best model on the test data\n scores = best_model.score(X_test, y_test)\n print('Score_test_data:', scores)\n \n return best_params, best_model\n\n\n# In[73]:\n\n\nfrom sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n\n# EVALUATION\n\ndef evaluate_model(X_test, y_test, best_model):\n # it will evaluate the score by taking testing data with best model\n \n #predict the target values for the best set\n y_pred = best_model.predict(X_test)\n \n # Calculate the MSE\n mse = mean_squared_error(y_test, y_pred)\n\n# Calculate the R-squared\n r2 = r2_score(y_test, y_pred)\n\n# Calculate the adjusted R-squared\n # adjusted_r2 = adjusted_r2_score(y_test, y_pred)\n\n# Calculate the MAE\n mae = mean_absolute_error(y_test, y_pred)\n\n# Print the scores\n print(\"MSE:\", mse)\n print(\"R-squared:\", r2)\n # print(\"Adjusted R-squared:\", adjusted_r2)\n print(\"MAE:\", mae)\n\n return mse,r2,mae\n\n\n# # Linear Regression\n\n# In[74]:\n\n\nfrom sklearn.linear_model import LinearRegression\n# Define the hyperparameters to tune\nhyperparameters = {\n # \"regularization\": [\"l1\", \"l2\"],\n # \"learning_rate\": [0.01, 0.001, 0.0001],\n # \"number_of_epochs\": [10, 50, 100],\n}\nmodel = LinearRegression()\n_,best_model = train(X_train,y_train,model,hyperparameters)\n# print('Intercept is :',best_model.intercept_)\n# print('Coefficient is :',best_model.coef_)\nscores = evaluate_model(X_test,y_test,best_model) \n\n\n# # Ridge\n\n# In[75]:\n\n\nfrom sklearn.linear_model import Ridge\n# Define the hyperparameters to tune\nhyperparameters = {\n \"alpha\": np.logspace(-4, 4, 10),\n}\n\n# Create a Ridge model\nmodel = Ridge()\n_,best_model = train(X_train,y_train,model,hyperparameters)\nscores = evaluate_model(X_test,y_test,best_model) \n\n\n\n# # Lasso\n\n# In[76]:\n\n\nfrom sklearn.linear_model import Lasso\n# Define the hyperparameters to tune\nhyperparameters = {\n \"alpha\": np.logspace(-4, 4, 10),\n}\n\n# Create a Lasso model\nmodel = Lasso()\n_,best_model = train(X_train,y_train,model,hyperparameters)\nscores = evaluate_model(X_test,y_test,best_model) \n\n\n\n# # Decision Tree\n\n# In[77]:\n\n\nfrom sklearn.tree import DecisionTreeRegressor\n# Define the hyperparameters to tune\nhyperparameters = {\n \"max_depth\": [3, 5, 10],\n \"min_samples_split\": [2, 5, 10],\n}\n\n# Create a decision tree regressor\nmodel = DecisionTreeRegressor()\n_,best_model = train(X_train,y_train,model,hyperparameters)\nscores = evaluate_model(X_test,y_test,best_model) \n\n\n\n# In[78]:\n\n\nimport matplotlib.pyplot as plt\n\n# Scores of each model\nlinear_score = 0.6840775270198252\nlasso_score = 0.6695115483312191 \nridge_score = 0.6753837888234437\ndecision_tree_score = 0.9861363636363636\n\n# Models names\nmodels = ['Linear Regression', 'Lasso', 'Ridge', 'Decision Tree']\n\n# Scores for each model\nscores = [linear_score, lasso_score, ridge_score, decision_tree_score]\n\n# Plotting the scores\nplt.bar(models, scores)\nplt.title('Comparison of Model Scores')\nplt.xlabel('Models')\nplt.ylabel('Scores')\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n", "repo_name": "Ashimeon/DATA-SCIENCE", "sub_path": "ForestFireAnalysis (1).py", "file_name": "ForestFireAnalysis (1).py", "file_ext": "py", "file_size_in_byte": 13470, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pandas.read_csv", "line_number": 26, "usage_type": "call"}, {"api_name": "pandas.RangeIndex", "line_number": 198, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 305, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 346, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 346, "usage_type": "name"}, {"api_name": "seaborn.heatmap", "line_number": 347, "usage_type": "call"}, {"api_name": "seaborn.countplot", "line_number": 360, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 361, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 361, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 362, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 362, "usage_type": "name"}, {"api_name": "seaborn.countplot", "line_number": 368, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 369, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 369, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 370, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 370, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 379, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 379, "usage_type": "name"}, {"api_name": "seaborn.countplot", "line_number": 387, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 388, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 388, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 402, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 402, "usage_type": "name"}, {"api_name": "seaborn.set_style", "line_number": 403, "usage_type": "call"}, {"api_name": "seaborn.countplot", "line_number": 404, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 405, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 405, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 406, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 406, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 407, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 407, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 408, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 408, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 409, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 409, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 409, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 410, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 410, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 411, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 411, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 419, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 419, "usage_type": "name"}, {"api_name": "seaborn.set_style", "line_number": 420, "usage_type": "call"}, {"api_name": "seaborn.countplot", "line_number": 421, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 422, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 422, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 423, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 423, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 424, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 424, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 425, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 425, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 426, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 426, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 426, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 427, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 427, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 428, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 428, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 436, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 436, "usage_type": "name"}, {"api_name": "seaborn.set_style", "line_number": 437, "usage_type": "call"}, {"api_name": "seaborn.countplot", "line_number": 438, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 439, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 439, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 440, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 440, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 441, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 441, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 442, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 442, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 443, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 443, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 444, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 444, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 456, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 456, "usage_type": "name"}, {"api_name": "seaborn.set_style", "line_number": 457, "usage_type": "call"}, {"api_name": "seaborn.countplot", "line_number": 458, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 461, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 461, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 462, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 462, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 463, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 463, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 466, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 466, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 474, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 474, "usage_type": "name"}, {"api_name": "seaborn.set_style", "line_number": 475, "usage_type": "call"}, {"api_name": "seaborn.countplot", "line_number": 476, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 479, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 479, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 480, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 480, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 481, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 481, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 484, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 484, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 490, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 490, "usage_type": "name"}, {"api_name": "seaborn.set_style", "line_number": 491, "usage_type": "call"}, {"api_name": "seaborn.countplot", "line_number": 492, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 495, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 495, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 496, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 496, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 497, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 497, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 500, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 500, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 506, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 506, "usage_type": "name"}, {"api_name": "seaborn.set_style", "line_number": 507, "usage_type": "call"}, {"api_name": "seaborn.countplot", "line_number": 508, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 511, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 511, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 512, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 512, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 513, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 513, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 516, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 516, "usage_type": "name"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 537, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 541, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 550, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 550, "usage_type": "name"}, {"api_name": "seaborn.heatmap", "line_number": 552, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 552, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 552, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 553, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 553, "usage_type": "name"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 594, "usage_type": "call"}, {"api_name": "sklearn.model_selection.GridSearchCV", "line_number": 616, "usage_type": "call"}, {"api_name": "sklearn.metrics.mean_squared_error", "line_number": 653, "usage_type": "call"}, {"api_name": "sklearn.metrics.r2_score", "line_number": 656, "usage_type": "call"}, {"api_name": "sklearn.metrics.mean_absolute_error", "line_number": 662, "usage_type": "call"}, {"api_name": "sklearn.linear_model.LinearRegression", "line_number": 685, "usage_type": "call"}, {"api_name": "numpy.logspace", "line_number": 700, "usage_type": "call"}, {"api_name": "sklearn.linear_model.Ridge", "line_number": 704, "usage_type": "call"}, {"api_name": "numpy.logspace", "line_number": 718, "usage_type": "call"}, {"api_name": "sklearn.linear_model.Lasso", "line_number": 722, "usage_type": "call"}, {"api_name": "sklearn.tree.DecisionTreeRegressor", "line_number": 741, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 765, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 765, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 766, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 766, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 767, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 767, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 768, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 768, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 769, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 769, "usage_type": "name"}]} +{"seq_id": "73777497342", "text": "from model import areaXYDao\nfrom service.api.sensibletemperature.formatConvertor import formatConvertor\nfrom service.api.sensibletemperature.sensibleTemperatureApi import sensibleTemperatureApi\nfrom datetime import datetime, timedelta\n\nfrom service.api.shorttermforecast.ForecastTypeEnum import ForecastType\nfrom service.api.shorttermforecast.shortTermWeatherForecastApi import ShortTermWeatherForecastApi\nfrom service.util.definitionRisk import check_risk\n\n\ndef get_today_minus_1():\n convertor = formatConvertor()\n today = convertor.datetime_to_string(datetime.today() - timedelta(hours=1))\n return today\n\n\n\ndef get_SKY_PTY_T1H_in_short_term_forecast(x=37, y=126):\n today = get_today_minus_1()\n ymd = today[0:6]\n time = today[6:] + '00'\n api = ShortTermWeatherForecastApi(x, y, ymd, time) # API 기본 Configuration (x, y, 검색날짜, 검색시간)\n response = api.request_api() # response 값 API 요청\n SKY = api.find_category_from_response(response,\n ForecastType.SKY.name) # response 값에서 카테고리에 따른 값 (카테고리 확인 : ForecastTypeEnum), Default=RN1\n\n PTY = api.find_category_from_response(response,\n ForecastType.PTY.name) # response 값에서 카테고리에 따른 값 (카테고리 확인 : ForecastTypeEnum), Default=RN1\n T1H = api.find_category_from_response(response,\n ForecastType.T1H.name) # response 값에서 카테고리에 따른 값 (카테고리 확인 : ForecastTypeEnum), Default=RN1\n return SKY, PTY, T1H\n\n\ndef get_sensible_temp_present(time_range):\n convertor = formatConvertor()\n today = get_today_minus_1()\n\n api = sensibleTemperatureApi(today) # api configuration\n response = api.request_api() # api 신청\n convertor.setData(response) # 컨버터 등록\n response = convertor.execute() # 컨버터 실행\n\n return convertor.get_predict_list_data(time_range, today)\n\n\ndef get_info_from_address(address): # 구, 동 으로 정보를 찾아냄. 정보가 없으면 구로만 검색한 결과를 뿌려줌\n addList = address.split(' ')\n gu, dong = addList[1], addList[2]\n return areaXYDao.findareaXYBygudong(gu, dong)\n\n\ndef check_weather(data):\n return check_risk(data)\n\n\nif __name__ == '__main__':\n print(get_info_from_address(address=\"제주특별자치도 서귀포시 가가로 14\"))\n get_sensible_temp_present(6)\n", "repo_name": "JangDongHa/miniProject_1week", "sub_path": "service/tempService.py", "file_name": "tempService.py", "file_ext": "py", "file_size_in_byte": 2478, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "service.api.sensibletemperature.formatConvertor.formatConvertor", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.datetime.today", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 13, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 13, "usage_type": "call"}, {"api_name": "service.api.shorttermforecast.shortTermWeatherForecastApi.ShortTermWeatherForecastApi", "line_number": 22, "usage_type": "call"}, {"api_name": "service.api.shorttermforecast.ForecastTypeEnum.ForecastType.SKY", "line_number": 25, "usage_type": "attribute"}, {"api_name": "service.api.shorttermforecast.ForecastTypeEnum.ForecastType", "line_number": 25, "usage_type": "name"}, {"api_name": "service.api.shorttermforecast.ForecastTypeEnum.ForecastType.PTY", "line_number": 28, "usage_type": "attribute"}, {"api_name": "service.api.shorttermforecast.ForecastTypeEnum.ForecastType", "line_number": 28, "usage_type": "name"}, {"api_name": "service.api.shorttermforecast.ForecastTypeEnum.ForecastType.T1H", "line_number": 30, "usage_type": "attribute"}, {"api_name": "service.api.shorttermforecast.ForecastTypeEnum.ForecastType", "line_number": 30, "usage_type": "name"}, {"api_name": "service.api.sensibletemperature.formatConvertor.formatConvertor", "line_number": 35, "usage_type": "call"}, {"api_name": "service.api.sensibletemperature.sensibleTemperatureApi.sensibleTemperatureApi", "line_number": 38, "usage_type": "call"}, {"api_name": "model.areaXYDao.findareaXYBygudong", "line_number": 49, "usage_type": "call"}, {"api_name": "model.areaXYDao", "line_number": 49, "usage_type": "name"}, {"api_name": "service.util.definitionRisk.check_risk", "line_number": 53, "usage_type": "call"}]} +{"seq_id": "157080379", "text": "import json\nimport datetime\nimport socket\nimport requests\n\nclass TimeShift(object):\n\tdef __init__(self):\n\t\ts=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n\t\ts.connect(('8.8.8.8',80))\n\t\tself.address=s.getsockname()[0]\n\n\t\t'''SAVING NEXT PROCESSING TIME FOR EACH PATIENT'''\n\t\tself.scheduling={\n\t\t\"2\":[],\n\t\t\"3\":[],\n\t\t\"4\":[],\n\t\t\"5\":[],\n\t\t}\n\n\t\t#self.catalog=\"http://192.168.1.103:8080\"\n\t\tself.catalog=json.loads(open(\"catalog.json\").read())[\"catalog\"]\n\t\t'''\n\t\tself.my_data={\n\t\t\"time_shift\":\n\t\t{\t\n\t\t\"ip\":socket.gethostbyname(socket.gethostname()),\n\t\t\"port\":8087\n\t\t}\n\t\t}'''\n\t\tself.my_data=json.loads(open(\"timeShiftData.json\").read())\n\t\tself.my_data[\"time_shift\"][\"ip\"]=self.address\n\n\tdef getAddress(self):\n\t\treturn self.address\n\n\tdef getData(self):\n\t\treturn self.my_data\n\n\tdef setData(self,data):\n\t\tself.ip_others=data\n\n\n\tdef configure(self):\n\t\tself.result=requests.post(self.catalog,json.dumps(self.my_data))\n\t\tself.ip_others=self.result.json()\n\n\tdef sendAlert(self):\n\n\t\tfor key in self.scheduling.keys():\n\t\t\tif(key==\"2\"):\n\t\t\t\tfor elem in self.scheduling[key]:\n\t\t\t\t\tif((datetime.datetime.now()-datetime.datetime.strptime(elem[\"last_measurement\"],'%Y-%m-%d %H:%M:%S')).total_seconds()>=60):\n\t\t\t\t\t\tr=requests.get(\"http://\"+self.ip_others[\"queue_server\"][0]+\":\"+self.ip_others[\"queue_server\"][1]+\"/retrieve?pressure_id=\"+elem[\"pressure_id\"]+\"&heart_id=\"+elem[\"heart_id\"]+\"&glucose_id=\"+elem[\"glucose_id\"])\n\t\t\telif(key==\"3\"):\n\t\t\t\tfor elem in self.scheduling[key]:\n\t\t\t\t\tif((datetime.datetime.now()-datetime.datetime.strptime(elem[\"last_measurement\"],'%Y-%m-%d %H:%M:%S')).total_seconds()>=240):\n\t\t\t\t\t\tr=requests.get(\"http://\"+self.ip_others[\"queue_server\"][0]+\":\"+self.ip_others[\"queue_server\"][1]+\"/retrieve?pressure_id=\"+elem[\"pressure_id\"]+\"&heart_id=\"+elem[\"heart_id\"]+\"&glucose_id=\"+elem[\"glucose_id\"])\n\t\t\telif(key==\"4\"):\n\t\t\t\tfor elem in self.scheduling[key]:\n\t\t\t\t\tif((datetime.datetime.now()-datetime.datetime.strptime(elem[\"last_measurement\"],'%Y-%m-%d %H:%M:%S')).total_seconds()>=480):\n\t\t\t\t\t\tr=requests.get(\"http://\"+self.ip_others[\"queue_server\"][0]+\":\"+self.ip_others[\"queue_server\"][1]+\"/retrieve?pressure_id=\"+elem[\"pressure_id\"]+\"&heart_id=\"+elem[\"heart_id\"]+\"&glucose_id=\"+elem[\"glucose_id\"])\n\t\t\telif(key==\"5\"):\n\t\t\t\tfor elem in self.scheduling[key]:\n\t\t\t\t\tif((datetime.datetime.now()-datetime.datetime.strptime(elem[\"last_measurement\"],'%Y-%m-%d %H:%M:%S')).total_seconds()>=960):\n\t\t\t\t\t\tr=requests.get(\"http://\"+self.ip_others[\"queue_server\"][0]+\":\"+self.ip_others[\"queue_server\"][1]+\"/retrieve?pressure_id=\"+elem[\"pressure_id\"]+\"&heart_id=\"+elem[\"heart_id\"]+\"&glucose_id=\"+elem[\"glucose_id\"])\n\n\t\n\tdef addToScheduling(self, data):\n\t\tdata=json.loads(data)\n\t\tobj={\n\t\t\"pressure_id\":data[\"pressure_id\"],\n\t\t\"heart_id\":data[\"heart_id\"],\n\t\t\"glucose_id\":data[\"glucose_id\"],\n\t\t\"last_measurement\":data[\"time_stamp\"]\n\t\t}\n\n\t\tself.scheduling[data[\"code\"]].append(obj)\n\n\tdef removeFromScheduling(self,code,pressure_id,heart_id,glucose_id):\n\t\tfor i in range(len(self.scheduling[str(code)])):\n\t\t\tif(self.scheduling[str(code)][i][\"pressure_id\"]==pressure_id and self.scheduling[str(code)][i][\"heart_id\"]==heart_id and self.scheduling[str(code)][i][\"glucose_id\"]==glucose_id):\n\t\t\t\tdel self.scheduling[str(code)][i]\n\n", "repo_name": "alessandrobaldo/IoTProject", "sub_path": "Code/Timer/TimeShift.py", "file_name": "TimeShift.py", "file_ext": "py", "file_size_in_byte": 3203, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "socket.socket", "line_number": 8, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 8, "usage_type": "attribute"}, {"api_name": "socket.SOCK_DGRAM", "line_number": 8, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 21, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 30, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 44, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 44, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 52, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 52, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 52, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 53, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 56, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 56, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 56, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 57, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 60, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 60, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 60, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 61, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 64, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 64, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 64, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 65, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 69, "usage_type": "call"}]} +{"seq_id": "33196846487", "text": "import pytest\r\nfrom UI_test.UI_Test_3.MY_python_pytest.src.common.webdriver_handler import WebDriverHandler\r\n\r\n\r\n@pytest.fixture(scope=\"function\")\r\ndef webdriver_handler():\r\n webdriver=WebDriverHandler()\r\n webdriver.setup()\r\n yield webdriver\r\n webdriver.quit()\r\n", "repo_name": "vaniffatiy/UI_Test_3", "sub_path": "MY_python_pytest/src/conftest.py", "file_name": "conftest.py", "file_ext": "py", "file_size_in_byte": 274, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "UI_test.UI_Test_3.MY_python_pytest.src.common.webdriver_handler.WebDriverHandler", "line_number": 7, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 5, "usage_type": "call"}]} +{"seq_id": "17303629959", "text": "from django.shortcuts import render, redirect, reverse\nfrom django.contrib import messages\nfrom .forms import ContactForm\n\n\n# Create your views here.\ndef contact(request):\n \"\"\" A view to show the contact page form \"\"\"\n\n if request.method == 'POST':\n form_data = {\n 'name': request.POST['name'],\n 'email': request.POST['email'],\n 'message': request.POST['message'],\n }\n contact_form = ContactForm(form_data)\n\n if contact_form.is_valid():\n contact_form.save()\n messages.success(request, 'Message sent successfully!')\n return redirect(reverse('contact'))\n else:\n messages.error(request, 'Message failed to send. Check if form is valid.')\n else:\n contact_form = ContactForm()\n\n context = {\n 'contact_form': contact_form,\n }\n\n return render(request, 'contact/contact.html', context)\n", "repo_name": "oksanaokhten/ambrosia", "sub_path": "contact/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 922, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "forms.ContactForm", "line_number": 16, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 20, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 20, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 21, "usage_type": "call"}, {"api_name": "django.shortcuts.reverse", "line_number": 21, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 23, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 23, "usage_type": "name"}, {"api_name": "forms.ContactForm", "line_number": 25, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "38164832642", "text": "import asyncio\nimport re\n\nimport socks_client.tcp_async as socks\n\n\nasync def tcp_client_through_socks(proxy_host, proxy_port, target_host, target_port):\n tcp_socks = socks.socksocket(\n proxy_type=socks.SOCKS5,\n proxy_host=proxy_host,\n proxy_port=proxy_port,\n username=\"my_username\",\n password=\"my_password\",\n rdns=False,\n )\n await tcp_socks.settimeout(5)\n sock = await tcp_socks.connect(dest_host=target_host, dest_port=target_port)\n\n reader, writer = await asyncio.open_connection(\n host=None,\n port=None,\n sock=sock,\n )\n request = (\n b\"GET / HTTP/1.1\\r\\n\" b\"Host: ip.sb\\r\\n\" b\"User-Agent: curl/7.64.0\\r\\n\\r\\n\"\n )\n writer.write(request)\n\n response = await asyncio.wait_for(reader.read(1024), timeout=1)\n\n response_headers = response.decode(\"utf-8\")\n ip_address = re.search(\n r\"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\", response_headers\n ).group()\n print(ip_address)\n\n\nasync def main():\n proxy_host = \"\"\n proxy_port = 1080\n target_host = \"ip.sb\"\n target_port = 80\n\n await tcp_client_through_socks(proxy_host, proxy_port, target_host, target_port)\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n", "repo_name": "plattanus/socks-client", "sub_path": "try_tcp_async.py", "file_name": "try_tcp_async.py", "file_ext": "py", "file_size_in_byte": 1229, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "socks_client.tcp_async.socksocket", "line_number": 8, "usage_type": "call"}, {"api_name": "socks_client.tcp_async", "line_number": 8, "usage_type": "name"}, {"api_name": "socks_client.tcp_async.SOCKS5", "line_number": 9, "usage_type": "attribute"}, {"api_name": "socks_client.tcp_async", "line_number": 9, "usage_type": "name"}, {"api_name": "asyncio.open_connection", "line_number": 19, "usage_type": "call"}, {"api_name": "asyncio.wait_for", "line_number": 29, "usage_type": "call"}, {"api_name": "re.search", "line_number": 32, "usage_type": "call"}, {"api_name": "asyncio.run", "line_number": 48, "usage_type": "call"}]} +{"seq_id": "25579514405", "text": "from tensorflow.keras.models import load_model\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.model_selection import train_test_split\r\nfrom skimage import io,transform #skimage模块下的io transform(图像的形变与缩放)模块\r\nimport glob #glob 文件通配符模块\r\nimport os #os 处理文件和目录的模块\r\nfrom sklearn.utils import shuffle\r\nimport scipy.io as sio\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\nimport pickle\r\nimport scipy.io as scio\r\nimport numpy as np\r\ndef load_dataset():\r\n def read_img(path):\r\n w = 64\r\n h = 64\r\n c = 3\r\n cate = [path + x for x in os.listdir(path) if os.path.isdir(path + x)]\r\n print(os.listdir(path))\r\n print(cate)\r\n imgs = []\r\n labels = []\r\n for idx, folder in enumerate(cate):\r\n for im in glob.glob(folder + '/*.png'):\r\n img = io.imread(im)\r\n img = transform.resize(img, (w, h))\r\n imgs.append(img)\r\n labels.append(idx)\r\n return np.asarray(imgs, np.float32), np.asarray(labels, np.int32)\r\n\r\n data, label = read_img('new_3/')\r\n data, label = shuffle(data, label)\r\n\r\n def normalization(data):\r\n _range = np.max(data) - np.min(data)\r\n return (data - np.min(data)) / _range\r\n\r\n data = normalization(data) # data / 255\r\n X_train, X_test, y_train, y_test = train_test_split(data, label, random_state=42, test_size=0.2)\r\n return X_test, y_test\r\n\r\n\r\nfrom sklearn.manifold import TSNE\r\n\r\n\r\ndef visualize(embedding, value):\r\n z = TSNE(n_components=2).fit_transform(embedding.detach().cpu().numpy())\r\n plt.figure(figsize=(16, 12))\r\n plt.xticks([])\r\n plt.yticks([])\r\n plt.scatter(z[:, 0], z[:, 1], s=30, c=value, cmap=\"Set2\", zorder=2)\r\n plt.show()\r\n\r\n\r\ndef eeg_test():\r\n X_test, y_test = load_dataset()\r\n output_dir = 'models/gai11'\r\n encoder = load_model(join(output_dir, 'encoder.h5'))\r\n x_preds = encoder.predict(X_test)\r\n #y_preds = encoder.predict(y_test)\r\n print('x_preds:', x_preds.shape)\r\n print('y_test:', y_test.shape)\r\n scio.savemat(r'D:\\contrastive-predictive-coding-master\\result_xy11tu.mat',\r\n {'matrix_1':x_preds,'matrix_2':y_test})\r\n # pca = PCA(n_components=4)\r\n # projected_config = pca.fit_transform(x_preds)\r\n # plt.scatter(projected_config[:, 0], projected_config[:, 1], c=)\r\n # plt.colorbar()\r\n# model.eval()\r\n# out = model(data.x)\r\n visualize(x_preds, color = y_test)\r\neeg_test()\r\n", "repo_name": "yanyy202108/CPC-EEG", "sub_path": "CPC-EEG/test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 2553, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "os.listdir", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 22, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 27, "usage_type": "call"}, {"api_name": "skimage.io.imread", "line_number": 28, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 28, "usage_type": "name"}, {"api_name": "skimage.transform.resize", "line_number": 29, "usage_type": "call"}, {"api_name": "skimage.transform", "line_number": 29, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 32, "usage_type": "attribute"}, {"api_name": "numpy.int32", "line_number": 32, "usage_type": "attribute"}, {"api_name": "sklearn.utils.shuffle", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 39, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 42, "usage_type": "call"}, {"api_name": "sklearn.manifold.TSNE", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 53, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 53, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "tensorflow.keras.models.load_model", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 61, "usage_type": "call"}, {"api_name": "scipy.io.savemat", "line_number": 66, "usage_type": "call"}, {"api_name": "scipy.io", "line_number": 66, "usage_type": "name"}]} +{"seq_id": "38237190943", "text": "import webbrowser\r\nimport urllib.parse\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\n\r\n\r\nprint(''' \r\n _____ _ _ _____ \r\n| _ |_|___| |_| _ |_ _ ___ \r\n| __| | _| '_| |_'_| -_|\r\n|__| |_|___|_,_|__|__|_,_|___| v.1 \r\n The Internet Digger \r\n\r\n +----------------+\r\n | By ZKRIM |\r\n | 2K23 |\r\n +----------------+\r\n\r\n''')\r\n\r\ndef search_on_browser(search_term):\r\n # Encodage du terme de recherche pour les URL\r\n encoded_search_term = urllib.parse.quote(search_term)\r\n\r\n # URL de recherche sur Google (vous pouvez modifier l'URL pour utiliser un autre moteur de recherche)\r\n search_url = f\"https://www.google.com/search?q={encoded_search_term}\"\r\n\r\n # Ouvrir le navigateur avec l'URL de recherche\r\n webbrowser.open(search_url)\r\n\r\ndef get_number_of_results(search_term):\r\n encoded_search_term = urllib.parse.quote(search_term)\r\n search_url = f\"https://www.google.com/search?q={encoded_search_term}\"\r\n response = requests.get(search_url)\r\n\r\n if response.status_code == 200:\r\n soup = BeautifulSoup(response.text, \"html.parser\")\r\n result_stats = soup.find(\"div\", {\"id\": \"result-stats\"})\r\n if result_stats:\r\n num_results = result_stats.get_text()\r\n return num_results\r\n return \"Nombre de résultats non disponible.\"\r\n\r\ndef sous_menu_fonction_1():\r\n prenom = input(\"Prénom : \")\r\n nom = input(\"Nom : \")\r\n search_term = f'intext:\"{prenom} {nom}\"'\r\n num_results = get_number_of_results(search_term)\r\n print(f\"Nombre de résultats trouvés sur Google : {num_results}\")\r\n search_on_browser(search_term)\r\n\r\ndef sous_menu_fonction_2():\r\n prenom = input(\"Prénom : \")\r\n nom = input(\"Nom : \")\r\n search_term = f'inurl:\"{prenom} {nom}\"'\r\n num_results = get_number_of_results(search_term)\r\n print(f\"Nombre de résultats trouvés sur Google : {num_results}\")\r\n search_on_browser(search_term)\r\n\r\ndef sous_menu_fonction_3():\r\n prenom = input(\"Prénom : \")\r\n nom = input(\"Nom : \")\r\n search_term = f'{prenom} {nom} site:youtube.com | site:instagram.com | site:twitter.com | site:linkedin.com | site:tiktok.com | site:facebook.com'\r\n num_results = get_number_of_results(search_term)\r\n print(f\"Nombre de résultats trouvés sur Google : {num_results}\")\r\n search_on_browser(search_term)\r\n\r\ndef sous_menu_fonction_4():\r\n prenom = input(\"Prénom : \")\r\n nom = input(\"Nom : \")\r\n search_term = f'intext:\"{prenom} {nom}\" filetype:pdf'\r\n num_results = get_number_of_results(search_term)\r\n print(f\"Nombre de résultats trouvés sur Google : {num_results}\")\r\n search_on_browser(search_term)\r\n\r\ndef afficher_sous_menu_fonction_1():\r\n while True:\r\n print(\"\\n----------> IDENTITY TRACKING MENU <----------\\n\")\r\n print(\"-> 1. Text Searching\")\r\n print(\"-> 2. Title Searching\")\r\n print(\"-> 3. Social Networks Searching\")\r\n print(\"-> 4. Document Searching\")\r\n print(\"-> 5. Main Menu\\n\")\r\n\r\n choix_sous_menu_fonction_1 = input(\"Choose An Option (1-5) : \")\r\n\r\n if choix_sous_menu_fonction_1 == \"1\":\r\n sous_menu_fonction_1()\r\n elif choix_sous_menu_fonction_1 == \"2\":\r\n sous_menu_fonction_2()\r\n elif choix_sous_menu_fonction_1 == \"3\":\r\n sous_menu_fonction_3()\r\n elif choix_sous_menu_fonction_1 == \"4\":\r\n sous_menu_fonction_4()\r\n elif choix_sous_menu_fonction_1 == \"5\":\r\n break\r\n else:\r\n print(\"Invalid Choice. Please Enter A Valid Number (1-5).\")\r\n\r\ndef fonction_1():\r\n while True:\r\n print(\"\\n----------> MENU <----------:\")\r\n print(\"-> 1. Identity Tracking\")\r\n print(\"-> 2. Username Tracking\")\r\n print(\"-> 3. Quit\\n\")\r\n\r\n choix_fonction_1 = input(\"Choose An Option (1-3) : \")\r\n\r\n if choix_fonction_1 == \"1\":\r\n afficher_sous_menu_fonction_1()\r\n elif choix_fonction_1 == \"2\":\r\n fonction_2()\r\n elif choix_fonction_1 == \"3\":\r\n break\r\n else:\r\n print(\"Invalid Choice. Please Enter A Valid Number (1-3).\")\r\n\r\ndef fonction_2():\r\n username = input(\"Username : \")\r\n search_term = f'{username} site:youtube.com | site:instagram.com | site:twitter.com | site:tiktok.com | site:facebook.com'\r\n num_results = get_number_of_results(search_term)\r\n print(f\"Nombre de résultats trouvés sur Google : {num_results}\")\r\n search_on_browser(search_term)\r\n\r\nif __name__ == \"__main__\":\r\n fonction_1()\r\n", "repo_name": "Warning33/PickAxe", "sub_path": "PickAxe.py", "file_name": "PickAxe.py", "file_ext": "py", "file_size_in_byte": 4581, "program_lang": "python", "lang": "fr", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "urllib.parse.parse.quote", "line_number": 25, "usage_type": "call"}, {"api_name": "urllib.parse.parse", "line_number": 25, "usage_type": "attribute"}, {"api_name": "urllib.parse", "line_number": 25, "usage_type": "name"}, {"api_name": "webbrowser.open", "line_number": 31, "usage_type": "call"}, {"api_name": "urllib.parse.parse.quote", "line_number": 34, "usage_type": "call"}, {"api_name": "urllib.parse.parse", "line_number": 34, "usage_type": "attribute"}, {"api_name": "urllib.parse", "line_number": 34, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 36, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 39, "usage_type": "call"}]} +{"seq_id": "29878707370", "text": "\r\nfrom setuptools import setup, find_packages\r\n\r\nwith open(\"requirements.txt\", \"r\") as requirement_file:\r\n requirements = requirement_file.read().splitlines()\r\n print(requirements)\r\n\r\nsetup(\r\n name='demo',\r\n version='0.0.1',\r\n package_dir={'': 'src'},\r\n packages=find_packages(\"src\"),\r\n install_requires=requirements,\r\n)", "repo_name": "Xophe92/py.mut-issue-pytest-package", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 341, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "setuptools.setup", "line_number": 8, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 12, "usage_type": "call"}]} +{"seq_id": "27960654064", "text": "from functools import partial\n\nimport grpc\nimport jwt\n\nfrom internal.dependencies import user_id_context_var\nfrom security.jwt import validate_jwt_token\n\n__all__ = (\n 'AuthInterceptor',\n)\n\n\ndef abort(ignored_request, context, text):\n context.abort(grpc.StatusCode.UNAUTHENTICATED, text)\n\n\n_abort_no_token = partial(abort, text='No JWT token present in request')\n_abort_wrong_token = partial(abort, text='JWT token is not valid')\n\n_abortion_no_token = grpc.unary_unary_rpc_method_handler(_abort_no_token)\n_abortion_wrong_token = grpc.unary_unary_rpc_method_handler(_abort_wrong_token)\n\n\nclass AuthInterceptor(grpc.aio.ServerInterceptor):\n \"\"\"\n Аутентифицирует запросы по переданному JWT токену.\n Пример Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjM0fQ.UwT8lPNUcHRAEEGesEIBcYKItbrp04maOG03F22ec0Q\n \"\"\"\n async def intercept_service(self, continuation, handler_call_details):\n for md in handler_call_details.invocation_metadata:\n if md.key == 'authorization':\n _, value = md.value.split(' ')\n try:\n user_id = validate_jwt_token(value.strip())\n except jwt.PyJWTError:\n return _abortion_wrong_token\n else:\n user_id_context_var.set(user_id)\n return await continuation(handler_call_details)\n else:\n return _abortion_no_token\n", "repo_name": "AlekseiKhatkevich/strike", "sub_path": "grpc_services/interceptors.py", "file_name": "interceptors.py", "file_ext": "py", "file_size_in_byte": 1451, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "grpc.StatusCode", "line_number": 15, "usage_type": "attribute"}, {"api_name": "functools.partial", "line_number": 18, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 19, "usage_type": "call"}, {"api_name": "grpc.unary_unary_rpc_method_handler", "line_number": 21, "usage_type": "call"}, {"api_name": "grpc.unary_unary_rpc_method_handler", "line_number": 22, "usage_type": "call"}, {"api_name": "grpc.aio", "line_number": 25, "usage_type": "attribute"}, {"api_name": "security.jwt.validate_jwt_token", "line_number": 35, "usage_type": "call"}, {"api_name": "jwt.PyJWTError", "line_number": 36, "usage_type": "attribute"}, {"api_name": "internal.dependencies.user_id_context_var.set", "line_number": 39, "usage_type": "call"}, {"api_name": "internal.dependencies.user_id_context_var", "line_number": 39, "usage_type": "name"}]} +{"seq_id": "22576199246", "text": "import pygame\nimport config\nimport terrain\n\noverworld_chunks = [\n ['a1', 'a2', 'a3'],\n ['b1', 'b2', 'b3'],\n ['c1', 'c2', 'c3']\n]\n\noverworld = [['0' for x in range(config.MAP_WIDTH)] for y in range(config.MAP_HEIGHT)]\noverworld_layer_1 = [[' ' for x in range(config.MAP_WIDTH)] for y in range(config.MAP_HEIGHT)]\n\n\noverworld_2 = [['0' for x in range(config.MAP_WIDTH)] for y in range(config.MAP_HEIGHT)]\noverworld2_layer_1 = [[' ' for x in range(config.MAP_WIDTH)] for y in range(config.MAP_HEIGHT)]\n\nunderground = [['+' for x in range(config.MAP_WIDTH)] for y in range(config.MAP_HEIGHT)]\n\noverworld2_layer_1[10][10] = 'p'\noverworld_2[4][4] = 'f'\n\noverworld2_layers = [overworld_2, overworld2_layer_1, False]\n\ndef create_boundary(area, id):\n new_area = area\n \n for x in range(len(area[0])):\n new_area[0][x] = id\n new_area[len(area[0]) - 1][x] = id\n for y in range(len(area)):\n new_area[y][0] = id\n new_area[y][len(area) - 1] = id\n\n return new_area\n\noverworld_layer_1 = create_boundary(overworld_layer_1, 'h')\noverworld2_layer_1 = create_boundary(overworld2_layer_1, 'h')\n\n\noverworld_layer_1[3][2] = 'p'\noverworld_layer_1[0][5] = 'H'\noverworld_layer_1[5][5] = 's'\noverworld2_layer_1[99][5] = 'H'\n\noverworld_layers = [overworld, overworld_layer_1, False]\n\ndef generate_underground_layer():\n return terrain.create_terrain(config.MAP_WIDTH, config.MAP_HEIGHT, 10000)\n\nunderground_1 = generate_underground_layer()\nunderground_1 = create_boundary(underground_1, '#')\n\n# for y in range(len(underground_1)):\n# row = ''\n# for x in range(len(underground_1[y])):\n# row += underground_1[y][x]\n\n# print(row)\nunderground_1[50][50] = 'p'\nunderground_layers = [underground, underground_1, True]\n\ndef get_level(level):\n if level == 'overworld':\n return overworld_layers\n \ncurrent_area = overworld_layers", "repo_name": "taloncouture/Sandbox-Game", "sub_path": "map.py", "file_name": "map.py", "file_ext": "py", "file_size_in_byte": 1874, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "config.MAP_WIDTH", "line_number": 11, "usage_type": "attribute"}, {"api_name": "config.MAP_HEIGHT", "line_number": 11, "usage_type": "attribute"}, {"api_name": "config.MAP_WIDTH", "line_number": 12, "usage_type": "attribute"}, {"api_name": "config.MAP_HEIGHT", "line_number": 12, "usage_type": "attribute"}, {"api_name": "config.MAP_WIDTH", "line_number": 15, "usage_type": "attribute"}, {"api_name": "config.MAP_HEIGHT", "line_number": 15, "usage_type": "attribute"}, {"api_name": "config.MAP_WIDTH", "line_number": 16, "usage_type": "attribute"}, {"api_name": "config.MAP_HEIGHT", "line_number": 16, "usage_type": "attribute"}, {"api_name": "config.MAP_WIDTH", "line_number": 18, "usage_type": "attribute"}, {"api_name": "config.MAP_HEIGHT", "line_number": 18, "usage_type": "attribute"}, {"api_name": "terrain.create_terrain", "line_number": 49, "usage_type": "call"}, {"api_name": "config.MAP_WIDTH", "line_number": 49, "usage_type": "attribute"}, {"api_name": "config.MAP_HEIGHT", "line_number": 49, "usage_type": "attribute"}]} +{"seq_id": "2462881040", "text": "\"\"\"Utils for monoDepth.\"\"\"\nimport re\nimport sys\n\nimport cv2\nimport numpy as np\nimport torch\n\nfrom imaginairy.modules.midas.api import load_midas_transform\n\n\nclass AddMiDaS:\n def __init__(self, model_type=\"dpt_hybrid\"):\n self.transform = load_midas_transform(model_type)\n\n def pt2np(self, x):\n x = ((x + 1.0) * 0.5).detach().cpu().numpy()\n return x\n\n def np2pt(self, x):\n x = torch.from_numpy(x) * 2 - 1.0\n return x\n\n def __call__(self, img):\n # sample['jpg'] is tensor hwc in [-1, 1] at this point\n img = self.pt2np(img)\n img = self.transform({\"image\": img})[\"image\"]\n return img\n\n\ndef read_pfm(path):\n \"\"\"\n Read pfm file.\n\n Args:\n path (str): path to file\n\n Returns:\n tuple: (data, scale)\n \"\"\"\n with open(path, \"rb\") as file:\n header = file.readline().rstrip()\n if header.decode(\"ascii\") == \"PF\":\n color = True\n elif header.decode(\"ascii\") == \"Pf\":\n color = False\n else:\n raise ValueError(\"Not a PFM file: \" + path)\n\n dim_match = re.match(r\"^(\\d+)\\s(\\d+)\\s$\", file.readline().decode(\"ascii\"))\n if dim_match:\n width, height = list(map(int, dim_match.groups()))\n else:\n raise RuntimeError(\"Malformed PFM header.\")\n\n scale = float(file.readline().decode(\"ascii\").rstrip())\n if scale < 0:\n # little-endian\n endian = \"<\"\n scale = -scale\n else:\n # big-endian\n endian = \">\"\n\n data = np.fromfile(file, endian + \"f\")\n shape = (height, width, 3) if color else (height, width)\n\n data = np.reshape(data, shape)\n data = np.flipud(data)\n\n return data, scale\n\n\ndef write_pfm(path, image, scale=1):\n \"\"\"\n Write pfm file.\n\n Args:\n path (str): pathto file\n image (array): data\n scale (int, optional): Scale. Defaults to 1.\n \"\"\"\n\n with open(path, \"wb\") as file:\n if image.dtype.name != \"float32\":\n raise ValueError(\"Image dtype must be float32.\")\n\n image = np.flipud(image)\n\n if len(image.shape) == 3 and image.shape[2] == 3: # color image\n color = True\n elif (\n len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1\n ): # greyscale\n color = False\n else:\n msg = \"Image must have H x W x 3, H x W x 1 or H x W dimensions.\"\n raise ValueError(msg)\n\n file.write(\"PF\\n\" if color else b\"Pf\\n\")\n file.write(b\"%d %d\\n\" % (image.shape[1], image.shape[0]))\n\n endian = image.dtype.byteorder\n\n if endian == \"<\" or endian == \"=\" and sys.byteorder == \"little\":\n scale = -scale\n\n file.write(b\"%f\\n\" % scale)\n\n image.tofile(file)\n\n\ndef read_image(path):\n \"\"\"\n Read image and output RGB image (0-1).\n\n Args:\n path (str): path to file\n\n Returns:\n array: RGB image (0-1)\n \"\"\"\n img = cv2.imread(path)\n\n if img.ndim == 2:\n img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) / 255.0\n\n return img\n\n\ndef resize_image(img):\n \"\"\"\n Resize image and make it fit for network.\n\n Args:\n img (array): image\n\n Returns:\n tensor: data ready for network\n \"\"\"\n height_orig = img.shape[0]\n width_orig = img.shape[1]\n\n scale = width_orig / 384 if width_orig > height_orig else height_orig / 384\n\n height = (np.ceil(height_orig / scale / 32) * 32).astype(int)\n width = (np.ceil(width_orig / scale / 32) * 32).astype(int)\n\n img_resized = cv2.resize(img, (width, height), interpolation=cv2.INTER_AREA)\n\n img_resized = (\n torch.from_numpy(np.transpose(img_resized, (2, 0, 1))).contiguous().float()\n )\n img_resized = img_resized.unsqueeze(0)\n\n return img_resized\n\n\ndef resize_depth(depth, width, height):\n \"\"\"\n Resize depth map and bring to CPU (numpy).\n\n Args:\n depth (tensor): depth\n width (int): image width\n height (int): image height\n\n Returns:\n array: processed depth\n \"\"\"\n depth = torch.squeeze(depth[0, :, :, :]).to(\"cpu\")\n\n depth_resized = cv2.resize(\n depth.numpy(), (width, height), interpolation=cv2.INTER_CUBIC\n )\n\n return depth_resized\n\n\ndef write_depth(path, depth, bits=1):\n \"\"\"\n Write depth map to pfm and png file.\n\n Args:\n path (str): filepath without extension\n depth (array): depth\n \"\"\"\n write_pfm(path + \".pfm\", depth.astype(np.float32))\n\n depth_min = depth.min()\n depth_max = depth.max()\n\n max_val = (2 ** (8 * bits)) - 1\n\n if depth_max - depth_min > np.finfo(\"float\").eps:\n out = max_val * (depth - depth_min) / (depth_max - depth_min)\n else:\n out = np.zeros(depth.shape, dtype=depth.type)\n\n if bits == 1:\n cv2.imwrite(path + \".png\", out.astype(\"uint8\"))\n elif bits == 2:\n cv2.imwrite(path + \".png\", out.astype(\"uint16\"))\n", "repo_name": "brycedrennan/imaginAIry", "sub_path": "imaginairy/modules/midas/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 5014, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7408, "dataset": "github-code", "pt": "24", "api": [{"api_name": "imaginairy.modules.midas.api.load_midas_transform", "line_number": 14, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 21, "usage_type": "call"}, {"api_name": "re.match", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.fromfile", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 88, "usage_type": "call"}, {"api_name": "sys.byteorder", "line_number": 105, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 123, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 126, "usage_type": "call"}, {"api_name": "cv2.COLOR_GRAY2BGR", "line_number": 126, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 128, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 128, "usage_type": "attribute"}, {"api_name": "numpy.ceil", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 149, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 151, "usage_type": "call"}, {"api_name": "cv2.INTER_AREA", "line_number": 151, "usage_type": "attribute"}, {"api_name": "torch.from_numpy", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 154, "usage_type": "call"}, {"api_name": "torch.squeeze", "line_number": 173, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 175, "usage_type": "call"}, {"api_name": "cv2.INTER_CUBIC", "line_number": 176, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 190, "usage_type": "attribute"}, {"api_name": "numpy.finfo", "line_number": 197, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 200, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 203, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 205, "usage_type": "call"}]} +{"seq_id": "71679106622", "text": "from django.db import models\nimport json\n\nclass Car(models.Model):\n # mã của giấy đăng ký\n registration_id = models.TextField(primary_key=True, null=False, max_length=20, unique=True)\n # biển số đăng ký\n plate_number = models.TextField(null=False, max_length=20, unique=True)\n # nơi đăng ký\n registration_place = models.TextField(null=False)\n # ngày cấp\n registration_date = models.DateField(null=False)\n # mục đích\n purpose = models.CharField(\n max_length=100,\n choices=[\n ('personal', 'Đi lại cá nhân'),\n ('passenger_service', 'Dịch vụ chở khách'),\n ('transportation_service', 'Dịch vụ vận tải'),\n ],\n default='personal',\n )\n # loại xe\n type = models.TextField(null=False)\n # hãng xe\n manufacturer = models.TextField(null=False)\n # mẫu xe\n model = models.TextField(null=False)\n\n # extra \n engine_number = models.TextField(null=False)\n chassis_number = models.TextField(null=False)\n # power = models.FloatField(blank=True, null=True)\n # torque = models.FloatField(blank=True, null=True)\n # transmission = models.CharField(max_length=50, blank=True, null=True)\n # seating_capacity = models.PositiveIntegerField(blank=True, null=True)\n # length = models.FloatField(blank=True, null=True)\n # width = models.FloatField(blank=True, null=True)\n # height = models.FloatField(blank=True, null=True)\n # weight = models.FloatField(blank=True, null=True)\n # fuel_consumption = models.FloatField(blank=True, null=True)\n # suspension = models.CharField(max_length=100, blank=True, null=True)\n # braking_system = models.CharField(max_length=100, blank=True, null=True)\n\n # chủ sở hữu\n owner = models.ForeignKey('owner.Owner', on_delete=models.CASCADE, null=True, blank=True)\n # đã đăng kiểm\n inspection_status = models.CharField(max_length=100, default='Chưa đăng kiểm')\n", "repo_name": "minhduc1122002/registry-total", "sub_path": "backend/car/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 1992, "program_lang": "python", "lang": "vi", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.db.models.Model", "line_number": 4, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 4, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 6, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 6, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 8, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 8, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 10, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 10, "usage_type": "name"}, {"api_name": "django.db.models.DateField", "line_number": 12, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 12, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 14, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 14, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 24, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 24, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 26, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 26, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 28, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 28, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 31, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 31, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 32, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 32, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 46, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 46, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 46, "usage_type": "attribute"}, {"api_name": "django.db.models.CharField", "line_number": 48, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 48, "usage_type": "name"}]} +{"seq_id": "75226318142", "text": "import smtplib\nimport datetime as dt\nimport random\nimport mailchimp_marketing as MailchimpMarketing\nfrom mailchimp_marketing.api_client import ApiClientError\n\n\n# |------------------------------------GETTING EMAILS FROM MAILCHIMP API------------------------------------|#\n\n# This is where subscribed members' emails will be saved to\nemails = []\n\n# Gets member info from MailChimp\ntry:\n client = MailchimpMarketing.Client()\n client.set_config({\n \"api_key\": \"ENTER_API_KEY_HERE\",\n \"server\": \"ENTER_YOUR_SERVER_HERE\"})\n\n # If members are currently subscribed, adds them to \"emails\" list\n response = client.lists.get_list_members_info(\"ENTER_YOUR_LIST_ID_HERE\")\n for member in response['members']:\n if member['status'] == \"subscribed\":\n emails.append(member['email_address'])\n\n\nexcept ApiClientError as error:\n print(\"Error: {}\".format(error.text))\n\n\n# |------------------------------------LOG IN FOR GMAIL------------------------------------|#\n\nmy_email = \"ENTER_YOUR_GMAIL_HERE\"\npassword = \"ENTER_YOUR_GMAIL_APP_KEY_HERE\"\nunsub_link_url = \"tinyurl.com/unsub321\"\n\n\n# |------------------------------------DATE FORMATTED FOR EMAIL TO BE SENT------------------------------------|#\n\nnow = dt.datetime.now()\nyear = now.year\nmonth = now.month\nday = now.day\nweekday = now.weekday() # 0 = monday, 1 = tuesday, etc\ntoday = f\"{month}/{day}/{year}\"\n\n\n# |------------------------------------WORKOUTS------------------------------------|#\nupper_body_beg = (\n \"Push-Ups: 2 sets of 20\",\n \"Chin-Ups: 2 sets of 5\",\n \"Wall Handstand: 2 sets of 30 seconds\",\n \"Wide-Grip Push-Ups: 2 sets of 20\",\n \"Close-Grip Push-Ups: 2 sets of 20\",\n)\n\nupper_body_int = (\n \"Feet Elevated Push-Ups: 2 sets of 20\",\n \"Pull-Ups: 2 sets of 10\",\n \"Feet Elevated Pike Push-Ups: 2 sets of 15\",\n \"Chin-Ups: 2 sets of 10\",\n \"Wall Handstand: 2 sets of 60 seconds\",\n \"Diamond Push-Ups: 2 sets of 15\",\n\n)\n\nupper_body_adv = (\n \"Feet Elevated Push-Ups: 3 sets of 25\",\n \"Archer Push-Ups: 3 sets of 12 (6 per side)\",\n \"Archer Pull-Ups: 3 sets of 6 (3 per side)\",\n \"One-Arm Push-Ups: 3 sets of 12 (6 per side)\",\n \"Diamond Push-Ups: 3 sets of 20\",\n \"Handstand Push-Ups: 3 sets of 10\",\n)\n\nlower_body_beg = (\n \"Squats: 2 sets of 20\",\n \"Lunges: 2 sets of 10 (each side)\",\n \"Hip Bridge: 2 sets of 20\",\n \"Lying Knee Tuck: 2 sets of 20\",\n \"Wall Sits: 2 sets of 60 seconds\",\n)\n\nlower_body_int = (\n \"Jump Squats: 2 sets of 20\",\n \"Lunges: 2 sets of 20 (each side)\",\n \"Jump Lunges: 2 sets of 12 (each side)\",\n \"Close-Feet Squats: 2 sets of 20\",\n \"Wall Sits: 2 sets of 2 minutes\",\n)\n\nlower_body_adv = (\n \"Pistol Squats: 3 sets of 10 (each side)\",\n \"Jump Squats: 3 sets of 15\",\n \"Jumping Lunges: 3 sets of 15 (each side)\",\n \"Shrimp Squat: 3 sets of 10 (each side)\",\n)\n\n\ncore = (\n \"Plank: 2 sets of 2 minutes\",\n \"Side Plank: 2 minutes (each side)\",\n \"Bicycle Crunches: 2 sets of 30 (each side)\",\n \"V-Ups: 2 sets of 30 reps\",\n \"Crunches: 2 sets of 30 reps\",\n \"Sit-Ups: 2 sets of 30 reps\",\n \"Russian Twists: 2 sets of 30 (each side)\",\n \"Scissor Kicks: 2 sets of 30 (each side)\",\n \"Leg Raises: 2 sets of 15\",\n\n)\n\n\n# |------------------------------------FUNCTION TO GENERATE UNIQUE WORKOUT------------------------------------|#\n\ndef generate_workout():\n upper_body_beg_choice = random.choice(upper_body_beg)\n upper_body_int_choice = random.choice(upper_body_int)\n upper_body_adv_choice = random.choice(upper_body_adv)\n\n lower_body_beg_choice = random.choice(lower_body_beg)\n lower_body_int_choice = random.choice(lower_body_int)\n lower_body_adv_choice = random.choice(lower_body_adv)\n\n core_choice = random.choice(core)\n core_choice_2 = random.choice(core)\n\n return f\"Beginner Workout: \\n\\n{upper_body_beg_choice} \\n{lower_body_beg_choice} \\n{core_choice}\\n\\n\\n\" \\\n f\"-------------------------------------------------------------------------------\\n\\n\\n\" \\\n f\"Intermediate Workout: \\n\\n{upper_body_int_choice} \\n{lower_body_int_choice} \\n{core_choice}\\n\\n\\n\" \\\n f\"-------------------------------------------------------------------------------\\n\\n\\n\" \\\n f\"Advanced Workout: \\n\\n{upper_body_adv_choice} \\n{lower_body_adv_choice} \\n{core_choice} \\n{core_choice_2}\\n\\n\\n\" \\\n f\"-------------------------------------------------------------------------------\\n\\n\\n\" \\\n f\"How to Use: If you're unable to complete the sets and reps required, \" \\\n f\"feel free to split the reps up and complete more sets to finish all the reps. \" \\\n f\"Once you're able to easily complete all sets and reps as written, move on to the next difficulty level.\\n\\n\\n\\n\\n\\n\" \\\n\n\n# |---------------------------------EMAILING THE EMAIL-LIST THE GENERATED WORKOUT---------------------------------|#\n\n\nwith smtplib.SMTP(\"smtp.gmail.com\", 587) as connection:\n connection.starttls()\n connection.login(user=my_email, password=password)\n connection.sendmail(from_addr=my_email,\n to_addrs=emails,\n msg=f\"Subject:Wake Up, Workout! {today} \\n\\n{generate_workout()} \\n\\n To unsubscribe, click here: {unsub_link_url}\"\n )\n\n", "repo_name": "deikaplan/Wake-Up-Workout-Project", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 5230, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "mailchimp_marketing.Client", "line_number": 15, "usage_type": "call"}, {"api_name": "mailchimp_marketing.api_client.ApiClientError", "line_number": 27, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 40, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 40, "usage_type": "attribute"}, {"api_name": "random.choice", "line_number": 117, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 118, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 119, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 121, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 122, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 123, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 125, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 126, "usage_type": "call"}, {"api_name": "smtplib.SMTP", "line_number": 142, "usage_type": "call"}]} +{"seq_id": "1267170662", "text": "from . import init_app, db\nfrom .models import Variables\nfrom .models import Geography\nfrom .models import GeographyTypes\nfrom .aggregate import Aggregator\nfrom .color import (color, labeled_color_map)\nfrom .legend import (make_numerical_legend, make_labeled_legend)\n\nimport argparse\nfrom pathlib import Path\nimport yaml\nfrom yaml.loader import SafeLoader\nimport pandas\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--update-legends', action='store_true', default=False,\n help=\"don't perform database commits, only update legends\")\n parser.add_argument('config', type=Path, help=\"name of configuration file\")\n args = parser.parse_args()\n\n app = init_app()\n\n # read configuration\n with open(args.config) as f:\n cfg = yaml.load(f, Loader=SafeLoader)\n\n # read data\n if cfg[\"type\"] == \"excel\":\n data = pandas.read_excel(cfg[\"path\"])\n elif cfg[\"type\"] == \"csv\":\n data = pandas.read_csv(cfg[\"path\"])\n else:\n parser.error(f\"unkown data type {cfg['type']}\")\n\n with app.app_context():\n # check datafile\n error = False\n for variable in cfg[\"variables\"]:\n if variable[\"geometry\"] not in data.columns:\n print(f'Error: geometry column {variable[\"geometry\"]}'\n ' not in file')\n error = True\n if variable[\"file_var\"] not in data.columns:\n print(f'Error: geometry column {variable[\"file_var\"]}'\n ' not in file')\n error = True\n v = db.session.query(Variables).filter(\n Variables.id == variable[\"db_var\"])\n if v.one_or_none() is None:\n print(f'Error: db variable {variable[\"db_var\"]} not defined')\n error = True\n if error:\n parser.error(f'errors in variable description file {cfg[\"path\"]}')\n\n agg = Aggregator()\n for variable in cfg[\"variables\"]:\n print(variable['db_var'])\n values = data[[variable[\"geometry\"], variable[\"file_var\"]]]\n values = values.rename(columns={variable[\"geometry\"]: 'gss_id',\n variable[\"file_var\"]: 'value'})\n values[\"year\"] = variable[\"year\"]\n values[\"variable_id\"] = variable[\"db_var\"]\n\n # Calculate color values\n layer_name = '{db_var}_{year}_S01'.format(**variable)\n if variable[\"colormethod\"] == 'labeled':\n # TODO check that 'label_var' is provided in variable\n values_and_labels = data[[variable['file_var'], variable['label_var']]]\n values_and_labels = values_and_labels.rename(columns={\n variable['file_var']: 'value',\n variable['label_var']: 'label',\n })\n values_and_labels = values_and_labels.drop_duplicates()\n values_and_labels.sort_values('value', inplace=True)\n values[\"color\"], cmap, limits = labeled_color_map(\n variable['colormap'],\n values['value'].to_numpy(),\n values_and_labels['value'],\n reverse_colors=variable.get('reverse_color', False),\n )\n make_labeled_legend(layer_name, cmap, values_and_labels['label'].to_numpy(), width=240)\n else:\n values[\"color\"], cmap, limits = color(variable, values[\"value\"].to_numpy())\n make_numerical_legend(layer_name, cmap, limits)\n\n # Aggregate data for composite geometries\n if 'aggregatemethod' in variable:\n meta_column_label = variable.get(\"aggregatemeta\", \"population\")\n meta_column = cfg[\"metadata\"][meta_column_label][variable[\"year\"]]\n population = data[[\n variable[\"geometry\"],\n variable[\"file_var\"],\n meta_column,\n ]]\n population = population.rename(columns={\n variable[\"geometry\"]: 'gss_id',\n variable[\"file_var\"]: 'value',\n meta_column: 'population'\n })\n population.set_index('gss_id', inplace=True)\n\n geography_types = db.session.query(GeographyTypes).where(\n (GeographyTypes.column_name != None),\n (GeographyTypes.gss_code != 'S01')\n )\n for geo_type in geography_types:\n print( 'aggregate {db_var} in {0} using {aggregatemethod}'.format(\n geo_type.gss_code,\n **variable,\n ))\n composite_geographies = db.session.query(Geography).where(\n Geography.gss_code == geo_type.gss_code\n )\n agg_values = agg.aggregate(\n variable['aggregatemethod'],\n composite_geographies,\n population,\n variable[\"year\"],\n variable[\"db_var\"],\n )\n agg_values['color'], cmap, limits = color(\n variable,\n agg_values['value'].to_numpy(),\n )\n layer_name = '{db_var}_{year}_{0}'.format(geo_type.gss_code, **variable)\n make_numerical_legend(layer_name, cmap, limits)\n values = pandas.concat((values, agg_values))\n\n if not args.update_legends:\n values.to_sql(\"data\", con=db.session.get_bind(),\n index=False, if_exists=\"append\", method=\"multi\")\n\n\n\nif __name__ == \"__main__\":\n main()\n", "repo_name": "EnvironmentSocietyHealth/CRESHMap", "sub_path": "CRESHMap/load_variables.py", "file_name": "load_variables.py", "file_ext": "py", "file_size_in_byte": 5827, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 16, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 19, "usage_type": "name"}, {"api_name": "yaml.load", "line_number": 26, "usage_type": "call"}, {"api_name": "yaml.loader.SafeLoader", "line_number": 26, "usage_type": "name"}, {"api_name": "pandas.read_excel", "line_number": 30, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 32, "usage_type": "call"}, {"api_name": "models.Variables", "line_number": 48, "usage_type": "argument"}, {"api_name": "models.Variables.id", "line_number": 49, "usage_type": "attribute"}, {"api_name": "models.Variables", "line_number": 49, "usage_type": "name"}, {"api_name": "aggregate.Aggregator", "line_number": 56, "usage_type": "call"}, {"api_name": "color.labeled_color_map", "line_number": 76, "usage_type": "call"}, {"api_name": "legend.make_labeled_legend", "line_number": 82, "usage_type": "call"}, {"api_name": "color.color", "line_number": 84, "usage_type": "call"}, {"api_name": "legend.make_numerical_legend", "line_number": 85, "usage_type": "call"}, {"api_name": "models.GeographyTypes", "line_number": 103, "usage_type": "argument"}, {"api_name": "models.GeographyTypes.column_name", "line_number": 104, "usage_type": "attribute"}, {"api_name": "models.GeographyTypes", "line_number": 104, "usage_type": "name"}, {"api_name": "models.GeographyTypes.gss_code", "line_number": 105, "usage_type": "attribute"}, {"api_name": "models.GeographyTypes", "line_number": 105, "usage_type": "name"}, {"api_name": "models.Geography", "line_number": 112, "usage_type": "argument"}, {"api_name": "models.Geography.gss_code", "line_number": 113, "usage_type": "attribute"}, {"api_name": "models.Geography", "line_number": 113, "usage_type": "name"}, {"api_name": "color.color", "line_number": 122, "usage_type": "call"}, {"api_name": "legend.make_numerical_legend", "line_number": 127, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 128, "usage_type": "call"}]} +{"seq_id": "13912849809", "text": "import discord\nimport os\nfrom discord.ext import commands\n\nclass ServerInfo(commands.Cog):\n \n def __inti__(self, client):\n self.client = client\n \n @commands.Cog.listener()\n async def on_ready(self):\n print('Server Info Cog is Running')\n \n @commands.command()\n async def serverinfo(self, ctx):\n \"\"\"Shows server info\"\"\"\n\n server = ctx.guild\n\n roles = str(len(server.roles))\n emojis = str(len(server.emojis))\n channels = str(len(server.channels))\n\n embeded = discord.Embed(title=server.name, description='Server Info', color=0xEE8700)\n embeded.set_thumbnail(url=server.icon_url)\n embeded.add_field(name=\"Created on:\", value=server.created_at.strftime('%d %B %Y at %H:%M UTC+3'), inline=False)\n embeded.add_field(name=\"Server ID:\", value=server.id, inline=False)\n embeded.add_field(name=\"Users on server:\", value=server.member_count, inline=True)\n\n embeded.add_field(name=\"Server Region:\", value=server.region, inline=True)\n embeded.add_field(name=\"Verification Level:\", value=server.verification_level, inline=True)\n\n embeded.add_field(name=\"Role Count:\", value=roles, inline=True)\n embeded.add_field(name=\"Emoji Count:\", value=emojis, inline=True)\n embeded.add_field(name=\"Channel Count:\", value=channels, inline=True)\n\n await ctx.channel.send(embed=embeded)\n\ndef setup(client):\n client.add_cog(ServerInfo(client))\n \ndef teardown(client):\n print('Server Info Cog is now not running')", "repo_name": "Archers007/DesertedBot", "sub_path": "Cog1/ServerInfo.py", "file_name": "ServerInfo.py", "file_ext": "py", "file_size_in_byte": 1548, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "discord.ext.commands.Cog", "line_number": 5, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 5, "usage_type": "name"}, {"api_name": "discord.ext.commands.Cog.listener", "line_number": 10, "usage_type": "call"}, {"api_name": "discord.ext.commands.Cog", "line_number": 10, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 10, "usage_type": "name"}, {"api_name": "discord.Embed", "line_number": 24, "usage_type": "call"}, {"api_name": "discord.ext.commands.command", "line_number": 14, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 14, "usage_type": "name"}]} +{"seq_id": "71043301822", "text": "# import the necessary packages\nfrom end2end.transform import four_point_transform\nfrom skimage.filters import threshold_local\nimport numpy as np\nimport argparse\nimport cv2\nimport imutils\n\ndef preprocess(image):\n # load the image and compute the ratio of the old height\n # to the new height, clone it, and resize it\n\n # image = cv2.imread(img_dir)\n # Replace with image data input\n\n ratio = image.shape[0] / 500.0\n orig = image.copy()\n image = imutils.resize(image, height = 500)\n # convert the image to grayscale, blur it, and find edges\n # in the image\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # gray = cv2.GaussianBlur(gray, (5, 5), 0)\n kernel = np.array([[-1,-1,-1], \n [-1, 9,-1],\n [-1,-1,-1]])\n gray = cv2.filter2D(gray, -1, kernel)\n gray = cv2.GaussianBlur(gray, (7, 7), 0)\n edged = cv2.Canny(gray, 75, 300)\n\n # find the contours in the edged image, keeping only the\n # largest ones, and initialize the screen contour\n cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]\n # loop over the contours\n for c in cnts:\n # approximate the contour\n peri = cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, 0.02 * peri, True)\n # if our approximated contour has four points, then we\n # can assume that we have found our screen\n if len(approx) == 4:\n screenCnt = approx\n break\n \n try:\n screenCnt\n except:\n raise ValueError(\"Image has no clear 4 sides\")\n finally:\n return orig\n \n # show the contour (outline) of the piece of paper\n # cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)\n\n # apply the four point transform to obtain a top-down\n # view of the original image\n warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)\n # convert the warped image to grayscale, then threshold it\n # to give it that 'black and white' paper effect\n warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)\n T = threshold_local(warped, 11, offset = 10, method = \"gaussian\")\n warped = (warped > T).astype(\"uint8\") * 255\n\n warped = cv2.cvtColor(warped, cv2.COLOR_GRAY2RGB)\n\n return warped\n\n", "repo_name": "ikhovryak/LeggoDutch", "sub_path": "web_app/end2end/preprocess_image.py", "file_name": "preprocess_image.py", "file_ext": "py", "file_size_in_byte": 2372, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "imutils.resize", "line_number": 18, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 21, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 21, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 23, "usage_type": "call"}, {"api_name": "cv2.filter2D", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.GaussianBlur", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.findContours", "line_number": 32, "usage_type": "call"}, {"api_name": "cv2.RETR_LIST", "line_number": 32, "usage_type": "attribute"}, {"api_name": "cv2.CHAIN_APPROX_SIMPLE", "line_number": 32, "usage_type": "attribute"}, {"api_name": "imutils.grab_contours", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.contourArea", "line_number": 34, "usage_type": "attribute"}, {"api_name": "cv2.arcLength", "line_number": 38, "usage_type": "call"}, {"api_name": "cv2.approxPolyDP", "line_number": 39, "usage_type": "call"}, {"api_name": "end2end.transform.four_point_transform", "line_number": 58, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 61, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 61, "usage_type": "attribute"}, {"api_name": "skimage.filters.threshold_local", "line_number": 62, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 65, "usage_type": "call"}, {"api_name": "cv2.COLOR_GRAY2RGB", "line_number": 65, "usage_type": "attribute"}]} +{"seq_id": "42058879323", "text": "from typing import Dict\n\nfrom pyspark.sql import SparkSession, Column, DataFrame\n\n# noinspection PyUnresolvedReferences\nfrom pyspark.sql.functions import col, lit\n\nfrom spark_auto_mapper.automappers.automapper import AutoMapper\nfrom spark_auto_mapper.helpers.automapper_helpers import AutoMapperHelpers as A\nfrom spark_auto_mapper.helpers.expression_comparer import assert_compare_expressions\n\n\ndef test_auto_mapper_boolean(spark_session: SparkSession) -> None:\n # Arrange\n spark_session.createDataFrame(\n [\n (1, \"Qureshi\", \"Imran\", \"0\"),\n (2, \"Vidal\", \"Michael\", \"1\"),\n ],\n [\"member_id\", \"last_name\", \"first_name\", \"my_age\"],\n ).createOrReplaceTempView(\"patients\")\n\n source_df: DataFrame = spark_session.table(\"patients\")\n\n df = source_df.select(\"member_id\")\n df.createOrReplaceTempView(\"members\")\n\n # Act\n mapper = AutoMapper(\n view=\"members\", source_view=\"patients\", keys=[\"member_id\"]\n ).columns(\n age=A.boolean(A.column(\"my_age\")),\n is_active=A.boolean(\"False\"),\n )\n\n assert isinstance(mapper, AutoMapper)\n sql_expressions: Dict[str, Column] = mapper.get_column_specs(source_df=source_df)\n for column_name, sql_expression in sql_expressions.items():\n print(f\"{column_name}: {sql_expression}\")\n\n assert_compare_expressions(\n sql_expressions[\"age\"], col(\"b.my_age\").cast(\"boolean\").alias(\"age\")\n )\n assert_compare_expressions(\n sql_expressions[\"is_active\"], lit(\"False\").cast(\"boolean\").alias(\"is_active\")\n )\n\n result_df: DataFrame = mapper.transform(df=df)\n\n # Assert\n result_df.printSchema()\n result_df.show()\n\n assert result_df.where(\"member_id == 1\").select(\n \"age\",\n \"is_active\",\n ).collect()[0][\n :\n ] == (False, False)\n assert result_df.where(\"member_id == 2\").select(\n \"age\",\n \"is_active\",\n ).collect()[0][\n :\n ] == (True, False)\n\n assert dict(result_df.dtypes)[\"age\"] == \"boolean\"\n assert dict(result_df.dtypes)[\"is_active\"] == \"boolean\"\n", "repo_name": "icanbwell/SparkAutoMapper", "sub_path": "tests/boolean/test_automapper_boolean.py", "file_name": "test_automapper_boolean.py", "file_ext": "py", "file_size_in_byte": 2064, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pyspark.sql.SparkSession", "line_number": 13, "usage_type": "name"}, {"api_name": "pyspark.sql.DataFrame", "line_number": 23, "usage_type": "name"}, {"api_name": "spark_auto_mapper.automappers.automapper.AutoMapper", "line_number": 29, "usage_type": "call"}, {"api_name": "spark_auto_mapper.helpers.automapper_helpers.AutoMapperHelpers.boolean", "line_number": 32, "usage_type": "call"}, {"api_name": "spark_auto_mapper.helpers.automapper_helpers.AutoMapperHelpers", "line_number": 32, "usage_type": "name"}, {"api_name": "spark_auto_mapper.helpers.automapper_helpers.AutoMapperHelpers.column", "line_number": 32, "usage_type": "call"}, {"api_name": "spark_auto_mapper.helpers.automapper_helpers.AutoMapperHelpers.boolean", "line_number": 33, "usage_type": "call"}, {"api_name": "spark_auto_mapper.helpers.automapper_helpers.AutoMapperHelpers", "line_number": 33, "usage_type": "name"}, {"api_name": "spark_auto_mapper.automappers.automapper.AutoMapper", "line_number": 36, "usage_type": "argument"}, {"api_name": "typing.Dict", "line_number": 37, "usage_type": "name"}, {"api_name": "pyspark.sql.Column", "line_number": 37, "usage_type": "name"}, {"api_name": "spark_auto_mapper.helpers.expression_comparer.assert_compare_expressions", "line_number": 41, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 42, "usage_type": "call"}, {"api_name": "spark_auto_mapper.helpers.expression_comparer.assert_compare_expressions", "line_number": 44, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.lit", "line_number": 45, "usage_type": "call"}, {"api_name": "pyspark.sql.DataFrame", "line_number": 48, "usage_type": "name"}]} +{"seq_id": "40829735034", "text": "import cv2\nfrom flask import Flask, Response\nfrom flask_sock import Sock\n\nimport RPi.GPIO as GPIO\nimport time\n# ! /usr/bin/python\n# -*- coding: utf-8 -*-\n\n# 17\n# 27\n# 22\n# 10\nRIGHT_STRAIGHT = 27\nRIGHT_REVERSE = 17\nLEFT_REVERSE = 22\nLEFT_STRAIGHT = 10\n\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(RIGHT_STRAIGHT, GPIO.OUT)\nGPIO.setup(RIGHT_REVERSE, GPIO.OUT)\nGPIO.setup(LEFT_STRAIGHT, GPIO.OUT)\nGPIO.setup(LEFT_REVERSE, GPIO.OUT)\n\nconnected = set()\napp = Flask('__name__')\nsock = Sock(app)\nvideo = cv2.VideoCapture(0)\n\n\ndef video_stream():\n while True:\n ret, frame = video.read()\n if not ret:\n break\n else:\n ret, buffer = cv2.imencode('.jpeg', frame)\n frame = buffer.tobytes()\n yield (b' --frame\\r\\n' b'Content-type: imgae/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\n\n\n@app.route('/video_feed')\ndef video_feed():\n return Response(video_stream(), mimetype='multipart/x-mixed-replace; boundary=frame')\n\n@sock.route(\"/sock\")\ndef server(ws):\n while True:\n try:\n message = ws.receive()\n ws.send(f' recebido: {message}')\n if (message == \"up\"):\n GPIO.output(RIGHT_STRAIGHT, GPIO.HIGH)\n GPIO.output(LEFT_STRAIGHT, GPIO.HIGH)\n time.sleep(0.2)\n GPIO.output(RIGHT_STRAIGHT, GPIO.LOW)\n GPIO.output(LEFT_STRAIGHT, GPIO.LOW)\n ws.send(f' recebido: {message}')\n elif (message == \"down\"):\n GPIO.output(RIGHT_REVERSE, GPIO.HIGH)\n GPIO.output(LEFT_REVERSE, GPIO.HIGH)\n time.sleep(0.2)\n GPIO.output(RIGHT_REVERSE, GPIO.LOW)\n GPIO.output(LEFT_REVERSE, GPIO.LOW)\n ws.send(f' recebido: {message}')\n elif (message == \"left\"):\n GPIO.output(LEFT_STRAIGHT, GPIO.HIGH)\n time.sleep(0.2)\n GPIO.output(LEFT_STRAIGHT, GPIO.LOW)\n ws.send(f' recebido: {message}')\n elif (message == \"right\"):\n GPIO.output(RIGHT_STRAIGHT, GPIO.HIGH)\n time.sleep(0.2)\n GPIO.output(RIGHT_STRAIGHT, GPIO.LOW)\n ws.send(f' recebido: {message}')\n except:\n print('erro na execução')\n connected.remove(ws)\n GPIO.cleanup()\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5000, debug=False)\n video.release()\n", "repo_name": "lucassenazuza/roboto", "sub_path": "server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 2431, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "RPi.GPIO.setmode", "line_number": 20, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 20, "usage_type": "name"}, {"api_name": "RPi.GPIO.BCM", "line_number": 20, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 21, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 21, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 21, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 22, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 22, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 22, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 23, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 23, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 23, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 24, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 24, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flask.Flask", "line_number": 27, "usage_type": "call"}, {"api_name": "flask_sock.Sock", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 29, "usage_type": "call"}, {"api_name": "cv2.imencode", "line_number": 38, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 45, "usage_type": "call"}, {"api_name": "RPi.GPIO.output", "line_number": 54, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 54, "usage_type": "name"}, {"api_name": "RPi.GPIO.HIGH", "line_number": 54, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 55, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 55, "usage_type": "name"}, {"api_name": "RPi.GPIO.HIGH", "line_number": 55, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 56, "usage_type": "call"}, {"api_name": "RPi.GPIO.output", "line_number": 57, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 57, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 57, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 58, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 58, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 58, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 61, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 61, "usage_type": "name"}, {"api_name": "RPi.GPIO.HIGH", "line_number": 61, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 62, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 62, "usage_type": "name"}, {"api_name": "RPi.GPIO.HIGH", "line_number": 62, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 63, "usage_type": "call"}, {"api_name": "RPi.GPIO.output", "line_number": 64, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 64, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 64, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 65, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 65, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 65, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 68, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 68, "usage_type": "name"}, {"api_name": "RPi.GPIO.HIGH", "line_number": 68, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 69, "usage_type": "call"}, {"api_name": "RPi.GPIO.output", "line_number": 70, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 70, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 70, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.output", "line_number": 73, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 73, "usage_type": "name"}, {"api_name": "RPi.GPIO.HIGH", "line_number": 73, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 74, "usage_type": "call"}, {"api_name": "RPi.GPIO.output", "line_number": 75, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 75, "usage_type": "name"}, {"api_name": "RPi.GPIO.LOW", "line_number": 75, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.cleanup", "line_number": 80, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 80, "usage_type": "name"}]} +{"seq_id": "26448470763", "text": "import hashlib\nimport logging\nimport math\nimport os\nimport re\nfrom pathlib import Path\n\nfrom utils.constants import HASH_BUFFER_LEN, TEMP_FOLDER_PATH # MESSAGE_MAX_LEN,\nfrom utils.types import CompressionMethod, DirData, ItemSearchResult, Message, TransferProgress, TransferStatus\n\n\ndef generate_transfer_progress() -> dict[Path, TransferProgress]:\n \"\"\"Generate transfer progress data in absence of dump.\n\n Parses the user's tmp folder to find offsets for incommplete files.\n\n Returns\n -------\n dict[Path, TransferProgress]\n Returns transfer progress dictionary as generated\n \"\"\"\n transfer_progress: dict[Path, TransferProgress] = {}\n for root, _, files in os.walk(str(TEMP_FOLDER_PATH)):\n for file in files:\n path = Path(root).joinpath(file)\n transfer_progress[path] = {\n \"progress\": path.stat().st_size,\n \"status\": TransferStatus.PAUSED,\n }\n return transfer_progress\n\n\ndef path_to_dict(path: Path, share_folder_path: str) -> DirData:\n \"\"\"Converts a given folder path to a dictionary representation of the entire directory structure\n\n Recursively constructs the output dictionary.\n Works relative to the user's share folder.\n\n Parameters\n ----------\n path : Path\n Path to an item to be added to dictionary\n share_folder_path : str\n string path to user's share directory which contains the item at [path]\n\n Returns\n -------\n DirData\n Returns dictionary representation as defined by the DirData custom type\n \"\"\"\n d: DirData = {\n \"path\": str(path).removeprefix(share_folder_path + \"/\"),\n \"name\": path.name,\n \"hash\": None,\n \"compression\": CompressionMethod.NONE.value,\n \"type\": \"\",\n \"size\": None,\n \"children\": [],\n }\n if path.is_dir():\n d[\"type\"] = \"directory\"\n d[\"children\"] = [path_to_dict(item, share_folder_path) for item in path.iterdir()]\n else:\n d[\"type\"] = \"file\"\n d[\"size\"] = Path(path).stat().st_size\n\n return d\n\n\ndef get_files_in_dir(dir: list[DirData] | None, files: list[DirData]):\n \"\"\"Obtain only the file items in a given directory dictionary\n\n Recursively parses dictionary to obtain file items.\n Output is given in the [files] parameter.\n\n Parameters\n ----------\n dir : list[DirData]\n Directory structure starting from immediate children of the desired folder.\n files : list[DirData]\n Empty list which holds the output of this function.\n \"\"\"\n if dir is None:\n return\n for item in dir:\n if item[\"type\"] == \"file\":\n files.append(item)\n else:\n get_files_in_dir(item[\"children\"], files)\n\n\ndef item_search(dir: list[DirData] | None, items: list[ItemSearchResult], search_query: str, owner: str):\n \"\"\"Item search utility.\n\n Recurses a given file structure of a directory to find items that match a search string.\n On each item, the function performs a regex search for exact matches followed by a fuzzy search to capture potential spelling errors.\n Output is given in the [items] parameter.\n\n Parameters\n ----------\n dir : list[DirData]\n Directory structure starting from immediate children of the desired folder.\n items : list[ItemSearchResult]\n Empty list which holds the search results.\n search_query : str\n User provided keyword used for the search process.\n owner : str\n Username of the owner of given [dir]\n\n \"\"\"\n from fuzzysearch import find_near_matches\n\n if dir is None:\n return\n for item in dir:\n if re.search(search_query, item[\"name\"].lower()) is not None or find_near_matches(\n search_query, item[\"name\"].lower(), max_l_dist=1\n ):\n items.append(\n {\n \"owner\": owner,\n \"data\": item,\n }\n )\n if item[\"type\"] == \"directory\":\n item_search(item[\"children\"], items, search_query, owner)\n\n\ndef display_share_dict(share: list[DirData] | None, indents: int = 0):\n \"\"\"Utility to print a dir structure to stdout\"\"\"\n if share is None:\n return\n for item in share:\n if item[\"type\"] == \"file\":\n print(\" \" * indents + item[\"name\"])\n else:\n print(\" \" * indents + item[\"name\"] + \"/\")\n display_share_dict(item[\"children\"], indents + 1)\n\n\ndef update_file_hash(share: list[DirData], file_path: str, new_hash: str):\n \"\"\"Utility to set a new hash value for a specified item in a dir structure.\n\n Recurses a given folder structure and updates the hash attribute when the specified item is found.\n\n Parameters\n ----------\n share : list[DirData]\n Dir structure that comntains item to update\n file_path : str\n Path attribute of item to update\n new_hash: str\n New hash value to be set\n \"\"\"\n for item in share:\n if item[\"type\"] == \"file\" and item[\"path\"] == file_path:\n item[\"hash\"] = new_hash\n return\n elif item[\"children\"]:\n update_file_hash(item[\"children\"], file_path, new_hash)\n return\n\n\ndef find_file(share: list[DirData] | None, path: str) -> DirData | None:\n \"\"\"Utility to find a file item given the file path.\"\"\"\n if share is None:\n return None\n for item in share:\n if item[\"path\"] == path:\n return item\n else:\n s = find_file(item[\"children\"], path)\n if s is not None:\n return s\n return None\n\n\ndef get_file_hash(filepath: str) -> str:\n \"\"\"Calculate hash for a given file on disk.\n\n Reads the given file in chunks and calculates a rolling hash for the same.\n\n Parameters\n ----------\n filepath : str\n Path to a file for which to calculate hash.\n \"\"\"\n hash = hashlib.sha1()\n with open(filepath, \"rb\") as file:\n while True:\n file_bytes = file.read(HASH_BUFFER_LEN)\n hash.update(file_bytes)\n if len(file_bytes) < HASH_BUFFER_LEN:\n break\n return hash.hexdigest()\n\n\ndef get_unique_filename(path: Path) -> Path:\n \"\"\"Utility to generate a unique filename if a desired name already exists on disk.\n\n Adds an incremental numeric suffix to the filename if the original or a previous iteration of the name exists in the user's downloads folder.\n Prevents accidental overwriting that may occur if different files happen to have the same name.\n\n Parameters\n ----------\n path : Path\n Desired path name for the file\n\n Returns\n -------\n Path\n Unique-ified path name for the file\n \"\"\"\n parent, filename, extension = path.parent, path.stem, path.suffix\n counter = 1\n logging.debug(f\"parent: {parent}\")\n logging.debug(f\"making unique file for {path}\")\n while path.exists():\n path = parent / Path(filename + \"_\" + str(counter) + extension)\n counter += 1\n\n logging.debug(f\"unique file name is {path}\")\n return path\n\n\ndef get_pending_downloads(transfer_progress: dict[Path, TransferProgress]) -> str:\n \"\"\"Utility to get a displayable string populated with incomplete downloads\"\"\"\n return \"\\n\".join(\n [\n f\"{str(file).removeprefix(str(TEMP_FOLDER_PATH) + '/')}: {progress['status'].name}\"\n for (file, progress) in transfer_progress.items()\n if progress[\"status\"] in [TransferStatus.DOWNLOADING, TransferStatus.PAUSED, TransferStatus.NEVER_STARTED]\n ]\n )\n\n\ndef get_directory_size(directory: DirData, size: int, count: int) -> tuple[int, int]:\n \"\"\"Calculate directory size and contained files count for a given directory.\n\n Recurses a given directory to calculate the total size of the folder as well as the number of files present in it or its sub folders.\n\n Parameters\n ----------\n directory : DirData\n Directory structure for which to calculate the statistics\n size : int\n Parent level size value, helper param for recursive call\n count : int\n Parent level count value, helper param for recursive call\n\n Returns\n -------\n tuple[int, int]\n Returns a pair of calculated size, count\n \"\"\"\n count = 0\n size = 0\n if directory[\"children\"] is None:\n count += 1\n size += directory[\"size\"]\n else:\n for child in directory[\"children\"]:\n if child[\"type\"] == \"file\":\n count += 1\n size += child[\"size\"]\n else:\n child_size, child_count = get_directory_size(child, size, count)\n size += child_size\n count += child_count\n return size, count\n\n\ndef import_file_to_share(file_path: Path, share_folder_path: Path) -> Path | None:\n \"\"\"Utility to generate symlink to a given file in the user's share folder path.\n\n Parameters\n ----------\n file_path : Path\n Path to a file for which symlink will be generated.\n share_folder_path : Path\n Path to user's share folder where the symlink will be saved.\n \"\"\"\n if file_path.exists():\n imported_file = share_folder_path / file_path.name\n imported_file.symlink_to(file_path, target_is_directory=file_path.is_dir())\n return imported_file\n else:\n logging.error(f\"Attempted to import file {str(file_path)} that does not exist\")\n return None\n\n\ndef construct_message_html(message: Message, is_self: bool) -> str:\n \"\"\"Utility to construct markup for a given message object.\n\n Parameters\n ----------\n message : Message\n A message object to be rendered.\n is_self : bool\n Boolean representing whether the sender of the given message is the current user.\n This is used for rendering a \"You\" in the markup instead of a sender username.\n\n Returns\n -------\n str\n Generated message html as a string\n \"\"\"\n return f\"\"\"

\n{\"You\" if is_self else message[\"sender\"]}: \n{message[\"content\"]}\n

\n\"\"\"\n\n\ndef convert_size(size_bytes: int) -> str:\n \"\"\"Utility to convert a size (bytes) value to a human readable string.\n\n Generates a size string suffixed with a unit like B, KB, MB and so on.\n\n Parameters\n ----------\n size_bytes : int\n Size to be converted as number of bytes\n\n Returns\n -------\n str\n Human readable size string\n \"\"\"\n if size_bytes == 0:\n return \"0B\"\n size_name = [\"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"]\n i = int(math.floor(math.log(size_bytes, 1024)))\n p = math.pow(1024, i)\n s = round(size_bytes / p, 2)\n return f\"{s} {size_name[i]}\"\n", "repo_name": "hs2361/Drizzle", "sub_path": "src/utils/helpers.py", "file_name": "helpers.py", "file_ext": "py", "file_size_in_byte": 10844, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "27", "api": [{"api_name": "pathlib.Path", "line_number": 22, "usage_type": "name"}, {"api_name": "utils.types.TransferProgress", "line_number": 22, "usage_type": "name"}, {"api_name": "os.walk", "line_number": 23, "usage_type": "call"}, {"api_name": "utils.constants.TEMP_FOLDER_PATH", "line_number": 23, "usage_type": "argument"}, {"api_name": "pathlib.Path", "line_number": 25, "usage_type": "call"}, {"api_name": "utils.types.TransferStatus.PAUSED", "line_number": 28, "usage_type": "attribute"}, {"api_name": "utils.types.TransferStatus", "line_number": 28, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 12, "usage_type": "name"}, {"api_name": "utils.types.TransferProgress", "line_number": 12, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 33, "usage_type": "name"}, {"api_name": "utils.types.DirData", "line_number": 51, "usage_type": "name"}, {"api_name": "utils.types.CompressionMethod.NONE", "line_number": 55, "usage_type": "attribute"}, {"api_name": "utils.types.CompressionMethod", "line_number": 55, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 65, "usage_type": "call"}, {"api_name": "utils.types.DirData", "line_number": 33, "usage_type": "name"}, {"api_name": "utils.types.DirData", "line_number": 70, "usage_type": "name"}, {"api_name": "utils.types.DirData", "line_number": 92, "usage_type": "name"}, {"api_name": "utils.types.ItemSearchResult", "line_number": 92, "usage_type": "name"}, {"api_name": "re.search", "line_number": 116, "usage_type": "call"}, {"api_name": "fuzzysearch.find_near_matches", "line_number": 116, "usage_type": "call"}, {"api_name": "utils.types.DirData", "line_number": 129, "usage_type": "name"}, {"api_name": "utils.types.DirData", "line_number": 141, "usage_type": "name"}, {"api_name": "utils.types.DirData", "line_number": 164, "usage_type": "name"}, {"api_name": "hashlib.sha1", "line_number": 188, "usage_type": "call"}, {"api_name": "utils.constants.HASH_BUFFER_LEN", "line_number": 191, "usage_type": "argument"}, {"api_name": "utils.constants.HASH_BUFFER_LEN", "line_number": 193, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 198, "usage_type": "name"}, {"api_name": "logging.debug", "line_number": 216, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 217, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 219, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 222, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 226, "usage_type": "name"}, {"api_name": "utils.types.TransferProgress", "line_number": 226, "usage_type": "name"}, {"api_name": "utils.constants.TEMP_FOLDER_PATH", "line_number": 230, "usage_type": "argument"}, {"api_name": "utils.types.TransferStatus.DOWNLOADING", "line_number": 232, "usage_type": "attribute"}, {"api_name": "utils.types.TransferStatus", "line_number": 232, "usage_type": "name"}, {"api_name": "utils.types.TransferStatus.PAUSED", "line_number": 232, "usage_type": "attribute"}, {"api_name": "utils.types.TransferStatus.NEVER_STARTED", "line_number": 232, "usage_type": "attribute"}, {"api_name": "utils.types.DirData", "line_number": 237, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 273, "usage_type": "name"}, {"api_name": "logging.error", "line_number": 288, "usage_type": "call"}, {"api_name": "utils.types.Message", "line_number": 292, "usage_type": "name"}, {"api_name": "math.floor", "line_number": 333, "usage_type": "call"}, {"api_name": "math.log", "line_number": 333, "usage_type": "call"}, {"api_name": "math.pow", "line_number": 334, "usage_type": "call"}]} +{"seq_id": "515732697", "text": "\"\"\"empty message\n\nRevision ID: 23bde1fa9e41\nRevises: \nCreate Date: 2019-02-03 19:23:48.182688\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '23bde1fa9e41'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('blacklist_token',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('token', sa.String(length=255), nullable=False),\n sa.Column('blacklisted_on', sa.DateTime(), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('token')\n )\n op.create_table('item',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=255), nullable=False),\n sa.Column('brand', sa.String(length=255), nullable=True),\n sa.Column('category', sa.String(length=255), nullable=True),\n sa.Column('productCode', sa.String(length=255), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n op.create_table('users',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('email', sa.String(length=255), nullable=False),\n sa.Column('password', sa.String(length=255), nullable=False),\n sa.Column('registered_on', sa.DateTime(), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email')\n )\n op.create_table('user_action',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('username', sa.String(length=255), nullable=False),\n sa.Column('item_name', sa.String(length=255), nullable=True),\n sa.Column('variant_name', sa.String(length=255), nullable=True),\n sa.Column('action', sa.String(length=255), nullable=False),\n sa.Column('timestamp', sa.DateTime(), nullable=False),\n sa.ForeignKeyConstraint(['username'], ['users.email'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('variant',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=255), nullable=True),\n sa.Column('item_id', sa.Integer(), nullable=True),\n sa.Column('sellingPrice', sa.String(length=255), nullable=True),\n sa.Column('costPrice', sa.String(length=255), nullable=True),\n sa.Column('quantity', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['item_id'], ['item.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('variant')\n op.drop_table('user_action')\n op.drop_table('users')\n op.drop_table('item')\n op.drop_table('blacklist_token')\n # ### end Alembic commands ###\n", "repo_name": "pmishra06/Inventory", "sub_path": "migrations/versions/23bde1fa9e41_.py", "file_name": "23bde1fa9e41_.py", "file_ext": "py", "file_size_in_byte": 2709, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "alembic.op.create_table", "line_number": 21, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 21, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 24, "usage_type": "call"}, {"api_name": "sqlalchemy.DateTime", "line_number": 24, "usage_type": "call"}, {"api_name": "sqlalchemy.PrimaryKeyConstraint", "line_number": 25, "usage_type": "call"}, {"api_name": "sqlalchemy.UniqueConstraint", "line_number": 26, "usage_type": "call"}, {"api_name": "alembic.op.create_table", "line_number": 28, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 28, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 29, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 29, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 30, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 30, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 31, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 31, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 32, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 32, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 33, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 33, "usage_type": "call"}, {"api_name": "sqlalchemy.PrimaryKeyConstraint", "line_number": 34, "usage_type": "call"}, {"api_name": "sqlalchemy.UniqueConstraint", "line_number": 35, "usage_type": "call"}, {"api_name": "alembic.op.create_table", "line_number": 37, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 37, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 38, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 38, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 39, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 39, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 40, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 40, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 41, "usage_type": "call"}, {"api_name": "sqlalchemy.DateTime", "line_number": 41, "usage_type": "call"}, {"api_name": "sqlalchemy.PrimaryKeyConstraint", "line_number": 42, "usage_type": "call"}, {"api_name": "sqlalchemy.UniqueConstraint", "line_number": 43, "usage_type": "call"}, {"api_name": "alembic.op.create_table", "line_number": 45, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 45, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 46, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 46, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 47, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 47, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 48, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 48, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 49, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 49, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 50, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 50, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 51, "usage_type": "call"}, {"api_name": "sqlalchemy.DateTime", "line_number": 51, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 52, "usage_type": "call"}, {"api_name": "sqlalchemy.PrimaryKeyConstraint", "line_number": 53, "usage_type": "call"}, {"api_name": "alembic.op.create_table", "line_number": 55, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 55, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 56, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 56, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 57, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 57, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 58, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 58, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 59, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 59, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 60, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 60, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 61, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 61, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 62, "usage_type": "call"}, {"api_name": "sqlalchemy.PrimaryKeyConstraint", "line_number": 63, "usage_type": "call"}, {"api_name": "alembic.op.drop_table", "line_number": 70, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 70, "usage_type": "name"}, {"api_name": "alembic.op.drop_table", "line_number": 71, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 71, "usage_type": "name"}, {"api_name": "alembic.op.drop_table", "line_number": 72, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 72, "usage_type": "name"}, {"api_name": "alembic.op.drop_table", "line_number": 73, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 73, "usage_type": "name"}, {"api_name": "alembic.op.drop_table", "line_number": 74, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 74, "usage_type": "name"}]} +{"seq_id": "41265278314", "text": "import json\nimport copy\nINPUT_DATASET_FILES = ['filtered_spatial_commonsense/posrel.json', 'filtered_spatial_commonsense/height.json', 'filtered_spatial_commonsense/size.json']\nOUTPUT_DATASET_FILES = ['filtered_spatial_commonsense/posrel_coco.json', 'filtered_spatial_commonsense/height_coco.json', 'filtered_spatial_commonsense/size_coco.json']\nLABEL_TO_COCO_LABEL_GENERATION_FOLDER = 'filtered_spatial_commonsense'\nDATASET_LABEL_TO_COCO_LABEL = 'filtered_spatial_commonsense/dataset_label_to_coco_label.json'\ndef help_generate_class_to_coco_class():\n \"\"\"\n This function will generate a json file containing every object class in all INPUT_DATASET_FILES as keys.\n The idea is that the user is to then fill this file's values in order for this program to be able to make the change from the datasets' classes to coco classes.\n So this function will for example leave \"Man\" or \"Girl\" as keys and the user would have to fill \"person\" as the appropiate coco class to them.\n \"\"\"\n print(\"As no DATASET_LABEL_TO_LABEL_CLASS was given, a file helping the process of making it will be made in \"+LABEL_TO_COCO_LABEL_GENERATION_FOLDER+\"/empty_dataset_label_to_coco_label.json\")\n print(\"Every label present in the datasets provided will be saved as a json file's keys. The user is then expecteds to fill these with their respective coco object label for the translation to be made in a later execution.\")\n print(\"If a dataset label doesn't have a coco label counterpart, the entire key should be deleted. When using the file later the ammount of data points deleted because no coco label existed for them will be reported in the statistics.\")\n print()\n all_labels = []\n for dataset_path in INPUT_DATASET_FILES:\n with open(dataset_path, \"r\") as dataset_file:\n for jsonObj in dataset_file:\n data_point = json.loads(jsonObj)\n all_labels.append(data_point['obj_a'])\n all_labels.append(data_point['obj_b'])\n all_labels = set(all_labels)\n label_dict = {}#will contain every label as keys and an empty string as value. It will be saved and the user is supposed to fill the values with the corresponding coco label\n for label in all_labels:\n label_dict[label] = \"\"\n with open(LABEL_TO_COCO_LABEL_GENERATION_FOLDER+\"/empty_dataset_label_to_coco_label.json\",\"w\") as f:\n json.dump(label_dict, f, indent=4, sort_keys=True)\n print(\"all datset labels correctly saved\")\n show_coco_labels = input(\"would you like to get the list of all coco labels?[y/n]\")\n if show_coco_labels == 'y' or show_coco_labels=='Y':\n all_coco_labels = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush']\n all_coco_labels = sorted(all_coco_labels) #order alphabetically\n print(all_coco_labels)\ndef change_labels():\n print(\"initilizing object label translation for:\")\n for dataset_path in INPUT_DATASET_FILES:\n print(\" \"+dataset_path)\n print(\"resuts will be saved in:\")\n for dataset_path in OUTPUT_DATASET_FILES:\n print(\" \"+dataset_path)\n print(\"stats will be saved in \"+LABEL_TO_COCO_LABEL_GENERATION_FOLDER+\"/label_translation_stats.json\")\n #load label translator from any label to coco label\n with open(DATASET_LABEL_TO_COCO_LABEL, 'r') as f:\n label_to_coco_label = json.load(f)\n scs_datasets = []\n #load all datasets\n for dataset_path in INPUT_DATASET_FILES:\n current_dataset = []\n with open(dataset_path, \"r\") as dataset_file:\n for jsonObj in dataset_file:\n data_point = json.loads(jsonObj)\n current_dataset.append(data_point)\n scs_datasets.append(current_dataset)\n #time to do the actual filtering:\n #if any object's label is not in the translation dict, that data point will be removed.\n #when removing a data_point, we save in stats what label caused that removal and the data_point's label removed\n\n stats = {}\n stats['removed_labels'] = []\n for i,dataset in enumerate(scs_datasets):\n #for this dataset initialize stats and future dataset\n filtered_dataset = []\n stats[INPUT_DATASET_FILES[i]] = {}\n stats[INPUT_DATASET_FILES[i]]['n_removed_labels'] = {}\n stats[INPUT_DATASET_FILES[i]]['previous_total'] = len(dataset)\n stats[INPUT_DATASET_FILES[i]]['n_removed_labels']['total'] = 0\n for data_point in dataset:#initialize every possible data point label count to 0\n if data_point['label'] not in stats[INPUT_DATASET_FILES[i]]['n_removed_labels'].keys():\n stats[INPUT_DATASET_FILES[i]]['n_removed_labels'][data_point['label']]=0\n for data_point in dataset:\n data_point = copy.deepcopy(data_point)\n remove = False\n #check whether both object labels are in the translation dict.\n #if they are, trasnlate them individually\n if data_point['obj_a'] not in label_to_coco_label.keys():\n stats['removed_labels'].append(data_point['obj_a'])\n remove=True\n else:\n data_point['obj_a'] = label_to_coco_label[data_point['obj_a']]\n if data_point['obj_b'] not in label_to_coco_label.keys():\n stats['removed_labels'].append(data_point['obj_b'])\n remove=True\n else:\n data_point['obj_b'] = label_to_coco_label[data_point['obj_b']]\n if not remove:#if both object labels are in the translation dict\n filtered_dataset.append(data_point)\n else:# if they're not, it will be removed and stats must be updated\n stats[INPUT_DATASET_FILES[i]]['n_removed_labels'][data_point['label']] += 1\n stats[INPUT_DATASET_FILES[i]]['n_removed_labels']['total'] +=1\n stats[INPUT_DATASET_FILES[i]]['new_total'] = len(filtered_dataset)\n #save new dataset. (stats for all the datsets will be saved in the same place)\n with open(OUTPUT_DATASET_FILES[i],\"w\") as output_file:\n for data_point in filtered_dataset:\n json.dump(data_point, output_file)\n print(file=output_file)\n #save stats\n stats['removed_labels'] = list(set(stats['removed_labels']))\n with open(LABEL_TO_COCO_LABEL_GENERATION_FOLDER+\"/label_translation_stats.json\", \"w\") as f:\n json.dump(stats, f, indent=4)\ndef main():\n if DATASET_LABEL_TO_COCO_LABEL is None:\n help_generate_class_to_coco_class()\n else:\n change_labels()\nif __name__ == '__main__':\n main()", "repo_name": "EXUPLOOOOSION/text-to-layout", "sub_path": "Spatial CommonSense Test/change_labels_to_coco.py", "file_name": "change_labels_to_coco.py", "file_ext": "py", "file_size_in_byte": 7351, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "json.loads", "line_number": 21, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 29, "usage_type": "call"}, {"api_name": "json.load", "line_number": 46, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 53, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 73, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 96, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 101, "usage_type": "call"}]} +{"seq_id": "6229093463", "text": "from typing import Optional, List, Tuple\nfrom tqdm import tqdm\nfrom pathlib import Path\nfrom concurrent.futures import ThreadPoolExecutor\nimport os\nimport numpy as np\nimport argparse\n\nDEFAULT_FILTER_TAGS = [\"monochrome\", \"greyscale\"]\n\nBATCH_SIZE = 200\n\n\ndef check_contains_tags(caption_file: Path, filter_tags):\n with open(caption_file, \"r\") as f:\n caption = f.read()\n for filter_tag in filter_tags:\n if filter_tag in caption:\n return True\n return False\n\n\ndef move_caption_and_image(\n caption_file: Path,\n image_file: Path,\n caption_output_dir: Path,\n image_output_dir: Path,\n):\n os.rename(caption_file, caption_output_dir / caption_file.name)\n os.rename(image_file, image_output_dir / image_file.name)\n\n\ndef process_captions(\n caption_files: List[Path],\n filter_tags,\n images_dir,\n caption_output_dir,\n image_output_dir,\n pbar,\n):\n for caption_file in tqdm(caption_files):\n if check_contains_tags(caption_file, filter_tags):\n # search image file. image file has same stem but unknown extension\n image_file = next(images_dir.glob(f\"{caption_file.stem}.*\"))\n move_caption_and_image(\n caption_file, image_file, caption_output_dir, image_output_dir\n )\n # print(caption_file, image_file)\n pbar.update(1)\n\n\ndef main(args):\n captions_dir = args.captions_dir\n images_dir = args.images_dir\n if images_dir is None:\n images_dir = captions_dir\n\n caption_output_dir = Path(args.caption_output_dir)\n image_output_dir = Path(args.image_output_dir)\n\n filter_tags = args.filter_tags\n\n caption_files = list(captions_dir.glob(\"*.txt\"))\n\n print(\"Total captions:\", len(caption_files))\n\n if not caption_output_dir.exists():\n caption_output_dir.mkdir()\n\n if not image_output_dir.exists():\n image_output_dir.mkdir()\n\n chunks = np.array_split(caption_files, BATCH_SIZE)\n\n with tqdm(total=len(caption_files)) as pbar:\n with ThreadPoolExecutor(max_workers=BATCH_SIZE) as executor:\n futures = []\n for chunk in chunks:\n futures.append(\n executor.submit(\n process_captions,\n chunk,\n images_dir,\n filter_tags,\n caption_output_dir,\n image_output_dir,\n pbar,\n )\n )\n\n for future in futures:\n future.result()\n\n print(\"Done\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--captions_dir\",\n type=str,\n required=True,\n help=\"Path to directory containing captions\",\n )\n parser.add_argument(\n \"--images_dir\",\n type=str,\n help=\"Path to directory containing images\",\n )\n parser.add_argument(\n \"--caption_output_dir\",\n type=str,\n help=\"Path to directory to save captions\",\n )\n parser.add_argument(\n \"--image_output_dir\",\n type=str,\n help=\"Path to directory to save images\",\n )\n parser.add_argument(\n \"--filter_tags\",\n type=str,\n nargs=\"+\",\n default=DEFAULT_FILTER_TAGS,\n help=\"Tags to filter\",\n )\n args = parser.parse_args()\n main(args)\n", "repo_name": "p1atdev/sd-annotators", "sub_path": "caption_filter.py", "file_name": "caption_filter.py", "file_ext": "py", "file_size_in_byte": 3404, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pathlib.Path", "line_number": 14, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 24, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 25, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 26, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 27, "usage_type": "name"}, {"api_name": "os.rename", "line_number": 29, "usage_type": "call"}, {"api_name": "os.rename", "line_number": 30, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 34, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 34, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 41, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 58, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.array_split", "line_number": 73, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 75, "usage_type": "call"}, {"api_name": "concurrent.futures.ThreadPoolExecutor", "line_number": 76, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 98, "usage_type": "call"}]} +{"seq_id": "71695072384", "text": "\nimport os\nfrom os import listdir\nfrom skimage import io\nfrom skimage.color import rgb2gray\nfrom skimage.data import stereo_motorcycle\nfrom skimage.registration import phase_cross_correlation\nfrom skimage.transform import AffineTransform, warp\nimport numpy as np\nimport pandas as pd\nimport argparse\nfrom pathlib import Path\nfrom skimage.util import img_as_ubyte\nfrom skimage.util import img_as_uint\nfrom skimage import exposure\n\n \ndef parseArgs():\n parser = argparse.ArgumentParser(description=\"Image registration parameters\")\n parser.add_argument('-path_to_round1', default= \"/Users/isabelmo/Downloads/registration/testdata/round1\")\n parser.add_argument('-path_to_round2', default= \"/Users/isabelmo/Downloads/registration/testdata/round2\")\n parser.add_argument('-outputs', default= \"/Users/isabelmo/Downloads/registration/testdata/outputs\")\n args = parser.parse_args()\n return args\n\ndef cal_phase_correlate(fixed, moving):\n # calculate phase correlations\n shift, error, phasediff = phase_cross_correlation(fixed, moving)\n shift = [shift[1], shift[0]]\n shift = np.array(shift)\n shift = shift*-1\n print(shift, error, phasediff)\n return shift\n\ndef transform_phase_correlate(moving, shift):\n # calculate correction transform\n transform = AffineTransform(translation=shift)\n # apply it to round 2 image\n return warp(moving, transform)\n\ndef main():\n # load all image names into lists\n args = parseArgs()\n path_to_round1 = args.path_to_round1\n path_to_round2 = args.path_to_round2\n ls_imgs1_names = os.listdir(path_to_round1)\n ls_imgs2_names = os.listdir(path_to_round2)\n path_to_outputs = args.outputs \n Path(path_to_outputs + \"/regs\").mkdir(parents=True, exist_ok=True)\n\n image_r1_names = []\n\n # Create tables for each experiment\n for image_r1 in ls_imgs1_names:\n # For each DAPI image in round 1\n if '_DAPI_ORG' in image_r1:\n # add round 1 path list\n image_r1_names.append(image_r1)\n # store sample id\n spot_str = image_r1[-7:-4]\n\n image_r2_names = []\n # Find corresponding channel images from round 2\n for image_r2 in ls_imgs2_names:\n if f'roi{spot_str}' in image_r2:\n image_r2_names.append(image_r2)\n\n # for dapi from 2nd round calculate transformation\n for image_r2 in image_r2_names:\n if f'_DAPI_ORG_roi{spot_str}' in image_r2:\n # open round 1 & round 2 DAPIs\n fixed = io.imread(f\"{path_to_round1}/{image_r1}\")\n moving = io.imread(f\"{path_to_round2}/{image_r2}\")\n \n # calculate transformation\n shift = cal_phase_correlate(fixed, moving)\n\n # transform dapi\n moving = transform_phase_correlate(moving.astype(np.uint8), shift)\n #moving = moving.astype(np.uint8)\n #fixed = fixed.astype(np.uint8)\n \n\n # create tumbnails\n r1image = np.expand_dims(fixed, axis=-1)\n r2image = np.expand_dims(moving, axis=-1)\n thumbnail = np.concatenate([r1image, r2image, r2image], axis=-1)\n # print(thumbnail.shape)\n # exit()\n io.imsave(f'{path_to_outputs}/DAPIaftertransform_roi{spot_str}.jpg', thumbnail)\n break\n\n transformed_images = []\n # transform all round 2 images\n for image_r2 in image_r2_names:\n # open image\n moving = io.imread(f\"{path_to_round2}/{image_r2}\")\n #moving = moving.astype(np.uint8)\n #print(moving.dtype)\n\n # before\n\n # create tumbnails\n r1image = np.expand_dims(fixed, axis=-1)\n r2image = np.expand_dims(moving, axis=-1)\n r3image = np.zeros_like(r2image)\n thumbnail = np.concatenate([r1image, r2image, r3image], axis=-1)\n # print(thumbnail.shape)\n # exit()\n io.imsave(f'{path_to_outputs}/before_{image_r2}.jpg', thumbnail)\n\n # transform image\n #img_as_ubyte(moving)\n moving = transform_phase_correlate(moving, shift) #astype(np.uint8)\n moving = img_as_uint(moving)\n #image = exposure.rescale_intensity(moving, in_range='uint8')\n transformed_images.append(moving)\n #moving = moving.astype(np.uint8)\n print(moving.dtype)\n\n # after\n\n # create tumbnails\n r1image = np.expand_dims(fixed, axis=-1)\n r2image = np.expand_dims(moving, axis=-1)\n thumbnail = np.concatenate([r1image, r2image, r3image], axis=-1)\n # print(thumbnail.shape)\n # exit()\n io.imsave(f'{path_to_outputs}/after_{image_r2}.jpg', thumbnail)\n \n \n io.imsave(f'{path_to_outputs}/regs/{image_r2}', moving) #astype(np.uint16))\n #io.imsave(f'{path_to_outputs}/regs/{image_r2}', moving.astype(np.uint8))\n \n print(fixed.dtype)\n \n\nif __name__ == \"__main__\":\n main()\n ", "repo_name": "isabellamermaid/image_registration", "sub_path": "imagereg.py", "file_name": "imagereg.py", "file_ext": "py", "file_size_in_byte": 5409, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 19, "usage_type": "call"}, {"api_name": "skimage.registration.phase_cross_correlation", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 30, "usage_type": "call"}, {"api_name": "skimage.transform.AffineTransform", "line_number": 37, "usage_type": "call"}, {"api_name": "skimage.transform.warp", "line_number": 39, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 46, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 47, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 49, "usage_type": "call"}, {"api_name": "skimage.io.imread", "line_number": 72, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 72, "usage_type": "name"}, {"api_name": "skimage.io.imread", "line_number": 73, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 73, "usage_type": "name"}, {"api_name": "numpy.uint8", "line_number": 79, "usage_type": "attribute"}, {"api_name": "numpy.expand_dims", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 87, "usage_type": "call"}, {"api_name": "skimage.io.imsave", "line_number": 90, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 90, "usage_type": "name"}, {"api_name": "skimage.io.imread", "line_number": 97, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 97, "usage_type": "name"}, {"api_name": "numpy.expand_dims", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 107, "usage_type": "call"}, {"api_name": "skimage.io.imsave", "line_number": 110, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 110, "usage_type": "name"}, {"api_name": "skimage.util.img_as_uint", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 126, "usage_type": "call"}, {"api_name": "skimage.io.imsave", "line_number": 129, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 129, "usage_type": "name"}, {"api_name": "skimage.io.imsave", "line_number": 132, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 132, "usage_type": "name"}]} +{"seq_id": "43593169248", "text": "import statistics\n\nfrom datetime import date\nfrom datetime import datetime\nfrom datetime import timedelta\n\nfrom lib.jira import Jira\n\nclass ServiceDesk():\n\n def __init__(self, cache, config):\n self.cache = cache\n self.config = config\n\n def buildDatesPast12Months(self):\n\n # Build date ranges filter\n dates = []\n\n # Current month\n last = date.today()\n first = last.replace(day=1)\n\n dates.append({\n \"first\": f\"{first.year}/{first.month}/{first.day}\",\n \"last\": f\"{last.year}/{last.month}/{last.day}\",\n \"label\": f\"{last.year}/{last.month}\",\n })\n\n # First day of this month\n dt = date.today().replace(day=1)\n\n # Loop past last 12 months\n for i in range(12):\n\n # Last of previous month\n last = dt - timedelta(days=1)\n # First of previous month\n dt = first = last.replace(day=1)\n\n dates.append({\n \"first\": f\"{first.year}/{first.month}/{first.day}\",\n \"last\": f\"{last.year}/{last.month}/{last.day}\",\n \"label\": f\"{last.year}/{last.month}\",\n })\n\n dates.reverse()\n\n return dates\n\n def buildDatesYears(self):\n dates = []\n\n for d in range(self.config.jira['start_year'], date.today().year + 1):\n dates.append({\n \"first\": f\"{d}/01/01\",\n \"last\": f\"{d}/12/31\",\n \"label\": f\"{d}\",\n })\n\n return dates\n\n def buildDatesYearlyMonths(self):\n\n # Dates dict\n dates = {}\n\n # Today's date for comparison\n dt = date.today()\n\n # Date for iterate\n di = date(self.config.jira['start_year'], 1, 1)\n\n # Up until current month\n while di < dt:\n # Get first date\n first = di.replace(day=1)\n\n # Update di to next month\n di = (di + timedelta(days=35)).replace(day=1)\n\n # Get last date\n last = di - timedelta(days=1)\n\n # Add new year list\n if first.year not in dates:\n dates[first.year] = []\n\n # Add range to dates\n dates[first.year].append({\n \"first\": f\"{first.year}/{first.month}/{first.day}\",\n \"last\": f\"{last.year}/{last.month}/{last.day}\",\n \"label\": f\"{last.year}/{last.month}\",\n })\n\n return dates\n\n def buildDatesYearlySprints(self):\n\n # Dates dict\n dates = {}\n\n # Today's date for comparison\n dt = date.today()\n\n # Date for iterate\n di = date(2022, 1, 6)\n\n # Up until current month\n while di < dt:\n # Get first date\n first = di\n\n # Get last date\n last = first + timedelta(days=13)\n\n # Update di\n di = last + timedelta(days=1)\n\n # Add new year list\n if first.year not in dates:\n dates[first.year] = []\n i = 1\n\n # Add range to dates\n dates[first.year].append({\n \"first\": f\"{first.year}/{first.month}/{first.day}\",\n \"last\": f\"{last.year}/{last.month}/{last.day}\",\n \"label\": f\"{first.year}-{first.month}-{first.day}\",\n })\n i += 1\n\n return dates\n\n def calculateStats(self, values):\n # Size\n stats = {\n 'size': len(values)\n }\n\n # Maximum, Mean\n if len(values) > 0:\n stats['maximum'] = round(max(values), 2)\n stats['mean'] = round(statistics.mean(values), 2)\n else:\n stats['maximum'] = 0\n stats['mean'] = 0\n\n # Stdev\n if len(values) > 1:\n stats['stdev'] = round(statistics.stdev(values), 2)\n else:\n stats['stdev'] = 0\n\n # Minimum\n while (0.0 in values):\n values.remove(0.0)\n\n if len(values) > 0:\n stats['minimum'] = round(min(values), 2)\n else:\n stats['minimum'] = 0\n\n return stats\n\n def closedIssuesYearly(self, project, extra, cache):\n\n # Build projects filter\n project = self.formatProject(project)\n\n # Build date ranges filter\n dates = self.buildDatesYears()\n\n return self.queryClosedIssues(project, dates, extra, cache)\n\n def closedIssuesYearlyMonthly(self, project, extra, cache):\n\n # Build projects filter\n project = self.formatProject(project)\n\n # Build date ranges filter\n dates = self.buildDatesYearlyMonths()\n\n results = {}\n\n for y, d in dates.items():\n # Query Jira\n results[y] = self.queryClosedIssues(project, d, extra, cache)\n\n return results\n\n def formatProject(self, project):\n\n # Build projects filter\n if type(project) is str:\n return f\"'{project}'\"\n\n elif type(project) is list:\n return \",\".join(list(map(lambda x: f\"'{x}'\", project)))\n\n def queryClosedIssues(self, project, dates, extra, cache=False):\n\n results = {}\n\n fields = [\n \"summary\",\n \"status\",\n ]\n\n jira = Jira(self.config)\n\n for dt in dates:\n\n first = dt['first']\n last = dt['last']\n\n # Prepare jql query\n jql = f\"project in ({project}) AND status in (Closed, Resolved, Done) AND status changed to (Closed, Resolved, Done) DURING ('{first} 00:00','{last} 23:59') {extra}\"\n\n search = jira.apiSearch(jql, fields)\n\n if search:\n result = search.json()\n\n results[dt['label']] = result['total']\n\n if cache:\n self.cache.write(\n run=cache['run'],\n label=cache['label'],\n index=dt['label'],\n value=result['total']\n )\n\n print(f\"results: {results}\")\n\n return results\n\n def queryIssueTimingsCustom(self, project, dates, extra, cache):\n\n # Initiate results dict\n results = {}\n for k in self.config.jira['custom_fields'].keys():\n results[k] = {}\n\n # Initiate fields list\n fields = [\n \"summary\",\n \"status\",\n \"created\",\n ] + list(map(lambda x: x['field'], self.config.jira['custom_fields'].values()))\n\n jira = Jira(self.config)\n\n # Loop dates\n for item in dates.values():\n for dt in item:\n\n first = dt['first']\n last = dt['last']\n\n # Prepare jql query\n jql = f\"project in ({project}) AND status in (Closed, Resolved, Done) AND status changed to (Closed, Resolved, Done) DURING ('{first} 00:00','{last} 23:59') {extra}\"\n\n search = jira.apiSearch(jql, fields)\n\n if search:\n result = search.json()\n\n # Init results lists\n for k in self.config.jira['custom_fields'].keys():\n results[k][dt['label']] = []\n\n for i in result['issues']:\n # Loop custom fields\n # Time to: resolution, first response, close after resolution\n for k in self.config.jira['custom_fields'].keys():\n field = self.config.jira['custom_fields'][k]['field']\n if i ['fields'][field] is not None:\n if len(i['fields'][field]['completedCycles']) > 0:\n field_value = 0\n for j in i['fields'][field]['completedCycles']:\n field_value += j['elapsedTime']['millis']\n\n results[k][dt['label']].append(round(field_value / 1000 / 3600, 2))\n\n for k, v in results.items():\n for dt in v.keys():\n results[k][dt] = self.calculateStats(results[k][dt])\n\n self.cache.write(\n run=cache['run'],\n label=k,\n index=dt,\n value=results[k][dt]\n )\n\n print(f\"results: {k}: {v}\")\n\n return results\n\n def queryIssueTimingsResolution(self, project, dates, extra, cache):\n\n # Initiate results dict\n results = {}\n\n # Initiate fields list\n fields = [\n 'summary',\n 'status',\n 'created',\n 'resolutiondate',\n ]\n\n jira = Jira(self.config)\n\n # Loop dates\n for item in dates.values():\n for dt in item:\n\n first = dt['first']\n last = dt['last']\n\n # Prepare jql query\n jql = f\"project in ({project}) AND status in (Closed, Resolved, Done) AND status changed to (Closed, Resolved, Done) DURING ('{first} 00:00','{last} 23:59') {extra}\"\n\n search = jira.apiSearch(jql, fields)\n\n if search:\n result = search.json()\n\n # Init results list\n results[dt['label']] = []\n\n for i in result['issues']:\n if i['fields']['resolutiondate'] is not None:\n ts = datetime.strptime(i['fields']['resolutiondate'], '%Y-%m-%dT%H:%M:%S.000%z') - \\\n datetime.strptime(i['fields']['created'], '%Y-%m-%dT%H:%M:%S.000%z')\n\n results[dt['label']].append(round(ts.days + ts.seconds / 86400, 2))\n\n for k, v in results.items():\n results[k] = self.calculateStats(v)\n\n self.cache.write(\n run=cache['run'],\n label=cache['label'],\n index=k,\n value=results[k]\n )\n\n print(f\"results: {results}\")\n\n return results\n\n def runCoreTimingsServiceDesk(self, queries, run):\n\n # Init data dict\n data = {\n 'data': [],\n 'labels': [],\n }\n\n # Build date ranges filter\n dates = self.buildDatesYearlySprints()\n\n # Loop queries\n for q in queries:\n\n project = self.formatProject(project=q['project'])\n\n result = self.queryIssueTimingsCustom(\n project=project,\n dates=dates,\n extra=q['extra'],\n cache={\n 'run': run\n }\n )\n\n # Loop result by custom_field key\n for k in result.keys():\n\n # Set labels\n data['labels'] = list(result[k].keys())\n\n # Append data\n data['data'].append({\n 'data': {\n 'maximum': list(map(lambda x: x['maximum'], result[k].values())),\n 'mean': list(map(lambda x: x['mean'], result[k].values())),\n 'minimum': list(map(lambda x: x['minimum'], result[k].values())),\n 'size': list(map(lambda x: x['size'], result[k].values())),\n 'stdev': list(map(lambda x: x['stdev'], result[k].values())),\n },\n 'label': self.config.jira['custom_fields'][k]['description'],\n })\n\n return data\n\n def runCoreTimingsTeams(self, queries, run):\n\n # Init data dict\n data = {\n 'data': [],\n 'labels': []\n }\n\n # Build date ranges filter\n dates = self.buildDatesYearlySprints()\n\n # Loop queries\n for q in queries:\n\n project = self.formatProject(project=q['project'])\n\n result = self.queryIssueTimingsResolution(\n project=project,\n dates=dates,\n extra=q['extra'],\n cache={\n 'label': q['label'],\n 'run': run\n }\n )\n\n # Set labels\n data['labels'] = list(result.keys())\n\n # Append data\n data['data'].append({\n 'data': {\n 'maximum': list(map(lambda x: x['maximum'], result.values())),\n 'mean': list(map(lambda x: x['mean'], result.values())),\n 'minimum': list(map(lambda x: x['minimum'], result.values())),\n 'size': list(map(lambda x: x['size'], result.values())),\n 'stdev': list(map(lambda x: x['stdev'], result.values())),\n },\n 'label': q['label']\n })\n\n return data\n\n def runMonthly(self, queries):\n\n data = {\n 'data': [],\n 'labels': [],\n }\n\n # Build date ranges filter\n dates = self.buildDatesPast12Months()\n\n for q in queries:\n\n # Build projects filter\n project = self.formatProject(project=q['project'])\n\n # Query Jira\n result = self.queryClosedIssues(project, dates, q['extra'])\n\n # Add results to data.json\n data['labels'] = list(result.keys())\n data['data'].append({\n 'data': list(result.values()),\n 'label': f\"{q['label']} ({sum(result.values())})\"\n })\n\n return data\n\n def runYearlyComponents(self, queries, run):\n\n data = {}\n\n results = {}\n\n for q in queries:\n result = self.closedIssuesYearly(\n project=self.config.queries['sd']['project'],\n extra=f\"{self.config.queries['sd']['extra']} {q['extra']}\",\n cache={\n 'label': q['label'],\n 'run': run\n }\n )\n\n # Build results\n for y, i in result.items():\n # Skip zero entries\n if i != 0:\n if y in results:\n results[y][q['label']] = i\n else:\n results[y] = {}\n results[y][q['label']] = i\n\n # Add results to data.json\n for y, i in results.items():\n # Skip if all results sum to 0\n if sum(i.values()) != 0:\n # Initiate object\n if y not in data:\n data[y] = {\n 'data': [],\n 'labels': [],\n }\n\n # Calculate percentages\n p = {}\n for k, j in i.items():\n p[k] = j / sum(i.values()) * 100\n\n data[y]['labels'] = list(map(lambda x: f\"{x} ({p[x] :.1f}%)\", p.keys()))\n data[y]['data'].append({\n 'data': list(i.values()),\n 'label': y\n })\n\n return data\n\n def runYearlyMonthlyComponents(self, queries, run):\n\n data = {}\n\n results = {}\n\n for q in queries:\n result = self.closedIssuesYearlyMonthly(\n project=q['project'],\n extra=q['extra'],\n cache={\n 'label': q['label'],\n 'run': run\n }\n )\n\n # Build results\n for y, i in result.items():\n if y in results:\n results[y][q['label']] = i\n else:\n results[y] = {}\n results[y][q['label']] = i\n\n # Add results to data.json\n for y, i in results.items():\n\n # Check if total year sum > 0\n year_sum = 0\n\n for a in i.values():\n year_sum += sum(a.values())\n\n if year_sum == 0:\n continue\n\n # Initiate object\n if y not in data:\n data[y] = {\n 'data': [],\n 'labels': [],\n }\n\n # Monthly sums dict\n sums = {}\n\n for k, j in i.items():\n # Skip if all results sum to 0\n if sum(j.values()) != 0:\n # Calculate monthly sums\n for m in j.keys():\n if m in sums:\n sums[m] += j[m]\n else:\n sums[m] = j[m]\n\n data[y]['data'].append({\n 'data': list(j.values()),\n 'label': f\"{k} ({sum(j.values())})\"\n })\n\n # Apply labels\n data[y]['labels'] = list(map(lambda x: f\"{datetime.strptime(x, '%Y/%m').strftime('%b')} ({sums[x]})\", sums.keys()))\n\n return data\n\n def runYearlyStatistics(self, queries, run):\n\n stats = {}\n for q in queries:\n # Query Jira\n result = self.closedIssuesYearly(\n project=q['project'],\n extra=q['extra'],\n cache={\n 'label': q['label'],\n 'run': run\n }\n )\n\n # Build stats from result\n for k, v in result.items():\n if k in stats:\n stats[k][q['label']] = v\n else:\n stats[k] = {'Year': k}\n stats[k][q['label']] = v\n\n return stats\n", "repo_name": "accesspc/jira-reports", "sub_path": "app/app/servicedesk.py", "file_name": "servicedesk.py", "file_ext": "py", "file_size_in_byte": 17468, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "datetime.date.today", "line_number": 21, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 21, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 31, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 37, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 54, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 54, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 69, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 69, "usage_type": "name"}, {"api_name": "datetime.date", "line_number": 72, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 80, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 83, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 104, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 104, "usage_type": "name"}, {"api_name": "datetime.date", "line_number": 107, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 115, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 118, "usage_type": "call"}, {"api_name": "statistics.mean", "line_number": 144, "usage_type": "call"}, {"api_name": "statistics.stdev", "line_number": 151, "usage_type": "call"}, {"api_name": "lib.jira.Jira", "line_number": 210, "usage_type": "call"}, {"api_name": "lib.jira.Jira", "line_number": 253, "usage_type": "call"}, {"api_name": "lib.jira.Jira", "line_number": 315, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 337, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 337, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 338, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 338, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 583, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 583, "usage_type": "name"}]} +{"seq_id": "19022932612", "text": "import argparse\nimport platform\nimport sys\n\nimport requests\n\nimport pytwot\n\n\ndef show_version():\n entries = []\n\n entries.append(\"- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}\".format(sys.version_info))\n entries.append(\"- pytwot v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}\".format(pytwot.version_info))\n entries.append(f\"- requests v{requests.__version__}\")\n uname = platform.uname()\n entries.append(\"- system info: {0.system} {0.release} {0.version}\".format(uname))\n print(\"\\n\".join(entries))\n\n\ndef core(args):\n if args.version:\n show_version()\n else:\n print(\n \"Hi Thank you for using pytwot! You can do can do `python3 -m pytwot --version` for version info!\\n\\nDocs: https://py-tweet.readthedocs.io/ \\nGithub: https://github.com/sengolda/pytwot/\"\n )\n\n\ndef parse_args():\n argparser = argparse.ArgumentParser()\n argparser.add_argument(\"-v\", \"--version\", action=\"store_true\", help=\"shows the library versioninfo\")\n argparser.set_defaults(func=core)\n return argparser.parse_args()\n\n\ndef main():\n args = parse_args()\n args.func(args)\n\n\nif __name__ == \"__main__\":\n main()\n", "repo_name": "Sengolda/pytwot", "sub_path": "pytwot/__main__.py", "file_name": "__main__.py", "file_ext": "py", "file_size_in_byte": 1162, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sys.version_info", "line_number": 13, "usage_type": "attribute"}, {"api_name": "pytwot.version_info", "line_number": 14, "usage_type": "attribute"}, {"api_name": "requests.__version__", "line_number": 15, "usage_type": "attribute"}, {"api_name": "platform.uname", "line_number": 16, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "72945464703", "text": "import linajea\nfrom linajea.tracking import TrackGraph\nimport daisy\nimport logging\nimport argparse\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO)\n\n\ndef check_for_duplicate_gt_tracks(\n gt_db_name,\n db_host,\n start_frame,\n end_frame,\n cell_radius,\n node_overlap_threshold):\n roi = daisy.Roi((start_frame, 0, 0, 0),\n (end_frame - start_frame, 10000, 10000, 10000))\n gt_db = linajea.CandidateDatabase(gt_db_name, db_host)\n gt_graph = gt_db[roi]\n if not gt_graph.number_of_edges():\n logger.info(\"No edges in database. Skipping track formation.\")\n return\n\n track_graph = TrackGraph(gt_graph)\n tracks = track_graph.get_tracks()\n\n logger.info(\"Found {} tracks\".format(len(tracks)))\n for track_id, track in enumerate(tracks):\n for cell_id in track.nodes():\n track_graph.nodes[cell_id]['track_id'] = track_id\n\n # Count how many times each pair of tracks has cells close to each other\n dup_counts = {}\n for frame, cells in track_graph._cells_by_frame.items():\n for i in range(len(cells)):\n cell1 = cells[i]\n for j in range(i + 1, len(cells)):\n cell2 = cells[j]\n if 'track_id' not in track_graph.nodes[cell1]:\n print(cell1)\n print(track_graph.nodes[cell1])\n track1 = track_graph.nodes[cell1]['track_id']\n track2 = track_graph.nodes[cell2]['track_id']\n if track1 == track2:\n continue\n if close(track_graph.nodes[cell1],\n track_graph.nodes[cell2],\n cell_radius):\n logger.info(\"These cells are close together: %d %s %d %s\"\n % (cell1, track_graph.nodes[cell1],\n cell2, track_graph.nodes[cell2]))\n tup = (min(track1, track2), max(track1, track2))\n dup_counts[tup] = 1 if tup not in dup_counts\\\n else dup_counts[tup] + 1\n print(dup_counts)\n\n for pair in dup_counts:\n if dup_counts[pair] < node_overlap_threshold:\n continue\n print(\"Tracks {} and {} are duplicates\".format(*pair))\n t1 = tracks[pair[0]]\n t2 = tracks[pair[1]]\n print(\"%d has %d cells, %d has %d cells\"\n % (pair[0], t1.number_of_nodes(),\n pair[1], t2.number_of_nodes()))\n to_delete = pair[0] if t1.number_of_nodes() < t2.number_of_nodes()\\\n else pair[1]\n print(\"Would delete track {}\".format(to_delete))\n\n\ndef close(c1, c2, cell_radius):\n p1 = [c1['z'], c1['y'], c1['x']]\n p2 = [c2['z'], c2['y'], c2['x']]\n assert len(p1) == len(p2)\n for dim in range(len(p1)):\n if abs(p1[dim] - p2[dim]) > cell_radius:\n return False\n return True\n\n\ndef check_missing_edges(\n gt_db_name,\n db_host,\n start_frame,\n end_frame,\n move_distance):\n roi = daisy.Roi((start_frame, 0, 0, 0),\n (end_frame - start_frame, 10000, 10000, 10000))\n gt_db = linajea.CandidateDatabase(gt_db_name, db_host)\n gt_graph = gt_db[roi]\n if not gt_graph.number_of_edges():\n logger.info(\"No edges in database. Skipping track formation.\")\n return\n\n track_graph = TrackGraph(gt_graph)\n tracks = track_graph.get_tracks()\n\n logger.info(\"Found {} tracks\".format(len(tracks)))\n for track_id, track in enumerate(tracks):\n for cell_id in track.nodes():\n track_graph.nodes[cell_id]['track_id'] = track_id\n\n missing_edges = {}\n for frame, cells in track_graph._cells_by_frame.items():\n prev_frame = frame - 1\n if prev_frame not in track_graph._cells_by_frame:\n continue\n prev_cells = track_graph._cells_by_frame[prev_frame]\n for i in range(len(cells)):\n cell1 = cells[i]\n if len(track_graph.prev_edges(cell1)) > 0:\n continue\n for j in range(len(prev_cells)):\n cell2 = prev_cells[j]\n if 'track_id' not in track_graph.nodes[cell1]:\n print(cell1)\n print(track_graph.nodes[cell1])\n track1 = track_graph.nodes[cell1]['track_id']\n track2 = track_graph.nodes[cell2]['track_id']\n if track1 == track2:\n continue\n if close(track_graph.nodes[cell1],\n track_graph.nodes[cell2],\n move_distance):\n logger.info(\"These cells are close together and \"\n \"potentially missing an edge between them: \"\n \"%d %s %d %s\"\n % (cell1, track_graph.nodes[cell1],\n cell2, track_graph.nodes[cell2]))\n missing_edges[(cell1, cell2)] = (track_graph.nodes[cell1],\n track_graph.nodes[cell2])\n\n print(\"Found %d potential missing edges:\" % len(missing_edges))\n approved_ids = []\n for ids, locs in missing_edges.items():\n print(\"%s %s %s %s\" % (ids[0], locs[0], ids[1], locs[1]))\n merge = input().strip()\n while merge not in ['y', 'n']:\n merge = input(\"Please enter y or n\")\n if merge == 'y':\n approved_ids.append(ids)\n print(\"Approved %d missing edges: %s\" % (len(approved_ids), approved_ids))\n\n\ndef check_degree(\n gt_db_name,\n db_host,\n start_frame,\n end_frame):\n roi = daisy.Roi((start_frame, 0, 0, 0),\n (end_frame - start_frame, 10000, 10000, 10000))\n gt_db = linajea.CandidateDatabase(gt_db_name, db_host)\n logger.info(\"Reading GT cells and edges in %s\" % roi)\n gt_subgraph = gt_db[roi]\n node_degrees = {node: degree for node, degree in gt_subgraph.in_degree()}\n max_node_degree = max(node_degrees.values())\n logger.info(\"Max node degree for subgraph: %s\" % max_node_degree)\n if max_node_degree > 2:\n logger.info(\"Expected max in_degree <=2, got %d. \\n %s\"\n % (max_node_degree, str(node_degrees)))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"gt_db_name\")\n parser.add_argument(\"cell_radius\")\n parser.add_argument(\"node_overlap_threshold\")\n parser.add_argument(\"move_threshold\")\n parser.add_argument(\"-f\", \"--frames\", type=int, nargs=2, default=[0, 10e5])\n args = parser.parse_args()\n gt_db_name = args.gt_db_name\n start_frame, end_frame = args.frames\n cell_radius = args.cell_radius\n node_overlap_threshold = args.node_overlap_threshold\n move_threshold = args.move_threshold\n\n db_host = \"localhost\"\n\n check_for_duplicate_gt_tracks(\n gt_db_name, db_host,\n start_frame, end_frame,\n int(cell_radius), int(node_overlap_threshold))\n check_missing_edges(\n gt_db_name, db_host,\n start_frame, end_frame,\n int(move_threshold))\n check_degree(gt_db_name, db_host, start_frame, end_frame)\n", "repo_name": "funkelab/linajea_experiments", "sub_path": "data/scripts/check_duplicate_gt_and_missing_edges.py", "file_name": "check_duplicate_gt_and_missing_edges.py", "file_ext": "py", "file_size_in_byte": 7230, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 7, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 8, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 8, "usage_type": "attribute"}, {"api_name": "daisy.Roi", "line_number": 18, "usage_type": "call"}, {"api_name": "linajea.CandidateDatabase", "line_number": 20, "usage_type": "call"}, {"api_name": "linajea.tracking.TrackGraph", "line_number": 26, "usage_type": "call"}, {"api_name": "daisy.Roi", "line_number": 89, "usage_type": "call"}, {"api_name": "linajea.CandidateDatabase", "line_number": 91, "usage_type": "call"}, {"api_name": "linajea.tracking.TrackGraph", "line_number": 97, "usage_type": "call"}, {"api_name": "daisy.Roi", "line_number": 152, "usage_type": "call"}, {"api_name": "linajea.CandidateDatabase", "line_number": 154, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 166, "usage_type": "call"}]} +{"seq_id": "40201359012", "text": "from matplotlib import pyplot as plt\nimport numpy as np \n\nf = open('idea1.txt', 'r')\na = f.read()\nf.close()\n\n\na = a.split()\n\ndic = {}\n\nfor j,i in enumerate(a):\n\tif j%2==0 and j%4!=0:\n\t\tx = int(a[j])\n\t\ty = int(a[j+1])\n\t\ttry:\n\t\t\tr = abs(x-y)/x\n\t\texcept:\n\t\t\tr = 0\n\t\tif r in dic:\n\t\t\tdic[r] += 1\n\t\telse:\n\t\t\tdic[r] = 1\n\narr = sorted(dic)\ndic1 = {(i):dic[i] for i in arr[1:]}\n\nplt.xlabel('Relative Error')\nplt.ylabel('Frequency')\nplt.plot(list(dic1.keys()), list(dic1.values()))\nplt.show()\n\n# plt.bar(dic1.keys(), dic1.values(), width=0.1,color='b')\n# plt.show()", "repo_name": "vinusankarsiitgn/My-approx", "sub_path": "distrib.py", "file_name": "distrib.py", "file_ext": "py", "file_size_in_byte": 557, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "matplotlib.pyplot.xlabel", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}]} +{"seq_id": "22264288368", "text": "import torch\nfrom torch import nn\nfrom torchsummary import summary\n\nclass CNN(nn.Module):\n\n def __init__(self):\n super().__init__()\n\n # 4 conv layer -> flatten -> linear -> softmax\n self.conv1 = nn.Sequential(\n nn.Conv2d(\n in_channels=1,\n out_channels=16,\n kernel_size=3,\n stride=1,\n padding=2\n ),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2)\n )\n self.conv2 = nn.Sequential(\n nn.Conv2d(\n in_channels=16,\n out_channels=32,\n kernel_size=3,\n stride=1,\n padding=2\n ),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2)\n )\n self.conv3 = nn.Sequential(\n nn.Conv2d(\n in_channels=32,\n out_channels=64,\n kernel_size=3,\n stride=1,\n padding=2\n ),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2)\n )\n self.conv4 = nn.Sequential(\n nn.Conv2d(\n in_channels=64,\n out_channels=128,\n kernel_size=3,\n stride=1,\n padding=2\n ),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2)\n )\n self.flatten = nn.Flatten()\n self.linear = nn.Linear(in_features=128 * 5 * 4, out_features=8)\n\n def forward(self, input_data):\n x = self.conv1(input_data)\n x = self.conv2(x)\n x = self.conv3(x)\n x = self.conv4(x)\n x = self.flatten(x)\n logits = self.linear(x)\n\n return logits\n\n\nif __name__ == \"__main__\":\n cnn = CNN()\n summary(cnn.cuda(), (1, 64, 44))\n", "repo_name": "kshipra-jadav/pytorch_audio_classification", "sub_path": "final/cnn.py", "file_name": "cnn.py", "file_ext": "py", "file_size_in_byte": 1801, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "torch.nn.Module", "line_number": 5, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 5, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 11, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 11, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 12, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 12, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 30, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 31, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 33, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 34, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 41, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 42, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 44, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 45, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 52, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 53, "usage_type": "name"}, {"api_name": "torch.nn.Flatten", "line_number": 55, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 55, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 56, "usage_type": "name"}, {"api_name": "torchsummary.summary", "line_number": 71, "usage_type": "call"}]} +{"seq_id": "22913294085", "text": "#!/usr/bin/python3\n\"\"\"The ``5-filter_cities`` module takes in the name of a states as an\n argument and lists all cities of that state, using the database\n 'hbtn_0e_4_usa'\n\"\"\"\nimport sys\nimport MySQLdb\n\nif __name__ == '__main__':\n if len(sys.argv) < 5:\n sys.exit(1)\n db = MySQLdb.connect(host=\"localhost\", port=3306, user=sys.argv[1],\n passwd=sys.argv[2], db=sys.argv[3])\n cur = db.cursor()\n cur.execute(\"\"\"SELECT cities.name FROM cities INNER JOIN states\n ON states.id = cities.state_id WHERE states.name LIKE %s\n ORDER BY cities.id ASC\"\"\", (sys.argv[4],))\n cities = cur.fetchall()\n j = 0\n for city in cities:\n for i in city:\n if j == 0:\n print(\"{}\".format(i), end=\"\")\n j += 1\n continue\n print(\", {}\".format(i), end=\"\")\n print()\n\n cur.close()\n db.close()\n", "repo_name": "budiong054/alx-higher_level_programming", "sub_path": "0x0F-python-object_relational_mapping/5-filter_cities.py", "file_name": "5-filter_cities.py", "file_ext": "py", "file_size_in_byte": 926, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sys.argv", "line_number": 10, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 11, "usage_type": "call"}, {"api_name": "MySQLdb.connect", "line_number": 12, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 12, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 13, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 17, "usage_type": "attribute"}]} +{"seq_id": "8279209707", "text": "import numpy as np\nimport torch\n\nclass AApLayer(torch.nn.Module):\n def __init__(self, n_in, n_out, aging_generator, args):\n super().__init__()\n self.args = args\n self.device = args.DEVICE\n \n theta = torch.rand([n_in + 2, n_out])/100. + args.gmin\n theta[-1, :] = theta[-1, :] + args.gmax\n theta[-2, :] = args.ACT_eta3/(1.-args.ACT_eta3)*(torch.sum(theta[:-2,:], axis=0)+theta[-1,:])\n self.theta_ = torch.nn.Parameter(theta, requires_grad=True)\n \n # initialize time sampling\n # t = 0 equals nominal training\n self.K = args.K_train\n if args.MODE == 'nominal':\n self.t = torch.tensor([0.])\n else:\n self.t = torch.linspace(0, 1, self.K)\n # initialize aging model\n self.M = args.M_train\n self.aging_generator = aging_generator\n \n # initialization for variation\n self.N = args.N_train\n self.epsilon = args.e_train\n \n @property\n def agingmodels(self):\n return self.aging_generator.get_models(self.M*self.theta_.numel()*self.N) # M aging models for each sampled theta (N variations)\n\n @property\n def theta_ideal(self):\n self.theta_.data.clamp_(-self.args.gmax, self.args.gmax)\n theta_temp = self.theta_.clone()\n theta_temp[theta_temp.abs() < self.args.gmin] = 0.\n return theta_temp.detach() + self.theta_ - self.theta_.detach()\n \n @property\n def theta(self):\n mean = self.theta_ideal.repeat(self.N, 1, 1)\n variation = (torch.rand(mean.shape)*2. - 1.) * self.epsilon + 1.\n return mean.to(self.device) * variation.to(self.device)\n \n @property\n def theta_aged(self):\n # generate aging decay coefficient [M, K, N, n_in, n_out]\n aging_decay = torch.tensor([m(self.t) for m in self.agingmodels]) # [M*N*n_in*n_out, K]\n aging_decay = aging_decay.reshape(self.M,self.theta.shape[0],self.theta.shape[1],self.theta.shape[2],self.K).permute(0,4,1,2,3)\n # broad casting: [M, K, N, n_in, n_out] * [N, n_in, n_out] -> multiply for the last 2 dimension\n return self.theta * aging_decay.to(self.device)\n \n @property\n def W(self):\n return self.theta_aged.abs() / torch.sum(self.theta_aged.abs(), axis=3, keepdim=True)\n\n def INV(self, x):\n return -(self.args.NEG_eta1 + self.args.NEG_eta2 * torch.tanh((x - self.args.NEG_eta3) * self.args.NEG_eta4))\n \n def MAC(self, a):\n # 0 and positive thetas are corresponding to no negative weight circuit\n positive = self.theta.clone().to(self.device)\n positive[positive >= 0] = 1.\n positive[positive < 0] = 0.\n negative = 1. - positive\n # a in [M, K, N, E, n_in]\n a_extend = torch.cat([a,\n torch.ones( [a.shape[0], a.shape[1], a.shape[2], a.shape[3], 1]).to(self.device),\n torch.zeros([a.shape[0], a.shape[1], a.shape[2], a.shape[3], 1]).to(self.device)], dim=4)\n a_neg = self.INV(a_extend)\n a_neg[:,:,:,:,-1] = 0.\n z = torch.matmul(a_extend, self.W * positive) + torch.matmul(a_neg, self.W * negative)\n return z\n \n def ACT(self, z):\n return self.args.ACT_eta1 + self.args.ACT_eta2 * torch.tanh((z - self.args.ACT_eta3) * self.args.ACT_eta4)\n \n def forward(self, a_previous):\n z_new = self.MAC(a_previous)\n a_new = self.ACT(z_new)\n return a_new\n \n def SetParameter(self, name, value):\n # set time sampling and update K\n if name == 't':\n self.t = value\n self.K = self.t.shape[0]\n # set number of aging-model sampling M\n elif name == 'M':\n self.M = value\n # set number of samples\n elif name == 'N':\n self.N = value\n # set variations\n elif name == 'epsilon':\n self.epsilon = value\n # set device\n elif name == 'device':\n self.device = value\n \n\nclass AApNN(torch.nn.Module):\n def __init__(self, topology, aging_generator, args):\n super().__init__()\n self.args = args\n self.M = args.M_train\n self.K = args.K_train\n if args.MODE == 'nominal':\n self.t = torch.tensor([0.])\n else:\n self.t = torch.linspace(0, 1, self.K)\n self.N = args.N_train\n self.epsilon = args.e_train\n self.model = torch.nn.Sequential()\n self.device = args.DEVICE\n for i in range(len(topology)-1):\n self.model.add_module(f'{i}-th pLayer', AApLayer(topology[i], topology[i+1], aging_generator, args))\n \n def forward(self, X):\n X_extend = X.repeat(self.M, self.K, self.N, 1, 1)\n return self.model(X_extend)\n \n def SetParameter(self, name, value):\n # set time sampling and update K\n if name == 't':\n self.t = value\n self.K = self.t.shape[0]\n for m in self.model:\n m.SetParameter('t', self.t)\n # set number of time sampling K and generate random time sampling\n elif name == 'K':\n self.K = value\n self.t = torch.rand(self.K)\n for m in self.model:\n m.SetParameter('t', self.t)\n # set number of aging-model sampling M\n elif name == 'M':\n self.M = value\n for m in self.model:\n m.SetParameter('M', self.M)\n # set number of samples\n elif name == 'N':\n self.N = value\n for m in self.model:\n m.SetParameter('N', self.N)\n # set variations\n elif name == 'epsilon':\n self.epsilon = value\n for m in self.model:\n m.SetParameter('epsilon', self.epsilon)\n # set device\n elif name == 'device':\n self.device = value\n for m in self.model:\n m.SetParameter('device', self.device)\n \n\nclass Lossfunction(torch.nn.Module):\n def __init__(self, args):\n super().__init__()\n self.args = args\n\n def standard(self, prediction, label): \n label = label.reshape(-1, 1)\n fy = prediction.gather(1, label).reshape(-1, 1)\n fny = prediction.clone()\n fny = fny.scatter_(1, label, -10 ** 10)\n fnym = torch.max(fny, axis=1).values.reshape(-1, 1)\n l = torch.max(self.args.m + self.args.T - fy, torch.tensor(0)) + torch.max(self.args.m + fnym, torch.tensor(0))\n L = torch.mean(l)\n return L\n \n def MonteCarlo(self, prediction, label):\n M = prediction.shape[0]\n K = prediction.shape[1]\n N = prediction.shape[2]\n loss = torch.tensor(0.).to(self.args.DEVICE)\n for m in range(M):\n for k in range(K):\n for n in range(N):\n loss += self.standard(prediction[m,k,n,:,:], label)\n return loss / M / K / N\n \n def GaussianQuadrature(self, prediction, label):\n return torch.tensor(0.)\n \n def forward(self, prediction, label):\n if self.args.integration == 'MC':\n return self.MonteCarlo(prediction, label)\n elif self.args.integration == 'GQ':\n return self.GaussianQuadrature(prediction, label)", "repo_name": "Neuromophic/Aging-aware-training", "sub_path": "pNN_aging.py", "file_name": "pNN_aging.py", "file_ext": "py", "file_size_in_byte": 7254, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "torch.nn", "line_number": 4, "usage_type": "attribute"}, {"api_name": "torch.rand", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 12, "usage_type": "call"}, {"api_name": "torch.nn.Parameter", "line_number": 13, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 13, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.linspace", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.rand", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.tanh", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 69, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.tanh", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 104, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 111, "usage_type": "call"}, {"api_name": "torch.linspace", "line_number": 113, "usage_type": "call"}, {"api_name": "torch.nn.Sequential", "line_number": 116, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 116, "usage_type": "attribute"}, {"api_name": "torch.rand", "line_number": 135, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 160, "usage_type": "attribute"}, {"api_name": "torch.max", "line_number": 170, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 171, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 171, "usage_type": "call"}, {"api_name": "torch.mean", "line_number": 172, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 179, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 187, "usage_type": "call"}]} +{"seq_id": "25616515380", "text": "import pickle as pkl\nfrom pathlib import Path\nimport numpy as np\n\nfrom aes670hw2 import enhance as enh\nfrom aes670hw2 import geo_plot as gp\n\ndef wrap_pixels(X, cycle_num, cycle_size, num_px):\n \"\"\"\n Based on the cycle size, the number of concatenated \"cycle split\" cycles,\n and the number of appended pixels per cycle in a 1D dataset, split the\n dataset back into the original continuous time series per pixel\n \"\"\"\n X = X[cycle_num*cycle_size:cycle_num*cycle_size+cycle_size]\n return np.split(X, num_px, axis=0)\n\n\nif __name__==\"__main__\":\n model_dir = Path(\"models/set003\")\n\n set_label = \"silty-loam_set003\"\n\n \"\"\"\n Parameters for 'wrapping' a dataset generated with the\n cycle-split technique datasets\n \"\"\"\n # Size of the\n cycle_size = 8064 # set003 training data\n #cycle_size = 2016 # set003 validation/testing data\n num_px = 12 # for unraveling pixels in each dataset\n #CNUM = 2 # cycle number\n #PNUM = 10\n for CNUM in range(4):\n for PNUM in range(12):\n TITLE = f\"Set 3 model on training data, C{CNUM}/P{PNUM}\"\n\n fig_dir = Path(f\"figures/output_curves/\")\n fig_path = fig_dir.joinpath(\n Path(f\"{set_label}_train_C{CNUM}_P{PNUM}.png\"))\n\n #checkpoint_file = Path(\"data/model_check/set001\")\n checkpoint_file = model_dir.joinpath(\"checkpoint\")\n\n t_out, v_out, s_out = pkl.load(model_dir.joinpath(\n f\"output/{set_label}_out.pkl\").open(\"rb\"))\n\n \"\"\" Load the pickles of model input data \"\"\"\n t_pkl = model_dir.joinpath(f\"input/{set_label}_training.pkl\")\n v_pkl = model_dir.joinpath(f\"input/{set_label}_validation.pkl\")\n s_pkl = model_dir.joinpath(f\"input/{set_label}_testing.pkl\")\n\n t_feat,t_truth,t_times = pkl.load(t_pkl.open(\"rb\"))\n v_feat,v_truth,v_times = pkl.load(v_pkl.open(\"rb\"))\n s_feat,s_truth,s_times = pkl.load(s_pkl.open(\"rb\"))\n\n \"\"\" Configure the dataset to model and plot \"\"\"\n TRUTH = t_truth\n OUT = t_out\n TIMES = t_times\n\n print(\"TRUTH:\",TRUTH.shape)\n print(\"MODEL:\",OUT.shape)\n\n # Extract the truth basis sample and split it into curves for each\n # independent soil depth level\n TRUTH = wrap_pixels(TRUTH, CNUM, cycle_size, num_px)[PNUM]\n TRUTH = [TRUTH[:,i] for i in range(TRUTH.shape[1])]\n OUT = wrap_pixels(OUT, CNUM, cycle_size, num_px)[PNUM]\n OUT = [OUT[:,i] for i in range(OUT.shape[1])]\n ipos = CNUM*cycle_size\n TIMES = [ t.strftime(\"%j\") for t in TIMES[CNUM] ]\n\n gp.plot_lines(\n TIMES,\n TRUTH+OUT,\n show=False,\n plot_spec={\n \"yrange\":(0,400),\n \"title\":TITLE,\n \"xlabel\":\"Day of the year\",\n \"ylabel\":\"Liquid soil moisture ($\\\\frac{kg}{m^2}$)\",\n \"line_width\":1.2,\n \"colors\":[\"blue\" for i in range(len(TRUTH))] + \\\n [\"red\" for i in range(len(OUT))],\n #\"legend_ncols\":2,\n \"dpi\":200,\n },\n image_path=fig_path\n )\n\n # tmp\n", "repo_name": "Mitchell-D/testbed", "sub_path": "old/evaluate_model.py", "file_name": "evaluate_model.py", "file_ext": "py", "file_size_in_byte": 3406, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.split", "line_number": 15, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 19, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 37, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 39, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 44, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 52, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 53, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 54, "usage_type": "call"}, {"api_name": "aes670hw2.geo_plot.plot_lines", "line_number": 73, "usage_type": "call"}, {"api_name": "aes670hw2.geo_plot", "line_number": 73, "usage_type": "name"}]} +{"seq_id": "28577807333", "text": "# Functionalities related to searching in a file\n\nimport modules.file.read as fr\nfrom __init__ import IDENTIFIER_COL, PATH\n\ndef get_item_details(file, identifier):\n \"\"\"Extract the item details from database\n \n Args:\n (str): the file to search for the item in\n (str|int): the identifier of the item being queried\n \n Returns:\n (list|None): list of the item details if exist and None otherwise\"\"\"\n\n # Extracting users data from database as list of lists\n items_data = fr.get_lines(PATH[file], type='list')\n\n # Iterating over the users data\n for item in items_data:\n\n # Checking the items identifiers against the queried identifier\n if item[IDENTIFIER_COL[file]] == identifier:\n # if found return the data\n return item\n\n # If the identifier is not found return None\n return None", "repo_name": "AbdElrahman-A-Eid/CrowdFundApp", "sub_path": "modules/file/search.py", "file_name": "search.py", "file_ext": "py", "file_size_in_byte": 868, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "modules.file.read.get_lines", "line_number": 17, "usage_type": "call"}, {"api_name": "modules.file.read", "line_number": 17, "usage_type": "name"}, {"api_name": "__init__.PATH", "line_number": 17, "usage_type": "name"}, {"api_name": "__init__.IDENTIFIER_COL", "line_number": 23, "usage_type": "name"}]} +{"seq_id": "31152739892", "text": "from django.urls import path \nfrom . import views \n\napp_name = 'user'\n\nurlpatterns = [\n path('dashboard/', views.dashboard_view, name='dashboard'),\n path('profile/', views.profile_view, name='profile'),\n path('diagnosis/', views.diagonzie_symptoms, name='diagnosis'),\n path('diagnosis-details/', views.diagnosis_details, name='diagnosis-details')\n]", "repo_name": "Prosperibe12/medproject", "sub_path": "userapp/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 360, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}]} +{"seq_id": "25094526232", "text": "\"\"\"\nScript used for training the normalnet using tfutils\n\"\"\"\n\nfrom __future__ import division, print_function, absolute_import\nimport os, sys\nimport numpy as np\n\nimport tensorflow as tf\n\nimport normal_encoder_asymmetric_with_bypass\n\nfrom tfutils import base, data, model, optimizer\n\nimport json\nimport copy\nimport argparse\n\n#os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2\"\n\nhost = os.uname()[1]\n\nDATA_PATH = {}\nif host == 'freud': # freud\n DATA_PATH['train'] = '/media/data/one_world_dataset/randomperm.hdf5'\n DATA_PATH['val'] = '/media/data/one_world_dataset/randomperm_test1.hdf5'\n\nelif host.startswith('node') or host == 'openmind7': # OpenMind\n DATA_PATH['train'] = '/om/user/chengxuz/Data/one_world_dataset/randomperm.hdf5'\n DATA_PATH['val'] = '/om/user/chengxuz/Data/one_world_dataset/randomperm_test1.hdf5'\nelse:\n print(\"Not supported yet!\")\n exit()\n\n\n\ndef online_agg(agg_res, res, step):\n if agg_res is None:\n agg_res = {k:[] for k in res}\n for k,v in res.items():\n agg_res[k].append(np.mean(v))\n return agg_res\n\n\ndef exponential_decay(global_step,\n learning_rate=.01,\n decay_factor=.95,\n decay_steps=1,\n ):\n # Decay the learning rate exponentially based on the number of steps.\n if decay_factor is None:\n lr = learning_rate # just a constant.\n else:\n # Calculate the learning rate schedule.\n lr = tf.train.exponential_decay(\n learning_rate, # Base learning rate.\n global_step, # Current index into the dataset.\n decay_steps, # Decay step\n decay_factor, # Decay rate.\n staircase=True)\n return lr\n\n\nclass Threedworld(data.HDF5DataProvider):\n\n #N_TRAIN = 2048000 - 102400\n #N_VAL = 102400 \n N_TRAIN = 2048000\n N_VAL = 128000\n\n def __init__(self,\n data_path,\n group='train',\n batch_size=1,\n crop_size=None,\n *args,\n **kwargs):\n \"\"\"\n A specific reader for Threedworld generated dataset stored as a HDF5 file\n\n Args:\n - data_path\n path to raw hdf5 data\n Kwargs:\n - group (str, default: 'train')\n Which subset of the dataset you want: train, val.\n The latter contains 50k images from the train set,\n so that you can directly compare performance on the validation set\n to the performance on the train set to track overfitting.\n - batch_size (int, default: 1)\n Number of images to return when `next` is called. By default set\n to 1 since it is expected to be used with queues where reading one\n image at a time is ok.\n - crop_size (int or None, default: None)\n For center crop (crop_size x crop_size). If None, no cropping will occur.\n - *args, **kwargs\n Extra arguments for HDF5DataProvider\n \"\"\"\n self.group = group\n self.images = 'images'\n self.labels = 'normals'\n '''\n if self.group=='train':\n subslice = range(self.N_TRAIN)\n else:\n subslice = range(self.N_TRAIN, self.N_TRAIN + self.N_VAL)\n '''\n super(Threedworld, self).__init__(\n data_path[group],\n [self.images, self.labels],\n batch_size=batch_size,\n postprocess={self.images: self.postproc, self.labels: self.postproc},\n pad=True,\n *args, **kwargs)\n if crop_size is None:\n self.crop_size = 256\n else:\n self.crop_size = crop_size\n\n self.off = None\n self.now_num = 0\n\n def postproc(self, ims, f):\n norm = ims.astype(np.float32) / 255\n if self.group=='train':\n #print('In train')\n if self.now_num==0:\n off = np.random.randint(0, 256 - self.crop_size, size=2)\n self.off = off\n else:\n off = self.off\n else:\n off = int((256 - self.crop_size)/2)\n off = [off, off]\n images_batch = norm[:,\n off[0]: off[0] + self.crop_size,\n off[1]: off[1] + self.crop_size]\n if self.now_num==0:\n self.now_num = 1\n else:\n self.now_num = 0\n\n return images_batch\n\n def next(self):\n batch = super(Threedworld, self).next()\n feed_dict = {'images': np.squeeze(batch[self.images]),\n 'labels': np.squeeze(batch[self.labels])}\n return feed_dict\n\n#BATCH_SIZE = 256\n#BATCH_SIZE = 192\nBATCH_SIZE = 128\nNUM_BATCHES_PER_EPOCH = Threedworld.N_TRAIN // BATCH_SIZE\nIMAGE_SIZE_CROP = 224\nNUM_CHANNELS = 3\nNORM_NUM = (IMAGE_SIZE_CROP**2) * NUM_CHANNELS * BATCH_SIZE\n\ndef loss_ave_l2(output, labels):\n loss = tf.nn.l2_loss(output - labels) / NORM_NUM\n return loss\n\ndef rep_loss(inputs, outputs, target):\n loss = tf.nn.l2_loss(outputs - inputs[target]) / NORM_NUM\n return {'loss': loss}\n\ndef postprocess_config(cfg):\n cfg = copy.deepcopy(cfg)\n for k in ['encode', 'decode', 'hidden']:\n if k in cfg:\n ks = cfg[k].keys()\n for _k in ks:\n cfg[k][int(_k)] = cfg[k].pop(_k)\n return cfg\n\n\ndef preprocess_config(cfg):\n cfg = copy.deepcopy(cfg)\n for k in ['encode', 'decode', 'hidden']:\n if k in cfg:\n ks = cfg[k].keys()\n for _k in ks:\n #assert isinstance(_k, int), _k\n cfg[k][str(_k)] = cfg[k].pop(_k)\n return cfg\n\ndef main(args):\n #cfg_initial = postprocess_config(json.load(open(cfgfile)))\n if args.gpu>-1:\n os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu)\n cfg_initial = preprocess_config(json.load(open(args.pathconfig)))\n exp_id = args.expId\n cache_dir = os.path.join(args.cacheDirPrefix, '.tfutils', 'localhost:'+ str(args.nport), 'normalnet-test', 'normalnet', exp_id)\n params = {\n 'save_params': {\n 'host': 'localhost',\n #'port': 31001,\n 'port': args.nport,\n 'dbname': 'normalnet-test',\n 'collname': 'normalnet',\n #'exp_id': 'trainval0',\n 'exp_id': exp_id,\n #'exp_id': 'trainval2', # using screen?\n\n 'do_save': True,\n #'do_save': False,\n 'save_initial_filters': True,\n 'save_metrics_freq': 2000, # keeps loss from every SAVE_LOSS_FREQ steps.\n 'save_valid_freq': 10000,\n 'save_filters_freq': 30000,\n 'cache_filters_freq': 10000,\n 'cache_dir': cache_dir, # defaults to '~/.tfutils'\n },\n\n 'load_params': {\n 'host': 'localhost',\n # 'port': 31001,\n # 'dbname': 'alexnet-test',\n # 'collname': 'alexnet',\n # 'exp_id': 'trainval0',\n 'port': args.nport,\n 'dbname': 'normalnet-test',\n 'collname': 'normalnet',\n #'exp_id': 'trainval0',\n 'exp_id': exp_id,\n #'exp_id': 'trainval2', # using screen?\n 'do_restore': True,\n 'load_query': None\n },\n\n 'model_params': {\n 'func': normal_encoder_asymmetric_with_bypass.normalnet_tfutils,\n 'seed': args.seed,\n 'cfg_initial': cfg_initial\n },\n\n 'train_params': {\n 'data_params': {\n 'func': Threedworld,\n 'data_path': DATA_PATH,\n 'group': 'train',\n 'crop_size': IMAGE_SIZE_CROP,\n 'batch_size': 1\n },\n 'queue_params': {\n 'queue_type': 'fifo',\n 'batch_size': BATCH_SIZE,\n 'n_threads': 4,\n 'seed': 0,\n },\n 'thres_loss': 1000,\n 'num_steps': 90 * NUM_BATCHES_PER_EPOCH # number of steps to train\n },\n\n 'loss_params': {\n 'targets': 'labels',\n 'agg_func': tf.reduce_mean,\n 'loss_per_case_func': loss_ave_l2,\n 'loss_per_case_func_params': {}\n },\n\n 'learning_rate_params': {\n 'func': tf.train.exponential_decay,\n 'learning_rate': .01,\n 'decay_rate': .95,\n 'decay_steps': NUM_BATCHES_PER_EPOCH, # exponential decay each epoch\n 'staircase': True\n },\n\n 'optimizer_params': {\n 'func': optimizer.ClipOptimizer,\n 'optimizer_class': tf.train.MomentumOptimizer,\n 'clip': True,\n 'momentum': .9\n },\n 'validation_params': {\n 'topn': {\n 'data_params': {\n 'func': Threedworld,\n 'data_path': DATA_PATH, # path to image database\n 'group': 'val',\n 'crop_size': IMAGE_SIZE_CROP, # size after cropping an image\n },\n 'targets': {\n 'func': rep_loss,\n 'target': 'labels',\n },\n 'queue_params': {\n 'queue_type': 'fifo',\n 'batch_size': BATCH_SIZE,\n 'n_threads': 4,\n 'seed': 0,\n },\n 'num_steps': Threedworld.N_VAL // BATCH_SIZE + 1,\n 'agg_func': lambda x: {k:np.mean(v) for k,v in x.items()},\n 'online_agg_func': online_agg\n },\n },\n\n 'log_device_placement': False, # if variable placement has to be logged\n }\n #base.get_params()\n base.train_from_params(**params)\n\nif __name__ == '__main__':\n #base.get_params()\n #base.train_from_params(**params)\n parser = argparse.ArgumentParser(description='The script to train the normalnet')\n parser.add_argument('--nport', default = 22334, type = int, action = 'store', help = 'Port number of mongodb')\n parser.add_argument('--pathconfig', default = \"normals_config_winner0.cfg\", type = str, action = 'store', help = 'Path to config file')\n parser.add_argument('--expId', default = \"trainval2\", type = str, action = 'store', help = 'Name of experiment id')\n parser.add_argument('--seed', default = 0, type = int, action = 'store', help = 'Random seed for model')\n parser.add_argument('--gpu', default = -1, type = int, action = 'store', help = 'Index of gpu, currently only one gpu is allowed')\n parser.add_argument('--cacheDirPrefix', default = \"/home/chengxuz\", type = str, action = 'store', help = 'Prefix of cache directory')\n\n args = parser.parse_args()\n\n main(args)\n", "repo_name": "neuroailab/barrel", "sub_path": "normals_relat/normal_pred/train_normalnet_hdf5.py", "file_name": "train_normalnet_hdf5.py", "file_ext": "py", "file_size_in_byte": 10725, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "24", "api": [{"api_name": "os.uname", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 41, "usage_type": "call"}, {"api_name": "tensorflow.train.exponential_decay", "line_number": 55, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 55, "usage_type": "attribute"}, {"api_name": "tfutils.data.HDF5DataProvider", "line_number": 64, "usage_type": "attribute"}, {"api_name": "tfutils.data", "line_number": 64, "usage_type": "name"}, {"api_name": "numpy.float32", "line_number": 124, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 128, "usage_type": "attribute"}, {"api_name": "numpy.squeeze", "line_number": 147, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 148, "usage_type": "call"}, {"api_name": "tensorflow.nn.l2_loss", "line_number": 160, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 160, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.l2_loss", "line_number": 164, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 164, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 168, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 178, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 190, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 191, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 193, "usage_type": "call"}, {"api_name": "os.path", "line_number": 193, "usage_type": "attribute"}, {"api_name": "normal_encoder_asymmetric_with_bypass.normalnet_tfutils", "line_number": 232, "usage_type": "attribute"}, {"api_name": "tensorflow.reduce_mean", "line_number": 257, "usage_type": "attribute"}, {"api_name": "tensorflow.train", "line_number": 263, "usage_type": "attribute"}, {"api_name": "tfutils.optimizer.ClipOptimizer", "line_number": 271, "usage_type": "attribute"}, {"api_name": "tfutils.optimizer", "line_number": 271, "usage_type": "name"}, {"api_name": "tensorflow.train", "line_number": 272, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 295, "usage_type": "call"}, {"api_name": "tfutils.base.train_from_params", "line_number": 303, "usage_type": "call"}, {"api_name": "tfutils.base", "line_number": 303, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 308, "usage_type": "call"}]} +{"seq_id": "74392918141", "text": "from src.config import Config\nfrom lightning.pytorch.callbacks.early_stopping import EarlyStopping\nfrom lightning.pytorch.callbacks.model_checkpoint import ModelCheckpoint\nfrom src.dataloaders import KFoldDataModuleContainer\nfrom src.models import S3Rec\nimport torch\nimport lightning as L\nimport copy\nimport numpy as np\nimport wandb\n\n\nclass HoldoutTrainer:\n def __init__(self, config: Config, model: L.LightningModule, data_module: L.LightningDataModule, metric: str, mode=\"max\") -> None:\n self.config = config\n self.model = model\n self.data_module = data_module\n self.is_cv = self.config.trainer.cv\n\n self.device = torch.device(\"cuda\" if config.cuda_condition else \"cpu\")\n\n self.early_stop = EarlyStopping(monitor=metric, patience=10, verbose=True, mode=mode)\n\n if config.trainer.is_pretrain:\n checkpoint_file = f\"{config.timestamp}_{config.model.model_name}_pretrain_{{{metric}:.2f}}\"\n else:\n checkpoint_file = f\"{config.timestamp}_{config.model.model_name}_{{{metric}:.2f}}\"\n\n self.checkpoint = ModelCheckpoint(monitor=metric, mode=mode, dirpath=config.path.output_dir, filename=checkpoint_file)\n\n if config.cuda_condition:\n self.trainer = L.Trainer(max_epochs=self.config.trainer.epoch, callbacks=[self.early_stop, self.checkpoint], accelerator=\"cuda\")\n else:\n self.trainer = L.Trainer(max_epochs=self.config.trainer.epoch, callbacks=[self.early_stop, self.checkpoint], accelerator=\"cpu\")\n\n def train(self):\n print(\"start training\")\n self.trainer.fit(self.model, datamodule=self.data_module)\n\n def predict(self):\n # inference\n preds = self.trainer.predict(self.model, datamodule=self.data_module)\n\n if self.is_cv:\n return torch.concatenate(preds)\n else:\n rating_pred = np.array(torch.concatenate(preds))\n ind = np.argpartition(rating_pred, -10)[:, -10:]\n arr_ind = rating_pred[np.arange(len(rating_pred))[:, None], ind]\n arr_ind_argsort = np.argsort(arr_ind)[np.arange(len(rating_pred)), ::-1]\n pred_list = ind[np.arange(len(rating_pred))[:, None], arr_ind_argsort]\n\n return pred_list\n\n def test(self):\n self.trainer.test(self.model, datamodule=self.data_module)\n\n\nclass PretrainTrainer(HoldoutTrainer):\n def __init__(self, config: Config, model: S3Rec, data_module: L.LightningDataModule, metric: str, mode: str, pretrain_path: str) -> None:\n super().__init__(config, model, data_module, metric, mode)\n self.pretrain_path = pretrain_path\n\n def train(self):\n super().train()\n\n self.save_best_pretrained_module()\n\n def save_best_pretrained_module(self):\n # load and\n self.model.load_from_checkpoint(self.checkpoint.best_model_path, config=self.config, name2attr_size=self.model.name2attr_size)\n self.model.save_pretrained_module(self.pretrain_path)\n\n\nclass KFoldTrainer:\n def __init__(\n self, config: Config, model: L.LightningModule, kfold_data_module_container: KFoldDataModuleContainer, metric: str, mode: str\n ) -> None:\n self.config = config\n self.n_fold = config.trainer.k\n\n self.kfold_data_module_container = kfold_data_module_container\n\n self.fold_trainers: list[HoldoutTrainer] = self.__fold_trainers(self.n_fold, config, model, kfold_data_module_container, metric, mode)\n self.sub_result_csv_list = []\n self.val_result_csv_list = []\n\n def __fold_trainers(\n self, n_fold: int, config: Config, model: L.LightningModule, kfold_data_module_container: KFoldDataModuleContainer, metric: str, mode: str\n ) -> list[HoldoutTrainer]:\n fold_trainers = []\n\n for fold in range(n_fold):\n fold_model = copy.deepcopy(model)\n kfold_data_module = kfold_data_module_container.kfold_data_module(fold)\n\n trainer = HoldoutTrainer(config, fold_model, kfold_data_module, metric, mode)\n fold_trainers.append(trainer)\n\n return fold_trainers\n\n def train(self):\n cv_score = 0.0\n\n for fold, fold_trainer in enumerate(self.fold_trainers):\n print(f\"------------- Train Fold {fold} -------------\")\n\n fold_trainer.train()\n fold_model = fold_trainer.model\n\n print(\n \"check tr_result, val_result: \",\n len(fold_model.tr_result),\n len(fold_model.val_result),\n )\n tr_avg_loss = torch.stack([x[\"rec_avg_loss\"] for x in fold_model.tr_result]).mean()\n tr_cur_loss = torch.stack([x[\"rec_cur_loss\"] for x in fold_model.tr_result]).mean()\n\n val_recall = fold_model.val_result.mean()\n\n print(f\">>> tr_avg_loss: {tr_avg_loss},tr_cur_loss: {tr_cur_loss}, val_recall@10: {val_recall}\")\n cv_score += val_recall\n\n cv_score /= self.n_fold\n print(f\"-----------------cv_recall@10_score: {cv_score}-----------------\")\n wandb.log({\"cv_score\": cv_score})\n\n return cv_score\n\n def predict(self):\n fold = 0\n while self.fold_trainers:\n fold_trainer = self.fold_trainers.pop(0)\n\n print(f\"------------- Predict Fold {fold} -------------\")\n if fold == 0:\n output = fold_trainer.predict()\n else:\n output = output + fold_trainer.predict()\n\n fold += 1\n\n rating_pred = np.array(output / self.n_fold)\n\n ind = np.argpartition(rating_pred, -10)[:, -10:]\n arr_ind = rating_pred[np.arange(len(rating_pred))[:, None], ind]\n arr_ind_argsort = np.argsort(arr_ind)[np.arange(len(rating_pred)), ::-1]\n oof_pred_list = ind[np.arange(len(rating_pred))[:, None], arr_ind_argsort]\n\n return oof_pred_list\n\n def test(self):\n pass\n", "repo_name": "boostcampaitech5/level2_movierecommendation-recsys-03", "sub_path": "sequential/src/trainers.py", "file_name": "trainers.py", "file_ext": "py", "file_size_in_byte": 5865, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "24", "api": [{"api_name": "src.config.Config", "line_number": 14, "usage_type": "name"}, {"api_name": "lightning.LightningModule", "line_number": 14, "usage_type": "attribute"}, {"api_name": "lightning.LightningDataModule", "line_number": 14, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 20, "usage_type": "call"}, {"api_name": "lightning.pytorch.callbacks.early_stopping.EarlyStopping", "line_number": 22, "usage_type": "call"}, {"api_name": "lightning.pytorch.callbacks.model_checkpoint.ModelCheckpoint", "line_number": 29, "usage_type": "call"}, {"api_name": "lightning.Trainer", "line_number": 32, "usage_type": "call"}, {"api_name": "lightning.Trainer", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.concatenate", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.concatenate", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.argpartition", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 51, "usage_type": "call"}, {"api_name": "src.config.Config", "line_number": 60, "usage_type": "name"}, {"api_name": "src.models.S3Rec", "line_number": 60, "usage_type": "name"}, {"api_name": "lightning.LightningDataModule", "line_number": 60, "usage_type": "attribute"}, {"api_name": "src.config.Config", "line_number": 77, "usage_type": "name"}, {"api_name": "lightning.LightningModule", "line_number": 77, "usage_type": "attribute"}, {"api_name": "src.dataloaders.KFoldDataModuleContainer", "line_number": 77, "usage_type": "name"}, {"api_name": "src.config.Config", "line_number": 89, "usage_type": "name"}, {"api_name": "lightning.LightningModule", "line_number": 89, "usage_type": "attribute"}, {"api_name": "src.dataloaders.KFoldDataModuleContainer", "line_number": 89, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 94, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 116, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 117, "usage_type": "call"}, {"api_name": "wandb.log", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.argpartition", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 146, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 147, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 147, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 148, "usage_type": "call"}]} +{"seq_id": "27928567950", "text": "import scapy.all as scapy\nimport argparse\n\ndef get_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", \"--ip\", dest=\"target\", help=\"Target IP / IP Range\")\n options = parser.parse_args()\n if not options.target:\n parser.error(\"[!] Please add an interface to proceed (like : 192.168.1.1/24), --help for more informations.\")\n return options\n\ndef scan(ip):\n arp_request = scapy.ARP(pdst = ip)\n broadcast = scapy.Ether(dst = \"ff:ff:ff:ff:ff:ff\")\n packet = broadcast/arp_request\n ask_list = scapy.srp(packet, timeout = 1, verbose = False)[0]\n \n packet_list = []\n for i in ask_list:\n packet_dict = {\"ip\" : i[1].psrc, \"mac\" : i[1].hwsrc}\n packet_list.append(packet_dict)\n return(packet_list)\n\ndef print_res(res):\n print(\"\"\" __ _ ___ _____ _ _ __ ___ _ __ __ ___ __ __ _ __ _ ___ ___ \n| \\| | __|_ _| | | |/__\\| _ \\ |/ / /' _/ / _// \\| \\| | \\| | __| _ \\ \n| | ' | _| | | | 'V' | \\/ | v / < `._`.| \\_| /\\ | | ' | | ' | _|| v / \n|_|\\__|___| |_| !_/ \\_!\\__/|_|_\\_|\\_\\ |___/ \\__/_||_|_|\\__|_|\\__|___|_|_\\ \"\"\")\n print(\"=========================================\")\n print(\"IP\\t\\t\\tMAC Address\\n=========================================\")\n for n in res:\n print(n[\"ip\"] + \"\\t\\t\" + n[\"mac\"])\n \noptions = get_arguments()\nscan_result = scan(options.target)\nprint_res(scan_result)", "repo_name": "LasCC/Network-Scanner", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1390, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 15, "dataset": "github-code", "pt": "27", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 5, "usage_type": "call"}, {"api_name": "scapy.all.ARP", "line_number": 13, "usage_type": "call"}, {"api_name": "scapy.all", "line_number": 13, "usage_type": "name"}, {"api_name": "scapy.all.Ether", "line_number": 14, "usage_type": "call"}, {"api_name": "scapy.all", "line_number": 14, "usage_type": "name"}, {"api_name": "scapy.all.srp", "line_number": 16, "usage_type": "call"}, {"api_name": "scapy.all", "line_number": 16, "usage_type": "name"}]} +{"seq_id": "23382301169", "text": "from .legion_tools import *\nimport scipy.sparse.linalg as lin\n\ndef liouvillian_sim(job_index, output_directory='./results'):\n\n with open('stack.csv', 'r') as f:\n header = f.readline()\n stack_name = header.split('\\n')[0]\n stack_frame = pd.read_csv(f)\n\n stack_directory = output_directory\n\n kappa_phi = 0.0\n\n sys_params = stack_frame.iloc[job_index]\n frame_params = sys_params\n packaged_params = Parameters(frame_params.fc, frame_params.Ej, frame_params.g, frame_params.Ec, frame_params.eps,\n frame_params.fd, frame_params.kappa, frame_params.gamma, frame_params.t_levels,\n frame_params.c_levels, frame_params.gamma_phi, kappa_phi, frame_params.n_t,\n frame_params.n_c)\n #directory = stack_directory + '/' + sys_params.group_folder + '/' + str(job_index)\n\n print(stack_directory)\n\n directory = stack_directory + '/' + sys_params.group_folder + '/' + str(sys_params.job_index)\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n cwd = os.getcwd()\n os.chdir(directory)\n print(directory)\n sys_params.to_csv('settings.csv', header=False)\n\n H = hamiltonian(packaged_params)\n c_ops = collapse_operators(packaged_params)\n\n L = liouvillian(H, c_ops)\n data = L.data\n csc = data.tocsc()\n\n values, states = lin.eigs(csc, k=2, sigma=0)\n values = pd.DataFrame(values)\n values.columns = ['eigenvalues']\n states = pd.DataFrame(states)\n values.to_csv('eigenvalues.csv',index=False)\n states.to_csv('states.csv',index=False)\n\n os.chdir(cwd)\n", "repo_name": "paulsbrookes/bistability_tools", "sub_path": "cqed_lib/cqed_tools/simulation/liouvillian_sim.py", "file_name": "liouvillian_sim.py", "file_ext": "py", "file_size_in_byte": 1631, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "scipy.sparse.linalg.eigs", "line_number": 41, "usage_type": "call"}, {"api_name": "scipy.sparse.linalg", "line_number": 41, "usage_type": "name"}]} +{"seq_id": "37902003689", "text": "import os\nfrom setuptools import setup\n\n# Utility function to read the README file.\n# Used for the long_description.\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetup(\n name = \"mpsolver\",\n version = \"1.0.0\",\n author = \"Darius Braziunas\",\n author_email = \"darius.braziunas@gmail.com\",\n description = \"Mathematical programming (MP) interface to CPLEX and GLPK solvers\",\n long_description=read('README.txt'),\n #keywords = \"example documentation tutorial\",\n url = \"http://cs.toronto.edu/~darius\",\n packages=['mpsolver'],\n platforms = ['any'],\n install_requires =['numpy']\n)\n\n", "repo_name": "dariux/mpsolver", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 649, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "os.path.join", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 7, "usage_type": "call"}, {"api_name": "setuptools.setup", "line_number": 9, "usage_type": "call"}]} +{"seq_id": "13971204172", "text": "from google.transit import gtfs_realtime_pb2\nimport requests\nimport math\nfrom datetime import datetime\nfrom pytz import timezone\nimport configparser\nimport operator\nfrom operator import itemgetter\n\nconfig = configparser.ConfigParser()\nconfig.read(\"nyc.ini\")\napikey = config[\"api\"][\"key\"]\n\ndef printRoute(id,name,time):\n if time == '0':\n print('\\x1b[0;30;41m ' + id + ' \\x1b[0m', '\\x1b[1;31;40m' + name + '\\x1b[0m', '\\x1b[1;31;40m' + time + '\\x1b[0m', '\\x1b[1;31;40m' + \"min\" + '\\x1b[0m', sep=\"\")\n else:\n print('\\x1b[0;30;41m ' + id + ' \\x1b[0m', '\\x1b[1;32;40m' + name + '\\x1b[0m', '\\x1b[1;32;40m' + time + '\\x1b[0m', '\\x1b[1;32;40m' + \"min\" + '\\x1b[0m', sep=\"\")\n\ndict = {}\ndictCount = 0\ndestinations = {'1': \" Van Cort Park 242 St \",'2':\" Wakefield-241 St \",'3':\" Harlem-148 St \"}\n\nfeed = gtfs_realtime_pb2.FeedMessage()\nresponse = requests.get(apikey)\nresponseString = response.content\nfeed.ParseFromString(responseString)\nif not responseString:\n print(\"MTA is Busy\")\nfor entity in feed.entity:\n if entity.HasField('trip_update'):\n tu = entity.trip_update\n tr = tu.trip\n rt = tr.route_id\n sc = len(tu.stop_time_update)\n count = 0\n if rt == '1' or rt == '2' or rt == '3':\n while count < sc:\n stu = tu.stop_time_update[count]\n sid = stu.stop_id\n arr = stu.arrival.time\n dep = stu.departure.time\n at = datetime.fromtimestamp(arr)\n dt = datetime.fromtimestamp(dep)\n now = datetime.now()\n tdelta = at - now\n seconds = tdelta.total_seconds()\n minutes = seconds / 60\n final = math.floor(minutes)\n if final < 0:\n final=1000\n count = count + 1\n if sid == '127N':\n if rt == '1':\n dict[dictCount] = final, \"1\"\n dictCount = dictCount + 1\n elif rt == '2':\n dict[dictCount] = final, \"2\"\n dictCount = dictCount + 1\n elif rt == '3':\n dict[dictCount] = final, \"3\"\n dictCount = dictCount + 1\n else:\n pass\n else:\n pass\ndictSorted = sorted(dict.items(), key=operator.itemgetter(1))\ntubListItem1 = dictSorted[0]\ntubListItem2 = dictSorted[1]\ntub1 = tubListItem1[1]\ntub2 = tubListItem2[1]\ntime1 = str(tub1[0])\ntime2 = str(tub2[0])\nnew_york = timezone('America/New_York')\nny_time = datetime.now(new_york)\n\n#Output\nprint (\"Times Sq-42 St -\", ny_time.strftime('%H:%M:%S'))\nprintRoute(tub1[1],destinations[tub1[1]],time1)\nprintRoute(tub2[1],destinations[tub2[1]],time2)\n", "repo_name": "simonbmadsen/settings", "sub_path": "nyc.py", "file_name": "nyc.py", "file_ext": "py", "file_size_in_byte": 2847, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "configparser.ConfigParser", "line_number": 10, "usage_type": "call"}, {"api_name": "google.transit.gtfs_realtime_pb2.FeedMessage", "line_number": 24, "usage_type": "call"}, {"api_name": "google.transit.gtfs_realtime_pb2", "line_number": 24, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 25, "usage_type": "call"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 43, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 43, "usage_type": "name"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 44, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 44, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 45, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 45, "usage_type": "name"}, {"api_name": "math.floor", "line_number": 49, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 67, "usage_type": "call"}, {"api_name": "pytz.timezone", "line_number": 74, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 75, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 75, "usage_type": "name"}]} +{"seq_id": "5058239061", "text": "from django.shortcuts import render, redirect\nfrom django.http import HttpResponse, JsonResponse, HttpResponseRedirect\nfrom .models import Book\nfrom .forms import BookForm\nfrom django.views.decorators.csrf import csrf_exempt\n\ndef index(request):\n all_books = Book.objects.all()\n return render(request, 'bookstore_list.html', context={\"books\": all_books})\n\nbookstore_list = [\n {\n 'index': 0,\n 'id': 1,\n 'name': 'Harry potter',\n 'price': 100,\n 'description': \"Learning Learnin gJSfffjk dfjdklg jkdgjdkgjdkgjd kgjdkgjdglk jdgkljfjfjejekgjekgjekgjekgjgekjgekLearningJSfffjkdfjdklgjkdgjdkgjdkgjdkgjdkgjdglkjdgkljfjfjejekgjekgjekgjekgjgekjgekLearningJSfffjkdfjdklgjkdgjdkgjdkgjdkgjdkgjdglkjdgkljfjfjejekgjekgjekgjekgjgekjgek\",\n },\n {\n 'index': 1,\n 'id': 2,\n 'name': 'harry potter',\n 'price': 400,\n 'description': \"Learning LearningJS fffjkdfjd klgjkdgjdkgjdkgjdkgjd kgjdglkjdgk ljfj fjejekgjekgjekgjekgjgekjgek\",\n },\n {\n 'index': 2,\n 'id': 3,\n 'name': 'Harry potter 3',\n 'price': 200,\n 'description': \"LearningJS fffjk dfjdklgjkdg jdkgjdkgjd kgjdkgjdglkjdgkl jfjfjejekg jekgjekgjekgjgekjgek\",\n },\n]\n\n\ndef bookstore_details(request, *args, **kwrgs):\n book_id = kwrgs.get('book_id')\n book = Book.objects.get(pk=book_id)\n return render(request, 'bookstore_details.html', context={\"book\": book})\n\ndef bookstore_delete(request, **kwargs):\n book_id = kwargs.get('book_id')\n Book.objects.get(pk=book_id).delete()\n return redirect(\"bookstore:bookstore-list\")\n\ndef bookstore_update(request, **kwargs):\n book_id = kwargs.get('book_id') \n book = Book.objects.get(pk=book_id)\n form = BookForm(instance=book)\n if request.method == \"PUT\":\n form = BookForm(data=request.POST, instance=book)\n if form.is_valid():\n form.save()\n return redirect(\"bookstore:bookstore-details\", pk=book.id)\n \n return render(request, 'bookstore_update.html', context={\n 'form': form, \n 'book': book\n })\n\ndef create_new_book(request):\n form = BookForm()\n if request.method == \"POST\":\n form = BookForm(data=request.POST)\n if form.is_valid():\n form.save()\n return redirect(\"bookstore:bookstore-list\")\n return render(request, 'bookstore_create.html', context={\n 'form': form\n })", "repo_name": "radwanabil/Django", "sub_path": "bookstoreLab1/bookstore/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2407, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "models.Book.objects.all", "line_number": 8, "usage_type": "call"}, {"api_name": "models.Book.objects", "line_number": 8, "usage_type": "attribute"}, {"api_name": "models.Book", "line_number": 8, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 9, "usage_type": "call"}, {"api_name": "models.Book.objects.get", "line_number": 38, "usage_type": "call"}, {"api_name": "models.Book.objects", "line_number": 38, "usage_type": "attribute"}, {"api_name": "models.Book", "line_number": 38, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 39, "usage_type": "call"}, {"api_name": "models.Book.objects.get", "line_number": 43, "usage_type": "call"}, {"api_name": "models.Book.objects", "line_number": 43, "usage_type": "attribute"}, {"api_name": "models.Book", "line_number": 43, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 44, "usage_type": "call"}, {"api_name": "models.Book.objects.get", "line_number": 48, "usage_type": "call"}, {"api_name": "models.Book.objects", "line_number": 48, "usage_type": "attribute"}, {"api_name": "models.Book", "line_number": 48, "usage_type": "name"}, {"api_name": "forms.BookForm", "line_number": 49, "usage_type": "call"}, {"api_name": "forms.BookForm", "line_number": 51, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 54, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 56, "usage_type": "call"}, {"api_name": "forms.BookForm", "line_number": 62, "usage_type": "call"}, {"api_name": "forms.BookForm", "line_number": 64, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 67, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 68, "usage_type": "call"}]} +{"seq_id": "30245029166", "text": "import pandas as pd\nimport matplotlib.pyplot as plt\n\n# 用来正常显示中文标签\nplt.rcParams[\"font.sans-serif\"] = [\"SimHei\"]\n# 用来正常显示负号\nplt.rcParams[\"axes.unicode_minus\"] = False\n# 图片输出目录\nfs_images_dir = \"images/3-4/\"\n\n\n# 评分记录数据查看\ndef get_ratings_mess(file_path):\n print(\"文件路径:{}\".format(file_path))\n # drop 删除函数,这里删除第0行\n events = pd.read_table(file_path, header=0, sep=\"|\").drop(0)\n print(\"原始events的key为:\\n{}\".format(events.keys()))\n # print(events.columns.values)\n print(\"数据的前5条为:\\n{}\".format(events.head(5)))\n # 去空格\n events.columns = events.rename(columns=lambda x: x.strip()).keys()\n events = events.replace(' ', '')\n print(\"去除标题空格后,events的key为:\\n{}\".format(events.keys()))\n print(\"去掉空格后,数据的前5条为:\\n{}\".format(events.head(5)))\n # 因为原始数据的原因,按照|分割后,字段前后多了空格\n rate_ser = events[\"rating\"].groupby(events[\"rating\"]).count()\n print(\"events的值有:\\n{}\".format(rate_ser))\n\n plt.axes(aspect=1)\n plt.pie(x=rate_ser.values, labels=rate_ser.keys(), autopct=\"%3.1f %%\")\n plt.legend(bbox_to_anchor=(1.0, 1.0))\n plt.title(\"评分记录信息\")\n plt.savefig(fs_images_dir + \"ratings.png\")\n plt.show()\n\n\nif __name__ == '__main__':\n fs_file_path = \"data/foursquare-2013/ratings.dat\"\n get_ratings_mess(fs_file_path)\n", "repo_name": "legend1412/Recommend", "sub_path": "Chapter03/3-4.py", "file_name": "3-4.py", "file_ext": "py", "file_size_in_byte": 1464, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "matplotlib.pyplot.rcParams", "line_number": 5, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 5, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 7, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 7, "usage_type": "name"}, {"api_name": "pandas.read_table", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.axes", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.pie", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}]} +{"seq_id": "35468360686", "text": "import time\nimport tornado.web\nimport json\n\nfrom lib import history\n\n\nclass MainUIRequestHandler(tornado.web.RequestHandler):\n name = None\n data_queues = None\n worker_handle = None\n components = None\n config = None\n historic_task_list = None\n\n def initialize(self, data_queues, worker_handle, settings):\n self.name = 'main'\n self.data_queues = data_queues\n self.worker_handle = worker_handle\n self.components = []\n self.config = settings\n self.historic_task_list = []\n\n def get(self, path):\n if self.get_query_arguments('ajax'):\n # Print out the json based on the call\n self.handle_ajax_call(self.get_query_arguments('ajax')[0])\n else:\n self.get_historical_tasks()\n self.set_header(\"Content-Type\", \"text/html\")\n self.render(\"main/main.html\", historic_task_list=self.historic_task_list, time_now=time.time())\n\n def handle_ajax_call(self, query):\n self.set_header(\"Content-Type\", \"application/json\")\n if query == 'workersInfo':\n if self.get_query_arguments('workerId'):\n worker_info = self.get_workers_info(self.get_query_arguments('workerId')[0])\n self.set_header(\"Content-Type\", \"text/html\")\n self.render(\"main/main-worker-pie-chart.html\", worker_info=worker_info)\n else:\n self.write(json.dumps(self.get_workers_info()))\n if query == 'pendingTasks':\n if self.get_query_arguments('format') and 'html' in self.get_query_arguments('format'):\n self.set_header(\"Content-Type\", \"text/html\")\n self.render(\"main/main-pending-tasks.html\", time_now=time.time())\n else:\n self.write(json.dumps(self.get_pending_tasks()))\n if query == 'historicalTasks':\n if self.get_query_arguments('format') and 'html' in self.get_query_arguments('format'):\n self.get_historical_tasks()\n self.set_header(\"Content-Type\", \"text/html\")\n self.render(\"main/main-completed-tasks-list.html\", historic_task_list=self.historic_task_list,\n time_now=time.time())\n else:\n self.set_header(\"Content-Type\", \"application/json\")\n self.write(json.dumps(self.get_historical_tasks()))\n\n def get_workers_info(self, worker_id=None):\n if worker_id is not None:\n workers_info = self.worker_handle.get_worker_status(worker_id)\n else:\n workers_info = self.worker_handle.get_all_worker_status()\n return workers_info\n\n def get_workers_count(self):\n return len(self.worker_handle.get_all_worker_status())\n\n def get_pending_tasks(self):\n return self.worker_handle.job_queue.list_all_incoming_items()\n\n def get_historical_tasks(self):\n history_logging = history.History(self.config)\n self.historic_task_list = list(history_logging.get_historic_task_list(20))\n return self.historic_task_list\n", "repo_name": "BrianPugh/unmanic", "sub_path": "webserver/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 3061, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "25", "api": [{"api_name": "tornado.web.web", "line_number": 8, "usage_type": "attribute"}, {"api_name": "tornado.web", "line_number": 8, "usage_type": "name"}, {"api_name": "time.time", "line_number": 31, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 41, "usage_type": "call"}, {"api_name": "time.time", "line_number": 45, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 47, "usage_type": "call"}, {"api_name": "time.time", "line_number": 53, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 56, "usage_type": "call"}, {"api_name": "lib.history.History", "line_number": 72, "usage_type": "call"}, {"api_name": "lib.history", "line_number": 72, "usage_type": "name"}]} +{"seq_id": "12828860704", "text": "import logging\n#from logging.handlers import RotatingFileHandler\nfrom recommender import config\n\ndef getLogger(obj):\n if not isinstance(obj, str):\n if hasattr(obj, '__name__'):\n obj = obj.__name__\n elif hasattr(obj, '__class__'):\n obj = obj.__class__.__name__\n else:\n obj = type(obj).__name__\n return configureLogger(logging.getLogger(obj))\n\ndef configureLogger(logger, level=config.LOG_LEVEL):\n if not len(logger.handlers):\n formatter = logging.Formatter(config.LOG_FORMAT)\n logger.setLevel(level)\n\n # Setup console logging\n ch = logging.StreamHandler()\n ch.setLevel(level)\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n\n # # Setup file logging as well\n # fh = RotatingFileHandler(config.LOG_FILE, maxBytes=config.LOG_FILE_MAX_BYTES,\n # backupCount=config.LOG_FILE_BACKUP_COUNT)\n # fh.setLevel(level)\n # fh.setFormatter(formatter)\n # logger.addHandler(fh)\n\n return logger", "repo_name": "ScJa/projectr", "sub_path": "recommender/recommender/util/log.py", "file_name": "log.py", "file_ext": "py", "file_size_in_byte": 1059, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "logging.getLogger", "line_number": 13, "usage_type": "call"}, {"api_name": "recommender.config.LOG_LEVEL", "line_number": 15, "usage_type": "attribute"}, {"api_name": "recommender.config", "line_number": 15, "usage_type": "name"}, {"api_name": "logging.Formatter", "line_number": 17, "usage_type": "call"}, {"api_name": "recommender.config.LOG_FORMAT", "line_number": 17, "usage_type": "attribute"}, {"api_name": "recommender.config", "line_number": 17, "usage_type": "name"}, {"api_name": "logging.StreamHandler", "line_number": 21, "usage_type": "call"}]} +{"seq_id": "30480180520", "text": "from django.test import TestCase\nfrom django.urls import reverse\nfrom django.contrib.auth.models import User\n\nfrom rest_framework.test import APIClient\nfrom rest_framework import status\n\nfrom articles.models import Author\n\n\nclass AuthorViewTestCase(TestCase):\n \"\"\"Test suite for the api endpoints related to authors.\"\"\"\n\n def setUp(self):\n \"\"\"Define the test client and other test variables.\"\"\"\n self.client = APIClient()\n\n self.user = User.objects.create(username='nerd', is_staff=True)\n self.author = Author.objects.create(name='Dennis Ritchie')\n\n self.epoint = reverse('author', kwargs={'pk': 1})\n\n\n def test_delete_author_unlogged(self):\n \"\"\"Test if an unlogged user can delete an author.\"\"\"\n request = self.client.delete(self.epoint)\n self.assertEqual(request.status_code, status.HTTP_403_FORBIDDEN)\n\n\n def test_add_author_unlogged(self):\n \"\"\"Test if an unlogged user can add an author.\"\"\"\n data = {\n 'name': 'Linus Torvalds'\n }\n\n request = self.client.post(reverse('author-create'), data)\n\n self.assertEqual(request.status_code, status.HTTP_403_FORBIDDEN)\n\n\n def test_update_author_unlogged(self):\n \"\"\"Test if an unlogged user can delete an author.\"\"\"\n data = {'name': 'Ken Thompson'}\n\n request = self.client.patch(self.epoint, data)\n\n self.assertEqual(request.status_code, status.HTTP_403_FORBIDDEN)\n\n\n def test_retrieve_author_unlogged(self):\n \"\"\"Test if an unlogged user can retrieve an author.\"\"\"\n request = self.client.get(self.epoint)\n\n self.assertEqual(request.status_code, status.HTTP_200_OK)\n\n\n def test_update_author_logged(self):\n \"\"\"Test if an logged user can delete an author.\"\"\"\n self.client.force_authenticate(user=self.user)\n\n data = {'name': 'Ken Thompson'}\n\n request = self.client.patch(self.epoint, data)\n\n self.assertEqual(request.status_code, status.HTTP_200_OK)\n\n\n def test_delete_author_logged(self):\n \"\"\"Test if an logged user can delete an author.\"\"\"\n self.client.force_authenticate(user=self.user)\n\n request = self.client.delete(self.epoint)\n self.assertEqual(request.status_code, status.HTTP_204_NO_CONTENT)\n\n\n def test_add_author_logged(self):\n \"\"\"Test if an logged user can add an author.\"\"\"\n self.client.force_authenticate(user=self.user)\n\n data = {\n 'name': 'Donald Knuth',\n }\n\n request = self.client.post(reverse('author-create'), data)\n\n self.assertEqual(request.status_code, status.HTTP_201_CREATED)\n", "repo_name": "murilocamargos/ckl-challenge", "sub_path": "articles/tests/views/author.py", "file_name": "author.py", "file_ext": "py", "file_size_in_byte": 2634, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.test.TestCase", "line_number": 11, "usage_type": "name"}, {"api_name": "rest_framework.test.APIClient", "line_number": 16, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.create", "line_number": 18, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 18, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 18, "usage_type": "name"}, {"api_name": "articles.models.Author.objects.create", "line_number": 19, "usage_type": "call"}, {"api_name": "articles.models.Author.objects", "line_number": 19, "usage_type": "attribute"}, {"api_name": "articles.models.Author", "line_number": 19, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 21, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_403_FORBIDDEN", "line_number": 27, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 27, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 36, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_403_FORBIDDEN", "line_number": 38, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 38, "usage_type": "name"}, {"api_name": "rest_framework.status.HTTP_403_FORBIDDEN", "line_number": 47, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 47, "usage_type": "name"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 54, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 54, "usage_type": "name"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 65, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 65, "usage_type": "name"}, {"api_name": "rest_framework.status.HTTP_204_NO_CONTENT", "line_number": 73, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 73, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 84, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 86, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 86, "usage_type": "name"}]} +{"seq_id": "24291139185", "text": "import sys\nimport os\nimport glob\nimport shutil\nimport tarfile\nimport boto3\nimport threading\nfrom caldp import process\nfrom caldp import log\nfrom caldp import exit_codes\nfrom caldp import sysexit\n\n\ndef s3_split_uri(uri):\n \"\"\"\n >>> s3_split_uri('s3://the-bucket/prefix/parts/come/next')\n ('the-bucket', 'prefix/parts/come/next')\n\n >>> s3_split_uri('s3://the-bucket')\n ('the-bucket', '')\n \"\"\"\n parts = uri[5:].split(\"/\")\n bucket, prefix = parts[0], \"/\".join(parts[1:])\n # print(\"s3_split_uri:\", uri, \"->\", bucket, prefix)\n return bucket, prefix\n\n\ndef get_input_path(input_uri, dataset, make=False):\n \"\"\"Fetches the path to input files\"\"\"\n cwd = os.getcwd()\n if input_uri.startswith(\"file\"):\n input_path = input_uri.split(\":\")[-1]\n else:\n input_path = os.path.join(cwd, \"inputs\", dataset)\n if make is True:\n os.makedirs(input_path, exist_ok=True)\n return input_path\n\n\ndef get_output_dir(output_uri):\n \"\"\"Returns full path to output folder\"\"\"\n if output_uri.startswith(\"file\"):\n output_dir = output_uri.split(\":\")[-1]\n elif output_uri.startswith(\"s3\"):\n output_dir = os.path.abspath(\"outputs\")\n return output_dir\n\n\ndef get_input_dir(input_uri):\n if input_uri.startswith(\"file\"):\n input_dir = input_uri.split(\":\")[-1]\n else:\n input_dir = os.path.join(os.getcwd(), \"inputs\")\n return input_dir\n\n\ndef find_output_files(dataset):\n if process.IPPPSSOOT_RE.match(dataset):\n search_fits = f\"{dataset}/*.fits\"\n search_tra = f\"{dataset}/*.tra\"\n output_files = list(glob.glob(search_fits))\n output_files.extend(list(glob.glob(search_tra)))\n return output_files\n elif process.SVM_RE.match(dataset) and dataset.split(\"_\")[0] in list(process.SVM_INSTR.keys()):\n ipppss = process.get_svm_obs_set(dataset)\n search_fits = f\"{dataset}/hst_*{ipppss}*.fits\"\n search_txt = f\"{dataset}/hst_*{ipppss}*.txt\"\n search_ecsv = f\"{dataset}/hst_*{ipppss}*.ecsv\"\n search_manifest = f\"{dataset}/{dataset}_manifest.txt\"\n search_log = f\"{dataset}/astrodrizzle.log\"\n output_files = list(glob.glob(search_fits))\n output_files.extend(list(glob.glob(search_txt)))\n output_files.extend(list(glob.glob(search_ecsv)))\n output_files.extend(list(glob.glob(search_manifest)))\n output_files.extend(list(glob.glob(search_log)))\n return output_files\n elif process.MVM_RE.match(dataset):\n search_fits = f\"{dataset}/hst_{dataset}*.fits\"\n search_txt = f\"{dataset}/hst_{dataset}*.txt\"\n search_manifest = f\"{dataset}/{dataset}_manifest.txt\"\n output_files = list(glob.glob(search_fits))\n output_files.extend(list(glob.glob(search_txt)))\n output_files.extend(list(glob.glob(search_manifest)))\n return output_files\n else:\n raise ValueError(\"Invalid dataset name {dataset}, dataset must be an ipppssoot, SVM, or MVM dataset\")\n\n\ndef find_previews(dataset, output_files):\n search_prev = f\"{dataset}/previews/*\"\n output_files.extend(list(glob.glob(search_prev)))\n return output_files\n\n\ndef find_input_files(dataset):\n \"\"\"If job fails (no outputs), tar the input files instead for debugging purposes.\"\"\"\n search_inputs = f\"{dataset}/*\"\n file_list = list(glob.glob(search_inputs))\n return file_list\n\n\ndef make_tar(file_list, dataset):\n tar = dataset + \".tar.gz\"\n log.info(\"Creating tarfile: \", tar)\n if os.path.exists(tar):\n os.remove(tar) # clean up from prev attempts\n with tarfile.open(tar, \"x:gz\") as t:\n for f in file_list:\n print(os.path.basename(f))\n t.add(f)\n log.info(\"Tar successful: \", tar)\n tar_dest = os.path.join(dataset, tar)\n shutil.copy(tar, dataset) # move tarfile to outputs/{ipst}\n os.remove(tar)\n return tar_dest\n\n\ndef upload_tar(tar, output_path):\n with sysexit.exit_on_exception(exit_codes.S3_UPLOAD_ERROR, \"S3 tar upload of\", tar, \"to\", output_path, \"FAILED.\"):\n client = boto3.client(\"s3\")\n parts = output_path[5:].split(\"/\")\n bucket, prefix = parts[0], \"/\".join(parts[1:])\n objectname = prefix + \"/\" + os.path.basename(tar)\n log.info(f\"Uploading: s3://{bucket}/{objectname}\")\n if output_path.startswith(\"s3\"):\n with open(tar, \"rb\") as f:\n client.upload_fileobj(f, bucket, objectname, Callback=ProgressPercentage(tar))\n\n\nclass ProgressPercentage(object):\n def __init__(self, filename):\n self._filename = filename\n self._size = float(os.path.getsize(filename))\n self._seen_so_far = 0\n self._lock = threading.Lock()\n\n def __call__(self, bytes_amount):\n # To simplify, assume this is hooked up to a single filename\n with self._lock:\n self._seen_so_far += bytes_amount\n percentage = (self._seen_so_far / self._size) * 100\n sys.stdout.write(\"\\r%s %s / %s (%.2f%%)\" % (self._filename, self._seen_so_far, self._size, percentage))\n sys.stdout.flush()\n\n\ndef clean_up(file_list, dataset, dirs=None):\n print(\"\\nCleaning up...\")\n for f in file_list:\n try:\n os.remove(f)\n except FileNotFoundError:\n print(f\"file {f} not found\")\n if dirs is not None:\n for d in dirs:\n subdir = os.path.abspath(f\"{dataset}/{d}\")\n try:\n shutil.rmtree(subdir)\n except OSError:\n print(f\"dir {subdir} not found\")\n print(\"Done.\")\n\n\ndef tar_outputs(dataset, input_uri, output_uri):\n working_dir = os.getcwd()\n output_path = process.get_output_path(output_uri, dataset)\n output_dir = get_output_dir(output_uri)\n os.chdir(output_dir) # create tarfile with ipst/*fits (ipst is parent dir)\n output_files = find_output_files(dataset)\n if len(output_files) == 0:\n log.info(\"No output files found. Tarring inputs for debugging.\")\n os.chdir(working_dir)\n input_dir = get_input_dir(input_uri)\n os.chdir(input_dir)\n file_list = find_input_files(dataset)\n else:\n file_list = find_previews(dataset, output_files)\n tar = make_tar(file_list, dataset)\n upload_tar(tar, output_path)\n clean_up(file_list, dataset, dirs=[\"previews\", \"env\"])\n os.chdir(working_dir)\n return tar, file_list\n", "repo_name": "spacetelescope/caldp", "sub_path": "caldp/file_ops.py", "file_name": "file_ops.py", "file_ext": "py", "file_size_in_byte": 6351, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "27", "api": [{"api_name": "os.getcwd", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path", "line_number": 53, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 53, "usage_type": "call"}, {"api_name": "caldp.process.IPPPSSOOT_RE.match", "line_number": 58, "usage_type": "call"}, {"api_name": "caldp.process.IPPPSSOOT_RE", "line_number": 58, "usage_type": "attribute"}, {"api_name": "caldp.process", "line_number": 58, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 61, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 62, "usage_type": "call"}, {"api_name": "caldp.process.SVM_RE.match", "line_number": 64, "usage_type": "call"}, {"api_name": "caldp.process.SVM_RE", "line_number": 64, "usage_type": "attribute"}, {"api_name": "caldp.process", "line_number": 64, "usage_type": "name"}, {"api_name": "caldp.process.SVM_INSTR.keys", "line_number": 64, "usage_type": "call"}, {"api_name": "caldp.process.SVM_INSTR", "line_number": 64, "usage_type": "attribute"}, {"api_name": "caldp.process.get_svm_obs_set", "line_number": 65, "usage_type": "call"}, {"api_name": "caldp.process", "line_number": 65, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 71, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 72, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 73, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 74, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 75, "usage_type": "call"}, {"api_name": "caldp.process.MVM_RE.match", "line_number": 77, "usage_type": "call"}, {"api_name": "caldp.process.MVM_RE", "line_number": 77, "usage_type": "attribute"}, {"api_name": "caldp.process", "line_number": 77, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 81, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 82, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 83, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 91, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 98, "usage_type": "call"}, {"api_name": "caldp.log.info", "line_number": 104, "usage_type": "call"}, {"api_name": "caldp.log", "line_number": 104, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 105, "usage_type": "call"}, {"api_name": "os.path", "line_number": 105, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 106, "usage_type": "call"}, {"api_name": "tarfile.open", "line_number": 107, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 109, "usage_type": "call"}, {"api_name": "os.path", "line_number": 109, "usage_type": "attribute"}, {"api_name": "caldp.log.info", "line_number": 111, "usage_type": "call"}, {"api_name": "caldp.log", "line_number": 111, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 112, "usage_type": "call"}, {"api_name": "os.path", "line_number": 112, "usage_type": "attribute"}, {"api_name": "shutil.copy", "line_number": 113, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 114, "usage_type": "call"}, {"api_name": "caldp.sysexit.exit_on_exception", "line_number": 119, "usage_type": "call"}, {"api_name": "caldp.sysexit", "line_number": 119, "usage_type": "name"}, {"api_name": "caldp.exit_codes.S3_UPLOAD_ERROR", "line_number": 119, "usage_type": "attribute"}, {"api_name": "caldp.exit_codes", "line_number": 119, "usage_type": "name"}, {"api_name": "boto3.client", "line_number": 120, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 123, "usage_type": "call"}, {"api_name": "os.path", "line_number": 123, "usage_type": "attribute"}, {"api_name": "caldp.log.info", "line_number": 124, "usage_type": "call"}, {"api_name": "caldp.log", "line_number": 124, "usage_type": "name"}, {"api_name": "os.path.getsize", "line_number": 133, "usage_type": "call"}, {"api_name": "os.path", "line_number": 133, "usage_type": "attribute"}, {"api_name": "threading.Lock", "line_number": 135, "usage_type": "call"}, {"api_name": "sys.stdout.write", "line_number": 142, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 142, "usage_type": "attribute"}, {"api_name": "sys.stdout.flush", "line_number": 143, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 143, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 150, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 155, "usage_type": "call"}, {"api_name": "os.path", "line_number": 155, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 157, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 164, "usage_type": "call"}, {"api_name": "caldp.process.get_output_path", "line_number": 165, "usage_type": "call"}, {"api_name": "caldp.process", "line_number": 165, "usage_type": "name"}, {"api_name": "os.chdir", "line_number": 167, "usage_type": "call"}, {"api_name": "caldp.log.info", "line_number": 170, "usage_type": "call"}, {"api_name": "caldp.log", "line_number": 170, "usage_type": "name"}, {"api_name": "os.chdir", "line_number": 171, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 173, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 180, "usage_type": "call"}]} +{"seq_id": "42484257292", "text": "import cv2\nimport numpy as np\nimport math\nimport config\n\nclass DrawAngle:\n def __init__(self, margin_=30, size_w_=300):\n # 初始化一个空画布 300×300 三通道 背景色为白色\n self.margin = margin_ # 上下左右边距\n self.size_w = size_w_\n self.radius = int((self.size_w - 2 * self.margin) / 2) # 圆的半径\n (self.center_x, self.center_y) = (int(self.radius + self.margin), int(self.radius + self.margin)) # 圆心\n self.center = (self.center_x, self.center_y)\n\n\n def draw_y(self, angle_y=80,b_show=False):\n \"\"\"\n 绘制横滚图\n :return:\n \"\"\"\n img = np.ones((self.size_w, self.size_w, 3), dtype=\"uint8\")\n # img *= 255\n # 蓝色底\n # rgb = [153, 194, 255]373d5f\n rgb = [55, 61, 95]\n img[:, :, 0] = np.squeeze(np.ones((self.size_w, self.size_w, 1), dtype=\"uint8\") * rgb[2])\n img[:, :, 1] = np.squeeze(np.ones((self.size_w, self.size_w, 1), dtype=\"uint8\") * rgb[1])\n img[:, :, 2] = np.squeeze(np.ones((self.size_w, self.size_w, 1), dtype=\"uint8\") * rgb[0])\n # 绘制一个绿色的圆\n cv2.circle(img, center=self.center, radius=self.radius, color=(255, 0, 0), thickness=1)\n # 绘制两条垂直辅助线\n cv2.line(img, (int(self.center_x - self.radius), int(self.center_y)),\n (int(self.center_x + self.radius), int(self.center_y)), (128, 128, 128),\n thickness=1)\n cv2.line(img, (int(self.center_x), int(self.center_y - self.radius)),\n (int(self.center_x), int(self.center_y + self.radius)), (128, 128, 128),\n thickness=1)\n\n # 绘制角度线\n x_0 = self.center_x - (self.radius - self.margin) * math.cos(angle_y * np.pi / 180.0)\n y_0 = self.center_y - (self.radius - self.margin) * math.sin(angle_y * np.pi / 180.0)\n x_1 = self.center_x + (self.radius - self.margin) * math.cos(angle_y * np.pi / 180.0)\n y_1 = self.center_y + (self.radius - self.margin) * math.sin(angle_y * np.pi / 180.0)\n cv2.line(img, (int(x_0), int(y_0)), (int(x_1), int(y_1)), (0, 255, 0), thickness=3)\n\n # 绘制角度线\n cv2.imwrite(config.save_angle_y_path, img)\n if b_show:\n cv2.imshow(\"circle\", img)\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n def draw_z(self,angle_z,b_show=False):\n img = np.ones((self.size_w, self.size_w, 3), dtype=\"uint8\")\n # img *= 255\n # 蓝色底\n # rgb = [153, 194, 255]\n rgb = [55, 61, 95]\n img[:, :, 0] = np.squeeze(np.ones((self.size_w, self.size_w, 1), dtype=\"uint8\") * rgb[2])\n img[:, :, 1] = np.squeeze(np.ones((self.size_w, self.size_w, 1), dtype=\"uint8\") * rgb[1])\n img[:, :, 2] = np.squeeze(np.ones((self.size_w, self.size_w, 1), dtype=\"uint8\") * rgb[0])\n # 绘制一个绿色的圆\n cv2.circle(img, center=self.center, radius=self.radius, color=(0, 255, 0), thickness=1)\n pt1 = []\n\n # 3. 画出60条秒和分钟的刻线\n for i in range(60):\n # 最外部圆,计算A点\n x1 = self.center_x + (self.radius - 5) * math.cos(i * 6 * np.pi / 180.0)\n y1 = self.center_y + (self.radius - 5) * math.sin(i * 6 * np.pi / 180.0)\n pt1.append((int(x1), int(y1)))\n\n # 同心小圆,计算B点\n x2 = self.center_x + (self.radius - self.margin) * math.cos(i * 6 * np.pi / 180.0)\n y2 = self.center_y + (self.radius - self.margin) * math.sin(i * 6 * np.pi / 180.0)\n\n cv2.line(img, pt1[i], (int(x2), int(y2)), (0, 0, 0), thickness=1)\n\n # 4. 画出12条小时的刻线\n for i in range(12):\n # 12条小时刻线应该更长一点\n x = self.center_x + (self.radius - int(self.margin * 1.5)) * math.cos(i * 30 * np.pi / 180.0)\n y = self.center_y + (self.radius - int(self.margin * 1.5)) * math.sin(i * 30 * np.pi / 180.0)\n # 这里用到了前面的pt1\n cv2.line(img, pt1[i * 5], (int(x), int(y)), (0, 0, 0), thickness=2)\n\n # 5 绘制 角度 绘制文字\n for i in range(12):\n # 12条小时刻线应该更长一点\n if 0 <= i <= 3 or 9 <= i < 12:\n delta_margin = int(self.margin / 3)\n else:\n delta_margin = int(self.margin * 4 / 5)\n x = self.center_x + (self.radius + delta_margin) * math.cos(i * 30 * np.pi / 180.0)\n y = self.center_y + (self.radius + delta_margin) * math.sin(i * 30 * np.pi / 180.0)\n font = cv2.FONT_HERSHEY_SIMPLEX\n show_angle = str((i * 30 + 90) % 360)\n # show_angle = str(i * 30)\n cv2.putText(img, show_angle, (int(x), int(y)), font, 0.3, (0, 0, 0), 1)\n show_n = False\n if i == 0:\n show_n = True\n str_n = 'E'\n elif i == 3:\n show_n = True\n str_n = 'S'\n elif i == 6:\n show_n = True\n str_n = 'W'\n elif i == 9:\n show_n = True\n str_n = 'N'\n else:\n show_n = False\n str_n = ''\n if show_n:\n x_n = self.center_x + (self.radius - int(self.margin * 2)) * math.cos(i * 30 * np.pi / 180.0)\n y_n = self.center_y + (self.radius - int(self.margin * 2)) * math.sin(i * 30 * np.pi / 180.0)\n cv2.putText(img, str_n, (int(x_n), int(y_n)), font, 0.7, (0, 0, 0), 1)\n\n # 6 绘制角度线\n angle_z = angle_z - 90\n if angle_z < 0:\n angle_z = angle_z + 360\n x = self.center_x + (self.radius - self.margin * 2) * math.cos(angle_z * np.pi / 180.0)\n y = self.center_y + (self.radius - self.margin * 2) * math.sin(angle_z * np.pi / 180.0)\n # 这里用到了前面的pt1\n cv2.line(img, self.center, (int(x), int(y)), (0, 0, 255), thickness=3)\n # # 绘制箭头\n # if i==0:\n # x_0 = center_x + (radius + delta_margin) * math.cos(i * 30 * np.pi / 180.0)\n # y_0 = center_y + (radius + delta_margin) * math.sin(i * 30 * np.pi / 180.0)\n # points =\n # cv2.polylines(img=img, pts=[points], isClosed=True, color=(0, 0, 255), thickness=3)\n\n # 绘制角度线\n cv2.imwrite(config.save_angle_z_path, img)\n if b_show:\n cv2.imshow(\"circle\", img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n draw_angle_obj = DrawAngle(20,200)\n draw_angle_obj.draw_y(20,b_show=True)\n draw_angle_obj.draw_z(30,b_show=True)\n", "repo_name": "ndkjing/uuv", "sub_path": "common/draw_angle.py", "file_name": "draw_angle.py", "file_ext": "py", "file_size_in_byte": 6695, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "numpy.ones", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 30, "usage_type": "call"}, {"api_name": "cv2.line", "line_number": 32, "usage_type": "call"}, {"api_name": "cv2.line", "line_number": 35, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 40, "usage_type": "attribute"}, {"api_name": "math.sin", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 41, "usage_type": "attribute"}, {"api_name": "math.cos", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 42, "usage_type": "attribute"}, {"api_name": "math.sin", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 43, "usage_type": "attribute"}, {"api_name": "cv2.line", "line_number": 44, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 47, "usage_type": "call"}, {"api_name": "config.save_angle_y_path", "line_number": 47, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 49, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 51, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 62, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 64, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 70, "usage_type": "attribute"}, {"api_name": "math.sin", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 71, "usage_type": "attribute"}, {"api_name": "math.cos", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 75, "usage_type": "attribute"}, {"api_name": "math.sin", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 76, "usage_type": "attribute"}, {"api_name": "cv2.line", "line_number": 78, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 83, "usage_type": "attribute"}, {"api_name": "math.sin", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 84, "usage_type": "attribute"}, {"api_name": "cv2.line", "line_number": 86, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 95, "usage_type": "attribute"}, {"api_name": "math.sin", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 96, "usage_type": "attribute"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 97, "usage_type": "attribute"}, {"api_name": "cv2.putText", "line_number": 100, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 118, "usage_type": "attribute"}, {"api_name": "math.sin", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 119, "usage_type": "attribute"}, {"api_name": "cv2.putText", "line_number": 120, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 126, "usage_type": "attribute"}, {"api_name": "math.sin", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 127, "usage_type": "attribute"}, {"api_name": "cv2.line", "line_number": 129, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 138, "usage_type": "call"}, {"api_name": "config.save_angle_z_path", "line_number": 138, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 140, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 141, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 142, "usage_type": "call"}]} +{"seq_id": "32612635360", "text": "import pandas as pd\nimport pathlib\nfrom enum import Enum\n\nclass FeatureType(Enum):\n CATEGORICAL = 1\n NUMERICAL = 2\n TIMESERIES = 3\n\n\n\ndef get_numeric_features(data, uniqueness_threshold=0.05):\n \"\"\"\n Given a pandas DataFrame, retuns the list of numeric columns from it.\n\n :param data: (pandas DataFrame), the target dataset\n :param uniqueness_threshold: (float), the uniqueness of occurance to treat numeric labeled feature to exclude from numeric\n :return: (list) list of numeric columns in the DataFrame\n \"\"\"\n\n num_cols = data._get_numeric_data().columns\n\n # finding out numeric labeled categorical features \n # Reference: https://stackoverflow.com/questions/35826912/what-is-a-good-heuristic-to-detect-if-a-column-in-a-pandas-dataframe-is-categori\n likely_categorical = []\n for var in num_cols:\n unique_values_ratio = 1.*data[var].nunique()/data[var].count()\n\n if unique_values_ratio < uniqueness_threshold:\n likely_categorical.append(var)\n\n\n return list(set(num_cols) - set(likely_categorical))\n\n\ndef get_categorical_features(data, uniqueness_threshold=0.05):\n \"\"\"\n Given a pandas DataFrame, retuns the list of categorical columns from it.\n\n :param data: (pandas DataFrame), the target dataset\n :param uniqueness_threshold: (float), the uniqueness of occurance to treat numeric labeled feature to exclude from numeric\n :return: (list) list of categorical columns in the DataFrame\n \"\"\"\n\n all_columns_set = set(data.columns)\n numeric_columns_set = set(get_numeric_features(data=data, uniqueness_threshold=uniqueness_threshold))\n\n return list(all_columns_set - numeric_columns_set)\n\n\ndef get_all_features(data):\n \"\"\"\n Given a Pandas DataFrame, returns all its column names.\n\n :param data: (Pandas DataFrame), the target DataFrame\n :return: (list) list of all the column names in the DataFrame\n \"\"\"\n\n return list(data.columns)\n\n\ndef get_feature_type(data, target_feature)->str:\n \"\"\" Returns the type of the supplied feature. Such as, Categorical, Neumerical, TimeSeries.\n\n Args:\n data (Pandas DataFrame): The target DataFrame \n target_feature (string, column name): the target feature to detect and return type of.\n\n Returns:\n str: \"\" \n \"\"\"\n\n if target_feature not in get_all_features(data):\n return None\n\n if target_feature in get_numeric_features(data):\n return FeatureType.NUMERICAL\n elif target_feature in get_categorical_features(data):\n return FeatureType.CATEGORICAL\n \n ## TODO: Add Time series data type\n\n return None\n\n\n\nif __name__ == '__main__':\n WEBAPP_DIR = str(pathlib.Path(__file__).parent.parent.parent.absolute()) + \"/webapp/\"\n\n df = pd.read_csv(WEBAPP_DIR+\"/datasets/titanic.csv\")\n\n print(get_numeric_features(df))\n print(get_categorical_features(df))\n\n print(get_feature_type(df, \"sex\") == get_feature_type(df, \"survived\"))\n\n print(FeatureType.CATEGORICAL == FeatureType.NUMERICAL)\n\n # n = get_all_features(data=df)\n\n # dataType = get_feature_type(data=df, target_feature=\"sex\")\n\n # print(dataType)\n", "repo_name": "pseudoPixels/vizAI", "sub_path": "graphaite/core/utils/dataFrameUtils.py", "file_name": "dataFrameUtils.py", "file_ext": "py", "file_size_in_byte": 3137, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "enum.Enum", "line_number": 5, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 88, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 90, "usage_type": "call"}]} +{"seq_id": "40243842182", "text": "import streamlit as st\nimport pandas as pd\nimport time\nfrom DAO import *\nfrom model import *\nimport pdfkit as pdf\nimport matplotlib.pyplot as plt\n\n# Função para gerar o relatório a partir dos critérios selecionados\ndef geraRelatorio():\n if not relatorio_fields:\n return -1\n \n # Verifica se foi adicionado algum filtro \n if st.session_state.filtros == \"\":\n st.session_state.filtros = None\n \n session = DAO.getSession()\n session.expire_on_commit = False\n\n # Verifica sobre qual tabela do banco será emitido um relatório\n if relatorio_type == 'Videos':\n query = DAORelatorioVideos.select(session, st.session_state.filtros, st.session_state.ordenacao, relatorio_fields)\n if relatorio_type == 'Streams':\n query = DAORelatorioStreams.select(session, st.session_state.filtros, st.session_state.ordenacao, relatorio_fields)\n if relatorio_type == 'Canais':\n query = DAORelatorioCanais.select(session, st.session_state.filtros, st.session_state.ordenacao, relatorio_fields)\n if relatorio_type == 'Usuários':\n query = DAORelatorioUsuarios.select(session, st.session_state.filtros, st.session_state.ordenacao, relatorio_fields)\n if relatorio_type == 'Categorias':\n query = DAORelatorioCategories.select(session, st.session_state.filtros, st.session_state.ordenacao, relatorio_fields)\n\n # Conexão\n connection = session.connection()\n df = pd.read_sql_query(query.statement, con = connection)\n session.commit()\n session.close()\n\n # Fazer com que o dataframe receba os dados da sql query recebida na linha 34\n st.session_state.dataframe = df\n\n # Convertendo o dataframe do relatorio para excel e html\n df.to_excel(\"DB/relatorio.xlsx\", index=False)\n df.to_html('DB/relatorio.html', index=False)\n\n# Função para limpar o campo do input do valor do filtro\ndef clear_form():\n st.session_state[\"bar\"] = \"\"\n\n# Define os campos que podem ser incluídos nos filtros e no relatório\ndef defineCampos():\n st.session_state.filtros = \"\"\n st.session_state.query = False\n st.session_state.qtdFiltros = 0\n\ndef defineOrdenacao():\n st.session_state.ordenacao = True\n\n# Converter o relatório para pdf\ndef relatorioPDF():\n path_to_wkhtmltopdf = r'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'\n config = pdf.configuration(wkhtmltopdf=path_to_wkhtmltopdf)\n pdf.from_file('DB/relatorio.html', 'relatorio.pdf', configuration=config)\n\n# Aqui está sendo mostrado o título da página (na aba do navegador)\nst.set_page_config(page_title=\"Relatório Twitch API\")\n\n# Estilização da página\napp_style = \"\"\"\n \n \"\"\"\nst.markdown(app_style, unsafe_allow_html=True) \n\n# Barra lateral\nst.sidebar.header(\"Twitch API\")\nst.sidebar.image('./img/twitch.png')\nst.sidebar.write(\"\\n\")\nst.sidebar.header(\"Desenvolvido por:\")\nst.sidebar.markdown('''
''', unsafe_allow_html=True)\nst.sidebar.write(\"Guilherme Ribeiro\")\nst.sidebar.write(\"Tales Oliveira\")\nst.sidebar.markdown('''
''', unsafe_allow_html=True)\n\n# Título da página\nst.title('Relatórios Twitch API\\n')\n\n# ===================================================================\n# Se pagina=0, mostra a página inicial. Se pagina=1, mostra o relatório\nif 'pagina' not in st.session_state:\n st.session_state.pagina = 0\n\n# Para exibir o dataframe\nif 'dataframe' not in st.session_state:\n st.session_state.dataframe = False\n\n# Dados do dataframe do relatório\nif 'df' not in st.session_state:\n st.session_state.df = False\n\n# Filtros\nif 'filtros' not in st.session_state:\n st.session_state.filtros = \"\"\n\n# Conta a quantidade de filtros\nif 'qtdFiltros' not in st.session_state:\n st.session_state.qtdFiltros = 0\n\n# Ordenação\nif 'ordenacao' not in st.session_state:\n st.session_state.ordenacao = None\n\n# Query SQL a ser executada\nif 'query' not in st.session_state:\n st.session_state.query = False\n\n# Relatóio\nif 'relatorio' not in st.session_state:\n st.session_state.relatorio = False\n\n# Dados em PDF\nif 'dataPdf' not in st.session_state:\n st.session_state.dataPdf = None\n\n# Dados em XLSX\nif 'dataXlsx' not in st.session_state:\n st.session_state.dataXlsx = None\n\n# ==============================================================================================\n# Página inicial, onde são selecionados os campos, filtros e ordenação para gerar o relatório\nif st.session_state.pagina == 0:\n relatorio_type = st.selectbox(\n 'Selecione a tabela para gerar o relatório:',\n ('Videos', 'Streams', 'Canais', 'Usuários', 'Categorias'), on_change=defineCampos)\n\n session = DAO.getSession()\n session.expire_on_commit = False\n\n if st.session_state.query is False:\n if relatorio_type == 'Videos':\n query = DAORelatorioVideos.select(session, None, None, None) \n elif relatorio_type == 'Streams':\n query = DAORelatorioStreams.select(session, None, None, None)\n elif relatorio_type == 'Canais':\n query = DAORelatorioCanais.select(session, None, None, None)\n elif relatorio_type == 'Usuários':\n query = DAORelatorioUsuarios.select(session, None, None, None)\n elif relatorio_type == 'Categorias':\n query = DAORelatorioCategories.select(session, None, None, None)\n\n st.session_state.df = pd.read_sql_query(query.statement, con=session.bind)\n session.commit()\n session.close()\n st.session_state.query = True\n\n # Selecionar os campos das tabelas\n relatorio_fields = st.multiselect(f'Selecione os campos do relatório de {relatorio_type}:', options = st.session_state.df.columns, placeholder = 'Selecionar campo')\n \n # Formulário dos filtros\n st.write('\\n')\n st.write(\"Filtrar por campos:\")\n with st.form(\"myform\"):\n f1, f2, f3 = st.columns([1, 1, 1])\n with f1:\n field = st.selectbox(\"Campo:\", options = st.session_state.df.columns)\n with f2:\n comparison = st.selectbox(\"Comparação:\", options = ('igual', 'maior', 'menor', 'maior ou igual', 'menor ou igual', 'diferente de', 'contendo a string'))\n with f3:\n comparison_value = st.text_input(\"Valor\")\n\n f1, f2, f3 = st.columns([1, 1, 1])\n \n with f2:\n st.write('\\n')\n submit = st.form_submit_button(label=\"Adicionar filtro\", on_click=clear_form)\n\n # Tipo de comparação a ser feita\n if submit and comparison_value:\n map_operation = {\n 'igual': f'= ',\n 'maior': f'> ',\n 'menor': f'< ',\n 'maior ou igual': f'>= ',\n 'menor ou igual': f'<= ',\n 'diferente de': f'!= ',\n 'contendo a string': 'LIKE \\'%'\n }\n\n operation = map_operation[comparison]\n \n if st.session_state.df[f'{field}'].dtypes == 'object' and not comparison == 'contendo a string':\n value = f\"'{comparison_value}'\"\n elif comparison == 'contendo a string':\n value = f\"{comparison_value}\"\n else:\n value = f'{comparison_value}'\n\n # Adiciona os filtros\n if st.session_state.qtdFiltros == 0:\n st.session_state.filtros += f\"{field} {operation}{value}\"\n else:\n st.session_state.filtros += f\" AND {field} {operation}{value}\"\n\n # Se a opção \"contendo a string\" for utilizada\n if comparison == 'contendo a string':\n st.session_state.filtros += '%\\''\n\n # Adiciona filtro\n st.session_state.qtdFiltros = 1\n container = st.empty()\n container.success('Filtro adicionado com sucesso!') \n time.sleep(3) \n container.empty() \n\n # Caso o valor a ser comparado com o campo não seja preenchido\n if submit and not comparison_value: \n container = st.empty()\n container.error('Preencha o valor da comparação!') \n time.sleep(3) \n container.empty() \n\n st.write('\\n\\n\\n\\n\\n\\n')\n st.write('Filtros adicionados:')\n with st.expander(\" \"):\n st.write(st.session_state.filtros)\n\n\n # Formulário de ordenação do relatório\n st.write('\\n')\n st.write(\"Ordenar relatório:\")\n with st.form(\"myform2\"):\n o1, o2 = st.columns([1.5, 1.5])\n with o1:\n camposOrdenacao = st.selectbox('Ordenar por:', options = st.session_state.df.columns)\n with o2:\n tipoOrdenacao = st.selectbox(f'Campo {camposOrdenacao} ordenado de modo:', options=('Crescente', 'Decrescente'), index=0)\n #tipoOrdenacao = st.radio(f'Campo {camposOrdenacao} ordenado de modo:', options = ('Crescente', 'Decrescente'), horizontal = True)\n \n st.write('\\n\\n\\n\\n\\n')\n o1, o2 = st.columns([1, 1])\n \n st.write('\\n')\n ordenacao_relatorio = st.form_submit_button(label='Ordenar relatório', on_click=defineOrdenacao)\n\n if ordenacao_relatorio == 'Crescente':\n ordenacao = 'ASC'\n else:\n ordenacao = 'DESC'\n \n if ordenacao_relatorio:\n st.session_state.ordenacao = f'{camposOrdenacao} {ordenacao}'\n container = st.empty()\n container.success(f'Relatório será ordenado pelo campo {camposOrdenacao} de forma {tipoOrdenacao}!') \n time.sleep(3) \n container.empty() \n\n st.write('\\n\\n\\n')\n f1, f2, f3 = st.columns([1, 1, 1])\n\n with f2:\n st.write('\\n\\n\\n\\n\\n')\n relatorio = st.button('Gerar relatório')\n\n st.write('\\n\\n\\n\\n\\n')\n\n if relatorio:\n status = geraRelatorio()\n if status == -1:\n st.error(\"Selecione os campos do relatório!\")\n else:\n st.session_state.pagina = 1\n st.rerun()\n\n# ==============================================================================================\n# Página do relatório\nelse:\n if st.session_state.relatorio == False:\n # Gerar pdf do relatório\n relatorioPDF()\n with open(\"relatorio.pdf\", \"rb\") as pdf_file:\n st.session_state.pdfData = pdf_file.read()\n\n # Gerar xlsx do relatório\n with open(\"DB/relatorio.xlsx\", \"rb\") as xlsx_file:\n st.session_state.xlsxData = xlsx_file.read()\n\n # Exibe dataframe\n st.session_state.relatorio = st.dataframe(st.session_state.dataframe, width=1000, height=500)\n\n f1, f2, f3 = st.columns([1, 1, 1])\n st.write('\\n')\n\n with f1:\n relatorio_pdf = st.download_button('Exportar relátorio para PDF', data = st.session_state.pdfData,\n file_name=\"relatorio.pdf\")\n\n with f2:\n relatorio_xlsx= st.download_button('Exportar relátorio para XLSX', data = st.session_state.xlsxData,\n file_name=\"relatorio.xlsx\")\n\n with f3:\n new_relatorios = st.button(\"Criar mais relatórios\")\n \n # Caso seja selecionada a opção de gerar mais relatórios\n if new_relatorios:\n st.session_state.pagina = 0\n st.session_state.qtdFiltros = 0\n st.session_state.filtros = \"\"\n st.session_state.ordenacao = None\n st.session_state.relatorio = False\n relatorio_fields = []\n st.rerun()\n\n with f1:\n relatorio_type = st.selectbox(\n 'Selecione o relatório:',\n ('Videos', 'Streams', 'Canais', 'Usuários', 'Categorias'), on_change=defineCampos)\n\n with f2:\n st.session_state.relatorio_fields = st.multiselect(f'Selecione os campos do relatório de {relatorio_type}:', options=st.session_state.df.columns)\n\n# ==============================================================================================\n# Lógica para o gráfico\n if st.session_state.relatorio and 'relatorio_fields' in st.session_state and len(st.session_state.relatorio_fields) >= 2:\n x_column = st.session_state.relatorio_fields[0]\n y_column = st.session_state.relatorio_fields[1]\n grouped_data = st.session_state.df.groupby(x_column)[y_column].count().reset_index()\n\n st.write('\\n\\n')\n st.write(f\"Gráfico de contagem de {y_column} agrupado por {x_column}:\")\n\n # Use st.pyplot() para exibir a figura Matplotlib\n fig, ax = plt.subplots()\n grouped_data.plot(kind='bar', x=x_column, y=y_column, ax=ax)\n st.pyplot(fig)\n", "repo_name": "Gksnoda/API-twitch", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 15456, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "streamlit.session_state", "line_number": 15, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 16, "usage_type": "attribute"}, {"api_name": "DAO.getSession", "line_number": 18, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 23, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 25, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 27, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 29, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 31, "usage_type": "attribute"}, {"api_name": "pandas.read_sql_query", "line_number": 35, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 40, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 48, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 52, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 53, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 54, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 57, "usage_type": "attribute"}, {"api_name": "pdfkit.configuration", "line_number": 62, "usage_type": "call"}, {"api_name": "pdfkit.from_file", "line_number": 63, "usage_type": "call"}, {"api_name": "streamlit.set_page_config", "line_number": 66, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 184, "usage_type": "call"}, {"api_name": "streamlit.sidebar.header", "line_number": 187, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 187, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.image", "line_number": 188, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 188, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.write", "line_number": 189, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 189, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.header", "line_number": 190, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 190, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.markdown", "line_number": 191, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 191, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.write", "line_number": 192, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 192, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.write", "line_number": 193, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 193, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.markdown", "line_number": 194, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 194, "usage_type": "attribute"}, {"api_name": "streamlit.title", "line_number": 197, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 201, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 202, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 205, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 206, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 209, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 210, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 213, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 214, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 217, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 218, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 221, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 222, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 225, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 226, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 229, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 230, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 233, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 234, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 237, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 238, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 242, "usage_type": "attribute"}, {"api_name": "streamlit.selectbox", "line_number": 243, "usage_type": "call"}, {"api_name": "DAO.getSession", "line_number": 247, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 250, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 262, "usage_type": "attribute"}, {"api_name": "pandas.read_sql_query", "line_number": 262, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 265, "usage_type": "attribute"}, {"api_name": "streamlit.multiselect", "line_number": 268, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 268, "usage_type": "attribute"}, {"api_name": "streamlit.write", "line_number": 271, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 272, "usage_type": "call"}, {"api_name": "streamlit.form", "line_number": 273, "usage_type": "call"}, {"api_name": "streamlit.columns", "line_number": 274, "usage_type": "call"}, {"api_name": "streamlit.selectbox", "line_number": 276, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 276, "usage_type": "attribute"}, {"api_name": "streamlit.selectbox", "line_number": 278, "usage_type": "call"}, {"api_name": "streamlit.text_input", "line_number": 280, "usage_type": "call"}, {"api_name": "streamlit.columns", "line_number": 282, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 285, "usage_type": "call"}, {"api_name": "streamlit.form_submit_button", "line_number": 286, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 302, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 310, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 311, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 313, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 317, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 320, "usage_type": "attribute"}, {"api_name": "streamlit.empty", "line_number": 321, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 323, "usage_type": "call"}, {"api_name": "streamlit.empty", "line_number": 328, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 330, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 333, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 334, "usage_type": "call"}, {"api_name": "streamlit.expander", "line_number": 335, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 336, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 336, "usage_type": "attribute"}, {"api_name": "streamlit.write", "line_number": 340, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 341, "usage_type": "call"}, {"api_name": "streamlit.form", "line_number": 342, "usage_type": "call"}, {"api_name": "streamlit.columns", "line_number": 343, "usage_type": "call"}, {"api_name": "streamlit.selectbox", "line_number": 345, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 345, "usage_type": "attribute"}, {"api_name": "streamlit.selectbox", "line_number": 347, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 350, "usage_type": "call"}, {"api_name": "streamlit.columns", "line_number": 351, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 353, "usage_type": "call"}, {"api_name": "streamlit.form_submit_button", "line_number": 354, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 362, "usage_type": "attribute"}, {"api_name": "streamlit.empty", "line_number": 363, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 365, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 368, "usage_type": "call"}, {"api_name": "streamlit.columns", "line_number": 369, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 372, "usage_type": "call"}, {"api_name": "streamlit.button", "line_number": 373, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 375, "usage_type": "call"}, {"api_name": "streamlit.error", "line_number": 380, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 382, "usage_type": "attribute"}, {"api_name": "streamlit.rerun", "line_number": 383, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 388, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 392, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 396, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 399, "usage_type": "attribute"}, {"api_name": "streamlit.dataframe", "line_number": 399, "usage_type": "call"}, {"api_name": "streamlit.columns", "line_number": 401, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 402, "usage_type": "call"}, {"api_name": "streamlit.download_button", "line_number": 405, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 405, "usage_type": "attribute"}, {"api_name": "streamlit.download_button", "line_number": 409, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 409, "usage_type": "attribute"}, {"api_name": "streamlit.button", "line_number": 413, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 417, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 418, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 419, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 420, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 421, "usage_type": "attribute"}, {"api_name": "streamlit.rerun", "line_number": 423, "usage_type": "call"}, {"api_name": "streamlit.selectbox", "line_number": 426, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 431, "usage_type": "attribute"}, {"api_name": "streamlit.multiselect", "line_number": 431, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 435, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 436, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 437, "usage_type": "attribute"}, {"api_name": "streamlit.session_state.df.groupby", "line_number": 438, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 438, "usage_type": "attribute"}, {"api_name": "streamlit.write", "line_number": 440, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 441, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 444, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 444, "usage_type": "name"}, {"api_name": "streamlit.pyplot", "line_number": 446, "usage_type": "call"}]} +{"seq_id": "71118427913", "text": "from datetime import timedelta\nfrom typing import List, Tuple\n\n\ndef humanize_timedelta(timedelta: timedelta) -> str:\n result: List[str] = []\n\n days = timedelta.days\n mm, ss = divmod(timedelta.seconds, 60)\n hh, mm = divmod(mm, 60)\n\n def plural(n: int) -> Tuple[int, str]:\n return n, \"s\" if abs(n) != 1 else \"\"\n\n if days > 0:\n result.append(\"%d day%s\" % plural(days))\n if hh > 0 or result:\n result.append(\"%d hour%s\" % plural(hh))\n if mm > 0 or result:\n result.append(\"%d min%s\" % plural(mm))\n if len(result) <= 1:\n result.append(\"%d sec%s\" % plural(ss))\n\n return \", \".join(result)\n\n\ndef humanize_bytes(bytes: int) -> str:\n units = [\"B\", \"kB\", \"MB\", \"GB\"]\n\n factor = 1\n unit = \"\"\n for unit in units:\n next_factor = factor << 10\n if bytes < next_factor:\n break\n factor = next_factor\n\n return \"%.2f %s\" % (float(bytes) / factor, unit)\n", "repo_name": "dmitmel/dotfiles", "sub_path": "script-resources/welcome/humanize.py", "file_name": "humanize.py", "file_ext": "py", "file_size_in_byte": 875, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 66, "dataset": "github-code", "pt": "27", "api": [{"api_name": "datetime.timedelta", "line_number": 5, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 6, "usage_type": "name"}, {"api_name": "datetime.timedelta.days", "line_number": 8, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 8, "usage_type": "name"}, {"api_name": "datetime.timedelta.seconds", "line_number": 9, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 9, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 12, "usage_type": "name"}]} +{"seq_id": "28771183549", "text": "import os\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom shared import database\nfrom shared import printlog\nfrom datetime import datetime\nimport matplotlib.dates as mdates\n\n\nclass Consumption:\n \"\"\" plotter implementation \"\"\"\n\n def __init__(self, from_date, to_date,\n filename='hourly.png',\n printer=printlog.PrintLog()):\n \"\"\" run plotter once \"\"\"\n\n # prefix filename with date\n filename = from_date[0:10] + '-' + filename\n\n # open database\n db = database.Database(printer)\n\n # create x axis as numpy datetime objects\n xlist = db.get_hours(from_date, to_date)\n xl = []\n for s in xlist:\n xl.append(datetime.strptime(s, '%Y-%m-%d %H:%M:%S'))\n x = np.array(xl)\n\n # create & decorate canvas\n fig, ax = plt.subplots(figsize=(11.6, 8.2)) # object oriented IF\n ax.set_xlabel('Datetime')\n ax.set_ylabel('kg (pellets)')\n ax.set_title(filename) # title is filename\n ax.grid(linestyle='dotted', linewidth='0.2', color='grey') # grid\n\n # create hourly chart\n ylist = db.get_hourly_consumption(from_date, to_date)\n y = np.array(ylist)\n charttype = 'bar'\n if charttype == 'line':\n hrs = mdates.HourLocator() # every hour\n ax.xaxis.set_minor_locator(hrs) # minor ticks\n ax.plot(x, y, label='kgh (pellets)', color='brown', linestyle='solid')\n ax.legend()\n #\n elif charttype == 'bar':\n # render xaxis labels\n plt.xticks(rotation=90)\n labels = []\n for s in xlist:\n labels.append(s[:13])\n # render bar chart\n ax.bar(np.array(labels, dtype=object), y)\n # add statistics to bar chart\n kgs = 0\n for y in ylist:\n kgs += y\n hrs = len(ylist)\n avg = round(kgs / hrs * 24, 1)\n stats = ' (' + str(kgs) + ' kg in ' + str(hrs) + ' hr, avg= ' + str(avg) + ' kg/day)'\n ax.set_title(filename + stats)\n ax.axhline(kgs / hrs, color='red', linewidth=2)\n #\n elif charttype == 'step':\n # see matplotlib.pyplot.step\n raise Exception('Step chart not implemented yet')\n #\n # create output file\n printer.print('Created file: ' + filename)\n fig.savefig(printer.get_foldername() + printer.get_slash() + filename)\n fig.show()\n\n\nif __name__ == '__main__':\n print('So sorry, the ' + os.path.basename(__file__) + ' module does not run as a standalone.')\n", "repo_name": "majo48/connect-web-logger", "sub_path": "plotter/consumption.py", "file_name": "consumption.py", "file_ext": "py", "file_size_in_byte": 2631, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "27", "api": [{"api_name": "shared.printlog.PrintLog", "line_number": 15, "usage_type": "call"}, {"api_name": "shared.printlog", "line_number": 15, "usage_type": "name"}, {"api_name": "shared.database.Database", "line_number": 22, "usage_type": "call"}, {"api_name": "shared.database", "line_number": 22, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 28, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 28, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.dates.HourLocator", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.dates", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path", "line_number": 77, "usage_type": "attribute"}]} +{"seq_id": "41963925015", "text": "'''\r\n1. 이 성에 있는 방의 개수\r\n2. 가장 넓은 방의 넓이\r\n3. 하나의 벽을 제거하여 얻을 수 있는 가장 넓은 방 크기\r\n\r\nN M\r\nM 개 줄 정수로 벽에 대한 정보\r\n\r\n서쪽 벽 1 L\r\n북쪽 벽 2 U\r\n동쪽 벽 4 R\r\n남쪽 벽 8 D\r\n1 \r\n2\r\n4 \r\n8\r\n1 2 => 3\r\n1 4 => 5\r\n1 8 => 9\r\n2 4 => 6\r\n2 8 => 10\r\n4 8 => 12\r\n1 2 4 => 7\r\n1 2 8 => 11\r\n1 4 8 => 13\r\n2 4 8 => 14\r\n1 2 4 8 => 15\r\n# 테두리에 위치한 노드는 벽이 있다\r\n'''\r\nfrom collections import deque\r\nM,N = map(int,input().split())\r\ngrid = [list(map(int,input().split())) for _ in range(N)]\r\nvisited = [[-1 for _ in range(M)] for _ in range(N)]\r\nque = deque([])\r\ndic = { # 갈 수 있는 곳 상하좌우 북2 /남8 /서1/ 동4 # 15 #1 2 4 8 서 북 동 남 / 좌 상 우 하\r\n '0' : [1,1,1,1],\r\n '1' : [0,1,1,1],\r\n '2' : [1,0,1,1],\r\n '4' : [1,1,0,1],\r\n '8' : [1,1,1,0],\r\n '3' : [0,0,1,1],\r\n '5' : [0,1,0,1],\r\n '9' : [0,1,1,0],\r\n '6' : [1,0,0,1],\r\n '10': [1,0,1,0],\r\n '12': [1,1,0,0],\r\n '7' : [0,0,0,1],\r\n '11' : [0,0,1,0],\r\n '13' : [0,1,0,0],\r\n '14' : [1,0,0,0],\r\n '15' : [0,0,0,0]\r\n}\r\n\r\ndef in_range(x,y):\r\n return 0<= x < N and 0<=y 30:\n pyautogui.click(screenWidth - center[0]*widthScalar, center[1]*heightScalar)\n #cv2.circle(frame, center, radius, (255, 0, 255), 3)\n\n #cv2.imshow(\"detected circles\", frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n # When everything done, release the capture\n cap.release()\n cv2.destroyAllWindows()\n return 0\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n", "repo_name": "SunnyHarjani/fingerStylus", "sub_path": "fingerStylus.py", "file_name": "fingerStylus.py", "file_ext": "py", "file_size_in_byte": 2040, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "cv2.VideoCapture", "line_number": 9, "usage_type": "call"}, {"api_name": "pyautogui.size", "line_number": 15, "usage_type": "call"}, {"api_name": "cv2.HoughCircles", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.HOUGH_GRADIENT", "line_number": 28, "usage_type": "attribute"}, {"api_name": "numpy.uint16", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.around", "line_number": 35, "usage_type": "call"}, {"api_name": "pyautogui.moveTo", "line_number": 42, "usage_type": "call"}, {"api_name": "pyautogui.click", "line_number": 48, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 52, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 56, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 61, "usage_type": "attribute"}]} +{"seq_id": "30302242595", "text": "from functools import wraps\nfrom inspect import Parameter, Signature\nfrom typing import Any, Callable, List, Optional\n\nfrom fastapi import Query\nfrom makefun import with_signature\nfrom pydantic import NonNegativeInt, conint\n\nfrom fastapi_rest_framework.errors import BizError, ErrorCode\nfrom fastapi_rest_framework.schemas import FilterQuery, OrderingQuery, PaginationQuery\n\n\ndef parse_pagination_query(\n max_limit: Optional[NonNegativeInt] = 500, default_limit: NonNegativeInt = 10\n) -> Callable[..., PaginationQuery]:\n LimitType = conint(ge=0, le=max_limit)\n\n @wraps\n def wrapped(\n offset: NonNegativeInt = Query(0),\n limit: LimitType = Query(default_limit), # type: ignore\n ) -> PaginationQuery:\n return PaginationQuery(offset=offset, limit=NonNegativeInt(limit))\n\n return wrapped\n\n\ndef parse_ordering_query(\n fields: Optional[List[str]] = None,\n) -> Callable[..., OrderingQuery]:\n if fields is not None:\n fields_set = set(fields)\n\n @wraps\n def wrapped(\n ordering: str = Query(\n \"\",\n description=\"Comma seperated list of ordering the results.\\n\"\n \"You may also specify reverse orderings by prefixing the field name with '-'.\",\n example=\"-updated_at\",\n ),\n ) -> OrderingQuery:\n orderings = list(filter(None, ordering.split(\",\")))\n if fields is not None:\n for x in orderings:\n name = x.startswith(\"-\") and x[1:] or x\n if name not in fields_set:\n raise BizError(\n ErrorCode.IllegalFieldError,\n f\"{x} is not available in ordering fields\",\n )\n return OrderingQuery(orderings=orderings)\n\n return wrapped\n\n\ndef parse_filter_query(\n fields: Optional[List[str]] = None,\n) -> Callable[..., FilterQuery]:\n if fields is None:\n fields = []\n parameters = [\n Parameter(\n name=field,\n kind=Parameter.KEYWORD_ONLY,\n annotation=str,\n default=Query(\"\", description=f\"F{field} filter\"),\n )\n for field in fields\n ]\n signature = Signature(parameters)\n\n @with_signature(signature)\n def wrapped(**kwargs: Any) -> FilterQuery:\n return FilterQuery(fields=kwargs)\n\n return wrapped\n", "repo_name": "joint-online-judge/fastapi-rest-framework", "sub_path": "fastapi_rest_framework/parsers.py", "file_name": "parsers.py", "file_ext": "py", "file_size_in_byte": 2329, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "typing.Optional", "line_number": 14, "usage_type": "name"}, {"api_name": "pydantic.NonNegativeInt", "line_number": 14, "usage_type": "name"}, {"api_name": "pydantic.conint", "line_number": 16, "usage_type": "call"}, {"api_name": "pydantic.NonNegativeInt", "line_number": 20, "usage_type": "name"}, {"api_name": "fastapi.Query", "line_number": 20, "usage_type": "call"}, {"api_name": "fastapi.Query", "line_number": 21, "usage_type": "call"}, {"api_name": "fastapi_rest_framework.schemas.PaginationQuery", "line_number": 23, "usage_type": "call"}, {"api_name": "pydantic.NonNegativeInt", "line_number": 23, "usage_type": "call"}, {"api_name": "functools.wraps", "line_number": 18, "usage_type": "name"}, {"api_name": "fastapi_rest_framework.schemas.PaginationQuery", "line_number": 22, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 15, "usage_type": "name"}, {"api_name": "fastapi_rest_framework.schemas.PaginationQuery", "line_number": 15, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 29, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 29, "usage_type": "name"}, {"api_name": "fastapi.Query", "line_number": 36, "usage_type": "call"}, {"api_name": "fastapi_rest_framework.errors.BizError", "line_number": 48, "usage_type": "call"}, {"api_name": "fastapi_rest_framework.errors.ErrorCode.IllegalFieldError", "line_number": 49, "usage_type": "attribute"}, {"api_name": "fastapi_rest_framework.errors.ErrorCode", "line_number": 49, "usage_type": "name"}, {"api_name": "fastapi_rest_framework.schemas.OrderingQuery", "line_number": 52, "usage_type": "call"}, {"api_name": "functools.wraps", "line_number": 34, "usage_type": "name"}, {"api_name": "fastapi_rest_framework.schemas.OrderingQuery", "line_number": 42, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 30, "usage_type": "name"}, {"api_name": "fastapi_rest_framework.schemas.OrderingQuery", "line_number": 30, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 58, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 58, "usage_type": "name"}, {"api_name": "inspect.Parameter", "line_number": 63, "usage_type": "call"}, {"api_name": "inspect.Parameter.KEYWORD_ONLY", "line_number": 65, "usage_type": "attribute"}, {"api_name": "inspect.Parameter", "line_number": 65, "usage_type": "name"}, {"api_name": "fastapi.Query", "line_number": 67, "usage_type": "call"}, {"api_name": "inspect.Signature", "line_number": 71, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 74, "usage_type": "name"}, {"api_name": "fastapi_rest_framework.schemas.FilterQuery", "line_number": 75, "usage_type": "call"}, {"api_name": "makefun.with_signature", "line_number": 73, "usage_type": "call"}, {"api_name": "fastapi_rest_framework.schemas.FilterQuery", "line_number": 74, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 59, "usage_type": "name"}, {"api_name": "fastapi_rest_framework.schemas.FilterQuery", "line_number": 59, "usage_type": "name"}]} +{"seq_id": "20964657909", "text": "import io\nimport logging\nimport os\nimport time\nfrom datetime import datetime\nfrom typing import List, Tuple\nfrom urllib.parse import quote\n\nimport PyRSS2Gen\nfrom starlette_context import context\n\nfrom podcast.dao.podcast import Podcast as PodcastDao, PodcastSource\n\nfrom podcast.dao.episode import Episode as EpisodeDao\nfrom podcast.internal.resource.resource import Resource as InternalResource\nfrom podcast.internal.episode.episode import Episode as EpisodeInternal\nfrom podcast.pkg.cipher.jwt import Jwt\nfrom podcast.pkg.errors.biz_error import PodcastShareNotSet, PodcastShareTokenInvalid\nfrom podcast.pkg.parser.podcast import Podcast as PodcastInfo\nfrom podcast.pkg.parser.document import Document\nfrom podcast.pkg.parser.rss import RSS\nfrom podcast.pkg.parser.video import Video\n\nfrom podcast.pkg.type import dict_exclude_keys, str_is_empty\nfrom podcast.pkg.segment.text_segments import TextSegment\nfrom podcast.dao.base import GenStatus\n\n\nclass Podcast:\n def __init__(self, **kwargs):\n self.gid = kwargs.get(\"gid\", \"\")\n self.source = kwargs.get(\"source\", \"\")\n self.title = kwargs.get(\"title\", \"\")\n self.author = kwargs.get(\"author\", \"\")\n self.description = kwargs.get(\"description\", \"\")\n self.cover_resource_id = kwargs.get(\"cover_resource_id\", None)\n self.book_resource_id = kwargs.get(\"book_resource_id\", None)\n self.recent_play_chapter_gid = kwargs.get(\"recent_play_chapter_gid\", None)\n self.category_id = kwargs.get(\"category_id\", None)\n self.language = kwargs.get(\"language\", None)\n self.share_time = kwargs.get(\"share_time\", None)\n self.share_enable = kwargs.get(\"share_enable\", None)\n self.cover_url = kwargs.get(\"cover_url\", None)\n self.url = kwargs.get(\"url\", None)\n self.frequency = kwargs.get(\"frequency\", None)\n self.first_execute_time = kwargs.get(\"first_execute_time\", None)\n self.timer_id = kwargs.get(\"timer_id\", None)\n\n self.blog_rss_url = kwargs.get(\"blog_rss_url\", None)\n\n def __iter__(self):\n keys_map = {\n \"gid\": \"id\",\n \"source\": \"source\",\n \"title\": \"title\",\n \"author\": \"author\",\n \"cover_url\": \"coverUrl\",\n \"url\": \"url\",\n \"description\": \"description\",\n \"recent_play_chapter_gid\": \"recentPlayChapterId\",\n \"language\": \"language\",\n \"share_time\": \"share_time\",\n \"share_enable\": \"share_enable\",\n \"frequency\": \"frequency\",\n \"first_execute_time\": \"firstExecuteTime\",\n \"timer_id\": \"timerId\",\n }\n for key, new_key in keys_map.items():\n yield new_key, self.__dict__.get(key)\n\n def get_podcast(self) -> PodcastDao:\n podcast_dao: PodcastDao = PodcastDao(gid=self.gid)\n return podcast_dao.get_by_gid()\n\n def delete_podcast(self):\n podcast_dao: PodcastDao = PodcastDao(gid=self.gid)\n return podcast_dao.delete()\n\n def get_podcast_detail(self, offset=0, limit=100, order=\"desc\") -> Tuple[PodcastDao, List[EpisodeDao], int]:\n podcast: PodcastDao = self.get_podcast()\n if podcast is None:\n return None, []\n\n episodes = EpisodeDao(podcast_gid=podcast.gid).get_episodes_by_podcast_gid( offset, limit, order)\n\n total = EpisodeDao(podcast_gid=podcast.gid).get_episodes_total_by_podcast_gid()\n return podcast, episodes, total\n\n def get_podcasts_by_gids(self, gids: List[int])->List[PodcastDao]:\n return PodcastDao.get_by_gids(gids)\n\n def _get_podcast_without_voice(self):\n podcast: PodcastDao = self.get_podcast()\n if podcast is None:\n return None, []\n return podcast, EpisodeDao.get_episodes_without_voice(podcast.gid)\n\n @classmethod\n def get_podcasts(cls, offset: int, limit: int):\n return PodcastDao.get_podcasts(offset, limit)\n\n @classmethod\n def get_podcasts_total(cls):\n return PodcastDao.get_podcasts_total()\n\n def _parse_local_book(self) -> PodcastInfo:\n resources = InternalResource.get_resources_by_gid_array([self.book_resource_id])\n book_resource_dict = resources.get(self.book_resource_id)\n\n document = Document(self.language)\n document.loads(book_resource_dict.get(\"name\"), book_resource_dict.get(\"content\"))\n return document.parse()\n\n def _parse_rss(self) -> PodcastInfo:\n rss = RSS(self.url, self.language)\n return rss.parse()\n\n def _parse_video(self) -> PodcastInfo:\n video = Video(self.language, self.url)\n return video.parse()\n\n def parse(self):\n podcast_dao = self.get_podcast()\n\n self.language = podcast_dao.language\n self.source = podcast_dao.source\n self.title = podcast_dao.title\n self.description = podcast_dao.description\n self.author = podcast_dao.author\n\n podcast_info: PodcastInfo = None\n if self.source == PodcastSource.local:\n self.book_resource_id = podcast_dao.book_resource_id\n podcast_info = self._parse_local_book()\n elif self.source == PodcastSource.rss:\n self.url = podcast_dao.url\n podcast_info = self._parse_rss()\n elif self.source == PodcastSource.video:\n self.url = podcast_dao.url\n podcast_info = self._parse_video()\n self.save_podcast(podcast_info)\n return podcast_info\n\n @classmethod\n def _gen_language_segments(cls, podcast: PodcastDao, episodes: List[EpisodeDao]):\n episode_language_segments = {}\n for episode in episodes:\n episode_language_segments[episode.gid] = TextSegment(podcast.language, episode.content).gen_lang_segments()\n return episode_language_segments\n\n def prepare_gen_episode(self):\n podcast_dao, episodes_dao = self._get_podcast_without_voice()\n return self.gid, podcast_dao.source, EpisodeInternal.gen_language_segments(podcast_dao.source,\n podcast_dao.language, episodes_dao)\n\n def add_podcast(self, name):\n if (self.title is None or self.title == \"\") and self.source == PodcastSource.local:\n self.title = os.path.splitext(os.path.basename(name))[0]\n podcast = PodcastDao(**dict_exclude_keys(self.__dict__, \"gid\"))\n podcast.save()\n return podcast\n\n def update_podcast_info(self, **kwargs):\n podcast = PodcastDao(gid=self.gid, **kwargs)\n podcast.update(kwargs)\n\n def _update_podcast(self, podcast_info: PodcastInfo):\n update_fields = {\n \"title\": podcast_info.title if str_is_empty(self.title) else self.title,\n \"author\": podcast_info.author if str_is_empty(self.author) else self.author,\n \"description\": podcast_info.description if str_is_empty(self.description) is None else self.description,\n }\n\n if podcast_info.cover is not None:\n resource_dao = InternalResource(file=podcast_info.cover, type=\"cover\").save()\n update_fields.update({\n \"cover_resource_id\": resource_dao.gid\n })\n\n PodcastDao(gid=self.gid).update(update_fields)\n\n def _update_episodes(self, podcast_info: PodcastInfo):\n keys = [episode.key for episode in podcast_info.episodes]\n existed_episodes = EpisodeDao.get_episode_by_keys(self.gid, keys)\n existed_keys = set([episode.key for episode in existed_episodes])\n\n new_episodes = []\n for episode in podcast_info.episodes:\n if episode.key not in existed_keys:\n new_episodes.append(episode)\n\n episodes_dao = []\n for episode in reversed(new_episodes):\n kwargs = {\n \"podcast_gid\": self.gid,\n } | episode.__dict__\n\n if episode.cover is not None:\n resource_dao = InternalResource(file=episode.cover, type=\"cover\").save()\n kwargs.update({\n \"cover_resource_id\": resource_dao.gid\n })\n episodes_dao.append(EpisodeDao(**(dict_exclude_keys(kwargs, \"gid\"))))\n EpisodeDao.save(episodes_dao)\n\n def save_podcast(self, podcast_info: PodcastInfo):\n self._update_podcast(podcast_info)\n self._update_episodes(podcast_info)\n\n \n @classmethod\n def _gen_share_token(cls, payload: dict) -> str:\n return quote(Jwt(payload=payload).encode_share_token())\n\n @classmethod\n def _gen_resource_token(cls, podcast_dao: PodcastDao, resource_id: str) -> str:\n return quote(Jwt(payload={\n \"podcast_id\": podcast_dao.gid,\n \"share_time\": podcast_dao.share_time,\n \"user_id\": podcast_dao.created_by,\n \"resource_id\": resource_id,\n }).encode_share_token())\n\n def share_podcast(self, share_enable: bool) -> str:\n podcast_dao: PodcastDao = self.get_podcast()\n\n share_time = podcast_dao.share_time if podcast_dao.share_enable else int(time.time())\n if bool(podcast_dao.share_enable) != share_enable:\n podcast_dao.update({\n \"share_enable\": share_enable,\n \"share_time\": share_time,\n })\n\n share_token = self._gen_share_token({\n \"podcast_id\": podcast_dao.gid,\n \"share_time\": share_time,\n \"user_id\": podcast_dao.created_by,\n }) if share_enable else \"\"\n\n return share_token\n\n def gen_rss(self, share_token: str):\n podcast, episodes, _ = self.get_podcast_detail()\n\n if podcast.share_enable == 0:\n raise PodcastShareNotSet()\n\n base_url = context.data.get(\"base_url\")\n cover_url = f\"{base_url}/api/web/podcast_resource/${self._gen_resource_token(podcast, podcast.cover_resource_id)}\"\n rss = PyRSS2Gen.RSS2(title=podcast.title,\n description=podcast.title,\n link=base_url if podcast.url is None else podcast.url,\n image=PyRSS2Gen.Image(\n url=cover_url,\n title=podcast.title,\n link=cover_url,\n ),\n lastBuildDate=datetime.now())\n\n for episode in episodes:\n voice_url = f\"{base_url}/api/web/podcast_resource/${self._gen_resource_token(podcast, episode.voice_resource_id)}\"\n\n cover_resource_id = episode.cover_resource_id\n if str_is_empty(cover_resource_id):\n cover_resource_id = podcast.cover_resource_id\n episode_cover_url = f\"{base_url}/api/web/podcast_resource/${self._gen_resource_token(podcast, cover_resource_id)}\"\n rss.items.append(PyRSS2Gen.RSSItem(\n title=episode.title,\n link=episode.link,\n description=episode.title,\n enclosure=PyRSS2Gen.Enclosure(voice_url,\n episode.episode_size,\n \"episode/mpeg\"),\n guid=PyRSS2Gen.Guid(episode_cover_url, isPermaLink=1),\n pubDate=datetime.fromtimestamp(episode.pub_time if episode.pub_time else episode.created_at)\n ))\n\n try:\n content_io = io.BytesIO()\n rss.write_xml(content_io, \"utf-8\")\n return content_io\n except Exception as ex:\n logging.exception(ex)\n\n @staticmethod\n def check_rss_token(token: str) -> dict:\n data = Jwt(token=token).decode_share_token()\n context.data[\"user_id\"] = data.get(\"user_id\")\n podcast_id = data.get(\"podcast_id\")\n share_time = data.get(\"share_time\")\n\n podcast_dao = Podcast(gid=podcast_id).get_podcast()\n if not podcast_dao.share_enable:\n raise PodcastShareNotSet()\n\n if podcast_dao.share_time != share_time:\n raise PodcastShareTokenInvalid()\n \n return data\n\n def update_gen_status(self, status: int):\n podcast_dao: PodcastDao = self.get_podcast()\n podcast_dao.update({\n \"gen_status\": status,\n })", "repo_name": "PodcastIO/canary", "sub_path": "server/src/podcast/internal/podcast/podcast.py", "file_name": "podcast.py", "file_ext": "py", "file_size_in_byte": 12195, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "podcast.dao.podcast.Podcast", "line_number": 72, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 71, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 76, "usage_type": "name"}, {"api_name": "podcast.dao.podcast", "line_number": 80, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 80, "usage_type": "name"}, {"api_name": "podcast.dao.podcast", "line_number": 81, "usage_type": "name"}, {"api_name": "podcast.dao.episode.Episode", "line_number": 84, "usage_type": "call"}, {"api_name": "podcast.dao.podcast.gid", "line_number": 84, "usage_type": "attribute"}, {"api_name": "podcast.dao.podcast", "line_number": 84, "usage_type": "name"}, {"api_name": "podcast.dao.episode.Episode", "line_number": 86, "usage_type": "call"}, {"api_name": "podcast.dao.podcast.gid", "line_number": 86, "usage_type": "attribute"}, {"api_name": "podcast.dao.podcast", "line_number": 86, "usage_type": "name"}, {"api_name": "podcast.dao.podcast", "line_number": 87, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 79, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 79, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 79, "usage_type": "name"}, {"api_name": "podcast.dao.episode.Episode", "line_number": 79, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 89, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.Podcast.get_by_gids", "line_number": 90, "usage_type": "call"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 90, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 89, "usage_type": "name"}, {"api_name": "podcast.dao.podcast", "line_number": 93, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 93, "usage_type": "name"}, {"api_name": "podcast.dao.podcast", "line_number": 94, "usage_type": "name"}, {"api_name": "podcast.dao.podcast", "line_number": 96, "usage_type": "name"}, {"api_name": "podcast.dao.episode.Episode.get_episodes_without_voice", "line_number": 96, "usage_type": "call"}, {"api_name": "podcast.dao.episode.Episode", "line_number": 96, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.gid", "line_number": 96, "usage_type": "attribute"}, {"api_name": "podcast.dao.podcast.Podcast.get_podcasts", "line_number": 100, "usage_type": "call"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 100, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.Podcast.get_podcasts_total", "line_number": 104, "usage_type": "call"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 104, "usage_type": "name"}, {"api_name": "podcast.internal.resource.resource.Resource.get_resources_by_gid_array", "line_number": 107, "usage_type": "call"}, {"api_name": "podcast.internal.resource.resource.Resource", "line_number": 107, "usage_type": "name"}, {"api_name": "podcast.pkg.parser.document.Document", "line_number": 110, "usage_type": "call"}, {"api_name": "podcast.pkg.parser.podcast.Podcast", "line_number": 106, "usage_type": "name"}, {"api_name": "podcast.pkg.parser.rss.RSS", "line_number": 115, "usage_type": "call"}, {"api_name": "podcast.pkg.parser.podcast.Podcast", "line_number": 114, "usage_type": "name"}, {"api_name": "podcast.pkg.parser.video.Video", "line_number": 119, "usage_type": "call"}, {"api_name": "podcast.pkg.parser.podcast.Podcast", "line_number": 118, "usage_type": "name"}, {"api_name": "podcast.pkg.parser.podcast.Podcast", "line_number": 131, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.PodcastSource.local", "line_number": 132, "usage_type": "attribute"}, {"api_name": "podcast.dao.podcast.PodcastSource", "line_number": 132, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.PodcastSource.rss", "line_number": 135, "usage_type": "attribute"}, {"api_name": "podcast.dao.podcast.PodcastSource", "line_number": 135, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.PodcastSource.video", "line_number": 138, "usage_type": "attribute"}, {"api_name": "podcast.dao.podcast.PodcastSource", "line_number": 138, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 145, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 145, "usage_type": "name"}, {"api_name": "podcast.dao.episode.Episode", "line_number": 145, "usage_type": "name"}, {"api_name": "podcast.pkg.segment.text_segments.TextSegment", "line_number": 148, "usage_type": "call"}, {"api_name": "podcast.dao.podcast.language", "line_number": 148, "usage_type": "attribute"}, {"api_name": "podcast.dao.podcast", "line_number": 148, "usage_type": "name"}, {"api_name": "podcast.internal.episode.episode.Episode.gen_language_segments", "line_number": 153, "usage_type": "call"}, {"api_name": "podcast.internal.episode.episode.Episode", "line_number": 153, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.PodcastSource.local", "line_number": 157, "usage_type": "attribute"}, {"api_name": "podcast.dao.podcast.PodcastSource", "line_number": 157, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 158, "usage_type": "call"}, {"api_name": "os.path", "line_number": 158, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 158, "usage_type": "call"}, {"api_name": "podcast.dao.podcast", "line_number": 159, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 159, "usage_type": "call"}, {"api_name": "podcast.pkg.type.dict_exclude_keys", "line_number": 159, "usage_type": "call"}, {"api_name": "podcast.dao.podcast.save", "line_number": 160, "usage_type": "call"}, {"api_name": "podcast.dao.podcast", "line_number": 160, "usage_type": "name"}, {"api_name": "podcast.dao.podcast", "line_number": 161, "usage_type": "name"}, {"api_name": "podcast.dao.podcast", "line_number": 164, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 164, "usage_type": "call"}, {"api_name": "podcast.dao.podcast.update", "line_number": 165, "usage_type": "call"}, {"api_name": "podcast.dao.podcast", "line_number": 165, "usage_type": "name"}, {"api_name": "podcast.pkg.parser.podcast.Podcast", "line_number": 167, "usage_type": "name"}, {"api_name": "podcast.pkg.type.str_is_empty", "line_number": 169, "usage_type": "call"}, {"api_name": "podcast.pkg.type.str_is_empty", "line_number": 170, "usage_type": "call"}, {"api_name": "podcast.pkg.type.str_is_empty", "line_number": 171, "usage_type": "call"}, {"api_name": "podcast.internal.resource.resource.Resource", "line_number": 175, "usage_type": "call"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 180, "usage_type": "call"}, {"api_name": "podcast.pkg.parser.podcast.Podcast", "line_number": 182, "usage_type": "name"}, {"api_name": "podcast.dao.episode.Episode.get_episode_by_keys", "line_number": 184, "usage_type": "call"}, {"api_name": "podcast.dao.episode.Episode", "line_number": 184, "usage_type": "name"}, {"api_name": "podcast.internal.resource.resource.Resource", "line_number": 199, "usage_type": "call"}, {"api_name": "podcast.dao.episode.Episode", "line_number": 203, "usage_type": "call"}, {"api_name": "podcast.pkg.type.dict_exclude_keys", "line_number": 203, "usage_type": "call"}, {"api_name": "podcast.dao.episode.Episode.save", "line_number": 204, "usage_type": "call"}, {"api_name": "podcast.dao.episode.Episode", "line_number": 204, "usage_type": "name"}, {"api_name": "podcast.pkg.parser.podcast.Podcast", "line_number": 206, "usage_type": "name"}, {"api_name": "urllib.parse.quote", "line_number": 213, "usage_type": "call"}, {"api_name": "podcast.pkg.cipher.jwt.Jwt", "line_number": 213, "usage_type": "call"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 216, "usage_type": "name"}, {"api_name": "urllib.parse.quote", "line_number": 217, "usage_type": "call"}, {"api_name": "podcast.pkg.cipher.jwt.Jwt", "line_number": 217, "usage_type": "call"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 225, "usage_type": "name"}, {"api_name": "time.time", "line_number": 227, "usage_type": "call"}, {"api_name": "podcast.dao.podcast", "line_number": 243, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.share_enable", "line_number": 245, "usage_type": "attribute"}, {"api_name": "podcast.dao.podcast", "line_number": 245, "usage_type": "name"}, {"api_name": "podcast.pkg.errors.biz_error.PodcastShareNotSet", "line_number": 246, "usage_type": "call"}, {"api_name": "starlette_context.context.data.get", "line_number": 248, "usage_type": "call"}, {"api_name": "starlette_context.context.data", "line_number": 248, "usage_type": "attribute"}, {"api_name": "starlette_context.context", "line_number": 248, "usage_type": "name"}, {"api_name": "podcast.dao.podcast", "line_number": 249, "usage_type": "argument"}, {"api_name": "podcast.dao.podcast.cover_resource_id", "line_number": 249, "usage_type": "attribute"}, {"api_name": "PyRSS2Gen.RSS2", "line_number": 250, "usage_type": "call"}, {"api_name": "podcast.dao.podcast.title", "line_number": 250, "usage_type": "attribute"}, {"api_name": "podcast.dao.podcast", "line_number": 250, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.title", "line_number": 251, "usage_type": "attribute"}, {"api_name": "podcast.dao.podcast", "line_number": 251, "usage_type": "name"}, {"api_name": "podcast.dao.podcast.url", "line_number": 252, "usage_type": "attribute"}, {"api_name": "podcast.dao.podcast", "line_number": 252, "usage_type": "name"}, {"api_name": "PyRSS2Gen.Image", "line_number": 253, "usage_type": "call"}, {"api_name": "podcast.dao.podcast.title", "line_number": 255, "usage_type": "attribute"}, {"api_name": "podcast.dao.podcast", "line_number": 255, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 258, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 258, "usage_type": "name"}, {"api_name": "podcast.dao.podcast", "line_number": 261, "usage_type": "argument"}, {"api_name": "podcast.pkg.type.str_is_empty", "line_number": 264, "usage_type": "call"}, {"api_name": "podcast.dao.podcast.cover_resource_id", "line_number": 265, "usage_type": "attribute"}, {"api_name": "podcast.dao.podcast", "line_number": 265, "usage_type": "name"}, {"api_name": "podcast.dao.podcast", "line_number": 266, "usage_type": "argument"}, {"api_name": "PyRSS2Gen.RSSItem", "line_number": 267, "usage_type": "call"}, {"api_name": "PyRSS2Gen.Enclosure", "line_number": 271, "usage_type": "call"}, {"api_name": "PyRSS2Gen.Guid", "line_number": 274, "usage_type": "call"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 275, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 275, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 279, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 283, "usage_type": "call"}, {"api_name": "podcast.pkg.cipher.jwt.Jwt", "line_number": 287, "usage_type": "call"}, {"api_name": "starlette_context.context.data", "line_number": 288, "usage_type": "attribute"}, {"api_name": "starlette_context.context", "line_number": 288, "usage_type": "name"}, {"api_name": "podcast.pkg.errors.biz_error.PodcastShareNotSet", "line_number": 294, "usage_type": "call"}, {"api_name": "podcast.pkg.errors.biz_error.PodcastShareTokenInvalid", "line_number": 297, "usage_type": "call"}, {"api_name": "podcast.dao.podcast.Podcast", "line_number": 302, "usage_type": "name"}]} +{"seq_id": "38970076267", "text": "\"\"\"views.py\"\"\"\nimport numpy as np\nfrom django.shortcuts import render\nfrom joblib import load\n\nclf = load(\"Notebooks/dt_model.joblib\")\n\n\ndef index(req):\n \"\"\"View function for home page of site.\"\"\"\n return render(req, \"index.html\")\n\n\ndef result(pred):\n \"\"\"View function for result page of site.\"\"\"\n data = predict(pred)\n return render(pred, \"result.html\", {\"data\": data})\n\n\ndef predict(req):\n \"\"\"View function for prediction page of site.\"\"\"\n age = req.POST[\"age\"]\n sex = req.POST[\"sex\"]\n cp_ = req.POST[\"cp\"]\n trestbps = req.POST[\"trestbps\"]\n chol = req.POST[\"chol\"]\n fbs = req.POST[\"fbs\"]\n thalach = req.POST[\"thalach\"]\n exang = req.POST[\"exang\"]\n thal = req.POST[\"thal\"]\n x_test = [[age, sex, cp_, trestbps, chol, fbs, thalach, exang, thal]]\n x_test = np.array(x_test).reshape(1, 9)\n x_test = np.array(x_test, dtype=float)\n y_pred = clf.predict(x_test).tolist()\n ans = y_pred[0]\n return ans\n", "repo_name": "debjitpal5040/save-heart", "sub_path": "save_heart/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 956, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "joblib.load", "line_number": 6, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 11, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 33, "usage_type": "call"}]} +{"seq_id": "8941565816", "text": "from torch import nn\nfrom torch.nn import functional as F\n\nfrom maskrcnn_benchmark.modeling.poolers import Pooler\n\nfrom maskrcnn_benchmark.layers import Conv2d\n\n\nclass KeypointRCNNFeatureExtractor(nn.Module):\n def __init__(self, cfg):\n super(KeypointRCNNFeatureExtractor, self).__init__()\n\n resolution = cfg.MODEL.ROI_KEYPOINT_HEAD.POOLER_RESOLUTION\n scales = cfg.MODEL.ROI_KEYPOINT_HEAD.POOLER_SCALES\n sampling_ratio = cfg.MODEL.ROI_KEYPOINT_HEAD.POOLER_SAMPLING_RATIO\n pooler = Pooler(\n output_size=(resolution, resolution),\n scales=scales,\n sampling_ratio=sampling_ratio,\n )\n self.pooler = pooler\n\n input_features = cfg.MODEL.BACKBONE.OUT_CHANNELS\n layers = cfg.MODEL.ROI_KEYPOINT_HEAD.CONV_LAYERS\n next_feature = input_features\n self.blocks = []\n for layer_idx, layer_features in enumerate(layers, 1):\n layer_name = \"conv_fcn{}\".format(layer_idx)\n module = Conv2d(next_feature, layer_features, 3, stride=1, padding=1)\n nn.init.kaiming_normal_(module.weight, mode=\"fan_out\", nonlinearity=\"relu\")\n nn.init.constant_(module.bias, 0)\n self.add_module(layer_name, module)\n next_feature = layer_features\n self.blocks.append(layer_name)\n\n def forward(self, x, proposals):\n x = self.pooler(x, proposals)\n for layer_name in self.blocks:\n x = F.relu(getattr(self, layer_name)(x))\n return x\n\n\n_ROI_KEYPOINT_FEATURE_EXTRACTORS = {\n \"KeypointRCNNFeatureExtractor\": KeypointRCNNFeatureExtractor\n}\n\n\ndef make_roi_keypoint_feature_extractor(cfg):\n func = _ROI_KEYPOINT_FEATURE_EXTRACTORS[\n cfg.MODEL.ROI_KEYPOINT_HEAD.FEATURE_EXTRACTOR\n ]\n return func(cfg)\n", "repo_name": "mlcommons/training", "sub_path": "object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/keypoint_head/roi_keypoint_feature_extractors.py", "file_name": "roi_keypoint_feature_extractors.py", "file_ext": "py", "file_size_in_byte": 1796, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1501, "dataset": "github-code", "pt": "24", "api": [{"api_name": "torch.nn.Module", "line_number": 9, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 9, "usage_type": "name"}, {"api_name": "maskrcnn_benchmark.modeling.poolers.Pooler", "line_number": 16, "usage_type": "call"}, {"api_name": "maskrcnn_benchmark.layers.Conv2d", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.nn.init.kaiming_normal_", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 30, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 30, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 31, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 31, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 39, "usage_type": "name"}]} +{"seq_id": "34485849037", "text": "from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.contrib.auth import authenticate, login as loginuser\n\n# Create your views here.\n\n\"\"\"\ndef home(request):\n \n # print(\"Hello World!...This is Home\")\n \n html = '''\n \n

Home Page

\n \n
    \n
  • Item 1
  • \n
  • Item 2
  • \n
  • Item 3
  • \n
  • Item 4
  • \n
\n \n

This is Para

\n \n \n \n Go to facebook\n '''\n \n \n # return HttpResponse(\"Response from View File\")\n return HttpResponse(html)\n\n\"\"\"\n\n\ndef home(request):\n \n return render(request,'index.html')\n\n\n\n\ndef login(request):\n \n if request.method == \"GET\":\n form = AuthenticationForm()\n context = { \"form\" : form }\n \n return render(request, 'login.html', context=context)\n \n else:\n form = AuthenticationForm(data=request.POST)\n print(form.is_valid())\n if form.is_valid():\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('passowrd')\n user = authenticate(username = username, password = password)\n print(\"Authenticated::\", user) \n if user is not None:\n loginuser(request, user)\n return redirect('home')\n \n else:\n context = { \"form\" : form }\n return render(request, 'login.html', context=context)\n\n\n\n\ndef signUp(request):\n \n if request.method == 'GET':\n \n form = UserCreationForm()\n context = {\n \"form\" : form\n }\n return render(request, 'signup.html', context=context)\n \n else:\n \n print(request.POST)\n form = UserCreationForm(request.POST)\n context = {\n \"form\" : form\n }\n \n \n if form.is_valid():\n user = form.save()\n print(user)\n # return HttpResponse(\"Form is Valid\")\n if user is not None:\n return redirect('login')\n else:\n # return HttpResponse(\"Form is Valid\")\n return render(request, 'signup.html', context=context)\n \n ", "repo_name": "Snoveedh/YouDo_Medo", "sub_path": "app/views_backup.py", "file_name": "views_backup.py", "file_ext": "py", "file_size_in_byte": 2422, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "django.shortcuts.render", "line_number": 40, "usage_type": "call"}, {"api_name": "django.contrib.auth.forms.AuthenticationForm", "line_number": 48, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 51, "usage_type": "call"}, {"api_name": "django.contrib.auth.forms.AuthenticationForm", "line_number": 54, "usage_type": "call"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 59, "usage_type": "call"}, {"api_name": "django.contrib.auth.login", "line_number": 62, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 63, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 67, "usage_type": "call"}, {"api_name": "django.contrib.auth.forms.UserCreationForm", "line_number": 76, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 80, "usage_type": "call"}, {"api_name": "django.contrib.auth.forms.UserCreationForm", "line_number": 85, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 96, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 99, "usage_type": "call"}]} +{"seq_id": "4430129234", "text": "\"\"\"Files.\"\"\"\nimport glob\nimport csv\nfrom datetime import datetime\nfrom datetime import date\n\n\ndef no_data(header, types_dict, i):\n \"\"\"If data is '-', then return this function.\"\"\"\n if header[i] not in types_dict:\n types_dict[header[i]] = ['-']\n else:\n types_dict[header[i]].append('-')\n\n\ndef final_data_types(types_dict):\n \"\"\"Get final data types into dict.\"\"\"\n for key in types_dict:\n val = types_dict[key]\n if 'str' in val:\n types_dict[key] = 'str'\n continue\n if 'int' in val and 'date' in val:\n types_dict[key] = 'str'\n continue\n if 'int' in val and 'str' not in val and 'date' not in val:\n types_dict[key] = 'int'\n continue\n if 'date' in val and 'str' not in val and 'int' not in val:\n types_dict[key] = 'date'\n continue\n if '-' in val and 'str' not in val and 'int' not in val and 'date' not in val:\n types_dict[key] = '-'\n continue\n if '-' in val:\n continue\n return types_dict\n\n\ndef add_str(header, types_dict, i):\n \"\"\"Add 'str' to list.\"\"\"\n if header[i] not in types_dict:\n types_dict[header[i]] = ['str']\n else:\n types_dict[header[i]].append('str')\n\n\ndef add_int(header, types_dict, i):\n \"\"\"Add 'int' to list.\"\"\"\n if header[i] not in types_dict:\n types_dict[header[i]] = ['int']\n else:\n types_dict[header[i]].append('int')\n\n\ndef is_int(value):\n \"\"\"Check for digit.\"\"\"\n return value.isdigit()\n\n\ndef is_date(value):\n \"\"\"Check is correct date.\"\"\"\n format = \"%d.%m.%Y\"\n try:\n datetime.strptime(value, format).date()\n return True\n except ValueError:\n return False\n\n\ndef final(csv_list, types_dict, header):\n \"\"\"Final list of dicts with correct types.\"\"\"\n final_list = []\n for row in csv_list[1:]:\n final_dict = {}\n for i, value in enumerate(row):\n if value == '-':\n final_dict[header[i]] = None\n continue\n if final_data_types(types_dict)[header[i]] == 'str':\n final_dict[header[i]] = str(value)\n continue\n if final_data_types(types_dict)[header[i]] == 'int':\n final_dict[header[i]] = int(value)\n continue\n if final_data_types(types_dict)[header[i]] == 'date':\n final_dict[header[i]] = datetime.strptime(value, \"%d.%m.%Y\").date()\n final_list.append(final_dict)\n return final_list\n\n\ndef read_file_contents(filename: str) -> str:\n \"\"\"Read file contents into string.\"\"\"\n with open(filename) as f: # Opens file with name of \"test.txt\"\n data = f.read() # Reads all the lines from the file and saves it as a string.\n return data\n\n\ndef read_file_contents_to_list(filename: str) -> list:\n \"\"\"Read file contents into list of lines.\"\"\"\n list_of_lines = read_file_contents(filename).split('\\n')\n return list_of_lines\n\n\ndef read_csv_file(filename: str) -> list:\n \"\"\"Read CSV file into list of rows.\"\"\"\n csv_list = []\n with open(filename) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n csv_list.append(row)\n return csv_list\n\n\ndef write_contents_to_file(filename: str, contents: str) -> None:\n \"\"\"Write contents to file.\"\"\"\n with open(filename, \"w\") as f:\n f.write(contents)\n\n\ndef write_lines_to_file(filename: str, lines: list) -> None:\n \"\"\"Write lines to file.\"\"\"\n with open(filename, \"w\") as f:\n lines = '\\n'.join(lines)\n f.write(lines)\n\n\ndef write_csv_file(filename: str, data: list) -> None:\n \"\"\"\n Write data into CSV file.\n\n Data is a list of lists.\n List represents lines.\n Each element (which is list itself) represents columns in a line.\n\n [[\"name\", \"age\"], [\"john\", \"11\"], [\"mary\", \"15\"]]\n Will result in csv file:\n\n name,age\n john,11\n mary,15\n\n Use csv module here.\n\n :param filename: Name of the file.\n :param data: List of lists to write to the file.\n :return: None\n \"\"\"\n with open(filename, 'w', newline='') as csv_file:\n csv_writer = csv.writer(csv_file)\n for row in data:\n csv_writer.writerow(row)\n\n\ndef merge_dates_and_towns_into_csv(dates_file: str, towns_file: str, csv_output: str) -> None:\n \"\"\"\n Merge information from two files into one CSV file.\n\n dates_file contains names and dates. Separated by colon.\n john:01.01.2001\n mary:06.03.2016\n\n You don't have to validate the date.\n Every line contains name, colon and date.\n\n towns_file contains names and towns. Separated by colon.\n john:london\n mary:new york\n\n Every line contains name, colon and town name.\n\n Those two files should be merged by names.\n The result should be a csv file:\n\n name,town,date\n john,london,01.01.2001\n mary,new york,06.03.2016\n\n Applies for the third part:\n If information about a person is missing, it should be \"-\" in the output file.\n\n The order of the lines should follow the order in dates input file.\n Names which are missing in dates input file, will follow the order\n in towns input file.\n The order of the fields is: name,town,date\n\n name,town,date\n john,-,01.01.2001\n mary,new york,-\n\n Hint: try to reuse csv reading and writing functions.\n When reading csv, delimiter can be specified.\n\n :param dates_file: Input file with names and dates.\n :param towns_file: Input file with names and towns.\n :param csv_output: Output CSV-file with names, towns and dates.\n :return: None\n \"\"\"\n dates = []\n towns = []\n result = [[\"name\", \"town\", \"date\"]]\n with open(dates_file) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=':')\n for row in csv_reader:\n dates.append(row)\n with open(towns_file) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=':')\n for row in csv_reader:\n towns.append(row)\n\n for date_person in dates:\n name, date = date_person\n result.append([name, '-', date])\n\n for town_person in towns:\n name2, town = town_person\n for elem in result[1:]:\n if name2 == elem[0]:\n elem[1] = town\n break\n else:\n result.append([name2, town, '-'])\n\n with open(csv_output, 'w', newline='') as csv_file:\n csv_writer = csv.writer(csv_file)\n for row in result:\n csv_writer.writerow(row)\n\n\ndef read_csv_file_into_list_of_dicts(filename: str) -> list:\n \"\"\"\n Read csv file into list of dictionaries.\n\n Header line will be used for dict keys.\n\n Each line after header line will result in a dict inside the result list.\n Every line contains the same number of fields.\n\n Example:\n\n name,age,sex\n John,12,M\n Mary,13,F\n\n Header line will be used as keys for each content line.\n The result:\n [\n {\"name\": \"John\", \"age\": \"12\", \"sex\": \"M\"},\n {\"name\": \"Mary\", \"age\": \"13\", \"sex\": \"F\"},\n ]\n\n If there are only header or no rows in the CSV-file,\n the result is an empty list.\n\n The order of the elements in the list should be the same\n as the lines in the file (the first line becomes the first element etc.)\n\n :param filename: CSV-file to read.\n :return: List of dictionaries where keys are taken from the header.\n \"\"\"\n list_of_dicts = []\n lists = read_csv_file(filename)\n if lists:\n header_list = lists[0]\n lists.remove(header_list)\n for content_list in lists:\n dic = {}\n for i in range(len(header_list)):\n key = header_list[i]\n value = content_list[i]\n dic[key] = value\n list_of_dicts.append(dic)\n return list_of_dicts\n else:\n return []\n\n\ndef write_list_of_dicts_to_csv_file(filename: str, data: list) -> None:\n \"\"\"\n Write list of dicts into csv file.\n\n Data contains a list of dictionaries.\n Dictionary key represents the field.\n\n Example data:\n [\n {\"name\": \"john\", \"age\": \"23\"}\n {\"name\": \"mary\", \"age\": \"44\"}\n ]\n Will become:\n name,age\n john,23\n mary,44\n\n The order of fields/headers is not important.\n The order of lines is important (the same as in the list).\n\n Example:\n [\n {\"name\": \"john\", \"age\": \"12\"},\n {\"name\": \"mary\", \"town\": \"London\"}\n ]\n Will become:\n name,age,town\n john,12,\n mary,,London\n\n Fields which are not present in one line will be empty.\n\n The order of the lines in the file should be the same\n as the order of elements in the list.\n\n :param filename: File to write to.\n :param data: List of dictionaries to write to the file.\n :return: None\n \"\"\"\n list_of_lists = []\n header = [] # header contains e.g name, hobby and etc\n for dic in data: # get dictionary from list\n for key in dic: # get dict key\n if key in header: # if the key is already in header list, then go ahead\n continue\n else:\n header.append(key)\n list_of_lists.append(header)\n\n for dict in data:\n content = []\n for i in header:\n if i in dict.keys(): # check if element i is in dict\n content.append(dict[i])\n else:\n content.append('')\n list_of_lists.append(content)\n if len(data) == 0:\n list_of_lists = ''\n return write_csv_file(filename, list_of_lists)\n else:\n return write_csv_file(filename, list_of_lists)\n\n\ndef read_csv_file_into_list_of_dicts_using_datatypes(filename: str) -> list:\n \"\"\"\n Read data from file and cast values into different datatypes.\n\n If a field contains only numbers, turn this into int.\n If a field contains only dates (in format dd.mm.yyyy), turn this into date.\n Otherwise the datatype is string (default by csv reader).\n\n Example:\n name,age\n john,11\n mary,14\n\n Becomes ('age' is int):\n [\n {'name': 'john', 'age': 11},\n {'name': 'mary', 'age': 14}\n ]\n\n But if all the fields cannot be cast to int, the field is left to string.\n Example:\n name,age\n john,11\n mary,14\n ago,unknown\n\n Becomes ('age' cannot be cast to int because of \"ago\"):\n [\n {'name': 'john', 'age': '11'},\n {'name': 'mary', 'age': '14'},\n {'name': 'ago', 'age': 'unknown'}\n ]\n\n Example:\n name,date\n john,01.01.2020\n mary,07.09.2021\n\n Becomes:\n [\n {'name': 'john', 'date': datetime.date(2020, 1, 1)},\n {'name': 'mary', 'date': datetime.date(2021, 9, 7)},\n ]\n\n Example:\n name,date\n john,01.01.2020\n mary,late 2021\n\n Becomes:\n [\n {'name': 'john', 'date': \"01.01.2020\"},\n {'name': 'mary', 'date': \"late 2021\"},\n ]\n\n Value \"-\" indicates missing value and should be None in the result\n Example:\n name,date\n john,-\n mary,07.09.2021\n\n Becomes:\n [\n {'name': 'john', 'date': None},\n {'name': 'mary', 'date': datetime.date(2021, 9, 7)},\n ]\n\n None value also doesn't affect the data type\n (the column will have the type based on the existing values).\n\n The order of the elements in the list should be the same\n as the lines in the file.\n\n For date, strptime can be used:\n https://docs.python.org/3/library/datetime.html#examples-of-usage-date\n \"\"\"\n csv_list = read_csv_file(filename)\n types_dict = {}\n if len(csv_list) == 0:\n return []\n else:\n header = csv_list[0]\n for row in csv_list[1:]:\n for i, value in enumerate(row):\n if value == '-':\n no_data(header, types_dict, i)\n continue\n if is_date(value):\n if header[i] not in types_dict:\n types_dict[header[i]] = ['date']\n continue\n else:\n types_dict[header[i]].append('date')\n continue\n\n if not is_date(value) and not is_int(value):\n if header[i] not in types_dict:\n types_dict[header[i]] = ['str']\n continue\n else:\n types_dict[header[i]].append('str')\n continue\n\n if is_int(value):\n add_int(header, types_dict, i)\n continue\n else:\n add_str(header, types_dict, i)\n\n return final(csv_list, types_dict, header)\n\n\ndef read_people_data(directory: str) -> dict:\n \"\"\"\n Read people data from files.\n\n Files are inside directory. Read all *.csv files.\n Each file has an int field \"id\" which should be used to merge information.\n The result should be one dict where the key is id (int) and value is\n a dict of all the different values across the the files.\n Missing keys should be in every dictionary.\n Missing value is represented as None.\n\n File: a.csv\n id,name\n 1,john\n 2,mary\n 3,john\n\n File: births.csv\n id,birth\n 1,01.01.2001\n 2,05.06.1990\n\n File: deaths.csv\n id,death\n 2,01.02.2020\n 1,-\n\n Becomes:\n {\n 1: {\"id\": 1, \"name\": \"john\", \"birth\": datetime.date(2001, 1, 1), \"death\": None},\n 2: {\"id\": 2, \"name\": \"mary\", \"birth\": datetime.date(1990, 6, 5),\n \"death\": datetime.date(2020, 2, 1)},\n 3: {\"id\": 3, \"name\": \"john\", \"birth\": None, \"death\": None},\n }\n\n\n :param directory: Directory where the csv files are.\n :return: Dictionary with id as keys and data dictionaries as values.\n \"\"\"\n path = (directory + \"/\" + \"*.csv\")\n dict = {}\n files = [f for f in glob.glob(path)]\n for f in files:\n d = read_csv_file_into_list_of_dicts_using_datatypes(f)\n for line in d:\n if line['id'] not in dict:\n dict[line['id']] = line\n else:\n dict[line['id']].update(line)\n return dict\n\n\ndef generate_people_report(person_data_directory: str, report_filename: str) -> None:\n \"\"\"\n Generate report about people data.\n\n Data should be read using read_people_data().\n\n The input files contain fields \"birth\" and \"death\" which are dates. Those can be in different files. There are no duplicate headers in the files (except for the \"id\").\n\n The report is a CSV file where all the fields are written to\n (along with the headers).\n In addition, there should be two fields:\n - \"status\" this is either \"dead\" or \"alive\" depending on whether\n there is a death date\n - \"age\" - current age or the age when dying.\n The age is calculated as full years.\n Birth 01.01.1940, death 01.01.2020 - age: 80\n Birth 02.01.1940, death 01.01.2020 - age: 79\n\n If there is no birth date, then the age is -1.\n\n When calculating age, dates can be compared.\n\n The lines in the files should be ordered:\n - first by the age ascending (younger before older);\n if the age cannot be calculated, then those lines will come last\n - if the age is the same, then those lines should be ordered\n by birthdate descending (newer birth before older birth)\n - if both the age and birth date are the same,\n then by name ascending (a before b). If name is not available, use \"\" (people with missing name should be before people with name)\n - if the names are the same or name field is missing,\n order by id ascending.\n\n Dates in the report should in the format: dd.mm.yyyy\n (2-digit day, 2-digit month, 4-digit year).\n\n :param person_data_directory: Directory of input data.\n :param report_filename: Output file.\n :return: None\n \"\"\"\n operate_with_dicts = []\n people_data = read_people_data(person_data_directory)\n\n for i in people_data.values():\n ret = {}\n for el in i:\n ret[el] = i[el]\n if i[el] is None:\n ret[el] = '-'\n if type(i[el]) is date:\n ret[el] = ret[el].strftime('%d.%m.%Y')\n\n if 'birth' in i and i['birth'] is not None and 'death' in i and i['death'] is not None:\n age = i['death'].year - i['birth'].year - (\n (i['death'].month, i['death'].day) < (i['birth'].month, i['birth'].day))\n ret['age'] = age\n if 'birth' in i and i['birth'] is not None and 'death' in i and i['death'] is None:\n today = date.today()\n age = today.year - i['birth'].year - ((today.month, today.day) < (i['birth'].month, i['birth'].day))\n ret['age'] = age\n i['birth'] = i['birth'].strftime(\"%d.%m.%Y\")\n\n if ret['birth'] == '-':\n ret['age'] = -1\n\n if ret['death'] != '-':\n ret['status'] = 'dead'\n else:\n ret['status'] = 'alive'\n\n operate_with_dicts.append(ret)\n\n sorted_list = sorted(operate_with_dicts, key=lambda i: (i['age'] if i['age'] > -1 else 10000,\n -date_to_int(i['birth']) if i['birth'] != '-' else i[\n 'birth'],\n i['name'] if 'name' in i else '',\n i['id']))\n\n return write_list_of_dicts_to_csv_file(report_filename, sorted_list)\n\n\ndef date_to_int(date) -> int:\n \"\"\"Convert date to int type number.\"\"\"\n d = date.split('.')\n d.reverse()\n joined_string = ''.join(d)\n return int(joined_string)\n\n\nif __name__ == '__main__':\n # print(read_csv_file_into_list_of_dicts('csv_town.txt'))\n # print(read_people_data('data'))\n print(generate_people_report('data', 'example_report.csv'))\n", "repo_name": "Danwerk/Python-course", "sub_path": "EX/ex07_files/file_handling.py", "file_name": "file_handling.py", "file_ext": "py", "file_size_in_byte": 17815, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "datetime.datetime.strptime", "line_number": 65, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 65, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 87, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 87, "usage_type": "name"}, {"api_name": "csv.reader", "line_number": 109, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 150, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 203, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 207, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 212, "usage_type": "name"}, {"api_name": "datetime.date", "line_number": 213, "usage_type": "name"}, {"api_name": "csv.writer", "line_number": 225, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 495, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 554, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 562, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 562, "usage_type": "name"}, {"api_name": "datetime.date.split", "line_number": 588, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 588, "usage_type": "name"}]} +{"seq_id": "17683608701", "text": "import hashlib\nimport json\nimport io\nimport random\n\nimport ddddocr\nfrom PIL import Image\nimport execjs\nimport requests\nimport time\n\nfrom loguru import logger\nsession = requests.session()\nencrypt = open('encrypt.js', encoding='utf-8').read()\nencrypt = execjs.compile(encrypt)\nencrypt_param = open('encrypt_param.js', encoding='utf-8').read()\nencrypt_param = execjs.compile(encrypt_param)\nocr = ddddocr.DdddOcr(det=False, ocr=False, show_ad=False)\n\n\ndef _img_restore(img: bytes) -> bytes:\n \"\"\"\n 底图还原\n \"\"\"\n image = Image.open(io.BytesIO(img))\n standard_img = Image.new(\"RGBA\", (260, 160))\n position = [39, 38, 48, 49, 41, 40, 46, 47, 35, 34, 50, 51, 33, 32, 28, 29, 27, 26, 36, 37, 31, 30, 44, 45, 43,\n 42, 12, 13, 23, 22, 14, 15, 21, 20, 8, 9, 25, 24, 6, 7, 3, 2, 0, 1, 11, 10, 4, 5, 19, 18, 16, 17]\n s, u = 80, 10\n for c in range(52):\n a = position[c] % 26 * 12 + 1\n b = s if position[c] > 25 else 0\n im = image.crop(box=(a, b, a + 10, b + 80))\n standard_img.paste(im, box=(c % 26 * 10, 80 if c > 25 else 0))\n temp_io = io.BytesIO()\n standard_img.save(temp_io, format='png')\n return temp_io.getvalue()\n\n\ndef register_slide():\n params = {\n 't': str(time.time()).replace(\".\", \"\")[:13],\n }\n print(params)\n url = 'https://www.geetest.com/demo/gt/register-slide-official'\n response = session.get(\n url,\n params=params,\n )\n if response.status_code == 200:\n if response.json().get('success') == 1:\n gt = response.json().get('gt')\n challenge = response.json().get('challenge')\n logger.success(f\"注册成功: gt {gt} challenge {challenge}\")\n return gt, challenge\n else:\n logger.error(f\"注册失败\")\n else:\n logger.error(f\"{url} 接口异常非200状态码\")\n\n\ndef get_image(gt, challenge):\n params = {\n 'is_next': 'true',\n 'type': 'slide3',\n 'gt': gt,\n 'challenge': challenge,\n 'lang': 'zh-cn',\n 'https': 'true',\n 'protocol': 'https://',\n 'offline': 'false',\n 'product': 'embed',\n 'api_server': 'api.geevisit.com',\n 'isPC': 'true',\n 'autoReset': 'true',\n 'width': '100%',\n 'callback': 'geetest_1693994409960',\n }\n\n # url = 'https://api.geetest.com/get.php'\n url = 'https://api.geevisit.com/get.php'\n response = session.get(url, params=params)\n # print(response.content.decode(\"unicode_escape\"))\n if response.status_code == 200:\n if 'bg' in response.text and 'fullbg' in response.text:\n data = response.text.replace('geetest_1693994409960(', \"\")[:-1]\n json_Data = json.loads(data)\n bg = 'https://static.geetest.com/' + json_Data.get('bg').replace(\".jpg\", '.webp')\n slice = 'https://static.geetest.com/' + json_Data.get('slice').replace(\".jpg\", '.webp')\n challenge = json_Data.get(\"challenge\")\n try:\n bg_reponse = session.get(bg)\n slice_reponse = session.get(slice)\n hy_image = _img_restore(bg_reponse.content)\n with open(\"底图还原.png\", \"wb\") as f:\n f.write(hy_image)\n with open(\"小滑块.png\", \"wb\") as f:\n f.write(slice_reponse.content)\n logger.success('成功获取混淆底图')\n logger.success(f\"返回新的challenge: {challenge}\")\n return challenge, json_Data.get('s')\n except:\n logger.error('保存混淆底图失败')\n else:\n logger.error(f\"{url} 接口异常非200状态码\")\n\n\ndef ajax(gt, challenge):\n response = session.get(\n f'https://api.geevisit.com/ajax.php?gt={gt}&challenge={challenge}&lang=zh-cn&pt=0&client_type=web',\n )\n # print(response.text)\n\ndef _track(distance: int):\n def __ease_out_expo(step):\n return 1 if step == 1 else 1 - pow(2, -10 * step)\n if not isinstance(distance, int) or distance < 0:\n raise ValueError(f\"distance类型必须是大于等于0的整数: distance: {distance}, type: {type(distance)}\")\n # 初始化轨迹列表\n slide_track = [[random.randint(-50, -10), random.randint(-50, -10), 0], [0, 0, 0],]\n # 共记录count次滑块位置信息\n count = 30 + int(distance / 2)\n # 初始化滑动时间\n t = random.randint(50, 100)\n # 记录上一次滑动的距离\n _x, _y = 0, 0\n for i in range(count):\n # 已滑动的横向距离\n x = round(__ease_out_expo(i / count) * distance)\n # 滑动过程消耗的时间\n t += random.randint(10, 20)\n if x == _x:\n continue\n slide_track.append([x, _y, t])\n _x = x\n slide_track.append(slide_track[-1])\n passTime = slide_track[-1][-1]\n return slide_track, passTime\n\ndef guiji(offset):\n # break_flag = x + offset\n guiji_array = []\n array_one = [-31, -31, 0]\n guiji_array.append(array_one)\n x, y, time_x = 0, 0, 0\n while x < offset:\n i = [x, y, time_x]\n x += random.randint(0, 2)\n y += random.randint(-1, 1)\n time_x += random.randint(0, 15)\n guiji_array.append(i)\n guiji_array.append(i) #\n logger.info(f\"原轨迹长度: {len(guiji_array)}\")\n logger.info(f\"原轨迹: {guiji_array}\")\n return guiji_array\n\n\ndef slide_verify(gt, challenge, guiji, t, passtime, s):\n encrypt_params = encrypt_param.call(\"get_aes_params\", guiji, t, gt, challenge, passtime, s)\n encrypt_params['rp'] = hashlib.md5(encrypt_params.get('rp').encode()).hexdigest()\n w = encrypt.call('get_w', json.dumps(encrypt_params))\n\n params = {\n 'gt': gt,\n 'challenge': challenge,\n 'lang': 'zh-cn',\n '%24_BCX': '0',\n 'client_type': 'web',\n \"w\": w,\n 'callback': 'geetest_1694058231021'\n }\n response = session.get(\n 'https://api.geevisit.com/ajax.php', params=params\n )\n print(response.text)\n\ndef loc_image(bg_path, block_path):\n try:\n # bg_img = Image.open(bg_path)\n # block_img = Image.open(block_path)\n target_content = open(bg_path, \"rb\").read()\n background_content = open(block_path, \"rb\").read()\n res = ocr.slide_match(target_content, background_content, simple_target=True)\n logger.success(\"识别成功: {}\".format(res))\n return res.get('target')[0]\n except:\n logger.error(\"ddddd识别异常\")\n\n\nif __name__ == '__main__':\n for i in range(5):\n gt, challenge = register_slide()\n ajax(gt, challenge)\n challenge, s = get_image(gt, challenge)\n loc = loc_image('底图还原.png', '小滑块.png')\n guiji_array, passtime = _track(loc)\n slide_verify(gt, challenge, guiji_array, loc, passtime, s)\n\n\n\n\n\n\n", "repo_name": "renxiaoyao798/gpss_learn_reverse", "sub_path": "极验三代/test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 6819, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "27", "api": [{"api_name": "requests.session", "line_number": 13, "usage_type": "call"}, {"api_name": "execjs.compile", "line_number": 15, "usage_type": "call"}, {"api_name": "execjs.compile", "line_number": 17, "usage_type": "call"}, {"api_name": "ddddocr.DdddOcr", "line_number": 18, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 25, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 25, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 25, "usage_type": "call"}, {"api_name": "PIL.Image.new", "line_number": 26, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 26, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 35, "usage_type": "call"}, {"api_name": "time.time", "line_number": 42, "usage_type": "call"}, {"api_name": "loguru.logger.success", "line_number": 54, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 54, "usage_type": "name"}, {"api_name": "loguru.logger.error", "line_number": 57, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 57, "usage_type": "name"}, {"api_name": "loguru.logger.error", "line_number": 59, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 59, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 87, "usage_type": "call"}, {"api_name": "loguru.logger.success", "line_number": 99, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 99, "usage_type": "name"}, {"api_name": "loguru.logger.success", "line_number": 100, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 100, "usage_type": "name"}, {"api_name": "loguru.logger.error", "line_number": 103, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 103, "usage_type": "name"}, {"api_name": "loguru.logger.error", "line_number": 105, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 105, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 120, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 124, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 131, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 148, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 149, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 150, "usage_type": "call"}, {"api_name": "loguru.logger.info", "line_number": 153, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 153, "usage_type": "name"}, {"api_name": "loguru.logger.info", "line_number": 154, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 154, "usage_type": "name"}, {"api_name": "hashlib.md5", "line_number": 160, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 161, "usage_type": "call"}, {"api_name": "loguru.logger.success", "line_number": 184, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 184, "usage_type": "name"}, {"api_name": "loguru.logger.error", "line_number": 187, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 187, "usage_type": "name"}]} +{"seq_id": "24766561534", "text": "from django.http import Http404\nfrom rest_framework import status, permissions, generics, filters\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom .models import Project, Pledge, Category\nfrom .serializers import ProjectSerializer, PledgeSerializer, ProjectDetailSerializer, CategoryProjectSerializer, CategorySerializer, ProjectTotalSerializer\nfrom .permissions import IsOwnerOrReadOnly, isSuperUser\n\nclass CategoryList(APIView):\n permission_classes = [isSuperUser,permissions.IsAuthenticatedOrReadOnly]\n\n def get(self, request):\n categories = Category.objects.all()\n serializer = CategorySerializer(categories, many=True)\n return Response(serializer.data)\n \n def post(self, request):\n serializer = CategorySerializer(data=request.data)\n \n if serializer.is_valid():\n print(request.user.is_superuser)\n\n if (request.user.is_superuser):\n\n serializer.save()\n return Response(\n serializer.data,\n status=status.HTTP_201_CREATED\n )\n return Response(\n serializer.errors,\n status=status.HTTP_401_UNAUTHORIZED\n )\n\nclass ProjectList(APIView):\n permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n\n def get(self, request):\n projects = Project.objects.all()\n serializer = ProjectSerializer(projects, many=True)\n return Response(serializer.data)\n\n def post(self, request):\n serializer = ProjectSerializer(data=request.data)\n\n if serializer.is_valid():\n serializer.save(owner=request.user)\n return Response(\n serializer.data,\n status=status.HTTP_201_CREATED\n )\n return Response(\n serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n\nclass FilterView(generics.ListAPIView):\n serializer_class = ProjectSerializer\n queryset = Project.objects.all()\n filter_backends = [filters.OrderingFilter]\n ordering_fields = ['category', 'deadline', 'owner']\n # def get_queryset(self):\n # queryset = Project.objects.all()\n # ...\n # category = self.request.query_params.get('category', None)\n # date_created = self.request.query_params.get('date_created', None)\n # ...\n # if category is not None:\n # queryset = queryset.filter(category=category)\n # if date_created is not None:\n # queryset = queryset.filter(date_created=date_created)\n # return queryset\n\nclass CategoryProject(generics.RetrieveAPIView):\n permission_classes = [isSuperUser]\n queryset = Category.objects.all()\n serializer_class = CategoryProjectSerializer\n lookup_field = 'category'\n\nclass ProjectDetail(APIView):\n permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]\n queryset = Project.objects.all()\n serializer_class = ProjectDetailSerializer\n\n def get_object(self, pk):\n try:\n return Project.objects.get(pk=pk)\n except Project.DoesNotExist:\n raise Http404\n \n def get(self, request, pk):\n project = self.get_object(pk)\n serializer = ProjectDetailSerializer(project)\n return Response(serializer.data)\n\n def put(self, request, pk):\n project = self.get_object(pk)\n self.check_object_permissions(request, project)\n data = request.data\n serializer = ProjectDetailSerializer(\n instance=project,\n data=data,\n partial=True\n )\n if serializer.is_valid():\n serializer.save()\n return Response(\n serializer.data,\n status=status.HTTP_201_CREATED\n )\n return Response(\n serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n\n def delete(self, request, pk):\n project = self.get_object(pk)\n self.check_object_permissions(request, project)\n\n try:\n project.delete()\n return Response(status = status.HTTP_204_NO_CONTENT)\n except Project.DoesNotExist:\n raise Http404\n\nclass PledgeList(APIView):\n permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n\n def get(self, request):\n pledges = Pledge.objects.all()\n serializer = PledgeSerializer(pledges, many=True)\n return Response(serializer.data)\n \n def post(self, request):\n serializer = PledgeSerializer(data=request.data)\n\n if serializer.is_valid():\n serializer.save(supporter=request.user)\n return Response(\n serializer.data,\n status=status.HTTP_201_CREATED\n )\n return Response(\n serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n\nclass PledgeDetail(APIView):\n permission_classes = [permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly]\n\n def get_object(self, pk):\n try:\n return Pledge.objects.get(pk=pk)\n except Pledge.DoesNotExist:\n raise Http404\n \n def get(self, request, pk):\n pledge = self.get_object(pk)\n serializer = PledgeSerializer(pledge)\n return Response(serializer.data)\n\n def put(self, request, pk):\n pledge = self.get_object(pk)\n self.check_object_permissions(request, pledge)\n data = request.data\n serializer = PledgeSerializer(\n instance=pledge,\n data=data,\n partial=True\n )\n if serializer.is_valid():\n serializer.save()\n return Response(\n serializer.data, \n status = status.HTTP_201_CREATED\n )\n return Response (\n serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n \n def delete(self, request, pk):\n pledge = self.get_object(pk)\n self.check_object_permissions(request, pledge)\n\n try:\n pledge.delete()\n return Response(status = status.HTTP_204_NO_CONTENT)\n except Pledge.DoesNotExist:\n raise Http404\n\nclass ProjectTotals(APIView):\n \n # permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n\n def get(self, request):\n projects = Project.objects.all()\n serializer = ProjectTotalSerializer(projects, many=True)\n return Response(serializer.data)", "repo_name": "SamaraLove/drf", "sub_path": "crowdfunding/projects/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 6500, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "rest_framework.views.APIView", "line_number": 9, "usage_type": "name"}, {"api_name": "permissions.isSuperUser", "line_number": 10, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAuthenticatedOrReadOnly", "line_number": 10, "usage_type": "attribute"}, {"api_name": "rest_framework.permissions", "line_number": 10, "usage_type": "name"}, {"api_name": "models.Category.objects.all", "line_number": 13, "usage_type": "call"}, {"api_name": "models.Category.objects", "line_number": 13, "usage_type": "attribute"}, {"api_name": "models.Category", "line_number": 13, "usage_type": "name"}, {"api_name": "serializers.CategorySerializer", "line_number": 14, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 15, "usage_type": "call"}, {"api_name": "serializers.CategorySerializer", "line_number": 18, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 26, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 28, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 28, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 30, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_401_UNAUTHORIZED", "line_number": 32, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 32, "usage_type": "name"}, {"api_name": "rest_framework.views.APIView", "line_number": 35, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAuthenticatedOrReadOnly", "line_number": 36, "usage_type": "attribute"}, {"api_name": "rest_framework.permissions", "line_number": 36, "usage_type": "name"}, {"api_name": "models.Project.objects.all", "line_number": 39, "usage_type": "call"}, {"api_name": "models.Project.objects", "line_number": 39, "usage_type": "attribute"}, {"api_name": "models.Project", "line_number": 39, "usage_type": "name"}, {"api_name": "serializers.ProjectSerializer", "line_number": 40, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 41, "usage_type": "call"}, {"api_name": "serializers.ProjectSerializer", "line_number": 44, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 48, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 50, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 50, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 52, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 54, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 54, "usage_type": "name"}, {"api_name": "rest_framework.generics.ListAPIView", "line_number": 57, "usage_type": "attribute"}, {"api_name": "rest_framework.generics", "line_number": 57, "usage_type": "name"}, {"api_name": "serializers.ProjectSerializer", "line_number": 58, "usage_type": "name"}, {"api_name": "models.Project.objects.all", "line_number": 59, "usage_type": "call"}, {"api_name": "models.Project.objects", "line_number": 59, "usage_type": "attribute"}, {"api_name": "models.Project", "line_number": 59, "usage_type": "name"}, {"api_name": "rest_framework.filters.OrderingFilter", "line_number": 60, "usage_type": "attribute"}, {"api_name": "rest_framework.filters", "line_number": 60, "usage_type": "name"}, {"api_name": "rest_framework.generics.RetrieveAPIView", "line_number": 74, "usage_type": "attribute"}, {"api_name": "rest_framework.generics", "line_number": 74, "usage_type": "name"}, {"api_name": "permissions.isSuperUser", "line_number": 75, "usage_type": "name"}, {"api_name": "models.Category.objects.all", "line_number": 76, "usage_type": "call"}, {"api_name": "models.Category.objects", "line_number": 76, "usage_type": "attribute"}, {"api_name": "models.Category", "line_number": 76, "usage_type": "name"}, {"api_name": "serializers.CategoryProjectSerializer", "line_number": 77, "usage_type": "name"}, {"api_name": "rest_framework.views.APIView", "line_number": 80, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAuthenticatedOrReadOnly", "line_number": 81, "usage_type": "attribute"}, {"api_name": "rest_framework.permissions", "line_number": 81, "usage_type": "name"}, {"api_name": "permissions.IsOwnerOrReadOnly", "line_number": 81, "usage_type": "name"}, {"api_name": "models.Project.objects.all", "line_number": 82, "usage_type": "call"}, {"api_name": "models.Project.objects", "line_number": 82, "usage_type": "attribute"}, {"api_name": "models.Project", "line_number": 82, "usage_type": "name"}, {"api_name": "serializers.ProjectDetailSerializer", "line_number": 83, "usage_type": "name"}, {"api_name": "models.Project.objects.get", "line_number": 87, "usage_type": "call"}, {"api_name": "models.Project.objects", "line_number": 87, "usage_type": "attribute"}, {"api_name": "models.Project", "line_number": 87, "usage_type": "name"}, {"api_name": "models.Project.DoesNotExist", "line_number": 88, "usage_type": "attribute"}, {"api_name": "models.Project", "line_number": 88, "usage_type": "name"}, {"api_name": "django.http.Http404", "line_number": 89, "usage_type": "name"}, {"api_name": "serializers.ProjectDetailSerializer", "line_number": 93, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 94, "usage_type": "call"}, {"api_name": "serializers.ProjectDetailSerializer", "line_number": 100, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 107, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 109, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 109, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 111, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 113, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 113, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 122, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_204_NO_CONTENT", "line_number": 122, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 122, "usage_type": "name"}, {"api_name": "models.Project.DoesNotExist", "line_number": 123, "usage_type": "attribute"}, {"api_name": "models.Project", "line_number": 123, "usage_type": "name"}, {"api_name": "django.http.Http404", "line_number": 124, "usage_type": "name"}, {"api_name": "rest_framework.views.APIView", "line_number": 126, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAuthenticatedOrReadOnly", "line_number": 127, "usage_type": "attribute"}, {"api_name": "rest_framework.permissions", "line_number": 127, "usage_type": "name"}, {"api_name": "models.Pledge.objects.all", "line_number": 130, "usage_type": "call"}, {"api_name": "models.Pledge.objects", "line_number": 130, "usage_type": "attribute"}, {"api_name": "models.Pledge", "line_number": 130, "usage_type": "name"}, {"api_name": "serializers.PledgeSerializer", "line_number": 131, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 132, "usage_type": "call"}, {"api_name": "serializers.PledgeSerializer", "line_number": 135, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 139, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 141, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 141, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 143, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 145, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 145, "usage_type": "name"}, {"api_name": "rest_framework.views.APIView", "line_number": 148, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAuthenticatedOrReadOnly", "line_number": 149, "usage_type": "attribute"}, {"api_name": "rest_framework.permissions", "line_number": 149, "usage_type": "name"}, {"api_name": "permissions.IsOwnerOrReadOnly", "line_number": 149, "usage_type": "name"}, {"api_name": "models.Pledge.objects.get", "line_number": 153, "usage_type": "call"}, {"api_name": "models.Pledge.objects", "line_number": 153, "usage_type": "attribute"}, {"api_name": "models.Pledge", "line_number": 153, "usage_type": "name"}, {"api_name": "models.Pledge.DoesNotExist", "line_number": 154, "usage_type": "attribute"}, {"api_name": "models.Pledge", "line_number": 154, "usage_type": "name"}, {"api_name": "django.http.Http404", "line_number": 155, "usage_type": "name"}, {"api_name": "serializers.PledgeSerializer", "line_number": 159, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 160, "usage_type": "call"}, {"api_name": "serializers.PledgeSerializer", "line_number": 166, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 173, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 175, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 175, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 177, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 179, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 179, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 188, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_204_NO_CONTENT", "line_number": 188, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 188, "usage_type": "name"}, {"api_name": "models.Pledge.DoesNotExist", "line_number": 189, "usage_type": "attribute"}, {"api_name": "models.Pledge", "line_number": 189, "usage_type": "name"}, {"api_name": "django.http.Http404", "line_number": 190, "usage_type": "name"}, {"api_name": "rest_framework.views.APIView", "line_number": 192, "usage_type": "name"}, {"api_name": "models.Project.objects.all", "line_number": 197, "usage_type": "call"}, {"api_name": "models.Project.objects", "line_number": 197, "usage_type": "attribute"}, {"api_name": "models.Project", "line_number": 197, "usage_type": "name"}, {"api_name": "serializers.ProjectTotalSerializer", "line_number": 198, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 199, "usage_type": "call"}]} +{"seq_id": "16047760362", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[26]:\n\n\n# Dependencies and Setup\nfrom bs4 import BeautifulSoup as bs\nfrom splinter import Browser\nimport pandas as pd\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport requests\nimport os\nimport time\n\n\n# In[2]:\n\n\nexecutable_path = {'executable_path': ChromeDriverManager().install()}\nbrowser = Browser('chrome', **executable_path, headless=False)\n\n\n# In[3]:\n\n\n# Visit the NASA Mars News Site\nurl = \"https://mars.nasa.gov/news/\"\nbrowser.visit(url)\n\n\n# In[4]:\n\n\n# Parse Results HTML with BeautifulSoup\n# Find Everything Inside:\n#
    \n#
  • \n\nhtml = browser.html\nnews_soup = bs(html, \"html.parser\")\nslide_element = news_soup.select_one(\"ul.item_list li.slide\")\n\n\n# In[5]:\n\n\nslide_element.find(\"div\", class_=\"content_title\")\n\n\n# In[6]:\n\n\n# Scrape the Latest News Title\n\nnews_title = slide_element.find(\"div\", class_=\"content_title\").get_text()\nprint(news_title)\n\n\n# In[7]:\n\n\n# Scrape the Latest Paragraph Text\nnews_paragraph = slide_element.find(\"div\", class_=\"article_teaser_body\").get_text()\nprint(news_paragraph)\n\n\n# In[8]:\n\n\n# FEATURED IMAGE\n# NASA JPL Site\nexecutable_path = {'executable_path': ChromeDriverManager().install()}\nbrowser = Browser('chrome', **executable_path, headless=False)\n\n\n# In[9]:\n\n\nurl = 'https://www.jpl.nasa.gov/spaceimages/'\nbrowser.visit(url)\n\n\n# In[10]:\n\n\n# Create a Beautiful Soup object\nhtml = browser.html\nsoup = bs(html, 'html.parser')\n\n\n# In[11]:\n\n\n#Get the images\nimages = soup.findAll('img')\nexample = images[0]\nexample\n\n\n# In[12]:\n\n\n# Use Base URL to Create Absolute URL\nimg_url = f\"https://www.jpl.nasa.gov{images}\"\nprint(img_url)\n\n\n# In[13]:\n\n\n#MARS WEATHER\n\nurl = \"https://twitter.com/marswxreport?lang=en\"\nbrowser.visit(url)\n\n\n# In[15]:\n\n\n# HTML Object \nhtml_weather = browser.html\n\n# Parse HTML with Beautiful Soup\nsoup = bs(html_weather, 'html.parser')\n\n# Find elements that contain tweets\nlatest_tweets = soup.find_all('div', class_='js-tweet-text-container')\n\n# Retrieve all elements that contain news title in the specified range\n# Look for entries that display weather related words to exclude non weather related tweets \nfor tweet in latest_tweets: \n weather_tweet = tweet.find('p').text\n if 'Sol' and 'pressure' in weather_tweet:\n print(weather_tweet)\n break\n else: \n pass\n\n\n# In[19]:\n\n\n#MARS FACTS\n\n# Visit Mars facts url \nfacts_url = 'http://space-facts.com/mars/'\n\n# Use Panda's `read_html` to parse the url\nmars_facts = pd.read_html(facts_url)\n\n# Find the mars facts DataFrame in the list of DataFrames as assign it to `mars_df`\nmars_df = mars_facts[0]\n\n# Assign the columns `['Description', 'Value']`\nmars_df.columns = ['Description','Value']\n\n# Set the index to the `Description` column without row indexing\nmars_df.set_index('Description', inplace=True)\n\n# Save html code to folder Assets\nmars_df.to_html()\n\ndata = mars_df.to_dict(orient='records') \n\n# Display mars_df\nmars_df\n\n\n# In[30]:\n\n\n#MARS HEMISPHERES\n\n# Go to hemisphere website through splinter module \nurl = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\nbrowser.visit(url)\n\n\n# In[31]:\n\n\nhemisphere_image_urls = []\n\n# Get a List of All the Hemispheres\nlinks = browser.find_by_css(\"a.product-item h3\")\nfor item in range(len(links)):\n hemisphere = {}\n \n # Find Element on Each Loop to Avoid a Stale Element Exception\n browser.find_by_css(\"a.product-item h3\")[item].click()\n \n # Find Sample Image Anchor Tag & Extract \n sample_element = browser.find_link_by_text(\"Sample\").first\n hemisphere[\"img_url\"] = sample_element[\"href\"]\n \n # Get Hemisphere Title\n hemisphere[\"title\"] = browser.find_by_css(\"h2.title\").text\n \n # Append Hemisphere Object to List\n hemisphere_image_urls.append(hemisphere)\n \n # Navigate Backwards\n browser.back()\n\n\n# In[32]:\n\n\nhemisphere_image_urls\n\n\n# In[ ]:\n\n\n\n\n", "repo_name": "gmichallet/web-scraping-challenge", "sub_path": "Scrape_mars.py", "file_name": "Scrape_mars.py", "file_ext": "py", "file_size_in_byte": 3919, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "webdriver_manager.chrome.ChromeDriverManager", "line_number": 20, "usage_type": "call"}, {"api_name": "splinter.Browser", "line_number": 21, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 41, "usage_type": "call"}, {"api_name": "webdriver_manager.chrome.ChromeDriverManager", "line_number": 73, "usage_type": "call"}, {"api_name": "splinter.Browser", "line_number": 74, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 89, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 125, "usage_type": "call"}, {"api_name": "pandas.read_html", "line_number": 150, "usage_type": "call"}]} +{"seq_id": "42239669035", "text": "from django.urls import path\nfrom .views import PostFeedbackList,PostList, PostCreate, PostDetailView,PostUpdate,PostFeedback,PostDelete\nfrom . import views\n\nurlpatterns = [\n path('', PostList.as_view(), name='post_list'),\n path('post/new/', PostCreate.as_view(), name='post_new'),\n path('post//', PostDetailView.as_view(), name='post_detail'),\n path('post//edit/', PostUpdate.as_view(), name='post_edit'),\n path('post/feedback/', PostFeedback.as_view(), name='feedback'),\n path('post/feedback/list/', PostFeedbackList.as_view(), name='feedbackList'),\n path('post//delete/', PostDelete.as_view(), name='post_delete'),\n\n]\n", "repo_name": "InesM95/djangogirlForms", "sub_path": "blog/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 666, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "views.PostList.as_view", "line_number": 6, "usage_type": "call"}, {"api_name": "views.PostList", "line_number": 6, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "views.PostCreate.as_view", "line_number": 7, "usage_type": "call"}, {"api_name": "views.PostCreate", "line_number": 7, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "views.PostDetailView.as_view", "line_number": 8, "usage_type": "call"}, {"api_name": "views.PostDetailView", "line_number": 8, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "views.PostUpdate.as_view", "line_number": 9, "usage_type": "call"}, {"api_name": "views.PostUpdate", "line_number": 9, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "views.PostFeedback.as_view", "line_number": 10, "usage_type": "call"}, {"api_name": "views.PostFeedback", "line_number": 10, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "views.PostFeedbackList.as_view", "line_number": 11, "usage_type": "call"}, {"api_name": "views.PostFeedbackList", "line_number": 11, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "views.PostDelete.as_view", "line_number": 12, "usage_type": "call"}, {"api_name": "views.PostDelete", "line_number": 12, "usage_type": "name"}]} +{"seq_id": "12031757049", "text": "import pyaudio\nimport numpy as np\nfrom presto.channels.channel import Channel\nimport struct\n\npa = pyaudio.PyAudio()\n\nDEFAULT_INFO = pa.get_default_host_api_info()\n\n\nclass MicrophoneAudio(Channel):\n def __init__(\n self,\n frames_per_buffer=1024,\n input_device_index=DEFAULT_INFO[\"defaultInputDevice\"],\n rate=48000,\n data_queue=None,\n ):\n super().__init__()\n self._rate = rate\n self._frames_per_buffer = frames_per_buffer\n self._data_queue = data_queue\n self._input_device_index = input_device_index\n self._stream = None\n\n def run(self):\n # read input stream\n self._stream = pa.open(\n rate=self._rate,\n channels=1,\n format=pyaudio.paInt16,\n input=True,\n input_device_index=self._input_device_index,\n frames_per_buffer=self._frames_per_buffer,\n )\n\n while True:\n data = self._stream.read(self._rate)\n samps = np.fromstring(data, dtype=np.int16)\n if self._data_queue is not None:\n self._data_queue.put(samps)\n\n def shutdown(self):\n if self._stream is not None:\n self._stream.stop_stream()\n self._stream.close()\n\n\nif __name__ == \"__main__\":\n listener = MicrophoneAudio()\n listener.start()\n", "repo_name": "jacquelinegarrahan/presto", "sub_path": "presto/channels/microphone.py", "file_name": "microphone.py", "file_ext": "py", "file_size_in_byte": 1348, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pyaudio.PyAudio", "line_number": 6, "usage_type": "call"}, {"api_name": "presto.channels.channel.Channel", "line_number": 11, "usage_type": "name"}, {"api_name": "pyaudio.paInt16", "line_number": 31, "usage_type": "attribute"}, {"api_name": "numpy.fromstring", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.int16", "line_number": 39, "usage_type": "attribute"}]} +{"seq_id": "13587714913", "text": "import dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\n\nfrom app import app\nfrom apps import BPD, CLR , NT\n\n\nindex_page = html.Div([\n dcc.Link('Annotate BPD', href='/apps/BPD'),\n html.Br(),\n dcc.Link('Annotate CLR', href='/apps/CLR'),\n html.Br(),\n dcc.Link('Annotate NT', href='/apps/NT'),\n])\n\napp.layout = html.Div([\n dcc.Location(id='url', refresh=False),\n html.Div(id='page-content')\n])\n\n\n@app.callback(Output('page-content', 'children'),\n Input('url', 'pathname'))\ndef display_page(pathname):\n if pathname == '/apps/BPD':\n return BPD.layout\n elif pathname == '/apps/CLR':\n return CLR.layout\n elif pathname == '/apps/NT':\n return NT.layout\n else:\n return index_page\n\nif __name__ == '__main__':\n app.run_server(debug=True)", "repo_name": "dmalagarriga/annotate_ecography_images", "sub_path": "index.py", "file_name": "index.py", "file_ext": "py", "file_size_in_byte": 861, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "dash_html_components.Div", "line_number": 9, "usage_type": "call"}, {"api_name": "dash_core_components.Link", "line_number": 10, "usage_type": "call"}, {"api_name": "dash_html_components.Br", "line_number": 11, "usage_type": "call"}, {"api_name": "dash_core_components.Link", "line_number": 12, "usage_type": "call"}, {"api_name": "dash_html_components.Br", "line_number": 13, "usage_type": "call"}, {"api_name": "dash_core_components.Link", "line_number": 14, "usage_type": "call"}, {"api_name": "app.app.layout", "line_number": 17, "usage_type": "attribute"}, {"api_name": "app.app", "line_number": 17, "usage_type": "name"}, {"api_name": "dash_html_components.Div", "line_number": 17, "usage_type": "call"}, {"api_name": "dash_core_components.Location", "line_number": 18, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 19, "usage_type": "call"}, {"api_name": "apps.BPD.layout", "line_number": 27, "usage_type": "attribute"}, {"api_name": "apps.BPD", "line_number": 27, "usage_type": "name"}, {"api_name": "apps.CLR.layout", "line_number": 29, "usage_type": "attribute"}, {"api_name": "apps.CLR", "line_number": 29, "usage_type": "name"}, {"api_name": "apps.NT.layout", "line_number": 31, "usage_type": "attribute"}, {"api_name": "apps.NT", "line_number": 31, "usage_type": "name"}, {"api_name": "app.app.callback", "line_number": 23, "usage_type": "call"}, {"api_name": "app.app", "line_number": 23, "usage_type": "name"}, {"api_name": "dash.dependencies.Output", "line_number": 23, "usage_type": "call"}, {"api_name": "dash.dependencies.Input", "line_number": 24, "usage_type": "call"}, {"api_name": "app.app.run_server", "line_number": 36, "usage_type": "call"}, {"api_name": "app.app", "line_number": 36, "usage_type": "name"}]} +{"seq_id": "35117307709", "text": "#!/usr/bin/python3.5\n# -*- coding: utf-8 -*-\n\nfrom multiprocessing import Event,Queue,Pool,Process,Value\nimport io,os,sys,time,random,threading,queue,pgbar\n\ndef eq_put_y(a,b,c):\n\tif a == 0:\n\t\tyield 0\n\tif c == 1:\n\t\tfor i in range(c):\n\t\t\tif a >= b:\n\t\t\t\ta-=b\n\t\t\t\tyield a\n\t\t\telse:\n\t\t\t\tyield 0\n\telif c > 1:\n\t\tfor i in range(c):\n\t\t\tif a >= b*c:\n\t\t\t\ta-=b\n\t\t\t\tyield a\n\t\t\telif a*c >= b/c and a < b*c:\n\t\t\t\tif a > c:\n\t\t\t\t\ta=a-(int(a/c)+a%c)\n\t\t\t\t\tyield a\n\t\t\t\telif a < c:\n\t\t\t\t\tyield 0\n\t\t\telif a*c < b/c:\n\t\t\t\t\tyield 0\n\ndef wq_put_y(a,b):\n\tfor i in range(a,b):\n\t\tyield i+1\n\ndef efunc():\n\tglobal task,wqs,procs,taskend\n\tprint('[efunc]event tid',threading.current_thread().name,'is starting...')\n\twhile True:\n\t\tif task != 0:\n\t\t\twhile not eq.full():\n\t\t\t\tif task == 0:\n\t\t\t\t\tbreak\n\t\t\t\teg=eq_put_y(task,wqs,procs)\n\t\t\t\teql=[]\n\t\t\t\t#print('[eq_put]task =',task)\n\t\t\t\teql.append(task)\n\t\t\t\ttask=next(eg)\n\t\t\t\teql.append(task)\n\t\t\t\t#print('[eq_put]eql :',eql)\n\t\t\t\teq.put(eql)\n\t\t\t\tet.set()\n\t\telif task == 0:\n\t\t\tbreak\n\t\tee.clear()\n\t\tee.wait()\n\t\tet.set()\n\t#print('[efunc]task =',task,'et set',et.is_set(),'| ee set',ee.is_set())\n\tn=0\n\twhile True:\t\n\t\tif not eq.full():\n\t\t\tn+=1\n\t\t\tif n <= procs:\n\t\t\t\teq.put('done')\n\t\t\t\tprint('[efunc]n =',n,'eq empty',eq.empty(),'ee set:',ee.is_set())\n\t\t\telif n > procs:\n\t\t\t\tee.clear()\n\t\t\t\tet.set()\n\t\t\t\ttaskend=True\n\t\t\t\tprint('[efunc]',threading.current_thread().name,'<1> et set:',et.is_set(),'| ee set:',ee.is_set())\n\t\t\t\treturn\n\t\tee.clear()\n\t\tee.wait()\n \ndef eq_get():\n\tglobal wqs,wg,procs,weqget,task\n\twqe=[]\n\twqa=None\n\twqb=None\n\t#print(threading.current_thread().name,'weqget =',weqget,'ee set',ee.is_set())\n\tif weqget:\n\t\tee.set()\n\t\twhile eq.empty():\n\t\t\tprint('[eq_get]',threading.current_thread().name,'wcq empty :',wcq.empty(),'weqget is',weqget,'| we set',we.is_set(),'| eq qsize:',eq.qsize())\n\t\t\tif not weqget or not ee.is_set():\n\t\t\t\tbreak\n\telse:\n\t\twfunc()\n\t\treturn\n\n\tif not eq.empty() and weqget:\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\twqe=eq.get_nowait()\n\t\t\texcept:\n\t\t\t\tprint('[eq_get]',threading.current_thread().name,'wqe get failed|eq empty :',eq.empty(),'| wcq empty :',wcq.empty(),'|weqget:',weqget)\n\t\t\t\tif not weqget:\n\t\t\t\t\twfunc()\n\t\t\t\t\treturn\n\t\t\t\telse:\n\t\t\t\t\tee.set()\n\t\t\t\t\tcontinue\n\t\t\tbreak\n\t\tprint('<%.4f s>' % (time.time()-st),'| [eq_get]',threading.current_thread().name,'wqe=',wqe,'| eq empty :',eq.empty(),'| we set',we.is_set(),'| ee set:',ee.is_set(),'| wcq empty :',wcq.empty(),)\n\t\tif wqe != 'done' and wqe != []:\n\t\t\twqa=wqe.pop()\n\t\t\twqb=wqe.pop()\n\t\t\twg=wq_put_y(wqa,wqb)\n\t\t\tee.set()\n\t\t\twq_put()\n\t\telif wqe == 'done':\n\t\t\tweqget=False\n\t\t\tee.set()\n\t#print('[eq_get]',threading.current_thread().name,'return to wfunc','we set :',we.is_set(),'ee set :',ee.is_set(),'| eq empty :',eq.empty(),'wcq empty :',wcq.empty(),'weqget :',weqget)\n\twe.set()\n\twfunc()\n\ndef wq_put():\n\tglobal wg,weqget\n\tx=None\n\tif not we.is_set() and not wcq.empty():\n\t\twe.set()\n\tif weqget:\n\t\ttry:\n\t\t\tx=next(wg)\n\t\texcept:\n\t\t\tif not wcq.empty():\n\t\t\t\twcq.get_nowait()\n\t\t\t\twe.clear()\n\t\t\tprint('[wq_put]',threading.current_thread().name,'return to wfunc','wcq empty :',wcq.empty(),'| eq empty :',eq.empty(),'weqget =',weqget,'we set',we.is_set())\n\t\t\twfunc()\n\t\t\treturn\n\telse:\n\t\tprint('[wq_put]',threading.current_thread().name,'return to wfunc','wcq empty :',wcq.empty(),'| eq empty :',eq.empty(),'weqget =',weqget,'we set',we.is_set())\n\t\twfunc()\n\t\treturn\n\t#print('[wq_put]',threading.current_thread().name,'x =',x,'we set',we.is_set())\n\tif not wq.full() and x != None:\n\t\ttry:\n\t\t\twq.put_nowait(x)\n\t\texcept:\n\t\t\tpass\n\t#print('[wq_put]check 2 :',threading.current_thread().name)\n\twfunc()\n\ndef wfunc():\n\tglobal ptime,pcount,resbf,threadover,weqget,errlist,th_fin_c\n\tx=None\n\tn=0\n\twhile not wq.empty():\n\t\ttry:\n\t\t\tx=wq.get_nowait()\n\t\texcept:\n\t\t\tbreak\n\t\ttext=''\n\t\t#print('[wfunc]',threading.current_thread().name,'x =',x)\n\t\tr=random.randint(2,6)\n\t\tfor i in range(r):\n\t\t\ttext+='a'\n\t\t\ttime.sleep(1)\n\t\tstd=str(x)+'\\t'+text+'\\n'\n\t\ttry:\n\t\t\tresbf.put_nowait(std)\n\t\texcept:\n\t\t\terrlist.append(std)\n\t\t#print('[wfunc]',threading.current_thread().name,'std :',std)\n\t\twq.task_done()\n\t\tptime+=r\n\t\tpcount+=1\n\t\tn+=1\n\n\tif wcq.empty():\n\t\ttry:\n\t\t\twcq.put_nowait(threading.current_thread().name)\n\t\texcept:\n\t\t\twfunc()\n\t\t\treturn\n\t\tprint('[wfunc]return to eq_get()',threading.current_thread().name,'wcq empty',wcq.empty(),'we set',we.is_set(),'weqget =',weqget)\n\t\twe.clear()\n\t\teq_get()\n\t\treturn\n\telif not weqget and not wcq.empty():\n\t\t#print('[wfunc]check 3 alive thresds :',threading.current_thread().name,threading.current_thread().is_alive())\n\t\tif ee.is_set():\n\t\t\tee.clear()\n\t\treturn\n\twe.wait()\n\t#print('[wfunc]check 1 :',threading.current_thread().name)\n\twq_put()\n\ndef resbf_flush(ps):\n\tglobal resbf,reslog,errline,task,taskend\n\tprint('[resbf_flush]res_save_tid',threading.current_thread().name,'is starting...')\n\twhile True:\n\t\tresbfqs=resbf.qsize()\n\t\t#print('[resbf_flus]task!=0,resbf qsize =',resbfqs)\n\t\tif resbfqs >= ps:\n\t\t\tthqs=int((resbfqs-resbfqs%ps)/ps)\n\t\telse:\n\t\t\tthqs=resbfqs\n\t\t#print('[resbf_flus]',threading.current_thread().name,'task!=0,thqs =',thqs)\n\t\tfor i in range(thqs):\n\t\t\ttry:\n\t\t\t\tv=resbf.get_nowait()\n\t\t\texcept:\n\t\t\t\tcontinue\n\t\t\t#print('[resbf_flus]v =',v)\n\t\t\ttry:\n\t\t\t\treslog.write(v)\n\t\t\texcept:\n\t\t\t\terrline+=1\n\t\t\t\tprint('reslog write erroe at line:',errline,v)\n\t\treslog.flush()\n\t\t#print('[resbf_flush]et set:',et.is_set(),'taskend =',taskend)\n\t\tif taskend == False:\n\t\t\tet.clear()\n\t\t\tet.wait()\n\t\telif taskend == True:\n\t\t\tet.wait()\n\t\t\t#print('[resbf_flush]',threading.current_thread().name,'<2> et set:',et.is_set(),'| end set:',end.is_set())\n\t\t\tend.wait()\n\t\t\t#print('[resbf_flush]',threading.current_thread().name,'<3> et set:',et.is_set(),'| end set:',end.is_set())\n\t\t\t#print('[resbf_flush]',threading.current_thread().name,'last resbf size ;',resbf.qsize())\n\t\t\twhile not resbf.empty():\n\t\t\t\ttry:\n\t\t\t\t\tv=resbf.get_nowait()\n\t\t\t\texcept:\n\t\t\t\t\tcontinue\n\t\t\t\t#print('[resbf_flush]',threading.current_thread().name,'check point.....','et set:',et.is_set(),'| resbf empty :',resbf.empty(),'v=',v)\n\t\t\t\ttry:\n\t\t\t\t\treslog.write(v)\n\t\t\t\texcept:\n\t\t\t\t\terrline+=1\n\t\t\t\t\tprint('reslog write erroe at line:',errline,v)\n\t\t\treslog.flush()\n\t\t\tbreak\n\ndef wfunc_bar():\n\tglobal bartask,st\n\twhile True:\n\t\tcount=bar.value\n\t\tif count < bartask:\n\t\t\tpgbar.bar(bartask,count,50,st)\n\t\telif count >= bartask:\n\t\t\tpgbar.bar(bartask,count,50,st)\n\t\t\tee.set()\n\t\t\tbreak\n\t\t#print('count =',count)\n\t\ttime.sleep(0.5)\n\ndef c_e_th():\n\tglobal wths,procs\n\tthp=[]\n\tpevent=threading.Thread(target=efunc,name='pevent_tid='+str(os.getpid())+'/0')\n\tpevent.start()\n\tx=int(wths/1000)\n\tif wths/1000 <= 1:\n\t\tths=procs\n\telse:\n\t\tths=procs*x\n\tfor i in range(ths):\n\t\trbf=threading.Thread(target=resbf_flush,args=(ths,),name='res_save_tid='+str(os.getpid())+'/'+str(i+1))\n\t\tthp.append(rbf)\n\tfor a in thp:\n\t\ta.start()\n\tpevent.join()\n\tprint('\\n[c_e_th]there is no more task,efunc done,use time:%.2f' % (time.time()-st)+'s')\n\tprint('='*60)\n\tprint('[c_e_th]waiting for resbf thread over...')\n\tfor b in thp:\n\t\tb.join()\n\tprint('[c_e_th]errline =',errline)\n\tprint('[c_e_th]resbf is over......')\n\n\t#wbar=threading.Thread(target=wfunc_bar,name='wbar_tid='+str(os.getpid()))\n\t#wbar.start()\n\t#wbar.join()\n\ndef c_w_th(ths):\n\tthp=[]\n\tfor i in range(ths):\n\t\tt=threading.Thread(target=wfunc,name='tid'+str(os.getpid())+r'/'+str(i))\n\t\tthp.append(t)\n\tfor a in thp:\n\t\ta.start()\n\tfor b in thp:\n\t\tb.join()\n\tprint('\\n[c_w_th]',os.getpid(),'wq unfinished tasks :',wq.unfinished_tasks)\n\tprint('[c_w_th]ee set',ee.is_set(),'| resbf qsize:',resbf.qsize())\n\t\ndef pefunc():\n\tprint(os.getpid(),'pefunc is starting......')\n\tc_e_th()\n\tprint('[pefunc]pefunc done......')\n\ndef pwfunc():\n\tglobal allcount,alltime\n\tprint('[pwfunc]pid =',os.getpid(),'is running...')\n\tc_w_th(wths)\n\tallcount.value+=pcount\n\talltime.value+=ptime\n\tprint('\\n[pwfunc]pid='+str(os.getpid())+' real time: '+str(ptime)+'s\\tcounts:'+str(pcount))\n\tprint('[pwfunc]'+str(os.getpid())+' wfunc is done use time:%.2f' % (time.time()-st)+'s')\n\tprint('[pwfunc]wq empty :',wq.empty(),'|wq size :',wq.qsize(),'| errlist count :',len(errlist))\n\treturn os.getpid()\n\t\ndef delcache():\n\tcachedir='__pycache__'\n\ttry:\n\t\tos.chdir(cachedir)\n\texcept:\n\t\treturn\n\tflist=os.listdir()\n\twhile True:\n\t\ttry:\n\t\t\tos.remove(flist.pop())\n\t\texcept:\n\t\t\tos.rmdir('../'+cachedir)\n\t\t\tos.chdir('../')\n\t\t\treturn\ndef cb_test(test):\n\tglobal p_fin_c,procs\n\tp_fin_c.append(test)\n\tprint('[cb_test]',p_fin_c)\n\tif len(p_fin_c) == procs:\n\t\tpw.terminate()\n\nif __name__=='__main__':\n\tst=time.time()\n#public var set\n\tprocs=int(input('set procs:'))-1\n\tif procs <= 1:\n\t\tprocs=1\n\twths=int(input('set thread count:'))\n\twqs=wths\n\t#procs=os.cpu_count()\n\teq=Queue(procs)\n\ttask=int(input('set task count:'))\n\tbartask=task\n\talltime=Value('i',0)\n\tallcount=Value('i',0)\n\tbar=Value('i',1)\n\n#log file set\n\tdelcache()\n\tfname='./result.log'\n\ttry:\n\t\tos.remove(fname)\n\texcept:\n\t\tpass\n\tos.path.exists(fname)\n\treslog=open(fname,'a')\n\tresbf=Queue()\n\terrline=0\n\n#set var to event procs\n\tee=Event()\n\tend=Event()\n\tet=threading.Event()\n\ttaskend=False\n\tpe=Process(target=pefunc)\n\tpe.start()\n\tdel et,taskend,bartask\n\n#set var to work procs\n\twq=queue.Queue(wqs)\n\twcq=queue.Queue(1)\n\twe=threading.Event()\n\tweqget=True\n\twg=None\n\tptime=0\n\tpcount=0\n\terrlist=[]\n\tp_fin_c=[]\n\tpw=Pool(procs)\n\tfor i in range(procs):\n\t\tpw.apply_async(pwfunc,callback=cb_test)\n\tpw.close()\n\tpw.join()\n\tprint('pw is over......')\n\tend.set()\n\tprint('mainend end set :',end.is_set())\n\tpe.join()\n\tprint('unfinished resbf size ;',resbf.qsize())\n\treslog.close()\n\n\tprint('\\nreal time: '+str(alltime.value)+'s\\tcounts: '+str(allcount.value))\n\tprint('use time: %.2f' % (time.time()-st)+'s')", "repo_name": "seantbs/python3.5", "sub_path": "py-test/event_qw_no_fin.py", "file_name": "event_qw_no_fin.py", "file_ext": "py", "file_size_in_byte": 9515, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "threading.current_thread", "line_number": 37, "usage_type": "call"}, {"api_name": "threading.current_thread", "line_number": 69, "usage_type": "call"}, {"api_name": "threading.current_thread", "line_number": 83, "usage_type": "call"}, {"api_name": "threading.current_thread", "line_number": 95, "usage_type": "call"}, {"api_name": "time.time", "line_number": 103, "usage_type": "call"}, {"api_name": "threading.current_thread", "line_number": 103, "usage_type": "call"}, {"api_name": "threading.current_thread", "line_number": 129, "usage_type": "call"}, {"api_name": "threading.current_thread", "line_number": 133, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 156, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 159, "usage_type": "call"}, {"api_name": "threading.current_thread", "line_number": 173, "usage_type": "call"}, {"api_name": "threading.current_thread", "line_number": 177, "usage_type": "call"}, {"api_name": "threading.current_thread", "line_number": 192, "usage_type": "call"}, {"api_name": "pgbar.bar", "line_number": 242, "usage_type": "call"}, {"api_name": "pgbar.bar", "line_number": 244, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 248, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 253, "usage_type": "call"}, {"api_name": "os.getpid", "line_number": 253, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 261, "usage_type": "call"}, {"api_name": "os.getpid", "line_number": 261, "usage_type": "call"}, {"api_name": "time.time", "line_number": 266, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 281, "usage_type": "call"}, {"api_name": "os.getpid", "line_number": 281, "usage_type": "call"}, {"api_name": "os.getpid", "line_number": 287, "usage_type": "call"}, {"api_name": "os.getpid", "line_number": 291, "usage_type": "call"}, {"api_name": "os.getpid", "line_number": 297, "usage_type": "call"}, {"api_name": "os.getpid", "line_number": 301, "usage_type": "call"}, {"api_name": "os.getpid", "line_number": 302, "usage_type": "call"}, {"api_name": "time.time", "line_number": 302, "usage_type": "call"}, {"api_name": "os.getpid", "line_number": 304, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 309, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 312, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 315, "usage_type": "call"}, {"api_name": "os.rmdir", "line_number": 317, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 318, "usage_type": "call"}, {"api_name": "time.time", "line_number": 328, "usage_type": "call"}, {"api_name": "multiprocessing.Queue", "line_number": 336, "usage_type": "call"}, {"api_name": "multiprocessing.Value", "line_number": 339, "usage_type": "call"}, {"api_name": "multiprocessing.Value", "line_number": 340, "usage_type": "call"}, {"api_name": "multiprocessing.Value", "line_number": 341, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 347, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 350, "usage_type": "call"}, {"api_name": "os.path", "line_number": 350, "usage_type": "attribute"}, {"api_name": "multiprocessing.Queue", "line_number": 352, "usage_type": "call"}, {"api_name": "multiprocessing.Event", "line_number": 356, "usage_type": "call"}, {"api_name": "multiprocessing.Event", "line_number": 357, "usage_type": "call"}, {"api_name": "threading.Event", "line_number": 358, "usage_type": "call"}, {"api_name": "multiprocessing.Process", "line_number": 360, "usage_type": "call"}, {"api_name": "queue.Queue", "line_number": 365, "usage_type": "call"}, {"api_name": "queue.Queue", "line_number": 366, "usage_type": "call"}, {"api_name": "threading.Event", "line_number": 367, "usage_type": "call"}, {"api_name": "multiprocessing.Pool", "line_number": 374, "usage_type": "call"}, {"api_name": "time.time", "line_number": 387, "usage_type": "call"}]} +{"seq_id": "39395553368", "text": "from __future__ import unicode_literals\nimport os\n\nfrom flask import Flask\nfrom flask import request\nfrom flask import jsonify\n\nfrom pbkdf2 import crypt\n\nfrom services.downloader import youtube_download\n\napp = Flask(__name__)\n\nHASHED_KEY = os.environ.get('YDL_HASHED_KEY', None)\nUSE_AUTH = os.environ.get('YDL_USE_AUTH', False)\nDL_PATH = os.environ.get('YDL_DL_PATH', '.')\n\n\n@app.route(\"/\", methods=[\"GET\"])\ndef handle_index():\n return handle_help()\n\n\n@app.route(\"/ydl\", methods=[\"GET\"])\ndef handle_download():\n\n youtubeId = request.args.get('id')\n onlyAudio = request.args.get('onlyAudio')\n key = request.args.get('key')\n\n if not youtubeId:\n return handle_help(400)\n\n # Authentication\n if USE_AUTH and not HASHED_KEY == crypt(key, HASHED_KEY):\n return response(500, 'incorrect key')\n\n ydl_opts = {\n 'format': 'bestaudio' if onlyAudio else 'best',\n 'outtmpl': DL_PATH+'/%(title)s.%(ext)s',\n 'nocheckcertificate': True\n }\n\n youtube_download(youtubeId, ydl_opts)\n return response(200, 'download started...')\n\n\n@app.route(\"/help\", methods=[\"GET\"])\ndef handle_help(code=200):\n return response(code, 'how to use this service: /ydl?id=&key=onlyAudio=false')\n\n\ndef response(code, message):\n response = jsonify({'message': message})\n response.status_code = code\n return response\n\nif __name__ == \"__main__\":\n app.run()", "repo_name": "mklan/remote-youtube-dl", "sub_path": "src/flask_app.py", "file_name": "flask_app.py", "file_ext": "py", "file_size_in_byte": 1422, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 12, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 14, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 15, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 16, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 16, "usage_type": "attribute"}, {"api_name": "flask.request.args.get", "line_number": 27, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 27, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 27, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 28, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 28, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 28, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 29, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 29, "usage_type": "name"}, {"api_name": "pbkdf2.crypt", "line_number": 35, "usage_type": "call"}, {"api_name": "services.downloader.youtube_download", "line_number": 44, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 54, "usage_type": "call"}]} +{"seq_id": "981578836", "text": "import numpy as np\nfrom PIL import Image, ImageFilter\n\nim = Image.open('./LLL.png').convert('L')\nimg = np.asarray(im)\nprint(img.dtype) # データ型\n\npil_img = Image.fromarray(img)\npil_img.save('./out.png')\n\nprint(img.size)", "repo_name": "Taiki-azrs/RaspiGPGPU_guide", "sub_path": "chap05/image_io_cpu.py", "file_name": "image_io_cpu.py", "file_ext": "py", "file_size_in_byte": 225, "program_lang": "python", "lang": "ar", "doc_type": "code", "stars": 22, "dataset": "github-code", "pt": "25", "api": [{"api_name": "PIL.Image.open", "line_number": 4, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 4, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 5, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 8, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 8, "usage_type": "name"}]} +{"seq_id": "21600105875", "text": "import time\nimport click\nimport contextlib\nfrom typing import Callable, Iterable\n\ndef wait(iterations: int, interval: float, error: Exception=TimeoutError(), predicate: Callable[[], bool]=lambda: False) -> Iterable[int]:\n for iteration in range(iterations):\n time.sleep(interval)\n if predicate():\n break\n yield\n else:\n raise error\n\ndef block_wait(iterations: int, interval: float, error: Exception=TimeoutError(), predicate: Callable[[], bool]=lambda: False) -> None:\n for x in wait(iterations, interval, error, predicate):\n pass\n\ndef negate(f: Callable[[], bool]) -> bool:\n return lambda: not(f())\n\ndef first(iterable):\n return next(iter(iterable))\n\nclass Timer:\n def __init__(self):\n self.start = None\n self.end = None\n def __enter__(self):\n self.start = time.time()\n return self\n def __exit__(self, *exc):\n self.end = time.time()\n @property\n def running(self):\n return self.start and not self.end\n @property\n def elapsed(self):\n if not self.start:\n raise ValueError('not started')\n end = self.end or time.time()\n return end-self.start\n\nclass EchoTimer(Timer):\n def __init__(self, message):\n super().__init__()\n self.message = message\n def __enter__(self):\n super().__enter__()\n click.echo(self.message+' ', nl=False)\n def __exit__(self, *exc):\n super().__exit__(*exc)\n if not any(exc):\n click.echo('(%.2fs)' % self.elapsed)\n\ndef null(obj, component):\n \"A Query `missing` function that always returns None\"\n return None\n\nclass Literal:\n \"Makes restructure_dict return a specific value (without dict lookup)\"\n def __init__(self, value):\n self.value = value\n\nclass Query:\n def __init__(self, path, missing=None, cast=None, reraise=KeyError):\n self.path = path\n self.missing = missing\n self.cast = cast\n self.reraise = reraise\n def __call__(self, obj):\n if isinstance(self.path, Literal):\n return self.path.value\n for component in self.path.split('/'):\n if component.startswith('[') and component.endswith(']'):\n component = int(component[1:-1])\n try:\n obj = obj[component]\n except KeyError as error:\n if self.missing:\n return self.missing(obj, component)\n if self.reraise is KeyError:\n raise\n else:\n raise self.reraise from error\n raise\n return obj if self.cast is None else self.cast(obj)\n\ndef restructure_dict(src, queries):\n dst = {}\n for dst_path, query in queries.items():\n dst_obj = dst\n components = dst_path.split('/')\n prefix, key = components[:-1], components[-1]\n for component in prefix:\n dst_obj = dst_obj.setdefault(component, {})\n dst_obj[key] = query(src)\n return dst\n\ndef shell(ns={}):\n try:\n import IPython\n IPython.start_ipython(user_ns=ns, display_banner=False, argv=[])\n except ImportError:\n import code\n code.interact(local=ns)\n", "repo_name": "yaniv-aknin/fafalytics", "sub_path": "fafalytics/pyutils.py", "file_name": "pyutils.py", "file_ext": "py", "file_size_in_byte": 3222, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.Callable", "line_number": 6, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 8, "usage_type": "call"}, {"api_name": "typing.Iterable", "line_number": 6, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 15, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 19, "usage_type": "name"}, {"api_name": "time.time", "line_number": 30, "usage_type": "call"}, {"api_name": "time.time", "line_number": 33, "usage_type": "call"}, {"api_name": "time.time", "line_number": 41, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 50, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 54, "usage_type": "call"}, {"api_name": "IPython.start_ipython", "line_number": 103, "usage_type": "call"}, {"api_name": "code.interact", "line_number": 106, "usage_type": "call"}]} +{"seq_id": "7345021316", "text": "from flask import Flask, request, render_template, redirect, flash, session\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom surveys import satisfaction_survey as survey\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = '0123456'\napp.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False\napp.debug = True\n\ndebug = DebugToolbarExtension(app)\n\n@app.route('/')\ndef root():\n \"\"\"Create start page\"\"\"\n\n title = survey.title\n instructions = survey.instructions\n\n return render_template('start.html', title=title, instructions=instructions)\n\n\n@app.route('/start', methods=['POST'])\ndef start():\n \"\"\"Start the survey and empty responses in session storage.\"\"\"\n \n session['responses'] = []\n\n return redirect('/questions/0')\n\n\n@app.route('/questions/')\ndef questions(q_id):\n \"\"\"Create questions pages\"\"\"\n \n responses = session['responses']\n\n if len(responses) == 0 and q_id != 0:\n flash('Click start to begin survey!')\n return redirect('/')\n\n if len(responses) == len(survey.questions):\n return redirect('/thanks')\n\n if q_id != len(responses):\n flash('Please answer questions in order!')\n return redirect(f'/questions/{len(responses)}')\n\n question = survey.questions[q_id]\n choices = question.choices\n\n return render_template('questions.html', question=question.question, choices=choices, id=q_id)\n\n\n@app.route('/answer', methods=['POST'])\ndef answers():\n \"\"\"Create answer route\"\"\"\n\n choice = request.form['answer']\n \n responses = session['responses']\n responses.append(choice)\n session['responses'] = responses\n\n if len(survey.questions) == len(responses):\n return redirect('/thanks')\n else:\n return redirect(f'/questions/{len(responses)}')\n\n\n@app.route('/thanks')\ndef thanks():\n \"\"\"Thank user for participating.\"\"\"\n\n return render_template('thanks.html')\n", "repo_name": "jr0dd/usf-bootcamp", "sub_path": "flask-survey/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1888, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "flask.Flask", "line_number": 5, "usage_type": "call"}, {"api_name": "flask_debugtoolbar.DebugToolbarExtension", "line_number": 10, "usage_type": "call"}, {"api_name": "surveys.satisfaction_survey.title", "line_number": 16, "usage_type": "attribute"}, {"api_name": "surveys.satisfaction_survey", "line_number": 16, "usage_type": "name"}, {"api_name": "surveys.satisfaction_survey.instructions", "line_number": 17, "usage_type": "attribute"}, {"api_name": "surveys.satisfaction_survey", "line_number": 17, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 19, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 26, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 28, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 35, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 38, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 39, "usage_type": "call"}, {"api_name": "surveys.satisfaction_survey.questions", "line_number": 41, "usage_type": "attribute"}, {"api_name": "surveys.satisfaction_survey", "line_number": 41, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 42, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 45, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 46, "usage_type": "call"}, {"api_name": "surveys.satisfaction_survey.questions", "line_number": 48, "usage_type": "attribute"}, {"api_name": "surveys.satisfaction_survey", "line_number": 48, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 51, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 58, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 58, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 60, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 62, "usage_type": "name"}, {"api_name": "surveys.satisfaction_survey.questions", "line_number": 64, "usage_type": "attribute"}, {"api_name": "surveys.satisfaction_survey", "line_number": 64, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 65, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 67, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 74, "usage_type": "call"}]} +{"seq_id": "23259139237", "text": "# Imports\n\nfrom flask import Flask, g\nfrom flask_cors import CORS\nfrom flask_login import LoginManager\nfrom api.user import user\nfrom api.parks import park\n\nimport models\n\n\n# ------------------------------------------------------------------------------------------------------\n\n# Setup and Initialization\n\nDEBUG = True\nPORT = 9000\nlogin_manager = LoginManager()\napp = Flask(__name__, static_url_path=\"\", static_folder=\"static\")\n\n\n# ------------------------------------------------------------------------------------------------------\n\n# Session\n\napp.secret_key = 'RANDOM ASS STRING'\napp.register_blueprint(user)\napp.register_blueprint(park)\n\n\n# CORS(api, origins = ['http://localhost:3000'], supports_credentials = True)\n# CORS(user, origins = ['http://localhost:3000'], supports_credentials = True)\n\n\nlogin_manager.init_app(app)\n\n\n# ------------------------------------------------------------------------------------------------------\n\n# Decorators and Functions\n\n@login_manager.user_loader\ndef load_user(userid):\n try:\n return models.User.get(models.User.id == userid)\n except models.DoesNotExist:\n return None\n\n@app.before_request\ndef before_request():\n \"\"\"Connect to the database before each request\"\"\"\n g.db = models.DATABASE\n g.db.connect()\n\n@app.after_request\ndef after_request(response):\n \"\"\"Close the database connection after each request\"\"\"\n g.db.close()\n return response\n\n@app.route('/')\ndef index():\n return 'hi'\n\n\n# ------------------------------------------------------------------------------------------------------\n\n# Run the App!\n\nif __name__ == '__main__':\n models.initialize()\n app.run(debug=DEBUG, port=PORT)\n", "repo_name": "OladiranJ/Open-Runs-Backend", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1744, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask_login.LoginManager", "line_number": 18, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 19, "usage_type": "call"}, {"api_name": "api.user.user", "line_number": 27, "usage_type": "argument"}, {"api_name": "api.parks.park", "line_number": 28, "usage_type": "argument"}, {"api_name": "models.User.get", "line_number": 45, "usage_type": "call"}, {"api_name": "models.User", "line_number": 45, "usage_type": "attribute"}, {"api_name": "models.DoesNotExist", "line_number": 46, "usage_type": "attribute"}, {"api_name": "flask.g.db", "line_number": 52, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 52, "usage_type": "name"}, {"api_name": "models.DATABASE", "line_number": 52, "usage_type": "attribute"}, {"api_name": "flask.g.db.connect", "line_number": 53, "usage_type": "call"}, {"api_name": "flask.g.db", "line_number": 53, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 53, "usage_type": "name"}, {"api_name": "flask.g.db.close", "line_number": 58, "usage_type": "call"}, {"api_name": "flask.g.db", "line_number": 58, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 58, "usage_type": "name"}, {"api_name": "models.initialize", "line_number": 71, "usage_type": "call"}]} +{"seq_id": "34861257228", "text": "from os.path import join as op_join\nimport copy\nimport numpy as np\nfrom numpy import newaxis as nax\n\nimport wx\nimport wx.aui\nimport wx.lib.plot.plotcanvas as wlpc\nimport wx.lib.stattext\nimport wx.lib.agw.buttonpanel as bp\nimport wx.lib.agw.foldpanelbar as fpb\nfrom wx.lib.anchors import LayoutAnchors\nfrom wx.lib.stattext import GenStaticText\nfrom wx.lib.buttons import GenToggleButton as wxTogBut\nfrom wx.lib.plot.polyobjects import PolyLine, PlotGraphics\n# from wx.lib.plot.polyobjects import PolyMarker\n\nimport mva.chemometrics as chemtrics\n# noinspection PyProtectedMember\nfrom mva.chemometrics import _index\nfrom plot import PolyEllipse\nfrom commons import error_box\nfrom commons import PolyMarker\n\n[wxID_PCA, wxID_PCAPLCPCALOADSV, wxID_PCAPLCPCASCORE, wxID_PCAPLCPCEIGS,\n wxID_PCAPLCPCVAR, \n ] = [wx.NewId() for _init_ctrls in range(5)]\n\n[ID_RUNPCA, ID_EXPORTPCA, ID_PCATYPE, \n ID_SPNPCS, ID_NUMPCS1, ID_NUMPCS2,\n ] = [wx.NewId() for _init_btnpanel_ctrls in range(6)]\n\n# FR1 (wxID_FRAME1)\n[FR1_, FR1_BTNAPPLY, FR1_CBGRID,\n FR1_SPNFONTSIZEAXES, FR1_SPNXMAX, FR1_SPNXMIN,\n FR1_SPNYMAX, FR1_SPNYMIN, FR1_STFONT,\n FR1_STTITLE, FR1_STXFROM, FR1_STXLABEL,\n FR1_STXTO, FR1_STYFROM, FR1_STYLABEL, FR1_STYTO,\n FR1_TXTTITLE, FR1_TXTXLABEL, FR1_TXTXMAX,\n FR1_TXTXMIN, FR1_TXTYLABEL, FR1_TXTYMAX,\n FR1_TXTYMIN,\n ] = [wx.NewId() for _init_plot_prop_ctrls in range(23)]\n\n[MNUPLOTCOPY, MNUPLOTPRINT, MNUPLOTSAVE, MNUPLOTPROPS, MNUPLOTCOORDS,\n ] = [wx.NewId() for _init_plot_menu_Items in range(5)]\n\n\ndef set_btn_state(s1, s2, tb):\n # toolbar button enabled condition\n if s1 == s2:\n state = False\n else:\n state = True\n \n buttons = [tb.tbLoadLabels, tb.tbLoadLabStd1, \n tb.tbLoadLabStd2, tb.tbLoadSymStd2]\n \n for button in buttons:\n button.Enable(state)\n\ndef create_sym_col_select(canvas, output):\n \"\"\" populate symbol select pop-up\n\n \"\"\"\n print(' in create_sym_col_select pca loc 76')\n # first destroy current\n canvas.tbMain.SymPopUpWin.Destroy()\n # create empty ctrl\n canvas.tbMain.SymPopUpWin = SymColSelectTool(canvas.tbMain)\n spuw = canvas.tbMain.SymPopUpWin\n # create ctrls\n count = 0\n # apply button\n spuw.btnApply = wx.Button(spuw, wx.NewId(), 'Apply')\n spuw.Bind(wx.EVT_BUTTON, spuw.on_btn_apply, spuw.btnApply)\n # close button\n spuw.btnClose = wx.Button(spuw, wx.NewId(), 'Close')\n spuw.Bind(wx.EVT_BUTTON, spuw.on_btn_close, spuw.btnClose)\n # spacer\n spuw.stSpacer = wx.StaticText(spuw, -1, '')\n # dynamic ctrls\n spuw.colctrls = []\n spuw.symctrls = []\n\n sc = str(count)\n for each in output:\n exec('canvas.tbMain.SymPopUpWin.st' + sc + ' = wx.StaticText(canvas.tbMain.SymPopUpWin, -1, ' +\n 'each[0])')\n exec('canvas.tbMain.SymPopUpWin.btn' + sc + ' = wx.BitmapButton(canvas.tbMain.SymPopUpWin, ' +\n 'bitmap=wx.Bitmap(op_join(\"bmp\", \"' + each[1] + '.bmp\"), wx.BITMAP_TYPE_BMP), id_=-1)')\n exec('canvas.tbMain.SymPopUpWin.btn' + sc + '.symname = \"' + each[1] + '\"')\n exec('canvas.tbMain.SymPopUpWin.btn' + sc + '.Bind(wx.EVT_BUTTON, canvas.tbMain.SymPopUpWin.on_btn_symbol' + ')')\n exec('canvas.tbMain.SymPopUpWin.cp' + sc + ' = wx.ColourPickerCtrl(canvas.tbMain.SymPopUpWin, ' +\n '-1, col=' + str(each[2]) + ', style=wx.CLRP_DEFAULT_STYLE)')\n \n # output ctrl names to use later\n spuw.colctrls.append('cp' + sc)\n spuw.symctrls.append('btn' + sc)\n count += 1 \n \n # create sizer\n spuw.grsSelect = wx.GridSizer(cols=3, hgap=2, rows=count+1, vgap=2)\n # add standard ctrls\n spuw.grsSelect.Add(spuw.btnClose, 0, border=0, flag=wx.EXPAND)\n spuw.grsSelect.Add(spuw.btnApply, 0, border=0, flag=wx.EXPAND)\n spuw.grsSelect.Add(spuw.stSpacer, 0, border=0, flag=wx.EXPAND)\n # add dynamic ctrls to sizer\n for nwin in range(count):\n exec('canvas.tbMain.SymPopUpWin.grsSelect.Add(canvas.tbMain.SymPopUpWin.st' +\n str(nwin) + ', 0, border=0, flag=wx.EXPAND)')\n exec('canvas.tbMain.SymPopUpWin.grsSelect.Add(canvas.tbMain.SymPopUpWin.btn' +\n str(nwin) + ', 0, border=0, flag=wx.EXPAND)')\n exec('canvas.tbMain.SymPopUpWin.grsSelect.Add(canvas.tbMain.SymPopUpWin.cp' +\n str(nwin) + ', 0, border=0, flag=wx.EXPAND)')\n \n # set sizer and resize\n # noinspection PyUnresolvedReferences\n canvas.tbMain.SymPopUpWin.SetSizer(canvas.tbMain.SymPopUpWin.grsSelect)\n resize = (canvas.tbMain.SymPopUpWin.GetSize()[0], count * 35)\n canvas.tbMain.SymPopUpWin.SetSize(resize)\n\n# noinspection PyTypeChecker\ndef box_plot(canvas, x, labels, **_attr):\n \"\"\"Box and whisker plot; x is a column vector, labels a list of strings\n\n \"\"\"\n objects, count = [], 1\n uG = np.unique(np.array(labels))\n for each in uG:\n # get values\n group = x[np.array(labels) == each]\n # calculate group median\n m = np.median(group)\n # lower (first) quartile\n lq = np.median(group[group < m])\n # upper (third) quartile\n uq = np.median(group[group > m])\n # interquartile range\n iqr = uq-lq\n # lower whisker\n lw = m - (1.5 * iqr)\n # upper whisker\n uw = m + (1.5 * iqr)\n # lower outlier\n lo = group[group < lw]\n # upper outlier\n uo = group[group > uw]\n # plot b&w\n solid = wx.PENSTYLE_SOLID\n objects.append(PolyLine([[count - .25, m], [count + .25, m]],\n width=1, colour='blue', style=solid))\n objects.append(PolyLine([[count - .25, lq], [count + .25, lq]],\n width=1, colour='black', style=solid))\n objects.append(PolyLine([[count - .25, uq], [count + .25, uq]],\n width=1, colour='black', style=solid))\n objects.append(PolyLine([[count - .25, lq], [count - .25, uq]],\n width=1, colour='black', style=solid))\n objects.append(PolyLine([[count + .25, lq], [count + .25, uq]],\n width=1, colour='black', style=solid))\n objects.append(PolyLine([[count, lq], [count, lw]],\n width=1, colour='black', style=solid))\n objects.append(PolyLine([[count, uq], [count, uw]],\n width=1, colour='black', style=solid))\n objects.append(PolyLine([[count - .1, lw], [count + .1, lw]],\n width=1, colour='black', style=solid))\n objects.append(PolyLine([[count - .1, uw], [count + .1, uw]],\n width=1, colour='black', style=solid))\n if len(lo) > 0:\n objects.append(PolyMarker(np.concatenate(\n (np.ones((len(lo), 1)) * count, lo[:, nax]), 1),\n colour='red', fillcolour='red', marker='circle', size=1))\n if len(uo) > 0:\n objects.append(PolyMarker(np.concatenate(\n (np.ones((len(uo), 1)) * count, uo[:, nax]), 1),\n colour='red', fillcolour='red', marker='circle', size=1))\n count += 1\n \n canvas.xSpec = 'auto'\n # canvas.draw(PlotGraphics(objects, _attr['title'], _attr['xLabel'],\n # _attr['yLabel'], xTickLabels=uG))\n canvas.draw(PlotGraphics(objects, _attr['title'], _attr['xLabel'],\n _attr['yLabel']))\n\n\n# noinspection PyTypeChecker\ndef plot_error_bar(canvas, **_attr):\n \"\"\"Errorbar plot\n Defaults: \n 'x'= None - xaxis values, column vector\n 'y'= None - average, column vector \n 'validation'= None - list of 0's & 1's & 2's \n 'title'= '', - plot title\n 'xLabel'= '', - x-axis label\n 'yLabel'= '', - y-axis label\n 'lsfit'=False, - show linear fit\n 'usesym'=[]\n 'usecol'=[]\n \"\"\"\n \n # defaults\n colours = ['black', 'red', 'blue']\n usesym = ['square', 'circle', 'triangle']\n ledgtext = ['Train', 'Validation', 'Test']\n\n # user defined\n if _attr['usesym']:\n # noinspection PyUnusedLocal\n symbols = _attr['usesym']\n if _attr['usecol']:\n colours = _attr['usecol']\n \n objects = []\n if _attr['lsfit']:\n # show linear fit\n objects.append(PolyLine(np.array([[_attr['x'].min(), _attr['x'].min()],\n [_attr['x'].max(), _attr['x'].max()]]),\n legend='Linear fit', colour='cyan',\n width=1, style=wx.PENSTYLE_SOLID))\n\n for val in range(max(_attr['validation']) + 1):\n # get average and stdev of predictions for each calibration point\n average, stdev = [], []\n xsub = np.take(_attr['x'], _index(_attr['validation'], val), 0)\n uXsub = np.unique(xsub)\n ysub = np.take(_attr['y'], _index(_attr['validation'], val), 0)\n for item in range(len(uXsub)):\n average.append(np.mean(np.take(ysub, _index(xsub, uXsub[item]))))\n stdev.append(np.std(np.take(ysub, _index(xsub, uXsub[item]))))\n \n # markers\n objects.append(PolyMarker(np.concatenate((uXsub[:, nax],\n np.array(average)[:, nax]), 1),\n legend=ledgtext[val], colour=colours[val],\n marker=usesym[val], size=1.5,\n fillstyle=wx.BRUSHSTYLE_SOLID))\n \n # errorbars & horizontal bars\n for line, uxval in enumerate(uXsub):\n avgln = average[line]\n stdln = stdev[line]\n # errorbars\n objects.append(\n PolyLine(np.array([[uxval, avgln - stdln],\n [uxval, avgln + stdln]]),\n colour=colours[val], width=1, style=wx.PENSTYLE_SOLID))\n # horizontal bars +ve\n amxs = .01 * abs(max(uXsub))\n objects.append(\n PolyLine(np.array([[uxval - amxs, avgln + stdln],\n [uxval + amxs, avgln + stdln]]),\n colour=colours[val], width=1, style=wx.PENSTYLE_SOLID))\n # horizontal bars -ve\n objects.append(\n PolyLine(np.array([[uxval - amxs, avgln-stdln],\n [uxval + amxs, avgln-stdln]]),\n colour=colours[val], width=1, style=wx.PENSTYLE_SOLID))\n \n # axis limits\n atx = _attr['x']\n aty = _attr['y']\n\n xAx = (atx.min() - (.05 * atx.max()), atx.max() + (.05 * atx.max()))\n yAx = (aty.min() - (.05 * aty.max()), aty.max() + (.05 * aty.max()))\n \n canvas.draw(PlotGraphics(objects, _attr['title'], _attr['xLabel'],\n _attr['yLabel']), xAx, yAx)\n \n# noinspection PyUnresolvedReferences\ndef plot_pls_model(canvas, model='full', tbar=None, **_attr):\n \"\"\"Plot PLS predictions or scores; model = 'full' for PLSR,\n model = 'ga' for GA-PLS feature selection\n \n **_attr - key word _attributes \n Defaults: \n 'predictions'= None - pls predictions\n 'cL' = None - constituents\n 'scores' = None - pls spectral scores\n 'plScL' = None - false class for pls-da\n 'validation' = None, - split data\n 'factors' = 1, - no. latent variables\n 'type' = 0 - plsr or pls-da\n 'symbols' = False - plot with symbols\n 'usetxt' = True - plot with text labels\n 'RMSEPT' = 0 - RMSE for independent test samples\n 'col1' = 0 - col for xaxis\n 'col2' = 1 - col for yaxis\n \"\"\"\n typex = _attr['type']\n cL = None\n pRed = None\n canvPref = None\n\n if model in ['full']:\n canvPref = 'plcPredPls'\n prnt = canvas.parent.parent\n elif model == 'ga':\n canvPref = 'plcGaModelPlot'\n prnt = canvas.parent.parent.prnt.splitPrnt\n\n nBook = canvas.parent\n\n # Parece que Notebook no tiene 'SetTabSize' en phoenyx\n # if _attr['predictions'].shape[1] > 1:\n # canvas.parent.SetTabSize((80, 15))\n # else:\n # canvas.parent.SetTabSize((0, 1))\n # canvas.parent.SetPageText(0, '')\n \n if typex == 0:\n numPlots = _attr['predictions'].shape[1]\n else:\n numPlots = _attr['predictions'].shape[1] + 1\n \n # delete pages\n nBook.SetSelection(0)\n for page in range(nBook.GetPageCount() - 1, -1, -1):\n nBook.DeletePage(page)\n \n for const in range(numPlots):\n if typex == 0:\n cL = _attr['cL'][:, const][:, nax]\n pRed = _attr['predictions'][:, const][:, nax]\n elif (typex == 1) & (const > 0) is True:\n cL = _attr['plScL'][:, const-1][:, nax]\n pRed = _attr['predictions'][:, const-1][:, nax]\n \n # create new canvas\n sc1 = str(const + 1)\n exec(\"prnt.\" + canvPref + sc1 + \"= MyPlotCanvas(id_=-1, \" +\n \"name='\" + canvPref + sc1 + \"', parent=nBook, \" +\n \"pos=(0, 0), size=(302, 246), \" +\n \"style=0, toolbar=tbar)\")\n exec(\"prnt.\" + canvPref + sc1 + \".font_size_axis = 8\")\n exec(\"prnt.\" + canvPref + sc1 + \".font_size_title = 10\")\n exec(\"prnt.\" + canvPref + sc1 + \".enable_zoom = True\")\n exec(\"prnt.\" + canvPref + sc1 + \".SetToolTip('')\")\n exec(\"prnt.\" + canvPref + sc1 + \".enable_legend = True\")\n exec(\"prnt.\" + canvPref + sc1 + \".font_size_legend = 8\")\n exec(\"prnt.\" + canvPref + sc1 + \".SetAutoLayout(True)\")\n exec(\"prnt.\" + canvPref + sc1 +\n \".SetConstraints(LayoutAnchors(prnt.\" + canvPref + sc1 +\n \", True, True, True, True))\")\n\n # create new nb page\n if _attr['predictions'].shape[1] > 1:\n exec(\"nBook.AddPage(imageId=-1, page=prnt.\" + canvPref +\n sc1 + \", select=False, text='PLS Predictions \" +\n sc1 + \"')\")\n else:\n exec(\"nBook.AddPage(imageId=-1, page=prnt.\" + canvPref +\n sc1 + \", select=False, text='')\")\n \n # use it for plotting\n cmd = \"ncanv = prnt.\" + canvPref + sc1\n exec(cmd, locals(), globals())\n \n if (typex == 1) and (const == 0):\n # plot pls-da scores\n plot_scores(ncanv, _attr['scores'], cl=_attr['cL'][:, 0],\n labels=_attr['label'], validation=_attr['validation'],\n col1=_attr['col1'], col2=_attr['col2'],\n title='PLS Scores',\n xLabel='t[%i]' % _attr['col1']+1,\n yLabel='t[%i]' % _attr['col2']+1,\n xval=True, pconf=False, symb=_attr['symbols'],\n text=_attr['usetxt'], usecol=_attr['usecol'],\n usesym=_attr['usesym'])\n \n else: \n if _attr['symbols']:\n # pls predictions as errorbar plot\n title = 'PLS Predictions: %i factors, RMS(Indep. Test) %.2f' % \\\n (_attr['factors']+1, _attr['RMSEPT'])\n plot_error_bar(ncanv, x=cL, y=pRed,\n validation=_attr['validation'],\n title=title, xLabel='Actual', yLabel='Predicted',\n lsfit=True, usesym=_attr['usesym'],\n usecol=_attr['usecol'])\n else:\n # pls predictions as scatter plot\n TrnPnts = np.zeros((1, 2), 'd')\n ValPnts = np.zeros((1, 2), 'd'),\n TstPnts = np.zeros((1, 2), 'd')\n\n for i in range(len(cL)):\n if int(np.reshape(_attr['validation'][i], ())) == 0:\n y = float(np.reshape(cL[i], ()))\n py = float(np.reshape(pRed[i], ()))\n TrnPnts = np.concatenate((TrnPnts, np.reshape((y, py), (1, 2))), 0)\n elif int(np.reshape(_attr['validation'][i], ())) == 1:\n y = float(np.reshape(cL[i], ()))\n py = float(np.reshape(pRed[i], ()))\n ValPnts = np.concatenate((ValPnts, np.reshape((y, py), (1, 2))), 0)\n elif int(np.reshape(_attr['validation'][i], ())) == 2:\n y = float(np.reshape(cL[i], ()))\n py = float(np.reshape(pRed[i], ()))\n TstPnts = np.concatenate((TstPnts, np.reshape((y, py), (1, 2))), 0)\n \n TrnPnts = TrnPnts[1:len(TrnPnts) + 1]\n ValPnts = ValPnts[1:len(ValPnts) + 1]\n TstPnts = TstPnts[1:len(TstPnts) + 1]\n \n TrnPntObj = PolyMarker(TrnPnts, legend='Train',\n colour='black',\n marker='square', size=1.5,\n fillstyle=wx.BRUSHSTYLE_TRANSPARENT)\n \n ValPntObj = PolyMarker(ValPnts, legend='Cross Val.',\n colour='red',\n marker='circle', size=1.5,\n fillstyle=wx.BRUSHSTYLE_TRANSPARENT)\n \n TstPntObj = PolyMarker(TstPnts, legend='Indep. Test',\n colour='blue',\n marker='triangle', size=1.5,\n fillstyle=wx.BRUSHSTYLE_TRANSPARENT)\n\n # noinspection PyTypeChecker\n LinearObj = PolyLine(np.array([[cL.min(), cL.min()],\n [cL.max(), cL.max()]]),\n legend='Linear fit', colour='cyan',\n width=1, style=wx.PENSTYLE_SOLID)\n \n PlsModel = PlotGraphics([TrnPntObj, ValPntObj, TstPntObj, LinearObj],\n ' '.join(('PLS Predictions:',\n str(_attr['factors'] + 1),\n 'factors, RMS(Indep. Test)',\n '%.2f' % _attr['RMSEPT'])),\n 'Actual', 'Predicted')\n \n xAx = (cL.min() - (0.05 * cL.max()), cL.max() + (0.05 * cL.max()))\n \n ys = np.concatenate((TrnPnts, ValPnts), 0)\n # noinspection PyArgumentList\n yAx = (ys.min() - (0.05 * ys.max()), ys.max() + (0.05 * ys.max()))\n \n ncanv.draw(PlsModel, xAx, yAx)\n\n nBook.SetSelection(0)\n exec(\"canvas = prnt.\" + canvPref + str(1))\n \n return canvas\n \ndef plot_line(plotCanvas, plotArr, **_attr):\n \"\"\"Line plot\n **_attr - key word _attributes\n Defaults:\n 'xaxis' = None, - Vector of x-axis values\n 'rownum' = 0, - Row of plotArr to plot\n 'tit'= '', - A small domestic bird\n 'xLabel'= '', - The desired x-axis label\n 'yLabel'= '', - The desired y-axis label\n 'type'= 'single', - 'single' or 'multi'\n 'ledge'= [], - Figure legend labels\n 'wdth'= 1, - Line width\n \"\"\"\n\n colourList = ['blue', 'red', 'green', 'light_grey', 'cyan', 'black']\n NewplotLine = None\n \n if _attr['type'] == 'single':\n pA = plotArr[_attr['rownum'], 0:len(_attr['xaxis'])][:, nax]\n Line = PolyLine(np.concatenate((_attr['xaxis'], pA), 1),\n colour='black', width=_attr['wdth'],\n style=wx.PENSTYLE_SOLID)\n NewplotLine = PlotGraphics([Line], _attr['tit'],\n _attr['xLabel'], _attr['yLabel'])\n elif _attr['type'] == 'multi':\n ColourCount = 0\n Line = []\n for i in range(plotArr.shape[0]):\n pA = plotArr[i]\n pA = pA[:, nax]\n if _attr['ledge'] is not None:\n Line.append(PolyLine(np.concatenate((_attr['xaxis'], pA), 1),\n legend=_attr['ledge'][i],\n colour=colourList[ColourCount],\n width=_attr['wdth'],\n style=wx.PENSTYLE_SOLID))\n else:\n Line.append(PolyLine(np.concatenate((_attr['xaxis'], pA), 1),\n colour=colourList[ColourCount],\n width=_attr['wdth'],\n style=wx.PENSTYLE_SOLID))\n ColourCount += 1\n if ColourCount == len(colourList):\n ColourCount = 0\n NewplotLine = PlotGraphics(Line, _attr['tit'],\n _attr['xLabel'], _attr['yLabel'])\n \n plotCanvas.draw(NewplotLine) # , xAxis=(_attr['xaxis'].min(), _attr['xaxis'].max()))\n \ndef plot_stem(plotCanvas, plotArr, **_attr):\n \"\"\"Stem plot\n **_attr - key word _attributes\n Defaults:\n 'tit'= '', - Figure title\n 'xLabel'= '', - The desired x-axis label\n 'yLabel'= '', - The desired y-axis label\n 'wdth'= 1, - Line width\n \"\"\"\n \n # plotArr is an n x 2 array\n plotStem = []\n for i in range(plotArr.shape[0]):\n newCoords = np.array([[plotArr[i, 0], 0], [plotArr[i, 0], plotArr[i, 1]]])\n plotStem.append(PolyLine(newCoords, colour='black',\n width=_attr['wdth'], style=wx.PENSTYLE_SOLID))\n # noinspection PyTypeChecker\n plotStem.append(PolyLine(\n np.array([[plotArr[0, 0] - (.1 * plotArr[0, 0]), 0],\n [plotArr[len(plotArr) - 1, 0] + (.1 * plotArr[0, 0]), 0]]),\n colour='black',\n width=1, style=wx.PENSTYLE_SOLID))\n \n plotStem = PlotGraphics(plotStem, _attr['tit'],\n _attr['xLabel'], _attr['yLabel'])\n \n plotCanvas.draw(plotStem)\n\ndef plot_symbols(plotCanvas, coords, **_attr):\n \"\"\"Symbol plot\n **_attr - key word _attributes\n Defaults:\n 'mask' = [], - List of zeros, ones and/or twos to\n define train, cross-validation and\n test samples\n 'cLass' = [], - List of integers from 1:n, where \n n=no. of groups\n 'col1' = 0, - Column to plot along abscissa\n 'col2' = 1, - Column to plot along ordinate\n 'tit'= '', - A small domestic bird\n 'xL'= '', - The desired x-axis label\n 'yL'= '', - The desired y-axis label\n 'text'= [], - List of labels to use in legend\n 'usemask'= True,- Flag to define whether to use 'mask'\n 'usecol'=[], - Use a list of colours\n 'usesym'= [], - List of symbols for plotting\n \"\"\"\n \n desCl = np.unique(_attr['text'])\n eCount = 0\n if not _attr['usecol']:\n colours = ['blue', 'red', 'green', 'cyan', 'black']\n else:\n colours = _attr['usecol']\n \n if not _attr['usesym']:\n symbols = ['circle', 'square', 'plus',\n 'triangle', 'cross', 'triangle_down']\n else:\n symbols = _attr['usesym']\n \n # plot scores using symbols\n valSym = ['circle', 'square']\n plotSym, countSym, countColour, output = [], 0, 0, []\n for each in desCl:\n if countSym > len(symbols)-1:\n countSym = 0\n if countColour > len(colours)-1:\n countColour = 0\n \n # slice coords\n alist = coords[np.array(_attr['text']) == each, :]\n\n if _attr['col1'] != _attr['col2']:\n alist = np.take(alist, (_attr['col1'], _attr['col2']), 1)\n else:\n sCount = copy.deepcopy(eCount)+1 \n eCount = eCount+len(alist)\n alist = np.concatenate((np.arange(sCount, eCount + 1)[:, nax],\n alist[:, _attr['col1']][:, nax]), 1)\n \n # col = wx.Colour(round(np.rand(1).tolist()[0]*255),\n # round(np.rand(1).tolist()[0]*255),\n # round(np.rand(1).tolist()[0]*255))\n \n output.append([each, symbols[countSym], colours[countColour]])\n \n if _attr['usemask'] is False:\n plotSym.append(PolyMarker(alist, marker=symbols[countSym],\n fillcolour=colours[countColour],\n colour=colours[countColour],\n size=2, legend=each))\n \n else:\n listM = _attr['mask'][np.array(_attr['text']) == each]\n for m in range(3):\n if m == 0:\n # include legend entry\n plotSym.append(PolyMarker(alist[listM == m],\n marker=symbols[countSym],\n fillcolour=colours[countColour],\n colour=colours[countColour],\n size=2.5, legend=each))\n else:\n # no legend\n plotSym.append(PolyMarker(alist[listM == m],\n marker=symbols[countSym],\n fillcolour=colours[countColour],\n colour=colours[countColour],\n size=2.5))\n if m > 0:\n if symbols[countSym] not in ['cross', 'plus']:\n # overlay white circle/square to indicate\n # validation/test sample\n plotSym.append(PolyMarker(\n alist[listM == m],\n marker=valSym[m - 1], colour=wx.Colour('white'),\n fillcolour=wx.Colour('white'), size=1))\n else:\n # overlay white square to indicate validation sample\n plotSym.insert(len(plotSym) - 1,\n PolyMarker(alist[listM == m],\n marker=valSym[m - 1],\n colour=wx.Colour('black'),\n fillcolour=wx.Colour('white'),\n size=2.5))\n \n countSym += 1\n countColour += 1\n \n draw_plotSym = PlotGraphics(plotSym, _attr['tit'],\n xLabel=_attr['xL'], yLabel=_attr['yL'])\n \n if plotCanvas is not None:\n plotCanvas.draw(draw_plotSym)\n \n return plotSym, output\n\ndef plot_text(plotCanvas, coords, **_attr):\n \"\"\"Text label plot\n **_attr - key word _attributes\n Defaults:\n 'mask' = [], - List of zeros, ones and/or twos to\n define train, cross-validation and\n test samples\n 'cLass' = [], - List of integers from 1:n, where \n n=no. of groups\n 'col1' = 0, - Column to plot along abscissa\n 'col2' = 1, - Column to plot along ordinate\n 'tit'= '', - A small domestic bird\n 'xL'= '', - The desired x-axis label\n 'yL'= '', - The desired y-axis label\n 'text'= [], - List of labels to use in plotting\n 'usemask'= True,- Flag to define whether to use 'mask' \n \"\"\"\n \n # make sure label string\n nt = [str(i) for i in _attr['text']]\n _attr['text'] = nt\n \n plotText = []\n colours = ['black', 'blue', 'red']\n if _attr['usemask']:\n colRange = 3\n else:\n colRange = 1\n\n # plot 2d\n if (coords.shape[1] > 1) & (_attr['col1'] != _attr['col2']):\n # set text colour - black=train, blue=val, red=test\n for getColour in range(colRange):\n if colRange == 3:\n idx = _index(_attr['mask'], getColour)\n else:\n idx = range(len(coords))\n plotText.append(PolyMarker(\n np.take(np.take(coords, [_attr['col1'], _attr['col2']], 1),\n idx, 0),\n marker='text', legend=np.take(_attr['text'], idx, 0),\n colour=colours[getColour]))\n # plot 1d\n else:\n points = np.take(coords, [_attr['col1']], 1)\n nCl = np.unique(_attr['text'])\n eCount = 0\n for each in nCl:\n aslice = points[np.array(_attr['text']) == each]\n lbls = np.array(_attr['text'])[np.array(_attr['text']) == each]\n \n sCount = copy.deepcopy(eCount) + 1\n eCount = eCount + len(aslice)\n \n pointSub = np.concatenate((np.arange(sCount, eCount + 1)[:, nax],\n aslice), 1)\n \n if _attr['usemask'] is False:\n plotText.append(PolyMarker(pointSub, marker='text',\n legend=lbls.tolist()))\n else:\n msk = np.array(_attr['mask'])\n txt = np.array(_attr['text'])\n for each2 in range(3):\n msk_lst = msk[txt == each2].tolist()\n msk_idx = _index(msk_lst, each2)\n plotText.append(\n PolyMarker(np.take(pointSub, msk_idx, 0),\n marker='text',\n legend=np.take(lbls, msk_idx.tolist(),\n colour=colours[each2])))\n \n if (coords.shape[1] > 1) & (_attr['col1'] != _attr['col2']):\n draw_plot_text = PlotGraphics(plotText, _attr['tit'],\n xLabel=_attr['xL'], yLabel=_attr['yL'])\n else:\n draw_plot_text = PlotGraphics(plotText, _attr['tit'],\n xLabel='', yLabel=_attr['yL'])\n print('plotText ', plotText)\n if plotCanvas is not None:\n plotCanvas.draw(draw_plot_text)\n \n return plotText\n\ndef plot_loads(canvas, loads, **_attr):\n \"\"\"Model loadings plot\n **_attr - key word _attributes\n Defaults:\n 'xaxis' = [], - Vector of x-axis values\n 'col1' = 0, - Column to plot along abscissa\n 'col2' = 1, - Column to plot along ordinate\n 'title'= '', - Figure title\n 'xLabel'= '', - The desired x-axis label\n 'yLabel'= '', - The desired y-axis label\n 'type'= 0, - List of labels to use in plotting\n 'usecol'= [], - List of colours for symbol plot\n 'usesym'= [], - List of symbols for plotting\n \"\"\"\n i = 0\n\n # for model loadings plots\n plot = []\n \n if (_attr['col1'] != _attr['col2']) & (loads is not None) is True:\n # standard deviation\n select = np.concatenate((loads[:, _attr['col1']][:, nax],\n loads[:, _attr['col2']][:, nax]), 1)\n meanCoords = np.reshape(np.mean(select, 0), (1, 2))\n std = np.mean(np.std(select))\n\n if _attr['type'] == 0:\n # plot labels\n textPlot = plot_text(None, select, mask=None, cLass=None,\n text=_attr['xaxis'], usemask=False, col1=0,\n col2=1, tit='', xL='', yL='')\n for each in textPlot:\n plot.append(each)\n \n else:\n test = np.sqrt((loads[:, _attr['col1']]-meanCoords[0, 0]) ** 2 +\n (loads[:, _attr['col2']]-meanCoords[0, 1]) ** 2)\n index = np.arange(len(_attr['xaxis']))\n\n if _attr['type'] == 1: \n # >1*std error & labels\n outIdx = index[test > std]\n getOutliers = np.take(select, outIdx, 0)\n\n # plot labels\n labels = []\n for each in outIdx:\n labels.append(_attr['xaxis'][each])\n textPlot = plot_text(None, getOutliers, mask=None, cLass=None,\n text=labels, usemask=False, col1=0, col2=1,\n tit='', xL='', yL='')\n for each in textPlot:\n plot.append(each)\n \n elif _attr['type'] == 2:\n # >2*std error & labels\n outIdx = index[test > std * 2]\n \n getOutliers = np.take(select, outIdx, 0)\n \n # plot labels\n labels = []\n for each in outIdx:\n labels.append(_attr['xaxis'][each])\n textPlot = plot_text(None, getOutliers, mask=None, cLass=None,\n text=labels, usemask=False, col1=0, col2=1,\n tit='', xL='', yL='')\n for each in textPlot:\n plot.append(each)\n \n elif _attr['type'] == 3:\n # >2*std error & symbols\n outIdx = index[test > std * 2]\n \n # loadings > 2*std\n getOutliers = np.take(select, outIdx, 0)\n \n # identify regions\n # noinspection PyUnusedLocal\n newxvar = np.take(_attr['xaxis'], outIdx)\n regions = [outIdx[0]]\n for i in range(len(outIdx) - 1 ):\n if outIdx[i + 1] - 1 != outIdx[i]:\n regions.append(outIdx[i])\n regions.append(outIdx[i + 1])\n if np.mod(len(regions), 2) == 1:\n regions.append(outIdx[i + 1])\n \n # plot regions by symbol/colour\n cl, labels, i = [], [], 0\n while i < len(regions):\n cl.extend((np.ones(regions[i + 1] - regions[i] + 1, ) * i).tolist())\n for j in range(regions[i + 1]-regions[i]+1):\n labels.append(str(_attr['xaxis'][regions[i]]) + ' - ' +\n str(_attr['xaxis'][regions[i + 1]]))\n i += 2\n \n symPlot, output = plot_symbols(None, getOutliers, mask=None,\n cLass=np.array(cl),\n text=labels, usemask=False,\n col1=0, col2=1, tit='',\n xL='', yL='',\n usecol=_attr['usecol'],\n usesym=_attr['usesym'])\n \n # create window in background for changing symbols/colours\n create_sym_col_select(canvas, output)\n \n for each in symPlot:\n plot.append(each)\n \n # ellipse boundary\n plot.append(PolyMarker([[meanCoords[0, 0] - (std * 2),\n meanCoords[0, 1] - (std * 2)],\n [meanCoords[0, 0] + (std * 2),\n meanCoords[0, 1] + (std * 2)]],\n colour='white', size=1, marker='circle'))\n # centroid\n plot.append(PolyMarker(meanCoords, colour='blue',\n size=2, marker='plus'))\n # plot 1 std\n plot.append(PolyEllipse(meanCoords, colour='green', width=1,\n dim=(std * 2, std * 2),\n style=wx.PENSTYLE_SOLID))\n # plot 2 stds\n plot.append(PolyEllipse(meanCoords, colour='green', width=1,\n dim=(std * 4, std * 4),\n style=wx.PENSTYLE_SOLID))\n \n # draw it\n canvas.draw(PlotGraphics(plot, _attr['title'], _attr['xLabel'],\n _attr['yLabel']))\n \n \ndef plot_scores(canvas, scores, **_attr):\n \"\"\"Model scores plot\n **_attr - key word _attributes\n Defaults:\n 'cl' = [] - List of integers\n 'labels' = [] - List of sample labels\n 'validation' = [] - List of zeros, ones and/or twos\n 'col1' = 0, - Column to plot along abscissa\n 'col2' = 1, - Column to plot along ordinate\n 'title'= '', - Figure title\n 'xLabel'= '', - The desired x-axis label\n 'yLabel'= '', - The desired y-axis label\n 'xval'= False, - Cross-validation used flag\n 'text'= True, - Text label plotting used flag\n 'pconf'= True, - 95% confidence limits plotted flag\n 'symb'= False, - Symbol plotting used flag\n 'usecol'= [], - List of colours to use in plotting\n 'usesym'= [], - List of symbols for plotting\n \"\"\"\n \n # make sure we can plot txt\n \n if (canvas.GetName() not in ['plcDFAscores']) & \\\n (len(canvas.GetName().split('plcGaModelPlot')) == 1):\n canvas.tbMain.tbConf.SetValue(False)\n if (canvas.tbMain.tbPoints.GetValue() is not True) & \\\n (canvas.tbMain.tbSymbols.GetValue() is not True):\n canvas.tbMain.tbPoints.SetValue(True)\n _attr['text'] = True\n \n # get mean centres\n # nb for a dfa/cva plot scaled to unit variance\n # 95% confidence radius is 2.15\n shapex = scores.shape\n nCl = np.unique(_attr['cl'])\n\n plot = []\n if (shapex[1] > 1) & (_attr['col1'] != _attr['col2']):\n canvas.xSpec = 'auto'\n \n scores = np.concatenate((scores[:, _attr['col1']][:, nax],\n scores[:, _attr['col2']][:, nax]), 1)\n \n mScores = np.zeros((1, 2))\n for i in range(len(nCl)):\n mScores = np.concatenate(\n (mScores, np.mean(np.take(scores, _index(_attr['cl'], nCl[i]),\n 0), 0)[nax, :]), 0)\n mScores = mScores[1: len(mScores)]\n \n if _attr['symb'] is True:\n # plot symbols\n sym_plot, output = plot_symbols(None, scores,\n mask=_attr['validation'],\n cLass=_attr['cl'],\n text=_attr['labels'],\n usemask=_attr['xval'], col1=0,\n col2=1, tit='', xL='', yL='',\n usecol=_attr['usecol'],\n usesym=_attr['usesym'])\n \n # create window in background for changing symbols/colours\n create_sym_col_select(canvas, output)\n \n for each in sym_plot:\n plot.append(each)\n \n if _attr['text']:\n # plot labels\n textPlot = plot_text(None, scores, mask=_attr['validation'],\n cLass=_attr['cl'], text=_attr['labels'],\n col1=0, col2=1, usemask=_attr['xval'], tit='',\n xL='', yL='')\n for each in textPlot:\n plot.append(each)\n \n if _attr['pconf']:\n # 95% confidence interval\n plot.append(PolyEllipse(mScores, colour='black', width=1,\n dim=(2.15 * 2, 2.15 * 2),\n style=wx.PENSTYLE_SOLID))\n # 95% confidence about the mean\n plot.append(PolyEllipse(mScores, colour='blue', width=1,\n dim=((1.95 / np.sqrt(len(nCl)) * 2),\n (1.95 / np.sqrt(len(nCl)) * 2)),\n style=wx.PENSTYLE_SOLID))\n # class centroids\n plot.append(PolyMarker(mScores[:, 0:2], colour='black',\n size=2, marker='plus'))\n # force boundary\n plot.append(PolyMarker([[min(mScores[:, 0] - 2.15),\n min(mScores[:, 1] - 2.15)],\n [max(mScores[:, 0] + 2.15),\n max(mScores[:, 1] + 2.15)]],\n colour='white', size=1, marker='circle'))\n\n # class centroid label\n if (_attr['symb'] is False) & (_attr['text'] is False):\n uC, centLab, centLabOrds = np.unique(_attr['cl']), [], []\n for gC in range(len(uC)):\n Idx = _index(_attr['cl'], uC[gC])[0]\n centLab.append(_attr['labels'][Idx])\n centLabOrds.append(np.reshape(mScores[gC, :], (scores.shape[1], )).tolist())\n \n # print centroid labels\n centPlot = plot_text(None, np.array(centLabOrds),\n cLass=np.arange(1, len(centLab) + 1),\n text=centLab, col1=0, col2=1,\n tit='', xL='', yL='', usemask=False)\n for each in centPlot:\n plot.append(each)\n \n canvas.draw(PlotGraphics(plot, _attr['title'],\n _attr['xLabel'], _attr['yLabel']))\n \n else:\n canvas.xSpec = 'none'\n if _attr['text']:\n # plot labels\n textPlot = plot_text(None, scores, mask=_attr['validation'],\n cLass=_attr['cl'], text=_attr['labels'],\n col1=_attr['col1'], col2=_attr['col1'],\n tit=_attr['title'], xL='Arbitrary',\n yL=_attr['yLabel'], usemask=_attr['xval'])\n # each are PolyMarkers\n\n for each in textPlot:\n print('each legend', each.getLegend())\n print('each tp labels attributes:', each.attributes['labels'])\n # noinspection PyProtectedMember\n print('each tp labels _attributes:', each._attributes['labels'])\n # print('each tp labels _attr:', each._attr['labels'])\n plot.append(each)\n \n if _attr['symb']:\n # plot symbols\n sym_plot, output = plot_symbols(None, scores,\n mask=_attr['validation'],\n cLass=_attr['cl'],\n text=_attr['labels'],\n usemask=_attr['xval'],\n col1=_attr['col1'],\n col2=_attr['col1'], tit='', xL='',\n yL='', usecol=_attr['usecol'],\n usesym=_attr['usesym'])\n \n # create window in background for changing symbols/colours\n create_sym_col_select(canvas, output)\n \n for each in sym_plot:\n print('each sp labels attributes:', each, each.attributes['labels'])\n # noinspection PyProtectedMember\n print('each sp labels _attributes:', each._attributes['labels'])\n plot.append(each)\n \n if _attr['text'] or _attr['symb']:\n graphic = PlotGraphics(plot, _attr['title'], '', _attr['yLabel'])\n print('legen names: ', graphic.getLegendNames())\n canvas.draw(graphic)\n \n \nclass SymColSelectTool(wx.Dialog):\n def __init__(self, parent):\n wx.Dialog.__init__(self, parent=parent, style=0)\n\n self.parent = parent\n self.SetSize((300, 0))\n self.SetAutoLayout(True)\n\n def on_btn_close(self, _):\n self.Show(False)\n\n # noinspection PyUnresolvedReferences\n def on_btn_apply(self, _):\n # get list of new colours\n collist = []\n for each in self.colctrls:\n exec('collist.append(self.' + each + '.GetColour())')\n # get list of new symbols\n symlist = []\n for each in self.symctrls:\n exec('symlist.append(self.' + each + '.symname)')\n # plot loadings\n self.parent.do_plot(loadType=3, symcolours=collist, symsymbols=symlist)\n self.parent.load_idx = 3\n \n def on_btn_symbol(self, evt):\n # symbol select dialog\n btn = evt.GetEventObject()\n dlg = SymDialog(self, btn)\n pos = btn.ClientToScreen((0, 0))\n sz = btn.GetSize()\n dlg.SetPosition((pos[0]-155, pos[1] + sz[1]))\n dlg.ShowModal()\n \nclass SymDialog(wx.Dialog):\n\n def __init__(self, parent, btn):\n wx.Dialog.__init__(self, id=-1, name=u'SymDialog', parent=parent,\n pos=(589, 316), size=(156, 155),\n style=wx.DEFAULT_DIALOG_STYLE,\n title=u'Select Symbol')\n\n self._init_ctrls()\n self.btn = btn\n\n def _init_ctrls(self):\n # generated method, don't edit\n\n self.SetClientSize((140, 119))\n self.SetToolTip(u'')\n\n bmp = wx.Bitmap(op_join('bmp', 'square.bmp'), wx.BITMAP_TYPE_BMP)\n self.tbSquare = wx.BitmapButton(bitmap=bmp, id=-1, name=u'tbSquare',\n parent=self, pos=(0, 0),\n size=(69, 38), style=0)\n self.tbSquare.Bind(wx.EVT_BUTTON, self.on_tb_square)\n\n bmp = wx.Bitmap(op_join('bmp', 'circle.bmp'), wx.BITMAP_TYPE_BMP)\n self.tbCircle = wx.BitmapButton(bitmap=bmp, id=-1, name=u'tbCircle',\n parent=self, pos=(71, 0),\n size=(69, 38), style=0)\n self.tbCircle.Bind(wx.EVT_BUTTON, self.on_tb_circle)\n\n bmp = wx.Bitmap(op_join('bmp', 'plus.bmp'), wx.BITMAP_TYPE_BMP)\n self.tbPlus = wx.BitmapButton(bitmap=bmp, id=-1, name=u'tbPlus',\n parent=self, pos=(0, 40),\n size=(69, 38), style=0)\n self.tbPlus.Bind(wx.EVT_BUTTON, self.on_tb_plus)\n\n bmp = wx.Bitmap(op_join('bmp', 'triangle.bmp'), wx.BITMAP_TYPE_BMP)\n self.tbTriangleUp = wx.BitmapButton(bitmap=bmp, id=-1,\n name=u'tbTriangleUp', parent=self,\n pos=(71, 40),\n size=(69, 38), style=0)\n self.tbTriangleUp.Bind(wx.EVT_BUTTON, self.on_tb_triangle_up)\n\n bmp = wx.Bitmap(op_join('bmp', 'triangle_down.bmp'), wx.BITMAP_TYPE_BMP)\n self.tbTriangleDown = wx.BitmapButton(bitmap=bmp, id=-1,\n name=u'tbTriangleDown',\n parent=self, pos=(0, 80),\n size=(69, 38), style=0)\n self.tbTriangleDown.Bind(wx.EVT_BUTTON, self.on_tb_triangle_down)\n\n bmp = wx.Bitmap(op_join('bmp', 'cross.bmp'), wx.BITMAP_TYPE_BMP)\n self.tbCross = wx.BitmapButton(bitmap=bmp, id=-1, name=u'tbCross',\n parent=self, pos=(71, 80),\n size=(69, 38), style=0)\n self.tbCross.Bind(wx.EVT_BUTTON, self.on_tb_cross)\n\n self._init_sizers()\n\n def _init_sizers(self):\n # generated method, don't edit\n self.grs_symdialog = wx.GridSizer(cols=2, hgap=2, rows=3, vgap=2)\n\n self._init_coll_grs_symdialog_items(self.grs_symdialog)\n\n self.SetSizer(self.grs_symdialog)\n\n def _init_coll_grs_symdialog_items(self, parent):\n \"\"\"\"\"\"\n parent.Add(self.tbSquare, 0, border=0, flag=wx.EXPAND)\n parent.Add(self.tbCircle, 0, border=0, flag=wx.EXPAND)\n parent.Add(self.tbPlus, 0, border=0, flag=wx.EXPAND)\n parent.Add(self.tbTriangleUp, 0, border=0, flag=wx.EXPAND)\n parent.Add(self.tbTriangleDown, 0, border=0, flag=wx.EXPAND)\n parent.Add(self.tbCross, 0, border=0, flag=wx.EXPAND)\n \n def on_tb_square(self, _):\n self.btn.SetBitmapLabel(wx.Bitmap(op_join('bmp', 'square.bmp')))\n self.btn.symname = 'square'\n self.Destroy()\n\n def on_tb_circle(self, _):\n self.btn.SetBitmapLabel(wx.Bitmap(op_join('bmp', 'circle.bmp')))\n self.btn.symname = 'circle'\n self.Destroy()\n\n def on_tb_plus(self, _):\n self.btn.SetBitmapLabel(wx.Bitmap(op_join('bmp', 'plus.bmp')))\n self.btn.symname = 'plus'\n self.Destroy()\n\n def on_tb_triangle_up(self, _):\n self.btn.SetBitmapLabel(wx.Bitmap(op_join('bmp', 'triangle.bmp')))\n self.btn.symname = 'triangle'\n self.Destroy()\n\n def on_tb_triangle_down(self, _):\n bmp = wx.Bitmap(op_join('bmp', 'triangle_down.bmp'))\n self.btn.SetBitmapLabel(bmp)\n self.btn.symname = 'triangle_down'\n self.Destroy()\n\n def on_tb_cross(self, _):\n bmp = wx.Bitmap(op_join('bmp', 'cross.bmp'))\n self.btn.SetBitmapLabel(bmp)\n self.btn.symname = 'cross'\n self.Destroy()\n\nclass MyPlotCanvas(wlpc.PlotCanvas):\n def __init__(self, parent, id_, pos, size, style, name, toolbar):\n wlpc.PlotCanvas.__init__(self, parent, id_, pos, size, style, name)\n\n wlpc.PlotCanvas._interEnabled = False\n wlpc.PlotCanvas._justDragged = False\n self._interEnabled = False\n\n self.xSpec = 'min'\n self.ySpec = 'min'\n\n self.minXrange = 0\n self.maxXrange = 0\n self.minYrange = 0\n self.maxYrange = 0\n\n self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseRightDown)\n self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)\n\n self._init_utils()\n self.parent = parent\n self.tbMain = toolbar\n\n def _init_utils(self):\n self.plotMenu = wx.Menu(title='')\n\n self._init_plot_menu(self.plotMenu)\n\n def _init_plot_menu(self, parent):\n \n parent.Append(helpString='', id=MNUPLOTCOPY, kind=wx.ITEM_NORMAL,\n item='Copy Figure')\n parent.Append(helpString='', id=MNUPLOTCOORDS, kind=wx.ITEM_NORMAL,\n item='Copy Coordinates')\n parent.Append(helpString='', id=MNUPLOTPRINT, kind=wx.ITEM_NORMAL,\n item='Print')\n parent.Append(helpString='', id=MNUPLOTSAVE, kind=wx.ITEM_NORMAL,\n item='Save')\n\n self.Bind(wx.EVT_MENU, self.on_mnu_plot_copy, id=MNUPLOTCOPY)\n self.Bind(wx.EVT_MENU, self.on_mnu_plot_print, id=MNUPLOTPRINT)\n self.Bind(wx.EVT_MENU, self.on_mnu_plot_save, id=MNUPLOTSAVE)\n self.Bind(wx.EVT_MENU, self.on_mnu_plot_coords, id=MNUPLOTCOORDS)\n \n def on_mnu_plot_copy(self, _):\n # for windows\n self.Redraw(wx.MetafileDC()).SetClipboard()\n\n # for linux\n # wx.TheClipboard.Open()\n # wx.TheClipboard.SetData(self.Copy())\n # wx.TheClipboard.Close()\n \n def on_mnu_plot_print(self, _):\n self.Printout()\n \n def on_mnu_plot_save(self, _):\n self.SaveFile()\n \n # def OnMnuPlotProperties(self, event):\n # dlg = plotProperties(self)\n # dlg.SetSize((450, 350))\n # dlg.Center(wx.BOTH)\n #\n # # Set up dialog for specific cases\n # # dfa & pca score plots\n # if self.GetName() in ['plcDFAscores',\n # 'plcPCAscore', 'plcGaFeatPlot']:\n # dlg.scoreSets.Enable(True)\n # # pca score plots minus conf intervals\n # if self.GetName() in ['plcPCAscore', 'plcGaFeatPlot']:\n # dlg.tbConf.Enable(False)\n # dlg.tbConf.SetValue(False)\n # # ga-dfa score plots\n # if self.GetName() in ['plcGaModelPlot1']:\n # if self.prnt.prnt.splitPrnt.type in ['DFA']:\n # dlg.scoreSets.Enable(True)\n # if self.GetName() in ['plcPcaLoadsV', 'plcDfaLoadsV',\n # 'plcGaSpecLoad', 'plcPLSloading']:\n # dlg.loadSets.Enable(True)\n # dlg.Iconize(False)\n # dlg.ShowModal()\n \n def on_mnu_plot_coords(self, _):\n # send coords to clipboard\n getPoints = self.last_draw[0].objects\n coords = []\n for each in getPoints:\n # noinspection PyProtectedMember\n coords.extend(each._points.tolist())\n \n data = np.array2string(coords, separator='\\t')\n wx.TheClipboard.Open()\n wx.TheClipboard.SetData(wx.TextDataObject('X\\tY\\n' + data))\n wx.TheClipboard.Close()\n \n def OnMouseRightDown(self, event):\n pt = event.GetPosition()\n self.PopupMenu(self.plotMenu, pt) \n \n def OnMouseLeftDown(self, event):\n # put info in tb\n self.populate_toolbar()\n # get coords for zoom centre\n self._zoomCorner1[0], self._zoomCorner1[1] = self._getXY(event)\n self._screenCoordinates = np.array(event.GetPosition())\n if self._dragEnabled:\n self.SetCursor(self.GrabHandCursor)\n self.tbMain.canvas.CaptureMouse()\n if self._interEnabled:\n if self.last_draw is not None:\n graphics, xAxis, yAxis = self.last_draw\n xy = self.PositionScreenToUser(self._screenCoordinates)\n graphics.objects.append(\n PolyLine([[xy[0], yAxis[0]], [xy[0], yAxis[1]]],\n colour='red'))\n self._Draw(graphics, xAxis, yAxis)\n \n def populate_toolbar(self):\n # enable plot toolbar\n self.tbMain.Enable(True)\n self.tbMain.Refresh()\n \n # populate plot toolbar\n self.tbMain.canvas = self\n self.tbMain.graph = self.last_draw[0]\n \n self.tbMain.txtPlot.SetValue(self.tbMain.graph.title)\n self.tbMain.txtXlabel.SetValue(self.tbMain.graph.xLabel)\n self.tbMain.txtYlabel.SetValue(self.tbMain.graph.yLabel)\n \n self.tbMain.spnAxesFont.SetValue(self.fontSizeAxis)\n self.tbMain.spn_title.SetValue(self.fontSizeTitle)\n \n self.minXrange = self.xCurrentRange[0]\n self.maxXrange = self.xCurrentRange[1]\n self.minYrange = self.yCurrentRange[0]\n self.maxYrange = self.yCurrentRange[1]\n \n self.tbMain.Increment = (self.maxXrange - self.minXrange)/100\n \n self.tbMain.txtXmin.SetValue('%.2f' % self.minXrange)\n self.tbMain.txtXmax.SetValue('%.2f' % self.maxXrange)\n self.tbMain.txtYmax.SetValue('%.2f' % self.maxYrange)\n self.tbMain.txtYmin.SetValue('%.2f' % self.minYrange)\n \n # enable controls\n names = ['plcPcaLoadsV', 'plcDfaLoadsV', 'plcGaSpecLoad',\n 'plcPLSloading', 'plcGaModelPlot1', 'plcDFAscores',\n 'plcGaFeatPlot']\n\n if self.GetName() not in names:\n # disable for general case\n self.tbMain.tbConf.Enable(False)\n self.tbMain.tbPoints.Enable(False)\n self.tbMain.tbSymbols.Enable(False)\n \n if self.GetName() in ['plcPCAscore', 'plcGaFeatPlot']:\n self.tbMain.tbPoints.Enable(True)\n self.tbMain.tbSymbols.Enable(True)\n \n if len(self.GetName().split('plcPredPls')) > 1:\n if self.parent.prnt.prnt.prnt.data['plstype'] == 1:\n self.tbMain.tbPoints.Enable(True)\n self.tbMain.tbSymbols.Enable(True)\n else:\n self.tbMain.tbSymbols.Enable(True)\n \n if self.GetName() in ['plcDFAscores']:\n # dfa score plots\n self.tbMain.tbConf.Enable(True)\n self.tbMain.tbPoints.Enable(True)\n self.tbMain.tbSymbols.Enable(True)\n else:\n self.tbMain.tbConf.Enable(False)\n \n if len(self.GetName().split('plcGaModelPlot')) > 1:\n # ga-dfa score plots\n if self.parent.prnt.prnt.splitPrnt.dtype in ['DFA']:\n self.tbMain.tbConf.Enable(True)\n self.tbMain.tbPoints.Enable(True)\n self.tbMain.tbSymbols.Enable(True)\n else:\n self.tbMain.tbConf.Enable(False)\n self.tbMain.tbPoints.Enable(False)\n self.tbMain.tbSymbols.Enable(True)\n \n if self.GetName() in ['plcPcaLoadsV', 'plcDfaLoadsV', 'plcPLSloading']:\n self.tbMain.tbLoadLabels.Enable(True)\n self.tbMain.tbLoadLabStd1.Enable(True)\n self.tbMain.tbLoadLabStd2.Enable(True)\n self.tbMain.tbLoadSymStd2.Enable(True)\n self.tbMain.tbPoints.Enable(False)\n self.tbMain.tbSymbols.Enable(False)\n else:\n self.tbMain.tbLoadLabels.Enable(False)\n self.tbMain.tbLoadLabStd1.Enable(False)\n self.tbMain.tbLoadLabStd2.Enable(False)\n self.tbMain.tbLoadSymStd2.Enable(False)\n\n def enable_drag(self, value):\n \"\"\"Set True to enable drag.\"\"\"\n if value not in [True, False]:\n raise TypeError(\"Value should be True or False\")\n if value:\n if self.GetEnableZoom():\n self.enableZoom = False\n if self.get_enable_interactive():\n self.enable_interactive(False)\n self.SetCursor(self.HandCursor)\n else:\n self.SetCursor(wx.CROSS_CURSOR)\n self._dragEnabled = value\n\n def enable_interactive(self, value):\n \"\"\"Set True to enable interactive mode - RMJ 03/2008.\"\"\"\n if value not in [True, False]:\n raise TypeError(\"Value should be True or False\")\n if value:\n if self.GetEnableZoom():\n self.enableZoom = False\n if self.GetEnableDrag():\n self.enable_drag(False)\n self.SetCursor(wx.Cursor(wx.CURSOR_PENCIL))\n else:\n self.SetCursor(wx.CROSS_CURSOR)\n self._interEnabled = value\n\n def get_enable_interactive(self):\n return self._interEnabled\n \n\nclass Pca(wx.Panel):\n \"\"\"principal component analysis\n\n \"\"\"\n def __init__(self, parent, id_, pos, size, style, name):\n \"\"\"\"\"\"\n wx.Panel.__init__(self, id=wxID_PCA, name='Pca', parent=parent,\n pos=(-12, 22), size=(1024, 599),\n style=wx.TAB_TRAVERSAL)\n\n _, _, _, _, _ = id_, pos, size, style, name\n\n self.parent = parent\n self._init_ctrls()\n self._init_sizers()\n\n def _init_ctrls(self):\n \"\"\"\"\"\"\n self.SetClientSize((1016, 565))\n self.SetAutoLayout(True)\n self.SetToolTip('')\n\n self.plcPCeigs = MyPlotCanvas(id_=-1, name='plcPCeigs',\n parent=self, pos=(589, 283),\n size=(200, 200), style=0,\n toolbar=self.parent.parent.tbMain)\n self.plcPCeigs.SetToolTip('')\n self.plcPCeigs.fontSizeTitle = 10\n self.plcPCeigs.enableZoom = True\n self.plcPCeigs.fontSizeAxis = 8\n self.plcPCeigs.SetConstraints(\n LayoutAnchors(self.plcPCeigs, False, True, False, True))\n self.plcPCeigs.fontSizeLegend = 8\n\n self.plcPCvar = MyPlotCanvas(id_=-1, name='plcPCvar', parent=self,\n pos=(176, 283),\n size=(200, 200), style=0,\n toolbar=self.parent.parent.tbMain)\n self.plcPCvar.fontSizeAxis = 8\n self.plcPCvar.fontSizeTitle = 10\n self.plcPCvar.enableZoom = True\n self.plcPCvar.SetToolTip('')\n self.plcPCvar.fontSizeLegend = 8\n\n self.plcPCAscore = MyPlotCanvas(\n parent=self, id_=-1, name='plcPCAscore', pos=(0, 24),\n size=(200, 200), style=0, toolbar=self.parent.parent.tbMain)\n self.plcPCAscore.fontSizeTitle = 10\n self.plcPCAscore.fontSizeAxis = 8\n self.plcPCAscore.enableZoom = True\n self.plcPCAscore.enableLegend = True\n self.plcPCAscore.SetToolTip('')\n self.plcPCAscore.fontSizeLegend = 8\n\n self.plcPcaLoadsV = MyPlotCanvas(\n id_=-1, name='plcPcaLoadsV', parent=self, pos=(0, 24),\n size=(200, 200), style=0, toolbar=self.parent.parent.tbMain)\n self.plcPcaLoadsV.SetToolTip('')\n self.plcPcaLoadsV.fontSizeTitle = 10\n self.plcPcaLoadsV.enableZoom = True\n self.plcPcaLoadsV.fontSizeAxis = 8\n self.plcPcaLoadsV.enableLegend = True\n self.plcPcaLoadsV.fontSizeLegend = 8\n\n self.titleBar = TitleBar(\n self, id_=-1, text=\"Principal Component Analysis\",\n style=bp.BP_USE_GRADIENT, alignment=bp.BP_ALIGN_LEFT)\n\n def _init_sizers(self):\n \"\"\"\"\"\"\n self.bxsPca1 = wx.BoxSizer(orient=wx.HORIZONTAL)\n self.bxsPca2 = wx.BoxSizer(orient=wx.VERTICAL)\n self.grsPca1 = wx.GridSizer(cols=2, hgap=2, rows=2, vgap=2)\n\n self.bxsPca1.Add(self.bxsPca2, 1, border=0, flag=wx.EXPAND)\n\n self.bxsPca2.Add(self.titleBar, 0, border=0, flag=wx.EXPAND)\n self.bxsPca2.Add(self.grsPca1, 1, border=0, flag=wx.EXPAND)\n\n self.grsPca1.Add(self.plcPCAscore, 0, border=0, flag=wx.EXPAND)\n self.grsPca1.Add(self.plcPcaLoadsV, 0, border=0, flag=wx.EXPAND)\n self.grsPca1.Add(self.plcPCvar, 0, border=0, flag=wx.EXPAND)\n self.grsPca1.Add(self.plcPCeigs, 0, border=0, flag=wx.EXPAND)\n \n self.SetSizer(self.bxsPca1)\n\n def reset(self):\n self.titleBar.spnNumPcs1.Enable(0)\n self.titleBar.spnNumPcs2.Enable(0)\n self.titleBar.spnNumPcs1.SetValue(1)\n self.titleBar.spnNumPcs2.SetValue(2)\n \n objects = {'plcPCeigs': ['Eigenvalues', 'Principal Component', 'Eigenvalue'],\n 'plcPCvar': ['Percentage Explained Variance',\n 'Principal Component', 'Cumulative % Variance'],\n 'plcPCAscore': ['PCA Scores', 't[1]', 't[2]'],\n 'plcPcaLoadsV': ['PCA Loading', 'w[1]', 'w[2]']}\n\n # noinspection PyUnusedLocal, PyTypeChecker\n curve = PolyLine([[0, 0], [1, 1]], colour='white', width=1,\n style=wx.PENSTYLE_TRANSPARENT)\n \n for each in objects.keys():\n exec('self.' + each + '.Draw(PlotGraphics([curve], ' +\n 'objects[\"' + each + '\"][0], ' + 'objects[\"' + each +\n '\"][1], ' + 'objects[\"' + each + '\"][2]))')\n\n\nclass TitleBar(bp.ButtonPanel):\n def __init__(self, parent, id_, text, style, alignment):\n \"\"\"\"\"\"\n bp.ButtonPanel.__init__(self, parent=parent, id=-1,\n text=\"Principal Component Analysis\",\n agwStyle=bp.BP_USE_GRADIENT,\n alignment=bp.BP_ALIGN_LEFT)\n\n _, _, _, _ = id_, text, style, alignment\n\n self.data = None\n self.parent = parent\n self._init_btnpanel_ctrls()\n self.create_buttons()\n\n def _init_btnpanel_ctrls(self):\n \"\"\"\"\"\"\n self.Bind(wx.EVT_PAINT, self.on_btnpanel_paint)\n \n bmp = wx.Bitmap(op_join('bmp', 'run.png'), wx.BITMAP_TYPE_PNG)\n self.btnRunPCA = bp.ButtonInfo(self, -1, bmp, kind=wx.ITEM_NORMAL,\n shortHelp='Run PCA',\n longHelp='Run Principal Component Analysis')\n self.btnRunPCA.Enable(False)\n self.Bind(wx.EVT_BUTTON, self.on_btn_run_pca, id=self.btnRunPCA.GetId())\n\n bmp = wx.Bitmap(op_join('bmp', 'export.png'), wx.BITMAP_TYPE_PNG)\n self.btnExportPcaResults = bp.ButtonInfo(self, -1, bmp,\n kind=wx.ITEM_NORMAL,\n shortHelp='Export PCA Results',\n longHelp='Export PCA Results')\n self.btnExportPcaResults.Enable(False)\n self.Bind(wx.EVT_BUTTON, self.on_btn_export_pca_results,\n id=self.btnExportPcaResults.GetId())\n\n choices = ['Raw spectra', 'Processed spectra']\n self.cbxData = wx.Choice(choices=choices, id=-1, name='cbxData',\n parent=self, pos=(118, 23),\n size=(100, 23), style=0)\n self.cbxData.SetSelection(0)\n \n self.cbxPcaType = wx.Choice(choices=['NIPALS', 'SVD'], id=-1,\n name='cbxPcaType', parent=self,\n pos=(56, 23),\n size=(64, 23), style=0)\n self.cbxPcaType.Bind(wx.EVT_COMBOBOX, self.on_cbx_pca_type, id=ID_PCATYPE)\n self.cbxPcaType.SetSelection(0)\n \n choices = ['Correlation matrix', 'Covariance matrix']\n self.cbxPreprocType = wx.Choice(choices=choices, id=-1,\n name='cbxPreprocType', parent=self,\n pos=(118, 23),\n size=(110, 23), style=0, )\n self.cbxPreprocType.SetSelection(0)\n \n self.spnPCAnum = wx.SpinCtrl(id=ID_SPNPCS, initial=3, max=100,\n min=3, name='spnPCAnum', parent=self,\n pos=(112, 158),\n size=(46, 23),\n style=wx.SP_ARROW_KEYS)\n self.spnPCAnum.SetToolTip('')\n self.spnPCAnum.SetValue(3)\n \n self.spnNumPcs1 = wx.SpinCtrl(id=ID_NUMPCS1, initial=1,\n max=100, min=1, name='spnNumPcs1',\n parent=self, pos=(240, 184),\n size=(46, 23),\n style=wx.SP_ARROW_KEYS)\n self.spnNumPcs1.Enable(0)\n self.spnNumPcs1.Bind(wx.EVT_SPINCTRL, self.on_spn_num_pcs1, id=-1)\n \n self.spnNumPcs2 = wx.SpinCtrl(id=ID_NUMPCS2, initial=1, max=100, min=1,\n name='spnNumPcs2', parent=self,\n pos=(240, 184),\n size=(46, 23),\n style=wx.SP_ARROW_KEYS)\n self.spnNumPcs2.Enable(0)\n self.spnNumPcs2.Bind(wx.EVT_SPINCTRL, self.on_spn_num_pcs2, id=-1)\n\n def create_buttons(self):\n self.Freeze()\n self.set_properties()\n style = wx.TRANSPARENT_WINDOW\n\n self.AddControl(self.cbxData)\n self.AddControl(self.cbxPreprocType)\n self.AddControl(self.cbxPcaType)\n self.AddControl(GenStaticText(self, -1, 'No. PCs:', style=style))\n self.AddControl(self.spnPCAnum)\n self.AddSeparator()\n self.AddControl(GenStaticText(self, -1, 'PC', style=style))\n self.AddControl(self.spnNumPcs1)\n self.AddControl(GenStaticText(self, -1, ' vs. ', style=style))\n self.AddControl(self.spnNumPcs2)\n self.AddSeparator()\n self.AddButton(self.btnRunPCA)\n self.AddSeparator()\n self.AddButton(self.btnExportPcaResults)\n \n self.Thaw()\n self.DoLayout()\n\n # noinspection PyMethodMayBeStatic\n def on_btnpanel_paint(self, event):\n event.Skip()\n \n def set_properties(self):\n\n # Sets the colours for the two demos: called only if the user didn't\n # modify the colours and sizes using the Settings Panel\n bpArt = self.GetBPArt()\n \n # set the color the text is drawn with\n bpArt.SetColour(bp.BP_TEXT_COLOUR, wx.WHITE)\n\n background = self.GetBackgroundColour() \n bpArt.SetColour(bp.BP_TEXT_COLOUR, wx.BLUE)\n bpArt.SetColour(bp.BP_BORDER_COLOUR,\n bp.BrightenColour(background, 0.85))\n bpArt.SetColour(bp.BP_SEPARATOR_COLOUR,\n bp.BrightenColour(background, 0.85))\n bpArt.SetColour(bp.BP_BUTTONTEXT_COLOUR, wx.BLACK)\n bpArt.SetColour(bp.BP_SELECTION_BRUSH_COLOUR, wx.Colour(242, 242, 235))\n bpArt.SetColour(bp.BP_SELECTION_PEN_COLOUR, wx.Colour(206, 206, 195))\n\n def on_btn_run_pca(self, _):\n self.run_pca()\n \n def on_btn_export_pca_results(self, _):\n dlg = wx.FileDialog(self, \"Choose a file\", \".\", \"\", \n \"Any files (*.*)|*.*\", wx.FD_SAVE)\n try:\n if dlg.ShowModal() == wx.ID_OK:\n saveFile = dlg.GetPath()\n scrs = np.array2string(self.data['pcscores'], separator='\\t')\n lods = np.array2string(self.data['pcloads'], separator='\\t')\n eign = np.array2string(self.data['pceigs'], separator='\\t')\n pcex = np.array2string(self.data['pcpervar'], separator='\\t')\n out = '#PRINCIPAL_COMPONENT_SCORES\\n' + scrs + '\\n' +\\\n '#PRINCIPAL_COMPONENT_LOADINGS\\n' + lods + '\\n' +\\\n '#EIGENVALUES\\n' + eign + '\\n' +\\\n '#CUMULATIVE_PERCENTAGE_EXPLAINED_VARIANCE\\n' + pcex + '\\n'\n\n with open(saveFile, 'w') as f:\n f.write(out)\n\n finally:\n dlg.Destroy()\n \n def on_cbx_pca_type(self, _):\n if self.cbxPcaType.GetSelection() == 1:\n self.spnPCAnum.Enable(0)\n else:\n self.spnPCAnum.Enable(1)\n \n def get_data(self, data):\n self.data = data\n \n def run_pca(self):\n \"\"\"Run principal component analysis\n\n \"\"\"\n xdata = None\n\n try:\n self.spnNumPcs1.Enable(1)\n self.spnNumPcs2.Enable(1)\n self.spnNumPcs1.SetValue(1)\n self.spnNumPcs2.SetValue(2)\n \n if self.cbxData.GetSelection() == 0:\n xdata = self.data['rawtrunc']\n elif self.cbxData.GetSelection() == 1:\n xdata = self.data['proctrunc']\n \n if self.cbxPreprocType.GetSelection() == 0:\n self.data['pcatype'] = 'covar'\n elif self.cbxPreprocType.GetSelection() == 1:\n self.data['pcatype'] = 'corr'\n \n if self.cbxPcaType.GetSelection() == 1:\n # run PCA using SVD\n scores, loads, self.data['pcpervar'], eigs = \\\n chemtrics.pca_svd(xdata, self.data['pcatype'])\n \n self.data['pcscores'] = scores[:, 0: len(eigs)]\n self.data['pcloads'] = loads[0: len(eigs), :]\n self.data['pceigs'] = eigs\n self.data['niporsvd'] = 'svd'\n \n elif self.cbxPcaType.GetSelection() == 0:\n # run PCA using NIPALS\n self.data['pcscores'], self.data['pcloads'], self.data['pcpervar'], self.data['pceigs'] = \\\n chemtrics.pca_nipals(xdata, self.spnPCAnum.GetValue(),\n self.data['pcatype'],\n self.parent.parent.parent.sbMain)\n \n self.data['niporsvd'] = 'nip'\n \n # Enable ctrls\n self.btnExportPcaResults.Enable(1)\n self.spnNumPcs1.SetRange(1, len(self.data['pceigs']))\n self.spnNumPcs1.SetValue(1)\n self.spnNumPcs2.SetRange(1, len(self.data['pceigs']))\n self.spnNumPcs2.SetValue(2)\n \n # check for metadata & setup limits for dfa\n tbar = self.parent.parent.parent.plDfa.titleBar\n klass = self.data['class']\n if (sum(klass[:, 0]) != 0) and (klass is not None):\n tbar.cbxData.SetSelection(0)\n tbar.spnDfaPcs.SetRange(2, len(self.data['pceigs']))\n tbar.spnDfaDfs.SetRange(1, len(np.unique(klass[:, 0])) - 1)\n \n # plot results\n self.plot_pca()\n \n except Exception as error:\n error_box(self, '%s' % str(error))\n raise\n \n def plot_pca(self):\n # Plot pca scores and loadings\n pc1 = self.spnNumPcs1.GetValue()\n pc2 = self.spnNumPcs2.GetValue()\n\n xL = 't[' + str(pc1) + '] (' + \\\n '%.2f' % (self.data['pcpervar'][pc1] -\n self.data['pcpervar'][pc1 - 1]) + '%)'\n \n yL = 't[' + str(pc2) + '] (' + \\\n '%.2f' % (self.data['pcpervar'][pc2] -\n self.data['pcpervar'][pc2-1]) + '%)'\n \n plot_scores(self.parent.plcPCAscore, self.data['pcscores'],\n cl=self.data['class'][:, 0],\n labels=self.data['label'],\n validation=self.data['validation'],\n col1=pc1-1, col2=pc2-1, pconf=False,\n title='PCA Scores', xLabel=xL, yLabel=yL, xval=False,\n symb=self.parent.parent.parent.tbMain.tbSymbols.GetValue(),\n text=self.parent.parent.parent.tbMain.tbPoints.GetValue(),\n usecol=[], usesym=[])\n \n # Plot loadings\n if pc1 != pc2:\n plot_loads(self.parent.plcPcaLoadsV,\n np.transpose(self.data['pcloads']),\n xaxis=self.data['indlabels'], col1=pc1-1,\n col2=pc2-1, title='PCA Loadings',\n xLabel='w[' + str(pc1) + ']',\n yLabel='w[' + str(pc2) + ']',\n type=self.parent.prnt.parent.tbMain.get_load_plot_idx(),\n usecol=[], usesym=[])\n else:\n idx = pc1-1\n plot_line(self.parent.plcPcaLoadsV,\n self.data['pcloads'],\n xaxis=self.data['xaxis'], rownum=idx, tit='PCA Loadings',\n type='single', xLabel='Variable',\n yLabel='w['+str(idx+1)+']', wdth=1, ledge=[])\n \n # Plot % variance\n plot_line(self.parent.plcPCvar, np.transpose(self.data['pcpervar']),\n xaxis=np.arange(0, len(self.data['pcpervar']))[:, nax],\n rownum=0, tit='Percentage Explained Variance', type='single',\n xLabel='Principal Component', yLabel='Cumulative % Variance',\n wdth=3, ledge=[])\n \n # Plot eigenvalues\n plot_line(self.parent.plcPCeigs, np.transpose(self.data['pceigs']),\n xaxis=np.arange(1, len(self.data['pceigs']) + 1)[:, nax],\n rownum=0, tit='Eigenvalues', xLabel='Principal Component',\n yLabel='Eigenvalue', wdth=3, type='single', ledge=[])\n \n # make sure ctrls enabled\n self.spnNumPcs1.Enable(True)\n self.spnNumPcs2.Enable(True)\n self.btnExportPcaResults.Enable(True)\n \n def on_spn_num_pcs1(self, _):\n pc1 = self.spnNumPcs1.GetValue()\n pc2 = self.spnNumPcs2.GetValue()\n self.plot_pca()\n set_btn_state(pc1, pc2, self.parent.prnt.prnt.tbMain)\n \n def on_spn_num_pcs2(self, _):\n pc1 = self.spnNumPcs1.GetValue()\n pc2 = self.spnNumPcs2.GetValue()\n self.plot_pca()\n set_btn_state(pc1, pc2, self.parent.prnt.prnt.tbMain)\n\n\nclass PlotProperties(wx.Dialog):\n \"\"\"\"\"\"\n def __init__(self, parent):\n \"\"\"\"\"\"\n wx.Dialog.__init__(self, id=-1, name='', parent=parent,\n pos=(0, 0), size=(530, 480),\n style=wx.MAXIMIZE_BOX | wx.DEFAULT_DIALOG_STYLE,\n title='Plot Properties')\n\n self._init_plot_prop_ctrls()\n self._init_plot_prop_sizers()\n self._init_grs_df_scores()\n self._init_grs_loads()\n\n self.foldPnl.Expand(self.genSets)\n self.foldPnl.Collapse(self.scoreSets)\n self.foldPnl.Collapse(self.loadSets)\n\n self.graph = parent.last_draw[0]\n self.canvas = parent\n\n self.minXrange = parent.get_x_current_range()[0]\n self.maxXrange = parent.get_x_current_range()[1]\n self.minYrange = parent.get_y_current_range()[0]\n self.maxYrange = parent.get_y_current_range()[1]\n\n self.Increment = (self.maxXrange - self.minXrange) / 100\n\n self.txtXmin.SetValue('%.3f' % self.minXrange)\n self.txtXmax.SetValue('%.3f' % self.maxXrange)\n self.txtYmin.SetValue('%.3f' % self.minYrange)\n self.txtYmax.SetValue('%.3f' % self.maxYrange)\n\n self.txtTitle.SetValue(self.graph.get_title())\n self.txtXlabel.SetValue(self.graph.get_xlabel())\n self.txtYlabel.SetValue(self.graph.get_ylabel())\n\n self.spnFontSizeAxes.SetValue(parent.get_font_size_axis())\n self.spnFontSizeTitle.SetValue(parent.get_font_size_title())\n\n if self.canvas.get_enable_grid():\n self.tbGrid.SetValue(1)\n if self.canvas.get_enable_zoom():\n self.tbZoom.SetValue(1)\n if self.canvas.get_enable_drag():\n self.tbDrag.SetValue(1)\n if self.canvas.get_enable_point_label():\n self.tbPointLabel.SetValue(1)\n\n def _init_grs_df_scores(self):\n\n self.grsDfScores = wx.GridSizer(cols=2, hgap=4, rows=2, vgap=4)\n\n self._init_coll_grs_df_scores(self.grsDfScores)\n\n self.scorePnl.SetSizer(self.grsDfScores)\n\n def _init_coll_grs_df_scores(self, parent):\n # generated method, don't edit\n\n parent.Add(self.tbConf, 0, border=0, flag=wx.EXPAND)\n parent.Add(self.tbPoints, 0, border=0, flag=wx.EXPAND)\n parent.Add(self.tbSymbols, 0, border=0, flag=wx.EXPAND)\n \n def _init_grs_loads(self):\n # generated method, don't edit\n self.grsLoadings = wx.GridSizer(cols=2, hgap=4, rows=2, vgap=4)\n\n self._init_coll_grs_loads(self.grsLoadings)\n\n self.loadPnl.SetSizer(self.grsLoadings)\n \n def _init_coll_grs_loads(self, parent):\n # generated method, don't edit\n parent.Add(self.tbLoadLabels, 0, border=0, flag=wx.EXPAND)\n parent.Add(self.tbLoadLabStd1, 0, border=0, flag=wx.EXPAND)\n parent.Add(self.tbLoadLabStd2, 0, border=0, flag=wx.EXPAND)\n parent.Add(self.tbLoadSymStd2, 0, border=0, flag=wx.EXPAND)\n \n def _init_coll_gbs_plot_props(self, parent):\n # generated method, don't edit\n flag = wx.EXPAND\n parent.Add(self.stTitle, (0, 0), border=4, flag=flag, span=(1, 1))\n parent.Add(self.txtTitle, (0, 1), border=4, flag=flag, span=(1, 5))\n parent.Add(wx.StaticText(self.genPnl, -1, 'Axes font',\n style=wx.ALIGN_LEFT),\n (1, 0), flag=flag, span=(1, 1))\n parent.Add(self.spnFontSizeAxes, (1, 1), border=4, flag=flag,\n span=(1, 1))\n parent.Add(wx.StaticText(self.genPnl, -1, 'Title font',\n style=wx.ALIGN_LEFT),\n (1, 2), flag=flag, span=(1, 1))\n parent.Add(self.spnFontSizeTitle, (1, 3), border=4, flag=flag,\n span=(1, 1))\n parent.Add(self.stXlabel, (2, 0), border=4, flag=flag, span=(1, 1))\n parent.Add(self.txtXlabel, (2, 1), border=4, flag=flag, span=(1, 5))\n parent.Add(self.stYlabel, (3, 0), border=4, flag=flag, span=(1, 1))\n parent.Add(self.txtYlabel, (3, 1), border=4, flag=flag, span=(1, 5))\n parent.Add(self.stXfrom, (4, 0), border=4, flag=flag, span=(1, 1))\n parent.Add(self.txtXmin, (4, 1), border=4, flag=flag, span=(1, 1))\n parent.Add(self.spnXmin, (4, 2), border=4, flag=flag, span=(1, 1))\n parent.Add(self.stXto, (4, 3), border=4, flag=flag, span=(1, 1))\n parent.Add(self.txtXmax, (4, 4), border=4, flag=flag, span=(1, 1))\n parent.Add(self.spnXmax, (4, 5), border=4, flag=flag, span=(1, 1))\n parent.Add(self.stYfrom, (5, 0), border=4, flag=flag, span=(1, 1))\n parent.Add(self.txtYmin, (5, 1), border=4, flag=flag, span=(1, 1))\n parent.Add(self.spnYmin, (5, 2), border=4, flag=flag, span=(1, 1))\n parent.Add(self.stYto, (5, 3), border=4, flag=flag, span=(1, 1))\n parent.Add(self.txtYmax, (5, 4), border=4, flag=flag, span=(1, 1))\n parent.Add(self.spnYmax, (5, 5), border=4, flag=flag, span=(1, 1))\n parent.Add(self.tbDrag, (6, 1), border=4, flag=flag, span=(1, 1))\n parent.Add(self.tbGrid, (6, 2), border=4, flag=flag, span=(1, 1))\n parent.Add(self.tbPointLabel, (6, 3), border=4, flag=flag, span=(1, 1))\n parent.Add(self.tbZoom, (6, 4), border=4, flag=flag, span=(1, 1))\n parent.Add(self.cbApply, (7, 0), border=4, flag=flag, span=(1, 1))\n parent.Add(self.btnApply, (7, 1), border=4, flag=flag, span=(1, 5))\n # parent.AddSpacer((8, 8), (8, 0), flag=flag, span=(2, 6))\n\n # noinspection PyMethodMayBeStatic\n def _init_coll_gbs_plot_props_growables(self, parent):\n # generated method, don't edit\n for col in range(6):\n parent.AddGrowableCol(col)\n\n def _init_plot_prop_sizers(self):\n # generated method, don't edit\n self.gbsPlotProps = wx.GridBagSizer(8, 8)\n self.gbsPlotProps.SetCols(6)\n self.gbsPlotProps.SetRows(6)\n self.gbsPlotProps.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)\n self.gbsPlotProps.SetMinSize((250, 439))\n self.gbsPlotProps.SetEmptyCellSize((0, 0))\n self.gbsPlotProps.SetFlexibleDirection(wx.HORIZONTAL)\n\n self._init_coll_gbs_plot_props(self.gbsPlotProps)\n self._init_coll_gbs_plot_props_growables(self.gbsPlotProps)\n\n self.genPnl.SetSizer(self.gbsPlotProps)\n\n def _init_plot_prop_ctrls(self):\n\n self.SetAutoLayout(True)\n \n self.foldPnl = fpb.FoldPanelBar(self, -1, wx.DefaultPosition,\n (525, 450),\n fpb.FPB_EXCLUSIVE_FOLD)\n self.foldPnl.SetConstraints(\n LayoutAnchors(self.foldPnl, True, True, True, True))\n self.foldPnl.SetAutoLayout(True)\n \n icons = wx.ImageList(16, 16)\n icons.Add(wx.Bitmap(op_join('bmp', 'arrown.png'), wx.BITMAP_TYPE_PNG))\n icons.Add(wx.Bitmap(op_join('bmp', 'arrows.png'), wx.BITMAP_TYPE_PNG))\n \n self.genSets = self.foldPnl.AddFoldPanel(\"General properties\", \n collapsed=True,\n foldIcons=icons)\n \n self.scoreSets = self.foldPnl.AddFoldPanel(\"Score plots\", \n collapsed=True,\n foldIcons=icons)\n self.scoreSets.Enable(False)\n \n self.loadSets = self.foldPnl.AddFoldPanel(\"Loadings plots\", \n collapsed=True,\n foldIcons=icons)\n self.loadSets.Enable(False)\n \n self.genPnl = wx.Panel(id=-1, name='genPnl', parent=self.genSets,\n pos=(0, 0), size=(20, 250),\n style=wx.TAB_TRAVERSAL)\n self.genPnl.SetToolTip('')\n \n self.scorePnl = wx.Panel(id=-1, name='scorePnl', parent=self.scoreSets,\n pos=(0, 0), size=(20, 100),\n style=wx.TAB_TRAVERSAL)\n self.scorePnl.SetToolTip('') \n \n self.loadPnl = wx.Panel(id=-1, name='loadPnl', parent=self.loadSets,\n pos=(0, 0), size=(20, 100),\n style=wx.TAB_TRAVERSAL)\n self.loadPnl.SetToolTip('') \n \n self.stTitle = wx.StaticText(id=-1, label='Title', name=u'stTitle',\n parent=self.genPnl, pos=(0, 0),\n size=(21, 24), style=0)\n self.stTitle.SetToolTip('')\n\n self.stYfrom = wx.StaticText(id=-1, label=u'Y-Axis From:',\n name=u'stYfrom', parent=self.genPnl,\n pos=(0, 131), size=(42, 24),\n style=0)\n self.stYfrom.SetToolTip('')\n\n self.stYto = wx.StaticText(id=-1, label='To:', name=u'stYto',\n parent=self.genPnl, pos=(144, 131),\n size=(40, 21), style=0)\n self.stYto.SetToolTip('')\n\n self.stXfrom = wx.StaticText(id=-1, label=u'X-Axis From:',\n name=u'stXfrom', parent=self.genPnl,\n pos=(0, 103), size=(40, 21),\n style=0)\n self.stXfrom.SetToolTip('')\n\n self.stXto = wx.StaticText(id=-1, label='To:', name=u'stXto',\n parent=self.genPnl, pos=(144, 103),\n size=(40, 21), style=0)\n self.stXto.SetToolTip('')\n\n self.stXlabel = wx.StaticText(id=-1, label='X label', name=u'stXlabel',\n parent=self.genPnl, pos=(0, 53),\n size=(40, 21), style=0)\n self.stXlabel.SetToolTip('')\n\n self.stYlabel = wx.StaticText(id=-1, label='Y label', name=u'stYlabel',\n parent=self.genPnl, pos=(0, 78),\n size=(40, 21), style=0)\n self.stYlabel.SetToolTip('')\n\n self.txtTitle = wx.TextCtrl(id=-1, name='txtTitle', parent=self.genPnl,\n pos=(15, 0), size=(40, 21),\n style=0, value='')\n self.txtTitle.SetToolTip('')\n self.txtTitle.Bind(wx.EVT_TEXT, self.on_txt_title)\n\n self.txtYlabel = wx.TextCtrl(id=-1, name='txtYlabel', parent=self.genPnl,\n pos=(15, 78), size=(40, 21),\n style=0, value='')\n self.txtYlabel.SetToolTip('')\n\n self.txtXlabel = wx.TextCtrl(id=-1, name='txtXlabel',\n parent=self.genPnl, pos=(15, 53),\n size=(40, 21), style=0, value='')\n self.txtXlabel.SetToolTip('')\n\n self.txtXmin = wx.TextCtrl(id=-1, name='txtXmin',\n parent=self.genPnl, pos=(15, 103),\n size=(40, 21), style=0, value='')\n self.txtXmin.SetToolTip('')\n\n self.spnXmin = wx.SpinButton(id=-1, name='spnXmin',\n parent=self.genPnl, pos=(96, 103),\n size=(15, 21), style=wx.SP_VERTICAL)\n self.spnXmin.SetToolTip('')\n self.spnXmin.Bind(wx.EVT_SPIN_DOWN, self.on_spn_xmin_down)\n self.spnXmin.Bind(wx.EVT_SPIN_UP, self.on_spn_xmin_up)\n self.spnXmin.Bind(wx.EVT_SPIN, self.on_spn_xmin)\n\n self.spnXmax = wx.SpinButton(id=-1, name='spnXmax',\n parent=self.genPnl, pos=(240, 103),\n size=(15, 21), style=wx.SP_VERTICAL)\n self.spnXmax.SetToolTip('')\n self.spnXmax.Bind(wx.EVT_SPIN_DOWN, self.on_spn_xmax_down)\n self.spnXmax.Bind(wx.EVT_SPIN_UP, self.on_spn_xmax_up)\n self.spnXmax.Bind(wx.EVT_SPIN, self.on_spn_xmax)\n\n self.spnYmax = wx.SpinButton(id=-1, name='spnYmax',\n parent=self.genPnl, pos=(240, 131),\n size=(15, 21), style=wx.SP_VERTICAL)\n self.spnYmax.SetToolTip('')\n self.spnYmax.Bind(wx.EVT_SPIN_DOWN, self.on_spn_ymax_down)\n self.spnYmax.Bind(wx.EVT_SPIN_UP, self.on_spn_ymax_up)\n self.spnYmax.Bind(wx.EVT_SPIN, self.on_spn_ymax)\n\n self.spnYmin = wx.SpinButton(id=-1, name='spnYmin',\n parent=self.genPnl, pos=(96, 131),\n size=(15, 21), style=wx.SP_VERTICAL)\n self.spnYmin.SetToolTip('')\n self.spnYmin.Bind(wx.EVT_SPIN_DOWN, self.on_spn_ymin_down)\n self.spnYmin.Bind(wx.EVT_SPIN_UP, self.on_spn_ymin_up)\n self.spnYmin.Bind(wx.EVT_SPIN, self.on_spn_ymin)\n\n self.txtXmax = wx.TextCtrl(id=-1, name='txtXmax', parent=self.genPnl,\n pos=(192, 103), size=(40, 21),\n style=0, value='')\n self.txtXmax.SetToolTip('')\n\n self.txtYmax = wx.TextCtrl(id=-1, name='txtYmax', parent=self.genPnl,\n pos=(192, 131), size=(40, 21),\n style=0, value='')\n self.txtYmax.SetToolTip('')\n\n self.txtYmin = wx.TextCtrl(id=-1, name='txtYmin',\n parent=self.genPnl, pos=(15, 131),\n size=(40, 21), style=0, value='')\n self.txtYmin.SetToolTip('')\n\n self.stFont = wx.StaticText(id=-1, name=u'stFont',\n label='Font size axes and title (pt)',\n parent=self.genPnl, pos=(0, 28),\n size=(40, 21), style=0)\n self.stFont.SetToolTip('')\n\n self.spnFontSizeAxes = wx.SpinCtrl(id=-1, name='spnFontSizeAxes',\n initial=8, max=76, min=4,\n parent=self.genPnl,\n pos=(15, 28),\n size=(40, 21),\n style=wx.SP_ARROW_KEYS)\n self.spnFontSizeAxes.SetToolTip('')\n self.spnFontSizeAxes.SetValue(8)\n self.spnFontSizeAxes.SetRange(4, 76)\n self.spnFontSizeAxes.Bind(wx.EVT_SPIN, self.on_spn_font_size_axes)\n \n self.spnFontSizeTitle = wx.SpinCtrl(id=-1, initial=8, max=76, min=4,\n name='spnFontSizeTitle',\n parent=self.genPnl,\n pos=(15, 28),\n size=(40, 21),\n style=wx.SP_ARROW_KEYS)\n self.spnFontSizeTitle.SetToolTip('')\n self.spnFontSizeTitle.SetValue(8)\n self.spnFontSizeTitle.SetRange(4, 76)\n self.spnFontSizeTitle.Bind(wx.EVT_SPIN, self.on_spn_font_size_title)\n \n self.tbGrid = wxTogBut(id=-1, name='tbGrid', label='Grid',\n parent=self.genPnl, pos=(248, 48),\n size=(40, 21), style=0)\n self.tbGrid.SetValue(False)\n self.tbGrid.SetToolTip('')\n self.tbGrid.Bind(wx.EVT_BUTTON, self.on_tb_grid)\n \n self.tbDrag = wxTogBut(id=-1, name='tbDrag', label='Drag',\n parent=self.genPnl, pos=(248, 48),\n size=(40, 21), style=0)\n self.tbDrag.SetValue(False)\n self.tbDrag.SetToolTip('')\n self.tbDrag.Bind(wx.EVT_BUTTON, self.on_tb_drag_button)\n \n self.tbPointLabel = wxTogBut(id=-1, label='Points',\n name='tbPointLabel', parent=self.genPnl,\n pos=(248, 48),\n size=(40, 21), style=0)\n self.tbPointLabel.SetValue(False)\n self.tbPointLabel.SetToolTip('')\n self.tbPointLabel.Bind(wx.EVT_BUTTON, self.on_tb_point_label)\n \n self.tbZoom = wxTogBut(id=-1, label='zoom', name='tbZoom',\n parent=self.genPnl, pos=(248, 48),\n size=(40, 21), style=0)\n self.tbZoom.SetValue(True)\n self.tbZoom.SetToolTip('')\n self.tbZoom.Bind(wx.EVT_BUTTON, self.on_tb_zoom_button)\n \n self.cbApply = wx.CheckBox(id=-1, name='cbApply',\n label='Immediate Apply',\n parent=self.genPnl, pos=(48, 96),\n size=(70, 13), style=0)\n \n self.btnApply = wx.Button(id=-1, label='Apply & Close',\n name='btnApply', parent=self.genPnl,\n pos=(192, 136),\n size=(40, 21), style=0)\n self.btnApply.Bind(wx.EVT_BUTTON, self.on_btn_apply)\n \n self.tbConf = wxTogBut(id=-1, name='tbConf',\n label='95% Confidence Circles',\n parent=self.scorePnl, pos=(248, 48),\n size=(40, 21))\n self.tbConf.SetValue(True)\n self.tbConf.SetToolTip('')\n self.tbConf.Bind(wx.EVT_BUTTON, self.on_tb_conf)\n \n self.tbPoints = wxTogBut(id=-1, label='Labels',\n name='tbPoints', parent=self.scorePnl,\n pos=(248, 48), size=(40, 21))\n self.tbPoints.SetValue(True)\n self.tbPoints.SetToolTip('')\n self.tbPoints.Bind(wx.EVT_BUTTON, self.on_tb_points)\n \n self.tbSymbols = wxTogBut(id=-1, name='tbSymbols', label='Symbols',\n parent=self.scorePnl, pos=(248, 48),\n size=(40, 21))\n self.tbSymbols.SetValue(False)\n self.tbSymbols.SetToolTip('')\n self.tbSymbols.Bind(wx.EVT_BUTTON, self.on_tb_symbols)\n \n self.tbLoadLabels = wx.Button(id=-1, name='tbLoadLabels',\n label='Labels', parent=self.loadPnl,\n pos=(248, 48),\n size=(40, 21))\n self.tbLoadLabels.SetToolTip('')\n self.tbLoadLabels.Bind(wx.EVT_BUTTON, self.on_tb_load_labels)\n \n self.tbLoadLabStd1 = wx.Button(id=-1, name='tbLoadLabStd1',\n label='Labels & 1 Std',\n parent=self.loadPnl,\n pos=(248, 48),\n size=(40, 21))\n self.tbLoadLabStd1.SetToolTip('')\n self.tbLoadLabStd1.Bind(wx.EVT_BUTTON, self.on_tb_load_lab_std1)\n \n self.tbLoadLabStd2 = wx.Button(id=-1, name='tbLoadLabStd2',\n label='Labels & 2 Std',\n parent=self.loadPnl,\n pos=(248, 48),\n size=(40, 21))\n self.tbLoadLabStd2.SetToolTip('')\n self.tbLoadLabStd2.Bind(wx.EVT_BUTTON, self.on_tb_load_lab_std2)\n \n self.tbLoadSymStd2 = wx.Button(id=-1, label='Symbols & 2 Std',\n name='tbLoadSymStd2',\n parent=self.loadPnl,\n pos=(248, 48),\n size=(40, 21))\n self.tbLoadSymStd2.SetToolTip('')\n self.tbLoadSymStd2.Bind(wx.EVT_BUTTON, self.on_tb_load_sym_std2)\n \n style = fpb.FPB_ALIGN_WIDTH\n self.foldPnl.AddFoldPanelWindow(self.genSets, self.genPnl, style)\n self.foldPnl.AddFoldPanelWindow(self.scoreSets, self.scorePnl, style)\n self.foldPnl.AddFoldPanelWindow(self.loadSets, self.loadPnl, style)\n \n # self.btnFont = wx.Button(id_=-1, label='Font',\n # name='btnFont', parent=self.genSets, pos=(192, 136),\n # size=(40, 21), style=0)\n # self.btnFont.Bind(wx.EVT_BUTTON, self.OnBtnFont)\n \n def on_tb_load_labels(self, _):\n # plot loadings\n self.do_plot(loadType=0)\n \n def on_tb_load_lab_std1(self, _):\n # plot loadings\n self.do_plot(loadType=1)\n \n def on_tb_load_lab_std2(self, _):\n # plot loadings\n self.do_plot(loadType=2)\n \n def on_tb_load_sym_std2(self, _):\n # plot loadings\n self.do_plot(loadType=3)\n \n def on_tb_conf(self, _):\n if (self.tbPoints.GetValue() is False) & \\\n (self.tbConf.GetValue() is False) & \\\n (self.tbSymbols.GetValue() is False) is False:\n # plot scores\n self.do_plot()\n \n def on_tb_points(self, _):\n if (self.tbPoints.GetValue() is False) & \\\n (self.tbConf.GetValue() is False) & \\\n (self.tbSymbols.GetValue() is False) is False:\n # plot scores\n self.do_plot()\n \n def on_tb_symbols(self, _):\n if (self.tbPoints.GetValue() is False) & \\\n (self.tbConf.GetValue() is False) & \\\n (self.tbSymbols.GetValue() is False) is False:\n # plot scores\n self.do_plot()\n \n def do_plot(self, loadType=0):\n tbar = self.canvas.prnt.titleBar\n ptbar = self.canvas.prnt.prnt.splitPrnt.titleBar\n pprnt = self.canvas.prnt.prnt.prnt.splitPrnt\n if self.canvas.GetName() in ['plcDFAscores']:\n plot_scores(self.canvas, tbar.data['dfscores'],\n cl=tbar.data['class'][:, 0],\n labels=tbar.data['label'],\n validation=tbar.data['validation'],\n col1=tbar.spnDfaScore1.GetValue() - 1,\n col2=tbar.spnDfaScore2.GetValue() - 1,\n title=self.graph.title, xLabel=self.graph.xLabel,\n yLabel=self.graph.yLabel,\n xval=tbar.cbDfaXval.GetValue(),\n text=self.tbPoints.GetValue(),\n pconf=self.tbConf.GetValue(),\n symb=self.tbSymbols.GetValue(), usecol=[], usesym=[])\n \n elif self.canvas.GetName() in ['plcPCAscore']:\n plot_scores(self.canvas, tbar.data['pcscores'],\n cl=tbar.data['class'][:, 0],\n labels=tbar.data['label'],\n validation=tbar.data['validation'],\n col1=tbar.spnNumPcs1.GetValue() - 1,\n col2=tbar.spnNumPcs2.GetValue() - 1,\n title=self.graph.title, xLabel=self.graph.xLabel,\n yLabel=self.graph.yLabel, xval=False,\n text=self.tbPoints.GetValue(), pconf=False,\n symb=self.tbSymbols.GetValue(), usecol=[], usesym=[])\n \n elif len(self.GetName().split('plcPredPls')) > 1:\n self.canvas = plot_pls_model(self.canvas, model='full',\n tbar=self.canvas.prnt.prnt.prnt.prnt.tbMain,\n cL=tbar.data['class'][:, nax],\n label=tbar.data['label'],\n scores=tbar.data['plst'],\n predictions=tbar.data['plspred'],\n validation=np.array(tbar.data['validation'], 'i')[:, nax],\n RMSEPT=tbar.data['RMSEPT'],\n factors=tbar.data['plsfactors'],\n type=tbar.data['plstype'],\n col1=tbar.spnPLSfactor1.GetValue() - 1,\n col2=tbar.spnPLSfactor2.GetValue() - 1,\n symbols=self.tbSymbols.GetValue(),\n usetxt=self.tbPoints.GetValue(),\n plScL=tbar.data['pls_class'])\n \n elif self.canvas.GetName() in ['plcGaFeatPlot']:\n plot_scores(self.canvas, ptbar.data['gavarcoords'],\n cl=ptbar.data['class'][:, 0],\n labels=ptbar.data['label'],\n validation=ptbar.data['validation'],\n col1=0, col2=1, title=self.graph.title,\n xLabel=self.graph.xLabel, yLabel=self.graph.yLabel,\n xval=True, text=self.tbPoints.GetValue(), pconf=False,\n symb=self.tbSymbols.GetValue(), usecol=[], usesym=[])\n \n elif len(self.GetName().split('plcGaModelPlot')) > 1:\n if self.canvas.prnt.prnt.splitPrnt.type in ['DFA']:\n plot_scores(self.canvas, ptbar.data['gadfadfscores'],\n cl=ptbar.data['class'][:, 0],\n labels=ptbar.data['label'],\n validation=ptbar.data['validation'],\n col1=ptbar.spnGaScoreFrom.GetValue() - 1,\n col2=ptbar.spnGaScoreTo.GetValue() - 1,\n title=self.graph.title, xLabel=self.graph.xLabel,\n yLabel=self.graph.yLabel, xval=True,\n text=self.tbPoints.GetValue(),\n pconf=self.tbConf.GetValue(),\n symb=self.tbSymbols.GetValue(), usecol=[], usesym=[])\n else:\n self.canvas = plot_pls_model(self.canvas, model='ga',\n tbar=self.canvas.prnt.prnt.splitPrnt.prnt.prnt.tbMain,\n cL=ptbar.data['class'][:, 0],\n scores=None,\n label=ptbar.data['label'],\n predictions=ptbar.data['gaplsscores'],\n validation=ptbar.data['validation'],\n RMSEPT=ptbar.data['gaplsrmsept'],\n factors=ptbar.data['gaplsfactors'],\n type=0, col1=ptbar.spnGaScoreFrom.GetValue()-1,\n col2=ptbar.spnGaScoreTo.GetValue()-1,\n symbols=self.tbSymbols.GetValue(),\n usetxt=self.tbPoints.GetValue(),\n usecol=[], usesym=[],\n plScL=ptbar.data['pls_class'])\n \n elif self.canvas.GetName() in ['plcPcaLoadsV']:\n plot_loads(self.canvas, np.transpose(tbar.data['pcloads']),\n xaxis=tbar.data['indlabels'],\n col1=tbar.spnNumPcs1.GetValue()-1,\n col2=tbar.spnNumPcs2.GetValue()-1,\n title=self.graph.title, xLabel=self.graph.xLabel,\n yLabel=self.graph.yLabel, type=loadType,\n usecol=[], usesym=[])\n \n elif self.canvas.GetName() in ['plcPLSloading']:\n plot_loads(self.canvas, tbar.data['plsloads'],\n xaxis=tbar.data['indlabels'],\n col1=tbar.spnPLSfactor1.GetValue()-1,\n col2=tbar.spnPLSfactor2.GetValue()-1,\n title=self.graph.title, xLabel=self.graph.xLabel,\n yLabel=self.graph.yLabel, type=loadType,\n usecol=[], usesym=[])\n \n elif self.canvas.GetName() in ['plcDfaLoadsV']:\n plot_loads(self.canvas, tbar.data['dfloads'],\n xaxis=tbar.data['indlabels'],\n col1=tbar.spnDfaScore1.GetValue() - 1,\n col2=tbar.spnDfaScore2.GetValue() - 1,\n title=self.graph.title, xLabel=self.graph.xLabel,\n yLabel=self.graph.yLabel, type=loadType,\n usecol=[], usesym=[])\n \n elif self.canvas.GetName() in ['plcGaSpecLoad']:\n if pprnt.type in ['DFA']:\n labels = []\n for each in pprnt.titleBar.data['gacurrentchrom']:\n labels.append(pprnt.titleBar.data['indlabels'][int(each)])\n\n plot_loads(self.canvas, pprnt.titleBar.data['gadfadfaloads'],\n xaxis=labels, title=self.graph.title,\n xLabel=self.graph.xLabel, yLabel=self.graph.yLabel,\n type=loadType, usecol=[], usesym=[])\n \n elif self.canvas.GetName() in ['plcGaSpecLoad']:\n if self.canvas.prnt.prnt.splitPrnt.type in ['PLS']:\n labels = []\n for each in pprnt.titleBar.data['gacurrentchrom']:\n labels.append(pprnt.titleBar.data['indlabels'][int(each)])\n\n plot_loads(self.canvas, ptbar.data['gaplsplsloads'],\n xaxis=labels, title=self.graph.title,\n xLabel=self.graph.xLabel, yLabel=self.graph.yLabel,\n type=loadType, usecol=[], usesym=[])\n \n # def OnBtnFont(self, event):\n # data = wx.FontData()\n # data.EnableEffects(True)\n # data.SetColour(self.canvas.GetForegroundColour())\n # data.SetInitialFont(self.canvas.GetFont())\n #\n # dlg = wx.FontDialog(self, data)\n # if dlg.ShowModal() == wx.ID_OK:\n # self.font = dlg.GetFontData().GetChosenFont()\n # self.colour = dlg.GetFontData().GetColour()\n #\n # if self.cbApply.GetValue() is True:\n # self.canvas.SetFont(self.font)\n # self.canvas.SetForegroundColour(self.colour)\n # self.canvas.redraw()\n \n def on_txt_title(self, _):\n if self.cbApply.GetValue() is True:\n self.graph.set_title(self.txtTitle.GetValue())\n self.canvas.redraw()\n \n def on_tb_grid(self, _):\n self.canvas.enable_grid(self.tbGrid.GetValue())\n \n def on_tb_drag_button(self, _):\n self.canvas.enable_drag(self.tbDrag.GetValue())\n \n def on_tb_point_label(self, _):\n self.canvas.enable_point_label(self.tbPointLabel.GetValue())\n \n def on_tb_zoom_button(self, _):\n self.canvas.enable_zoom(self.tbZoom.GetValue())\n \n def on_btn_apply(self, _):\n self.canvas.font_size_axis = self.spnFontSizeAxes.GetValue()\n self.canvas.font_size_title = self.spnFontSizeTitle.GetValue()\n \n self.graph.set_title(self.txtTitle.GetValue())\n self.graph.set_xlabel(self.txtXlabel.GetValue())\n self.graph.set_ylabel(self.txtYlabel.GetValue())\n \n xmin = float(self.txtXmin.GetValue())\n xmax = float(self.txtXmax.GetValue())\n ymin = float(self.txtYmin.GetValue())\n ymax = float(self.txtYmax.GetValue())\n\n if (xmin < xmax) and (ymin < ymax):\n self.canvas.last_draw = [self.canvas.last_draw[0],\n np.array([xmin, xmax]),\n np.array([ymin, ymax])]\n self.canvas.redraw()\n self.Close()\n \n def on_spn_font_size_axes(self, _):\n if self.cbApply.GetValue() is True:\n self.canvas.font_size_axis = self.spnFontSizeAxes.GetValue()\n self.canvas.redraw()\n \n def on_spn_font_size_title(self, _):\n if self.cbApply.GetValue() is True:\n self.canvas.font_size_title = self.spnFontSizeTitle.GetValue()\n self.canvas.redraw()\n \n def resize_axes(self):\n xmin = float(self.txtXmin.GetValue())\n xmax = float(self.txtXmax.GetValue())\n ymin = float(self.txtYmin.GetValue())\n ymax = float(self.txtYmax.GetValue())\n\n if (xmin < xmax) and (ymin < ymax) and self.cbApply.GetValue():\n self.canvas.last_draw = [self.canvas.last_draw[0],\n np.array([xmin, xmax]),\n np.array([ymin, ymax])]\n self.canvas.redraw()\n \n def on_spn_xmin(self, _):\n self.resize_axes()\n \n def on_spn_xmax(self, _):\n self.resize_axes()\n \n def on_spn_ymin(self, _):\n self.resize_axes()\n \n def on_spn_ymax(self, _):\n self.resize_axes()\n \n def on_spn_xmin_up(self, _):\n curr = float(self.txtXmin.GetValue())\n curr = curr + self.Increment\n self.txtXmin.SetValue('%.3f' % curr)\n\n def on_spn_xmin_down(self, _):\n curr = float(self.txtXmin.GetValue())\n curr = curr - self.Increment\n self.txtXmin.SetValue('%.3f' % curr)\n\n def on_spn_xmax_up(self, _):\n curr = float(self.txtXmax.GetValue())\n curr = curr + self.Increment\n self.txtXmax.SetValue('%.3f' % curr)\n\n def on_spn_xmax_down(self, _):\n curr = float(self.txtXmax.GetValue())\n curr = curr - self.Increment\n self.txtXmax.SetValue('%.3f' % curr)\n\n def on_spn_ymax_up(self, _):\n curr = float(self.txtYmax.GetValue())\n curr = curr + self.Increment\n self.txtYmax.SetValue('%.3f' % curr)\n\n def on_spn_ymax_down(self, _):\n curr = float(self.txtYmax.GetValue())\n curr = curr - self.Increment\n self.txtYmax.SetValue('%.3f' % curr)\n\n def on_spn_ymin_up(self, _):\n curr = float(self.txtYmin.GetValue())\n curr = curr + self.Increment\n self.txtYmin.SetValue('%.3f' % curr)\n\n def on_spn_ymin_down(self, _):\n curr = float(self.txtYmin.GetValue())\n curr = curr - self.Increment\n self.txtYmin.SetValue('%.3f' % curr)\n\n\nif __name__ == '__main__':\n app = wx.App()\n # This needs parameters to work\n # noinspection PyTypeChecker\n props = PlotProperties(None)\n app.MainLoop()\n", "repo_name": "joaquinabian/PyChem3K", "sub_path": "pca.py", "file_name": "pca.py", "file_ext": "py", "file_size_in_byte": 110910, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "wx.NewId", "line_number": 27, "usage_type": "call"}, {"api_name": "wx.NewId", "line_number": 31, "usage_type": "call"}, {"api_name": "wx.NewId", "line_number": 42, "usage_type": "call"}, {"api_name": "wx.NewId", "line_number": 45, "usage_type": "call"}, {"api_name": "wx.Button", "line_number": 74, "usage_type": "call"}, {"api_name": "wx.NewId", "line_number": 74, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 75, "usage_type": "attribute"}, {"api_name": "wx.Button", "line_number": 77, "usage_type": "call"}, {"api_name": "wx.NewId", "line_number": 77, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 78, "usage_type": "attribute"}, {"api_name": "wx.StaticText", "line_number": 80, "usage_type": "call"}, {"api_name": "wx.GridSizer", "line_number": 102, "usage_type": "call"}, {"api_name": "wx.EXPAND", "line_number": 104, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 105, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 106, "usage_type": "attribute"}, {"api_name": "numpy.unique", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 131, "usage_type": "call"}, {"api_name": "numpy.median", "line_number": 133, "usage_type": "call"}, {"api_name": "numpy.median", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.median", "line_number": 137, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_SOLID", "line_number": 149, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 150, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 152, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 154, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 156, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 158, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 160, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 162, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 164, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 166, "usage_type": "call"}, {"api_name": "commons.PolyMarker", "line_number": 169, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 169, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 170, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 170, "usage_type": "name"}, {"api_name": "commons.PolyMarker", "line_number": 173, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 173, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 174, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 174, "usage_type": "name"}, {"api_name": "wx.lib.plot.polyobjects.PlotGraphics", "line_number": 181, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 215, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_SOLID", "line_number": 218, "usage_type": "attribute"}, {"api_name": "numpy.take", "line_number": 223, "usage_type": "call"}, {"api_name": "mva.chemometrics._index", "line_number": 223, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 224, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 225, "usage_type": "call"}, {"api_name": "mva.chemometrics._index", "line_number": 225, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 227, "usage_type": "call"}, {"api_name": "mva.chemometrics._index", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 228, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 228, "usage_type": "call"}, {"api_name": "mva.chemometrics._index", "line_number": 228, "usage_type": "call"}, {"api_name": "commons.PolyMarker", "line_number": 231, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 231, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 231, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 232, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 232, "usage_type": "name"}, {"api_name": "wx.BRUSHSTYLE_SOLID", "line_number": 235, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 243, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 243, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_SOLID", "line_number": 245, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 249, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 249, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_SOLID", "line_number": 251, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 254, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 254, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_SOLID", "line_number": 256, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.polyobjects.PlotGraphics", "line_number": 265, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 321, "usage_type": "name"}, {"api_name": "numpy.newaxis", "line_number": 322, "usage_type": "name"}, {"api_name": "numpy.newaxis", "line_number": 324, "usage_type": "name"}, {"api_name": "numpy.newaxis", "line_number": 325, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 381, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 382, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 383, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 386, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 387, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 388, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 389, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 389, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 390, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 391, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 392, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 393, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 393, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 394, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 395, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 396, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 397, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 397, "usage_type": "call"}, {"api_name": "commons.PolyMarker", "line_number": 403, "usage_type": "call"}, {"api_name": "wx.BRUSHSTYLE_TRANSPARENT", "line_number": 406, "usage_type": "attribute"}, {"api_name": "commons.PolyMarker", "line_number": 408, "usage_type": "call"}, {"api_name": "wx.BRUSHSTYLE_TRANSPARENT", "line_number": 411, "usage_type": "attribute"}, {"api_name": "commons.PolyMarker", "line_number": 413, "usage_type": "call"}, {"api_name": "wx.BRUSHSTYLE_TRANSPARENT", "line_number": 416, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 419, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 419, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_SOLID", "line_number": 422, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.polyobjects.PlotGraphics", "line_number": 424, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 433, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 462, "usage_type": "name"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 463, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 463, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_SOLID", "line_number": 465, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.polyobjects.PlotGraphics", "line_number": 466, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 473, "usage_type": "name"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 475, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 475, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_SOLID", "line_number": 479, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 481, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 481, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_SOLID", "line_number": 484, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.polyobjects.PlotGraphics", "line_number": 488, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 506, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 507, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_SOLID", "line_number": 508, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 510, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 511, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_SOLID", "line_number": 514, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.polyobjects.PlotGraphics", "line_number": 516, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 541, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 564, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 567, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 569, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 571, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 571, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 571, "usage_type": "name"}, {"api_name": "numpy.newaxis", "line_number": 572, "usage_type": "name"}, {"api_name": "commons.PolyMarker", "line_number": 581, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 587, "usage_type": "call"}, {"api_name": "commons.PolyMarker", "line_number": 591, "usage_type": "call"}, {"api_name": "commons.PolyMarker", "line_number": 598, "usage_type": "call"}, {"api_name": "commons.PolyMarker", "line_number": 607, "usage_type": "call"}, {"api_name": "wx.Colour", "line_number": 609, "usage_type": "call"}, {"api_name": "wx.Colour", "line_number": 610, "usage_type": "call"}, {"api_name": "commons.PolyMarker", "line_number": 614, "usage_type": "call"}, {"api_name": "wx.Colour", "line_number": 616, "usage_type": "call"}, {"api_name": "wx.Colour", "line_number": 617, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PlotGraphics", "line_number": 623, "usage_type": "call"}, {"api_name": "mva.chemometrics._index", "line_number": 665, "usage_type": "call"}, {"api_name": "commons.PolyMarker", "line_number": 668, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 669, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 671, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 675, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 676, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 679, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 680, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 682, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 685, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 685, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 685, "usage_type": "name"}, {"api_name": "commons.PolyMarker", "line_number": 689, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 692, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 693, "usage_type": "call"}, {"api_name": "mva.chemometrics._index", "line_number": 696, "usage_type": "call"}, {"api_name": "commons.PolyMarker", "line_number": 698, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 698, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 700, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PlotGraphics", "line_number": 704, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PlotGraphics", "line_number": 707, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 736, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 736, "usage_type": "name"}, {"api_name": "numpy.newaxis", "line_number": 737, "usage_type": "name"}, {"api_name": "numpy.reshape", "line_number": 738, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 738, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 739, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 739, "usage_type": "call"}, {"api_name": "plot.append", "line_number": 747, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 750, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 752, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 757, "usage_type": "call"}, {"api_name": "plot.append", "line_number": 767, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 773, "usage_type": "call"}, {"api_name": "plot.append", "line_number": 783, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 790, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 794, "usage_type": "call"}, {"api_name": "numpy.mod", "line_number": 800, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 806, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 813, "usage_type": "call"}, {"api_name": "plot.append", "line_number": 824, "usage_type": "call"}, {"api_name": "plot.append", "line_number": 827, "usage_type": "call"}, {"api_name": "commons.PolyMarker", "line_number": 827, "usage_type": "call"}, {"api_name": "plot.append", "line_number": 833, "usage_type": "call"}, {"api_name": "commons.PolyMarker", "line_number": 833, "usage_type": "call"}, {"api_name": "plot.append", "line_number": 836, "usage_type": "call"}, {"api_name": "plot.PolyEllipse", "line_number": 836, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_SOLID", "line_number": 838, "usage_type": "attribute"}, {"api_name": "plot.append", "line_number": 840, "usage_type": "call"}, {"api_name": "plot.PolyEllipse", "line_number": 840, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_SOLID", "line_number": 842, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.polyobjects.PlotGraphics", "line_number": 845, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 883, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 889, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 889, "usage_type": "name"}, {"api_name": "numpy.newaxis", "line_number": 890, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 892, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 894, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 895, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 895, "usage_type": "call"}, {"api_name": "mva.chemometrics._index", "line_number": 895, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 896, "usage_type": "name"}, {"api_name": "plot.append", "line_number": 914, "usage_type": "call"}, {"api_name": "plot.append", "line_number": 923, "usage_type": "call"}, {"api_name": "plot.append", "line_number": 927, "usage_type": "call"}, {"api_name": "plot.PolyEllipse", "line_number": 927, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_SOLID", "line_number": 929, "usage_type": "attribute"}, {"api_name": "plot.append", "line_number": 931, "usage_type": "call"}, {"api_name": "plot.PolyEllipse", "line_number": 931, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 932, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 933, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_SOLID", "line_number": 934, "usage_type": "attribute"}, {"api_name": "plot.append", "line_number": 936, "usage_type": "call"}, {"api_name": "commons.PolyMarker", "line_number": 936, "usage_type": "call"}, {"api_name": "plot.append", "line_number": 939, "usage_type": "call"}, {"api_name": "commons.PolyMarker", "line_number": 939, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 947, "usage_type": "call"}, {"api_name": "mva.chemometrics._index", "line_number": 949, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 951, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 954, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 955, "usage_type": "call"}, {"api_name": "plot.append", "line_number": 959, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PlotGraphics", "line_number": 961, "usage_type": "call"}, {"api_name": "plot.append", "line_number": 981, "usage_type": "call"}, {"api_name": "plot.append", "line_number": 1002, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PlotGraphics", "line_number": 1005, "usage_type": "call"}, {"api_name": "wx.Dialog", "line_number": 1010, "usage_type": "attribute"}, {"api_name": "wx.Dialog.__init__", "line_number": 1012, "usage_type": "call"}, {"api_name": "wx.Dialog", "line_number": 1012, "usage_type": "attribute"}, {"api_name": "wx.Dialog", "line_number": 1044, "usage_type": "attribute"}, {"api_name": "wx.Dialog.__init__", "line_number": 1047, "usage_type": "call"}, {"api_name": "wx.Dialog", "line_number": 1047, "usage_type": "attribute"}, {"api_name": "wx.DEFAULT_DIALOG_STYLE", "line_number": 1049, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 1061, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1061, "usage_type": "call"}, {"api_name": "wx.BITMAP_TYPE_BMP", "line_number": 1061, "usage_type": "attribute"}, {"api_name": "wx.BitmapButton", "line_number": 1062, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 1065, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 1067, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1067, "usage_type": "call"}, {"api_name": "wx.BITMAP_TYPE_BMP", "line_number": 1067, "usage_type": "attribute"}, {"api_name": "wx.BitmapButton", "line_number": 1068, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 1071, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 1073, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1073, "usage_type": "call"}, {"api_name": "wx.BITMAP_TYPE_BMP", "line_number": 1073, "usage_type": "attribute"}, {"api_name": "wx.BitmapButton", "line_number": 1074, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 1077, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 1079, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1079, "usage_type": "call"}, {"api_name": "wx.BITMAP_TYPE_BMP", "line_number": 1079, "usage_type": "attribute"}, {"api_name": "wx.BitmapButton", "line_number": 1080, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 1084, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 1086, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1086, "usage_type": "call"}, {"api_name": "wx.BITMAP_TYPE_BMP", "line_number": 1086, "usage_type": "attribute"}, {"api_name": "wx.BitmapButton", "line_number": 1087, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 1091, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 1093, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1093, "usage_type": "call"}, {"api_name": "wx.BITMAP_TYPE_BMP", "line_number": 1093, "usage_type": "attribute"}, {"api_name": "wx.BitmapButton", "line_number": 1094, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 1097, "usage_type": "attribute"}, {"api_name": "wx.GridSizer", "line_number": 1103, "usage_type": "call"}, {"api_name": "wx.EXPAND", "line_number": 1111, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1112, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1113, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1114, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1115, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1116, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 1119, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1119, "usage_type": "call"}, {"api_name": "wx.Bitmap", "line_number": 1124, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1124, "usage_type": "call"}, {"api_name": "wx.Bitmap", "line_number": 1129, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1129, "usage_type": "call"}, {"api_name": "wx.Bitmap", "line_number": 1134, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1134, "usage_type": "call"}, {"api_name": "wx.Bitmap", "line_number": 1139, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1139, "usage_type": "call"}, {"api_name": "wx.Bitmap", "line_number": 1145, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1145, "usage_type": "call"}, {"api_name": "wx.lib.plot.plotcanvas.PlotCanvas", "line_number": 1150, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.plotcanvas", "line_number": 1150, "usage_type": "name"}, {"api_name": "wx.lib.plot.plotcanvas.PlotCanvas.__init__", "line_number": 1152, "usage_type": "call"}, {"api_name": "wx.lib.plot.plotcanvas.PlotCanvas", "line_number": 1152, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.plotcanvas", "line_number": 1152, "usage_type": "name"}, {"api_name": "wx.lib.plot.plotcanvas.PlotCanvas", "line_number": 1154, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.plotcanvas", "line_number": 1154, "usage_type": "name"}, {"api_name": "wx.lib.plot.plotcanvas.PlotCanvas", "line_number": 1155, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.plotcanvas", "line_number": 1155, "usage_type": "name"}, {"api_name": "wx.EVT_RIGHT_DOWN", "line_number": 1166, "usage_type": "attribute"}, {"api_name": "wx.EVT_LEFT_DOWN", "line_number": 1167, "usage_type": "attribute"}, {"api_name": "wx.Menu", "line_number": 1174, "usage_type": "call"}, {"api_name": "wx.ITEM_NORMAL", "line_number": 1180, "usage_type": "attribute"}, {"api_name": "wx.ITEM_NORMAL", "line_number": 1182, "usage_type": "attribute"}, {"api_name": "wx.ITEM_NORMAL", "line_number": 1184, "usage_type": "attribute"}, {"api_name": "wx.ITEM_NORMAL", "line_number": 1186, "usage_type": "attribute"}, {"api_name": "wx.EVT_MENU", "line_number": 1189, "usage_type": "attribute"}, {"api_name": "wx.EVT_MENU", "line_number": 1190, "usage_type": "attribute"}, {"api_name": "wx.EVT_MENU", "line_number": 1191, "usage_type": "attribute"}, {"api_name": "wx.EVT_MENU", "line_number": 1192, "usage_type": "attribute"}, {"api_name": "wx.MetafileDC", "line_number": 1196, "usage_type": "call"}, {"api_name": "numpy.array2string", "line_number": 1241, "usage_type": "call"}, {"api_name": "wx.TheClipboard.Open", "line_number": 1242, "usage_type": "call"}, {"api_name": "wx.TheClipboard", "line_number": 1242, "usage_type": "attribute"}, {"api_name": "wx.TheClipboard.SetData", "line_number": 1243, "usage_type": "call"}, {"api_name": "wx.TheClipboard", "line_number": 1243, "usage_type": "attribute"}, {"api_name": "wx.TextDataObject", "line_number": 1243, "usage_type": "call"}, {"api_name": "wx.TheClipboard.Close", "line_number": 1244, "usage_type": "call"}, {"api_name": "wx.TheClipboard", "line_number": 1244, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 1255, "usage_type": "call"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 1264, "usage_type": "call"}, {"api_name": "wx.CROSS_CURSOR", "line_number": 1361, "usage_type": "attribute"}, {"api_name": "wx.Cursor", "line_number": 1373, "usage_type": "call"}, {"api_name": "wx.CURSOR_PENCIL", "line_number": 1373, "usage_type": "attribute"}, {"api_name": "wx.CROSS_CURSOR", "line_number": 1375, "usage_type": "attribute"}, {"api_name": "wx.Panel", "line_number": 1382, "usage_type": "attribute"}, {"api_name": "wx.Panel.__init__", "line_number": 1388, "usage_type": "call"}, {"api_name": "wx.Panel", "line_number": 1388, "usage_type": "attribute"}, {"api_name": "wx.TAB_TRAVERSAL", "line_number": 1390, "usage_type": "attribute"}, {"api_name": "wx.lib.anchors.LayoutAnchors", "line_number": 1413, "usage_type": "call"}, {"api_name": "wx.lib.agw.buttonpanel.BP_USE_GRADIENT", "line_number": 1448, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1448, "usage_type": "name"}, {"api_name": "wx.lib.agw.buttonpanel.BP_ALIGN_LEFT", "line_number": 1448, "usage_type": "attribute"}, {"api_name": "wx.BoxSizer", "line_number": 1452, "usage_type": "call"}, {"api_name": "wx.HORIZONTAL", "line_number": 1452, "usage_type": "attribute"}, {"api_name": "wx.BoxSizer", "line_number": 1453, "usage_type": "call"}, {"api_name": "wx.VERTICAL", "line_number": 1453, "usage_type": "attribute"}, {"api_name": "wx.GridSizer", "line_number": 1454, "usage_type": "call"}, {"api_name": "wx.EXPAND", "line_number": 1456, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1458, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1459, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1461, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1462, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1463, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1464, "usage_type": "attribute"}, {"api_name": "wx.lib.plot.polyobjects.PolyLine", "line_number": 1481, "usage_type": "call"}, {"api_name": "wx.PENSTYLE_TRANSPARENT", "line_number": 1482, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel.ButtonPanel", "line_number": 1490, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1490, "usage_type": "name"}, {"api_name": "wx.lib.agw.buttonpanel.ButtonPanel.__init__", "line_number": 1493, "usage_type": "call"}, {"api_name": "wx.lib.agw.buttonpanel.ButtonPanel", "line_number": 1493, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1493, "usage_type": "name"}, {"api_name": "wx.lib.agw.buttonpanel.BP_USE_GRADIENT", "line_number": 1495, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1495, "usage_type": "name"}, {"api_name": "wx.lib.agw.buttonpanel.BP_ALIGN_LEFT", "line_number": 1496, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1496, "usage_type": "name"}, {"api_name": "wx.EVT_PAINT", "line_number": 1507, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 1509, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1509, "usage_type": "call"}, {"api_name": "wx.BITMAP_TYPE_PNG", "line_number": 1509, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel.ButtonInfo", "line_number": 1510, "usage_type": "call"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1510, "usage_type": "name"}, {"api_name": "wx.ITEM_NORMAL", "line_number": 1510, "usage_type": "attribute"}, {"api_name": "wx.EVT_BUTTON", "line_number": 1514, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 1516, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1516, "usage_type": "call"}, {"api_name": "wx.BITMAP_TYPE_PNG", "line_number": 1516, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel.ButtonInfo", "line_number": 1517, "usage_type": "call"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1517, "usage_type": "name"}, {"api_name": "wx.ITEM_NORMAL", "line_number": 1518, "usage_type": "attribute"}, {"api_name": "wx.EVT_BUTTON", "line_number": 1522, "usage_type": "attribute"}, {"api_name": "wx.Choice", "line_number": 1526, "usage_type": "call"}, {"api_name": "wx.Choice", "line_number": 1531, "usage_type": "call"}, {"api_name": "wx.EVT_COMBOBOX", "line_number": 1535, "usage_type": "attribute"}, {"api_name": "wx.Choice", "line_number": 1539, "usage_type": "call"}, {"api_name": "wx.SpinCtrl", "line_number": 1545, "usage_type": "call"}, {"api_name": "wx.SP_ARROW_KEYS", "line_number": 1549, "usage_type": "attribute"}, {"api_name": "wx.SpinCtrl", "line_number": 1553, "usage_type": "call"}, {"api_name": "wx.SP_ARROW_KEYS", "line_number": 1557, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPINCTRL", "line_number": 1559, "usage_type": "attribute"}, {"api_name": "wx.SpinCtrl", "line_number": 1561, "usage_type": "call"}, {"api_name": "wx.SP_ARROW_KEYS", "line_number": 1565, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPINCTRL", "line_number": 1567, "usage_type": "attribute"}, {"api_name": "wx.TRANSPARENT_WINDOW", "line_number": 1572, "usage_type": "attribute"}, {"api_name": "wx.lib.stattext.GenStaticText", "line_number": 1577, "usage_type": "call"}, {"api_name": "wx.lib.stattext.GenStaticText", "line_number": 1580, "usage_type": "call"}, {"api_name": "wx.lib.stattext.GenStaticText", "line_number": 1582, "usage_type": "call"}, {"api_name": "wx.lib.agw.buttonpanel.BP_TEXT_COLOUR", "line_number": 1603, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1603, "usage_type": "name"}, {"api_name": "wx.WHITE", "line_number": 1603, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel.BP_TEXT_COLOUR", "line_number": 1606, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1606, "usage_type": "name"}, {"api_name": "wx.BLUE", "line_number": 1606, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel.BP_BORDER_COLOUR", "line_number": 1607, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1607, "usage_type": "name"}, {"api_name": "wx.lib.agw.buttonpanel.BrightenColour", "line_number": 1608, "usage_type": "call"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1608, "usage_type": "name"}, {"api_name": "wx.lib.agw.buttonpanel.BP_SEPARATOR_COLOUR", "line_number": 1609, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1609, "usage_type": "name"}, {"api_name": "wx.lib.agw.buttonpanel.BrightenColour", "line_number": 1610, "usage_type": "call"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1610, "usage_type": "name"}, {"api_name": "wx.lib.agw.buttonpanel.BP_BUTTONTEXT_COLOUR", "line_number": 1611, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1611, "usage_type": "name"}, {"api_name": "wx.BLACK", "line_number": 1611, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel.BP_SELECTION_BRUSH_COLOUR", "line_number": 1612, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1612, "usage_type": "name"}, {"api_name": "wx.Colour", "line_number": 1612, "usage_type": "call"}, {"api_name": "wx.lib.agw.buttonpanel.BP_SELECTION_PEN_COLOUR", "line_number": 1613, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.buttonpanel", "line_number": 1613, "usage_type": "name"}, {"api_name": "wx.Colour", "line_number": 1613, "usage_type": "call"}, {"api_name": "wx.FileDialog", "line_number": 1619, "usage_type": "call"}, {"api_name": "wx.FD_SAVE", "line_number": 1620, "usage_type": "attribute"}, {"api_name": "wx.ID_OK", "line_number": 1622, "usage_type": "attribute"}, {"api_name": "numpy.array2string", "line_number": 1624, "usage_type": "call"}, {"api_name": "numpy.array2string", "line_number": 1625, "usage_type": "call"}, {"api_name": "numpy.array2string", "line_number": 1626, "usage_type": "call"}, {"api_name": "numpy.array2string", "line_number": 1627, "usage_type": "call"}, {"api_name": "mva.chemometrics.pca_svd", "line_number": 1673, "usage_type": "call"}, {"api_name": "mva.chemometrics", "line_number": 1673, "usage_type": "name"}, {"api_name": "mva.chemometrics.pca_nipals", "line_number": 1683, "usage_type": "call"}, {"api_name": "mva.chemometrics", "line_number": 1683, "usage_type": "name"}, {"api_name": "numpy.unique", "line_number": 1702, "usage_type": "call"}, {"api_name": "commons.error_box", "line_number": 1708, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 1737, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 1753, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 1754, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 1754, "usage_type": "name"}, {"api_name": "numpy.transpose", "line_number": 1760, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 1761, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 1761, "usage_type": "name"}, {"api_name": "wx.Dialog", "line_number": 1783, "usage_type": "attribute"}, {"api_name": "wx.Dialog.__init__", "line_number": 1787, "usage_type": "call"}, {"api_name": "wx.Dialog", "line_number": 1787, "usage_type": "attribute"}, {"api_name": "wx.MAXIMIZE_BOX", "line_number": 1789, "usage_type": "attribute"}, {"api_name": "wx.DEFAULT_DIALOG_STYLE", "line_number": 1789, "usage_type": "attribute"}, {"api_name": "wx.GridSizer", "line_number": 1834, "usage_type": "call"}, {"api_name": "wx.EXPAND", "line_number": 1843, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1844, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1845, "usage_type": "attribute"}, {"api_name": "wx.GridSizer", "line_number": 1849, "usage_type": "call"}, {"api_name": "wx.EXPAND", "line_number": 1857, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1858, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1859, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1860, "usage_type": "attribute"}, {"api_name": "wx.EXPAND", "line_number": 1864, "usage_type": "attribute"}, {"api_name": "wx.StaticText", "line_number": 1867, "usage_type": "call"}, {"api_name": "wx.ALIGN_LEFT", "line_number": 1868, "usage_type": "attribute"}, {"api_name": "wx.StaticText", "line_number": 1872, "usage_type": "call"}, {"api_name": "wx.ALIGN_LEFT", "line_number": 1873, "usage_type": "attribute"}, {"api_name": "wx.GridBagSizer", "line_number": 1909, "usage_type": "call"}, {"api_name": "wx.FLEX_GROWMODE_SPECIFIED", "line_number": 1912, "usage_type": "attribute"}, {"api_name": "wx.HORIZONTAL", "line_number": 1915, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.foldpanelbar.FoldPanelBar", "line_number": 1926, "usage_type": "call"}, {"api_name": "wx.lib.agw.foldpanelbar", "line_number": 1926, "usage_type": "name"}, {"api_name": "wx.DefaultPosition", "line_number": 1926, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.foldpanelbar.FPB_EXCLUSIVE_FOLD", "line_number": 1928, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.foldpanelbar", "line_number": 1928, "usage_type": "name"}, {"api_name": "wx.lib.anchors.LayoutAnchors", "line_number": 1930, "usage_type": "call"}, {"api_name": "wx.ImageList", "line_number": 1933, "usage_type": "call"}, {"api_name": "wx.Bitmap", "line_number": 1934, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1934, "usage_type": "call"}, {"api_name": "wx.BITMAP_TYPE_PNG", "line_number": 1934, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 1935, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1935, "usage_type": "call"}, {"api_name": "wx.BITMAP_TYPE_PNG", "line_number": 1935, "usage_type": "attribute"}, {"api_name": "wx.Panel", "line_number": 1951, "usage_type": "call"}, {"api_name": "wx.TAB_TRAVERSAL", "line_number": 1953, "usage_type": "attribute"}, {"api_name": "wx.Panel", "line_number": 1956, "usage_type": "call"}, {"api_name": "wx.TAB_TRAVERSAL", "line_number": 1958, "usage_type": "attribute"}, {"api_name": "wx.Panel", "line_number": 1961, "usage_type": "call"}, {"api_name": "wx.TAB_TRAVERSAL", "line_number": 1963, "usage_type": "attribute"}, {"api_name": "wx.StaticText", "line_number": 1966, "usage_type": "call"}, {"api_name": "wx.StaticText", "line_number": 1971, "usage_type": "call"}, {"api_name": "wx.StaticText", "line_number": 1977, "usage_type": "call"}, {"api_name": "wx.StaticText", "line_number": 1982, "usage_type": "call"}, {"api_name": "wx.StaticText", "line_number": 1988, "usage_type": "call"}, {"api_name": "wx.StaticText", "line_number": 1993, "usage_type": "call"}, {"api_name": "wx.StaticText", "line_number": 1998, "usage_type": "call"}, {"api_name": "wx.TextCtrl", "line_number": 2003, "usage_type": "call"}, {"api_name": "wx.EVT_TEXT", "line_number": 2007, "usage_type": "attribute"}, {"api_name": "wx.TextCtrl", "line_number": 2009, "usage_type": "call"}, {"api_name": "wx.TextCtrl", "line_number": 2014, "usage_type": "call"}, {"api_name": "wx.TextCtrl", "line_number": 2019, "usage_type": "call"}, {"api_name": "wx.SpinButton", "line_number": 2024, "usage_type": "call"}, {"api_name": "wx.SP_VERTICAL", "line_number": 2026, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPIN_DOWN", "line_number": 2028, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPIN_UP", "line_number": 2029, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPIN", "line_number": 2030, "usage_type": "attribute"}, {"api_name": "wx.SpinButton", "line_number": 2032, "usage_type": "call"}, {"api_name": "wx.SP_VERTICAL", "line_number": 2034, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPIN_DOWN", "line_number": 2036, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPIN_UP", "line_number": 2037, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPIN", "line_number": 2038, "usage_type": "attribute"}, {"api_name": "wx.SpinButton", "line_number": 2040, "usage_type": "call"}, {"api_name": "wx.SP_VERTICAL", "line_number": 2042, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPIN_DOWN", "line_number": 2044, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPIN_UP", "line_number": 2045, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPIN", "line_number": 2046, "usage_type": "attribute"}, {"api_name": "wx.SpinButton", "line_number": 2048, "usage_type": "call"}, {"api_name": "wx.SP_VERTICAL", "line_number": 2050, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPIN_DOWN", "line_number": 2052, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPIN_UP", "line_number": 2053, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPIN", "line_number": 2054, "usage_type": "attribute"}, {"api_name": "wx.TextCtrl", "line_number": 2056, "usage_type": "call"}, {"api_name": "wx.TextCtrl", "line_number": 2061, "usage_type": "call"}, {"api_name": "wx.TextCtrl", "line_number": 2066, "usage_type": "call"}, {"api_name": "wx.StaticText", "line_number": 2071, "usage_type": "call"}, {"api_name": "wx.SpinCtrl", "line_number": 2077, "usage_type": "call"}, {"api_name": "wx.SP_ARROW_KEYS", "line_number": 2082, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPIN", "line_number": 2086, "usage_type": "attribute"}, {"api_name": "wx.SpinCtrl", "line_number": 2088, "usage_type": "call"}, {"api_name": "wx.SP_ARROW_KEYS", "line_number": 2093, "usage_type": "attribute"}, {"api_name": "wx.EVT_SPIN", "line_number": 2097, "usage_type": "attribute"}, {"api_name": "wx.lib.buttons.GenToggleButton", "line_number": 2099, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 2104, "usage_type": "attribute"}, {"api_name": "wx.lib.buttons.GenToggleButton", "line_number": 2106, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 2111, "usage_type": "attribute"}, {"api_name": "wx.lib.buttons.GenToggleButton", "line_number": 2113, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 2119, "usage_type": "attribute"}, {"api_name": "wx.lib.buttons.GenToggleButton", "line_number": 2121, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 2126, "usage_type": "attribute"}, {"api_name": "wx.CheckBox", "line_number": 2128, "usage_type": "call"}, {"api_name": "wx.Button", "line_number": 2133, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 2137, "usage_type": "attribute"}, {"api_name": "wx.lib.buttons.GenToggleButton", "line_number": 2139, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 2145, "usage_type": "attribute"}, {"api_name": "wx.lib.buttons.GenToggleButton", "line_number": 2147, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 2152, "usage_type": "attribute"}, {"api_name": "wx.lib.buttons.GenToggleButton", "line_number": 2154, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 2159, "usage_type": "attribute"}, {"api_name": "wx.Button", "line_number": 2161, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 2166, "usage_type": "attribute"}, {"api_name": "wx.Button", "line_number": 2168, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 2174, "usage_type": "attribute"}, {"api_name": "wx.Button", "line_number": 2176, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 2182, "usage_type": "attribute"}, {"api_name": "wx.Button", "line_number": 2184, "usage_type": "call"}, {"api_name": "wx.EVT_BUTTON", "line_number": 2190, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.foldpanelbar.FPB_ALIGN_WIDTH", "line_number": 2192, "usage_type": "attribute"}, {"api_name": "wx.lib.agw.foldpanelbar", "line_number": 2192, "usage_type": "name"}, {"api_name": "numpy.newaxis", "line_number": 2272, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 2276, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 2276, "usage_type": "name"}, {"api_name": "numpy.transpose", "line_number": 2327, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 2423, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 2424, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 2446, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 2447, "usage_type": "call"}, {"api_name": "wx.App", "line_number": 2504, "usage_type": "call"}]} +{"seq_id": "37614464044", "text": "import json\nimport urllib.parse\nimport urllib.request\n\n# Google Knowledge Graph API key\napi_key = \"AIzaSyDPZceqCgLVGytRa14EOvYfcYarjfqMLm0\"\n\nquery = 'university'\nservice_url = 'https://kgsearch.googleapis.com/v1/entities:search'\nparams = {\n 'query': query,\n # 'ids': 'kg:/m/0gg594v',\n 'limit': 3,\n 'indent': True,\n 'key': api_key,\n}\n\nurl = service_url + '?' + urllib.parse.urlencode(params)\n\nwith urllib.request.urlopen(url) as response:\n bb = response.read()\n obj = bb.decode('utf-8')\n\nobj = json.loads(obj)\nitems = obj['itemListElement']\nfor element in items:\n print(element['result']['name'] + ' (' + str(element['resultScore']) + ')')\n\n", "repo_name": "amirhdrz/nlp_experiments", "sub_path": "knowledge_graph.py", "file_name": "knowledge_graph.py", "file_ext": "py", "file_size_in_byte": 664, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "urllib.parse.parse.urlencode", "line_number": 18, "usage_type": "call"}, {"api_name": "urllib.parse.parse", "line_number": 18, "usage_type": "attribute"}, {"api_name": "urllib.parse", "line_number": 18, "usage_type": "name"}, {"api_name": "urllib.parse.request.urlopen", "line_number": 20, "usage_type": "call"}, {"api_name": "urllib.parse.request", "line_number": 20, "usage_type": "attribute"}, {"api_name": "urllib.parse", "line_number": 20, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 24, "usage_type": "call"}]} +{"seq_id": "13310558836", "text": "\"\"\"basenodemaps.py\nBase maps for HDF5 objects with node methods.\n\"\"\"\n# Package Header #\nfrom ...header import *\n\n# Header #\n__author__ = __author__\n__credits__ = __credits__\n__maintainer__ = __maintainer__\n__email__ = __email__\n\n\n# Imports #\n# Standard Libraries #\n\n# Third-Party Packages #\nimport h5py\n\n# Local Packages #\nfrom ...hdf5bases import HDF5Map, DatasetMap\nfrom ...dataset import ObjectReferenceComponent\nfrom ..datasetcomponents import NodeDatasetComponent\nfrom ..groupcomponents import NodeGroupComponent\n\n\n# Definitions #\n# Classes #\nclass BaseNodeDatasetMap(DatasetMap):\n \"\"\"A dataset map which outlines a dataset with basic node methods.\"\"\"\n\n default_dtype = ((\"Node\", h5py.ref_dtype),)\n default_component_types = {\n \"object_reference\": (\n ObjectReferenceComponent,\n {\n \"reference_fields\": {\"dataset\": \"Dataset\"},\n \"primary_reference_field\": \"dataset\",\n },\n ),\n \"tree_node\": (NodeDatasetComponent, {}),\n }\n\n\nclass BaseNodeGroupMap(HDF5Map):\n \"\"\"A group map which outlines a group with basic node methods.\"\"\"\n\n default_attribute_names = {\"tree_type\": \"tree_type\"}\n default_attributes = {\"tree_type\": \"Node\"}\n default_map_names = {\"node_map\": \"node_map\"}\n default_maps = {\"node_map\": BaseNodeDatasetMap()}\n default_component_types = {\n \"tree_node\": (NodeGroupComponent, {}),\n }\n", "repo_name": "FongAnthonyM/python-hdf5objects", "sub_path": "src/hdf5objects/treehierarchy/maps/basenodemaps.py", "file_name": "basenodemaps.py", "file_ext": "py", "file_size_in_byte": 1416, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "hdf5bases.DatasetMap", "line_number": 29, "usage_type": "name"}, {"api_name": "h5py.ref_dtype", "line_number": 32, "usage_type": "attribute"}, {"api_name": "dataset.ObjectReferenceComponent", "line_number": 35, "usage_type": "name"}, {"api_name": "datasetcomponents.NodeDatasetComponent", "line_number": 41, "usage_type": "name"}, {"api_name": "hdf5bases.HDF5Map", "line_number": 45, "usage_type": "name"}, {"api_name": "groupcomponents.NodeGroupComponent", "line_number": 53, "usage_type": "name"}]} +{"seq_id": "38082556492", "text": "import sys\r\nimport importlib\r\n#from data_esod import ESOD_Test\r\nimport torch\r\nimport time\r\nfrom progress.bar import Bar\r\nimport os\r\nfrom collections import OrderedDict\r\nimport cv2\r\nfrom PIL import Image\r\nimport numpy as np\r\n\r\nfrom base.framework_factory import load_framework\r\nfrom base.data import Test_Dataset\r\nfrom base.metric import *\r\nfrom base.util import *\r\n\r\n\r\ndef test_model(model, test_sets, config, saver=None):\r\n model.eval()\r\n st = time.time()\r\n for set_name, test_set in test_sets.items():\r\n save_folder = os.path.join(config['save_path'], set_name)\r\n check_path(save_folder)\r\n \r\n titer = test_set.size\r\n MR = MetricRecorder(titer)\r\n scores = []\r\n \r\n test_bar = Bar('Dataset {:10}:'.format(set_name), max=titer)\r\n for j in range(titer):\r\n image, gt, name = test_set.load_data(j)\r\n Y = model(image.cuda())\r\n pred = Y['final'][0, 0].sigmoid_().cpu().data.numpy()\r\n \r\n out_shape = gt.shape\r\n \r\n #pred = np.array(Image.fromarray(pred).resize((out_shape[::-1]), resample=0))\r\n pred = cv2.resize(pred, (out_shape[::-1]), interpolation=cv2.INTER_LINEAR)\r\n \r\n pred, gt = normalize_pil(pred, gt)\r\n pred = np.clip(np.round(pred * 255) / 255., 0, 1)\r\n MR.update(pre=pred, gt=gt)\r\n \r\n #scores.append(get_scores(pred, gt))\r\n #print(get_scores(pred, gt))\r\n \r\n # save predictions\r\n if config['save']:\r\n fnl_folder = os.path.join(save_folder, 'final')\r\n check_path(fnl_folder)\r\n im_path = os.path.join(fnl_folder, name + '.png')\r\n Image.fromarray((pred * 255)).convert('L').save(im_path)\r\n \r\n if saver is not None:\r\n saver(Y, gt, name, save_folder, config)\r\n pass\r\n \r\n Bar.suffix = '{}/{}'.format(j, titer)\r\n test_bar.next()\r\n \r\n #scores = np.array(scores)\r\n #print(np.mean(scores, axis=0))\r\n \r\n mae, (maxf, meanf, *_), sm, em, wfm = MR.show(bit_num=3)\r\n #print(' MAE: {}, Max-F: {}, Maen-F: {}, SM: {}, EM: {}, Fbw: {}.'.format(mae, maxf, meanf, sm, em, wfm))\r\n print(' Max-F: {:.3f}, Maen-F: {:.3f}, Fbw: {:.3f}, MAE: {:.3f}, SM: {:.3f}, EM: {:.3f}.'.format(maxf, meanf, wfm, mae, sm, em))\r\n \r\n print('Test using time: {}.'.format(round(time.time() - st, 3)))\r\n\r\ndef main():\r\n if len(sys.argv) > 1:\r\n net_name = sys.argv[1]\r\n else:\r\n print('Need model name!')\r\n return\r\n \r\n config, model, _, _, _, saver = load_framework(net_name)\r\n print(config)\r\n \r\n #model.load_state_dict(torch.load(config['weight'], map_location='cpu'))\r\n saved_model = torch.load(config['weight'], map_location='cpu')\r\n new_name = {}\r\n for k, v in saved_model.items():\r\n if k.startswith('model'):\r\n new_name[k[6:]] = v\r\n else:\r\n new_name[k] = v\r\n model.load_state_dict(new_name)\r\n\r\n test_sets = OrderedDict()\r\n for set_name in config['vals']:\r\n test_sets[set_name] = Test_Dataset(name=set_name, config=config)\r\n \r\n model = model.cuda()\r\n \r\n test_model(model, test_sets, config, saver=saver)\r\n \r\nif __name__ == \"__main__\":\r\n main()", "repo_name": "moothes/SALOD", "sub_path": "test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 3423, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 38, "dataset": "github-code", "pt": "27", "api": [{"api_name": "time.time", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "progress.bar.Bar", "line_number": 30, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 39, "usage_type": "call"}, {"api_name": "cv2.INTER_LINEAR", "line_number": 39, "usage_type": "attribute"}, {"api_name": "numpy.clip", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path", "line_number": 52, "usage_type": "attribute"}, {"api_name": "PIL.Image.fromarray", "line_number": 53, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 53, "usage_type": "name"}, {"api_name": "progress.bar.Bar.suffix", "line_number": 59, "usage_type": "attribute"}, {"api_name": "progress.bar.Bar", "line_number": 59, "usage_type": "name"}, {"api_name": "time.time", "line_number": 69, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 72, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 73, "usage_type": "attribute"}, {"api_name": "base.framework_factory.load_framework", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 82, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 91, "usage_type": "call"}, {"api_name": "base.data.Test_Dataset", "line_number": 93, "usage_type": "call"}]} +{"seq_id": "73091392705", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[24]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nimport tov_solver as tov\nfrom scipy import interpolate\n\ndef modified_wave_equation(rho_c = 1e-3):\n \n def M(x):\n ## interpolation of M(r) from TOV solution\n sol = tov.TOV_solver(rho_c)\n r = np.linspace(0,sol.t[-1],len(sol.y[0]))\n Mr = interpolate.interp1d(r, sol.y[0])\n return Mr(x)\n def v(x):\n ## interpolation of v(r) from TOV solution\n sol = tov.TOV_solver(rho_c)\n r = np.linspace(0,sol.t[-1],len(sol.y[0]))\n vr = interpolate.interp1d(r, sol.y[1])\n return vr(x)\n def p(x):\n ## interpolation of p(r) from TOV solution\n sol = tov.TOV_solver(rho_c)\n r = np.linspace(0,sol.t[-1],len(sol.y[0]))\n pr = interpolate.interp1d(r, sol.y[2])\n return pr(x)\n\n def rho(x):\n ## interpolation of rho(r) from TOV solution\n return (p(x)/50)**(1/2)\n\n def func(r):\n ## function f(r) in the wave equation\n sol = tov.TOV_solver(rho_c)\n return np.exp(M(r)/2)*(1 - 2*v(r)/r)**(1/2)\n\n def gfunc(r):\n ## defined function g for wave equation\n return 1/r**2\n\n def init(r):\n ## inital condition for the wave\n return -2*1e-3*np.exp(-r**2/2)*r\n def init2(r):\n ## inital condition for the wave\n return 1e-3*np.exp(-r**2/2)\n\n def hfunc(r):\n return rho(r)-3*p(r)\n\n sol = tov.TOV_solver(rho_c)\n c = 1 #speed of light\n N = 300 # mesh element number\n r = np.linspace(0,7,N) #space\n t = np.linspace(0,5,N) #time\n dr = r[1] - r[0] #differential space element\n dt = t[1] - t[0] # differential time element\n lam = c*dt/dr # lambda\n\n #discretize functions\n g = np.zeros(N)\n g = gfunc(r)\n f = np.zeros(N)\n f = func(r)\n h = np.zeros(N)\n h = hfunc(r)\n f[0] = 1\n g[0] = 1e4\n Psi = np.zeros((N,N))\n Pi = np.zeros((N,N))\n psi = np.zeros((N,N))\n #initial condition\n for i in range(N):\n Psi[0,i] = init(r[i])\n psi[0,i] = init2(r[i])\n\n #BCs\n Psi[:,0] = 0\n Pi [:,0] = 0\n psi[:,0] = 1e-3\n\n Psi[:,-1] = 0\n Pi [:,-1] = 0\n\n #solving PDE\n T = 250\n for n in range(1,T): ##time\n for j in range(1,N-1): ##space\n if (n == 0):\n Psi[1,j] = 0.75*Psi[0,j] + 0.25*Psi[2,j] + lam*0.5*((f[j+1]*Pi[0,j+1]) - (f[j-1]*Pi[0,j-1]))\n Pi[1,j] = 0.75*Pi[0,j] + 0.25*Pi[2,j] + lam*0.5*g[j]*(((1/g[j+1])*f[j+1]*Psi[0,j+1]) - ((1/g[j-1])*f[j-1]*Psi[0,j-1]))\n +48*np.pi*np.exp(-12*psi[0,j]**2)*psi[0,j]*(h[j])*dt\n psi[n,j+1] = psi[n,j] + dr*Psi[n,j+1]\n\n Psi[n+1,j] = Psi[n-1,j] + lam*((f[j+1]*Pi[n,j+1]) - (f[j+1]*Pi[n,j-1]))\n Pi[n+1,j] = Pi[n-1,j] + lam*g[j]*(((1/g[j+1])*f[j+1]*Psi[n,j+1]) - ((1/g[j-1])*f[j-1]*Psi[n,j-1])) \n +48*np.pi*np.exp(-12*psi[n,j]**2)*psi[n,j]*(h[j])*dt\n psi[n,j+1] = psi[n,j] + dr*Psi[n,j+1]\n #plotting space vs time\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n X, Y = np.meshgrid(r[2:], t[0:T:20])\n Z = psi[0:T:20,2:]\n ax.set_xlabel('r')\n ax.set_ylabel('time')\n ax.set_zlabel('psi')\n surf = ax.scatter3D(X, Y, Z, cmap='viridis')\n ax.set_title('Solution for psi');\n ax.set_xlim3d(0, sol.t[-1])\n #ax.set_ylim3d(0,0.2)\n ax.set_zlim3d(-0.001,0.000)\n\n", "repo_name": "ekremdemirboga/PHYS-414-514-Final-Project", "sub_path": "Beyond Einstein/wave_equation_with_added_term.py", "file_name": "wave_equation_with_added_term.py", "file_ext": "py", "file_size_in_byte": 3458, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "tov_solver.TOV_solver", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 19, "usage_type": "call"}, {"api_name": "scipy.interpolate.interp1d", "line_number": 20, "usage_type": "call"}, {"api_name": "scipy.interpolate", "line_number": 20, "usage_type": "name"}, {"api_name": "tov_solver.TOV_solver", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 25, "usage_type": "call"}, {"api_name": "scipy.interpolate.interp1d", "line_number": 26, "usage_type": "call"}, {"api_name": "scipy.interpolate", "line_number": 26, "usage_type": "name"}, {"api_name": "tov_solver.TOV_solver", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 31, "usage_type": "call"}, {"api_name": "scipy.interpolate.interp1d", "line_number": 32, "usage_type": "call"}, {"api_name": "scipy.interpolate", "line_number": 32, "usage_type": "name"}, {"api_name": "tov_solver.TOV_solver", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 53, "usage_type": "call"}, {"api_name": "tov_solver.TOV_solver", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 99, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 104, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 107, "usage_type": "name"}, {"api_name": "numpy.meshgrid", "line_number": 109, "usage_type": "call"}]} +{"seq_id": "28865489309", "text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nimport re\nfrom libs.pyaml import configure\nfrom modules.interaction.metric import AbstractMetric\n\n\ndef _set_metric(metric=None):\n if not metric:\n metric = AbstractMetric()\n for key, value in configure['metric'].items():\n setattr(metric, key, value)\n if hasattr(metric, 'expend_time'):\n seconds = 0\n items = re.findall(r'\\d+', metric.expend_time)\n bases = [1, 60, 3600, 86400]\n for i, item in enumerate(reversed(items)):\n seconds += int(item) * bases[i]\n print(seconds, '秒')\n print(metric)\n\n\nif __name__ == '__main__':\n _set_metric()\n", "repo_name": "beikejinmiao/HawkSec", "sub_path": "tests/metric_test.py", "file_name": "metric_test.py", "file_ext": "py", "file_size_in_byte": 663, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "modules.interaction.metric.AbstractMetric", "line_number": 10, "usage_type": "call"}, {"api_name": "libs.pyaml.configure", "line_number": 11, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 15, "usage_type": "call"}]} +{"seq_id": "17966669232", "text": "import logging\n\nfrom flask_restx import Api\nfrom web import settings\n\n# from sqlalchemy.orm.exc import NoResultFound\n\nlog = logging.getLogger(__name__)\n\napi = Api(\n version='1.0',\n title='GoodAttitude 결제 구현 API.',\n description='GA 유저가 텀블러를 사용하기 위해, 카드를 선 등록 후 -> 대여 기간에 늦거나 반납을 하지 않았을 시, 해당 결제 금액만큼 자동결제(빌링)\\n'\n '카드사1: toss payments\\n'\n '카드사1: kakaopay (구현 예정)\\n'\n '기능 1: 일반 카드 결제\\n'\n '기능 2: 카드 선 등록 -> 자동 결제 (빌링)\\n'\n '기능 2-1: 대여기간이 늦어질 시, status code: 1\\n'\n '기능 2-2: 제품에 하자가 생길 시, status code:2\\n'\n '기능 2-3: 반납이 안될 시(대여기간이 늦어진 상태에서 1차 결제를 하고, 그 후에도 반납이 안되면 추가 결제), status code:3\\n'\n '기능 3: 결제 취소 (구현 예정)\\n'\n '기능 4: 결제 조회 (구현 예정)\\n'\n '기능 5: 결제 승인 및 취소 조회 (구현 예정)\\n'\n '기능 6: 현금영수증 발급 및 취소 (구현 예정)\\n'\n '기능 7: 수동 정산 (구현 예정)\\n'\n '기능 8: 카드사 혜택 조회 (구현 예정)\\n'\n '기능 9: 세금 처리 (구현 예정)\\n',\n terms_url=\"/\",\n contact_email=\"tyty587587@gmail.com\",\n contact=\"010-7704-1961\",\n)\n\n\n@api.errorhandler\ndef default_error_handler(e):\n message = 'An unhandled exception occurred.'\n log.exception(message)\n\n if not settings.FLASK_DEBUG:\n return {'message': message}, 500\n\n\n# @api.errorhandler(NoResultFound)\n# def database_not_found_error_handler(e):\n# \"\"\"No results found in database\"\"\"\n# log.warning(traceback.format_exc())\n# return {'message': 'A database result was required but none was found.'}, 404", "repo_name": "KYUSEONGHAN/payment", "sub_path": "web/restapi.py", "file_name": "restapi.py", "file_ext": "py", "file_size_in_byte": 2001, "program_lang": "python", "lang": "ko", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "logging.getLogger", "line_number": 8, "usage_type": "call"}, {"api_name": "flask_restx.Api", "line_number": 10, "usage_type": "call"}, {"api_name": "web.settings.FLASK_DEBUG", "line_number": 39, "usage_type": "attribute"}, {"api_name": "web.settings", "line_number": 39, "usage_type": "name"}]} +{"seq_id": "73337791744", "text": "from PIL import Image\nimport pytesseract\nimport os\n\ndef getPhotoToText():\n pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'\n\n arr = os.listdir(\"images\")\n image_path = f\"images/{arr[0]}\"\n image = Image.open(image_path)\n\n text = pytesseract.image_to_string(image, lang=\"rus\")\n return text", "repo_name": "KirillhacT/projects", "sub_path": "PhotoToTextAPI/photoToText.py", "file_name": "photoToText.py", "file_ext": "py", "file_size_in_byte": 343, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pytesseract.pytesseract", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 8, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 10, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 10, "usage_type": "name"}, {"api_name": "pytesseract.image_to_string", "line_number": 12, "usage_type": "call"}]} +{"seq_id": "31916554562", "text": "import copy\nimport json\nimport os\n\nDIR_1 = '/Users/hsor001/Projects/musculoskeletal/workflows/sparc/data/argon_viewer_out'\nDIR_2 = '/Users/hsor001/Projects/musculoskeletal/data/vickie_shim_6f1/'\n\nVERSION_INFO = {\n \"OpenCMISS-Argon Version\": [\n \"0\",\n \"2\",\n \"2\"\n ],\n}\n\nSCENE_GRAPHICS = {\n \"Scene\": {\n \"Graphics\": [\n {\n \"BoundaryMode\": \"ALL\",\n \"CoordinateField\": \"coordinates\",\n \"ElementFaceType\": \"ALL\",\n \"FieldDomainType\": \"MESH2D\",\n \"Material\": \"black\",\n \"RenderLineWidth\": 1,\n \"RenderPointSize\": 1,\n \"RenderPolygonMode\": \"SHADED\",\n \"Scenecoordinatesystem\": \"LOCAL\",\n \"SelectMode\": \"ON\",\n \"SelectedMaterial\": \"default_selected\",\n \"Surfaces\": {},\n \"Tessellation\": \"default\",\n \"Type\": \"SURFACES\",\n \"VisibilityFlag\": True\n }\n ],\n \"VisibilityFlag\": True\n }\n}\n\nFIELD_MODULE = {\n \"Fieldmodule\": {\n \"Fields\": [\n {\n \"CoordinateSystemType\": \"RECTANGULAR_CARTESIAN\",\n \"FieldFiniteElement\": {\n \"ComponentNames\": [\n \"x\",\n \"y\",\n \"z\"\n ],\n \"NumberOfComponents\": 3\n },\n \"IsManaged\": True,\n \"IsTypeCoordinate\": True,\n \"Name\": \"coordinates\"\n },\n {\n \"CoordinateSystemType\": \"FIBRE\",\n \"FieldFiniteElement\": {\n \"ComponentNames\": [\n \"fibre angle\",\n \"imbrication angle\",\n \"sheet angle\"\n ],\n \"NumberOfComponents\": 3\n },\n \"IsManaged\": True,\n \"IsTypeCoordinate\": False,\n \"Name\": \"fibres\"\n }\n ]\n },\n}\n\nEMPTY_REGION = {\n \"Fieldmodule\": None,\n \"Scene\": {\n \"Graphics\": None,\n \"VisibilityFlag\": True\n }\n}\n\nSKIP_REGIONS = ['maxilla', ]\n\n\ndef main():\n os.walk(DIR_2)\n data_files = []\n for root, dirs, files in os.walk(DIR_2, topdown=True):\n current_dir = {\n 'node_files': [],\n 'elem_files': []\n }\n for file in files:\n # print(file)\n if file.endswith('.EXNODE'):\n current_dir['node_files'].append(os.path.join(root, file))\n if file.endswith('.EXELEM'):\n current_dir['elem_files'].append(os.path.join(root, file))\n\n if len(current_dir[\"node_files\"]):\n data_files.append(current_dir)\n\n common_path = os.path.commonpath([d[\"node_files\"][0] for d in data_files])\n\n argon_document = {\n **VERSION_INFO\n }\n\n root_region = copy.deepcopy(EMPTY_REGION)\n\n bits = []\n for index, data in enumerate(data_files):\n\n exnode_file = data[\"node_files\"][0]\n region_path = exnode_file.replace(common_path, '')\n\n region_parts = region_path.split('/')\n region_parts.pop(0)\n base_region = root_region\n for i in range(len(region_parts) - 1):\n current_region = region_parts[i].lower()\n\n if \"ChildRegions\" not in base_region:\n base_region[\"ChildRegions\"] = []\n\n child_region_names = []\n for region_info in base_region[\"ChildRegions\"]:\n child_region_names.append(region_info[\"Name\"])\n\n if current_region not in child_region_names:\n new_child = copy.deepcopy(EMPTY_REGION)\n new_child['Name'] = current_region\n base_region[\"ChildRegions\"].append(new_child)\n child_region_names.append(current_region)\n\n j = child_region_names.index(current_region)\n\n base_region = base_region[\"ChildRegions\"][j]\n\n # base_region[\"Fieldmodule\"] = copy.deepcopy(FIELD_MODULE[\"Fieldmodule\"])\n base_region[\"Scene\"] = copy.deepcopy(SCENE_GRAPHICS[\"Scene\"])\n bit = f\"'{region_parts[-2].lower()}',\"\n # if bit not in bits:\n # bits.append(bit)\n if region_parts[-2].lower() in SKIP_REGIONS:\n continue\n\n if \"Model\" not in base_region:\n base_region[\"Model\"] = {\"Sources\": []}\n\n for node_file in data['node_files']:\n exnode_path = node_file # .replace(common_path, '')[1:]\n base_region[\"Model\"][\"Sources\"].insert(\n 0,\n {\n \"FileName\": exnode_path,\n \"RegionName\": os.path.dirname(region_path).lower(),\n \"Type\": \"FILE\"\n }\n )\n for elem_file in data['elem_files']:\n exelem_path = elem_file # .replace(common_path, '')[1:]\n base_region[\"Model\"][\"Sources\"].append(\n {\n \"FileName\": exelem_path,\n \"RegionName\": os.path.dirname(region_path).lower(),\n \"Type\": \"FILE\"\n }\n )\n\n if 'MUSCLES' in region_path or 'NECK' in region_path:\n base_region[\"Scene\"][\"Graphics\"][0][\"Material\"] = \"muscle\"\n if 'BONE' in region_path:\n base_region[\"Scene\"][\"Graphics\"][0][\"Material\"] = \"bone\"\n if 'LIGAMENT' in region_path:\n base_region[\"Scene\"][\"Graphics\"][0][\"Material\"] = \"white\"\n if 'SKIN' in region_path:\n base_region[\"Scene\"][\"Graphics\"][0][\"Material\"] = \"brown\"\n\n argon_document[\"RootRegion\"] = root_region\n\n print('\\n'.join(bits))\n with open(os.path.join(DIR_2, 'test_file.json'), 'w') as f:\n f.write(json.dumps(argon_document, default=lambda o: o.__dict__, sort_keys=True, indent=2))\n\n\nif __name__ == \"__main__\":\n main()\n\nmodel_sources = {\n \"Model\": {\n \"Sources\": [\n {\n \"FileName\": \"FEMUR.EXNODE\",\n \"RegionName\": \"/left_lower_limb/bones/femur\",\n \"Type\": \"FILE\"\n },\n {\n \"FileName\": \"FEMUR.EXELEM\",\n \"RegionName\": \"/left_lower_limb/bones/femur\",\n \"Type\": \"FILE\"\n }\n ]\n },\n}\n", "repo_name": "hsorby/shell-scripts", "sub_path": "opencmiss/generate_argon_document.py", "file_name": "generate_argon_document.py", "file_ext": "py", "file_size_in_byte": 6332, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.walk", "line_number": 88, "usage_type": "call"}, {"api_name": "os.walk", "line_number": 90, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 98, "usage_type": "call"}, {"api_name": "os.path", "line_number": 98, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 100, "usage_type": "call"}, {"api_name": "os.path", "line_number": 100, "usage_type": "attribute"}, {"api_name": "os.path.commonpath", "line_number": 105, "usage_type": "call"}, {"api_name": "os.path", "line_number": 105, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 111, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 133, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 143, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 159, "usage_type": "call"}, {"api_name": "os.path", "line_number": 159, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 168, "usage_type": "call"}, {"api_name": "os.path", "line_number": 168, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 185, "usage_type": "call"}, {"api_name": "os.path", "line_number": 185, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 186, "usage_type": "call"}]} +{"seq_id": "14915590730", "text": "from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QMainWindow, QApplication\nimport sys\nimport boj\n\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\nimport matplotlib.pyplot as plt\n\nimport random\n\nclass MainWindow(object):\n def setupUI(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.setWindowModality(QtCore.Qt.NonModal)\n MainWindow.resize(640, 320)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(270, 240, 100, 40))\n self.pushButton.setObjectName(\"pushButton\")\n self.label = QtWidgets.QLabel(self.centralwidget)\n self.label.setEnabled(True)\n self.label.setGeometry(QtCore.QRect(0, 30, 640, 130))\n font = QtGui.QFont()\n font.setFamily(\"Arial Rounded MT Bold\")\n font.setPointSize(128)\n font.setBold(True)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setFrameShape(QtWidgets.QFrame.NoFrame)\n self.label.setFrameShadow(QtWidgets.QFrame.Raised)\n self.label.setTextFormat(QtCore.Qt.RichText)\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setOpenExternalLinks(False)\n self.label.setObjectName(\"label\")\n self.label_2 = QtWidgets.QLabel(self.centralwidget)\n self.label_2.setGeometry(QtCore.QRect(0, 160, 640, 21))\n font = QtGui.QFont()\n font.setFamily(\"Arial Rounded MT Bold\")\n font.setPointSize(16)\n font.setBold(True)\n font.setWeight(75)\n self.label_2.setFont(font)\n self.label_2.setFrameShape(QtWidgets.QFrame.NoFrame)\n self.label_2.setFrameShadow(QtWidgets.QFrame.Raised)\n self.label_2.setTextFormat(QtCore.Qt.RichText)\n self.label_2.setAlignment(QtCore.Qt.AlignCenter)\n self.label_2.setOpenExternalLinks(False)\n self.label_2.setObjectName(\"label_2\")\n self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)\n self.lineEdit.setEnabled(True)\n self.lineEdit.setGeometry(QtCore.QRect(230, 200, 180, 30))\n self.lineEdit.setText(\"\")\n self.lineEdit.setObjectName(\"lineEdit\")\n MainWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n self.actionsddjd = QtWidgets.QAction(MainWindow)\n self.actionsddjd.setObjectName(\"actionsddjd\")\n self.actionvdmns = QtWidgets.QAction(MainWindow)\n self.actionvdmns.setObjectName(\"actionvdmns\")\n\n self.retranslateUI(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUI(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"BOJ.GG\"))\n self.pushButton.setText(_translate(\"MainWindow\", \"검색\"))\n self.label.setText(_translate(\"MainWindow\", \"BOJ.GG\"))\n self.label_2.setText(_translate(\"MainWindow\", \"Beakjoon Online Judge 전적검색 프로그램\"))\n self.actionsddjd.setText(_translate(\"MainWindow\", \"sddjd\"))\n self.actionvdmns.setText(_translate(\"MainWindow\", \"vdmns\"))\n\n\nclass UserInfoWindow(object):\n def setupUI(self, MainWindow, userID):\n _translate = QtCore.QCoreApplication.translate\n\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(840, 640)\n\n self.userID = userID\n\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n\n self.statusTable = QtWidgets.QTableWidget(self.centralwidget)\n self.statusTable.setGeometry(QtCore.QRect(220, 40, 611, 331))\n self.statusTable.setShowGrid(False)\n self.statusTable.setObjectName(\"statusTable\")\n\n self.statusTableTitle = [\"문제 번호\", \"문제 이름\", \"결과\", \"메모리\", \"시간\", \"언어\", \"코드 길이\", \"제출한 시간\"]\n self.statusTable.setColumnCount(len(self.statusTableTitle))\n for i in range(len(self.statusTableTitle)):\n item = QtWidgets.QTableWidgetItem()\n item.setText(_translate(\"MainWindow\", self.statusTableTitle[i]))\n self.statusTable.setHorizontalHeaderItem(i, item)\n self.statusTable.setSortingEnabled(False)\n self.statusTable.verticalHeader().setVisible(False)\n\n self.infoTable = QtWidgets.QTableWidget(self.centralwidget)\n self.infoTable.setGeometry(QtCore.QRect(10, 40, 201, 331))\n self.infoTable.setShowGrid(False)\n self.infoTable.setObjectName(\"infoTable\")\n self.infoTable.setColumnCount(2)\n self.infoTable.setColumnWidth(0, 70)\n self.infoTable.setColumnWidth(1, 130)\n self.infoTable.setRowCount(12)\n for i in range(self.infoTable.rowCount()):\n for j in range(self.infoTable.columnCount()):\n item = QtWidgets.QTableWidgetItem()\n self.infoTable.setItem(i, j, item)\n self.infoTable.horizontalHeader().setVisible(False)\n self.infoTable.verticalHeader().setVisible(False)\n\n self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)\n self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 380, 821, 251))\n self.verticalLayoutWidget.setObjectName(\"verticalLayoutWidget\")\n self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)\n self.verticalLayout.setContentsMargins(10, 10, 10, 10)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.figure = plt.figure()\n self.graphView = FigureCanvas(self.figure)\n self.verticalLayout.addWidget(self.graphView)\n\n self.refreshButton = QtWidgets.QPushButton(self.centralwidget)\n self.refreshButton.setGeometry(QtCore.QRect(740, 580, 50, 50))\n self.refreshButton.setText(\"\")\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\"refresh.png\"), QtGui.QIcon.Normal,\n QtGui.QIcon.Off)\n self.refreshButton.setIcon(icon)\n self.refreshButton.setIconSize(QtCore.QSize(32, 32))\n self.refreshButton.setObjectName(\"refreshButton\")\n\n self.infoLabel = QtWidgets.QLabel(self.centralwidget)\n self.infoLabel.setGeometry(QtCore.QRect(10, 10, 101, 21))\n self.infoLabel.setObjectName(\"infoLabel\")\n\n self.statusLabel = QtWidgets.QLabel(self.centralwidget)\n self.statusLabel.setGeometry(QtCore.QRect(220, 10, 101, 21))\n self.statusLabel.setObjectName(\"statusLabel\")\n\n self.exitButton = QtWidgets.QPushButton(self.centralwidget)\n self.exitButton.setGeometry(QtCore.QRect(780, 580, 50, 50))\n icon1 = QtGui.QIcon()\n icon1.addPixmap(QtGui.QPixmap(\"close.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.exitButton.setIcon(icon1)\n self.exitButton.setIconSize(QtCore.QSize(32, 32))\n self.exitButton.setObjectName(\"exitButton\")\n MainWindow.setCentralWidget(self.centralwidget)\n\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"BOJ.GG\"))\n self.infoLabel.setText(_translate(\"MainWindow\", self.userID + \" 정보\"))\n self.statusLabel.setText(_translate(\"MainWindow\", \"채점 현황\"))\n\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n self.setupUserInfo(MainWindow)\n self.setupStatus(MainWindow)\n self.setupGraph(MainWindow)\n\n\n def setupUserInfo(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n __sortingEnabled = self.infoTable.isSortingEnabled()\n self.infoTable.setSortingEnabled(False)\n data = boj.getUserInfo(self.userID)\n for i in range(len(data)):\n for j in range(len(data[i])):\n item = self.infoTable.item(i, j)\n item.setText(_translate(\"MainWindow\", data[i][j]))\n self.infoTable.setSortingEnabled(__sortingEnabled)\n\n def setupStatus(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n __sortingEnabled = self.statusTable.isSortingEnabled()\n data = boj.getStatus(self.userID)\n self.statusTable.setRowCount(len(data))\n for i in range(len(data)):\n for j in range(len(data[i])):\n item = QtWidgets.QTableWidgetItem()\n\n if j == 2:\n font = QtGui.QFont()\n font.setBold(True)\n font.setWeight(75)\n item.setFont(font)\n brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))\n brush.setStyle(QtCore.Qt.NoBrush)\n item.setBackground(brush)\n if data[i][j] == \"맞았습니다!!\":\n brush = QtGui.QBrush(QtGui.QColor(0, 255, 0))\n else:\n brush = QtGui.QBrush(QtGui.QColor(255, 0, 0))\n brush.setStyle(QtCore.Qt.NoBrush)\n item.setForeground(brush)\n\n item.setText(_translate(\"MainWindow\", data[i][j]))\n self.statusTable.setItem(i, j, item)\n self.statusTable.setSortingEnabled(__sortingEnabled)\n\n def setupGraph(self, MainWindow):\n data = boj.getAcceptedData(self.userID)\n self.figure.clear()\n ax = self.figure.add_subplot(111)\n # ax.bar(reversed(list(data.keys())), reversed(list(data.values())), color='g')\n ax.bar(list(reversed(list(data.keys()))), list(reversed(list(data.values()))), color='g')\n # ax.hist(list(data.keys()), data.values())\n self.graphView.draw()\n\nclass Window(QMainWindow):\n def __init__(self, parent=None):\n super(Window, self).__init__(parent)\n self.mainWindow = MainWindow()\n self.userInfoWindow = UserInfoWindow()\n self.startMainWindow()\n # self.startUserInfoWindow('sunjbs98')\n\n def startMainWindow(self):\n self.mainWindow.setupUI(self)\n self.mainWindow.pushButton.clicked.connect(lambda: self.startUserInfoWindow(self.mainWindow.lineEdit.text()))\n self.show()\n\n def startUserInfoWindow(self, userID):\n if boj.isBOJUser(userID):\n self.userInfoWindow.setupUI(self, userID)\n self.userInfoWindow.exitButton.clicked.connect(self.startMainWindow)\n self.show()\n else:\n self.mainWindow.statusbar.showMessage(\"존재하지 않는 아이디입니다.\")\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n w = Window()\n sys.exit(app.exec_())\n", "repo_name": "ParkJH1/BOJ.GG", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 10751, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "PyQt5.QtCore.Qt", "line_number": 15, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 15, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 17, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 17, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 19, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 19, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 20, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 20, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 22, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 22, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 24, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 24, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 25, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 25, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFrame", "line_number": 31, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 31, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFrame", "line_number": 32, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 32, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 33, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 33, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 34, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 34, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 37, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 37, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 38, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 38, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 39, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 39, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFrame", "line_number": 45, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 45, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFrame", "line_number": 46, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 46, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 47, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 47, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 48, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 48, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 51, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 51, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 53, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 53, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QStatusBar", "line_number": 57, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 57, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 60, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 60, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 62, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 62, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QMetaObject.connectSlotsByName", "line_number": 66, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QMetaObject", "line_number": 66, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 66, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 69, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 69, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 80, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 80, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 87, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 87, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QTableWidget", "line_number": 90, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 90, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 91, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 91, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 98, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 98, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QTableWidget", "line_number": 104, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 104, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 105, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 105, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 114, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 114, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 119, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 119, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 120, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 120, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QVBoxLayout", "line_number": 122, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 122, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg", "line_number": 126, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 129, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 129, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 130, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 130, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 132, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 132, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 133, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 133, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 133, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 134, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui", "line_number": 134, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QSize", "line_number": 136, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 136, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 139, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 139, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 140, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 140, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 143, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 143, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 144, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 144, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 147, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 147, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 148, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 148, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 149, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 149, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 150, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 150, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 150, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QSize", "line_number": 152, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 152, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QMetaObject.connectSlotsByName", "line_number": 160, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QMetaObject", "line_number": 160, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 160, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 168, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 168, "usage_type": "name"}, {"api_name": "boj.getUserInfo", "line_number": 171, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 179, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 179, "usage_type": "name"}, {"api_name": "boj.getStatus", "line_number": 181, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 185, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 185, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 188, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 188, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QBrush", "line_number": 192, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 192, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QColor", "line_number": 192, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 193, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 193, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QBrush", "line_number": 196, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 196, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QColor", "line_number": 196, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QBrush", "line_number": 198, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 198, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QColor", "line_number": 198, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 199, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 199, "usage_type": "name"}, {"api_name": "boj.getAcceptedData", "line_number": 207, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 215, "usage_type": "name"}, {"api_name": "boj.isBOJUser", "line_number": 229, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 237, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 237, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 239, "usage_type": "call"}]} +{"seq_id": "31525616767", "text": "import numpy as np\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import RandomForestClassifier\nfrom typing import Tuple\n\nfrom simulation.dgps import outcomes_not_treated, outcomes_treated\n\n\ndef regression_prediction(x_train: np.ndarray, y_train: np.ndarray, x_test: np.ndarray, **kwargs) -> np.ndarray:\n # fit random forest regression\n model = RandomForestRegressor(**kwargs)\n model.fit(x_train, y_train)\n # predict outcomes\n y_pred = model.predict(x_test)\n return y_pred\n\ndef classification_prediction(x_train: np.ndarray, w_train: np.ndarray, x_test: np.ndarray, **kwargs) -> np.ndarray:\n # fit random forest classification\n model = RandomForestClassifier(**kwargs)\n model.fit(x_train, w_train)\n # predict treatment probabilities\n w_pred = model.predict_proba(x_test)[:,1]\n return w_pred\n\ndef estimate_ate(y: np.ndarray, w: np.ndarray, x: np.ndarray, x_policy: np.ndarray, true_ate: float, cate_type: str, \n nfolds: int=2, under_sample_train: bool=False, under_sample_test: bool=False, **kwargs) -> float:\n # if both train and test sets are under-sampled, under-sample the entire dataset\n if under_sample_train and under_sample_test:\n y, w, x = _under_sample_majority_treatment(y, w, x)\n # compute pseudo-outcomes\n tau = _estimate_pseudo_outcomes(y, w, x, nfolds, under_sample_fitting=under_sample_train and not under_sample_test,**kwargs)\n # estimate ATE using doubly robust estimator\n ate = np.mean(tau)\n # compute optimal policy and its regret\n w_opt = _compute_optimal_policy(tau-true_ate, x, x_policy, **kwargs) # use the true ATE as the cost for implementing the policy\n regret = _compute_regret(w_opt,x_policy, true_ate, cate_type)\n return ate, regret\n\n\ndef _estimate_pseudo_outcomes(y: np.ndarray, w: np.ndarray, x: np.ndarray, nfolds: int=2, under_sample_fitting: bool=False, **kwargs) -> np.ndarray:\n # function to estimate pseudo-outcomes using cross-fitting\n # split sample into folds\n n = x.shape[0]\n idx = np.random.choice(np.arange(n), size=n, replace=False)\n idx = np.array_split(idx, nfolds)\n # estimate ration of treated to non-treated\n ratio_treated = np.sum(w)/np.sum(1-w)\n # initialize pseudo-outcomes\n tau = np.zeros(n)\n # loop over folds\n for i in range(nfolds):\n # split sample into train and test\n idx_test = idx[i]\n idx_train = np.concatenate(idx[:i] + idx[(i+1):])\n x_train = x[idx_train,:]\n y_train = y[idx_train]\n w_train = w[idx_train]\n x_test = x[idx_test,:]\n y_test = y[idx_test]\n w_test = w[idx_test]\n # if train and/or test sample have no treated or no non-treated, set tau to nan\n if (np.sum(w_train==1)==0) or (np.sum(w_train==0)==0) or (np.sum(w_test==1)==0) or (np.sum(w_test==0)==0):\n tau[idx_test] = np.nan\n continue\n # under-sample fitting folds if specified\n if under_sample_fitting:\n y_train, w_train, x_train=_under_sample_majority_treatment(y_train, w_train, x_train)\n # predict outcomes using data on the treated\n y_pred_treated = regression_prediction(x_train[w_train==1,:], y_train[w_train==1], x_test, **kwargs)\n # predict outcomes using data on the non-treated\n y_pred_not_treated = regression_prediction(x_train[w_train==0,:], y_train[w_train==0], x_test, **kwargs)\n # predict treatment probabilities\n w_pred = classification_prediction(x_train, w_train, x_test, **kwargs)\n # correct predicted probabilities for under-sampling (Dal Pozzolo et al., 2015)\n if under_sample_fitting:\n if ratio_treated < 1:\n # correct for under-sampling of the treated\n w_pred = ratio_treated*w_pred/(ratio_treated*w_pred - w_pred + 1)\n else:\n # correct for under-sampling of the non-treated\n w_pred = w_pred/((1-w_pred)/ratio_treated - w_pred)\n # compute pseudo-outcomes on test set\n tau[idx_test] = y_pred_treated-y_pred_not_treated + w_test*(y_test-y_pred_treated)/(w_pred+1e-10) - (1-w_test)*(y_test-y_pred_not_treated)/(1-w_pred+1e-10)\n return tau\n\n\n\ndef _under_sample_majority_treatment(y: np.ndarray, w: np.ndarray, x: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n n = x.shape[0]\n # under-sample the majority class\n n_treated = np.sum(w)\n n_not_treated = n - n_treated\n if n_treated > n_not_treated:\n # under-sample treated\n idx = np.where(w == 1)[0]\n idx = np.random.choice(idx, size=n_not_treated, replace=False)\n idx = np.concatenate((idx, np.where(w == 0)[0]))\n else:\n # under-sample not treated\n idx = np.where(w == 0)[0]\n idx = np.random.choice(idx, size=n_treated, replace=False)\n idx = np.concatenate((idx, np.where(w == 1)[0]))\n x = x[idx,:]\n y = y[idx]\n w = w[idx]\n return y, w, x\n\n\ndef _compute_optimal_policy(pseudo_outcome: np.ndarray, x_test: np.ndarray, x_policy: np.ndarray, **kwargs) -> np.ndarray:\n # define classification target:\n # 1 if pseudo-outcome is positive, 0 otherwise\n pseudo_outcome_sign = pseudo_outcome > 0\n # define weights for random forest classification\n weight = np.abs(pseudo_outcome)\n # fit random forest classification\n model = RandomForestClassifier(**kwargs)\n model.fit(x_test, pseudo_outcome_sign, sample_weight=weight)\n # predict optimal policy\n w_opt = model.predict(x_policy)\n return w_opt\n\ndef _compute_regret(w_opt: np.ndarray, x_policy: np.ndarray, true_ate: bool, cate_type: str) -> float:\n y_treated = outcomes_treated(x_policy, true_ate, cate_type)\n y_not_treated = outcomes_not_treated(x_policy)\n # determine oracle policy (i.e. policy that maximizes the expected outcome)\n w_oracle = y_treated - y_not_treated > true_ate # treat only if individual CATE is larger than true ATE\n # define outcome based on policy\n y_policy = y_treated*w_opt + y_not_treated*(1-w_opt) - w_opt*true_ate\n y_oracle = y_treated*w_oracle + y_not_treated*(1-w_oracle) - w_oracle*true_ate\n # compute regret as the average outcome of the oracle policy minus the average outcome of the optimal policy\n regret = np.mean(y_oracle) - np.mean(y_policy)\n return regret\n", "repo_name": "dballinari/simulation-unbalanced-treatment", "sub_path": "simulation/estimator.py", "file_name": "estimator.py", "file_ext": "py", "file_size_in_byte": 6318, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.ndarray", "line_number": 9, "usage_type": "attribute"}, {"api_name": "sklearn.ensemble.RandomForestRegressor", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 17, "usage_type": "attribute"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 25, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 40, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 44, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.array_split", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 63, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 88, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 96, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 101, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 102, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 88, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 109, "usage_type": "attribute"}, {"api_name": "numpy.abs", "line_number": 114, "usage_type": "call"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 122, "usage_type": "attribute"}, {"api_name": "simulation.dgps.outcomes_treated", "line_number": 123, "usage_type": "call"}, {"api_name": "simulation.dgps.outcomes_not_treated", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 131, "usage_type": "call"}]} +{"seq_id": "5245815186", "text": "from django.shortcuts import render, get_object_or_404\nfrom django.views import View\nfrom news.models import News\nfrom core.models import Index\nfrom contacts.models import *\nfrom pages.models import Page\nfrom django.http import Http404\n\n\nclass IndexView(View):\n def get(self, request):\n news = News.objects.filter(is_active=True)[:3]\n index = Index.objects.first()\n\n addresses = Address.objects.all()\n ptypes = PhoneType.objects.all()\n emails = Email.objects.all()\n schedule = Schedule.objects.all()\n map_code = MapCode.objects.filter(map_type='contacts').first()\n\n areas = ActivityArea.objects.all()\n area_code = MapCode.objects.filter(map_type='area').first()\n\n context = {\n 'news': news,\n 'index': index,\n 'addresses': addresses,\n 'ptypes': ptypes,\n 'emails': emails,\n 'schedule': schedule,\n 'map_code': map_code,\n 'areas': areas,\n 'area_code': area_code,\n }\n return render(request, 'core/index.html', context)\n\n\nclass CalcView(View):\n def get(self, request):\n index = Index.objects.first()\n koef = str(index.koef).replace(',', '.')\n\n context = {\n 'koef': koef,\n }\n return render(request, 'core/calc.html', context)\n\n\nclass DropMenuView(View):\n def get(self, request, drop_menu):\n drop_page = get_object_or_404(Page, slug=drop_menu)\n\n context = {\n 'drop_page': drop_page,\n }\n return render(request, 'core/drop_menu.html', context)", "repo_name": "gurgenXD/maykoptec", "sub_path": "core/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1610, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.views.View", "line_number": 10, "usage_type": "name"}, {"api_name": "news.models", "line_number": 12, "usage_type": "name"}, {"api_name": "news.models.News.objects.filter", "line_number": 12, "usage_type": "call"}, {"api_name": "news.models.News.objects", "line_number": 12, "usage_type": "attribute"}, {"api_name": "news.models.News", "line_number": 12, "usage_type": "name"}, {"api_name": "core.models.Index.objects.first", "line_number": 13, "usage_type": "call"}, {"api_name": "core.models.Index.objects", "line_number": 13, "usage_type": "attribute"}, {"api_name": "core.models.Index", "line_number": 13, "usage_type": "name"}, {"api_name": "news.models", "line_number": 25, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 35, "usage_type": "call"}, {"api_name": "django.views.View", "line_number": 38, "usage_type": "name"}, {"api_name": "core.models.Index.objects.first", "line_number": 40, "usage_type": "call"}, {"api_name": "core.models.Index.objects", "line_number": 40, "usage_type": "attribute"}, {"api_name": "core.models.Index", "line_number": 40, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 46, "usage_type": "call"}, {"api_name": "django.views.View", "line_number": 49, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 51, "usage_type": "call"}, {"api_name": "pages.models.Page", "line_number": 51, "usage_type": "argument"}, {"api_name": "django.shortcuts.render", "line_number": 56, "usage_type": "call"}]} +{"seq_id": "40969445493", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 20 13:22:29 2015\r\n\r\n@author: Don\r\n\"\"\"\r\n\r\n#! /usr/bin/python\r\n\r\nimport datetime\r\nimport time\r\nimport csv\r\nimport smtplib\r\nimport os, sys\r\nimport itertools\r\n\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\n\r\n \r\ndef processData():\r\n \r\n #partialfilename = \"C:\\myFolder\\StockChange\"\r\n \r\n ordersDataList = []\r\n \r\n ordersDataList.append(getListingCount()) #HourlyListingCount\r\n \r\n emailSubject = constructEmail(\"S\",ordersDataList)\r\n emailBody = constructEmail(\"B\",ordersDataList)\r\n \r\n sendEmail(emailSubject,emailBody)\r\n \r\n return\r\n\r\ndef cleanData():\r\n \r\n partialfilename = \"C:\\myFolder\\StockChange\"\r\n lstngTimeStampPrev = \" \"\r\n \r\n fib1 = open(partialfilename+\".csv\") \r\n fi_b1 = csv.reader(fib1)\r\n \r\n fob1 = open(partialfilename+\"Clean.csv\",'w')\r\n fo_b1 = csv.writer(fob1,lineterminator='\\n')\r\n\r\n for row1 in fi_b1:\r\n \r\n if row1[3] == lstngTimeStampPrev:\r\n x = 0\r\n else:\r\n lstngTimeStampPrev = row1[3]\r\n fo_b1.writerow(row1)\r\n\r\n fib1.close()\r\n fob1.close()\r\n \r\n return \r\n \r\ndef getListingCount():\r\n \r\n partialfilename = \"C:\\myFolder\\StockChange\"\r\n columnSKU = 0\r\n columnStkNow = 1\r\n columnLvlChg = 2 \r\n columnDate = 3\r\n columnLstr = 4\r\n columnImgId = 5\r\n actDay = 7\r\n formatAs = \" - \"\r\n customerReturn = 0\r\n \r\n today = datetime.datetime.today()\r\n thisHour = datetime.datetime.now().strftime('%I') \r\n \r\n two_hours_ago = datetime.datetime.now() - datetime.timedelta(hours=2)\r\n d = modification_date(partialfilename+\".csv\")\r\n\r\n if d < two_hours_ago :\r\n return \" Restart Linnworks ---------> \" + partialfilename + \".csv is not current \\n\\n\" \r\n \r\n lines = \"\"\r\n\r\n partialfilename = \"C:\\myFolder\\PosInv.csv\"\r\n \r\n totValue = 0\r\n\r\n fib1 = open(partialfilename,encoding='UTF8') \r\n fi_b1 = csv.reader(fib1)\r\n next (fi_b1)\r\n \r\n fob1 = open(\"C:\\myFolder\\Tmp.csv\",'w')\r\n fo_b1 = csv.writer(fob1,lineterminator='\\n')\r\n\r\n for row1 in fi_b1:\r\n departmnt = row1[0]\r\n totValue = int(float(row1[1]))\r\n \r\n if departmnt == \"TILE\":\r\n fo_b1.writerow([departmnt,totValue,200000,totValue-200000])\r\n elif departmnt == \"LAMINATE\":\r\n fo_b1.writerow([departmnt,totValue,65000,totValue-65000])\r\n \r\n fib1.close()\r\n fob1.close()\r\n\r\n sortLinesInFile(\"C:\\myFolder\\Tmp.csv\")\r\n \r\n f = open(\"C:\\myFolder\\Tmp.csv\", \"r\")\r\n for i, line in enumerate(f):\r\n lines = lines + \" \" + line.split(\",\")[0].zfill(15) + formatAs + line.split(\",\")[1].zfill(3) + formatAs + line.split(\",\")[2].zfill(3) + formatAs + line.split(\",\")[3].zfill(3) + \"\\n\"\r\n f.close()\r\n \r\n return lines\r\n\r\n \r\ndef sortLinesInFile(fileName):\r\n f = open(fileName, \"r\")\r\n lines = [line for line in f if line.strip()]\r\n f.close()\r\n lines.sort()\r\n \r\n f = open(fileName, 'w')\r\n f.writelines(lines)\r\n f.close() \r\n\r\ndef modification_date(filename):\r\n t = os.path.getmtime(filename)\r\n return datetime.datetime.fromtimestamp(t)\r\n \r\ndef constructEmail(emailSubjectOrBody,ordersDataList): \r\n today = datetime.date.today().strftime('%x')\r\n thisHour = datetime.datetime.now().strftime('%I:%M:%S %p')\r\n now_time = datetime.datetime.now()\r\n \r\n if emailSubjectOrBody == \"S\" and now_time > now_time.replace(hour=9, minute=0, second=0, microsecond=0) :\r\n return \"Inventory Targets : \" + str(today) + \" \" + str(thisHour) \r\n \r\n elif emailSubjectOrBody == \"B\" and now_time > now_time.replace(hour=9, minute=0, second=0, microsecond=0) :\r\n body = \"PAYLESS COMPONENTS : \\n******************\\n\" \r\n body = body + \" Listings by the Hour today: \\n\" + ordersDataList[0] + \"\\n\"\r\n return body \r\n \r\ndef sendEmail(emailSubject,emailBody):\r\n me = \"reports@paylesscomponents.com\"\r\n you = \"don@paylesscomponents.com\"\r\n #you = [\"don@paylesscomponents.com\", \"sales@paylesscomponents.com\"]\r\n #you = [\"kyle@paylesscomponents.com\", \"don@paylesscomponents.com\", \"nick@paylesscomponents.com\"]\r\n #you = [\"kyle@paylesscomponents.com\", \"jhamamy@factory-surplus.com\", \"nick@paylesscomponents.com\", \"desirae@paylesscomponents.com\", \"don@paylesscomponents.com\"]\r\n \r\n COMMASPACE = ', '\r\n\r\n msg = MIMEMultipart('alternative')\r\n msg['Subject'] = emailSubject\r\n msg['From'] = me\r\n msg['To'] = COMMASPACE.join(you)\r\n\r\n part1 = MIMEText(emailBody, 'plain') \r\n msg.attach(part1)\r\n \r\n s = smtplib.SMTP_SSL('smtpout.secureserver.net',465) \r\n s.login(\"don@paylesscomponents.com\", \"donpay123\")\r\n \r\n s.sendmail(me, you, msg.as_string())\r\n s.quit()\r\n\r\n#cleanData()\r\n\r\nprocessData()", "repo_name": "paylessc/pointOfSaleAutomation", "sub_path": "QBPOS%20Custom%20Reports/PosInventoryTargets.py", "file_name": "PosInventoryTargets.py", "file_ext": "py", "file_size_in_byte": 5006, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "csv.reader", "line_number": 42, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 45, "usage_type": "call"}, {"api_name": "datetime.datetime.today", "line_number": 73, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 73, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 74, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 74, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 76, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 76, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 76, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 89, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 93, "usage_type": "call"}, {"api_name": "os.path.getmtime", "line_number": 128, "usage_type": "call"}, {"api_name": "os.path", "line_number": 128, "usage_type": "attribute"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 129, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 129, "usage_type": "attribute"}, {"api_name": "datetime.date.today", "line_number": 132, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 132, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 133, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 133, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 134, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 134, "usage_type": "attribute"}, {"api_name": "email.mime.multipart.MIMEMultipart", "line_number": 153, "usage_type": "call"}, {"api_name": "email.mime.text.MIMEText", "line_number": 158, "usage_type": "call"}, {"api_name": "smtplib.SMTP_SSL", "line_number": 161, "usage_type": "call"}]} +{"seq_id": "24385020187", "text": "\"\"\"\nAbstraction of the deployment functionality for processors.\n\nThe Processing Server provides the configuration parameters to the Deployer agent.\nThe Deployer agent runs the RabbitMQ Server, MongoDB and the Processing Hosts.\nEach Processing Host may have several Processing Workers.\nEach Processing Worker is an instance of an OCR-D processor.\n\"\"\"\nfrom __future__ import annotations\nfrom typing import Dict, List, Union\nfrom re import search as re_search\nfrom pathlib import Path\nimport subprocess\nfrom time import sleep\n\nfrom ocrd_utils import config, getLogger, safe_filename\n\nfrom .deployment_utils import (\n create_docker_client,\n DeployType,\n verify_mongodb_available,\n verify_rabbitmq_available,\n)\nfrom .logging import get_mets_server_logging_file_path\nfrom .runtime_data import (\n DataHost,\n DataMongoDB,\n DataProcessingWorker,\n DataProcessorServer,\n DataRabbitMQ\n)\nfrom .utils import (\n is_mets_server_running,\n stop_mets_server,\n validate_and_load_config\n)\n\n\nclass Deployer:\n def __init__(self, config_path: str) -> None:\n self.log = getLogger('ocrd_network.deployer')\n config = validate_and_load_config(config_path)\n\n self.data_mongo: DataMongoDB = DataMongoDB(config['database'])\n self.data_queue: DataRabbitMQ = DataRabbitMQ(config['process_queue'])\n self.data_hosts: List[DataHost] = []\n self.internal_callback_url = config.get('internal_callback_url', None)\n for config_host in config['hosts']:\n self.data_hosts.append(DataHost(config_host))\n self.mets_servers: Dict = {} # {\"mets_server_url\": \"mets_server_pid\"}\n\n # TODO: Reconsider this.\n def find_matching_processors(\n self,\n worker_only: bool = False,\n server_only: bool = False,\n docker_only: bool = False,\n native_only: bool = False,\n str_names_only: bool = False,\n unique_only: bool = False\n ) -> Union[List[str], List[object]]:\n \"\"\"Finds and returns a list of matching data objects of type:\n `DataProcessingWorker` and `DataProcessorServer`.\n\n :py:attr:`worker_only` match only processors with worker status\n :py:attr:`server_only` match only processors with server status\n :py:attr:`docker_only` match only docker processors\n :py:attr:`native_only` match only native processors\n :py:attr:`str_only` returns the processor_name instead of data object\n :py:attr:`unique_only` remove duplicates from the matches\n\n `worker_only` and `server_only` are mutually exclusive to each other\n `docker_only` and `native_only` are mutually exclusive to each other\n `unique_only` is allowed only together with `str_names_only`\n \"\"\"\n\n if worker_only and server_only:\n raise ValueError(f\"Only 'worker_only' or 'server_only' is allowed, not both.\")\n if docker_only and native_only:\n raise ValueError(f\"Only 'docker_only' or 'native_only' is allowed, not both.\")\n if not str_names_only and unique_only:\n raise ValueError(f\"Value 'unique_only' is allowed only together with 'str_names_only'\")\n\n # Find all matching objects of type:\n # DataProcessingWorker or DataProcessorServer\n matched_objects = []\n for data_host in self.data_hosts:\n if not server_only:\n for data_worker in data_host.data_workers:\n if data_worker.deploy_type == DeployType.NATIVE and docker_only:\n continue\n if data_worker.deploy_type == DeployType.DOCKER and native_only:\n continue\n matched_objects.append(data_worker)\n if not worker_only:\n for data_server in data_host.data_servers:\n if data_server.deploy_type == DeployType.NATIVE and docker_only:\n continue\n if data_server.deploy_type == DeployType.DOCKER and native_only:\n continue\n matched_objects.append(data_server)\n if str_names_only:\n # gets only the processor names of the matched objects\n name_list = [match.processor_name for match in matched_objects]\n if unique_only:\n # removes the duplicates, if any\n return list(dict.fromkeys(name_list))\n return name_list\n return matched_objects\n\n def resolve_processor_server_url(self, processor_name) -> str:\n processor_server_url = ''\n for data_host in self.data_hosts:\n for data_server in data_host.data_servers:\n if data_server.processor_name == processor_name:\n processor_server_url = f'http://{data_host.address}:{data_server.port}/'\n return processor_server_url\n\n def kill_all(self) -> None:\n \"\"\" kill all started services: hosts, database, queue\n\n The order of killing is important to optimize graceful shutdown in the future. If RabbitMQ\n server is killed before killing Processing Workers, that may have bad outcome and leave\n Processing Workers in an unpredictable state\n \"\"\"\n self.kill_hosts()\n self.kill_mongodb()\n self.kill_rabbitmq()\n\n def deploy_hosts(\n self,\n mongodb_url: str,\n rabbitmq_url: str\n ) -> None:\n for host_data in self.data_hosts:\n if host_data.needs_ssh:\n host_data.create_client(client_type='ssh')\n assert host_data.ssh_client\n if host_data.needs_docker:\n host_data.create_client(client_type='docker')\n assert host_data.docker_client\n\n self.log.debug(f'Deploying processing workers on host: {host_data.address}')\n for data_worker in host_data.data_workers:\n self._deploy_processing_worker(\n mongodb_url,\n rabbitmq_url,\n host_data,\n data_worker\n )\n\n self.log.debug(f'Deploying processor servers on host: {host_data.address}')\n for data_server in host_data.data_servers:\n self._deploy_processor_server(\n mongodb_url,\n host_data,\n data_server\n )\n\n if host_data.ssh_client:\n host_data.ssh_client.close()\n host_data.ssh_client = None\n if host_data.docker_client:\n host_data.docker_client.close()\n host_data.docker_client = None\n\n def _deploy_processing_worker(\n self,\n mongodb_url: str,\n rabbitmq_url: str,\n host_data: DataHost,\n data_worker: DataProcessingWorker\n ) -> None:\n self.log.debug(f\"Deploying processing worker, \"\n f\"environment: '{data_worker.deploy_type}', \"\n f\"name: '{data_worker.processor_name}', \"\n f\"address: '{host_data.address}'\")\n\n if data_worker.deploy_type == DeployType.NATIVE:\n assert host_data.ssh_client # to satisfy mypy\n pid = self.start_native_processor(\n ssh_client=host_data.ssh_client,\n processor_name=data_worker.processor_name,\n queue_url=rabbitmq_url,\n database_url=mongodb_url,\n )\n data_worker.pid = pid\n elif data_worker.deploy_type == DeployType.DOCKER:\n assert host_data.docker_client # to satisfy mypy\n pid = self.start_docker_processor(\n docker_client=host_data.docker_client,\n processor_name=data_worker.processor_name,\n _queue_url=rabbitmq_url,\n _database_url=mongodb_url\n )\n data_worker.pid = pid\n sleep(0.2)\n\n # TODO: Revisit this to remove code duplications of deploy_* methods\n def _deploy_processor_server(\n self,\n mongodb_url: str,\n host_data: DataHost,\n data_server: DataProcessorServer,\n ) -> None:\n self.log.debug(f\"Deploying processing worker, \"\n f\"environment: '{data_server.deploy_type}', \"\n f\"name: '{data_server.processor_name}', \"\n f\"address: '{data_server.host}:{data_server.port}'\")\n\n if data_server.deploy_type == DeployType.NATIVE:\n assert host_data.ssh_client\n pid = self.start_native_processor_server(\n ssh_client=host_data.ssh_client,\n processor_name=data_server.processor_name,\n agent_address=f'{data_server.host}:{data_server.port}',\n database_url=mongodb_url,\n )\n data_server.pid = pid\n\n if data_server.processor_name in host_data.server_ports:\n name = data_server.processor_name\n port = data_server.port\n if host_data.server_ports[name]:\n host_data.server_ports[name] = host_data.server_ports[name].append(port)\n else:\n host_data.server_ports[name] = [port]\n else:\n host_data.server_ports[data_server.processor_name] = [data_server.port]\n elif data_server.deploy_type == DeployType.DOCKER:\n raise Exception(\"Deploying docker processor server is not supported yet!\")\n\n def deploy_rabbitmq(\n self,\n image: str,\n detach: bool,\n remove: bool,\n ports_mapping: Union[Dict, None] = None\n ) -> str:\n if self.data_queue.skip_deployment:\n self.log.debug(f\"RabbitMQ is externaly managed. Skipping deployment\")\n verify_rabbitmq_available(\n self.data_queue.address,\n self.data_queue.port,\n self.data_queue.vhost,\n self.data_queue.username,\n self.data_queue.password\n )\n return self.data_queue.url\n self.log.debug(f\"Trying to deploy '{image}', with modes: \"\n f\"detach='{detach}', remove='{remove}'\")\n\n if not self.data_queue or not self.data_queue.address:\n raise ValueError('Deploying RabbitMQ has failed - missing configuration.')\n\n client = create_docker_client(\n self.data_queue.address,\n self.data_queue.ssh_username,\n self.data_queue.ssh_password,\n self.data_queue.ssh_keypath\n )\n if not ports_mapping:\n # 5672, 5671 - used by AMQP 0-9-1 and AMQP 1.0 clients without and with TLS\n # 15672, 15671: HTTP API clients, management UI and rabbitmq admin, without and with TLS\n # 25672: used for internode and CLI tools communication and is allocated from\n # a dynamic range (limited to a single port by default, computed as AMQP port + 20000)\n ports_mapping = {\n 5672: self.data_queue.port,\n 15672: 15672,\n 25672: 25672\n }\n res = client.containers.run(\n image=image,\n detach=detach,\n remove=remove,\n ports=ports_mapping,\n # The default credentials to be used by the processing workers\n environment=[\n f'RABBITMQ_DEFAULT_USER={self.data_queue.username}',\n f'RABBITMQ_DEFAULT_PASS={self.data_queue.password}'\n ]\n )\n assert res and res.id, \\\n f'Failed to start RabbitMQ docker container on host: {self.data_queue.address}'\n self.data_queue.pid = res.id\n client.close()\n\n rmq_host = self.data_queue.address\n rmq_port = int(self.data_queue.port)\n rmq_vhost = '/'\n\n verify_rabbitmq_available(\n host=rmq_host,\n port=rmq_port,\n vhost=rmq_vhost,\n username=self.data_queue.username,\n password=self.data_queue.password\n )\n self.log.info(f'The RabbitMQ server was deployed on URL: '\n f'{rmq_host}:{rmq_port}{rmq_vhost}')\n return self.data_queue.url\n\n def deploy_mongodb(\n self,\n image: str,\n detach: bool,\n remove: bool,\n ports_mapping: Union[Dict, None] = None\n ) -> str:\n if self.data_mongo.skip_deployment:\n self.log.debug('MongoDB is externaly managed. Skipping deployment')\n verify_mongodb_available(self.data_mongo.url)\n return self.data_mongo.url\n\n self.log.debug(f\"Trying to deploy '{image}', with modes: \"\n f\"detach='{detach}', remove='{remove}'\")\n\n if not self.data_mongo or not self.data_mongo.address:\n raise ValueError('Deploying MongoDB has failed - missing configuration.')\n\n client = create_docker_client(\n self.data_mongo.address,\n self.data_mongo.ssh_username,\n self.data_mongo.ssh_password,\n self.data_mongo.ssh_keypath\n )\n if not ports_mapping:\n ports_mapping = {\n 27017: self.data_mongo.port\n }\n if self.data_mongo.username:\n environment = [\n f'MONGO_INITDB_ROOT_USERNAME={self.data_mongo.username}',\n f'MONGO_INITDB_ROOT_PASSWORD={self.data_mongo.password}'\n ]\n else:\n environment = []\n\n res = client.containers.run(\n image=image,\n detach=detach,\n remove=remove,\n ports=ports_mapping,\n environment=environment\n )\n if not res or not res.id:\n raise RuntimeError('Failed to start MongoDB docker container on host: '\n f'{self.data_mongo.address}')\n self.data_mongo.pid = res.id\n client.close()\n\n mongodb_hostinfo = f'{self.data_mongo.address}:{self.data_mongo.port}'\n self.log.info(f'The MongoDB was deployed on host: {mongodb_hostinfo}')\n return self.data_mongo.url\n\n def kill_rabbitmq(self) -> None:\n if self.data_queue.skip_deployment:\n return\n elif not self.data_queue.pid:\n self.log.warning('No running RabbitMQ instance found')\n return\n client = create_docker_client(\n self.data_queue.address,\n self.data_queue.ssh_username,\n self.data_queue.ssh_password,\n self.data_queue.ssh_keypath\n )\n client.containers.get(self.data_queue.pid).stop()\n self.data_queue.pid = None\n client.close()\n self.log.info('The RabbitMQ is stopped')\n\n def kill_mongodb(self) -> None:\n if self.data_mongo.skip_deployment:\n return\n elif not self.data_mongo.pid:\n self.log.warning('No running MongoDB instance found')\n return\n client = create_docker_client(\n self.data_mongo.address,\n self.data_mongo.ssh_username,\n self.data_mongo.ssh_password,\n self.data_mongo.ssh_keypath\n )\n client.containers.get(self.data_mongo.pid).stop()\n self.data_mongo.pid = None\n client.close()\n self.log.info('The MongoDB is stopped')\n\n def kill_hosts(self) -> None:\n self.log.debug('Starting to kill/stop hosts')\n # Kill processing hosts\n for host_data in self.data_hosts:\n if host_data.needs_ssh:\n host_data.create_client(client_type='ssh')\n assert host_data.ssh_client\n if host_data.needs_docker:\n host_data.create_client(client_type='docker')\n assert host_data.docker_client\n\n self.log.debug(f'Killing/Stopping processing workers on host: {host_data.address}')\n self.kill_processing_workers(host_data)\n\n self.log.debug(f'Killing/Stopping processor servers on host: {host_data.address}')\n self.kill_processor_servers(host_data)\n\n if host_data.ssh_client:\n host_data.ssh_client.close()\n host_data.ssh_client = None\n if host_data.docker_client:\n host_data.docker_client.close()\n host_data.docker_client = None\n\n # TODO: Optimize the code duplication from start_* and kill_* methods\n def kill_processing_workers(self, host_data: DataHost) -> None:\n amount = len(host_data.data_workers)\n if not amount:\n self.log.info(f'No active processing workers to be stopped.')\n return\n self.log.info(f\"Trying to stop {amount} processing workers:\")\n for worker in host_data.data_workers:\n if not worker.pid:\n continue\n if worker.deploy_type == DeployType.NATIVE:\n host_data.ssh_client.exec_command(f'kill {worker.pid}')\n self.log.info(f\"Stopped native worker with pid: '{worker.pid}'\")\n elif worker.deploy_type == DeployType.DOCKER:\n host_data.docker_client.containers.get(worker.pid).stop()\n self.log.info(f\"Stopped docker worker with container id: '{worker.pid}'\")\n host_data.data_workers = []\n\n def kill_processor_servers(self, host_data: DataHost) -> None:\n amount = len(host_data.data_servers)\n if not amount:\n self.log.info(f'No active processor servers to be stopped.')\n return\n self.log.info(f\"Trying to stop {amount} processing workers:\")\n for server in host_data.data_servers:\n if not server.pid:\n continue\n if server.deploy_type == DeployType.NATIVE:\n host_data.ssh_client.exec_command(f'kill {server.pid}')\n self.log.info(f\"Stopped native server with pid: '{server.pid}'\")\n elif server.deploy_type == DeployType.DOCKER:\n host_data.docker_client.containers.get(server.pid).stop()\n self.log.info(f\"Stopped docker server with container id: '{server.pid}'\")\n host_data.data_servers = []\n\n def start_native_processor(\n self,\n ssh_client,\n processor_name: str,\n queue_url: str,\n database_url: str\n ) -> str:\n \"\"\" start a processor natively on a host via ssh\n\n Args:\n ssh_client: paramiko SSHClient to execute commands on a host\n processor_name: name of processor to run\n queue_url: url to rabbitmq\n database_url: url to database\n\n Returns:\n str: pid of running process\n \"\"\"\n self.log.info(f'Starting native processing worker: {processor_name}')\n channel = ssh_client.invoke_shell()\n stdin, stdout = channel.makefile('wb'), channel.makefile('rb')\n cmd = f'{processor_name} worker --database {database_url} --queue {queue_url} &'\n # the only way (I could find) to make it work to start a process in the background and\n # return early is this construction. The pid of the last started background process is\n # printed with `echo $!` but it is printed inbetween other output. Because of that I added\n # `xyz` before and after the code to easily be able to filter out the pid via regex when\n # returning from the function\n\n self.log.debug(f'About to execute command: {cmd}')\n stdin.write(f'{cmd}\\n')\n stdin.write('echo xyz$!xyz \\n exit \\n')\n output = stdout.read().decode('utf-8')\n stdout.close()\n stdin.close()\n return re_search(r'xyz([0-9]+)xyz', output).group(1) # type: ignore\n\n def start_docker_processor(\n self,\n docker_client,\n processor_name: str,\n _queue_url: str,\n _database_url: str\n ) -> str:\n # TODO: Raise an exception here as well?\n # raise Exception(\"Deploying docker processing worker is not supported yet!\")\n\n self.log.info(f'Starting docker container processor: {processor_name}')\n # TODO: add real command here to start processing server in docker here\n res = docker_client.containers.run('debian', 'sleep 500s', detach=True, remove=True)\n assert res and res.id, f'Running processor: {processor_name} in docker-container failed'\n return res.id\n\n # TODO: Just a copy of the above start_native_processor() method.\n # Far from being great... But should be good as a starting point\n def start_native_processor_server(\n self,\n ssh_client,\n processor_name: str,\n agent_address: str,\n database_url: str\n ) -> str:\n self.log.info(f\"Starting native processor server: {processor_name} on {agent_address}\")\n channel = ssh_client.invoke_shell()\n stdin, stdout = channel.makefile('wb'), channel.makefile('rb')\n cmd = f'{processor_name} server --address {agent_address} --database {database_url} &'\n self.log.debug(f'About to execute command: {cmd}')\n stdin.write(f'{cmd}\\n')\n stdin.write('echo xyz$!xyz \\n exit \\n')\n output = stdout.read().decode('utf-8')\n stdout.close()\n stdin.close()\n return re_search(r'xyz([0-9]+)xyz', output).group(1) # type: ignore\n\n # TODO: No support for TCP version yet\n def start_unix_mets_server(self, mets_path: str) -> Path:\n log_file = get_mets_server_logging_file_path(mets_path=mets_path)\n mets_server_url = Path(config.OCRD_NETWORK_SOCKETS_ROOT_DIR, f\"{safe_filename(mets_path)}.sock\")\n\n if is_mets_server_running(mets_server_url=str(mets_server_url)):\n self.log.info(f\"The mets server is already started: {mets_server_url}\")\n return mets_server_url\n\n cwd = Path(mets_path).parent\n self.log.info(f'Starting UDS mets server: {mets_server_url}')\n sub_process = subprocess.Popen(\n args=['nohup', 'ocrd', 'workspace', '--mets-server-url', f'{mets_server_url}',\n '-d', f'{cwd}', 'server', 'start'],\n shell=False,\n stdout=open(file=log_file, mode='w'),\n stderr=open(file=log_file, mode='a'),\n cwd=cwd,\n universal_newlines=True\n )\n # Wait for the mets server to start\n sleep(2)\n self.mets_servers[mets_server_url] = sub_process.pid\n return mets_server_url\n\n def stop_unix_mets_server(self, mets_server_url: str) -> None:\n self.log.info(f'Stopping UDS mets server: {mets_server_url}')\n if Path(mets_server_url) in self.mets_servers:\n mets_server_pid = self.mets_servers[Path(mets_server_url)]\n else:\n raise Exception(f\"Mets server not found: {mets_server_url}\")\n\n '''\n subprocess.run(\n args=['kill', '-s', 'SIGINT', f'{mets_server_pid}'],\n shell=False,\n universal_newlines=True\n )\n '''\n\n # TODO: Reconsider this again\n # Not having this sleep here causes connection errors\n # on the last request processed by the processing worker.\n # Sometimes 3 seconds is enough, sometimes not.\n sleep(5)\n stop_mets_server(mets_server_url=mets_server_url)\n", "repo_name": "OCR-D/core", "sub_path": "ocrd_network/ocrd_network/deployer.py", "file_name": "deployer.py", "file_ext": "py", "file_size_in_byte": 23362, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 117, "dataset": "github-code", "pt": "27", "api": [{"api_name": "ocrd_utils.getLogger", "line_number": 41, "usage_type": "call"}, {"api_name": "ocrd_utils.config", "line_number": 42, "usage_type": "name"}, {"api_name": "utils.validate_and_load_config", "line_number": 42, "usage_type": "call"}, {"api_name": "runtime_data.DataMongoDB", "line_number": 44, "usage_type": "name"}, {"api_name": "ocrd_utils.config", "line_number": 44, "usage_type": "name"}, {"api_name": "runtime_data.DataRabbitMQ", "line_number": 45, "usage_type": "name"}, {"api_name": "ocrd_utils.config", "line_number": 45, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 46, "usage_type": "name"}, {"api_name": "runtime_data.DataHost", "line_number": 46, "usage_type": "name"}, {"api_name": "ocrd_utils.config.get", "line_number": 47, "usage_type": "call"}, {"api_name": "ocrd_utils.config", "line_number": 47, "usage_type": "name"}, {"api_name": "ocrd_utils.config", "line_number": 48, "usage_type": "name"}, {"api_name": "runtime_data.DataHost", "line_number": 49, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 50, "usage_type": "name"}, {"api_name": "deployment_utils.DeployType.NATIVE", "line_number": 90, "usage_type": "attribute"}, {"api_name": "deployment_utils.DeployType", "line_number": 90, "usage_type": "name"}, {"api_name": "deployment_utils.DeployType.DOCKER", "line_number": 92, "usage_type": "attribute"}, {"api_name": "deployment_utils.DeployType", "line_number": 92, "usage_type": "name"}, {"api_name": "deployment_utils.DeployType.NATIVE", "line_number": 97, "usage_type": "attribute"}, {"api_name": "deployment_utils.DeployType", "line_number": 97, "usage_type": "name"}, {"api_name": "deployment_utils.DeployType.DOCKER", "line_number": 99, "usage_type": "attribute"}, {"api_name": "deployment_utils.DeployType", "line_number": 99, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 61, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 61, "usage_type": "name"}, {"api_name": "runtime_data.DataHost", "line_number": 171, "usage_type": "name"}, {"api_name": "runtime_data.DataProcessingWorker", "line_number": 172, "usage_type": "name"}, {"api_name": "deployment_utils.DeployType.NATIVE", "line_number": 179, "usage_type": "attribute"}, {"api_name": "deployment_utils.DeployType", "line_number": 179, "usage_type": "name"}, {"api_name": "deployment_utils.DeployType.DOCKER", "line_number": 188, "usage_type": "attribute"}, {"api_name": "deployment_utils.DeployType", "line_number": 188, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 197, "usage_type": "call"}, {"api_name": "runtime_data.DataHost", "line_number": 203, "usage_type": "name"}, {"api_name": "runtime_data.DataProcessorServer", "line_number": 204, "usage_type": "name"}, {"api_name": "deployment_utils.DeployType.NATIVE", "line_number": 211, "usage_type": "attribute"}, {"api_name": "deployment_utils.DeployType", "line_number": 211, "usage_type": "name"}, {"api_name": "deployment_utils.DeployType.DOCKER", "line_number": 230, "usage_type": "attribute"}, {"api_name": "deployment_utils.DeployType", "line_number": 230, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 238, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 238, "usage_type": "name"}, {"api_name": "deployment_utils.verify_rabbitmq_available", "line_number": 242, "usage_type": "call"}, {"api_name": "deployment_utils.create_docker_client", "line_number": 256, "usage_type": "call"}, {"api_name": "deployment_utils.verify_rabbitmq_available", "line_number": 292, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 308, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 308, "usage_type": "name"}, {"api_name": "deployment_utils.verify_mongodb_available", "line_number": 312, "usage_type": "call"}, {"api_name": "deployment_utils.create_docker_client", "line_number": 321, "usage_type": "call"}, {"api_name": "deployment_utils.create_docker_client", "line_number": 362, "usage_type": "call"}, {"api_name": "deployment_utils.create_docker_client", "line_number": 379, "usage_type": "call"}, {"api_name": "runtime_data.DataHost", "line_number": 415, "usage_type": "name"}, {"api_name": "deployment_utils.DeployType.NATIVE", "line_number": 424, "usage_type": "attribute"}, {"api_name": "deployment_utils.DeployType", "line_number": 424, "usage_type": "name"}, {"api_name": "deployment_utils.DeployType.DOCKER", "line_number": 427, "usage_type": "attribute"}, {"api_name": "deployment_utils.DeployType", "line_number": 427, "usage_type": "name"}, {"api_name": "runtime_data.DataHost", "line_number": 432, "usage_type": "name"}, {"api_name": "deployment_utils.DeployType.NATIVE", "line_number": 441, "usage_type": "attribute"}, {"api_name": "deployment_utils.DeployType", "line_number": 441, "usage_type": "name"}, {"api_name": "deployment_utils.DeployType.DOCKER", "line_number": 444, "usage_type": "attribute"}, {"api_name": "deployment_utils.DeployType", "line_number": 444, "usage_type": "name"}, {"api_name": "re.search", "line_number": 483, "usage_type": "call"}, {"api_name": "re.search", "line_number": 520, "usage_type": "call"}, {"api_name": "logging.get_mets_server_logging_file_path", "line_number": 524, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 525, "usage_type": "call"}, {"api_name": "ocrd_utils.config.OCRD_NETWORK_SOCKETS_ROOT_DIR", "line_number": 525, "usage_type": "attribute"}, {"api_name": "ocrd_utils.config", "line_number": 525, "usage_type": "name"}, {"api_name": "ocrd_utils.safe_filename", "line_number": 525, "usage_type": "call"}, {"api_name": "utils.is_mets_server_running", "line_number": 527, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 531, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 533, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 543, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 523, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 549, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 550, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 566, "usage_type": "call"}, {"api_name": "utils.stop_mets_server", "line_number": 567, "usage_type": "call"}]} +{"seq_id": "72709351104", "text": "from flask import Flask\nimport feedparser\nimport csv\nimport json\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import classification_report, confusion_matrix\n\napp = Flask(__name__)\ncont =0\n@app.route(\"/knn\")\ndef main():\n\turl_test = 'test.csv'\n\turl_train = 'train.csv'\n\ttraining_data = []\n\ttest_data = []\n\tprint(\"datos totales\")\n\tprint(test_data)\n\tprint(\"----------------------------------\")\n\tdf_test = pd.read_csv(url_test)\n\tdf_train = pd.read_csv(url_train)\n\tprint('\\nEstadísticas del dataset:')\n\tprint(df_train.describe())\n\tprint(df_test.describe())\n\tprint('\\nMedia')\n\tprint(df_test.mean())\n\tprint(df_train.mean())\n\tprint(\"\\nPrecisión\")\n\tX = np.array(df_train.drop(['species'], 1))\n\ty = np.array(df_train['species'])\n\tprint(\"train\",np.array(df_train['species']))\n\tprint(X)\n\tprint(y)\n\tX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)\n\tknn = KNeighborsClassifier(n_neighbors = 3)\n\tknn.fit(X_train, y_train)\n\tY_pred = knn.predict(X_test)\n\tprediccion_knn = knn.predict(df_test)\n\tprint(\"Aqui esta el df_test\", df_test.iloc[:,:-1].values)\n\tprint(\"prediccion del KNN\")\n\tprint(prediccion_knn)\n\tprint('Precisión Vecinos más Cercanos:')\n\tprint(knn.score(X_train, y_train))\n\tprint(\"Matriz de confusion\")\n\tprint(confusion_matrix(y_test, Y_pred))\n\tprint(\"Reporte de clasificacion\")\n\tprint(classification_report(y_test, Y_pred))\n\tjst = {str(i):prediccion_knn[i] for i in range(len(prediccion_knn))}\n\tjst[\"saludo\"] =\"hola\"\n\treturn jst #dict({\"informacion_knn\":[{i:prediccion_knn[i] for i in range(len(prediccion_knn))},{\"hola\":\"holin\"}]})\nif __name__ == \"__main__\":\n app.run(debug=True)", "repo_name": "SebastianTT/algoritmo_knn", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1852, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "flask.Flask", "line_number": 14, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 25, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 36, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 39, "usage_type": "call"}, {"api_name": "sklearn.neighbors.KNeighborsClassifier", "line_number": 40, "usage_type": "call"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 50, "usage_type": "call"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 52, "usage_type": "call"}]} +{"seq_id": "9166796731", "text": "from selenium import webdriver\n\n#driver = webdriver.Chrome(executable_path=r'C:\\Users\\Southville\\Downloads\\chromedriver_win32\\chromedriver')\n#driver = webdriver.Firefox(executable_path=r'C:\\Users\\Southville\\Downloads\\geckodriver-v0.27.0-win64\\geckodriver')\ndriver = webdriver.Ie(executable_path=r'C:\\Users\\Southville\\Downloads\\IEDriverServer_x64_3.150.1\\IEDriverServer')\ndriver.get('https://rahulshettyacademy.com/#/index') # http://206.189.237.25/\ndriver.maximize_window()\nprint(driver.title)\nprint(driver.current_url)\ndriver.get('https://rahulshettyacademy.com/#/index')\nprint(driver.title)\nprint(driver.current_url)\ndriver.back()\ndriver.refresh()\ndriver.minimize_window()\ndriver.close() # only the current window will close\n#driver.quit() # all the windows which are open will close simultanuously", "repo_name": "nadiamehmood/GitDemo", "sub_path": "PythonSelenium/PythonDemo.py", "file_name": "PythonDemo.py", "file_ext": "py", "file_size_in_byte": 813, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "selenium.webdriver.Ie", "line_number": 5, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 5, "usage_type": "name"}]} +{"seq_id": "28663830837", "text": "\"\"\"Script for parsing emails. By default finds all ips (v4 and v6) and domains in letter,\r\nwrites it into db and prints it in console. Can also search headers by pattern or substring\r\n(start script with parameters -hs --header-string to search by string, and -hp --header-pattern\r\nto use regex pattern).\r\nWrites logs into main.log. It's possible to change level of logging (by adding -cl\r\n--change-level argument).\"\"\"\r\n\r\n\r\nimport re\r\nimport json\r\nimport sys\r\nimport argparse\r\nimport logging\r\nimport mysql.connector\r\n\r\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)s %(levelname)s: %(message)s',\r\n filename='main.log')\r\nLOGGER = logging.getLogger()\r\nDB_CONF_FILE = 'db_conf.json'\r\nLEVELS = {'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING,\r\n 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL}\r\n\r\n\r\nclass DbConnection:\r\n \"\"\"Class, based on singleton pattern for creating database connection instance.\r\n Uses MySQL connector.\"\"\"\r\n\r\n _instance = None\r\n\r\n def __new__(cls, *ars, **kwars):\r\n \"\"\"Singleton pattern realization\"\"\"\r\n\r\n if not isinstance(cls._instance, DbConnection):\r\n cls._instance = object.__new__(cls)\r\n return cls._instance\r\n\r\n def __init__(self, host='127.0.0.1', port=3306, user='root', password='', data_base=''):\r\n \"\"\"Initializes a class and creates db connection instance.\r\n\r\n :param host: MySQL server host\r\n :param port: MySQL server port\r\n :param user: username of user with needed privileges\r\n :param password: user's password\r\n :param data_base: name of already created schema\r\n \"\"\"\r\n\r\n self.host = host\r\n self.port = port\r\n self.user = user\r\n\r\n if password != '':\r\n self.password = password\r\n else:\r\n logging.error('Password could not be an empty string. Check db configuration.')\r\n sys.exit(2)\r\n\r\n if data_base != '':\r\n self.data_base = data_base\r\n else:\r\n logging.error('You have to select database to connect to. Check db configuration.')\r\n sys.exit(2)\r\n\r\n try:\r\n self.conn = mysql.connector.connect(host=self.host, database=self.data_base,\r\n user=self.user, password=self.password,\r\n port=self.port)\r\n if self.conn.is_connected():\r\n logging.info(\"Database connected.\")\r\n self.recreate_tables()\r\n else:\r\n logging.info(\"Connection failed.\")\r\n self.conn = None\r\n except mysql.connector.Error:\r\n logging.info(\"Can not connect to database!\")\r\n self.conn = None\r\n\r\n def recreate_tables(self):\r\n \"\"\"Method for cleaning database. It drops old tables and creates new empty\r\n tables 'ips' and 'domains\"\"\"\r\n\r\n cursor = self.conn.cursor()\r\n\r\n try:\r\n cursor.execute(\"DROP TABLE ips\")\r\n logging.debug(\"Old table ips dropped\")\r\n except mysql.connector.errors.ProgrammingError:\r\n pass\r\n finally:\r\n cursor.execute(\"CREATE TABLE ips (id INT PRIMARY KEY AUTO_INCREMENT UNIQUE, ip \"\r\n \"VARCHAR(255) NOT NULL)\")\r\n logging.info(\"Table ips created\")\r\n try:\r\n cursor.execute(\"DROP TABLE domains\")\r\n logging.debug(\"Old table domains dropped\")\r\n except mysql.connector.errors.ProgrammingError:\r\n pass\r\n finally:\r\n cursor.execute(\r\n \"CREATE TABLE domains (id INT PRIMARY KEY AUTO_INCREMENT UNIQUE, \"\r\n \"domain VARCHAR(255) NOT NULL)\")\r\n logging.info(\"Table domains created\")\r\n\r\n\r\ndef start_db_connection():\r\n \"\"\"Function for loading db configuration json file and create DbConnection instance.\r\n :returns DbConnection instance\"\"\"\r\n\r\n try:\r\n db_conf = json.load(open(DB_CONF_FILE))\r\n logging.debug(\"Db configuration loaded\")\r\n except FileNotFoundError:\r\n logging.error('DB configuration file not found')\r\n sys.exit(2)\r\n db_instance = DbConnection(host=db_conf['host'], data_base=db_conf['db'],\r\n user=db_conf['user'], password=db_conf['password'],\r\n port=db_conf['port'])\r\n logging.debug(\"DbConnection instance created\")\r\n if not db_instance.conn:\r\n logging.error('DB connection failed. Check configuration file and db server status.')\r\n sys.exit(2)\r\n\r\n return db_instance\r\n\r\n\r\ndef open_mail(path_to_mail: str):\r\n \"\"\"\r\n Function to correctly open and read email file. If there are some problems with file\r\n (wrong extension, file not found) func logs message and exits\r\n\r\n :param path_to_mail: path to email file (str) with extension .eml\r\n :return: content of email (str)\r\n \"\"\"\r\n\r\n if not isinstance(path_to_mail, str):\r\n logging.error('Wrong datatype input. Path to mail have to be string')\r\n sys.exit(2)\r\n\r\n if path_to_mail.find('.eml') == -1:\r\n logging.error('File has wrong extension. You have to choose \\\".eml\\\" file.')\r\n sys.exit(2)\r\n\r\n try:\r\n with open(path_to_mail, 'r') as file:\r\n file_text = file.read()\r\n logging.debug(\"Email file opened\")\r\n except FileNotFoundError:\r\n logging.error('File not found. Check your path or choose another file. Entered path: %s'\r\n % path_to_mail)\r\n sys.exit(2)\r\n return file_text\r\n\r\n\r\ndef tld_config():\r\n \"\"\"Func loads TLD configuration file and makes a regex pattern from all domains from it\r\n :returns regex pattern of TLD\"\"\"\r\n\r\n try:\r\n tld_list = open('TLD.conf').read()\r\n except FileNotFoundError:\r\n logging.info('No TLD config found. Setting a default TLD configuration...')\r\n tld_list = 'com|org|net|int|edu|gov|mil|arpa'\r\n last_n = tld_list.rfind('\\n')\r\n if len(tld_list) - last_n == 1:\r\n tld_list = tld_list[:last_n]\r\n tld_list = tld_list.replace('\\n', '|')\r\n return tld_list\r\n\r\n\r\ndef parse_mail(email_content: str, db_conn: DbConnection):\r\n \"\"\"\r\n Function parses email text to find IPs (v4 and v6) and domains, and writes it into db.\r\n\r\n :param db_conn: MySQL db connection\r\n :param email_content: text content of email (str)\r\n \"\"\"\r\n\r\n if not isinstance(email_content, str):\r\n logging.debug('Email content variable should be a string.')\r\n logging.error('Email content has incorrect type')\r\n sys.exit(2)\r\n\r\n ip_v4 = re.findall(r\"(?\", methods=[\"GET\",\"POST\"]) #buton will get the id & post request \ndef update(id):\n form= TeamForm()\n team= Teams.query.filter_by(id=id).first()\n\n if request.method == 'GET':\n form.form_name.data = team.name # put data in the input box \n form.form_city.data = team.city\n form.form_conference.data = team.conference\n form.form_rank.data = team.rank\n\n elif request.method ==\"POST\": # id the form has been posted \n team.name = form.form_name.data # refere to model.py && send to the data base \n team.city = form.form_city.data\n team.conference = form.form_conference.data\n team.rank = form.form_rank.data\n db.session.commit()\n return redirect(url_for(\"home\")) \n return render_template(\"update.html\", form=form, title=\"Update Team\", team=team)\n \n@app.route(\"/delete/\")\ndef delete(id):\n team=Teams.query.filter_by(id=id).first()\n for player in team.players: \n db.session.delete(player)\n db.session.delete(team)\n db.session.commit()\n return redirect(url_for(\"home\"))\n\n\n@app.route(\"/player/\",methods=[\"GET\", \"POST\"]) \ndef player(id):\n form=PlayerForm()\n if request.method == \"POST\": \n if form.validate_on_submit():\n new_player = Players(\n pl_name = form.form_name.data, # filling in each column \n pl_position = form.form_position.data,\n teamid = id \n ) \n db.session.add(new_player) # add the new team to the route \n db.session.commit() # commit to the data base itself\n return redirect(url_for(\"home\")) #redirect back to the home page\n return render_template(\"add-Player.html\", title = \"Add Players to your Teams\", form=form) # display ftml file", "repo_name": "PhilipL1/project-bball", "sub_path": "application/routes.py", "file_name": "routes.py", "file_ext": "py", "file_size_in_byte": 3184, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "application.models.Teams.query.all", "line_number": 11, "usage_type": "call"}, {"api_name": "application.models.Teams.query", "line_number": 11, "usage_type": "attribute"}, {"api_name": "application.models.Teams", "line_number": 11, "usage_type": "name"}, {"api_name": "application.models.Players.query.all", "line_number": 12, "usage_type": "call"}, {"api_name": "application.models.Players.query", "line_number": 12, "usage_type": "attribute"}, {"api_name": "application.models.Players", "line_number": 12, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 14, "usage_type": "call"}, {"api_name": "application.app.route", "line_number": 8, "usage_type": "call"}, {"api_name": "application.app", "line_number": 8, "usage_type": "name"}, {"api_name": "application.app.route", "line_number": 9, "usage_type": "call"}, {"api_name": "application.app", "line_number": 9, "usage_type": "name"}, {"api_name": "application.forms.TeamForm", "line_number": 18, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 19, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 19, "usage_type": "name"}, {"api_name": "application.models.Teams", "line_number": 21, "usage_type": "call"}, {"api_name": "application.db.session.add", "line_number": 27, "usage_type": "call"}, {"api_name": "application.db.session", "line_number": 27, "usage_type": "attribute"}, {"api_name": "application.db", "line_number": 27, "usage_type": "name"}, {"api_name": "application.db.session.commit", "line_number": 28, "usage_type": "call"}, {"api_name": "application.db.session", "line_number": 28, "usage_type": "attribute"}, {"api_name": "application.db", "line_number": 28, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 30, "usage_type": "call"}, {"api_name": "application.app.route", "line_number": 16, "usage_type": "call"}, {"api_name": "application.app", "line_number": 16, "usage_type": "name"}, {"api_name": "application.forms.TeamForm", "line_number": 34, "usage_type": "call"}, {"api_name": "application.models.Teams.query.filter_by", "line_number": 35, "usage_type": "call"}, {"api_name": "application.models.Teams.query", "line_number": 35, "usage_type": "attribute"}, {"api_name": "application.models.Teams", "line_number": 35, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 37, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 37, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 43, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 43, "usage_type": "name"}, {"api_name": "application.db.session.commit", "line_number": 48, "usage_type": "call"}, {"api_name": "application.db.session", "line_number": 48, "usage_type": "attribute"}, {"api_name": "application.db", "line_number": 48, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 49, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 49, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 50, "usage_type": "call"}, {"api_name": "application.app.route", "line_number": 32, "usage_type": "call"}, {"api_name": "application.app", "line_number": 32, "usage_type": "name"}, {"api_name": "application.models.Teams.query.filter_by", "line_number": 54, "usage_type": "call"}, {"api_name": "application.models.Teams.query", "line_number": 54, "usage_type": "attribute"}, {"api_name": "application.models.Teams", "line_number": 54, "usage_type": "name"}, {"api_name": "application.db.session.delete", "line_number": 56, "usage_type": "call"}, {"api_name": "application.db.session", "line_number": 56, "usage_type": "attribute"}, {"api_name": "application.db", "line_number": 56, "usage_type": "name"}, {"api_name": "application.db.session.delete", "line_number": 57, "usage_type": "call"}, {"api_name": "application.db.session", "line_number": 57, "usage_type": "attribute"}, {"api_name": "application.db", "line_number": 57, "usage_type": "name"}, {"api_name": "application.db.session.commit", "line_number": 58, "usage_type": "call"}, {"api_name": "application.db.session", "line_number": 58, "usage_type": "attribute"}, {"api_name": "application.db", "line_number": 58, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 59, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 59, "usage_type": "call"}, {"api_name": "application.app.route", "line_number": 52, "usage_type": "call"}, {"api_name": "application.app", "line_number": 52, "usage_type": "name"}, {"api_name": "application.forms.PlayerForm", "line_number": 64, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 65, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 65, "usage_type": "name"}, {"api_name": "application.models.Players", "line_number": 67, "usage_type": "call"}, {"api_name": "application.db.session.add", "line_number": 72, "usage_type": "call"}, {"api_name": "application.db.session", "line_number": 72, "usage_type": "attribute"}, {"api_name": "application.db", "line_number": 72, "usage_type": "name"}, {"api_name": "application.db.session.commit", "line_number": 73, "usage_type": "call"}, {"api_name": "application.db.session", "line_number": 73, "usage_type": "attribute"}, {"api_name": "application.db", "line_number": 73, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 74, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 74, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 75, "usage_type": "call"}, {"api_name": "application.app.route", "line_number": 62, "usage_type": "call"}, {"api_name": "application.app", "line_number": 62, "usage_type": "name"}]} +{"seq_id": "71075521342", "text": "# -- coding:utf-8--\nimport multiprocessing\nfrom urllib import request\nimport os\nimport shutil\nimport zipfile\nimport time\nimport datetime\nimport json\nimport sys\nimport socket\n\n\ndef rm():\n\tprint(\"one\")\n\ttime.sleep(2)\n\tprint(\"two\")\n\tos.system(r\"rm.py\")\n\ndef jc_update():\n\tjg = True\n\tupdate_url = \"http://lucyx.cn/zzz/update.json\"\n\trequest.urlretrieve(update_url, r\"update.json\")\n\twith open(\"update.json\") as zx_1:\n\t\tedition = json.load(zx_1)\n\tif edition == 2 :\n\t\tjg = False\n\telse:\n\t\tjg = True\n\treturn jg\n\nif __name__ == \"__main__\":\n\t#防止程序打包无限循环\n\tmultiprocessing.freeze_support()\n\tif jc_update():\n\t\tprint(\"yes\")\n\telse:\n\t\tprint(\"no\")\n\n\tp = multiprocessing.Process(target=rm)\n\t#运行脚本\n\tp.start()\n\t#主进程同时打开V2RAY\n\ts.remove(r\"hi.py\")", "repo_name": "ZiJie-Duan/lcv2", "sub_path": "src/test/hi.py", "file_name": "hi.py", "file_ext": "py", "file_size_in_byte": 764, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "time.sleep", "line_number": 16, "usage_type": "call"}, {"api_name": "os.system", "line_number": 18, "usage_type": "call"}, {"api_name": "urllib.request.urlretrieve", "line_number": 23, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 23, "usage_type": "name"}, {"api_name": "json.load", "line_number": 25, "usage_type": "call"}, {"api_name": "multiprocessing.freeze_support", "line_number": 34, "usage_type": "call"}, {"api_name": "multiprocessing.Process", "line_number": 40, "usage_type": "call"}]} +{"seq_id": "23924056205", "text": "import argparse\nimport contextlib\nimport logging\nimport os\nimport string\nimport sys\nimport traceback\n\nfrom typing import Dict\nfrom typing import List\nfrom typing import Tuple\n\nfrom sampletester import convention\nfrom sampletester import environment_registry\nfrom sampletester import inputs\nfrom sampletester import runner\nfrom sampletester import summary\nfrom sampletester import testplan\nfrom sampletester import xunit\n\nVERSION = '0.16.3'\nEXITCODE_SUCCESS = 0\nEXITCODE_TEST_FAILURE = 1\nEXITCODE_FLAG_ERROR = 2\nEXITCODE_SETUP_ERROR = 3\nEXITCODE_USER_ABORT = 4\n\n# Set this to True to get a backtrace for debugging, or enable debug-level\n# logging from the command line.\nDEBUGME=False\n\ndef main():\n args, usage = parse_cli()\n if not args:\n exit(EXITCODE_SETUP_ERROR)\n\n if args.version:\n print(\"sampletester version {}\".format(VERSION))\n exit(EXITCODE_SUCCESS)\n\n log_level = LOG_LEVELS[args.logging]\n logging.getLogger().setLevel(log_level)\n logging.debug(\"argv: {}\".format(sys.argv))\n\n global DEBUGME\n DEBUGME = DEBUGME or (log_level == logging.DEBUG)\n\n try:\n indexed_docs = inputs.index_docs(*args.files)\n\n registry = environment_registry.new(args.convention, indexed_docs)\n test_suites = testplan.suites_from(indexed_docs, args.suites, args.cases)\n\n if len(test_suites) == 0:\n exit(EXITCODE_SUCCESS)\n manager = testplan.Manager(registry, test_suites, args.envs)\n\n except Exception as e:\n logging.error(f'fatal error: {repr(e)}')\n print(f'\\nERROR: could not run tests because {e}\\n')\n if DEBUGME:\n traceback.print_exc(file=sys.stdout)\n else:\n print(usage)\n exit(EXITCODE_SETUP_ERROR)\n\n verbosity = VERBOSITY_LEVELS[args.verbosity]\n quiet = verbosity == summary.Detail.NONE\n visitor = testplan.MultiVisitor(runner.Visitor(args.fail_fast),\n summary.SummaryVisitor(verbosity,\n not args.suppress_failures,\n debug=DEBUGME))\n try:\n success = manager.accept(visitor)\n except KeyboardInterrupt:\n print('\\nkeyboard interrupt; aborting')\n exit(EXITCODE_USER_ABORT)\n\n if not quiet or (not success and not args.suppress_failures):\n print()\n if success:\n print(\"Tests passed\")\n else:\n print(\"Tests failed\")\n\n if args.xunit:\n try:\n with smart_open(args.xunit) as xunit_output:\n xunit_output.write(manager.accept(xunit.Visitor()))\n if not quiet:\n print('xUnit output written to \"{}\"'.format(args.xunit))\n except Exception as e:\n print(\"could not write xunit output to {}: {}\".format(args.xunit, e))\n if DEBUGME:\n traceback.print_exc(file=sys.stdout)\n exit(EXITCODE_FLAG_ERROR)\n\n exit(EXITCODE_SUCCESS if success else EXITCODE_TEST_FAILURE)\n\n\nLOG_LEVELS = {\"none\": logging.CRITICAL, \"info\": logging.INFO, \"debug\": logging.DEBUG}\nDEFAULT_LOG_LEVEL = \"none\"\n\nVERBOSITY_LEVELS = {\"quiet\": summary.Detail.NONE, \"summary\": summary.Detail.BRIEF, \"detailed\": summary.Detail.FULL}\nDEFAULT_VERBOSITY_LEVEL = \"summary\"\n\ndef parse_cli():\n epilog = \"\"\"CONFIGS consists of any number of the following, in any order:\n\n TEST.yaml files: these are the test plans to execute against the CONVENTION\n\n arbitrary files/paths, depending on CONVENTION. For `tag` (the\n default), these should be paths to `MANIFEST.manifest.yaml` files.\n \"\"\"\n\n parser = argparse.ArgumentParser(\n description=\"A tool to run tests on equivalent samples in different languages\",\n epilog=epilog,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n parser.add_argument(\n \"-c\",\n \"--convention\",\n metavar=\"CONVENTION:ARG,ARG,...\",\n help=('name of the convention to use in resolving artifact names in ' +\n 'specific languages, and a comma-separated list of arguments to ' +\n 'that convention (default: \"{}\")'.format(convention.DEFAULT)),\n default=convention.DEFAULT\n )\n\n parser.add_argument(\n \"--xunit\", metavar=\"FILE\", help=\"xunit output file (use `-` for stdout)\")\n\n parser.add_argument(\n \"-v\", \"--verbosity\",\n help=('how much output to show for passing tests (default: \"{}\")'\n .format(DEFAULT_VERBOSITY_LEVEL)),\n choices=list(VERBOSITY_LEVELS.keys()),\n default=\"summary\"\n )\n\n parser.add_argument(\n \"-f\", \"--suppress_failures\",\n help=\"suppress showing output for failing cases\",\n action='store_true')\n\n parser.add_argument(\n \"-l\",\n \"--logging\",\n help=('show logs at the specified level (default: \"{}\")'\n .format(DEFAULT_LOG_LEVEL)),\n choices=list(LOG_LEVELS.keys()),\n default=\"none\")\n\n parser.add_argument(\n \"--envs\",\n metavar=\"TESTENV_FILTER\",\n help=\"regex filtering test environments to execute\"\n )\n\n parser.add_argument(\n \"--suites\",\n metavar=\"SUITE_FILTER\",\n help=\"regex filtering test suites to execute\"\n )\n\n parser.add_argument(\n \"--cases\",\n metavar=\"CASE_FILTER\",\n help=\"regex filtering test cases to execute\"\n )\n\n parser.add_argument(\n \"--version\",\n help=\"print version number\",\n action=\"store_true\")\n\n parser.add_argument(\n \"--fail-fast\",\n help=(\"stop execution as soon as any test case fails, preempting \" +\n \"additional test cases/suites/environments from running\"),\n action=\"store_true\")\n\n parser.add_argument(\"files\", metavar=\"CONFIGS\", nargs=argparse.REMAINDER)\n return parser.parse_args(), parser.format_usage()\n\n\n# from https://stackoverflow.com/a/17603000\n@contextlib.contextmanager\ndef smart_open(filename: str=None):\n if filename and filename != \"-\":\n fh = open(filename, \"w\")\n else:\n fh = sys.stdout\n\n try:\n yield fh\n finally:\n if fh is not sys.stdout:\n fh.close()\n\n\nif __name__ == \"__main__\":\n main()\n", "repo_name": "googleapis/sample-tester", "sub_path": "sampletester/cli.py", "file_name": "cli.py", "file_ext": "py", "file_size_in_byte": 5847, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 42, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 43, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 43, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 46, "usage_type": "attribute"}, {"api_name": "sampletester.inputs.index_docs", "line_number": 49, "usage_type": "call"}, {"api_name": "sampletester.inputs", "line_number": 49, "usage_type": "name"}, {"api_name": "sampletester.environment_registry.new", "line_number": 51, "usage_type": "call"}, {"api_name": "sampletester.environment_registry", "line_number": 51, "usage_type": "name"}, {"api_name": "sampletester.testplan.suites_from", "line_number": 52, "usage_type": "call"}, {"api_name": "sampletester.testplan", "line_number": 52, "usage_type": "name"}, {"api_name": "sampletester.testplan.Manager", "line_number": 56, "usage_type": "call"}, {"api_name": "sampletester.testplan", "line_number": 56, "usage_type": "name"}, {"api_name": "logging.error", "line_number": 59, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 62, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 62, "usage_type": "attribute"}, {"api_name": "sampletester.summary.Detail", "line_number": 68, "usage_type": "attribute"}, {"api_name": "sampletester.summary", "line_number": 68, "usage_type": "name"}, {"api_name": "sampletester.testplan.MultiVisitor", "line_number": 69, "usage_type": "call"}, {"api_name": "sampletester.testplan", "line_number": 69, "usage_type": "name"}, {"api_name": "sampletester.runner.Visitor", "line_number": 69, "usage_type": "call"}, {"api_name": "sampletester.runner", "line_number": 69, "usage_type": "name"}, {"api_name": "sampletester.summary.SummaryVisitor", "line_number": 70, "usage_type": "call"}, {"api_name": "sampletester.summary", "line_number": 70, "usage_type": "name"}, {"api_name": "sampletester.xunit.Visitor", "line_number": 89, "usage_type": "call"}, {"api_name": "sampletester.xunit", "line_number": 89, "usage_type": "name"}, {"api_name": "traceback.print_exc", "line_number": 95, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 95, "usage_type": "attribute"}, {"api_name": "logging.CRITICAL", "line_number": 101, "usage_type": "attribute"}, {"api_name": "logging.INFO", "line_number": 101, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 101, "usage_type": "attribute"}, {"api_name": "sampletester.summary.Detail", "line_number": 104, "usage_type": "attribute"}, {"api_name": "sampletester.summary", "line_number": 104, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 116, "usage_type": "call"}, {"api_name": "argparse.RawDescriptionHelpFormatter", "line_number": 119, "usage_type": "attribute"}, {"api_name": "sampletester.convention.DEFAULT", "line_number": 127, "usage_type": "attribute"}, {"api_name": "sampletester.convention", "line_number": 127, "usage_type": "name"}, {"api_name": "sampletester.convention.DEFAULT", "line_number": 128, "usage_type": "attribute"}, {"api_name": "sampletester.convention", "line_number": 128, "usage_type": "name"}, {"api_name": "argparse.REMAINDER", "line_number": 184, "usage_type": "attribute"}, {"api_name": "sys.stdout", "line_number": 194, "usage_type": "attribute"}, {"api_name": "sys.stdout", "line_number": 199, "usage_type": "attribute"}, {"api_name": "contextlib.contextmanager", "line_number": 189, "usage_type": "attribute"}]} +{"seq_id": "22684095149", "text": "from tornado.web import RequestHandler\n\nfrom handlers.http_handler.mongo_conn import MongoModel, JSONEncoder\n\n\nclass SewageHandler(RequestHandler):\n\n def get(self, *args, **kwargs):\n point_id = self.get_argument('PointID')\n count = self.get_argument('count')\n my_set = MongoModel().get_collection(name='datas')\n mn = point_id + '~32_2011'\n result_json = JSONEncoder().encode(my_set.find_one({'code': mn}))\n\n self.write('查到数据:{}'.format(result_json))\n", "repo_name": "MarnoonFeng/my_project", "sub_path": "src/handlers/http_handler/sewage_handler.py", "file_name": "sewage_handler.py", "file_ext": "py", "file_size_in_byte": 503, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "tornado.web.RequestHandler", "line_number": 6, "usage_type": "name"}, {"api_name": "handlers.http_handler.mongo_conn.MongoModel", "line_number": 11, "usage_type": "call"}, {"api_name": "handlers.http_handler.mongo_conn.JSONEncoder", "line_number": 13, "usage_type": "call"}]} +{"seq_id": "40875865840", "text": "from keras.layers import Bidirectional, Concatenate, Permute, Dot, Input, LSTM, Multiply\nfrom keras.layers import RepeatVector, Dense, Activation, Lambda\nimport tensor as tf\n\nx = tf.Variable([[1.,2.,3.],[3.,4.,5.]])\ny = tf.Variable([[4.,5.,6.],[6.,7.,8.]])\nz = Dot(axes=1)([x,y])\n\ninit = tf.initialize_all_variables()\nsess = tf.Session()\nsess.run(init)\nsess.run(x)\nsess.run(y)\nsess.run(z)\n", "repo_name": "david-d-an/Chapter5Week3", "sub_path": "NeuralMachineTranslation/KerasNotes.py", "file_name": "KerasNotes.py", "file_ext": "py", "file_size_in_byte": 389, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "tensor.Variable", "line_number": 5, "usage_type": "call"}, {"api_name": "tensor.Variable", "line_number": 6, "usage_type": "call"}, {"api_name": "keras.layers.Dot", "line_number": 7, "usage_type": "call"}, {"api_name": "tensor.initialize_all_variables", "line_number": 9, "usage_type": "call"}, {"api_name": "tensor.Session", "line_number": 10, "usage_type": "call"}]} +{"seq_id": "74346546945", "text": "from airflow import DAG\nfrom airflow.operators import LoadDimensionOperator\n\ndef load_dimension_table_dag(\n parent_dag_name,\n child_dag_name,\n args,\n tables_and_queries,\n redshift_conn_id):\n\n subdag = DAG(\n dag_id='{0}.{1}'.format(parent_dag_name, child_dag_name),\n default_args=args\n )\n with subdag:\n for table, query in tables_and_queries.items():\n load_dimension_table = LoadDimensionOperator(\n task_id=f'Load_{table}_dim_table',\n redshift_conn_id=redshift_conn_id,\n table={table},\n query=query,\n dag=subdag\n )\n\n return subdag", "repo_name": "bellabellahuang/Udacity-DEND", "sub_path": "data-pipeline/airflow/dags/subdag.py", "file_name": "subdag.py", "file_ext": "py", "file_size_in_byte": 674, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "airflow.DAG", "line_number": 11, "usage_type": "call"}, {"api_name": "airflow.operators.LoadDimensionOperator", "line_number": 17, "usage_type": "call"}]} +{"seq_id": "71170619261", "text": "from uuid import uuid4\n\nfrom . import simple_storage\nfrom . import simple_network\nfrom . import resource\nfrom .templates.redfish_computer_system import REDFISH_TEMPLATE\nfrom api_emulator.exceptions import CreatePooledNodeError\nfrom api_emulator import utils\n\nfrom .processor import Processors, Processor\n\nfrom threading import Thread\nfrom time import sleep\n\nimport collections\n\nclass ResetWorker(Thread):\n def __init__(self, states, cs):\n super(ResetWorker, self).__init__()\n self.states = states\n self.cs = cs\n\n def run(self):\n self.cs.config['PowerState'] = self.states[0]\n sleep(10)\n self.cs.config['PowerState'] = self.states[1]\n\n\nclass ComputerSystem(object):\n \"\"\"\n Pooled node based on the ComputerSystem.1.00.0.ComputerSystem\n \"\"\"\n def __init__(self, config, cs_puid, rest_base, suffix):\n \"\"\"\n ComputerSystem Constructor\n\n Note: If OVF is set to True, then config must be of type \n \n \"\"\"\n self.suffix = suffix\n self.cs_puid = cs_puid\n self.rb = rest_base\n self.config = {}\n self.processor_count = 0\n self.total_memory_gb = 0\n\n self.SimpleNetwork = simple_network.EthernetNetworkInterfaceCollection(self.rb)\n self.EthernetInterfaces= simple_network.EthernetNetworkInterfaceCollection(self.rb)\n self.SimpleStorage = simple_storage.SimpleStorageCollection(self.rb, suffix)\n self.Processors = Processors(rest_base, suffix, cs_puid)\n\n self.SimpleNetwork.init_config(self.cs_puid, suffix)\n self.EthernetInterfaces.init_config(self.cs_puid,suffix)\n self.SimpleStorage.init_config(self.cs_puid)\n\n self.configure(config)\n\n @property\n def configuration(self):\n config = self.config.copy()\n\n if self.SimpleNetwork.members:\n config['Links']['SimpleNetwork'] = \\\n {'@odata.id': self.SimpleNetwork.odata_id}\n if self.EthernetInterfaces.members:\n config['Links']['EthernetInterfaces'] = \\\n {'@odata.id': self.EthernetInterfaces.odata_id}\n if self.SimpleStorage.members:\n config['Links']['SimpleStorage'] = \\\n {'@odata.id': self.SimpleStorage.odata_id}\n\n return self.config\n\n @property\n def storage_gb(self):\n \"\"\"\n Return the amount of storage the system has in GB\n \"\"\"\n return self.SimpleStorage.storage_gb\n\n @property\n def network_ports(self):\n \"\"\"\n Return the number of VLAN network ports in the system\n \"\"\"\n return self.SimpleNetwork.port_count\n\n def configure(self, config):\n \"\"\"\n Overridden configure() method\n \"\"\"\n self._base_configure()\n self.config['Processors']['Count'] = int(config['NumberOfProcessors'])\n self.config['Links']['Processors'] = {'@odata.id': self.Processors.odata_id}\n self.processor_count = int(config['NumberOfProcessors'])\n self._create_processors(self.processor_count)\n\n self.config['Memory']['TotalSystemMemoryGB'] = int(config['TotalSystemMemoryGB'])\n self.total_memory_gb = self.config['Memory']['TotalSystemMemoryGB']\n\n if 'Boot' in config:\n self.config['Boot'] = config['Boot']\n\n self.add_network_ports(int(config['NumberOfNetworkPorts']))\n self.add_storage(config['Devices'])\n\n def reboot(self, config):\n state = config['PowerState']\n\n if state == 'On':\n states = [ 'On', 'Off' ]\n elif state == 'Off':\n states = [ 'Off', 'On' ]\n else:\n raise CreatePooledNodeError('Incorrect PowerState value.')\n\n ResetWorker(states, self).start()\n\n def _replace_config(self, config, change):\n for key, value in change.iteritems():\n if isinstance(value, collections.Mapping):\n ret = self._replace_config(config.get(key, {}), value)\n config[key] = ret\n else:\n config[key] = change[key]\n return config\n\n def update_config(self,change):\n self.config = self._replace_config(self.config, change)\n\n def add_network_ports(self, amount):\n \"\"\"\n Add network ports to the pooled node\n\n Arguments:\n amount - Number of ports to add\n \"\"\"\n status = resource.Status(resource.StateEnum.ENABLED, resource.HealthEnum.OK)\n network_objs = []\n for i in range(amount):\n config = simple_network.EthernetNetworkInterface.create_config(\n self.rb, self.suffix, self.cs_puid, i + 1, status, None, 100)\n eth = simple_network.EthernetNetworkInterface(config, None)\n network_objs.append(eth)\n self.SimpleNetwork.add_network_objects(network_objs)\n self.EthernetInterfaces.add_network_objects(network_objs)\n\n def add_storage(self, device_list):\n \"\"\"\n Add the given devices to the storage for the pooled node.\n\n NOTE: The device_list should be a list of dictionaries that can be\n turned into SimpleStorage objects\n \"\"\"\n devices = []\n\n # Creating a SimpleStorage object\n for dev in device_list:\n status = resource.Status(\n state=resource.StateEnum.ENABLED,\n health=resource.HealthEnum.OK)\n device = simple_storage.Device(\n name=dev['Name'],\n manufacturer='N/A',\n model='N/A',\n size=dev['Size'],\n status=status,\n oem={})\n devices.append(device)\n\n # Creating SimpleStorage objects\n ss = simple_storage.SimpleStorage()\n ss.init_config(\n item_id=1,\n parent_cs_puid=self.cs_puid,\n status=resource.Status(\n resource.StateEnum.ENABLED,\n resource.HealthEnum.OK,\n resource.HealthEnum.OK),\n devices=devices,\n rest_base=self.rb,\n system_suffix=self.suffix)\n storage_objects = [ss]\n self.SimpleStorage.append(storage_objects)\n\n def _create_processors(self, count):\n \"\"\"\n Populates the Processors attribute\n \"\"\"\n status = resource.Status(resource.StateEnum.ENABLED,\n resource.HealthEnum.OK)\n for i in range(count):\n p = Processor(self.rb, self.suffix, self.cs_puid,\n i + 1, i + 1, 3700, 8, 4, 4, 2, status)\n self.Processors.add_processor(p)\n\n def _base_configure(self):\n \"\"\"\n Private method to do a base configuration of the pooled node\n \"\"\"\n try:\n self.config = REDFISH_TEMPLATE.copy()\n self.odata_id = self.config['@odata.id'].format(\n rest_base=self.rb, cs_puid=self.cs_puid)\n self.config['@odata.context'] = self.config['@odata.context'].format(\n rest_base=self.rb, cs_puid=self.cs_puid)\n self.config['@odata.id'] = self.odata_id\n self.config['Actions']['#ComputerSystem.Reset']['target'] = \\\n self.config['Actions']['#ComputerSystem.Reset']['target'].format(\n cs_puid=self.cs_puid)\n self.config['Id'] = self.cs_puid\n\n except KeyError as e:\n raise CreatePooledNodeError(\n 'Incorrect configuration, missing key: ' + e.message)\n", "repo_name": "facebook/openbmc", "sub_path": "tools/Redfish-Interface-Emulator/api_emulator/redfish/computer_system.py", "file_name": "computer_system.py", "file_ext": "py", "file_size_in_byte": 7479, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 601, "dataset": "github-code", "pt": "24", "api": [{"api_name": "threading.Thread", "line_number": 17, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 25, "usage_type": "call"}, {"api_name": "processor.Processors", "line_number": 50, "usage_type": "call"}, {"api_name": "api_emulator.exceptions.CreatePooledNodeError", "line_number": 115, "usage_type": "call"}, {"api_name": "collections.Mapping", "line_number": 121, "usage_type": "attribute"}, {"api_name": "processor.Processor", "line_number": 193, "usage_type": "call"}, {"api_name": "templates.redfish_computer_system.REDFISH_TEMPLATE.copy", "line_number": 202, "usage_type": "call"}, {"api_name": "templates.redfish_computer_system.REDFISH_TEMPLATE", "line_number": 202, "usage_type": "name"}, {"api_name": "api_emulator.exceptions.CreatePooledNodeError", "line_number": 214, "usage_type": "call"}]} +{"seq_id": "15445848706", "text": "# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\nimport json\nfrom odoo.addons import decimal_precision as dp\n\nclass Product(models.Model):\n _inherit = 'product.product'\n attribute_value_ids_json = fields.Char()\n attrs_jsonb_show = fields.Char(compute='_attrs_jsonb_show')\n pname = fields.Char(related='name', store=True)\n lst_price = fields.Float(\n 'Sale Price', compute='_compute_product_lst_price', store=True,\n digits=dp.get_precision('Product Price'), inverse='_set_product_lst_price',\n help=\"The sale price is managed from the product template. Click on the 'Configure Variants' button to set the extra attribute prices.\")\n # attrs_json = fields.Json()\n\n def _attrs_jsonb_show(self):\n for r in self:\n query = '''SELECT attrs_jsonb from product_product\n WHERE id = %s'''%(r.id)\n self.env.cr.execute(query)\n rs = self.env.cr.dictfetchall()\n if rs:\n rs = rs[0]['attrs_jsonb']\n r. attrs_jsonb_show = rs\n\n def thay_doi_attribute_value_ids(self,obj, vals):\n if 'attribute_value_ids' in vals:\n for r in obj:\n adict = {}\n for attr in r.attribute_value_ids:\n attribute_id = attr.attribute_id.name\n adict[attribute_id] = attr.id\n # r.attribute_value_ids_json = adict\n query = '''UPDATE product_product\n SET attrs_jsonb = '%s'::jsonb\n WHERE id = %s'''%(json.dumps(adict), r.id)\n self.env.cr.execute(query)\n # rs = self.env.cr.fetchall()\n # print ('***rs***',rs)\n\n\n @api.model\n def create(self,vals):\n # self.clear_caches()\n rs = super(Product, self.sudo()).create(vals)\n self.thay_doi_attribute_value_ids(rs, vals)\n return rs\n\n \n @api.multi\n def write(self, vals):\n # self.clear_caches()\n rs = super(Product, self.sudo()).write(vals)\n self.thay_doi_attribute_value_ids(self, vals)\n return rs", "repo_name": "tu95ctv/tglteam", "sub_path": "attrs_json/models/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 2124, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "odoo.models.Model", "line_number": 7, "usage_type": "attribute"}, {"api_name": "odoo.models", "line_number": 7, "usage_type": "name"}, {"api_name": "odoo.fields.Char", "line_number": 9, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 9, "usage_type": "name"}, {"api_name": "odoo.fields.Char", "line_number": 10, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 10, "usage_type": "name"}, {"api_name": "odoo.fields.Char", "line_number": 11, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 11, "usage_type": "name"}, {"api_name": "odoo.fields.Float", "line_number": 12, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 12, "usage_type": "name"}, {"api_name": "odoo.addons.decimal_precision.get_precision", "line_number": 14, "usage_type": "call"}, {"api_name": "odoo.addons.decimal_precision", "line_number": 14, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 38, "usage_type": "call"}, {"api_name": "odoo.api.model", "line_number": 44, "usage_type": "attribute"}, {"api_name": "odoo.api", "line_number": 44, "usage_type": "name"}, {"api_name": "odoo.api.multi", "line_number": 52, "usage_type": "attribute"}, {"api_name": "odoo.api", "line_number": 52, "usage_type": "name"}]} +{"seq_id": "40409449554", "text": "import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport viz_utility as vutil\nimport altair as alt\n\nst.title('MH URS Parsinator - Data Review')\nst.header('Single-State Data Explorer')\n\nst.text('To view data, select a state.')\nst.text('Data is currently only available for NOMS domain, but ACCESS tab is visible for testing.')\n\n#Initialize\nstate_select = 'Select State'\n\n@st.cache_data\ndef load_data():\n data = vutil.viz_data_get()\n return data\n\n@st.cache_data\ndef load_states():\n data = vutil.url_data_get()\n return data\n\nstates = load_states()\n\nstate_select = st.selectbox(\n \"Which state's data would you like to review?\",\n ('Select State',)+tuple(states['state_name'].unique()))\n\ndata = load_data()\n\ndomains = [\"NOMS\", \"ACCESS\"]\n\nif state_select != 'Select State':\n data = data[data.state_name == state_select]\n \n tab1, tab2= st.tabs(domains)\n tabs = [tab1,tab2]\n\n for i in range(0,len(domains),1):\n domain_data = data[data.domain == domains[i]]\n\n with tabs[i]:\n for table in domain_data['table_name'].unique().tolist(): \n table_data = domain_data[domain_data.table_name == table]\n with st.expander(table):\n for metric in table_data['metric_name'].unique().tolist():\n st.header(metric)\n ch = alt.Chart(table_data[table_data['metric_name']==metric]).mark_line().encode(x='year',y='metric_result',text='state_name')\n st.altair_chart(ch, use_container_width=True)\n st.divider()\n\n\n\n", "repo_name": "PoofyOddish/mh-urs-parsinator", "sub_path": "pages/2_Single_State_Data_Explorer.py", "file_name": "2_Single_State_Data_Explorer.py", "file_ext": "py", "file_size_in_byte": 1599, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "26", "api": [{"api_name": "streamlit.title", "line_number": 7, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 8, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 10, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 11, "usage_type": "call"}, {"api_name": "viz_utility.viz_data_get", "line_number": 18, "usage_type": "call"}, {"api_name": "streamlit.cache_data", "line_number": 16, "usage_type": "attribute"}, {"api_name": "viz_utility.url_data_get", "line_number": 23, "usage_type": "call"}, {"api_name": "streamlit.cache_data", "line_number": 21, "usage_type": "attribute"}, {"api_name": "streamlit.selectbox", "line_number": 28, "usage_type": "call"}, {"api_name": "streamlit.tabs", "line_number": 39, "usage_type": "call"}, {"api_name": "streamlit.expander", "line_number": 48, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 50, "usage_type": "call"}, {"api_name": "altair.Chart", "line_number": 51, "usage_type": "call"}, {"api_name": "streamlit.altair_chart", "line_number": 52, "usage_type": "call"}, {"api_name": "streamlit.divider", "line_number": 53, "usage_type": "call"}]} +{"seq_id": "17200223586", "text": "from django.db import models\nfrom inventario.models import Semilla\nfrom usuario.models import Agricultor\n# Create your models here.\n\n\nclass EntregaAAgricultor(models.Model):\n FechaEntrega = models.DateField(\n verbose_name=\"Fecha de movimiento\",\n auto_now=True\n )\n HectareasAPlantar = models.PositiveIntegerField(verbose_name=\"Hectareas a plantar\")\n SemillasDadas = models.PositiveIntegerField(\n verbose_name=\"KG de semillas dadas\",\n default=1,\n )\n TipoSemilla = models.ForeignKey(\n Semilla,\n verbose_name=\"Tipo de semillas que se darán\",\n null=True,\n blank=True,\n on_delete=models.CASCADE\n )\n NombreAgricultor = models.ForeignKey(\n Agricultor,\n default=2,\n verbose_name=\"Agricultor al que se le darán las semillas\",\n null=True,\n blank=True,\n on_delete=models.CASCADE\n )\n\n def __str__(self):\n return str(self.SemillasDadas) + \" KG de \" + str(self.TipoSemilla) + \" - \" + str(self.NombreAgricultor)\n\n class Meta:\n ordering = [\"-FechaEntrega\"]\n verbose_name_plural = \"Entregas a agricultores\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "repo_name": "miguelzetina/sistema", "sub_path": "movimiento/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 1164, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.db.models.Model", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 7, "usage_type": "name"}, {"api_name": "django.db.models.DateField", "line_number": 8, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 8, "usage_type": "name"}, {"api_name": "django.db.models.PositiveIntegerField", "line_number": 12, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 12, "usage_type": "name"}, {"api_name": "django.db.models.PositiveIntegerField", "line_number": 13, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 13, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 17, "usage_type": "call"}, {"api_name": "inventario.models.Semilla", "line_number": 18, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 17, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 22, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 22, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 24, "usage_type": "call"}, {"api_name": "usuario.models.Agricultor", "line_number": 25, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 24, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 30, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 30, "usage_type": "name"}]} +{"seq_id": "37488531762", "text": "#!/usr/local/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@File : ui_stdf.py\n@Author : Link\n@Time : 2022/5/2 10:44\n@Mark : \n\"\"\"\nimport math\nimport sys\nimport datetime as dt\nfrom typing import Union, List\nfrom pydoc import help\n\nimport numpy as np\nimport pandas as pd\nfrom PySide2.QtCore import Slot, QTimer, Qt, Signal\nfrom PySide2.QtGui import QCloseEvent\nfrom PySide2.QtWidgets import QMainWindow, QApplication, QWidget, QMessageBox\n\nfrom pyqtgraph.dockarea import *\n\nfrom chart_core.chart_pyqtgraph.core.mixin import ChartType\nfrom chart_core.chart_pyqtgraph.poll import ChartDockWindow\nfrom common.li import Li, SummaryCore\nfrom ui_component.ui_analysis_stdf.ui_components.ui_data_group import DataGroupWidget\nfrom ui_component.ui_common.ui_console import ConsoleWidget\nfrom ui_component.ui_analysis_stdf.ui_designer.ui_home_load import Ui_MainWindow\nfrom ui_component.ui_common.ui_utils import QTableUtils\nfrom ui_component.ui_analysis_stdf.ui_components.ui_file_load_widget import FileLoadWidget # 文件选取\nfrom ui_component.ui_analysis_stdf.ui_components.ui_tree_load_widget import TreeLoadWidget # 载入的数据选取\nfrom ui_component.ui_analysis_stdf.ui_components.ui_table_load_widget import TableLoadWidget # 测试项选取\n\n\nclass StdfLoadUi(QMainWindow, Ui_MainWindow):\n \"\"\"\n 懒加载界面\n \"\"\"\n closeSignal = Signal(int)\n parent = None\n\n def __init__(self, parent=None, space_nm=1, path_select=False, select=True, is_web=False):\n super(StdfLoadUi, self).__init__(parent)\n self.setupUi(self)\n self.space_nm = space_nm\n self.li = Li()\n self.summary = SummaryCore()\n self.title = \"STDF数据载入空间: {}\".format(space_nm)\n self.setWindowTitle(self.title)\n\n self.area = DockArea()\n self.setCentralWidget(self.area)\n \" FileLoadWidget用来载入数据文件,内部用到多线程 \"\n self.stdf_select_widget = FileLoadWidget(self.summary, self, space_nm=space_nm)\n self.dock_stdf_load = Dock(\"STDF File Select\", size=(400, 100))\n self.dock_stdf_load.addWidget(self.stdf_select_widget)\n self.area.addDock(self.dock_stdf_load)\n\n \" TreeLoadWidget用来载入和配对内部数据,会占用到大量的IO资源 \"\n self.tree_load_widget = TreeLoadWidget(self.li, self.summary, self)\n dock_tree_load = Dock(\"Data Tree Select & Config\", size=(200, 300))\n dock_tree_load.addWidget(self.tree_load_widget)\n self.area.addDock(dock_tree_load, \"bottom\", self.dock_stdf_load)\n # self.area.moveDock(self.dock_stdf_load, 'above', dock_tree_load)\n\n \" TableLoadWidget用来载入和配对内部数据,会占用到大量的IO资源, 并且是作为主要的分析界面 \"\n self.table_load_widget = TableLoadWidget(self.li, self.summary, self)\n dock_table_load = Dock(\"Data TEST NO&ITEM Analysis\", size=(200, 300))\n dock_table_load.addWidget(self.table_load_widget)\n self.area.addDock(dock_table_load, \"right\", dock_tree_load)\n # self.area.moveDock(dock_tree_load, 'above', dock_table_load)\n\n \" DataGroupWidget用来对数据进行简单的分组和筛选 \"\n self.group_table_widget = DataGroupWidget(self.li)\n dock_group_load = Dock(\"Data Group\", size=(50, 300))\n dock_group_load.addWidget(self.group_table_widget)\n self.area.addDock(dock_group_load)\n\n text = \"\"\"\n 载入的功能包: np(numpy), pd(pandas), math\n 载入的数据:\n 点击RUN后会被刷新 \n li: 数据空间的集合数据, 通过help(li)查看\n RUN.\n \"\"\"\n self.namespace = {\n \"np\": np,\n \"pd\": pd,\n \"math\": math,\n \"help\": help,\n \"li\": self.li,\n \"summary\": self.summary\n }\n self.console = ConsoleWidget(parent=self, namespace=self.namespace, text=text)\n self.dock_console_load = Dock(\"Python Console\", size=(400, 100))\n self.dock_console_load.addWidget(self.console)\n self.area.addDock(self.dock_console_load, \"bottom\")\n # self.area.moveDock(self.dock_stdf_load, 'above', dock_console_load)\n \"------------------------------------------------------------------------------\"\n self.area.restoreState(\n {\n 'main': (\n 'horizontal',\n [\n ('dock', 'Data Group', {}),\n ('vertical',\n [('horizontal', [\n (\n 'vertical',\n [\n (\n 'dock',\n 'STDF File Select',\n {}\n ),\n ('dock',\n 'Data Tree Select & Config',\n {}\n )\n ],\n {\n 'sizes': [147, 198]\n }\n ),\n (\n 'dock',\n 'Python Console',\n {})],\n {'sizes': [737, 429]}),\n ('dock',\n 'Data TEST NO&ITEM Analysis',\n {})],\n {'sizes': [350, 439]})],\n {'sizes': [372, 1171]}), 'float': []})\n self.dock_console_load.hide() # 可以显示和隐藏\n self.init_signal()\n\n \" 用来存放chart的 \"\n self.chart_ui = ChartDockWindow(self.li, None, icon=None, space_nm=space_nm) # type:ChartDockWindow\n\n if select and is_web is False:\n if path_select:\n self.stdf_select_widget.first_directory_select()\n else:\n self.stdf_select_widget.first_select()\n\n def init_signal(self):\n self.stdf_select_widget.finished.connect(self.tree_load_widget.set_tree)\n self.li.QCalculation.connect(self.q_calculation)\n self.li.QMessage.connect(self.message_show)\n self.li.QStatusMessage.connect(self.mdi_space_message_emit)\n\n def q_calculation(self):\n self.table_load_widget.cal_table()\n self.group_table_widget.checkbox_changed()\n\n @Slot(SummaryCore)\n def merge_data_emit(self, data: SummaryCore):\n self.summary = data\n self.tree_load_widget.set_tree()\n\n @Slot()\n def on_action_dock_structure_triggered(self):\n \"\"\" 将 area 布局保存在泡菜中 \"\"\"\n state = self.area.saveState()\n print(state)\n\n @Slot()\n def on_action_sava_data_triggered(self):\n \"\"\" 将数据保存在csv文件中 \"\"\"\n\n @Slot()\n def on_action_console_triggered(self):\n if self.action_console.isChecked():\n self.dock_console_load.show()\n else:\n self.dock_console_load.hide()\n\n @Slot()\n def on_action_limit_triggered(self):\n self.li.show_limit_diff()\n\n @Slot(str)\n def mdi_space_message_emit(self, message: str):\n \"\"\"\n append message\n :param message:\n :return:\n \"\"\"\n self.statusbar.showMessage(\"==={}==={}===\".format(dt.datetime.now().strftime(\"%H:%M:%S\"), message))\n\n def message_show(self, text: str) -> bool:\n res = QMessageBox.question(self, '待确认', text,\n QMessageBox.Yes | QMessageBox.No,\n QMessageBox.Yes)\n if res == QMessageBox.Yes:\n return True\n else:\n return False\n\n def get_test_id_column(self) -> Union[List[int], None]:\n \"\"\"\n\n :return:\n \"\"\"\n return QTableUtils.get_table_widget_test_id(self.table_load_widget.cpk_info_table)\n\n def get_text_column(self) -> Union[List[str], None]:\n \"\"\"\n\n :return:\n \"\"\"\n test_id_column = self.get_test_id_column()\n if not test_id_column:\n return None\n text_column = []\n for each in test_id_column:\n table_row = self.li.capability_key_dict[each]\n text = str(table_row[\"TEST_NUM\"]) + \":\" + table_row[\"TEST_TXT\"]\n text_column.append(text)\n return text_column\n\n @Slot()\n def on_action_qt_distribution_trans_triggered(self):\n \"\"\" 使用PYQT来拉出横向柱状分布图 \"\"\"\n test_id_column: List[int] = self.get_test_id_column()\n self.chart_ui.add_chart_dock(test_id_column, ChartType.TransBar)\n self.chart_ui.show()\n self.chart_ui.raise_()\n\n @Slot()\n def on_action_qt_scatter_triggered(self):\n \"\"\" 使用PYQT来拉出线性散点图 \"\"\"\n test_id_column: List[int] = self.get_test_id_column()\n self.chart_ui.add_chart_dock(test_id_column, ChartType.TransScatter)\n self.chart_ui.show()\n self.chart_ui.raise_()\n\n @Slot()\n def on_action_qt_mapping_triggered(self):\n \"\"\" 使用PYQT来拉出Mapping图 \"\"\"\n pass\n\n @Slot()\n def on_action_qt_visual_map_triggered(self):\n \"\"\" 使用PYQT来拉出Visual Map图 \"\"\"\n test_id_column = self.get_test_id_column()\n self.chart_ui.add_chart_dock(test_id_column, ChartType.VisualMap)\n self.chart_ui.show()\n self.chart_ui.raise_()\n\n def closeEvent(self, a0: QCloseEvent) -> None:\n \"\"\"\n 删除mdi时, 需要将与其对应的chart也删除\n \"\"\"\n self.closeSignal.emit(self.space_nm)\n return super(StdfLoadUi, self).closeEvent(a0)\n", "repo_name": "Crazytommy90/ATE_STDF_ANALYSIS", "sub_path": "ui_component/ui_analysis_stdf/ui_stdf.py", "file_name": "ui_stdf.py", "file_ext": "py", "file_size_in_byte": 9798, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "PySide2.QtWidgets.QMainWindow", "line_number": 36, "usage_type": "name"}, {"api_name": "ui_component.ui_analysis_stdf.ui_designer.ui_home_load.Ui_MainWindow", "line_number": 36, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Signal", "line_number": 40, "usage_type": "call"}, {"api_name": "common.li.Li", "line_number": 47, "usage_type": "call"}, {"api_name": "common.li.SummaryCore", "line_number": 48, "usage_type": "call"}, {"api_name": "ui_component.ui_analysis_stdf.ui_components.ui_file_load_widget.FileLoadWidget", "line_number": 55, "usage_type": "call"}, {"api_name": "ui_component.ui_analysis_stdf.ui_components.ui_tree_load_widget.TreeLoadWidget", "line_number": 61, "usage_type": "call"}, {"api_name": "ui_component.ui_analysis_stdf.ui_components.ui_table_load_widget.TableLoadWidget", "line_number": 68, "usage_type": "call"}, {"api_name": "ui_component.ui_analysis_stdf.ui_components.ui_data_group.DataGroupWidget", "line_number": 75, "usage_type": "call"}, {"api_name": "pydoc.help", "line_number": 91, "usage_type": "name"}, {"api_name": "ui_component.ui_common.ui_console.ConsoleWidget", "line_number": 95, "usage_type": "call"}, {"api_name": "chart_core.chart_pyqtgraph.poll.ChartDockWindow", "line_number": 140, "usage_type": "call"}, {"api_name": "common.li.SummaryCore", "line_number": 159, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Slot", "line_number": 158, "usage_type": "call"}, {"api_name": "common.li.SummaryCore", "line_number": 158, "usage_type": "argument"}, {"api_name": "PySide2.QtCore.Slot", "line_number": 163, "usage_type": "call"}, {"api_name": "PySide2.QtCore.Slot", "line_number": 169, "usage_type": "call"}, {"api_name": "PySide2.QtCore.Slot", "line_number": 173, "usage_type": "call"}, {"api_name": "PySide2.QtCore.Slot", "line_number": 180, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 191, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 191, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore.Slot", "line_number": 184, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QMessageBox.question", "line_number": 194, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QMessageBox", "line_number": 194, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QMessageBox.Yes", "line_number": 195, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets.QMessageBox", "line_number": 195, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QMessageBox.No", "line_number": 195, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets.QMessageBox.Yes", "line_number": 196, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets.QMessageBox", "line_number": 196, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QMessageBox.Yes", "line_number": 197, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets.QMessageBox", "line_number": 197, "usage_type": "name"}, {"api_name": "ui_component.ui_common.ui_utils.QTableUtils.get_table_widget_test_id", "line_number": 207, "usage_type": "call"}, {"api_name": "ui_component.ui_common.ui_utils.QTableUtils", "line_number": 207, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 202, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 202, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 209, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 209, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 227, "usage_type": "name"}, {"api_name": "chart_core.chart_pyqtgraph.core.mixin.ChartType.TransBar", "line_number": 228, "usage_type": "attribute"}, {"api_name": "chart_core.chart_pyqtgraph.core.mixin.ChartType", "line_number": 228, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Slot", "line_number": 224, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 235, "usage_type": "name"}, {"api_name": "chart_core.chart_pyqtgraph.core.mixin.ChartType.TransScatter", "line_number": 236, "usage_type": "attribute"}, {"api_name": "chart_core.chart_pyqtgraph.core.mixin.ChartType", "line_number": 236, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Slot", "line_number": 232, "usage_type": "call"}, {"api_name": "PySide2.QtCore.Slot", "line_number": 240, "usage_type": "call"}, {"api_name": "chart_core.chart_pyqtgraph.core.mixin.ChartType.VisualMap", "line_number": 249, "usage_type": "attribute"}, {"api_name": "chart_core.chart_pyqtgraph.core.mixin.ChartType", "line_number": 249, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Slot", "line_number": 245, "usage_type": "call"}, {"api_name": "PySide2.QtGui.QCloseEvent", "line_number": 253, "usage_type": "name"}]} +{"seq_id": "71521177342", "text": "import collections\nimport itertools\n\nimport numpy as np\n\nfrom ... import draw, mesh\nfrom ...draw import internal\n\nLightInfo = collections.namedtuple(\n 'LightInfo', ['normal', 'magnitude'])\n\n@internal.ShapeDecorator\nclass Disks(draw.Disks):\n __doc__ = draw.Disks.__doc__\n\n def render(self, rotation=(1, 0, 0, 0), name_suffix='', illo_id='illo',\n **kwargs):\n # in the zdog coordinate system, x is to the right, y is down,\n # and z is toward you\n lines = []\n\n particles = zip(*mesh.unfoldProperties([\n self.positions*(1, -1), self.diameters, self.colors*255]))\n for i, (position, (diameter,), color) in enumerate(particles):\n group_index = 'disk_{}_{}'.format(name_suffix, i)\n\n (r, g, b) = map(int, color[:3])\n color_str = '\"rgba({}, {}, {}, {})\"'.format(\n r, g, b, color[3]/255)\n\n lines.append(\"\"\"\n new Zdog.Shape({{\n addTo: {illo_id},\n translate: {{x: {pos[0]}, y: {pos[1]}}},\n stroke: {diameter},\n color: {color},\n }});\"\"\".format(\n group_index=group_index, illo_id=illo_id, pos=position,\n diameter=diameter, color=color_str))\n\n return lines\n", "repo_name": "glotzerlab/plato", "sub_path": "plato/draw/zdog/Disks.py", "file_name": "Disks.py", "file_ext": "py", "file_size_in_byte": 1288, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 11, "dataset": "github-code", "pt": "24", "api": [{"api_name": "collections.namedtuple", "line_number": 9, "usage_type": "call"}, {"api_name": "draw.Disks", "line_number": 13, "usage_type": "attribute"}, {"api_name": "draw.Disks", "line_number": 14, "usage_type": "attribute"}, {"api_name": "draw.internal.ShapeDecorator", "line_number": 12, "usage_type": "attribute"}, {"api_name": "draw.internal", "line_number": 12, "usage_type": "name"}]} +{"seq_id": "43150134416", "text": "import asyncio\nimport random\n\nimport discord\nimport json\n\nfrom discord.ext import commands\n\n\nclass Shop(commands.Cog):\n def __init__(self, bot: commands.Bot):\n self.bot = bot\n self.config = json.load(open(\"config.json\", \"r\"))\n self.colors = [0xFFE4E1, 0x00FF7F, 0xD8BFD8, 0xDC143C, 0xFF4500, 0xDEB887, 0xADFF2F, 0x800000, 0x4682B4, 0x006400, 0x808080, 0xA0522D, 0xF08080, 0xC71585, 0xFFB6C1, 0x00CED1]\n self.cache = {}\n self.messages = {}\n self.embeds = {}\n\n @commands.command()\n @commands.has_permissions(administrator=True)\n async def new(self, ctx: commands.Context):\n questions = [\n \"What will be the product name ?\",\n \"What will be the product prize ?\",\n \"Please send the product image here.\",\n \"What will be the destination channel ?\"\n ]\n answers = []\n\n def check(m):\n return m.author == ctx.author and m.channel == ctx.channel\n i = 1\n for q in questions:\n xx = await ctx.send(embed=discord.Embed(title=f\"Question {i}\", color=random.choice(self.colors), description=q))\n msg = await self.bot.wait_for(\"message\", check=check)\n answers.append(msg.content)\n i+=1\n await xx.delete()\n await msg.delete()\n try:\n int(answers[3][2:-1])\n float(answers[1])\n except ValueError:\n return await ctx.send(\"The channel you mentionned or the prize are not correct.\")\n\n embed = discord.Embed(title=answers[0], color=random.choice(self.colors), description=f\"{answers[1]}€\\nStock!\")\n embed.set_image(url=answers[2])\n channel = self.bot.get_channel(int(answers[3][2:-1]))\n x = await channel.send(embed=embed)\n await x.add_reaction(\"🛒\")\n await x.add_reaction(\"❌\")\n\n products = json.load(open(\"products.json\", \"r\"))\n products[str(x.id)] = {\n \"name\": answers[0],\n \"prize\": float(answers[1])\n }\n json.dump(products, open(\"products.json\", \"w\"), indent=4)\n\n @commands.Cog.listener()\n async def on_raw_reaction_add(self, payload):\n member = payload.member\n user = self.bot.get_user(payload.user_id)\n emoji = payload.emoji\n message_id = payload.message_id\n if self.bot.user in [member, user] : return\n is_dm = isinstance(self.bot.get_channel(payload.channel_id), discord.DMChannel)\n products = json.load(open(\"products.json\", \"r\"))\n if str(message_id) in products.keys():\n channel = self.bot.get_channel(payload.channel_id)\n message = await channel.fetch_message(message_id)\n await message.remove_reaction(emoji, member)\n\n async def edit_cart():\n p = []\n total_prize = 0\n for product in cart_data.keys():\n if self.cache[member.id][product] == 0:\n continue\n else:\n p.append(\n f\"**{products[str(product)]['name']}** x **{self.cache[member.id][product]}**= **{round(products[str(product)]['prize'] * self.cache[member.id][product], 2)}€**\\n\")\n total_prize += round(products[str(product)][\"prize\"], 2) * self.cache[member.id][product]\n\n products_string = \"\".join(p)\n delemitation = \"~--------------------------------------~\\nReact with ✔️ to confirm the order and create a ticket.\\nReact with ❌ to cancel the order\"\n due_embed = discord.Embed(title=f\"Ticket for {member.name}\", color=random.choice(self.colors),\n description=f\"{products_string}\\n**Total Prize: __{total_prize}__**\\n{delemitation}\")\n\n if member.id not in self.messages.keys():\n dm = await member.send(embed=due_embed)\n await dm.add_reaction(\"✔️\")\n await dm.add_reaction(\"❌\")\n self.messages[member.id] = dm.id\n self.embeds[member.id] = due_embed.to_dict()\n else:\n chann_user = self.bot.get_user(member.id)\n priv_chann = chann_user.dm_channel\n temp_msg = await priv_chann.fetch_message(self.messages[member.id])\n self.embeds[member.id][\n \"description\"] = f\"{products_string}\\n**Total Prize: __{round(total_prize, 2)}€__**\\n{delemitation}\"\n edited_embed = discord.Embed.from_dict(self.embeds[member.id])\n await temp_msg.edit(embed=edited_embed)\n\n if str(emoji) == \"🛒\":\n if member.id not in self.cache.keys():\n self.cache[member.id] = {}\n if message_id not in self.cache[member.id].keys():\n self.cache[member.id][message_id] = 0\n self.cache[member.id][message_id] += 1\n cart_data = self.cache[member.id]\n await edit_cart()\n\n if str(emoji) == \"❌\":\n if member.id not in self.cache.keys() or message_id not in self.cache[member.id].keys() or self.cache[member.id][message_id] <= 0: return\n self.cache[member.id][message_id] -= 1\n cart_data = self.cache[member.id]\n await edit_cart()\n\n elif is_dm:\n if str(emoji) == \"✔️\":\n guild = self.bot.get_guild(self.config[\"guild_id\"])\n private_channel = user.dm_channel\n msg = await private_channel.fetch_message(self.messages[user.id])\n tickets_catergory = discord.utils.get(guild.categories, id=self.config[\"tickets_category\"])\n await tickets_catergory.set_permissions(user, read_messages=True)\n command_channel = await guild.create_text_channel(f\"ticket-{user.name}\", category=tickets_catergory)\n embed = discord.Embed(title=f\"Ticket {user.name.capitalize()}\", color=random.choice(self.colors), description=\n f\"**Order Summary ->**\\n\\n{self.embeds[user.id]['description'].split('~')[0]}\\n\"\n f\"Use the command `!close` to close this ticket!\")\n await command_channel.send(embed=embed)\n del self.embeds[user.id]\n del self.cache[user.id]\n del self.messages[user.id]\n await msg.delete()\n\n tickets = json.load(open(\"tickets.json\", \"r\"))\n tickets[str(command_channel.id)] = user.id\n json.dump(tickets, open(\"tickets.json\", \"w\"), indent=4)\n\n if str(emoji) == \"❌\":\n private_channel = user.dm_channel\n msg = await private_channel.fetch_message(self.messages[user.id])\n del self.embeds[user.id]\n del self.cache[user.id]\n del self.messages[user.id]\n await msg.edit(embed=discord.Embed(description=\"Order Canceled.\", color=random.choice(self.colors)))\n for reaction in msg.reactions:\n await msg.remove_reaction(reaction, self.bot.user)\n await asyncio.sleep(5)\n await msg.delete()\n\n @commands.command()\n @commands.has_permissions(administrator=True)\n async def delete(self, ctx, msg_id):\n data = json.load(open(\"products.json\", \"r\"))\n if not msg_id in data.keys():\n return await ctx.send(embed=discord.Embed(color=random.choice(self.colors), description=\"No product found with this id\"))\n name = data[msg_id][\"name\"]\n try:\n msg = await ctx.channel.fetch_message(int(msg_id))\n await msg.delete()\n except Exception:\n pass\n await ctx.send(embed=discord.Embed(color=random.choice(self.colors), description=f\"The product `{name}` was removed from the shop.\"))\n del data[msg_id]\n json.dump(data, open(\"products.json\", \"w\"), indent=4)\n\n @commands.command()\n async def close(self, ctx):\n tickets = json.load(open(\"tickets.json\", \"r\"))\n if str(ctx.channel.id) in tickets.keys():\n channel = self.bot.get_channel(ctx.channel.id)\n embed = discord.Embed(title=\"Ticket closed.\", color=random.choice(self.colors),\n description=\"This ticket channel will be closed in 5 seconds.\")\n await channel.send(embed=embed)\n await asyncio.sleep(5)\n await channel.delete()\n del tickets[str(ctx.channel.id)]\n json.dump(tickets, open(\"tickets.json\", \"w\"), indent=4)\n\ndef setup(bot): bot.add_cog(Shop(bot))", "repo_name": "AirReaper/Bot-Discord-Shop-Keeper", "sub_path": "cogs/shop.py", "file_name": "shop.py", "file_ext": "py", "file_size_in_byte": 8771, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "discord.ext.commands.Cog", "line_number": 10, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 10, "usage_type": "name"}, {"api_name": "discord.ext.commands.Bot", "line_number": 11, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 11, "usage_type": "name"}, {"api_name": "json.load", "line_number": 13, "usage_type": "call"}, {"api_name": "discord.ext.commands.Context", "line_number": 21, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 21, "usage_type": "name"}, {"api_name": "discord.Embed", "line_number": 34, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 34, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 46, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 46, "usage_type": "call"}, {"api_name": "json.load", "line_number": 53, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 58, "usage_type": "call"}, {"api_name": "discord.ext.commands.command", "line_number": 19, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 19, "usage_type": "name"}, {"api_name": "discord.ext.commands.has_permissions", "line_number": 20, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 20, "usage_type": "name"}, {"api_name": "discord.DMChannel", "line_number": 67, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 68, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 87, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 87, "usage_type": "call"}, {"api_name": "discord.Embed.from_dict", "line_number": 102, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 102, "usage_type": "attribute"}, {"api_name": "discord.utils.get", "line_number": 125, "usage_type": "call"}, {"api_name": "discord.utils", "line_number": 125, "usage_type": "attribute"}, {"api_name": "discord.Embed", "line_number": 128, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 128, "usage_type": "call"}, {"api_name": "json.load", "line_number": 137, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 139, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 147, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 147, "usage_type": "call"}, {"api_name": "asyncio.sleep", "line_number": 150, "usage_type": "call"}, {"api_name": "discord.ext.commands.Cog.listener", "line_number": 60, "usage_type": "call"}, {"api_name": "discord.ext.commands.Cog", "line_number": 60, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 60, "usage_type": "name"}, {"api_name": "json.load", "line_number": 156, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 158, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 158, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 165, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 165, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 167, "usage_type": "call"}, {"api_name": "discord.ext.commands.command", "line_number": 153, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 153, "usage_type": "name"}, {"api_name": "discord.ext.commands.has_permissions", "line_number": 154, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 154, "usage_type": "name"}, {"api_name": "json.load", "line_number": 171, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 174, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 174, "usage_type": "call"}, {"api_name": "asyncio.sleep", "line_number": 177, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 180, "usage_type": "call"}, {"api_name": "discord.ext.commands.command", "line_number": 169, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 169, "usage_type": "name"}]} +{"seq_id": "72048417346", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.decomposition import PCA\nfrom sklearn import datasets\nfrom sklearn.cluster import KMeans\n\n# load the dataset\niris_df = datasets.load_iris()\npca = PCA(2)\n\n# print y-values names\nprint(iris_df.target_names)\n\n# split the dataset\nX, y = iris_df.data, iris_df.target\nX_proj = pca.fit_transform(X)\n\n# plot the dataset\nplt.scatter(X_proj[:, 0], X_proj[:, 1], c=y)\nplt.show()\n\n# set the size of the plot\nplt.figure(figsize=(10, 4))\n\n# create color map\ncolormap = np.array(['red', 'lime', 'black', 'blue', 'yellow', 'green', 'red'])\n\nk = 3 # running kmeans clustering into two\nkmeans = KMeans(n_clusters=k, random_state=0).fit(X_proj) # train the classifier\n\n# set the classifiers y-values to labels\nlabels = kmeans.labels_\n\n# plot the original classifier\nplt.subplot(1, 2, 1)\nplt.scatter(X_proj[:, 0], X_proj[:, 1], c=colormap[y], s=40)\nplt.title('Real Classification')\n\n# plot the model classifier\nplt.subplot(1, 2, 2)\nplt.scatter(X_proj[:, 0], X_proj[:, 1], c=colormap[labels], s=40)\nplt.title('K-Mean Classification')\n\nplt.show()\n", "repo_name": "alex-marquardt/MachineLearningExam2019", "sub_path": "Exercise 3/iris_dataset_kmeans_pca.py", "file_name": "iris_dataset_kmeans_pca.py", "file_ext": "py", "file_size_in_byte": 1091, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sklearn.datasets.load_iris", "line_number": 8, "usage_type": "call"}, {"api_name": "sklearn.datasets", "line_number": 8, "usage_type": "name"}, {"api_name": "sklearn.decomposition.PCA", "line_number": 9, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 26, "usage_type": "call"}, {"api_name": "sklearn.cluster.KMeans", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 36, "usage_type": "call"}, {"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": "matplotlib.pyplot.subplot", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}]} +{"seq_id": "33317312855", "text": "from pymongo import MongoClient\nfrom exceptions.StudentExistsException import StudentExistsException\nfrom email_sender import send_email\nimport pickle\nimport os\n\nclient = MongoClient(os.environ['MONGODB_HOST_NAME'])\ndb = client[os.environ['MONGODB_DB_NAME']]\ncollection = db[os.environ['MONGODB_COLLECTION_NAME']]\n\n\ndef add_student_to_course(course, student):\n # serialization of objects\n student_binary = pickle.dumps(student)\n course_binary = pickle.dumps(course)\n\n if not student in course.students:\n collection.update_one({'_id': course.unique_id},\n {'$set':\n {'course': course_binary},\n '$push':\n {'students': student_binary},\n },\n upsert=True)\n course.add_student(student)\n send_email(student, course, 'verification')\n else:\n raise StudentExistsException()\n\n\ndef remove_course(course):\n collection.delete_one({'_id': course.unique_id})\n\n\ndef get_courses():\n documents = list(collection.find({}))\n courses = []\n for course_binary in documents:\n # deserializes objects\n course = pickle.loads(course_binary['course'])\n\n for student_binary in course_binary['students']:\n student = pickle.loads(student_binary)\n course.add_student(student)\n courses.append(course)\n return courses\n\n\ndef get_number_of_courses():\n return collection.estimated_document_count()\n", "repo_name": "mertbarutcuoglu/Seat-Checker", "sub_path": "database.py", "file_name": "database.py", "file_ext": "py", "file_size_in_byte": 1555, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pymongo.MongoClient", "line_number": 7, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 8, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 9, "usage_type": "attribute"}, {"api_name": "pickle.dumps", "line_number": 14, "usage_type": "call"}, {"api_name": "pickle.dumps", "line_number": 15, "usage_type": "call"}, {"api_name": "email_sender.send_email", "line_number": 26, "usage_type": "call"}, {"api_name": "exceptions.StudentExistsException.StudentExistsException", "line_number": 28, "usage_type": "call"}, {"api_name": "pickle.loads", "line_number": 40, "usage_type": "call"}, {"api_name": "pickle.loads", "line_number": 43, "usage_type": "call"}]} +{"seq_id": "3925888555", "text": "import numpy\nimport spidev # import the spidev module\nimport time\nimport OSC\n\nnumChannels = 6;\nchannelOffset = 2;\nnumSamples = 4;\n\n# values = numpy.empty((numChannels, numSamples), dtype=numpy.uint16)\nsampleIndex = 0\nvalues = [-1, -1, -1, -1, -1, -1]\n# lastValues = [-1, -1, -1, -1, -1, -1, -1, -1]\n\nspi = spidev.SpiDev() # create a new spidev object\nspi.open(0, 1) # open bus 0, chip enable 1\nspi.max_speed_hz = 500000 # 1MHz\n\nsc = OSC.OSCClient()\nsc.connect(('127.0.0.1', 57120)) #send locally to sc\n# sc.connect(('192.168.1.35', 57120)) #send to external sc\n\ndef init():\n values = values * 0\n lastSendValue = lastSensValue * 0\n\ndef sendOSC(_name, _values):\n msg = OSC.OSCMessage()\n msg.setAddress(_name)\n for value in _values:\n msg.append(4095 - value)\n try:\n sc.send(msg)\n except:\n 1+1 # dummy\n #print msg\n\ndef readADC(_channel):\n if _channel > 7 or _channel < 0:\n return -1\n\n input_mode = 1; # single ended = 1, differential = 0\n command = 0x04; # start flag\n command |= (input_mode<<1);\n command |= (_channel>>2) & 0x01; # add msb of channel in our first command byte\n bytes = spi.xfer2([command, _channel<<6, 0x00])\n result = (bytes[1] & 0x0f)<<8 | bytes[2]\n return result;\n\ntry:\n while True:\n for channel in range(numChannels):\n # values[channel, sampleIndex] = readADC(channel)\n values[channel] = readADC(channel + channelOffset)\n\n # medianValues = numpy.median(values, axis=1)\n # medianValues = 1 - (medianValues/4095.0)\n # print \"%4d\" % value,\n sendOSC(\"/adc\", values)\n # sampleIndex += 1\n # sampleIndex %= numSamples\n\n time.sleep(0.05)\n # print;\nexcept KeyboardInterrupt:\n # Ctrl+C pressed, so...\n spi.close()\n", "repo_name": "constantin3000/PiCollider", "sub_path": "adc2osc_bundle.py", "file_name": "adc2osc_bundle.py", "file_ext": "py", "file_size_in_byte": 1708, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "24", "api": [{"api_name": "spidev.SpiDev", "line_number": 15, "usage_type": "call"}, {"api_name": "OSC.OSCClient", "line_number": 19, "usage_type": "call"}, {"api_name": "OSC.OSCMessage", "line_number": 28, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 63, "usage_type": "call"}]} +{"seq_id": "32893567818", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n\tpath('', views.homepage, name='homepage'),\n\tpath('quiz_start', views.quiz_start, name='quiz_start'),\n\tpath('quiz', views.quiz, name='quiz'),\n\tpath('feedback',views.feedback, name = 'feedback'),\n\tpath('other', views.other, name = 'other'),\n\tpath('serene',views.serene, name = 'serene'),\n]", "repo_name": "Mouzier/Mindpal_WebProject", "sub_path": "MindPal/mindreader/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 354, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.urls.path", "line_number": 5, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}]} +{"seq_id": "46191537092", "text": "from setuptools import setup, find_packages\n\ntry:\n with open('requirements.txt') as f:\n requires = f.read().splitlines()\nexcept IOError:\n with open('codeyoloco.egg-info/requires.txt') as f:\n requires = f.read().splitlines()\n \nwith open('VERSION') as f:\n version = f.read().strip()\n\nsetup(\n name = \"codeyoloco\",\n version = version,\n packages = find_packages(),\n package_dir = {'codeyoloco':'codeyoloco'},\n author = 'codeyoloco',\n author_email = 'surajshah525@gmail.com',\n description = 'iCTF and Project Package',\n license = \"PSF\",\n include_package_data = True,\n ) \n", "repo_name": "theskullcrusher/codeyoloco", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 645, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "setuptools.setup", "line_number": 13, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 16, "usage_type": "call"}]} +{"seq_id": "25873324262", "text": "import json\nfrom twisted.internet.defer import inlineCallbacks\nfrom labrad.wrappers import connectAsync\nfrom lib.helpers import sleep\n\nfrom conductor_device.conductor_parameter import ConductorParameter\n\nclass State(ConductorParameter):\n priority = 1\n\n @inlineCallbacks\n def initialize(self):\n self.cxn = yield connectAsync(name=self.name)\n yield self.cxn.power_supply.select_device('quadrant_coils')\n \n @inlineCallbacks\n def update(self):\n parameter_values = yield self.cxn.conductor.get_parameter_values()\n sequence = json.loads(parameter_values)['sequencer']['sequence']\n yield self.cxn.power_supply.state(False)\n if 'evaporate' in sequence:\n yield sleep(6)\n yield self.cxn.power_supply.state(self._value)\n", "repo_name": "yesrgang/labrad_tools", "sub_path": "conductor/devices/quadrant_coils/seperate_settings/state.py", "file_name": "state.py", "file_ext": "py", "file_size_in_byte": 791, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "26", "api": [{"api_name": "conductor_device.conductor_parameter.ConductorParameter", "line_number": 8, "usage_type": "name"}, {"api_name": "labrad.wrappers.connectAsync", "line_number": 13, "usage_type": "call"}, {"api_name": "twisted.internet.defer.inlineCallbacks", "line_number": 11, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 19, "usage_type": "call"}, {"api_name": "lib.helpers.sleep", "line_number": 22, "usage_type": "call"}, {"api_name": "twisted.internet.defer.inlineCallbacks", "line_number": 16, "usage_type": "name"}]} +{"seq_id": "2286078012", "text": "import torch\nfrom torch import nn\n\n\nclass Lenet(nn.Module):\n def __init__(self, num_classes=10, grayscale=False):\n super(Lenet, self).__init__()\n\n self.grayscale = grayscale\n self.num_classes = num_classes\n\n if self.grayscale:\n in_channels = 1\n else:\n in_channels = 3\n\n self.features = nn.Sequential(\n nn.Conv2d(in_channels, 20, kernel_size=5, stride=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2),\n nn.Conv2d(20, 20, kernel_size=5, stride=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2),\n )\n\n self.classifier = nn.Sequential(\n nn.Linear(20 * 4 * 4, 120),\n nn.ReLU(inplace=True),\n nn.Linear(120, 84),\n # nn.Sigmoid(),\n nn.Linear(84, num_classes)\n )\n\n def forward(self, x):\n x = self.features(x)\n # print(x.shape)\n x = torch.flatten(x, 1)\n # print(x.shape)\n logits = self.classifier(x)\n # probas = F.softmax(logits, dim=1)\n\n return logits", "repo_name": "silidada/Lenet", "sub_path": "python/model/Lenet.py", "file_name": "Lenet.py", "file_ext": "py", "file_size_in_byte": 1117, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "torch.nn.Module", "line_number": 5, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 5, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 17, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 18, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 18, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 26, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 27, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 29, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 31, "usage_type": "name"}, {"api_name": "torch.flatten", "line_number": 37, "usage_type": "call"}]} +{"seq_id": "17350435876", "text": "import gym\nimport roomba_env\n\nimport time\n\nimport random, numpy, math\n\nfrom keras.models import Sequential\nfrom keras.layers import *\nfrom keras.optimizers import *\n\nclass Model:\n def __init__(self, stateCnt, actionCnt):\n\n self.stateCnt = stateCnt\n self.actionCnt = actionCnt\n\n self.model = self._createModel()\n # self.model.load_weights(\"cartpole-basic.h5\")\n\n def _createModel(self):\n self.model = Sequential()\n self.model.add(Dense(24, input_shape=(5,), activation=\"relu\"))\n self.model.add(Dense(24, activation=\"relu\"))\n self.model.add(Dense(5, activation=\"softmax\"))\n self.model.compile(loss=\"mse\", optimizer=Adam(lr=0.00025))\n\n return self.model\n\n def train(self, x, y, epoch=1, verbose=0):\n self.model.fit(x, y, batch_size=64, nb_epoch=epoch, verbose=verbose)\n\n def predict(self, s):\n return self.model.predict(s)\n\n def predictOne(self, s):\n return self.predict(s.reshape(1, self.stateCnt)).flatten()\n\n\n\nclass Memory: # stored as ( s, a, r, s_ )\n samples = []\n\n def __init__(self, capacity):\n self.capacity = capacity\n\n def add(self, sample):\n self.samples.append(sample)\n\n if len(self.samples) > self.capacity:\n self.samples.pop(0)\n\n def sample(self, n):\n n = min(n, len(self.samples))\n return random.sample(self.samples, n)\n\n\nMEMORY_CAPACITY = 100000\nBATCH_SIZE = 64\n\nGAMMA = 0.99\n\n#exploration rate\nMAX_EPSILON = 1\nMIN_EPSILON = 0.01\n\nLAMBDA = 0.001 # speed of decay\n\n\nclass Agent:\n steps = 0\n epsilon = MAX_EPSILON\n\n def __init__(self, stateCnt, actionCnt):\n self.stateCnt = stateCnt\n self.actionCnt = actionCnt\n\n self.brain = Model(stateCnt, actionCnt)\n self.memory = Memory(MEMORY_CAPACITY)\n\n def act(self, s):\n if random.random() < self.epsilon:\n return random.randint(0, self.actionCnt - 1)\n else:\n return numpy.argmax(self.brain.predictOne(s))\n\n def observe(self, sample): # in (s, a, r, s_) format\n self.memory.add(sample)\n\n # slowly decrease Epsilon based on our experience\n self.steps += 1\n self.epsilon = MIN_EPSILON + (MAX_EPSILON - MIN_EPSILON) * math.exp(-LAMBDA * self.steps)\n\n def replay(self):\n batch = self.memory.sample(BATCH_SIZE)\n print(batch)\n batchLen = len(batch)\n\n no_state = numpy.zeros(self.stateCnt)\n\n states = numpy.array([o for o in batch])\n print(states)\n states_ = numpy.array([no_state if o is None else o for o in batch])\n print(states_)\n p = self.brain.predict(states)\n p_ = self.brain.predict(states_)\n\n x = numpy.zeros((batchLen, self.stateCnt))\n y = numpy.zeros((batchLen, self.actionCnt))\n\n for i in range(batchLen):\n o = batch[i]\n print(i)\n s = o[0]\n a = o[1]\n r = o[2]\n s_ = o[3]\n\n t = p[i]\n print(t)\n if s_ is None:\n t[a] = r\n else:\n t[a] = r + GAMMA * numpy.amax(p_[i])\n\n x[i] = s\n y[i] = t\n\n self.brain.train(x, y)\n\n\n\n\n\nenv = gym.make('roomba-v0')\n\nACTIONS = [\"F\", \"B\", \"L\", \"R\", \"S\"]\n\nenemy = \"enemy\"\nreward_enemy = 0.0\n\nfriendly = \"friendly\"\nreward_friendly = 0.0\n\nstate_enemy, state_friendly = env.reset()\n\n\nagent_enemy = Agent(5,5)\nagent_friendly = Agent(5,5)\n\nfor i in range(1,100000000000001):\n\n done = False\n\n step = 0\n\n initial_input_enemy = []\n\n initial_input_enemy.append(state_enemy[0])\n initial_input_enemy.append(state_enemy[1])\n initial_input_enemy.append(state_friendly[0])\n initial_input_enemy.append(state_friendly[1])\n initial_input_enemy.append(reward_enemy)\n input_array_enemy = np.asarray(initial_input_enemy)\n\n initial_input_friendly = []\n\n initial_input_friendly.append(state_enemy[0])\n initial_input_friendly.append(state_enemy[1])\n initial_input_friendly.append(state_friendly[0])\n initial_input_friendly.append(state_friendly[1])\n initial_input_friendly.append(reward_friendly)\n input_array_friendly = np.asarray(initial_input_friendly)\n\n while done == False:\n\n if(step %2 ==0):\n\n\n\n action = agent_enemy.act(input_array_enemy)\n\n action_code = ACTIONS[action]\n\n state_next_enemy, state_friendly, reward_enemy, reward_friendly, done, info_enemy, info_friendly = env.step(action_code, enemy)\n\n env.render()\n\n #klopt dit?!\n agent_enemy.observe([state_next_enemy[0],state_next_enemy[1], state_friendly[0], state_friendly[1], reward_enemy])\n agent_enemy.replay()\n\n input_next_enemy = []\n input_next_enemy.append(state_next_enemy[0])\n input_next_enemy.append(state_next_enemy[1])\n input_next_enemy.append(state_friendly[0])\n input_next_enemy.append(state_friendly[1])\n input_next_enemy.append(reward_enemy)\n\n input_array_next_enemy = np.asarray(input_next_enemy)\n print(input_array_next_enemy)\n\n\n input_array_enemy = input_array_next_enemy\n\n\n\n # print(\"Game: \" + str(i) + \", exploration: \" + str(dqn_solver_enemy.exploration_rate) + \", score: \" + str(\"nog niet geimplementeerd\"))\n\n\n else:\n action = agent_enemy.act(input_array_friendly)\n\n action_code = ACTIONS[action]\n\n state, state_next_friendly, reward_enemy, reward_friendly, done, info_enemy, info_friendly = env.step(\n action_code, friendly)\n\n env.render()\n\n agent_enemy.observe((input_array_friendly[0], action, reward_friendly, state_next_friendly))\n agent_enemy.replay()\n\n input_next_friendly = []\n input_next_friendly.append(state_next_friendly[0])\n input_next_friendly.append(state_next_friendly[1])\n input_next_friendly.append(state_enemy[0])\n input_next_friendly.append(state_enemy[1])\n input_next_friendly.append(reward_friendly)\n\n input_array_next_friendly = np.asarray(input_next_friendly)\n\n input_array_friendly = input_array_next_friendly\n\n\n\n\n\n time.sleep(0.1)\n step +=1\n print(step)\n\n env.reset()\n env.render()\n time.sleep(3)\n\n\n\n\n", "repo_name": "VanbecelaereVincent/Q_Learning_roomba-env", "sub_path": "Q-learning/test_files/DQN2.py", "file_name": "DQN2.py", "file_ext": "py", "file_size_in_byte": 6358, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "keras.models.Sequential", "line_number": 22, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 55, "usage_type": "call"}, {"api_name": "random.random", "line_number": 82, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 85, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.amax", "line_number": 124, "usage_type": "call"}, {"api_name": "gym.make", "line_number": 135, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 239, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 245, "usage_type": "call"}]} +{"seq_id": "27716224445", "text": "\"\"\"\nWalk Agent MIB (SNMPv1)\n+++++++++++++++++++++++\n\nPerform SNMP GETNEXT operation with the following options:\n\n* with SNMPv1, community 'public'\n* over IPv4/UDP\n* to an Agent at demo.snmplabs.com:161\n* for OID in tuple form\n\nThis script performs similar to the following Net-SNMP command:\n\n| $ snmpwalk -v1 -c public -ObentU demo.snmplabs.com 1.3.6\n\n\"\"\"#\nfrom pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher\nfrom pysnmp.carrier.asyncore.dgram import udp\nfrom pyasn1.codec.ber import encoder, decoder\nfrom pysnmp.proto import api\nfrom time import time\n\n# Protocol version to use\npMod = api.PROTOCOL_MODULES[api.SNMP_VERSION_1]\n# pMod = api.protoModules[api.protoVersion2c]\n\n# SNMP table header\nheadVars = [pMod.ObjectIdentifier((1, 3, 6))]\n\n# Build PDU\nreqPDU = pMod.GetNextRequestPDU()\npMod.apiPDU.setDefaults(reqPDU)\npMod.apiPDU.setVarBinds(reqPDU, [(x, pMod.null) for x in headVars])\n\n# Build message\nreqMsg = pMod.Message()\npMod.apiMessage.setDefaults(reqMsg)\npMod.apiMessage.setCommunity(reqMsg, 'public')\npMod.apiMessage.setPDU(reqMsg, reqPDU)\n\nstartedAt = time()\n\n\ndef cbTimerFun(timeNow):\n if timeNow - startedAt > 3:\n raise Exception(\"Request timed out\")\n\n\n# noinspection PyUnusedLocal\ndef cbRecvFun(transportDispatcher, transportDomain, transportAddress,\n wholeMsg, reqPDU=reqPDU, headVars=headVars):\n\n while wholeMsg:\n rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message())\n rspPDU = pMod.apiMessage.getPDU(rspMsg)\n\n # Match response to request\n if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU):\n\n # Check for SNMP errors reported\n errorStatus = pMod.apiPDU.getErrorStatus(rspPDU)\n if errorStatus and errorStatus != 2:\n raise Exception(errorStatus)\n\n # Format var-binds table\n varBindTable = pMod.apiPDU.getVarBindTable(reqPDU, rspPDU)\n\n # Report SNMP table\n for tableRow in varBindTable:\n for name, val in tableRow:\n print('from: %s, %s = %s' % (transportAddress,\n name.prettyPrint(),\n val.prettyPrint()))\n\n # Stop on EOM\n for oid, val in varBindTable[-1]:\n if not isinstance(val, pMod.Null):\n break\n\n else:\n transportDispatcher.jobFinished(1)\n continue\n\n # Generate request for next row\n pMod.apiPDU.setVarBinds(\n reqPDU, [(x, pMod.null) for x, y in varBindTable[-1]]\n )\n\n pMod.apiPDU.setRequestID(reqPDU, pMod.getNextRequestID())\n\n transportDispatcher.sendMessage(\n encoder.encode(reqMsg), transportDomain, transportAddress\n )\n\n global startedAt\n\n if time() - startedAt > 3:\n raise Exception('Request timed out')\n\n startedAt = time()\n\n return wholeMsg\n\n\ntransportDispatcher = AsyncoreDispatcher()\n\ntransportDispatcher.registerRecvCbFun(cbRecvFun)\ntransportDispatcher.registerTimerCbFun(cbTimerFun)\n\ntransportDispatcher.registerTransport(\n udp.DOMAIN_NAME, udp.UdpSocketTransport().openClientMode()\n)\n\ntransportDispatcher.sendMessage(\n encoder.encode(reqMsg), udp.DOMAIN_NAME, ('demo.snmplabs.com', 161)\n)\n\ntransportDispatcher.jobStarted(1)\n\ntransportDispatcher.runDispatcher()\n\ntransportDispatcher.closeDispatcher()\n", "repo_name": "etingof/pysnmp", "sub_path": "examples/v1arch/asyncore/manager/cmdgen/getnext-pull-whole-mib.py", "file_name": "getnext-pull-whole-mib.py", "file_ext": "py", "file_size_in_byte": 3505, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 544, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pysnmp.proto.api.PROTOCOL_MODULES", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pysnmp.proto.api", "line_number": 24, "usage_type": "name"}, {"api_name": "pysnmp.proto.api.SNMP_VERSION_1", "line_number": 24, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 41, "usage_type": "call"}, {"api_name": "pyasn1.codec.ber.decoder.decode", "line_number": 54, "usage_type": "call"}, {"api_name": "pyasn1.codec.ber.decoder", "line_number": 54, "usage_type": "name"}, {"api_name": "pyasn1.codec.ber.encoder.encode", "line_number": 92, "usage_type": "call"}, {"api_name": "pyasn1.codec.ber.encoder", "line_number": 92, "usage_type": "name"}, {"api_name": "time.time", "line_number": 97, "usage_type": "call"}, {"api_name": "time.time", "line_number": 100, "usage_type": "call"}, {"api_name": "pysnmp.carrier.asyncore.dispatch.AsyncoreDispatcher", "line_number": 105, "usage_type": "call"}, {"api_name": "pysnmp.carrier.asyncore.dgram.udp.DOMAIN_NAME", "line_number": 111, "usage_type": "attribute"}, {"api_name": "pysnmp.carrier.asyncore.dgram.udp", "line_number": 111, "usage_type": "name"}, {"api_name": "pysnmp.carrier.asyncore.dgram.udp.UdpSocketTransport", "line_number": 111, "usage_type": "call"}, {"api_name": "pyasn1.codec.ber.encoder.encode", "line_number": 115, "usage_type": "call"}, {"api_name": "pyasn1.codec.ber.encoder", "line_number": 115, "usage_type": "name"}, {"api_name": "pysnmp.carrier.asyncore.dgram.udp.DOMAIN_NAME", "line_number": 115, "usage_type": "attribute"}, {"api_name": "pysnmp.carrier.asyncore.dgram.udp", "line_number": 115, "usage_type": "name"}]} +{"seq_id": "71171030782", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef get_points(ds, show_images_count: int):\n r_up = np.array([])\n r_down = np.array([])\n c = np.array([])\n i = 0\n for d_s in ['train', 'val', 'test']:\n for image, target in ds[d_s]:\n my_mask = image[0].detach()\n my_mask[my_mask < 1e-18] = 0\n my_mask[my_mask > 1e-18] = 1\n np_im = my_mask.numpy()\n rows = np.argwhere(np.sum(np_im, axis=1) > 10)\n cols = np.argwhere(np.sum(np_im, axis=0) > 10)\n col1 = np.argmax(cols)\n row1 = rows[0]\n row2 = rows[-1]\n if col1 < 2700:\n r_up = np.append(r_up, row1)\n r_down = np.append(r_down, row2)\n c = np.append(c, col1)\n if i < show_images_count:\n if col1 >= 2700:\n # new_image = np_im[row1[0]-50:row2[0]+50, 0:col1+50]\n print(target['file'])\n new_image = np_im[:, 0:2590]\n print(col1)\n plt.imshow(new_image)\n plt.show()\n # plt.imshow(image[0])\n # plt.title(str(i))\n # plt.show()\n i += 1\n print(np.min(r_up), np.max(r_down), np.max(c))\n return np.min(r_up), np.max(r_down), np.max(c)\n", "repo_name": "xkuubix/Breast-Cancer-Classification-with-MIL-models", "sub_path": "get_points_to_crop.py", "file_name": "get_points_to_crop.py", "file_ext": "py", "file_size_in_byte": 1370, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "numpy.array", "line_number": 6, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 7, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.argwhere", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.argwhere", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "numpy.min", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 38, "usage_type": "call"}]} +{"seq_id": "71873973821", "text": "import time\nfrom multiprocessing import cpu_count\nfrom typing import Union, NamedTuple\n# from torchsummary import summary\n\nimport torch\nimport torch.backends.cudnn # Backend for using NVIDIA CUDA\nimport numpy as np\nimport pickle\n\nfrom torch import nn, optim\nfrom torch.nn import functional as F\nfrom torch.optim .optimizer import Optimizer\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch.utils.data import DataLoader\nfrom torch.utils import data\nfrom random import randint\n\nimport argparse\nfrom pathlib import Path\n\n# Enable benchmark mode on CUDNN since the input sizes do not vary. This finds the best algorithm to implement the convolutions given the layout.\ntorch.backends.cudnn.benchmark = True\n\n# Add argument parser\nparser = argparse.ArgumentParser(\n description=\"Training a 4-conv-layer CNN on UrbanSound8K\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n)\n\n# Add arguments to parse\nparser.add_argument(\n \"--log-dir\",\n default=Path(\"logs\"),\n type=Path\n )\nparser.add_argument(\n \"--learning-rate\",\n default=1e-3,\n type=float,\n help=\"Learning rate\"\n )\nparser.add_argument(\n \"--batch-size\",\n default=32,\n type=int,\n help=\"Number of images within each mini-batch\",\n)\nparser.add_argument(\n \"--epochs\",\n default=50,\n type=int,\n help=\"Number of epochs (passes through the entire dataset) to train for\",\n)\nparser.add_argument(\n \"--val-frequency\",\n default=5,\n type=int,\n help=\"How frequently to test the model on the validation set in number of epochs\",\n)\nparser.add_argument(\n \"--log-frequency\",\n default=10,\n type=int,\n help=\"How frequently to save logs to tensorboard in number of steps\",\n)\nparser.add_argument(\n \"--print-frequency\",\n default=300,\n type=int,\n help=\"How frequently to print progress to the command line in number of steps\",\n)\nparser.add_argument(\n \"-j\",\n \"--worker-count\",\n default=cpu_count(),\n type=int,\n help=\"Number of worker processes used to load data.\",\n)\nparser.add_argument(\n \"--momentum\",\n default=0.9,\n type=float,\n)\nparser.add_argument(\n \"--dropout\",\n default=0.5,\n type=float,\n)\nparser.add_argument(\n \"--mode\",\n default=\"LMC\",\n type=str,\n help=\"The type of data to train the network on (LMC, MC, MLMC)\"\n)\nparser.add_argument(\n \"--optimiser\",\n default=\"SGD\",\n type=str,\n help=\"The optimiser used (SGD, Adam, AdamW)\"\n)\nparser.add_argument(\n \"--weight-decay\",\n default=0.01,\n type=float,\n help=\"The L2 regularisation decay parameter\"\n)\nparser.add_argument(\n \"--TSCNN\",\n action = 'store_true',\n help=\"Parameter for dealing with TSCNN combining of logits\"\n)\nparser.add_argument(\n \"--improvements\",\n action = 'store_true',\n help=\"Parameter for adding improvements to the architecture CNN\"\n)\n\nclass DataShape(NamedTuple):\n height: int\n width: int\n channels: int\n\n# Use GPU if cuda is available\nif torch.cuda.is_available():\n DEVICE = torch.device(\"cuda\")\n print (\"Using CUDA...\")\nelse:\n DEVICE = torch.device(\"cpu\")\n print (\"Using CPU...\")\n\n\n# Main function loop for training and testing the data\ndef main(args):\n\n # Load and prepare the data\n istrain = True\n train_dataset = UrbanSound8KDataset(\"./UrbanSound8K_train.pkl\", istrain, args.mode, args.improvements)\n test_dataset = UrbanSound8KDataset(\"./UrbanSound8K_test.pkl\", not istrain, args.mode, args.improvements)\n train_loader = torch.utils.data.DataLoader(\n train_dataset,\n shuffle=True,\n batch_size=args.batch_size,\n pin_memory=True,\n num_workers=args.worker_count,\n )\n test_loader = torch.utils.data.DataLoader(\n test_dataset,\n shuffle=False,\n batch_size=args.batch_size,\n num_workers=args.worker_count,\n pin_memory=True,\n )\n\n # Get the dimensions of the data\n data_channels = train_dataset.__getitem__(0)[0].shape[0]\n data_height = train_dataset.__getitem__(0)[0].shape[1]\n data_width = train_dataset.__getitem__(0)[0].shape[2]\n\n # Define the CNN model\n model = CNN(height=data_height, width=data_width, channels=data_channels, class_count=10, dropout=args.dropout, mode=args.mode, improvements=args.improvements)\n\n # Running Torch Summary to check the architecture\n # summary(model, (data_channels,data_height,data_width))\n\n # Define the unbalanced class weight of the data and move it to the appropriate device (hardcoded from analysis of the dataset)\n data_weight = torch.Tensor(6299/(np.array([6295,1825,6248,5121,5682,6282,1112,5886,5819,6299]))).to(DEVICE)\n\n # Define the criterion to be softmax cross entropy\n criterion = nn.CrossEntropyLoss(weight=data_weight)\n\n # Define the optimizer based on parsed arguments\n if args.optimiser == \"Adam\":\n optimizer = optim.Adam(model.parameters(), lr = args.learning_rate, betas = (args.momentum, 0.999), weight_decay=args.weight_decay)\n elif args.optimiser == \"AdamW\":\n optimizer = optim.AdamW(model.parameters(), lr = args.learning_rate, betas = (args.momentum, 0.999), weight_decay=args.weight_decay)\n elif args.optimiser == \"SGD\":\n optimizer = optim.SGD(model.parameters(), lr = args.learning_rate, momentum = args.momentum, weight_decay=args.weight_decay)\n else:\n print(\"Error: Invalid optimiser argument, defaulting to SGD...\")\n optimizer = optim.SGD(model.parameters(), lr = args.learning_rate, momentum = args.momentum, weight_decay=args.weight_decay)\n\n # Setup directory for the logs\n log_dir = get_summary_writer_log_dir(args)\n print(f\"Writing logs to {log_dir}\")\n\n # Define the summary writer for logging\n summary_writer = SummaryWriter(\n str(log_dir),\n flush_secs=5\n )\n\n # Prep notes file for reference\n f = open(\"logs/notes-sbatch.md\", \"a\")\n f.write(\"Logged to: \" + log_dir + (\" - TSCNN\" if args.TSCNN else f\" - storing {args.mode}\") + \"\\n\")\n f.close()\n\n # Define the model trainer\n trainer = Trainer(\n model, train_loader, test_loader, criterion, optimizer, summary_writer, DEVICE, log_dir, args.TSCNN, args.mode\n )\n\n # Use the trainer to train the model\n trainer.train(\n args.epochs,\n args.val_frequency,\n print_frequency=args.print_frequency,\n log_frequency=args.log_frequency,\n )\n\n # Close the summary writer at the end of the training\n summary_writer.close()\n\n# The Dataset class\nclass UrbanSound8KDataset(data.Dataset):\n def __init__(self, dataset_path, istrain, mode, improvements):\n\n # Load the dataset\n self.dataset = pickle.load(open(dataset_path, 'rb'))\n self.mode = mode\n self.improvements = improvements\n self.istrain = istrain\n\n def __getitem__(self, index):\n\n # Extract the necessary features from the loaded dataset\n LM = self.dataset[index][\"features\"][\"logmelspec\"]\n MFCC = self.dataset[index][\"features\"][\"mfcc\"]\n C = self.dataset[index][\"features\"][\"chroma\"]\n SC = self.dataset[index][\"features\"][\"spectral_contrast\"]\n T = self.dataset[index][\"features\"][\"tonnetz\"]\n\n # Appropriately prepare the data given the selected mode, based on the specifications of the paper\n if self.mode == 'LMC':\n LMC = np.concatenate((LM, C, SC, T), axis=0)\n if self.improvements and self.istrain:\n LMC = LMC*randint(1,4) # Random augmentation of the training data\n feature = torch.from_numpy(LMC.astype(np.float32)).unsqueeze(0)\n elif self.mode == 'MC':\n MC = np.concatenate((MFCC, C, SC, T), axis=0)\n if self.improvements and self.istrain:\n MC = MC*randint(1,4) # Random augmentation of the training data\n feature = torch.from_numpy(MC.astype(np.float32)).unsqueeze(0)\n elif self.mode == 'MLMC':\n MLMC = np.concatenate((MFCC, LM, C, SC, T), axis=0)\n if self.improvements and self.istrain:\n MLMC = MLMC*randint(1,4) # Random augmentation of the training data\n feature = torch.from_numpy(MLMC.astype(np.float32)).unsqueeze(0)\n label = self.dataset[index]['classID']\n fname = self.dataset[index]['filename']\n\n return feature, label, fname, index\n\n def __len__(self):\n return len(self.dataset)\n\n# The architecture class\nclass CNN(nn.Module):\n def __init__(self, height: int, width: int, channels: int, class_count: int, dropout: float, mode: str, improvements: bool):\n super().__init__()\n\n # Define some global class variables\n self.input_shape = DataShape(height=height, width=width, channels=channels)\n self.class_count = class_count\n self.mode = mode\n self.improvements = improvements\n\n # Defining the first convolutional layer & initialising its weights using Kaiming\n self.conv1 = nn.Conv2d(\n in_channels=self.input_shape.channels,\n out_channels=32,\n bias=False,\n kernel_size=(3,3),\n padding=(1,1),\n # padding=(43,21),\n # stride=(2,2)\n )\n self.initialise_layer(self.conv1)\n\n # Defining batch normalisation of the outputs of the first conv layer\n self.bnorm1 = nn.BatchNorm2d(\n num_features=32\n )\n\n # Defining the second convolutional layer & initialising its weights using Kaiming\n self.conv2 = nn.Conv2d(\n in_channels = 32,\n out_channels = 32,\n kernel_size = (3, 3),\n bias=False,\n padding=(1,1),\n # padding = (43, 21),\n # stride=(2,2)\n )\n self.initialise_layer(self.conv2)\n\n # Defining batch normalisation of the outputs of the second conv layer\n self.bnorm2 = nn.BatchNorm2d(\n num_features = 32\n )\n\n # Defining the pooling layer for the batch normalised 2nd conv output\n self.pool2 = nn.MaxPool2d(\n kernel_size=(2, 2),\n padding=(1,1),\n stride=(2, 2)\n )\n\n # Defining the third convolutional layer & initialising its weights using Kaiming\n self.conv3 = nn.Conv2d(\n in_channels=32,\n out_channels=64,\n kernel_size=(3,3),\n bias=False,\n padding=(1,1),\n # padding = (22,11),\n # stride=(2,2)\n )\n self.initialise_layer(self.conv3)\n\n # Defining batch normalisation of the outputs of the third conv layer\n self.bnorm3 = nn.BatchNorm2d(\n num_features=64\n )\n\n # Defining the fourth convolutional layer & initialising its weights using Kaiming\n # Could use Max Pooling for the last layer, but probably more likely to be stride (based on the paper)\n self.conv4 = nn.Conv2d(\n in_channels=64,\n out_channels=64,\n kernel_size=(3,3),\n padding=(1,1),\n stride=(2,2),\n bias=False,\n )\n self.initialise_layer(self.conv4)\n\n # Adding a pooling layer with stride instead of conv4 with stride\n # self.pool4 = nn.MaxPool2d(\n # kernel_size=(2, 2),\n # padding=(1,1),\n # stride=(2, 2)\n # )\n\n # Defining batch normalisation of the outputs of the fourth conv layer\n self.bnorm4 = nn.BatchNorm2d(\n num_features=64\n )\n\n # Defining the first fully connected layer & initialising the weights using Kaiming\n # The size of the data for MLMC is larger and requires a larger fully connected layer\n if self.mode == \"MLMC\":\n self.fc1 = nn.Linear(26048, 1024)\n else:\n self.fc1 = nn.Linear(15488, 1024)\n self.initialise_layer(self.fc1)\n\n # Defining batch normalisation of the outputs of the first fully connected layer\n self.bnormfc1 = nn.BatchNorm1d(\n num_features = 1024\n )\n\n # Defining the final fully connected layer to 10 classes & initialising the weights using Kaiming\n self.fc2 = nn.Linear (1024, 10)\n self.initialise_layer(self.fc2)\n\n # Defining the dropout used in the CNN\n self.dropout = nn.Dropout2d(p=dropout)\n\n def forward(self, input_data: torch.Tensor) -> torch.Tensor:\n\n # Implementing the first conv hidden layer\n x = self.conv1(input_data)\n x = self.bnorm1(x)\n x = F.relu(x)\n\n # Implementing the second conv hidden layer\n x = self.conv2(self.dropout(x))\n x = self.bnorm2(x)\n x = F.relu(x)\n\n # Implementing a pooling stage to the outputs of the first layer\n x = self.pool2(x)\n\n # Implementing the third conv hidden layer\n # if self.improvements:\n # x = self.dropout(x)\n x = self.conv3(x)\n x = self.bnorm3(x)\n x = F.relu(x)\n\n # Implementing the fourth conv hidden layer\n x = self.conv4(self.dropout(x))\n x = self.bnorm4(x)\n x = F.relu(x)\n\n # Use pooling with stride instead of conv4 with stride\n # x = self.pool4(x)\n\n # Flattening the output of the fourth conv layer for the first fc layer\n x = torch.flatten(x, start_dim = 1)\n\n # Implementing the first fully connected hidden layer\n x = self.fc1(self.dropout(x))\n # x = self.bnormfc1(x) # This was not in the paper\n x = torch.sigmoid(x)\n\n # Implementing the final fully connected hidden layer\n x = self.fc2(x)\n return x\n\n @staticmethod\n def initialise_layer(layer):\n if hasattr(layer, \"bias\"):\n if layer.bias is not None:\n nn.init.zeros_(layer.bias)\n if hasattr(layer, \"weight\"):\n nn.init.kaiming_normal_(layer.weight)\n\n# Class for the execution of the main training loop\nclass Trainer:\n def __init__(\n self,\n model: nn.Module,\n train_loader: DataLoader,\n val_loader: DataLoader,\n criterion: nn.Module,\n optimizer: Optimizer,\n summary_writer: SummaryWriter,\n device: torch.device,\n log_dir: str,\n TSCNN: bool,\n mode: str,\n ):\n self.model = model.to(device)\n self.device = device\n self.train_loader = train_loader\n self.val_loader = val_loader\n self.criterion = criterion\n self.optimizer = optimizer\n self.summary_writer = summary_writer\n self.step = 0\n self.log_dir = log_dir\n self.TSCNN = TSCNN\n self.mode = mode\n\n def train(\n self,\n epochs: int,\n val_frequency: int,\n print_frequency: int = 20,\n log_frequency: int = 5,\n start_epoch: int = 0,\n ):\n # Setting model to training mode\n self.model.train()\n\n # Defining list of results for each epoch\n results_epoch = {}\n\n # Main training loop\n for epoch in range(start_epoch, epochs):\n self.model.train()\n\n # Extracting required data from loader\n data_load_start_time = time.time()\n for batch, labels, fname, index in self.train_loader:\n batch = batch.to(self.device)\n labels = labels.to(self.device)\n data_load_end_time = time.time()\n\n # Compute the forward pass of the model\n logits = self.model.forward(batch)\n\n # Calculate the loss of the forward pass\n loss = self.criterion(logits, labels)\n\n # Implement backpropogation\n loss.backward()\n\n # Update the optimiser parameters and set the update grads to zero again\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n # Disabling autograd when calculationg the accuracy\n with torch.no_grad():\n preds = logits.argmax(-1)\n accuracy = compute_accuracy(labels, preds)\n\n # Writing to logs and printing out the progress\n data_load_time = data_load_end_time - data_load_start_time\n step_time = time.time() - data_load_end_time\n if ((self.step + 1) % log_frequency) == 0:\n self.log_metrics(epoch, accuracy, loss, data_load_time, step_time)\n if ((self.step + 1) % print_frequency) == 0:\n self.print_metrics(epoch, accuracy, loss, data_load_time, step_time)\n\n # Update loop params for next batch\n self.step += 1\n data_load_start_time = time.time()\n\n # Write to summary writer at the end of each epoch\n self.summary_writer.add_scalar(\"epoch\", epoch, self.step)\n if ((epoch + 1) % val_frequency) == 0:\n results_epoch[epoch] = self.validate(epoch, epochs, self.log_dir)\n\n # Exporting data\n if not self.TSCNN:\n pickle.dump(results_epoch, open(\"TSCNN_store_\" + self.mode + \".pkl\", \"wb\"))\n else:\n pickle.dump(results_epoch, open(\"TSCNN_store_\" + \"TSCNN\" + \".pkl\", \"wb\"))\n\n # Function used to print the progress\n def print_metrics(self, epoch, accuracy, loss, data_load_time, step_time):\n epoch_step = self.step % len(self.train_loader)\n print(\n f\"epoch: [{epoch}], \"\n f\"step: [{epoch_step}/{len(self.train_loader)}], \"\n f\"batch loss: {loss:.5f}, \"\n f\"batch accuracy: {accuracy * 100:2.2f}, \"\n f\"data load time: \"\n f\"{data_load_time:.5f}, \"\n f\"step time: {step_time:.5f},\"\n\n )\n\n # Function used to log the progress\n def log_metrics(self, epoch, accuracy, loss, data_load_time, step_time):\n self.summary_writer.add_scalar(\"epoch\", epoch, self.step)\n self.summary_writer.add_scalars(\n \"accuracy\",\n {\"train\": accuracy},\n self.step\n )\n self.summary_writer.add_scalars(\n \"loss\",\n {\"train\": float(loss.item())},\n self.step\n )\n self.summary_writer.add_scalar(\n \"time/data\", data_load_time, self.step\n )\n self.summary_writer.add_scalar(\n \"time/data\", step_time, self.step\n )\n\n # Function used to validate the model\n def validate(self, epoch, epochs, log_dir):\n results = {\"preds\": [], \"labels\": [], \"logits\": [], \"indices\": []}\n total_loss = 0\n\n # Loading data from previous runs and defining softmax to combine for TSCNN\n if self.TSCNN:\n results_epoch_LMC = pickle.load(open(\"TSCNN_store_LMC.pkl\", \"rb\"))\n results_epoch_MC = pickle.load(open(\"TSCNN_store_MC.pkl\", \"rb\"))\n smax = nn.Softmax(dim=-1)\n counter = 0 # used to load the appropriate logits from the stored data\n\n # Put model in validation mode\n self.model.eval()\n\n # No need to track gradients for validation, we're not optimizing.\n with torch.no_grad():\n for batch, labels, fname, index in self.val_loader:\n\n # Shifting batch and labels to appropriate device for efficiency\n batch = batch.to(self.device)\n labels = labels.to(self.device)\n\n # Calculating the logits of the testing batch\n logits = self.model(batch)\n\n # Averaging the logits by fname and making the new labels\n fname_logits, fname_labels, fname_indices = orderbyfname(labels,fname,logits, index)\n fname_logits = fname_logits.to(self.device)\n fname_labels = fname_labels.to(self.device)\n\n # Combining saved LMC and current MC logits for TSCNN, including some sanity checks\n if self.TSCNN:\n combined_logits = []\n if len(fname_logits) != len(fname_labels):\n print(\"ERROR: Incorrect lengths of logit and label arrays, sanity check failed!\") # Sanity check\n for fname_logit, fname_label in zip(fname_logits, fname_labels):\n if fname_label != results_epoch_LMC[epoch][\"labels\"][counter] or fname_label != results_epoch_MC[epoch][\"labels\"][counter]:\n print(\"ERROR: Incorrect label, sanity check failed!\") # Sanity check\n combined_logits.append(np.array(smax(results_epoch_LMC[epoch][\"logits\"][counter]).cpu() + smax(results_epoch_MC[epoch][\"logits\"][counter]).cpu()))\n counter += 1\n\n # Overwriting logits with new combined logits and preparing the tensor\n fname_logits = (torch.Tensor(combined_logits).type(torch.float)).to(self.device)\n\n\n # Calculating loss with new logits and labels\n loss = self.criterion(fname_logits, fname_labels)\n total_loss += loss.item()\n\n # Getting predictions of new logits\n preds = fname_logits.argmax(dim=-1).cpu().numpy()\n\n # Appending results\n results[\"logits\"].extend(list(fname_logits))\n results[\"preds\"].extend(list(preds))\n results[\"labels\"].extend(list(fname_labels.cpu().numpy()))\n results[\"indices\"].extend(list(fname_indices))\n\n # Find the overall accuracy of the model\n accuracy = compute_accuracy(\n np.array(results[\"labels\"]), np.array(results[\"preds\"])\n )\n\n # Find the class accuracy of the model\n class_accuracy = compute_class_accuracy(\n np.array(results[\"labels\"]), np.array(results[\"preds\"])\n )\n\n # Find the average class accuracy\n class_accuracy_avg = sum(class_accuracy)/100*len(class_accuracy)\n\n # Compute the average loss\n average_loss = total_loss / len(self.val_loader)\n\n # Write the progress to the logs\n self.summary_writer.add_scalars(\n \"accuracy\",\n {\"test\": accuracy},\n self.step\n )\n self.summary_writer.add_scalars(\n \"average_class\",\n {\"test\": class_accuracy_avg},\n self.step\n )\n self.summary_writer.add_scalars(\n \"loss\",\n {\"test\": average_loss},\n self.step\n )\n\n # Switch model back to evaluation mode\n self.model.train()\n\n # Print the progress & exporting the softmaxed logits and labels\n display_text = f\"validation loss: {average_loss:.5f}, accuracy: {accuracy * 100:2.2f}, class_accuracy: {class_accuracy}\\nclass_avg: {class_accuracy_avg}\"\n if (epoch+1) == epochs:\n f = open(\"logs/accuracy.md\", \"a\")\n f.write(log_dir + \"\\n\")\n f.write(display_text + \"\\n\\n\")\n f.close()\n print(display_text)\n return results\n\n# Function for averaging the logits and proucing new labels from old\ndef orderbyfname(labels,fname,logits, index):\n fname_set = sorted(set(fname))\n new_logits = []\n new_labels = []\n new_indices = []\n for iter,name in enumerate(fname_set):\n\n # Determining the indices of the batch which are from the same filename\n indices = np.where(np.array(fname)==name)[0]\n sum = np.zeros(10)\n index_store_temp = []\n\n # Using the indices to average the logits\n for i in indices:\n sum += np.array(logits[i].cpu())\n index_store_temp.append(index[i]) # qualitative analysis\n sum = sum/len(indices)\n\n # appending new data\n new_logits.append(sum)\n new_labels.append(labels[indices[0]])\n\n # Storing the actual test data indices for the qualitative analysis\n new_indices.append(index_store_temp)\n\n return torch.Tensor(new_logits).type(torch.float), torch.Tensor(new_labels).type(torch.long), new_indices\n\n# Function for computing the overall accuracy of the model\ndef compute_accuracy(\n labels: Union[torch.Tensor, np.ndarray], preds: Union[torch.Tensor, np.ndarray]\n) -> float:\n \"\"\"\n Args:\n labels: ``(batch_size, class_count)`` tensor or array containing example labels\n preds: ``(batch_size, class_count)`` tensor or array containing model prediction\n \"\"\"\n assert len(labels) == len(preds)\n return float((labels == preds).sum()) / len(labels)\n\n# Function for computing the class accuracy of the model\ndef compute_class_accuracy(labels: Union[torch.Tensor, np.ndarray], preds: Union[torch.Tensor, np.ndarray], class_count: int = 10) -> float:\n assert len(labels) == len(preds)\n class_accuracy = []\n for class_label in range(0,class_count):\n class_labels = np.where(labels == class_label, class_label, class_label)\n class_accuracy.append(float(np.logical_and((preds == class_labels),(labels == class_labels)).sum())*100 / np.array(labels == class_labels).sum())\n return class_accuracy\n\n\n\n# Function for handling the directory for writing logs to\ndef get_summary_writer_log_dir(args: argparse.Namespace) -> str:\n \"\"\"Get a unique directory that hasn't been logged to before for use with a TB\n SummaryWriter.\n\n Args:\n args: CLI Arguments\n\n Returns:\n Subdirectory of log_dir with unique subdirectory name to prevent multiple runs\n from getting logged to the same TB log directory (which you can't easily\n untangle in TB).\n \"\"\"\n tb_log_dir_prefix = (f'CNN_bn_epochs={args.epochs}_dropout={args.dropout}_bs={args.batch_size}_optim={args.optimiser}_decay={args.weight_decay}_lr={args.learning_rate}_momentum={args.momentum}_mode=' + (\"TSCNN\" if args.TSCNN else args.mode) + (\"_improvements_\" if args.improvements else \"\") +'_run_')\n i = 0\n while i < 1000:\n tb_log_dir = args.log_dir / (tb_log_dir_prefix + str(i))\n if not tb_log_dir.exists():\n return str(tb_log_dir)\n i += 1\n return str(tb_log_dir)\n\n# Running the Progamme\nif __name__ == \"__main__\":\n start = time.time()\n main(parser.parse_args())\n print (\"Total time taken: {}\".format(time.time() - start))\n", "repo_name": "fz16336/Applied-Deep-Learning", "sub_path": "code/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 26170, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "24", "api": [{"api_name": "torch.backends", "line_number": 23, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 26, "usage_type": "call"}, {"api_name": "argparse.ArgumentDefaultsHelpFormatter", "line_number": 28, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 34, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 35, "usage_type": "name"}, {"api_name": "multiprocessing.cpu_count", "line_number": 76, "usage_type": "call"}, {"api_name": "typing.NamedTuple", "line_number": 119, "usage_type": "name"}, {"api_name": "torch.cuda.is_available", "line_number": 125, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 125, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 126, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 129, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 140, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 140, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 147, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 167, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 167, "usage_type": "call"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 170, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 170, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 174, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 174, "usage_type": "name"}, {"api_name": "torch.optim.AdamW", "line_number": 176, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 176, "usage_type": "name"}, {"api_name": "torch.optim.SGD", "line_number": 178, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 178, "usage_type": "name"}, {"api_name": "torch.optim.SGD", "line_number": 181, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 181, "usage_type": "name"}, {"api_name": "torch.utils.tensorboard.SummaryWriter", "line_number": 188, "usage_type": "call"}, {"api_name": "torch.utils.data.Dataset", "line_number": 215, "usage_type": "attribute"}, {"api_name": "torch.utils.data", "line_number": 215, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 219, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 235, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 237, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 238, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 238, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 240, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 242, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 243, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 243, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 245, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 247, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 248, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 248, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 258, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 258, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 269, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 269, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 281, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 281, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 286, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 286, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 298, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 298, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 303, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 303, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 310, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 310, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 322, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 322, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 328, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 328, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 346, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 346, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 353, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 353, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 355, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 355, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm1d", "line_number": 359, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 359, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 364, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 364, "usage_type": "name"}, {"api_name": "torch.nn.Dropout2d", "line_number": 368, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 368, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 370, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.relu", "line_number": 375, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 375, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 380, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 380, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 390, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 390, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 395, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 395, "usage_type": "name"}, {"api_name": "torch.flatten", "line_number": 401, "usage_type": "call"}, {"api_name": "torch.sigmoid", "line_number": 406, "usage_type": "call"}, {"api_name": "torch.nn.init.zeros_", "line_number": 416, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 416, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 416, "usage_type": "name"}, {"api_name": "torch.nn.init.kaiming_normal_", "line_number": 418, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 418, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 418, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 424, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 424, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 425, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 426, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 427, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 427, "usage_type": "name"}, {"api_name": "torch.optim.optimizer.Optimizer", "line_number": 428, "usage_type": "name"}, {"api_name": "torch.utils.tensorboard.SummaryWriter", "line_number": 429, "usage_type": "name"}, {"api_name": "torch.device", "line_number": 430, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 466, "usage_type": "call"}, {"api_name": "time.time", "line_number": 470, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 486, "usage_type": "call"}, {"api_name": "time.time", "line_number": 492, "usage_type": "call"}, {"api_name": "time.time", "line_number": 500, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 509, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 511, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 554, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 555, "usage_type": "call"}, {"api_name": "torch.nn.Softmax", "line_number": 556, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 556, "usage_type": "name"}, {"api_name": "torch.no_grad", "line_number": 563, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 586, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 590, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 590, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 608, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 613, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 661, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 661, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 662, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 667, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 678, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 678, "usage_type": "attribute"}, {"api_name": "torch.long", "line_number": 678, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 682, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 682, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 682, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 693, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 693, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 693, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 697, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 698, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 698, "usage_type": "call"}, {"api_name": "argparse.Namespace", "line_number": 704, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 727, "usage_type": "call"}, {"api_name": "time.time", "line_number": 729, "usage_type": "call"}]} +{"seq_id": "73775317181", "text": "__author__ = \"ContraxSuite, LLC; LexPredict, LLC\"\n__copyright__ = \"Copyright 2015-2021, ContraxSuite, LLC\"\n__license__ = \"https://github.com/LexPredict/lexpredict-lexnlp/blob/2.3.0/LICENSE\"\n__version__ = \"2.3.0\"\n__maintainer__ = \"LexPredict, LLC\"\n__email__ = \"support@contraxsuite.com\"\n\n\nimport re\nfrom typing import List, Generator\nfrom lexnlp.extract.common.annotations.definition_annotation import DefinitionAnnotation\nfrom lexnlp.extract.common.definitions.common_definition_patterns import CommonDefinitionPatterns\nfrom lexnlp.extract.common.definitions.universal_definition_parser import UniversalDefinitionsParser\nfrom lexnlp.extract.common.pattern_found import PatternFound\nfrom lexnlp.extract.es.language_tokens import EsLanguageTokens\nfrom lexnlp.utils.lines_processing.line_processor import LineSplitParams\n\n\nclass SpanishParsingMethods:\n \"\"\"\n the class contains methods with the same signature:\n def method_name(phrase: str) -> List[DefinitionMatch]:\n the methods are used for finding definition \"candidates\"\n \"\"\"\n reg_hereafter = re.compile(\"(?<=(en adelante[,\\\\s]))[\\\\w\\\\s*\\\\\\\"*]+\", re.UNICODE)\n reg_reffered = re.compile(\"^.+(?=se refiere)\", re.UNICODE)\n reg_first_word_is = re.compile(r\"^.+?(?=es\\s+\\w+\\W+\\w+|está\\s+\\w+\\W+\\w+)\", re.UNICODE)\n\n @staticmethod\n def match_es_def_by_hereafter(phrase: str) -> List[PatternFound]:\n \"\"\"\n :param phrase: las instrucciones de uso o instalación del software o todas las descripciones\n de uso del mismo (de aquí en adelante, la \"Documentación\");\n :return: {name: 'Documentación', probability: 100, ...}\n \"\"\"\n reg = SpanishParsingMethods.reg_hereafter\n dfs = CommonDefinitionPatterns. \\\n collect_regex_matches_with_quoted_chunks(phrase, reg, 100,\n lambda p, m, e: 0,\n lambda p, m, e: m.start() + e.end(),\n lambda p, m: 0,\n lambda p, m: m.end())\n return dfs\n\n @staticmethod\n def match_es_def_by_reffered(phrase: str) -> List[PatternFound]:\n \"\"\"\n :param phrase: En este acuerdo, el término \"Software\" se refiere a: (i) el programa informático\n que acompaña a este Acuerdo y todos sus componentes;\n :return: definitions (objects)\n \"\"\"\n reg = SpanishParsingMethods.reg_reffered\n dfs = CommonDefinitionPatterns. \\\n collect_regex_matches_with_quoted_chunks(phrase, reg, 100,\n lambda p, m, e: m.start() + e.start(),\n lambda p, m, e: len(phrase),\n lambda p, m: m.start(),\n lambda p, m: len(p))\n return dfs\n\n @staticmethod\n def match_first_word_is(phrase: str) -> List[PatternFound]:\n \"\"\"\n :param phrase: El tabaquismo es la adicción al tabaco, provocada principalmente.\n :return: definitions (objects)\n \"\"\"\n reg = SpanishParsingMethods.reg_first_word_is\n dfs = CommonDefinitionPatterns.\\\n collect_regex_matches_with_quoted_chunks(phrase, reg, 65,\n lambda p, m, e: m.start() + e.start(),\n lambda p, m, e: len(phrase),\n lambda p, m: m.start(),\n lambda p, m: len(p))\n return dfs\n\n\ndef make_es_definitions_parser():\n split_params = LineSplitParams()\n split_params.line_breaks = {'\\n', '.', ';', '!', '?'}\n split_params.abbreviations = EsLanguageTokens.abbreviations\n split_params.abbr_ignore_case = True\n\n functions = [CommonDefinitionPatterns.match_es_def_by_semicolon,\n CommonDefinitionPatterns.match_acronyms,\n SpanishParsingMethods.match_es_def_by_hereafter,\n SpanishParsingMethods.match_es_def_by_reffered,\n SpanishParsingMethods.match_first_word_is]\n\n return UniversalDefinitionsParser(functions, split_params)\n\n\nparser = make_es_definitions_parser()\n\n\ndef get_definition_annotations(text: str, language: str = 'es') -> Generator[DefinitionAnnotation, None, None]:\n yield from parser.parse(text, language)\n\n\ndef get_definition_annotation_list(text: str, language: str = 'es') -> List[DefinitionAnnotation]:\n return list(get_definition_annotations(text, language))\n\n\ndef get_definitions(text: str, language: str = 'es') -> Generator[dict, None, None]:\n for annotation in parser.parse(text, language):\n yield annotation.to_dictionary()\n\n\ndef get_definition_list(text: str, language: str = 'es') -> List[dict]:\n return list(get_definitions(text, language))\n", "repo_name": "LexPredict/lexpredict-lexnlp", "sub_path": "lexnlp/extract/es/definitions.py", "file_name": "definitions.py", "file_ext": "py", "file_size_in_byte": 5005, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 654, "dataset": "github-code", "pt": "24", "api": [{"api_name": "re.compile", "line_number": 25, "usage_type": "call"}, {"api_name": "re.UNICODE", "line_number": 25, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 26, "usage_type": "call"}, {"api_name": "re.UNICODE", "line_number": 26, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 27, "usage_type": "call"}, {"api_name": "re.UNICODE", "line_number": 27, "usage_type": "attribute"}, {"api_name": "lexnlp.extract.common.definitions.common_definition_patterns.CommonDefinitionPatterns.collect_regex_matches_with_quoted_chunks", "line_number": 37, "usage_type": "call"}, {"api_name": "lexnlp.extract.common.definitions.common_definition_patterns.CommonDefinitionPatterns", "line_number": 37, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 30, "usage_type": "name"}, {"api_name": "lexnlp.extract.common.pattern_found.PatternFound", "line_number": 30, "usage_type": "name"}, {"api_name": "lexnlp.extract.common.definitions.common_definition_patterns.CommonDefinitionPatterns.collect_regex_matches_with_quoted_chunks", "line_number": 53, "usage_type": "call"}, {"api_name": "lexnlp.extract.common.definitions.common_definition_patterns.CommonDefinitionPatterns", "line_number": 53, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 46, "usage_type": "name"}, {"api_name": "lexnlp.extract.common.pattern_found.PatternFound", "line_number": 46, "usage_type": "name"}, {"api_name": "lexnlp.extract.common.definitions.common_definition_patterns.CommonDefinitionPatterns.collect_regex_matches_with_quoted_chunks", "line_number": 68, "usage_type": "call"}, {"api_name": "lexnlp.extract.common.definitions.common_definition_patterns.CommonDefinitionPatterns", "line_number": 68, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 62, "usage_type": "name"}, {"api_name": "lexnlp.extract.common.pattern_found.PatternFound", "line_number": 62, "usage_type": "name"}, {"api_name": "lexnlp.utils.lines_processing.line_processor.LineSplitParams", "line_number": 78, "usage_type": "call"}, {"api_name": "lexnlp.extract.es.language_tokens.EsLanguageTokens.abbreviations", "line_number": 80, "usage_type": "attribute"}, {"api_name": "lexnlp.extract.es.language_tokens.EsLanguageTokens", "line_number": 80, "usage_type": "name"}, {"api_name": "lexnlp.extract.common.definitions.common_definition_patterns.CommonDefinitionPatterns.match_es_def_by_semicolon", "line_number": 83, "usage_type": "attribute"}, {"api_name": "lexnlp.extract.common.definitions.common_definition_patterns.CommonDefinitionPatterns", "line_number": 83, "usage_type": "name"}, {"api_name": "lexnlp.extract.common.definitions.common_definition_patterns.CommonDefinitionPatterns.match_acronyms", "line_number": 84, "usage_type": "attribute"}, {"api_name": "lexnlp.extract.common.definitions.common_definition_patterns.CommonDefinitionPatterns", "line_number": 84, "usage_type": "name"}, {"api_name": "lexnlp.extract.common.definitions.universal_definition_parser.UniversalDefinitionsParser", "line_number": 89, "usage_type": "call"}, {"api_name": "typing.Generator", "line_number": 95, "usage_type": "name"}, {"api_name": "lexnlp.extract.common.annotations.definition_annotation.DefinitionAnnotation", "line_number": 95, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 99, "usage_type": "name"}, {"api_name": "lexnlp.extract.common.annotations.definition_annotation.DefinitionAnnotation", "line_number": 99, "usage_type": "name"}, {"api_name": "typing.Generator", "line_number": 103, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 108, "usage_type": "name"}]} +{"seq_id": "31843693097", "text": "# -*- coding: utf-8 -*-\n\"\"\"upperenvelope\n\nProvides a Numba jit compilled upper envelope for a custom utility function.\n\"\"\"\n\nimport numpy as np\nfrom numba import njit\n\ndef create(ufunc,use_inv_w=False):\n \"\"\" create upperenvelope function from the utility function ufunc\n \n Args:\n\n ufunc (callable): utility function with *args (must be decorated with @njit)\n\n Returns:\n\n upperenvelope (callable): upperenvelope called as (grid_a,m_vec,c_vec,inv_w_vec,use_inv_w,grid_m,c_ast_vec,v_ast_vec,*args)\n use_inv_w (bool,optional): assume that the post decision value-of-choice vector is a negative inverse\n \n \"\"\"\n\n @njit\n def upperenvelope(grid_a,m_vec,c_vec,inv_w_vec,grid_m,c_ast_vec,v_ast_vec,*args):\n \"\"\" upperenvelope function\n \n Args:\n\n grid_a (numpy.ndarray): input, end-of-period asset vector of length Na\n m_vec (numpy.ndarray): input, cash-on-hand vector from egm of length Na\n c_vec (numpy.ndarray): input, consumption vector from egm of length Na\n inv_w_vec (numpy.ndarray): input, post decision value-of-choice vector from egm of length Na\n grid_m (numpy.ndarray): input, common grid for cash-on-hand of length Nm\n c_ast_vec (numpy.ndarray): output, consumption on common grid for cash-on-hand of length Nm\n v_ast_vec (numpy.ndarray): output, value-of-choice on common grid for cash-on-hand of length Nm\n *args: additional arguments to the utility function\n \n \"\"\"\n\n # for given m_vec, c_vec and w_vec (coming from grid_a)\n # find the optimal consumption choices (c_ast_vec) at the common grid (grid_m) \n # using the upper envelope + also value the implied values-of-choice (v_ast_vec)\n\n Na = grid_a.size\n Nm = grid_m.size\n\n c_ast_vec[:] = 0\n v_ast_vec[:] = -np.inf\n\n # constraint\n # the constraint is binding if the common m is smaller\n # than the smallest m implied by EGM step (m_vec[0])\n\n im = 0\n while im < Nm and grid_m[im] <= m_vec[0]:\n \n # a. consume all\n c_ast_vec[im] = grid_m[im] \n\n # b. value of choice\n u = ufunc(c_ast_vec[im],*args)\n if use_inv_w:\n v_ast_vec[im] = u + (-1.0/inv_w_vec[0])\n else:\n v_ast_vec[im] = u + inv_w_vec[0]\n\n im += 1\n\n # upper envellope\n # apply the upper envelope algorithm\n \n for ia in range(Na-1):\n\n # a. a inteval and w slope\n a_low = grid_a[ia]\n a_high = grid_a[ia+1]\n \n inv_w_low = inv_w_vec[ia]\n inv_w_high = inv_w_vec[ia+1]\n\n if a_low > a_high:\n continue\n\n inv_w_slope = (inv_w_high-inv_w_low)/(a_high-a_low)\n \n # b. m inteval and c slope\n m_low = m_vec[ia]\n m_high = m_vec[ia+1]\n\n c_low = c_vec[ia]\n c_high = c_vec[ia+1]\n\n c_slope = (c_high-c_low)/(m_high-m_low)\n\n # c. loop through common grid\n for im in range(Nm):\n\n # i. current m\n m = grid_m[im]\n\n # ii. interpolate?\n interp = (m >= m_low) and (m <= m_high) \n extrap_above = ia == Na-2 and m > m_vec[Na-1]\n\n # iii. interpolation (or extrapolation)\n if interp or extrap_above:\n\n # o. implied guess\n c_guess = c_low + c_slope * (m - m_low)\n a_guess = m - c_guess\n\n # oo. implied post-decision value function\n inv_w = inv_w_low + inv_w_slope * (a_guess - a_low) \n\n # ooo. value-of-choice\n u = ufunc(c_guess,*args)\n if use_inv_w:\n v_guess = u + (-1/inv_w)\n else:\n v_guess = u + inv_w\n\n # oooo. update\n if v_guess > v_ast_vec[im]:\n v_ast_vec[im] = v_guess\n c_ast_vec[im] = c_guess\n \n return upperenvelope", "repo_name": "NumEconCopenhagen/ConsumptionSaving", "sub_path": "consav/upperenvelope.py", "file_name": "upperenvelope.py", "file_ext": "py", "file_size_in_byte": 4256, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 19, "dataset": "github-code", "pt": "24", "api": [{"api_name": "numpy.inf", "line_number": 49, "usage_type": "attribute"}, {"api_name": "numba.njit", "line_number": 24, "usage_type": "name"}]} +{"seq_id": "3875357075", "text": "from itertools import combinations\n\norders = [\"XYZ\", \"XWY\", \"WXA\"]\ncourse = [2,3,4]\n\nd = dict()\n\nfor o in orders:\n tmp_o = list(o)\n for c_num in course:\n if c_num > len(tmp_o):\n break\n for cand in combinations(tmp_o, c_num):\n cand_str = ''.join(sorted(cand))\n if not d.get(cand_str):\n d[cand_str] = 1\n else:\n d[cand_str] += 1\n\na_dict = dict() \nfor k, v in d.items():\n t_num = len(k)\n if not a_dict.get(t_num):\n if v > 1:\n a_dict[t_num] = ([k], v)\n else:\n if a_dict[t_num][1] < v:\n a_dict[t_num] = ([k], v)\n elif a_dict[t_num][1] == v:\n a_dict[t_num][0].append(k)\n\nanswer = []\nfor c_num in course:\n if a_dict.get(c_num):\n for t_ans in a_dict[c_num][0]:\n answer.append(t_ans)\nanswer.sort()\nprint(answer)", "repo_name": "TTC1018/Algo_Py", "sub_path": "programmers/menu_renewal.py", "file_name": "menu_renewal.py", "file_ext": "py", "file_size_in_byte": 882, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "itertools.combinations", "line_number": 13, "usage_type": "call"}]} +{"seq_id": "21365989854", "text": "from django import forms\nfrom django.core.exceptions import ValidationError\n\nfrom itou.job_applications.enums import SenderKind\nfrom itou.job_applications.models import JobApplication\n\n\nclass JobApplicationAdminForm(forms.ModelForm):\n class Meta:\n model = JobApplication\n fields = \"__all__\"\n\n def clean(self):\n sender = self.cleaned_data[\"sender\"]\n sender_kind = self.cleaned_data[\"sender_kind\"]\n sender_company = self.cleaned_data.get(\"sender_company\")\n sender_prescriber_organization = self.cleaned_data.get(\"sender_prescriber_organization\")\n\n if sender_kind == SenderKind.JOB_SEEKER:\n if sender is None:\n raise ValidationError(\"Emetteur candidat manquant.\")\n if not sender.is_job_seeker:\n raise ValidationError(\"Emetteur du mauvais type.\")\n\n if sender_kind == SenderKind.EMPLOYER:\n if sender_company is None:\n raise ValidationError(\"SIAE émettrice manquante.\")\n if sender is None:\n raise ValidationError(\"Emetteur SIAE manquant.\")\n else:\n # Sender is optional, but if it exists, check its role.\n if not sender.is_employer:\n raise ValidationError(\"Emetteur du mauvais type.\")\n\n elif sender_company is not None:\n raise ValidationError(\"SIAE émettrice inattendue.\")\n\n if sender_kind == SenderKind.PRESCRIBER:\n if sender:\n # Sender is optional, but if it exists, check its role.\n if not sender.is_prescriber:\n raise ValidationError(\"Emetteur du mauvais type.\")\n # Request organization only if prescriber is actively linked to an organization\n if (\n sender_prescriber_organization is None\n and sender.prescribermembership_set.filter(is_active=True).exists()\n ):\n raise ValidationError(\"Organisation du prescripteur émettrice manquante.\")\n else:\n raise ValidationError(\"Emetteur prescripteur manquant.\")\n elif sender_prescriber_organization is not None:\n raise ValidationError(\"Organisation du prescripteur émettrice inattendue.\")\n\n return\n", "repo_name": "gip-inclusion/les-emplois", "sub_path": "itou/job_applications/admin_forms.py", "file_name": "admin_forms.py", "file_ext": "py", "file_size_in_byte": 2305, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 26, "dataset": "github-code", "pt": "26", "api": [{"api_name": "django.forms.ModelForm", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 8, "usage_type": "name"}, {"api_name": "itou.job_applications.models.JobApplication", "line_number": 10, "usage_type": "name"}, {"api_name": "itou.job_applications.enums.SenderKind.JOB_SEEKER", "line_number": 19, "usage_type": "attribute"}, {"api_name": "itou.job_applications.enums.SenderKind", "line_number": 19, "usage_type": "name"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 21, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 23, "usage_type": "call"}, {"api_name": "itou.job_applications.enums.SenderKind.EMPLOYER", "line_number": 25, "usage_type": "attribute"}, {"api_name": "itou.job_applications.enums.SenderKind", "line_number": 25, "usage_type": "name"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 27, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 29, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 33, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 36, "usage_type": "call"}, {"api_name": "itou.job_applications.enums.SenderKind.PRESCRIBER", "line_number": 38, "usage_type": "attribute"}, {"api_name": "itou.job_applications.enums.SenderKind", "line_number": 38, "usage_type": "name"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 42, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 48, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 50, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 52, "usage_type": "call"}]} +{"seq_id": "10837055555", "text": "from openerp import models, fields, api, _\nfrom openerp.osv import osv, fields\nimport re\nfrom datetime import datetime, timedelta, date\nfrom openerp import tools, SUPERUSER_ID\nimport base64, csv, StringIO\n\nclass account_invoice(osv.osv):\n\t\n\t_inherit = 'account.invoice'\n\t\n\t@api.multi\n\tdef confirm_paid(self):\n\t\tsuper(account_invoice, self).confirm_paid()\n\t# ketika invoice dibayar, set tanggal bayarnya yaitu tanggal payment pertama\n\t\tpayment_date = date.today()\n\t\tfor payment in self.payment_ids:\n\t\t\tif payment.date:\n\t\t\t\tpayment_date = payment.date\n\t\t\telif payment.date_created:\n\t\t\t\tpayment_date = payment.date_created\n\t\t\tbreak # ambil payment yang pertama aja. asumsi tidak ada backdate payment sedemikian sehingga tanggal payument yang kedua lebih dulu dari yang pertama\n\t\treturn self.write({'payment_date': payment_date})\n\t\t\n\t@api.model\n\tdef calculate_invoice_point(self, member, invoice_line):\n\t# ambil nilai uang dari mo ini\n\t\tamount = invoice_line.price_subtotal\n\t# ambil settingan terakhir. kalau productnya ngga ada setting, ya udah\n\t\tsetting = invoice_line.product_id.member_point_settings\n\t\tif not setting: return 0\n\t# dapatkan setting line berdasarkan level member saat ini \n\t\tused_setting_line = None\n\t\tfor setting_line in setting:\n\t\t\tif setting_line.membership_level_id.id == member.current_level.id:\n\t\t\t\tused_setting_line = setting_line\n\t\t\t\tbreak\n\t\tif not used_setting_line: return 0\n\t# hitung poin beserta pembulatannya\n\t\tpoint = used_setting_line.factor * amount / 1000\t\t\n\t\tpoint = point - (point % used_setting_line.rounding)\n\t\treturn point\n\n\n", "repo_name": "miebakso/ciptadlab2", "sub_path": "account_invoice.py", "file_name": "account_invoice.py", "file_ext": "py", "file_size_in_byte": 1561, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "openerp.osv.osv.osv", "line_number": 8, "usage_type": "attribute"}, {"api_name": "openerp.osv.osv", "line_number": 8, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 16, "usage_type": "name"}, {"api_name": "openerp.api.multi", "line_number": 12, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 12, "usage_type": "name"}, {"api_name": "openerp.api.model", "line_number": 25, "usage_type": "attribute"}, {"api_name": "openerp.api", "line_number": 25, "usage_type": "name"}]} +{"seq_id": "41064437649", "text": "#!/usr/bin/env python\n# Implementation of algorithm from http://stackoverflow.com/a/22640362/6029703\nimport numpy as np\nimport pylab\nimport matplotlib.pyplot as plt\n\ndef thresholding_algo(y, lag, threshold, influence):\n signals = np.zeros(len(y)) # Initialise signal results\n filteredY = np.array(y) # Initialise filtered series\n avgFilter = [0]*len(y) # Initialise average filter\n stdFilter = [0]*len(y) # Initialise std. filter\n avgFilter[lag - 1] = np.mean(y[0:lag]) # Initialise first value\n stdFilter[lag - 1] = np.std(y[0:lag]) # Initialise first value \n for i in range(lag, len(y) - 1):\n if abs(y[i] - avgFilter[i-1]) > threshold * stdFilter [i-1]:\n if y[i] > avgFilter[i-1]:\n signals[i] = 1 # Positive signal\n else:\n signals[i] = -1 # Negative signal\n\n # Make influence lower\n filteredY[i] = influence * y[i] + (1 - influence) * filteredY[i-1]\n else:\n signals[i] = 0 # No signal\n filteredY[i] = y[i]\n avgFilter[i] = np.mean(filteredY[(i-lag):i])\n stdFilter[i] = np.std(filteredY[(i-lag):i])\n\n return dict(signals = np.asarray(signals),\n avgFilter = np.asarray(avgFilter),\n stdFilter = np.asarray(stdFilter))\n\n\n\n# Data\ny = np.array([1,1,1.1,1,0.9,1,1,1.1,1,0.9,1,1.1,1,1,0.9,1,1,1.1,1,1,1,1,1.1,0.9,1,1.1,1,1,0.9,\n 1,1.1,1,1,1.1,1,0.8,0.9,1,1.2,0.9,1,1,1.1,1.2,1,1.5,1,3,2,5,3,2,1,1,1,0.9,1,1,3,\n 2.6,4,3,3.2,2,1,1,0.8,4,4,2,2.5,1,1,1])\n\n# Settings: lag = 30, threshold = 5, influence = 0\nlag = 30\nthreshold = 5\ninfluence = 0\n\n# Run algo with settings from above\nresult = thresholding_algo(y, lag=lag, threshold=threshold, influence=influence)\n\n# Plot result\nplt.subplot(211)\nplt.plot(np.arange(1, len(y)+1), y)\n\nplt.plot(np.arange(1, len(y)+1),\n result[\"avgFilter\"], color=\"cyan\", lw=2)\n\nplt.plot(np.arange(1, len(y)+1),\n result[\"avgFilter\"] + threshold * result[\"stdFilter\"], color=\"green\", lw=2)\n\nplt.plot(np.arange(1, len(y)+1),\n result[\"avgFilter\"] - threshold * result[\"stdFilter\"], color=\"green\", lw=2)\n\nplt.subplot(212)\nplt.step(np.arange(1, len(y)+1), result[\"signals\"], color=\"red\", lw=2)\nplt.ylim(-1.5, 1.5)\nplt.show()\n\n\n\n", "repo_name": "bmaz/projet_buzz_twitter", "sub_path": "ThresholdingAlgo.py", "file_name": "ThresholdingAlgo.py", "file_ext": "py", "file_size_in_byte": 2260, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "numpy.zeros", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 58, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.step", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}]} +{"seq_id": "40040031736", "text": "#! /usr/bin/env python\n\n\"\"\"Main script to run training and evaluation of models.\n\"\"\"\n\nimport functools\nimport os\nimport tempfile\nimport yaml\n\nfrom seq2seq import models\nfrom seq2seq.data import data_utils, vocab\nfrom seq2seq.training import HParamsParser\nfrom seq2seq.training import utils as training_utils\nfrom seq2seq.training import metrics\n\nimport tensorflow as tf\nfrom tensorflow.contrib.learn.python.learn import learn_runner\nfrom tensorflow.contrib.learn.python.learn.estimators import run_config\nfrom tensorflow.python.platform import gfile\n\n\n# Input Data\ntf.flags.DEFINE_string(\"train_source\", None,\n \"\"\"Path to the training data source sentences. A raw\n text files with tokens separated by spaces.\"\"\")\ntf.flags.DEFINE_string(\"train_target\", None,\n \"\"\"Path to the training data target sentences. A raw\n text files with tokens separated by spaces.\"\"\")\ntf.flags.DEFINE_string(\"dev_source\", None,\n \"\"\"Path to the development data source sentences.\n Same format as training data.\"\"\")\ntf.flags.DEFINE_string(\"dev_target\", None,\n \"\"\"Path to the development data target sentences.\n Same format as training data.\"\"\")\ntf.flags.DEFINE_string(\"vocab_source\", None,\n \"\"\"Path to the source vocabulary.\n A raw text file with one word per line.\"\"\")\ntf.flags.DEFINE_string(\"vocab_target\", None,\n \"\"\"Path to the target vocabulary.\n A raw text file with one word per line.\"\"\")\ntf.flags.DEFINE_string(\"delimiter\", \" \",\n \"\"\"Split input files into tokens on this delimiter.\n Defaults to \" \" (space).\"\"\")\ntf.flags.DEFINE_string(\"config_path\", None,\n \"\"\"Path to a YAML configuration file defining FLAG\n values and hyperparameters. Refer to the documentation\n for more details.\"\"\")\n\n# Model Configuration\ntf.flags.DEFINE_string(\"model\", \"AttentionSeq2Seq\",\n \"\"\"The model class to use. Refer to the documentation\n for all available models.\"\"\")\ntf.flags.DEFINE_string(\"buckets\", None,\n \"\"\"Buckets input sequences according to these length.\n A comma-separated list of sequence length buckets, e.g.\n \"10,20,30\" would result in 4 buckets:\n <10, 10-20, 20-30, >30. None disabled bucketing. \"\"\")\ntf.flags.DEFINE_integer(\"batch_size\", 16,\n \"\"\"Batch size used for training and evaluation.\"\"\")\ntf.flags.DEFINE_string(\"hparams\", None,\n \"\"\"A comma-separated list of hyeperparameter values that\n overwrite the model defaults, e.g.\n \"optimizer.name=Adam,optimization.learning_rate=0.1\".\n Refer to the documentation for a detailed list of\n available hyperparameters.\"\"\")\ntf.flags.DEFINE_string(\"output_dir\", None,\n \"\"\"The directory to write model checkpoints and summaries\n to. If None, a local temporary directory is created.\"\"\")\n\n# Training parameters\ntf.flags.DEFINE_string(\"schedule\", None,\n \"\"\"Estimator function to call, defaults to\n train_and_evaluate for local run\"\"\")\ntf.flags.DEFINE_integer(\"train_steps\", None,\n \"\"\"Maximum number of training steps to run.\n If None, train forever.\"\"\")\ntf.flags.DEFINE_integer(\"train_epochs\", None,\n \"\"\"Maximum number of training epochs over the data.\n If None, train forever.\"\"\")\ntf.flags.DEFINE_integer(\"eval_every_n_steps\", 1000,\n \"Run evaluation on validation data every N steps.\")\ntf.flags.DEFINE_integer(\"sample_every_n_steps\", 500,\n \"\"\"Sample and print sequence predictions every N steps\n during training.\"\"\")\n\n# RunConfig Flags\ntf.flags.DEFINE_integer(\"tf_random_seed\", None,\n \"\"\"Random seed for TensorFlow initializers. Setting\n this value allows consistency between reruns.\"\"\")\ntf.flags.DEFINE_integer(\"save_checkpoints_secs\", 600,\n \"\"\"Save checkpoints every this many seconds.\n Can not be specified with save_checkpoints_steps.\"\"\")\ntf.flags.DEFINE_integer(\"save_checkpoints_steps\", None,\n \"\"\"Save checkpoints every this many steps.\n Can not be specified with save_checkpoints_secs.\"\"\")\ntf.flags.DEFINE_integer(\"keep_checkpoint_max\", 5,\n \"\"\"Maximum number of recent checkpoint files to keep.\n As new files are created, older files are deleted.\n If None or 0, all checkpoint files are kept.\"\"\")\ntf.flags.DEFINE_integer(\"keep_checkpoint_every_n_hours\", 4,\n \"\"\"In addition to keeping the most recent checkpoint\n files, keep one checkpoint file for every N hours of\n training.\"\"\")\n\nFLAGS = tf.flags.FLAGS\n\ndef create_experiment(output_dir):\n \"\"\"\n Creates a new Experiment instance.\n\n Args:\n output_dir: Output directory for model checkpoints and summaries.\n \"\"\"\n\n config = run_config.RunConfig(\n tf_random_seed=FLAGS.tf_random_seed,\n save_checkpoints_secs=FLAGS.save_checkpoints_secs,\n save_checkpoints_steps=FLAGS.save_checkpoints_steps,\n keep_checkpoint_max=FLAGS.keep_checkpoint_max,\n keep_checkpoint_every_n_hours=FLAGS.keep_checkpoint_every_n_hours\n )\n\n # Load vocabulary info\n source_vocab_info = vocab.get_vocab_info(FLAGS.vocab_source)\n target_vocab_info = vocab.get_vocab_info(FLAGS.vocab_target)\n\n # Find model class\n model_class = getattr(models, FLAGS.model)\n\n # Parse parameter and merge with defaults\n hparams = model_class.default_params()\n if FLAGS.hparams is not None and isinstance(FLAGS.hparams, str):\n hparams = HParamsParser(hparams).parse(FLAGS.hparams)\n elif isinstance(FLAGS.hparams, dict):\n hparams.update(FLAGS.hparams)\n\n # Print hparams\n training_utils.print_hparams(hparams)\n\n # One the main worker, save training options and vocabulary\n if config.is_chief:\n # Copy vocabulary to output directory\n gfile.MakeDirs(output_dir)\n source_vocab_path = os.path.join(output_dir, \"vocab_source\")\n gfile.Copy(FLAGS.vocab_source, source_vocab_path, overwrite=True)\n target_vocab_path = os.path.join(output_dir, \"vocab_target\")\n gfile.Copy(FLAGS.vocab_target, target_vocab_path, overwrite=True)\n # Save train options\n train_options = training_utils.TrainOptions(\n hparams=hparams,\n model_class=FLAGS.model,\n source_vocab_path=source_vocab_path,\n target_vocab_path=target_vocab_path)\n train_options.dump(output_dir)\n\n # Create model\n model = model_class(\n source_vocab_info=source_vocab_info,\n target_vocab_info=target_vocab_info,\n params=hparams)\n\n bucket_boundaries = None\n if FLAGS.buckets:\n bucket_boundaries = list(map(int, FLAGS.buckets.split(\",\")))\n\n # Create training input function\n train_input_fn = training_utils.create_input_fn(\n data_provider_fn=functools.partial(\n data_utils.make_parallel_data_provider,\n data_sources_source=FLAGS.train_source,\n data_sources_target=FLAGS.train_target,\n shuffle=True,\n num_epochs=FLAGS.train_epochs,\n delimiter=FLAGS.delimiter),\n batch_size=FLAGS.batch_size,\n bucket_boundaries=bucket_boundaries)\n\n # Create eval input function\n eval_input_fn = training_utils.create_input_fn(\n data_provider_fn=functools.partial(\n data_utils.make_parallel_data_provider,\n data_sources_source=FLAGS.dev_source,\n data_sources_target=FLAGS.dev_target,\n shuffle=False,\n num_epochs=1,\n delimiter=FLAGS.delimiter),\n batch_size=FLAGS.batch_size)\n\n def model_fn(features, labels, params, mode):\n \"\"\"Builds the model graph\"\"\"\n return model(features, labels, params, mode)\n\n estimator = tf.contrib.learn.estimator.Estimator(\n model_fn=model_fn,\n model_dir=output_dir,\n config=config)\n\n train_hooks = training_utils.create_default_training_hooks(\n estimator=estimator,\n sample_frequency=FLAGS.sample_every_n_steps,\n delimiter=FLAGS.delimiter)\n\n eval_metrics = {\n \"log_perplexity\": metrics.streaming_log_perplexity(),\n \"bleu\": metrics.make_bleu_metric_spec(),\n }\n\n experiment = tf.contrib.learn.experiment.Experiment(\n estimator=estimator,\n train_input_fn=train_input_fn,\n eval_input_fn=eval_input_fn,\n min_eval_frequency=FLAGS.eval_every_n_steps,\n train_steps=FLAGS.train_steps,\n eval_steps=None,\n eval_metrics=eval_metrics,\n train_monitors=train_hooks)\n\n return experiment\n\n\ndef main(_argv):\n \"\"\"The entrypoint for the script\"\"\"\n\n # Load flags from config file\n if FLAGS.config_path:\n with gfile.GFile(FLAGS.config_path) as config_file:\n config_flags = yaml.load(config_file)\n for flag_key, flag_value in config_flags.items():\n setattr(FLAGS, flag_key, flag_value)\n\n if not FLAGS.output_dir:\n FLAGS.output_dir = tempfile.mkdtemp()\n\n learn_runner.run(\n experiment_fn=create_experiment,\n output_dir=FLAGS.output_dir,\n schedule=FLAGS.schedule)\n\n\nif __name__ == \"__main__\":\n tf.logging.set_verbosity(tf.logging.INFO)\n tf.app.run()\n", "repo_name": "ForeverZyh/TensorFlow-Program-Bugs", "sub_path": "Github/UT-4/seq2seq-fix/bin/train.py", "file_name": "train.py", "file_ext": "py", "file_size_in_byte": 9655, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 29, "dataset": "github-code", "pt": "24", "api": [{"api_name": "tensorflow.flags.DEFINE_string", "line_number": 24, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 24, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_string", "line_number": 27, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 27, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_string", "line_number": 30, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 30, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_string", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 33, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_string", "line_number": 36, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 36, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_string", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 39, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_string", "line_number": 42, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 42, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_string", "line_number": 45, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 45, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_string", "line_number": 51, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 51, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_string", "line_number": 54, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 54, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_integer", "line_number": 59, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 59, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_string", "line_number": 61, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 61, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_string", "line_number": 67, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 67, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_string", "line_number": 72, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 72, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_integer", "line_number": 75, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 75, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_integer", "line_number": 78, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 78, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_integer", "line_number": 81, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 81, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_integer", "line_number": 83, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 83, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_integer", "line_number": 88, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 88, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_integer", "line_number": 91, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 91, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_integer", "line_number": 94, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 94, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_integer", "line_number": 97, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 97, "usage_type": "attribute"}, {"api_name": "tensorflow.flags.DEFINE_integer", "line_number": 101, "usage_type": "call"}, {"api_name": "tensorflow.flags", "line_number": 101, "usage_type": "attribute"}, {"api_name": "tensorflow.flags", "line_number": 106, "usage_type": "attribute"}, {"api_name": "tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig", "line_number": 116, "usage_type": "call"}, {"api_name": "tensorflow.contrib.learn.python.learn.estimators.run_config", "line_number": 116, "usage_type": "name"}, {"api_name": "seq2seq.data.vocab.get_vocab_info", "line_number": 125, "usage_type": "call"}, {"api_name": "seq2seq.data.vocab", "line_number": 125, "usage_type": "name"}, {"api_name": "seq2seq.data.vocab.get_vocab_info", "line_number": 126, "usage_type": "call"}, {"api_name": "seq2seq.data.vocab", "line_number": 126, "usage_type": "name"}, {"api_name": "seq2seq.models", "line_number": 129, "usage_type": "argument"}, {"api_name": "seq2seq.training.HParamsParser", "line_number": 134, "usage_type": "call"}, {"api_name": "seq2seq.training.utils.print_hparams", "line_number": 139, "usage_type": "call"}, {"api_name": "seq2seq.training.utils", "line_number": 139, "usage_type": "name"}, {"api_name": "tensorflow.python.platform.gfile.MakeDirs", "line_number": 144, "usage_type": "call"}, {"api_name": "tensorflow.python.platform.gfile", "line_number": 144, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 145, "usage_type": "call"}, {"api_name": "os.path", "line_number": 145, "usage_type": "attribute"}, {"api_name": "tensorflow.python.platform.gfile.Copy", "line_number": 146, "usage_type": "call"}, {"api_name": "tensorflow.python.platform.gfile", "line_number": 146, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 147, "usage_type": "call"}, {"api_name": "os.path", "line_number": 147, "usage_type": "attribute"}, {"api_name": "tensorflow.python.platform.gfile.Copy", "line_number": 148, "usage_type": "call"}, {"api_name": "tensorflow.python.platform.gfile", "line_number": 148, "usage_type": "name"}, {"api_name": "seq2seq.training.utils.TrainOptions", "line_number": 150, "usage_type": "call"}, {"api_name": "seq2seq.training.utils", "line_number": 150, "usage_type": "name"}, {"api_name": "seq2seq.training.utils.create_input_fn", "line_number": 168, "usage_type": "call"}, {"api_name": "seq2seq.training.utils", "line_number": 168, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 169, "usage_type": "call"}, {"api_name": "seq2seq.data.data_utils.make_parallel_data_provider", "line_number": 170, "usage_type": "attribute"}, {"api_name": "seq2seq.data.data_utils", "line_number": 170, "usage_type": "name"}, {"api_name": "seq2seq.training.utils.create_input_fn", "line_number": 180, "usage_type": "call"}, {"api_name": "seq2seq.training.utils", "line_number": 180, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 181, "usage_type": "call"}, {"api_name": "seq2seq.data.data_utils.make_parallel_data_provider", "line_number": 182, "usage_type": "attribute"}, {"api_name": "seq2seq.data.data_utils", "line_number": 182, "usage_type": "name"}, {"api_name": "tensorflow.contrib.learn.estimator.Estimator", "line_number": 194, "usage_type": "call"}, {"api_name": "tensorflow.contrib", "line_number": 194, "usage_type": "attribute"}, {"api_name": "seq2seq.training.utils.create_default_training_hooks", "line_number": 199, "usage_type": "call"}, {"api_name": "seq2seq.training.utils", "line_number": 199, "usage_type": "name"}, {"api_name": "seq2seq.training.metrics.streaming_log_perplexity", "line_number": 205, "usage_type": "call"}, {"api_name": "seq2seq.training.metrics", "line_number": 205, "usage_type": "name"}, {"api_name": "seq2seq.training.metrics.make_bleu_metric_spec", "line_number": 206, "usage_type": "call"}, {"api_name": "seq2seq.training.metrics", "line_number": 206, "usage_type": "name"}, {"api_name": "tensorflow.contrib.learn.experiment.Experiment", "line_number": 209, "usage_type": "call"}, {"api_name": "tensorflow.contrib", "line_number": 209, "usage_type": "attribute"}, {"api_name": "tensorflow.python.platform.gfile.GFile", "line_number": 227, "usage_type": "call"}, {"api_name": "tensorflow.python.platform.gfile", "line_number": 227, "usage_type": "name"}, {"api_name": "yaml.load", "line_number": 228, "usage_type": "call"}, {"api_name": "tempfile.mkdtemp", "line_number": 233, "usage_type": "call"}, {"api_name": "tensorflow.contrib.learn.python.learn.learn_runner.run", "line_number": 235, "usage_type": "call"}, {"api_name": "tensorflow.contrib.learn.python.learn.learn_runner", "line_number": 235, "usage_type": "name"}, {"api_name": "tensorflow.logging.set_verbosity", "line_number": 242, "usage_type": "call"}, {"api_name": "tensorflow.logging", "line_number": 242, "usage_type": "attribute"}, {"api_name": "tensorflow.app.run", "line_number": 243, "usage_type": "call"}, {"api_name": "tensorflow.app", "line_number": 243, "usage_type": "attribute"}]} +{"seq_id": "6164584664", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2022/4/20 9:06\n# @Author : jingwen\n# @File : SocketService.py\n# @Desc: : 将预测代码拆开封装成接口供java客户端调用\nimport os\nimport subprocess\nimport time\n\nimport cv2\nimport numpy as np\n\nfrom model.retinaface import Retinaface\nfrom apiResponse.ApiResponse import ApiResponse\nfrom encoding import encoding\n\nfrom socket_config import *\n\n\n# socket中可能要多次调用下列方法,建立一个service类\nclass SocketService(object):\n def __init__(self):\n super(SocketService, self).__init__()\n self.retinaface = Retinaface()\n\n # 内部函数\n def get_file_save_path(self, image_path):\n file_name = os.path.basename(image_path) # jingwen_undetected.jpg\n save_directory = detection_result\n if not os.path.exists(save_directory):\n os.makedirs(save_directory)\n new_file_name = file_name.replace(\"_undetected\", \"_detected\", 1)\n save_image_path = save_directory + new_file_name\n return save_image_path\n\n # 检测图片\n def predictImage(self, image_path=\"\", save_image=False):\n print(\"检测图片,image_path=\", image_path, )\n image = cv2.imread(image_path)\n if image is None:\n # print(\"图片路径有误\")\n return ApiResponse(code=500, message='图片路径有误')\n else:\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n r_image, recognition_face_list = self.retinaface.detect_image(image)\n print(f'FaceNet识别出{len(recognition_face_list)}张人脸:{recognition_face_list}')\n\n # r_image = cv2.cvtColor(r_image, cv2.COLOR_RGB2BGR)\n # cv2.imshow(\"after\", r_image)\n # cv2.waitKey(0)\n\n data = {}\n data.setdefault('recognition_face_list', recognition_face_list)\n\n # 是否保存检测图片\n if save_image:\n r_image = cv2.cvtColor(r_image, cv2.COLOR_RGB2BGR)\n save_file_path = self.get_file_save_path(image_path)\n cv2.imwrite(save_file_path, r_image)\n data.setdefault('save_file_path', save_file_path)\n print('保存检测结果: ' + save_file_path)\n return ApiResponse(code=200, message=\"识别成功\", data=data)\n\n # 检测视频,完成学生正脸检测,并返回最终得分\n def predictVideo(self, video_path=\"\", save_video=False, video_fps=30):\n print(\"检测视频,video_path=\", video_path)\n\n data = {}\n # 防止传入数据为摄像头\n if video_path == 0:\n return ApiResponse(code=500, message=\"该方法为检测视频,请更换摄像头检测方法\")\n all_recognition_face_list = [] # 为检测到的所有人脸\n\n capture = cv2.VideoCapture(video_path)\n # 视频保存路径\n video_save_path = ''\n if save_video:\n video_save_path = self.get_file_save_path(video_path)\n # 视频的编码\n fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n # 视频的分辨率\n size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n # 定义视频输出\n out = cv2.VideoWriter(video_save_path, fourcc, video_fps, size)\n\n ref, frame = capture.read()\n if not ref: # null 0\n raise ApiResponse(code=500, message=\"未能正确读取视频,请检查视频路径是否正确\")\n\n input_video_fps = capture.get(5) # 获取输入视频帧数\n frameRate = int(input_video_fps) * videoTimeRate # 每隔videoTimeRate秒取一帧\n current_ref = 1 # 当前帧\n fps = 0.0\n while (True):\n\n ref, frame = capture.read()\n\n if not ref:\n break\n \"\"\"\n # 镜头水平反转代码\n \"\"\"\n # frame = cv2.flip(frame, 180)\n recognition_face_list = []\n if (current_ref % frameRate == 0):\n t1 = time.time()\n # 读取某一帧\n # 格式转变,BGRtoRGB\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n # 进行检测\n frame, recognition_face_list = self.retinaface.detect_image(frame)\n\n frame = np.array(frame)\n # RGBtoBGR满足opencv显示格式\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n\n fps = (fps + (1. / (time.time() - t1))) / 2\n print(f'fps= {fps:.2f}; '\n f'facenet识别出{len(recognition_face_list)}张人脸:{recognition_face_list} ')\n\n # 根据当前帧识别的人脸 更新总识别人脸数\n if len(recognition_face_list) != 0:\n for face_name in recognition_face_list:\n if face_name not in all_recognition_face_list:\n all_recognition_face_list.append(face_name)\n frame = cv2.putText(frame, \"fps= %.2f, recognition_num= %d\" % (fps, len(recognition_face_list)),\n (0, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)\n current_ref += 1\n\n # cv2.imshow(\"video\", frame)\n c = cv2.waitKey(1) & 0xff\n if save_video:\n out.write(frame)\n\n if c == 27:\n capture.release()\n break\n print(\"Video Detection Done!\")\n capture.release()\n if save_video == True:\n out.release()\n \"\"\"\n # 为视频添加音频信息\n video_add_voice_config=True 表示添加\n video_add_voice_config=False 表示不添加 \n \"\"\"\n if video_add_voice_config:\n video_save_path = self.video_add_voice(video_save_path, video_path)\n print(\"Save processed video to the path :\" + video_save_path)\n cv2.destroyAllWindows()\n\n data.setdefault('save_file_path', video_save_path)\n data.setdefault('recognition_face_list', all_recognition_face_list)\n return ApiResponse(code=200, message=\"视频检测完成\", data=data)\n\n # 给数据库人脸编码\n def update_face_dataset(self):\n encoding()\n # 更新初始化的retinaface的人脸库信息\n self.retinaface.known_face_encodings = np.load(\n \"model/model_data/{backbone}_face_encoding.npy\".format(backbone=self.retinaface.facenet_backbone))\n self.retinaface.known_face_names = np.load(\n \"model/model_data/{backbone}_names.npy\".format(backbone=self.retinaface.facenet_backbone))\n return ApiResponse(code=200, message='人脸库更新成功')\n\n def video_add_voice(self, video_file, voice_file):\n \"\"\"\n 视频添加音频\n :param video_file: 传入视频文件的路径\n :param voice_file: 传入音频文件的路径\n :return:\n \"\"\"\n outfile_name = video_file.split('.')[0] + '_voice.mp4'\n subprocess.call('ffmpeg -y -i ' + video_file\n + ' -i ' + voice_file + ' -strict -2 -f mp4 '\n + outfile_name, shell=True)\n # 删除原视频文件,若不想删除可以注释掉下行代码\n os.remove(video_file)\n\n return outfile_name\n", "repo_name": "jing3wen/jw_project", "sub_path": "facenet-retinaface-pytorch/SocketService.py", "file_name": "SocketService.py", "file_ext": "py", "file_size_in_byte": 7363, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "24", "api": [{"api_name": "model.retinaface.Retinaface", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 32, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 40, "usage_type": "call"}, {"api_name": "apiResponse.ApiResponse.ApiResponse", "line_number": 43, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 45, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 45, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 58, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2BGR", "line_number": 58, "usage_type": "attribute"}, {"api_name": "cv2.imwrite", "line_number": 60, "usage_type": "call"}, {"api_name": "apiResponse.ApiResponse.ApiResponse", "line_number": 63, "usage_type": "call"}, {"api_name": "apiResponse.ApiResponse.ApiResponse", "line_number": 72, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 75, "usage_type": "call"}, {"api_name": "cv2.VideoWriter_fourcc", "line_number": 81, "usage_type": "call"}, {"api_name": "cv2.CAP_PROP_FRAME_WIDTH", "line_number": 83, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FRAME_HEIGHT", "line_number": 83, "usage_type": "attribute"}, {"api_name": "cv2.VideoWriter", "line_number": 85, "usage_type": "call"}, {"api_name": "apiResponse.ApiResponse.ApiResponse", "line_number": 89, "usage_type": "call"}, {"api_name": "time.time", "line_number": 107, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 110, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 110, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 114, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 116, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2BGR", "line_number": 116, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 118, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 127, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 128, "usage_type": "attribute"}, {"api_name": "cv2.waitKey", "line_number": 132, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 151, "usage_type": "call"}, {"api_name": "apiResponse.ApiResponse.ApiResponse", "line_number": 155, "usage_type": "call"}, {"api_name": "encoding.encoding", "line_number": 159, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 161, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 163, "usage_type": "call"}, {"api_name": "apiResponse.ApiResponse.ApiResponse", "line_number": 165, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 175, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 179, "usage_type": "call"}]} +{"seq_id": "28020732345", "text": "import os\nfrom pathlib import Path\n\nfrom flask import Flask\nfrom flask_bootstrap import Bootstrap\nimport logging\n\ndef create_app(test_config=None):\n #create and configure application\n app = Flask(__name__, instance_relative_config=True)\n Bootstrap(app)\n app.config.from_mapping(\n SECRET_KEY = 'devvvv'\n )\n \n\n\n config_file = Path(app.root_path) / \"config.py\"\n\n if test_config is None:\n #Load instance config, if it exists, when not testing\n app.config.from_pyfile(config_file,silent=True)\n else:\n #Load the test config if passed in\n app.config.from_mapping(test_config)\n \n #ensure the instantce folder exist\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n \n #hello page for test\n @app.route('/hello')\n def hello():\n return \"Hello World\"\n \n #load application modules(blueprints)\n from . import flatfile_operations\n from . import backup_operations\n from . import scp_interface\n with app.app_context():\n app.register_blueprint(flatfile_operations.bp)\n app.register_blueprint(backup_operations.bp)\n app.register_blueprint(scp_interface.bp)\n\n #configure logger\n logging.basicConfig(filename='app.log',\n filemode='a',\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\n app.logger = logging.getLogger('werkzeug')\n #app.logger.disabled = True\n \n return app", "repo_name": "GregZly/Flatfile_ed", "sub_path": "flatfileed/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 1538, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 10, "usage_type": "call"}, {"api_name": "flask_bootstrap.Bootstrap", "line_number": 11, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 18, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 29, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 48, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 52, "usage_type": "call"}]} +{"seq_id": "24468062966", "text": "import json\nimport requests\nimport datetime\nfrom datetime import date, timedelta\nimport codecs\n\n\ndef daterange(start_date, end_date):\n for n in range(int((end_date - start_date).days)):\n yield start_date + timedelta(n)\n\n\ndef list_to_str(k):\n d = \"\"\n for x in k:\n d = str(d) + \"-\" + str(x)\n return d[1:]\n\n\n# start_date = date(2007, 1, 1)\n# end_date = date(2007, 1, 2)\n# stations_data = {\"6\": [1711,44,46,202,43,42,45], \"152\": [1747],\n# \"153\": [1752], \"16\": [144,149,146,148,242,143,145], \"149\": [1725,1723,1724,1726],\n# \"7\": [49,54,61,57,211,53,50,55]}\n\nif __name__ == \"__main__\":\n start_date = date(2016, 4, 6)\n end_date = date(2016, 4, 7)\n stations_data = {\"6\": [44, 46, 202, 43, 42, 45], \"152\": [1747],\n \"153\": [1752], \"16\": [144, 149, 146, 148, 242, 143, 145], \"149\": [1725, 1723, 1724, 1726],\n \"7\": [49, 54, 61, 57, 211, 53, 50, 55]}\n\n for stat_number, stat_param in stations_data.items():\n for single_date in daterange(start_date, end_date):\n ref = 'http://monitoring.krakow.pios.gov.pl/dane-pomiarowe/automatyczne/stacja/' + str(\n stat_number) + '/parametry/' + str(list_to_str(stat_param))\n response = requests.post(\n url='http://monitoring.krakow.pios.gov.pl/dane-pomiarowe/pobierz',\n data={\n 'query': json.dumps({\n \"measType\": \"Auto\",\n \"viewType\": \"Station\",\n \"dateRange\": \"Day\",\n \"date\": str(single_date.strftime(\"%d.%m.%Y\")),\n \"viewTypeEntityId\": str(stat_number),\n \"channels\": stat_param\n })\n },\n headers={\n 'Referer': ref,\n 'Cookie': 'start_selector_nth=0; start_selector_hide=yes',\n 'Origin': 'http://monitoring.krakow.pios.gov.pl',\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n 'Accept-Encoding': 'gzip, deflate, lzma',\n 'DNT': '1',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36 OPR/35.0.2066.92',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'Host': 'monitoring.krakow.pios.gov.pl',\n 'X-Requested-With': 'XMLHttpRequest',\n 'Connection': 'keep-alive',\n 'Accept-Language': 'pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4'\n }\n )\n\n d = response.json()\n print(str(stat_number) + ' <> ' + str(single_date.strftime(\"%Y-%m-%d\")), '-->', d['success'])\n json_file_name = 'smog/' + str(single_date.strftime(\"%Y-%m-%d\")) + \".json\"\n with codecs.open(json_file_name, \"w\", 'utf-8') as json_file:\n json.dump(d, json_file)\n\n file_name = 'smog/' + str(stat_number) + \"-\" + str(single_date.strftime(\"%Y-%m-%d\")) + \".csv\"\n\n\n def date_str(x):\n return datetime.datetime.fromtimestamp(int(x)).strftime('%H:%M')\n\n\n with codecs.open(file_name, \"w\", 'utf-8') as my_file:\n dane = {':'.join([str(x).zfill(2), '00']): {} for x in range(24)}\n print('CZAS', end=\"\", file=my_file)\n comp = []\n for k in d['data']['series']:\n compound_str = str(k['paramLabel'])\n if compound_str == \"Ozon\":\n compound_str = k['label'][:7]\n if compound_str == \"Tlenek węgla\":\n compound_str = k['label'][:15]\n\n if k['data']:\n comp.append(compound_str)\n\n for t, v in k['data']:\n ds = date_str(t)\n if ds not in dane: continue\n dane[ds][compound_str] = v\n\n print(';' + ';'.join(x for x in comp), file=my_file)\n\n for k in [':'.join([str(x).zfill(2), '00']) for x in range(24)]:\n line = k\n for c in comp:\n line += ';'\n line += \"\" if c not in dane[k] else str(dane[k][c])\n\n print(line, file=my_file)\n", "repo_name": "lukasz149/agh-smog-project", "sub_path": "scripts/download-smog.py", "file_name": "download-smog.py", "file_ext": "py", "file_size_in_byte": 4447, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "datetime.timedelta", "line_number": 10, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 28, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 37, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 40, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 68, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 69, "usage_type": "call"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 75, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 75, "usage_type": "attribute"}, {"api_name": "codecs.open", "line_number": 78, "usage_type": "call"}]} +{"seq_id": "72355325828", "text": "#!/usr/bin/env python\nfrom argparse import ArgumentParser\nfrom sklearn.utils import shuffle\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import roc_curve, auc\nimport os\nimport numpy\nimport scipy\nimport pylab\nimport torch\nimport torch.nn as nn\n \n \ninput_size = 949\nhidden_size = 1000\nnum_classes = 2\nnum_epochs = 10\nbatch_size = 1000\nlearning_rate = 0.01\n\nif __name__ == \"__main__\":\n cadd_dir = '/home/alex'\n ClinVar_ESP_dir = '/home/alex'\n \n print('Load Data')\n X_tr = numpy.load(os.path.join(cadd_dir, 'training.X.npz'))\n X_tr = scipy.sparse.csr_matrix((X_tr['data'], X_tr['indices'], X_tr['indptr']), shape=X_tr['shape'])\n y_tr = numpy.load(os.path.join(cadd_dir, 'training.y.npy'))\n \n X_va = numpy.load(os.path.join(cadd_dir, 'validation.X.npz'))\n X_va = scipy.sparse.csr_matrix((X_va['data'], X_va['indices'], X_va['indptr']), shape=X_va['shape'])\n y_va = numpy.load(os.path.join(cadd_dir, 'validation.y.npy')) \n \n X_te = numpy.load(os.path.join(cadd_dir, 'testing.X.npz'))\n X_te = scipy.sparse.csr_matrix((X_te['data'], X_te['indices'], X_te['indptr']), shape=X_te['shape'])\n y_te = numpy.load(os.path.join(cadd_dir, 'testing.y.npy'))\n \n X_ClinVar_ESP = numpy.load(os.path.join(ClinVar_ESP_dir, 'ClinVar_ESP.X.npz')) \n X_ClinVar_ESP = scipy.sparse.csr_matrix((X_ClinVar_ESP['data'], X_ClinVar_ESP['indices'], X_ClinVar_ESP['indptr']), shape=X_ClinVar_ESP['shape'])\n y_ClinVar_ESP = numpy.load(os.path.join(ClinVar_ESP_dir, 'ClinVar_ESP.y.npy'))\n\n\n\n\nx_dense_va = scipy.sparse.csc_matrix.todense(X_va)\nx_tensor_va = torch.from_numpy(x_dense_va)\n\nx_tensor_va, y_tensor_va\n\n#need to import data \nimport torch.utils.data\n#Define Batch Size \nbatch_size = 200000\n\n# Dataset \ntrain_loader = torch.utils.data.TensorDataset(X_train_tensor,y_train_tensor)\n \ntest_dataset = torch.utils.data.TensorDataset(x_tensor_va,y_tensor_va)\n# Data loader\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=False)\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset, \n batch_size=batch_size, \n shuffle=False)\n\n#Defining Dataset from dataloader\ntest_dataset = torch.utils.data.TensorDataset(x_tensor_va,y_tensor_va)\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)\n\n#Constructing the neuralnet from scratch. We added 3 more layers (6 layers in total)\nclass NeuralNet(nn.Module):\n def __init__(self, input_size, hidden_size, num_classes):\n super(NeuralNet, self).__init__()\n self.fc1 = nn.Linear(input_size, hidden_size) \n self.relu = nn.ReLU()\n self.fc2 = nn.Linear(hidden_size, hidden_size) \n self.relu2 = nn.ReLU()\n self.fc3 = nn.Linear(hidden_size, hidden_size) \n self.relu3 = nn.ReLU()\n self.fc4 = nn.Linear(hidden_size, hidden_size) \n self.relu4 = nn.ReLU()\n self.fc5 = nn.Linear(hidden_size, hidden_size) \n self.relu5 = nn.ReLU()\n self.fc6 = nn.Linear(hidden_size, num_classes) \n self.dropout = nn.Dropout(0.1)\n \n \n def forward(self, x):\n out = self.fc1(x)\n out = self.relu(out)\n out = self.dropout(out)\n out = self.fc2(out)\n out = self.relu2(out)\n out = self.dropout(out)\n out = self.fc3(out)\n out = self.relu3(out)\n out = self.dropout(out)\n out = self.fc4(out)\n out = self.relu4(out)\n out = self.dropout(out)\n out = self.fc5(out)\n out = self.relu5(out)\n out = self.dropout(out)\n out = self.fc6(out)\n \n return out\n#Check if cpu is availble, for user's information\ntorch.cuda.is_available()\n\n# Device configuration \ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n# Loading the model \n\nmodel = NeuralNet(input_size, hidden_size, num_classes).to(device)\n\n# Loss and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) \n\n# Define the number of epochs\nnum_epochs = 10\n# Display the number of epoches\nprint ('batch_size = ' + batch_size)\n\n# Train the model\ntotal_step = len(train_loader)\nfor epoch in range(num_epochs):\n for i, (data, labels) in enumerate(train_loader): \n \n data = data.cuda()\n labels = labels.cuda()\n # Forward pass\n outputs = model(data)\n loss = criterion(outputs, labels)\n \n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n if (i+1) % 10 == 0:\n print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' \n .format(epoch+1, num_epochs, i+1, total_step, loss.item()))\n# Let us save the model immediately \ntorch.save(model, 'savedodel.ckpt')\n\n\ntorch.load('model2.ckpt')\n\n# Test the model\n# In test phase, we don't need to compute gradients (for memory efficiency)\nwith torch.no_grad():\n correct = 0\n total = 0\n for images, labels in test_loader:\n images = images.to(device)\n labels = labels.to(device)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n print('Accuracy of the network on the test set: {} %'.format(100 * correct / total))\n\n# Save the model checkpoint\ntorch.save(model.state_dict(), 'model2.ckpt')\n\n", "repo_name": "findalexli/DANN", "sub_path": "dann.py", "file_name": "dann.py", "file_ext": "py", "file_size_in_byte": 5555, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "numpy.load", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path", "line_number": 27, "usage_type": "attribute"}, {"api_name": "scipy.sparse.csr_matrix", "line_number": 28, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 28, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "scipy.sparse.csr_matrix", "line_number": 32, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 32, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "scipy.sparse.csr_matrix", "line_number": 36, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 36, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path", "line_number": 39, "usage_type": "attribute"}, {"api_name": "scipy.sparse.csr_matrix", "line_number": 40, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 40, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "attribute"}, {"api_name": "scipy.sparse.csc_matrix.todense", "line_number": 46, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 46, "usage_type": "attribute"}, {"api_name": "torch.from_numpy", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.utils.data.TensorDataset", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 57, "usage_type": "attribute"}, {"api_name": "torch.utils.data.TensorDataset", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 59, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 61, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 61, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 62, "usage_type": "attribute"}, {"api_name": "torch.utils.data.TensorDataset", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 67, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 68, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 71, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 71, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 74, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 75, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 76, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 76, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 77, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 77, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 78, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 79, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 79, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 80, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 81, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 81, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 82, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 82, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 83, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 83, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 84, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 85, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 85, "usage_type": "name"}, {"api_name": "torch.cuda.is_available", "line_number": 108, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 108, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 111, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 111, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 111, "usage_type": "attribute"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 117, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 117, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 118, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 118, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 145, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 148, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 152, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 159, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 166, "usage_type": "call"}]} +{"seq_id": "34307733271", "text": "import new_crank\r\nimport original_crank\r\nimport time\r\nimport matplotlib.pyplot as plt\r\n\r\ndef test_new_tridiag():\r\n time1 = time.time()\r\n for _ in range(200):\r\n new_crank.price_american_option_with_divs()\r\n time2 = time.time()\r\n print(\"New: %.4f seconds\" % (time2-time1))\r\n\r\ndef test_one_new():\r\n new_crank.price_american_option_with_divs()\r\n start = time.time()\r\n new_crank.price_american_option_with_divs()\r\n end = time.time()\r\n print(\"Time to calc one option price: %.8f seconds\" % (end-start))\r\n\r\ndef test_old_method():\r\n time1 = time.time()\r\n for _ in range(200):\r\n original_crank.price_american_option_with_divs()\r\n time2 = time.time()\r\n print(\"Original: %.4f seconds\" % (time2-time1))\r\n\r\n# Tests 100 calculations of the original and new crank-nicolson method, measuring runtime\r\ndef test_crank():\r\n time1 = time.time()\r\n for _ in range(200):\r\n original_crank.price_american_option_with_divs()\r\n time2 = time.time()\r\n for _ in range(200):\r\n new_crank.price_american_option_with_divs()\r\n time3 = time.time()\r\n print(\"Original: %.4f seconds\" % (time2-time1))\r\n print(\"New: %.4f seconds\" % (time3-time2))\r\n\r\n# Tests 2000 calculations each of the original and new implementations of the crank-nicolson method, measuring runtime every 100 calculations\r\ndef test_crank_plot():\r\n time_orig_start = time.time()\r\n original_times = [0]\r\n for i in range(20):\r\n for _ in range(100):\r\n original_crank.price_american_option_with_divs()\r\n original_times.append(time.time() - time_orig_start)\r\n print(\"loop %d complete, time = %.4f seconds\" % (i+1, original_times[i+1]))\r\n new_crank.price_american_option_with_divs()\r\n time_new_start = time.time()\r\n new_times = [0]\r\n for i in range(20):\r\n for _ in range(100):\r\n new_crank.price_american_option_with_divs()\r\n new_times.append(time.time() - time_new_start)\r\n print(\"loop %d complete, time = %.4f seconds\" % (i+1, new_times[i+1]))\r\n x = range(0, 2001, 100)\r\n plt.plot(x, original_times, \"r^-\", label=\"Original\")\r\n plt.plot(x, new_times, \"bo-\", label=\"New\")\r\n plt.legend()\r\n plt.title(\"Comparison of Crank-Nicolson Method Implementations\\n(Ryzen 3700X, RTX 2080S, 32GB of RAM)\")\r\n plt.xlabel(\"Number of calculations\")\r\n plt.ylabel(\"Time (seconds)\")\r\n plt.annotate(\"%.2f\" % (original_times[-1]), xy=(x[-1], original_times[-1]), xytext=(x[-1], original_times[-1]))\r\n plt.annotate(\"%.2f\" % (new_times[-1]), xy=(x[-1], new_times[-1]), xytext=(x[-1], new_times[-1]))\r\n plt.show() \r\n plt.grid()\r\n plt.savefig(\"crank_plot.png\")\r\n\r\nif __name__ == \"__main__\":\r\n #test_crank_plot()\r\n test_one_new()\r\n #test_new_tridiag()\r\n", "repo_name": "EzePze/AmericanOptionPricing", "sub_path": "tester.py", "file_name": "tester.py", "file_ext": "py", "file_size_in_byte": 2766, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "26", "api": [{"api_name": "time.time", "line_number": 7, "usage_type": "call"}, {"api_name": "new_crank.price_american_option_with_divs", "line_number": 9, "usage_type": "call"}, {"api_name": "time.time", "line_number": 10, "usage_type": "call"}, {"api_name": "new_crank.price_american_option_with_divs", "line_number": 14, "usage_type": "call"}, {"api_name": "time.time", "line_number": 15, "usage_type": "call"}, {"api_name": "new_crank.price_american_option_with_divs", "line_number": 16, "usage_type": "call"}, {"api_name": "time.time", "line_number": 17, "usage_type": "call"}, {"api_name": "time.time", "line_number": 21, "usage_type": "call"}, {"api_name": "original_crank.price_american_option_with_divs", "line_number": 23, "usage_type": "call"}, {"api_name": "time.time", "line_number": 24, "usage_type": "call"}, {"api_name": "time.time", "line_number": 29, "usage_type": "call"}, {"api_name": "original_crank.price_american_option_with_divs", "line_number": 31, "usage_type": "call"}, {"api_name": "time.time", "line_number": 32, "usage_type": "call"}, {"api_name": "new_crank.price_american_option_with_divs", "line_number": 34, "usage_type": "call"}, {"api_name": "time.time", "line_number": 35, "usage_type": "call"}, {"api_name": "time.time", "line_number": 41, "usage_type": "call"}, {"api_name": "original_crank.price_american_option_with_divs", "line_number": 45, "usage_type": "call"}, {"api_name": "time.time", "line_number": 46, "usage_type": "call"}, {"api_name": "new_crank.price_american_option_with_divs", "line_number": 48, "usage_type": "call"}, {"api_name": "time.time", "line_number": 49, "usage_type": "call"}, {"api_name": "new_crank.price_american_option_with_divs", "line_number": 53, "usage_type": "call"}, {"api_name": "time.time", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 58, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.annotate", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.annotate", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}]} +{"seq_id": "41931699031", "text": "from omegaconf import DictConfig\nfrom claficle.models.sandwich import Sandwich\nfrom claficle.models.plain_gpt2 import PlainGPT2\nfrom claficle.models.gewechselt import Gewechselt\nfrom claficle.models.vessel import Vessel\n\nNAME_TO_CLASS = {\n \"sandwich\": Sandwich,\n \"plain_gpt2\": PlainGPT2,\n \"Gewechselt\": Gewechselt,\n \"vessel\": Vessel,\n}\n\n\ndef get_model_preamble_post_init_kwargs(cfg: DictConfig):\n NAME_TO_KWARGS = {\"vessel\": {\"seed\": cfg.seed}}\n try:\n kwargs = NAME_TO_KWARGS[cfg.model.name]\n except KeyError:\n raise ValueError(\n \"This model class either does not have a post_init or its post_init is not \"\n \"expected in preamble\"\n )\n return kwargs\n", "repo_name": "thesofakillers/CLAfICLe", "sub_path": "claficle/models/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 716, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "26", "api": [{"api_name": "claficle.models.sandwich.Sandwich", "line_number": 8, "usage_type": "name"}, {"api_name": "claficle.models.plain_gpt2.PlainGPT2", "line_number": 9, "usage_type": "name"}, {"api_name": "claficle.models.gewechselt.Gewechselt", "line_number": 10, "usage_type": "name"}, {"api_name": "claficle.models.vessel.Vessel", "line_number": 11, "usage_type": "name"}, {"api_name": "omegaconf.DictConfig", "line_number": 15, "usage_type": "name"}]} +{"seq_id": "37590665672", "text": "# -*- coding: utf-8 -*-\nfrom ppdai_utils import *\nimport pickle\nfrom keras.models import load_model\nfrom myloss import focal_loss\n\ncdict, emat = embedding('/files/faust/COMPETITION/ppdai/char_embed.txt')\nquestions = pickle.load(open('/files/faust/COMPETITION/ppdai/questions.pkl', 'rb'))\ntestpair = readtest()\n\n\nMAX_SEQUENCE_LENGTH = 60\ntestpair_idx = []\nfor q0, q1 in testpair:\n q0_chars = questions[q0]['cchars']\n q1_chars = questions[q1]['cchars']\n q0_idx = sent2idx(q0_chars, cdict, MAX_SEQUENCE_LENGTH)\n q1_idx = sent2idx(q1_chars, cdict, MAX_SEQUENCE_LENGTH)\n testpair_idx.append((q0_idx, q1_idx))\nprint(len(testpair_idx))\n\ntest_q1 = np.array([p[0] for p in testpair_idx])\ntest_q2 = np.array([p[1] for p in testpair_idx])\n\n\n###############################################\n# test\n###############################################\nmodel = load_model('ppdai_cnn.model')\npred_y = model.predict([test_q1, test_q2], batch_size=64)\nprint(pred_y.shape)\npred_y = np.reshape(pred_y, (len(pred_y),))\nmake_submission(pred_y, 'submission.csv')\n\n", "repo_name": "MingYates/QMATCH", "sub_path": "ppdai/ppdai_cnn_test.py", "file_name": "ppdai_cnn_test.py", "file_ext": "py", "file_size_in_byte": 1051, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "pickle.load", "line_number": 8, "usage_type": "call"}, {"api_name": "keras.models.load_model", "line_number": 29, "usage_type": "call"}]} +{"seq_id": "26609709198", "text": "from django.http import HttpRequest, HttpResponse, Http404\r\nfrom django.shortcuts import render\r\n\r\ncity = {\r\n 'msk': 'Москвы',\r\n 'spb': 'Питера',\r\n 'nsb': 'Новосибирска',\r\n 'ekb': 'ЕКБ',\r\n 'kaz': 'Казани',\r\n}\r\n\r\ntour_id = {}\r\nfor i in range(1000):\r\n tour_id[i] = i\r\n\r\n\r\ndef main_view(request: HttpRequest):\r\n return render(request, 'tours/index.html')\r\n\r\n\r\ndef departure_view(request, departure):\r\n try:\r\n departure_city = city[departure]\r\n except KeyError:\r\n raise Http404\r\n return render(request, 'tours/departure.html', context={'departure_view': departure_city})\r\n\r\n\r\ndef tour_view(request, id):\r\n try:\r\n tour_page = tour_id[id]\r\n except KeyError:\r\n raise Http404\r\n return render(request, 'tours/tour.html', context={'tour_view': tour_page})\r\n", "repo_name": "art213/stepik_demo", "sub_path": "stepik_tours/tours/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 847, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "django.http.HttpRequest", "line_number": 17, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 18, "usage_type": "call"}, {"api_name": "django.http.Http404", "line_number": 25, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 26, "usage_type": "call"}, {"api_name": "django.http.Http404", "line_number": 33, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 34, "usage_type": "call"}]} +{"seq_id": "1314294075", "text": "from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\n\nfrom .forms import CreateProfileForm, CreatePromDateForm\nfrom .models import Profile, PromDate\n\n# Create your views here.\n\ndef index(request):\n return render(request, 'promApp/index.html')\n\ndef about(request):\n return render(request, 'promApp/about.html')\n\ndef handler404(request, exception):\n return render(request, 'promApp/err404.html', status=404)\n \ndef handler500(request, *args, **argv): \n return render(request, 'promApp/err500.html', status=500)\n\ndef sorry(request):\n return render(request, \"promApp/sorry.html\")\n\ndef guide(request):\n return render(request, \"promApp/guide.html\")\n\n@login_required(login_url=\"/google/login\")\ndef app(request):\n if request.method == \"POST\":\n if \"profile\" in request.POST:\n profileForm = CreateProfileForm(data=request.POST)\n if profileForm.is_valid():\n profile = profileForm.save(commit=False)\n profile.owner = request.user \n profile.save()\n return redirect(\"promApp:app\")\n elif \"crush\" in request.POST:\n \n crushNameList = PromDate.objects.filter(profile=Profile.objects.filter(owner=request.user).first()).values_list('name', flat=True)\n \n crushName = request.POST['name'].title().strip()\n crushYear = request.POST['year']\n # if inputted name is same as self\n if crushName == request.user.get_full_name():\n return redirect(\"promApp:app\")\n \n # if inputted name already inputted\n if crushName in crushNameList:\n return redirect(\"promApp:app\")\n \n if crushYear == \"FR\" or crushYear == \"SO\":\n return redirect(\"promApp:sorry\")\n \n crushForm = CreatePromDateForm(data=request.POST)\n if crushForm.is_valid():\n crusher = Profile.objects.filter(owner=request.user).first()\n crush = crushForm.save(commit=False)\n crush.profile = crusher\n crush.name = crushName\n crush.save()\n return redirect(\"promApp:app\")\n \n return render(request, \"promApp/app.html\", context={})\n else:\n profileNotCreated = len(Profile.objects.filter(owner=request.user)) == 0\n profileForm = CreateProfileForm()\n crushForm = CreatePromDateForm()\n\n if not profileNotCreated:\n\n crusher = Profile.objects.filter(owner=request.user).first()\n \n if crusher.year == \"FR\" or crusher.year == \"SO\":\n return redirect(\"promApp:sorry\")\n\n remaining = 5-PromDate.objects.filter(profile=crusher).count()\n\n crushList = PromDate.objects.filter(profile=crusher).all()\n crushingOnMe = PromDate.objects.filter(name=request.user.get_full_name(), year=crusher.year)\n\n numCrushing = crushingOnMe.count()\n\n matches = []\n for person in crushingOnMe:\n for crush in crushList:\n\n if (person.profile.owner.get_full_name() == crush.name) and (crush.year == person.profile.year):\n matches.append((crush.name, person.profile.year))\n \n \n context = {\n \"remaining\" : remaining,\n \"matches\" : matches,\n \"profileNotCreated\" : profileNotCreated,\n \"profileForm\" : profileForm,\n \"crushForm\" : crushForm,\n \"crushList\": crushList,\n \"numCrushing\" : numCrushing,\n }\n else:\n \n context = {\n \"profileNotCreated\" : profileNotCreated,\n \"profileForm\" : profileForm,\n \"crushForm\" : crushForm,\n }\n\n return render(request, \"promApp/app.html\", context=context)\n\n\n\n\n\n", "repo_name": "EdwardX29/nwprom", "sub_path": "promApp/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 4003, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "django.shortcuts.render", "line_number": 10, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 13, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 16, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 19, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 22, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 25, "usage_type": "call"}, {"api_name": "forms.CreateProfileForm", "line_number": 31, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 36, "usage_type": "call"}, {"api_name": "models.PromDate.objects.filter", "line_number": 39, "usage_type": "call"}, {"api_name": "models.PromDate.objects", "line_number": 39, "usage_type": "attribute"}, {"api_name": "models.PromDate", "line_number": 39, "usage_type": "name"}, {"api_name": "models.Profile.objects.filter", "line_number": 39, "usage_type": "call"}, {"api_name": "models.Profile.objects", "line_number": 39, "usage_type": "attribute"}, {"api_name": "models.Profile", "line_number": 39, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 45, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 49, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 52, "usage_type": "call"}, {"api_name": "forms.CreatePromDateForm", "line_number": 54, "usage_type": "call"}, {"api_name": "models.Profile.objects.filter", "line_number": 56, "usage_type": "call"}, {"api_name": "models.Profile.objects", "line_number": 56, "usage_type": "attribute"}, {"api_name": "models.Profile", "line_number": 56, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 61, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 63, "usage_type": "call"}, {"api_name": "models.Profile.objects.filter", "line_number": 65, "usage_type": "call"}, {"api_name": "models.Profile.objects", "line_number": 65, "usage_type": "attribute"}, {"api_name": "models.Profile", "line_number": 65, "usage_type": "name"}, {"api_name": "forms.CreateProfileForm", "line_number": 66, "usage_type": "call"}, {"api_name": "forms.CreatePromDateForm", "line_number": 67, "usage_type": "call"}, {"api_name": "models.Profile.objects.filter", "line_number": 71, "usage_type": "call"}, {"api_name": "models.Profile.objects", "line_number": 71, "usage_type": "attribute"}, {"api_name": "models.Profile", "line_number": 71, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 74, "usage_type": "call"}, {"api_name": "models.PromDate.objects.filter", "line_number": 76, "usage_type": "call"}, {"api_name": "models.PromDate.objects", "line_number": 76, "usage_type": "attribute"}, {"api_name": "models.PromDate", "line_number": 76, "usage_type": "name"}, {"api_name": "models.PromDate.objects.filter", "line_number": 78, "usage_type": "call"}, {"api_name": "models.PromDate.objects", "line_number": 78, "usage_type": "attribute"}, {"api_name": "models.PromDate", "line_number": 78, "usage_type": "name"}, {"api_name": "models.PromDate.objects.filter", "line_number": 79, "usage_type": "call"}, {"api_name": "models.PromDate.objects", "line_number": 79, "usage_type": "attribute"}, {"api_name": "models.PromDate", "line_number": 79, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 108, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 27, "usage_type": "call"}]} +{"seq_id": "13897086625", "text": "\"\"\"\nbase_trainer.py has one class BaseTrainer.\n\nBaseTrainer provides base functionality for any trainer object.\nIt provides functionality to:\n - train for one epoch\n - validation \n - testing\n - freezing model\n - unfreezing model\n - saving checkpoint\n - loading checkpoint\n\"\"\"\nimport torch\nfrom torchvision import models\nimport math\nimport matplotlib.pyplot as plt\nimport copy\nimport os\nimport datetime\nfrom base import base_trainer\n\n\nclass BaseTrainer:\n \"\"\"Base Class for trainer/train.py.\"\"\"\n\n def __init__(self, model, train_dl, valid_dl, test_dl, criterion):\n \"\"\"Initialize the BaseTrainer object.\"\"\"\n self.model = model\n self.train_dl = train_dl\n self.valid_dl = valid_dl\n self.test_dl = test_dl\n self.criterion = criterion\n self.opt_lrs = []\n\n def train_epoch(self, optimizer, scheduler):\n \"\"\"\n Perform one training epoch.\n\n Parameters:\n optimizer - optimizer to use while training\n scheduler - scheduler to use while training\n Returns: training loss after epoch\n\n \"\"\"\n self.model.train()\n\n final_loss = None\n\n for inputs, labels in self.train_dl:\n\n inputs = inputs.to(self.device)\n labels = labels.to(self.device)\n loss = None\n\n optimizer.zero_grad()\n\n outputs = self.model(inputs)\n loss = self.criterion(outputs, labels)\n loss.backward()\n\n optimizer.step()\n self.opt_lrs.append(optimizer.state_dict()['param_groups'][0]['lr'])\n scheduler.step()\n\n final_loss = float(loss)\n\n del(loss)\n\n torch.cuda.empty_cache()\n\n del(inputs)\n del(labels)\n del(outputs)\n\n return final_loss\n\n def valid_epoch(self):\n \"\"\"\n Perform one validation epoch.\n\n Returns:\n val_loss - Validation loss \n val_acc - Validation accuracy\n\n \"\"\"\n self.model.eval()\n\n running_loss = 0.0\n running_corrects = 0\n\n with torch.no_grad():\n\n for val_inputs, val_labels in self.valid_dl:\n val_inputs = val_inputs.to(self.device)\n val_labels = val_labels.to(self.device)\n\n val_loss = None\n\n val_outputs = self.model(val_inputs)\n val_preds, val_indices = torch.max(val_outputs, dim=1)\n\n val_loss = self.criterion(val_outputs, val_labels)\n\n # float(val_loss) => the float() is the most important thing\n # to avoid cuda out of memory error\n # https://pytorch.org/docs/stable/notes/faq.html#my-model-reports-cuda-runtime-error-2-out-of-memory\n running_loss += float(val_loss)\n running_corrects += torch.sum(val_indices == val_labels)\n\n del(val_loss)\n\n torch.cuda.empty_cache()\n\n del(val_inputs)\n del(val_labels)\n del(val_outputs)\n\n epoch_loss = running_loss / len(self.valid_dl.dataset)\n epoch_acc = running_corrects.double() / len(self.valid_dl.dataset)\n\n return [epoch_loss, epoch_acc]\n\n def test_epoch(self):\n \"\"\"\n Perform a test epoch using current model.\n\n Returns accuracy on test set\n \"\"\"\n self.model.eval()\n\n corrects = 0\n print('Performing Test Epoch')\n for test_inputs, test_labels in self.test_dl:\n test_inputs = test_inputs.to(self.device)\n test_labels = test_labels.to(self.device)\n\n test_output = self.model(test_inputs)\n test_output_labels = torch.max(test_output, dim=1)[1]\n corrects += int(torch.sum(test_output_labels == test_labels))\n\n del(test_inputs)\n del(test_labels)\n del(test_output)\n\n return corrects/len(self.test_dl.dataset)\n\n def unfreeze(self):\n \"\"\"Unfreeze all layers of model.\"\"\"\n for param in self.model.parameters():\n param.requires_grad = True\n\n def freeze(self):\n \"\"\"Freeze all layers of model.\"\"\"\n for param in self.model.parameters():\n param.requires_grad = False\n\n def save_checkpoint(self, path, optimizer, scheduler, cycle, train_loss,\n valid_loss, valid_acc):\n \"\"\"\n Save checkpoint into given path.\n\n Parameters:\n path - path where checkpoint would be saved\n optimizer - optimizer's current state_dict to save\n scheduler - scheduler's current state_dict to save\n cycle - current cycle number (in SGDR) used for filename\n train_loss - training loss at the end of cycle \n valid_loss - validation loss at the end of cycle\n valid_acc - validation accuracy at the end of cycle\n\n \"\"\"\n state = {\n 'model': self.model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'scheduler': scheduler.state_dict(),\n 'cycle': cycle,\n 'train_loss': train_loss,\n 'valid_loss': valid_loss,\n 'valid_acc': valid_acc\n }\n\n filename = f'cycle_{cycle}'\n torch.save(state, f'{path}/{filename}')\n\n def load_checkpoint(self, path):\n \"\"\"\n Load checkpoint from given path.\n\n Returns state dictionary with keys:\n model - model's state dictionary\n optimizer - optimizer's state dictionary\n scheduler - scheduler's state dictionary\n cycle - cycle number when checkpoint was saved\n train_loss - training loss when checkpoint was saved\n valid_loss - validation loss when checkpoint was saved\n valid_acc - validation accuracy when checkpoint was saved\n\n \"\"\"\n state = torch.load(path)\n return state\n", "repo_name": "jayeshsaita/Speech-Commands-Recognition", "sub_path": "base/base_trainer.py", "file_name": "base_trainer.py", "file_ext": "py", "file_size_in_byte": 5873, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 35, "dataset": "github-code", "pt": "26", "api": [{"api_name": "torch.cuda.empty_cache", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 70, "usage_type": "attribute"}, {"api_name": "torch.no_grad", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 101, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 109, "usage_type": "call"}, {"api_name": "torch.cuda.empty_cache", "line_number": 113, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 113, "usage_type": "attribute"}, {"api_name": "torch.max", "line_number": 139, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 140, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 184, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 200, "usage_type": "call"}]} +{"seq_id": "70448737030", "text": "import itertools\nimport json\nimport math\nimport pprint\nimport time\n\nimport nltk\nfrom nltk import PorterStemmer\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.metrics import precision_score, f1_score, recall_score, average_precision_score\nfrom truecase import get_true_case\n\nfrom project_ex2 import getDataFromDir\nfrom project_ex3 import getAllCandidates, getTFIDFScore, listOfTaggedToString, getBM25Score\nimport sklearn.metrics\n\n# nltk.download('maxent_ne_chunker')\n# nltk.download('words')\nfrom project_p2_ex1 import Metrics, Helper\n\n\ndef createTargetList(reference, term_list):\n target = {}\n with open(reference) as f:\n reference_results = json.load(f)\n for i, (name, doc_values) in enumerate(reference_results.items()):\n classes = []\n\n for term in term_list[i]:\n\n values = list(itertools.chain.from_iterable(doc_values))\n\n porter = PorterStemmer()\n\n stemmed = \"\"\n\n for w in term.split():\n stemmed += porter.stem(w) + \" \"\n stemmed = stemmed[:-1]\n\n # s_term = porter.stem(term)\n\n if stemmed in values:\n classes.append(1)\n else:\n classes.append(0)\n\n target.update({name: classes})\n return target\n\n\ndef calculateParameters(all_cands, doc, scores):\n params = []\n\n max_cand_score = max(scores.values())\n\n for cand in all_cands:\n\n freq = doc.count(cand)\n\n if cand not in scores:\n cand_score = 0.\n else:\n cand_score = scores[cand] # / max_cand_score\n\n cand_len = len(cand)\n cand_term_count = len(cand.split())\n ne_cand = get_true_case(cand)\n words = nltk.pos_tag(nltk.word_tokenize(ne_cand))\n ne = nltk.tree2conlltags(nltk.ne_chunk(words))\n ne = [' '.join(word for word, pos, chunk in group).lower()\n for key, group in itertools.groupby(ne, lambda tpl: tpl[2] != 'O') if key]\n\n ne_cnt = len(ne[0].split()) if ne else 0\n\n first_match = doc.find(cand) / len(doc)\n last_match = doc.rfind(cand) / len(doc)\n\n # if cand_term_count == 1:\n # cohesion = 0.\n # else:\n # cohesion = cand_term_count * (1 + math.log(freq, 10)) * freq /\n\n if first_match == last_match:\n spread = 0.\n else:\n spread = last_match - first_match\n\n # print([cand_score, freq, cand_len, cand_term_count, first_match, last_match, spread, ne_cnt])\n\n params.append([cand_score, cand_len, cand_term_count, first_match, last_match, spread, ne_cnt]) #cand_score,\n return params\n\n\ndef calcResults(predicted, true):\n # , average_precision_score(true, predicted)\n return precision_score(true, predicted), recall_score(true, predicted), f1_score(true, predicted)\n\np_classifier = Perceptron(alpha=0.1)\n\ntrain = getDataFromDir('ake-datasets-master/datasets/500N-KPCrowd/train', mode='list')\ntrainStr = listOfTaggedToString(train)\n\ntest = getDataFromDir('ake-datasets-master/datasets/500N-KPCrowd/test', mode='list')\ntestStr = listOfTaggedToString(test)\n\nallCandidatesTrain = getAllCandidates(train)\nallCandidatesTest = getAllCandidates(test)\n\n\n# bm25\n# 0.3558736870896098\n# 0.7640337163696295\n# 0.4607649659785287\n\n# TF IDF\n# 0.37863851957992073\n# 0.31571002226187983\n# 0.3159382700815522\n\nbm25train = getBM25Score(train, mergetype='dict', min_df=1)\nbm25test = getBM25Score(test, mergetype='dict', min_df=1)\n\ntargets = createTargetList('ake-datasets-master/datasets/500N-KPCrowd/references/train.reader.stem.json',\n allCandidatesTrain)\n\ntestTargets = createTargetList('ake-datasets-master/datasets/500N-KPCrowd/references/test.reader.stem.json',\n allCandidatesTest)\n\nfor doc_index, doc_name in enumerate(train.keys()):\n allParams = calculateParameters(allCandidatesTrain[doc_index], trainStr[doc_index], bm25train[doc_name])\n if not targets[doc_name].count(0) == len(targets[doc_name]):\n p_classifier.fit(allParams, targets[doc_name])\n\nprint('predict')\n\nprecision = []\nrecall = []\nf1 = []\nap = []\ntr = Helper.getTrueKeyphrases('ake-datasets-master/datasets/500N-KPCrowd/references/test.reader.stem.json')\nkfs = {}\n\nfor doc_index, doc_name in enumerate(test.keys()):\n params = calculateParameters(allCandidatesTest[doc_index], testStr[doc_index], bm25test[doc_name])\n\n predicted = p_classifier.predict(params)\n plane = p_classifier.decision_function(params)\n true = testTargets[doc_name]\n\n print('PERCEPTRON')\n print(predicted)\n print('[P2]', plane)\n print('REALITY')\n print(true)\n\n rnk = {list(bm25test[doc_name].keys())[i]: v for i, v in enumerate(plane) if v > 0}\n rnk = list(dict(Helper.dictToOrderedList(rnk, rev=True)).keys())\n p, r, f = calcResults(predicted, true)\n kfs[doc_name] = rnk\n\n #precision.append(p)\n #recall.append(r)\n #f1.append(f)\n #ap.append(aps)\n\nmeanAPre, meanPre, meanRe, meanF1 = Helper.results(kfs, 'ake-datasets-master/datasets/500N-KPCrowd/references/test'\n '.reader.stem.json')\nprint('--RESULTS--')\nprint('Precision = ', meanPre)\nprint('Recall = ', meanRe)\nprint('F1 = ', meanF1)\nprint('Mean AVG Precision = ', meanAPre)\n\n# for dos documentos\n# para cada doc_name extrair candidatos\n# para cada candidato calcular os parâmetros\n\n# for dos documentos\n# passamos a lista que contem os parametros de todos os candidatos\n# calculamos a lista de resultados [ 0 0 0 1 0 0 1 ]\n# fit\n", "repo_name": "davidfrickert/PRI-19-20", "sub_path": "project_ex4.py", "file_name": "project_ex4.py", "file_ext": "py", "file_size_in_byte": 5597, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "json.load", "line_number": 25, "usage_type": "call"}, {"api_name": "itertools.chain.from_iterable", "line_number": 31, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 31, "usage_type": "attribute"}, {"api_name": "nltk.PorterStemmer", "line_number": 33, "usage_type": "call"}, {"api_name": "truecase.get_true_case", "line_number": 68, "usage_type": "call"}, {"api_name": "nltk.pos_tag", "line_number": 69, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 69, "usage_type": "call"}, {"api_name": "nltk.tree2conlltags", "line_number": 70, "usage_type": "call"}, {"api_name": "nltk.ne_chunk", "line_number": 70, "usage_type": "call"}, {"api_name": "itertools.groupby", "line_number": 72, "usage_type": "call"}, {"api_name": "sklearn.metrics.precision_score", "line_number": 97, "usage_type": "call"}, {"api_name": "sklearn.metrics.recall_score", "line_number": 97, "usage_type": "call"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 97, "usage_type": "call"}, {"api_name": "sklearn.linear_model.Perceptron", "line_number": 99, "usage_type": "call"}, {"api_name": "project_ex2.getDataFromDir", "line_number": 101, "usage_type": "call"}, {"api_name": "project_ex3.listOfTaggedToString", "line_number": 102, "usage_type": "call"}, {"api_name": "project_ex2.getDataFromDir", "line_number": 104, "usage_type": "call"}, {"api_name": "project_ex3.listOfTaggedToString", "line_number": 105, "usage_type": "call"}, {"api_name": "project_ex3.getAllCandidates", "line_number": 107, "usage_type": "call"}, {"api_name": "project_ex3.getAllCandidates", "line_number": 108, "usage_type": "call"}, {"api_name": "project_ex3.getBM25Score", "line_number": 121, "usage_type": "call"}, {"api_name": "project_ex3.getBM25Score", "line_number": 122, "usage_type": "call"}, {"api_name": "project_p2_ex1.Helper.getTrueKeyphrases", "line_number": 141, "usage_type": "call"}, {"api_name": "project_p2_ex1.Helper", "line_number": 141, "usage_type": "name"}, {"api_name": "project_p2_ex1.Helper.dictToOrderedList", "line_number": 158, "usage_type": "call"}, {"api_name": "project_p2_ex1.Helper", "line_number": 158, "usage_type": "name"}, {"api_name": "project_p2_ex1.Helper.results", "line_number": 167, "usage_type": "call"}, {"api_name": "project_p2_ex1.Helper", "line_number": 167, "usage_type": "name"}]} +{"seq_id": "34087072610", "text": "# %% [markdown]\n# # Credit-Score-Classification\n# \n# - Projeto de classificação de clientes de acordo com seus dados pessoais e financeiros. Dataset disponível em https://www.kaggle.com/laotse/credit-risk-dataset.\n# - GitHub : https://github.com/Ewertonv90/Credit-Score-Classification\n# \n# \n# \n# # EN\n# \n# Problem Statement\n# You are working as a data scientist in a global finance company. Over the years, the company has collected basic bank details and gathered a lot of credit-related information. The management wants to build an intelligent system to segregate the people into credit score brackets to reduce the manual efforts.\n# \n# Task\n# Given a person’s credit-related information, build a machine learning model that classifies the customer if credit can be released or not.\n# \n# # PT-BR\n# \n# Declaração do problema\n# Você está trabalhando como cientista de dados em uma empresa financeira global. Ao longo dos anos, a empresa coletou dados bancários básicos e reuniu muitas informações relacionadas a crédito. A gerência quer construir um sistema inteligente para segregar as pessoas em faixas de pontuação de crédito para reduzir os esforços manuais.\n# \n# Tarefa\n# Dadas as informações relacionadas ao crédito de uma pessoa, construa um modelo de aprendizado de máquina que possa classificar o cliente e se o crédito deve ser liberado ou não.\n# \n# Bussiness Sucess Criteria : more or equal to 85%\n# \n# \n# # Data dictonary\n# \n# \n# \n# - person_age = Age\n# - person_income\t = Annual Income\n# - personhomeownership\t = Home ownership\n# - personemplength\t = Employment length (in years)\n# - loan_intent\t = Loan intent\n# - loan_grade\t = Loan grade\n# - loan_amnt\t = Loan amount\n# - loanintrate\t = Interest rate\n# - loan_status\t = Loan status (0 is non default 1 is default)\n# - loanpercentincome\t = Percent income\n# - cbpersondefaultonfile\t = Historical default\n# - cbpresoncredhistlength\t= Credit history length\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import Normalizer\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.metrics import f1_score,accuracy_score, precision_score, recall_score\nimport joblib\n# Data Engeneering\n\ndf = pd.read_csv('data/credit_risk_dataset.csv')\n\nindex = df[ df['person_age'] >= 100 ].index\ndf.drop(index, inplace=True)\n\ndf = df.dropna(how=\"all\")\n\ndf = df.drop_duplicates(keep='first')\n\nX = df.drop(columns=['loan_status'])\ny = df['loan_status']\n\n\n\n# Train and Test split\nX_train, X_test, y_train, y_test = train_test_split(X, y , test_size=0.2, random_state=42)\n\n# PIPELINE\n\npipe = Pipeline(steps=[\n \n ('encoder', ColumnTransformer(\n [\n ('encoder_type', OneHotEncoder(drop='first'),['loan_intent','loan_grade','person_home_ownership', 'cb_person_default_on_file'])\n ]\n )\n ),\n ('imputer', SimpleImputer(strategy='mean',fill_value=np.nan)),\n ('normalizer', Normalizer()),\n ('classifier', GradientBoostingClassifier(max_depth=5, min_samples_split=3,\n n_estimators=300))\n ]\n)\n\n\npipe.fit(X_train, y_train)\n\nprint(round(pipe.score(X_train, y_train),4)*100, \"%\")\nprint(round(pipe.score(X_test, y_test),4)*100 , \"%\")\n\ny_pred = pipe.predict(X_test)\n\nparam_grid = {\n 'classifier__n_estimators' : [300],\n 'classifier__max_depth' : [5],\n 'classifier__min_samples_split': [3],\n}\n\n# param_grid = {\n# 'classifier__n_estimators' : [100, 200, 300],\n# 'classifier__learning_rate' : [0.1, 0.5, 1.0],\n# 'classifier__subsample': [0.1, 0.3, 0.5, 0.8, 1.0],\n# 'classifier__max_depth' : [1, 3, 5, 10],\n# 'classifier__min_samples_leaf' : [1,3, 5, 10],\n# 'classifier__min_samples_split': [2, 3, 5, 10],\n# }\n\ngrid = GridSearchCV(estimator=pipe, param_grid=param_grid,cv=3 , n_jobs= -1, verbose=0, )\ngrid.fit(X_train, y_train)\nprint(grid.score(X_train, y_train))\nprint(grid.score(X_test, y_test))\n\nf1 = round(f1_score(y_test, y_pred, average=\"micro\")*100, 2)\naccuracy = round(accuracy_score(y_test, y_pred)*100, 2)\nprecision = round(precision_score(y_test, y_pred)*100 , 2)\nrecall = round(recall_score(y_test, y_pred, average='micro')*100 , 2)\n\nprint(f\"F1 Score: {f1}%\")\nprint(f\"Accuracy Score: {accuracy}%\")\nprint(f\"Precision Score: {precision}%\")\nprint(f\"Recall Score: {recall}%\")\n\nmetrics = {}\n\nmetrics = {\n\n \"accuracy\" : accuracy,\n \"precision\" : precision,\n \"recall\" : recall,\n \"f1\" : f1\n }\n\nbest_pipeline = grid.best_estimator_\n\njoblib.dump(metrics, filename=\"log/model_score_train.pkl\")\njoblib.dump(best_pipeline, filename=\"src/deployment/models/model_pipeline.pkl\")\n\n\n\n\n", "repo_name": "Ewertonv90/Credit-Score-Classification_Risk", "sub_path": "src/deployment/train.py", "file_name": "train.py", "file_ext": "py", "file_size_in_byte": 5160, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "26", "api": [{"api_name": "pandas.read_csv", "line_number": 59, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 74, "usage_type": "call"}, {"api_name": "sklearn.pipeline.Pipeline", "line_number": 78, "usage_type": "call"}, {"api_name": "sklearn.compose.ColumnTransformer", "line_number": 80, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.OneHotEncoder", "line_number": 82, "usage_type": "call"}, {"api_name": "sklearn.impute.SimpleImputer", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 86, "usage_type": "attribute"}, {"api_name": "sklearn.preprocessing.Normalizer", "line_number": 87, "usage_type": "call"}, {"api_name": "sklearn.ensemble.GradientBoostingClassifier", "line_number": 88, "usage_type": "call"}, {"api_name": "sklearn.model_selection.GridSearchCV", "line_number": 116, "usage_type": "call"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 121, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 122, "usage_type": "call"}, {"api_name": "sklearn.metrics.precision_score", "line_number": 123, "usage_type": "call"}, {"api_name": "sklearn.metrics.recall_score", "line_number": 124, "usage_type": "call"}, {"api_name": "joblib.dump", "line_number": 143, "usage_type": "call"}, {"api_name": "joblib.dump", "line_number": 144, "usage_type": "call"}]} +{"seq_id": "73372784383", "text": "\"\"\"\nA module for aggregating the data from the off-chain sources. For the\nperp futures data there is an option of adding funding rates data.\n#####################################################################\nData format\nSPOT MARKET: 'ETHUSDT' or 'ethusdt'\nPERP MARKET: 'ALTUSDT-PERP' or 'altusdt-perp'\nFUTURES MARKET: 'BTCUSD-CURRENT' or 'btcusd-next'\nDVOL DATA: 'ETH-DVOL' or 'eth-dvol'\n\nOPTION DATA: 'ETH-OPT' or 'eth-opt'\n\"\"\"\n\n# pylint: disable=anomalous-backslash-in-string, too-many-instance-attributes, too-many-public-methods, too-many-arguments, too-many-locals, invalid-name\nimport re\nimport datetime\nimport itertools\nfrom typing import Union, List, Tuple, Dict, Any\nimport requests\nimport numpy as np\nimport pandas as pd\n\n\nclass DeFibulizer():\n \"\"\"\n Class for data aggregation and processing of the on-chain and off-chain data.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Class constructor.\n \"\"\"\n\n self.asset_names = None\n self.asset_types = None\n self.start_date = None\n self.end_date = None\n self.frequency = None\n self.get_funding_rate = None\n self.joint_dataframe = None\n self.allowed_dvol = ['ETH', 'BTC']\n\n @staticmethod\n def set_asset_name(asset_names: Union[str, List[str]]) -> np.ndarray:\n \"\"\"\n Checks whither the provided asset_names parameter type is correct and\n transforms the data into an uppercase list of strings if needed.\n :param asset_names: (str, List[str]) Provided list of asset names to\n retrieve data for.\n :return: (List[str]) List of the asset names to retrieve data for.\n \"\"\"\n # Performing the typing check and transformation.\n\n if isinstance(asset_names, str):\n\n # If the singular asset is provided transforming it into the list.\n asset_names = np.array([asset_names.upper()])\n\n elif isinstance(asset_names, list) and all(isinstance(asset, str) for asset in asset_names):\n\n # If multiple assets are provided in a form of the list keeping it intact.\n asset_names = np.array([name.upper() for name in asset_names])\n\n else:\n\n # Else raise type error.\n raise TypeError('Incorrect asset type, please provide either str or List[str].')\n\n return asset_names\n\n @staticmethod\n def set_date(date: Union[datetime.datetime, str]) -> int:\n \"\"\"\n Checks whither the provided dates parameter types are correct and\n transforms the data into an timestamps.\n :param date: (datetime.datetime/str)\n :return: (datetime.timestamp) Timestamp to retrieve data for.\n \"\"\"\n # Performing the type check and transformation.\n\n if isinstance(date, str):\n # Splitting the string into year month and day component.\n temp = date.split('-')\n\n # Transform the date into timestamp.\n date = datetime.datetime(int(temp[0]), int(temp[1]), int(temp[2])).timestamp()\n\n elif isinstance(date, datetime.datetime):\n\n # If multiple assets are provided in a form of the list keeping it intact.\n date = date.timestamp()\n else:\n\n # Else raise type error.\n raise TypeError('Incorrect date type, please provide either YYYY-MM-DD '\n 'or datetime.datetime.')\n\n return int(date)\n\n @staticmethod\n def set_frequency(frequency: str = 'h') -> Tuple[int, str]:\n \"\"\"\n Checks whether the provided frequency belongs to the range of available options\n and convert it into seconds.\n Options:\n m - minutely\n h - hourly\n d - daily\n :param frequency: (str) Desired data frequency in str format.\n :return: (int) Data frequency in seconds.\n \"\"\"\n # Initializing\n freq_str = ['m', 'h', 'd']\n freq_seconds = [60, 3600, 86400]\n\n adjust_for_binance = lambda el: '1' + el\n\n if frequency not in freq_str:\n # Raise type error if the frequency provided does not belong to the\n # list of possible options.\n raise TypeError('Incorrect frequency type, please provide either m, h or d.')\n\n # Finding the corresponding index in the freq_str\n index = freq_str.index(frequency)\n\n # Taking the equivalent value in seconds from the frec_seconds\n frequency = (freq_seconds[index], adjust_for_binance(freq_str[index]))\n\n return frequency\n\n def is_spot(self) -> list:\n \"\"\"\n Creates a boolean mask that returns true values if the asset belongs to spot market\n based on the provided asset symbol formatting.\n :return: (list) List of boolean indexes that showcase whether the asset\n belongs to the spot market.\n \"\"\"\n # Creating a regular expression pattern to recognize the assets from spot market.\n spot_pattern = re.compile('^([A-Z]+)$')\n\n # Applying the pattern to the asset names to create the boolean mask\n spot_mask = [bool(spot_pattern.match(name)) for name in self.asset_names]\n\n return spot_mask\n\n def is_perp(self) -> list:\n \"\"\"\n Creates a boolean mask that returNs true values if the asset belongs to future market\n and is a perpetual based on the provided asset symbol formatting.\n :return: (list) List of boolean indexes that showcase whether the asset belongs to\n the spot market.\n \"\"\"\n # Creating a regular expression pattern to recognize the assets from spot market.\n perp_pattern = re.compile('^([A-Z]+)[\\-](PERP)$')\n\n # Applying the pattern to the asset names to create the boolean mask\n perp_mask = [bool(perp_pattern.match(name)) for name in self.asset_names]\n\n return perp_mask\n\n def is_futures(self) -> list:\n \"\"\"\n Creates a boolean mask that returns true values if the asset belongs to future market\n and has an expiry date based on the provided asset symbol formatting.\n :return: (list) List of boolean indexes that showcase whether the asset belongs\n to the spot market.\n \"\"\"\n # Creating a regular expression pattern to recognize the assets from spot market.\n futures_pattern = re.compile('^([A-Z]+)[\\-](CURRENT|NEXT)$')\n\n # Applying the pattern to the asset names to create the boolean mask\n futures_mask = [bool(futures_pattern.match(name)) for name in self.asset_names]\n\n return futures_mask\n\n def is_dvol(self) -> list:\n \"\"\"\n Creates a boolean mask that returns true values if the asset asset_name reffers to DVOL\n data based on the provided asset symbol formatting.\n :return: (list) List of boolean indexes that showcase whether the asset belongs\n to the spot market.\n \"\"\"\n # Creating a regular expression pattern to recognize the assets from spot market.\n dvol_pattern = re.compile('^([A-Z]+)[\\-](DVOL)$')\n\n # Applying the pattern to the asset names to create the boolean mask\n dvol_mask = [bool(dvol_pattern.match(name)) for name in self.asset_names]\n\n return dvol_mask\n\n def is_option(self) -> list:\n \"\"\"\n Creates a boolean mask that returns true values if the asset asset_name reffers to option\n data based on the provided asset symbol formatting.\n\n :return: (list) List of boolean indexes that showcase whether the asset belongs\n to the spot market.\n \"\"\"\n # Creating a regular expression pattern to recognize the assets from spot market.\n dvol_pattern = re.compile('^([A-Z]+)[\\-](OPT)$')\n\n # Applying the pattern to the asset names to create the boolean mask\n dvol_mask = [bool(dvol_pattern.match(name)) for name in self.asset_names]\n\n return dvol_mask\n\n def asset_mapping(self):\n \"\"\"\n Maps the provided asset/assets to the class of asset it belongs to, returning the\n array of mapped values.\n Mappings:\n s - spot market assets\n p - perpetual futures\n f - regular futures\n v - volatility index\n o - options\n\n :return: (list) Asset mapping to the asset types.\n \"\"\"\n # Initializing the array for mapped values.\n asset_types = self.asset_names.copy()\n\n # Assigning the list of possible labels for the assets.\n asset_labels = ['s', 'p', 'f', 'v', 'o']\n\n # Creating the boolean masks for each type of assets.\n asset_masks = [self.is_spot(), self.is_perp(), self.is_futures(), self.is_dvol(), self.is_option()]\n\n # Mapping the labels.\n for label, mask in zip(asset_labels, asset_masks):\n asset_types[mask] = label\n\n for index, element in enumerate(asset_types):\n\n if element not in asset_labels:\n raise ValueError(f'The {index} element asset_name is provided incorrectly')\n\n return asset_types\n\n def get_binance_spot_query(self, asset_name: str) -> Dict[str, Union[Union[str, int], Any]]:\n \"\"\"\n Prepares the provided general data and the asset_name to transform into\n the required format for the Binance spot data request.\n :param asset_name: (str) The asset_name of the asset.\n :return: (list) Query details for the Binance data.\n \"\"\"\n\n start_date = int(self.start_date * 1e3)\n end_date = int(self.end_date * 1e3)\n interval = self.frequency[1]\n limit = 1000\n\n query = {'symbol': asset_name,\n 'interval': interval,\n 'startTime': start_date,\n 'endTime': end_date,\n 'limit': limit\n }\n\n return query\n\n def get_binance_futures_query(self, asset_name: str, asset_type: str):\n \"\"\"\n Prepares the provided general data and the asset_name to transform into\n the required format for the Binance futures data request.\n :param asset_name: (str) The asset_name of the asset.\n :param asset_type: (str) The type of the futures - finite or perpetual.\n :return: (list) Query details for the Binance data.\n \"\"\"\n # Setup the initial data parameters\n start_date = int(self.start_date * 1e3)\n end_date = int(self.end_date * 1e3)\n limit = 1000\n interval = self.frequency[1]\n name, contract_type = asset_name.split('-')\n\n # Complete the string for the contract type\n if asset_type == 'p':\n string_completion = 'ETUAL'\n elif asset_type == 'f':\n string_completion = '_QUARTER'\n else:\n raise ValueError('Incorrect asset type literal.')\n\n contract_type += string_completion\n\n query = {'pair': name,\n 'contractType': contract_type,\n 'interval': interval,\n 'startTime': start_date,\n 'endTime': end_date,\n 'limit': limit\n }\n\n return query\n\n def get_binance_funding_query(self, asset_name: str):\n \"\"\"\n Prepares the provided general data and the asset_name to transform into\n the required format for the Binance funding rate data request.\n :param asset_name: (str) The asset_name of the asset.\n :return: (list) Query details for the Binance data.\n \"\"\"\n # Setup the initial data parameters\n start_date = int(self.start_date * 1e3)\n end_date = int(self.end_date * 1e3)\n limit = 1000\n name, _ = asset_name.split('-')\n\n query = {'symbol': name,\n 'startTime': start_date,\n 'endTime': end_date,\n 'limit': limit\n }\n\n return query\n\n @staticmethod\n def get_url(query: dict, data_type: str) -> List[Union[str, dict]]:\n \"\"\"\n Creates url string to be used in API call\n :param query: (dict) Dict of the key query parameters.\n :param data_type: (str) The type of the URL request to construct.\n Input options: 'binance_spot'; 'binance_funding'; 'deribit_dvol'\n :return: (list) URL for the data request and a dict of request parameters.\n \"\"\"\n params = query\n\n if data_type == 'binance_spot':\n # Constructing an URL for the spot/futures/perp price data request\n url = 'https://api.binance.com/api/v3/klines'\n\n if data_type == 'binance_futures':\n url = 'https://fapi.binance.com/fapi/v1/continuousKlines'\n\n elif data_type == 'binance_funding':\n\n # Constructing an URL for the funding rate request\n url = 'https://fapi.binance.com/fapi/v1/fundingRate'\n\n elif data_type == 'deribit_dvol':\n\n # Constructing an URL for the DVOL price data request\n url = 'https://www.deribit.com/api/v2/public/get_volatility_index_data?'\n\n elif data_type == 'deribit_option':\n\n # Constructing an URL for the Derobit option trade data request\n url = 'https://history.deribit.com/api/v2/public/get_last_trades_by_currency_and_time?'\n\n else:\n\n # Else raise type error.\n raise TypeError('Incorrect URL type')\n\n output = [url, params]\n\n return output\n\n def get_deribit_query(self, name: str, asset_type: str) -> Dict[str, Union[Union[str, int, float], Any]]:\n \"\"\"\n Prepares the provided general data and the asset_name to transform into\n the required format for the Deribit data.\n :param name: (str) The asset_name of the asset.\n :param asset_type: (str) The type of the deribit data to request - dvol or options.\n :return: (list) Query details for the Deribit data.\n \"\"\"\n # Select only the part relevant to the query\n name = name.split('-')[0]\n\n # Adjust the timestamp to be in ms\n start_date = int(self.start_date * 1e3)\n end_date = int(self.end_date * 1e3)\n\n frequency = self.frequency[0]\n\n # Adjust the symbol for daily data\n if frequency == 86400:\n frequency = '1D'\n\n # Set up the base deribit query parameters\n query = {'currency': name,\n 'start_timestamp': start_date,\n 'end_timestamp': end_date\n }\n\n # Add asset-specific query parameters\n if asset_type == 'v':\n query['resolution'] = frequency\n\n elif asset_type == 'o':\n query['kind'] = 'option'\n query['count'] = 1e4\n query['include_old'] = 'true'\n\n else:\n raise ValueError('Incorrect asset type literal.')\n\n # query = [name, start_date, end_date, frequency]\n\n return query\n\n def get_fractional_binance_request(self, query: dict, data_type: str) -> list:\n \"\"\"\n Generator function that generates Binance request results for the fractions of\n the data range until the whole data range is processed.\n :param query: (list) The list of API query parameters:\n [asset_names, start_date, end_date, frequency].\n :param data_type: (str) The type of data that needs to be downloaded 'binance_spot'or\n 'binance_funding'\n \"\"\"\n # Getting the start and end date from the initial query\n start_date = query['startTime']\n end_date = query['endTime']\n\n # Establishing an appropriate step for the request, -1 to avoid jumping over the 9th hours\n step = int(query['limit'] * self.frequency[0] * 1e3 - 1)\n\n # Starting a cycle of generating the outcomes of fractional requests until\n # the whole data range is processed\n\n\n for start_time in range(start_date, end_date, step):\n\n # Calculating an end_time of a fraction\n end_time = min(start_time + step, end_date)\n\n # Set the new start/end time for the fractional query\n query['startTime'] = start_time\n query['endTime'] = end_time\n # Creating an URL for the request\n url, params = self.get_url(query, data_type)\n\n # Trying getting the results of the query\n resp = requests.get(url, params=params).json()\n\n if isinstance(resp, dict):\n msg = 'msg'\n raise ValueError(f'{resp[msg]}')\n\n # Yielding the request results\n yield resp\n\n def get_fractional_deribit_request(self, query: dict) -> list:\n \"\"\"\n Generator function that generates deribit request results for the fractions\n of the data range until the whole data range is processed.\n :param query: (list) The list of API query parameters:\n [asset_names, start_date, end_date, frequency].\n \"\"\"\n # Setting the continuation as the end date\n continuation = query['end_timestamp']\n currency = 'currency'\n\n while continuation is not None:\n\n query['end_timestamp'] = continuation\n\n # Creating an URL for the request\n continuation_url, params = self.get_url(query, 'deribit_dvol')\n\n # Trying to get the request and return an exception otherwise\n try:\n resp = requests.get(continuation_url, params=params).json()['result']\n except TypeError as type_err: # pragma: no cover\n raise TypeError(f'The provided {query[currency]} deribit data is incorrect.') from type_err\n except KeyError as key_err: # pragma: no cover\n raise KeyError(requests.get(continuation_url, params=params).json()['error']) from key_err\n\n data = resp['data']\n\n yield data\n\n continuation = resp['continuation'] # pragma: no cover\n\n def get_fractional_deribit_option_request(self, query: dict) -> list:\n \"\"\"\n Generator function that generates deribit request option trades results for the fractions\n of the data range until the whole data range is processed.\n\n :param query: (list) The list of API query parameters:\n [asset_names, start_date, end_date, frequency].\n \"\"\"\n # Setting the continuation as the end date\n continuation = query['start_timestamp']\n\n currency = 'currency'\n\n has_more = True\n\n while has_more:\n\n query['start_timestamp'] = continuation\n\n # Creating an URL for the request\n continuation_url, params = self.get_url(query, 'deribit_option')\n\n # Trying to get the request and return an exception otherwise\n try:\n resp = requests.get(continuation_url, params=params).json()['result']\n except TypeError as type_err: # pragma: no cover\n raise TypeError(f'The provided {query[currency]} option data is incorrect.') from type_err\n except KeyError as key_err: # pragma: no cover\n raise KeyError(requests.get(continuation_url, params=params).json()['error']) from key_err\n\n data = resp['trades']\n\n yield data\n\n continuation = resp['trades'][-1]['timestamp'] # pragma: no cover\n\n has_more = resp['has_more']\n\n def get_binance_data(self, query: dict, data_type: str) -> list:\n \"\"\"\n Retrieves the raw json data from the Binance API according to passed query\n parameters. The query provided has to include the asset asset_name, start and end\n dates for the required data and the frequency. The retrieved data is then\n transformed into a single list.\n :param query: (list) The list of API query parameters:\n [asset_names, start_date, end_date, frequency].\n :return: (list) List of data for the provided query date range, data format:\n [startTime, time, open, high, low, close, volume].\n \"\"\"\n\n # Get the Binance request generator\n binance_generator = self.get_fractional_binance_request(query=query,\n data_type=data_type)\n\n # Create a list from the generator for the Binance requests\n output = list(itertools.chain.from_iterable(binance_generator))\n\n return output\n\n def get_deribit_data(self, query: dict, is_option: bool = True) -> dict:\n \"\"\"\n Retrieves the raw vol data from the Deribit API according to passed query\n parameters. The query provided has to include the asset asset_name, start and end dates for\n the required data and the frequency. The retrieved data is then transformed into\n a single list.\n :param query: (list) The list of API query parameters:\n [asset_names, start_date, end_date, frequency]\n :return: (list) List of data for the provided query date range, data format:\n [time, open, high, low, close].\n \"\"\"\n # Check whether the token has data available\n if not query['currency'] in self.allowed_dvol:\n raise ValueError('The dvol data for this asset is not available')\n\n # Getting the deribit request generator\n if is_option:\n deribit_generator = self.get_fractional_deribit_option_request(query=query)\n else:\n deribit_generator = self.get_fractional_deribit_request(query=query)\n\n # Getting the full list of data for the whole range of dates from generator\n unchained_output = list(itertools.chain.from_iterable(deribit_generator))\n output = list(itertools.chain(unchained_output))\n\n return output\n\n @staticmethod\n def dvol_data_processing(raw_data: dict, asset_names: str) -> pd.DataFrame:\n \"\"\"\n Creates an organized pandas DataFrame from the raw data collected from the\n Deribit API calls.\n :param raw_data: (pd.DataFrame) Raw list of dictionaries containing the API request output.\n :param asset_names: (str) The asset_name of the asset.\n :return: (pd.DataFrame) Query details for the Deribit data.\n \"\"\"\n\n # Creating a pd.DataFrame from the raw data\n dataframe = pd.DataFrame(raw_data)\n\n # Establishing the column names\n dataframe.columns = ['time', 'open', 'high', 'low', 'close']\n\n dataframe = dataframe.sort_values(by=['time'])\n\n # Add the datetime index\n timestamp_temp = pd.to_datetime(dataframe.time, unit='ms', utc=True)\n\n dataframe.set_index(timestamp_temp, inplace=True)\n\n # Add a MultiIndex\n dataframe.columns = pd.MultiIndex.from_product([[asset_names], dataframe.columns])\n\n return dataframe\n\n @staticmethod\n def option_data_processing(raw_data: dict) -> pd.DataFrame:\n \"\"\"\n Creates an organized pandas DataFrame from the raw options data collected from the\n Deribit API calls.\n\n :param raw_data: (pd.DataFrame) Raw list of dictionaries containing the API request output.\n\n :return: (pd.DataFrame) Query details for the Deribit data.\n \"\"\"\n\n # Creating a pd.DataFrame from the raw data\n dataframe = pd.DataFrame.from_dict(raw_data)\n\n # Establishing the column names\n temp_timestamp = pd.to_datetime(dataframe.timestamp, unit='ms')\n\n dataframe = dataframe.sort_values(by=['timestamp'])\n\n temp = dataframe.instrument_name.str.split('-').tolist()\n\n dataframe[['asset', 'expiry_date', 'strike', 'option_type']] = pd.DataFrame(temp, index=dataframe.index)\n\n convert_expiry = lambda date: datetime.datetime.strptime(date, '%d%b%y')\n\n dataframe.expiry_date = dataframe.expiry_date.apply(convert_expiry)\n\n dataframe.strike = pd.to_numeric(dataframe.strike)\n\n # Add the datetime index\n\n dataframe.set_index(temp_timestamp, inplace=True)\n\n return dataframe\n\n @staticmethod\n def binance_data_processing(raw_data: list,\n asset_name: str,\n raw_funding_rates=None) -> pd.DataFrame:\n \"\"\"\n Creates an organized pandas DataFrame from the raw data collected from the\n Binance API calls.\n :param raw_data: (pd.DataFrame) Raw list of dictionaries containing the API request output\n :param asset_name: (str) The asset_name of the asset.\n :param raw_funding_rates: (pd.DataFrame) Raw list of dictionaries containing the API\n request output for the funding rates.\n :return: (pd.DataFrame) Query details for the Deribit data.\n \"\"\"\n\n # Creating a pd.DataFrame from the raw data\n dataframe = pd.DataFrame(raw_data)\n\n columns = ['open_time', 'open', 'high',\n 'low', 'close', 'volume',\n 'close_time', 'quote_asset_volume',\n 'number_of_trades', 'taker_buy_volume',\n 'taker_buy_quote_asset_volume', 'drop']\n\n dataframe.columns = columns\n\n convert_to_date = lambda col: pd.to_datetime(col, unit='ms', utc=True)\n\n if raw_funding_rates is not None:\n # Creating the funding rates dataframe\n funding_dataframe = pd.DataFrame(raw_funding_rates)\n # Merging the funding data with the original perp dataframe\n dataframe = dataframe.merge(funding_dataframe, how='left',\n left_on='open_time', right_on='fundingTime')\n\n dataframe.drop(['fundingTime', 'symbol'], axis=1, inplace=True)\n\n dataframe.drop(['drop'], axis=1, inplace=True)\n\n time_related_subset = dataframe.filter(regex='time')\n not_time_subset = dataframe.filter(regex='^((?!time).)*$')\n\n dataframe[time_related_subset.columns] = time_related_subset.apply(convert_to_date)\n\n # Add the datetime index\n timestamp_temp = pd.to_datetime(dataframe.open_time, unit='ms', utc=True)\n\n dataframe.set_index(timestamp_temp, inplace=True)\n\n dataframe[not_time_subset.columns] = dataframe[not_time_subset.columns].astype(float)\n\n # Adding a MultiIndex\n dataframe.columns = pd.MultiIndex.from_product([[asset_name], dataframe.columns])\n\n return dataframe\n\n def get_spot_data(self, data: list, asset_name: str):\n \"\"\"\n Runs the procedure to form a request, get and postprocess the spot\n data. Then the dataframe is appended to the list of the dataframes.\n\n :param data: (list) The list of dataframes for all the retrieved data.\n :param asset_name: (str) The name of the asset to retrieve.\n \"\"\"\n # Creating a query variables list\n query = self.get_binance_spot_query(asset_name)\n # Getting the raw data from the Binance API\n raw_data = self.get_binance_data(query, 'binance_spot')\n # Appending the processed dataframe\n data.append(self.binance_data_processing(raw_data, asset_name))\n\n def get_perp_data(self, data: list, asset_name: str):\n \"\"\"\n Runs the procedure to form a request, get and postprocess the perpetual futures\n data. Then the dataframe is appended to the list of the dataframes.\n\n :param data: (list) The list of dataframes for all the retrieved data.\n :param asset_name: (str) The name of the asset to retrieve.\n \"\"\"\n asset_type = 'p'\n\n # Creating a query variables list for the perp\n query = self.get_binance_futures_query(asset_name, asset_type)\n # Getting the raw data from the Binance API\n raw_data = self.get_binance_data(query, 'binance_futures')\n\n # If there is a flag for getting the funding rate start the procedure\n if self.get_funding_rate:\n # Creating a query variables list for the perp funding rates\n query = self.get_binance_funding_query(asset_name)\n # Getting the raw funding rates data from the Binance API\n raw_funding_rates = self.get_binance_data(query, 'binance_funding')\n # Appending the processed dataframe\n data.append(self.binance_data_processing(raw_data, asset_name, raw_funding_rates))\n\n else:\n # Appending the processed dataframe\n data.append(self.binance_data_processing(raw_data, asset_name))\n\n def get_futures_data(self, data: list, asset_name: str):\n \"\"\"\n Runs the procedure to form a request, get and postprocess the finite futures\n data. Then the dataframe is appended to the list of the dataframes.\n\n :param data: (list) The list of dataframes for all the retrieved data.\n :param asset_name: (str) The name of the asset to retrieve.\n \"\"\"\n asset_type = 'f'\n\n # Creating a query variables list for the future\n query = self.get_binance_futures_query(asset_name, asset_type)\n # Getting the raw data from the Binance API\n raw_data = self.get_binance_data(query, 'binance_futures')\n # Appending the processed dataframe\n data.append(self.binance_data_processing(raw_data, asset_name))\n\n def get_options_data(self, data: list, asset_name: str):\n \"\"\"\n Runs the procedure to form a request, get and postprocess the Deribit options\n data. Then the dataframe is appended to the list of the dataframes.\n\n :param data: (list) The list of dataframes for all the retrieved data.\n :param asset_name: (str) The name of the asset to retrieve.\n \"\"\"\n asset_type = 'o'\n # Creating a query variables list for the future\n query = self.get_deribit_query(asset_name, asset_type)\n # Getting the raw data from the Deribit API\n raw_data = self.get_deribit_data(query, is_option=True)\n # Appending the processed dataframe\n data.append(self.option_data_processing(raw_data))\n\n def get_dvol_data(self, data: list, asset_name: str):\n \"\"\"\n Runs the procedure to form a request, get and postprocess the volatility index\n data. Then the dataframe is appended to the list of the dataframes.\n\n :param data: (list) The list of dataframes for all the retrieved data.\n :param asset_name: (str) The name of the asset to retrieve.\n \"\"\"\n asset_type = 'v'\n\n # Creating a query variables list for the future\n query = self.get_deribit_query(asset_name, asset_type)\n # Getting the raw data from the Deribit API\n raw_data = self.get_deribit_data(query, is_option=False)\n # Appending the processed dataframe\n data.append(self.dvol_data_processing(raw_data, asset_name))\n\n def init_asset_getter_dict(self):\n \"\"\"\n Creates a dictionary of data retrieving procedures corresponding to\n respective types of assets.\n\n :return: (dict) Dictionary with the asset types as key and processing\n functions as values.\n \"\"\"\n asset_types = ['s', 'p', 'f', 'v', 'o']\n\n data_getters = [self.get_spot_data,\n self.get_perp_data,\n self.get_futures_data,\n self.get_dvol_data,\n self.get_options_data]\n\n output = dict(map(lambda i, j: (i, j), asset_types, data_getters))\n\n return output\n\n def get_data(self,\n asset_names: Union[str, List[str]] = None,\n start_date: Union[datetime.datetime, str] = None,\n end_date: Union[datetime.datetime, str] = None,\n frequency: str = 'm',\n get_funding_rate: bool = False,\n joint_dataframe=True,\n save_csv: bool = False) -> Union[pd.DataFrame, List[pd.DataFrame]]:\n \"\"\"\n Gathers the available instrument data in a requested data range for every\n instance in the provided asset_names list. The data is gathered using the\n respective API - Binance or Deribit. Obtained raw data is then processed into\n a single concatenated dataframe for all assets/list of data frames for\n each individual asset data.\n :param asset_names: (str, List[str]) List of asset names to retrieve data for.\n :param start_date: (datetime.datetime, str) Beginning of data range. Str format\n should be YYYY-MM-DD.\n :param end_date: (datetime.datetime, str) End of the data range. tr format\n should be YYYY-MM-DD.\n :param frequency: (str) The wanted data frequency. Available formats:\n 'm' - minutely; 'h' - hourly; 'd' - daily.\n :param get_funding_rate: (bool) Flag whether to retrieve the funding rate data\n for the perpetual futures.\n :param joint_dataframe: (bool) Flag whether to return a joint dataframe or a list\n of separate dataframes.\n :param save_csv: (bool) Flag whether to save the dataframe on users system.\n :return: (pd.DataFrame, List[pd.DataFrame]) Processed data.\n \"\"\"\n # Setting all the attributes from the provided arguments\n self.asset_names = self.set_asset_name(asset_names)\n # Mapping the asset names to the asset type\n self.asset_types = self.asset_mapping()\n # Transforming the start and end date into int(timestamps)\n self.start_date = self.set_date(start_date)\n self.end_date = self.set_date(end_date)\n # Setting the data frequency\n self.frequency = self.set_frequency(frequency)\n # Setting the flags rom the provided\n self.get_funding_rate = get_funding_rate\n self.joint_dataframe = joint_dataframe\n\n # Checking whether the start and end dates are valid\n if self.start_date > self.end_date:\n raise ValueError('End date can not precede the start date.')\n\n # Initializing the data list\n data = []\n\n fill_in_parameters = lambda func: func(data=data, asset_name=asset_name)\n\n # Initialize the dictionary of a getter functions for respective asset types\n data_getter = self.init_asset_getter_dict()\n\n if 'o' in self.asset_types:\n joint_dataframe = False\n\n # For every asset in provided list get the data from the respective API\n for asset_type, asset_name in zip(self.asset_types, self.asset_names):\n\n # If the asset belongs to spot market, perpetual futures, finite futures\n # options or Deribit volatility indexes - start the respective procedure\n fill_in_parameters(data_getter[asset_type])\n\n # Concatenating the dataframes if the flag is true\n if joint_dataframe:\n for el in data:\n ind = el[el.index.duplicated()].index\n el.drop(ind, axis=0, inplace=True)\n output_data = pd.concat(data, axis=1)\n\n output_data.index.name = 'time'\n\n # Saving the data if the flag is true\n self.save_csv(data, save_csv)\n else:\n output_data = data\n\n return output_data\n\n def save_csv(self, data: Union[list, pd.DataFrame] = None, flag: bool = True, test: bool = False) -> None:\n \"\"\"\n Saves data in a *.csv data format.\n :param data: (list/pd.DataFrame) Data to be saved.\n :param flag: (bool) A flag signifying whether to save the files\n :param test: (bool) A flag signifying whether it is in a unit test or not.\n \"\"\"\n if flag:\n if isinstance(data, pd.DataFrame):\n if not test: # pragma: no cover\n dataframe_name = '_'.join(self.asset_names)\n data.to_csv(f'{dataframe_name}.csv')\n\n else:\n # If data is a list - save as separate entities\n if not test: # pragma: no cover\n for name, dataframe in zip(self.asset_names, data):\n dataframe.to_csv(f'{name}.csv')\n\n @staticmethod\n def load_csv(file_name: str) -> pd.DataFrame:\n \"\"\"\n Assists the users with reading the MultiIndex csv DataFrame.\n :param file_name: (str) Name of the saved DeFibulizer dataframe or the path to the file.\n :return: (pd.DataFrame) The correctly formatted dataframe from the saved csv file.\n \"\"\"\n # Reading the csv specifying the levels and indexes\n output = pd.read_csv(file_name, header=[0, 1], index_col=0)\n\n return output\n", "repo_name": "Brahma-fi/brahma-vaults-backtests", "sub_path": "modules/defibulizer/offchain_defibulizer.py", "file_name": "offchain_defibulizer.py", "file_ext": "py", "file_size_in_byte": 36717, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "typing.Union", "line_number": 44, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 44, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 44, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 72, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 72, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 86, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 88, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 101, "usage_type": "name"}, {"api_name": "re.compile", "line_number": 139, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 154, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 169, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 184, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 200, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 240, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 240, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 240, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 319, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 319, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 360, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 360, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 360, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 435, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 464, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 468, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 500, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 504, "usage_type": "call"}, {"api_name": "itertools.chain.from_iterable", "line_number": 531, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 531, "usage_type": "attribute"}, {"api_name": "itertools.chain.from_iterable", "line_number": 557, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 557, "usage_type": "attribute"}, {"api_name": "itertools.chain", "line_number": 558, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 573, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 581, "usage_type": "call"}, {"api_name": "pandas.MultiIndex.from_product", "line_number": 586, "usage_type": "call"}, {"api_name": "pandas.MultiIndex", "line_number": 586, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 563, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame.from_dict", "line_number": 602, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 602, "usage_type": "attribute"}, {"api_name": "pandas.to_datetime", "line_number": 605, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 611, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 613, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 613, "usage_type": "attribute"}, {"api_name": "pandas.to_numeric", "line_number": 617, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 591, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 640, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 650, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 654, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 669, "usage_type": "call"}, {"api_name": "pandas.MultiIndex.from_product", "line_number": 676, "usage_type": "call"}, {"api_name": "pandas.MultiIndex", "line_number": 676, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 628, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 794, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 794, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 795, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 795, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 796, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 796, "usage_type": "attribute"}, {"api_name": "pandas.concat", "line_number": 861, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 800, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 800, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 800, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 872, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 872, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 880, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 899, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 892, "usage_type": "attribute"}]} +{"seq_id": "4045120204", "text": "import json\nimport random\n\nfrom data.dimo_loader import DimoLoader\nfrom pathlib import Path\nfrom typing import List, Tuple\nimport numpy as np\nfrom bop_toolkit_lib import misc, visibility, inout, renderer\nimport os\nimport shutil\nimport cv2\n\n\ndimo_data = {\n 'im_width': 2560,\n 'im_height': 2048\n}\n\n\ndef create_or_ignore_folder(path: str):\n if not os.path.exists(path):\n os.mkdir(path)\n\n\ndef create_or_empty_folder(path: str):\n if os.path.exists(path):\n shutil.rmtree(path)\n os.mkdir(path)\n\n\ndef get_file_count(path: str) -> int:\n if not os.path.exists(path):\n return 0\n else:\n return len(os.listdir(path))\n\n\ndef create_dimo_masks(path: str, subsets: List[str], override: bool = False) -> None:\n \"\"\"\n Generates the visible mask for each object in each image.\n Masks are saved separately as a binary image for each object under {scene_id}/masks/{image_id}/{object_no}.png\n :param override: masks that are already generated are ignored if set to false, otherwise new masks are generated\n :param path: path to DIMO dataset\n :param subsets: subsets of dimo dataset to generate masks for (eg. sim_jaigo)\n \"\"\"\n dimo_loader = DimoLoader()\n dimo_ds = dimo_loader.load(Path(path), cameras=subsets)\n\n for subset_name in subsets:\n subset = dimo_ds[subset_name]\n models = dimo_ds['models']\n\n ren = renderer.create_renderer(dimo_data['im_width'], dimo_data['im_height'], renderer_type='vispy', mode='depth')\n for model in models:\n ren.add_object(model['id'], model['cad'])\n\n for scene in subset:\n masks_path = os.path.join(scene['path'], 'mask_visib/')\n print(f\"Processing {scene['path']}\")\n\n if get_file_count(masks_path) == sum([len(image['objects']) for image in scene['images']]):\n continue\n\n if override:\n create_or_empty_folder(masks_path)\n else:\n create_or_ignore_folder(masks_path)\n\n render_scene_masks(scene, ren)\n\n\ndef render_scene_masks(scene: dict, ren: renderer):\n masks_path = os.path.join(scene['path'], 'mask_visib/')\n\n for image in scene['images']:\n camera = image['camera']\n\n K = camera['K']\n fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2]\n\n dist_image = np.array(np.ones((dimo_data['im_height'], dimo_data['im_width'])) * np.inf)\n distance_maps = []\n for object in image['objects']:\n depth_gt = \\\n ren.render_object(object['id'], np.array(object['cam_R_m2c']).reshape(3, 3), np.array(object['cam_t_m2c']),\n fx, fy, cx, cy)['depth']\n dist_gt = misc.depth_im_to_dist_im_fast(depth_gt, K)\n\n # set zero depths to infinity to compute closest object for total depth map\n dist_gt[dist_gt == 0] = np.inf\n dist_image = np.minimum(dist_image, dist_gt)\n\n dist_gt[dist_gt == np.inf] = 0\n distance_maps.append(dist_gt)\n\n dist_image[dist_image == np.inf] = 0\n\n for object_no, dist_map in enumerate(distance_maps):\n object_mask_path = os.path.join(masks_path, f\"{str(image['id']).zfill(6)}_{str(object_no).zfill(6)}.png\")\n mask_visib = visibility.estimate_visib_mask_gt(dist_image, dist_map, 1, visib_mode='bop19') * 255\n inout.save_im(object_mask_path, np.array(mask_visib, dtype=np.uint8))\n\n\ndef create_dimo_scene_masks(path: str, subset: str, scene_id: int) -> None:\n dimo_loader = DimoLoader()\n dimo_ds = dimo_loader.load(Path(path), cameras=[subset])\n\n subset = dimo_ds[subset]\n models = dimo_ds['models']\n\n ren = renderer.create_renderer(dimo_data['im_width'], dimo_data['im_height'], renderer_type='vispy', mode='depth')\n for model in models:\n ren.add_object(model['id'], model['cad'])\n\n for scene in subset:\n if scene['id'] == scene_id:\n masks_path = os.path.join(scene['path'], 'mask_visib/')\n\n print(f\"Processing {scene['path']}\")\n create_or_empty_folder(masks_path)\n render_scene_masks(scene, ren)\n\n\ndef create_dimo_train_split(path: str, subsets: List[str], train: float = 0.9, val: float = 0.05, test: float = 0.05, seed: int = None, split_scenes: bool = False) -> None:\n \"\"\"\n Given the path to a dimo dataset, this function will split the scenes of the given subsets in training, validation\n and testing dataset. The function creates files of name {split}.txt\n :param path: path to the dimo dataset\n :param subsets: subsets to generate split for\n :param train: portion of scenes to be training dataset\n :param val: portion of scenes to be validation dataset\n :param test: portion of scenes to be test dataset\n :param seed: optionally set random seed\n :param split_scenes:if set to true the split are based on the scenes, otherwise on the images\n :return:\n \"\"\"\n def get_scenes_split(subset: list) -> Tuple[List[str], List[str], List[str]]:\n scenes = subset\n random.shuffle(scenes)\n\n train_ids = [f\"{scene['id']}_{image['id']}\" for scene in scenes[:int(train * len(scenes))] for image in scene['images']]\n val_ids = [f\"{scene['id']}_{image['id']}\" for scene in scenes[int(train * len(scenes)):int((val + train) * len(scenes))] for image in scene['images']]\n test_ids = [f\"{scene['id']}_{image['id']}\" for scene in scenes[int((val + train) * len(scenes)):] for image in scene['images']]\n\n return train_ids, val_ids, test_ids\n\n def get_images_split(subset: list) -> Tuple[List[str], List[str], List[str]]:\n image_ids = [f\"{scene['id']}_{image['id']}\" for scene in subset for image in scene['images']]\n random.shuffle(image_ids)\n\n train_ids = image_ids[:int(train * len(image_ids))]\n val_ids = image_ids[int(train * len(image_ids)):int((val + train) * len(image_ids))]\n test_ids = image_ids[int((val + train) * len(image_ids)):]\n\n return train_ids, val_ids, test_ids\n\n def write_to_file(file: str, data: list):\n with open(file, 'w') as f:\n for element in data:\n f.write(f\"{element}\\n\")\n\n if seed:\n random.seed(seed)\n\n train /= sum([train, val, test])\n test /= sum([train, val, test])\n val /= sum([train, val, test])\n\n dimo_loader = DimoLoader()\n dimo_ds = dimo_loader.load(Path(path), cameras=subsets, models_dir=None)\n\n for subset_name in subsets:\n subset = dimo_ds[subset_name]\n\n train_ids, val_ids, test_ids = get_scenes_split(subset) if split_scenes else get_images_split(subset)\n\n subset_path = os.path.join(path, f\"{subset_name}/\")\n write_to_file(os.path.join(subset_path, \"train.txt\"), train_ids)\n write_to_file(os.path.join(subset_path, \"val.txt\"), val_ids)\n write_to_file(os.path.join(subset_path, \"test.txt\"), test_ids)\n\n\nif __name__ == \"__main__\":\n create_dimo_scene_masks(\"D:/Datasets/DIMO/dimo\", \"sim_jaigo_rand_light_rand_pose\", 3649)", "repo_name": "EDM-Research/DIMO_ObjectDetection", "sub_path": "data/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 7051, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "26", "api": [{"api_name": "os.path.exists", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 27, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path", "line_number": 32, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 35, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 38, "usage_type": "name"}, {"api_name": "data.dimo_loader.DimoLoader", "line_number": 46, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 47, "usage_type": "call"}, {"api_name": "bop_toolkit_lib.renderer.create_renderer", "line_number": 53, "usage_type": "call"}, {"api_name": "bop_toolkit_lib.renderer", "line_number": 53, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path", "line_number": 58, "usage_type": "attribute"}, {"api_name": "bop_toolkit_lib.renderer", "line_number": 72, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path", "line_number": 73, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 81, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 85, "usage_type": "call"}, {"api_name": "bop_toolkit_lib.misc.depth_im_to_dist_im_fast", "line_number": 87, "usage_type": "call"}, {"api_name": "bop_toolkit_lib.misc", "line_number": 87, "usage_type": "name"}, {"api_name": "numpy.inf", "line_number": 90, "usage_type": "attribute"}, {"api_name": "numpy.minimum", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 93, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 96, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 99, "usage_type": "call"}, {"api_name": "os.path", "line_number": 99, "usage_type": "attribute"}, {"api_name": "bop_toolkit_lib.visibility.estimate_visib_mask_gt", "line_number": 100, "usage_type": "call"}, {"api_name": "bop_toolkit_lib.visibility", "line_number": 100, "usage_type": "name"}, {"api_name": "bop_toolkit_lib.inout.save_im", "line_number": 101, "usage_type": "call"}, {"api_name": "bop_toolkit_lib.inout", "line_number": 101, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 101, "usage_type": "attribute"}, {"api_name": "data.dimo_loader.DimoLoader", "line_number": 105, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 106, "usage_type": "call"}, {"api_name": "bop_toolkit_lib.renderer.create_renderer", "line_number": 111, "usage_type": "call"}, {"api_name": "bop_toolkit_lib.renderer", "line_number": 111, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 117, "usage_type": "call"}, {"api_name": "os.path", "line_number": 117, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 124, "usage_type": "name"}, {"api_name": "random.shuffle", "line_number": 139, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 137, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 137, "usage_type": "name"}, {"api_name": "random.shuffle", "line_number": 149, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 147, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 147, "usage_type": "name"}, {"api_name": "data.dimo_loader", "line_number": 159, "usage_type": "name"}, {"api_name": "random.seed", "line_number": 163, "usage_type": "call"}, {"api_name": "data.dimo_loader.DimoLoader", "line_number": 169, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 170, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 177, "usage_type": "call"}, {"api_name": "os.path", "line_number": 177, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 178, "usage_type": "call"}, {"api_name": "os.path", "line_number": 178, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 179, "usage_type": "call"}, {"api_name": "os.path", "line_number": 179, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 180, "usage_type": "call"}, {"api_name": "os.path", "line_number": 180, "usage_type": "attribute"}]} +{"seq_id": "27746688628", "text": "import datetime\nimport logging\nimport os\nimport re\nfrom functools import wraps\nfrom random import randint\n\nimport sqlalchemy\nfrom telegram import Update, ReplyKeyboardMarkup, InlineKeyboardButton, InlineKeyboardMarkup\nfrom telegram.ext import ApplicationBuilder, CallbackContext, CommandHandler, MessageHandler, filters, \\\n ConversationHandler, CallbackQueryHandler\nfrom transmission_rpc import TransmissionError\n\nfrom bot_csv import csv_upload_handler, csv_download_handler\nfrom bot_get_progress import get_progress\nfrom bot_utils import make_movie_reply, update_torr_db, \\\n exclude_torrents_from_watchlist, get_movie_from_all_databases, search_imdb_title, add_to_watchlist, \\\n get_telegram_users, invite_friend\nfrom command_regex_handler import RegexpCommandHandler\nfrom bot_watchlist import get_torrents_for_imdb_id, update_watchlist_item_status\nfrom utils import deconvert_imdb_id, send_torrent, compose_link, get_user_by_tgram_id, get_my_movie_by_imdb, \\\n update_many, Movie, convert_imdb_id, check_database, User, get_onetimepasswords, remove_onetimepassword, \\\n insert_onetimepasswords, get_movies_for_bulk_rating, make_client, update_torrent_status, update_torrent_grace_days, \\\n get_torrent_by_torr_id_user\n\n\"\"\"\nIMPORTANT for SSL: add verify=False in\nAnaconda3\\envs\\mSquaredPlex\\Lib\\site-packages\\telegram\\request\\_httpxrequest.py\nin self._client_kwargs = dict()\n\"\"\"\n\n# Enable logging\nlogging.basicConfig(\n format='[%(asctime)s] {%(filename)s:%(lineno)d} [%(name)s] [%(levelname)s] --> %(message)s', level=logging.INFO\n)\n\nlogger = logging.getLogger('MovieTimeBot')\n\nSUPERADMIN_PASSWORD = os.getenv('SUPERADMIN_PASSWORD')\n\nTELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')\nTELEGRAM_AUTH_TEST_PATH = os.getenv('TELEGRAM_AUTH_TEST_PATH')\nTELEGRAM_AUTH_APPROVE = os.getenv('TELEGRAM_AUTH_APPROVE')\nTELEGRAM_IMDB_RATINGS = os.getenv('TELEGRAM_IMDB_RATINGS')\nTELEGRAM_NETFLIX_PNG = os.getenv('TELEGRAM_NETFLIX_PNG')\nTELEGRAM_RESET_PNG = os.getenv('TELEGRAM_RESET_PNG')\n\n# State definitions for top level conversation\nCHOOSE_TASK, REGISTER_USER, DOWNLOAD_MOVIE, CHECK_PROGRESS, UPLOAD_ACTIVITY, RATE_TITLE = range(6)\n\n# State definitions DOWNLOAD_MOVIE\nCHOOSE_MULTIPLE, CHOOSE_ONE, CONFIRM_REDOWNLOAD_ACTION, SEARCH_FOR_TORRENTS, \\\nDOWNLOAD_TORRENT, WATCHLIST_NO_TORR = range(6, 12)\n\n# State definitions for CHECK_PROGRESS\nDOWNLOAD_PROGRESS = 12\n\n# State definitions for UPLOAD_ACTIVITY\nNETFLIX_CSV, UPLOAD_CSV = 13, 14\n\n# State definitions for DOWNLOAD_ACTIVITY\nDOWNLOAD_CSV = 15\n\n# State definitions for RATE_TITLE\nCHOOSE_WHAT_TO_RATE = 16\nSUBMIT_RATING = 17\n\n# State definitions for REGISTER_USER\nCHECK_EMAIL, GIVE_IMDB, CHECK_IMDB = range(18, 21)\n\nUSERS = None\n\nmenu_keyboard = [\n [\"📥 Download a movie\"],\n [\"📈 Check download progress\", \"🌡️ Rate a title\"],\n [\"❤☠🤖 Upload Netflix activity\", '💾 Download my movies']\n]\nbool_keyboard = [\n ['Yes'],\n ['No']\n]\nmovie_selection_keyboard = [\n ['Yes'],\n ['No'],\n ['Exit'],\n]\nrate_keyboard = [\n ['1', '2'],\n ['3', '4'],\n ['5', '6'],\n ['7', '8'],\n ['9', '10'],\n [\"I've changed my mind\"]\n]\nrate_keyboard_bulk = [\n ['1', '2'],\n ['3', '4'],\n ['5', '6'],\n ['7', '8'],\n ['9', '10'],\n [\"Skip this movie.\"],\n [\"Exit rating process.\"]\n]\n\n\ndef auth_wrap(f):\n @wraps(f)\n async def wrap(update: Update, context: CallbackContext, *optional_args):\n # print(f\"Wrapped {f.__name__}\", )\n user = update.effective_user['id']\n if user in USERS.keys():\n # User is registered\n result = f(update, context, *optional_args)\n # print(result)\n return await result\n else:\n if USERS:\n # New user ask for password\n await update.message.reply_text(\"Please input the password provided by the admin\")\n context.user_data['user_type'] = 'user'\n else:\n # No users registered, probably admin but check.\n await update.effective_message.reply_photo(\n photo=open(TELEGRAM_AUTH_TEST_PATH, 'rb'),\n caption=\"Looks like you're new here. Answer correctly and you may enter.\",\n )\n context.user_data['user_type'] = 'admin'\n return REGISTER_USER\n\n return wrap\n\n\n\"\"\"<< DOWNLOAD A MOVIE >>\"\"\"\n\n\n@auth_wrap\nasync def start(update: Update, context: CallbackContext, message: str = '') -> int:\n \"\"\"Send a message when the command /start is issued.\"\"\"\n\n user = update.effective_user\n if not message:\n message = f\"Hi {user.mention_markdown_v2()}\\!\\n\" \\\n fr\"Please select one of the options or type /help for more options\\.\"\n await update.message.reply_markdown_v2(\n message,\n reply_markup=ReplyKeyboardMarkup(menu_keyboard, one_time_keyboard=True, resize_keyboard=True),\n )\n return CHOOSE_TASK\n\n\n@auth_wrap\nasync def reset(update: Update, context: CallbackContext.DEFAULT_TYPE) -> int:\n \"\"\"End Conversation by command.\"\"\"\n\n await update.message.reply_text(\"See you next time. Type anything to get started.\")\n\n return ConversationHandler.END\n\n\n@auth_wrap\nasync def choose_task(update: Update, context: CallbackContext) -> int:\n \"\"\"Choose between download a movie, get download progress, upload activity\n or download my viewing activity\"\"\"\n\n if update.message.text == menu_keyboard[0][0]:\n message = 'Great, give me an IMDB id, a title or an IMDB link.'\n context.user_data['action'] = 'download'\n await update.message.reply_text(message)\n return DOWNLOAD_MOVIE\n\n elif update.message.text == menu_keyboard[1][0]:\n await update.effective_message.reply_text('Ok, retrieving data... (might be slow sometimes)')\n context.user_data['download_progress'] = 0\n return await get_download_progress(update, context)\n\n elif update.message.text == menu_keyboard[1][1]:\n await update.effective_message.reply_text('Do you wish to rate a new title or a seen but unrated movie?',\n reply_markup=ReplyKeyboardMarkup([['New title', 'Rate seen movies']],\n one_time_keyboard=True,\n resize_keyboard=True,\n ))\n return RATE_TITLE\n\n elif update.message.text == menu_keyboard[2][0]:\n await update.message.reply_photo(photo=open(TELEGRAM_NETFLIX_PNG, 'rb'),\n caption=\"Ok, follow the instructions, \"\n \"hit `Download all` and upload here the resulting .csv.\\n\"\n \"You may add any other records to \"\n \"the CSV, given that you don't change the column names.\\n\"\n \"If you want to also add ratings, create an extra column \"\n \"named 'Ratings' and it will be picked up.\\n\"\n \"Any overlapping ratings/seen dates will be overwritten. However, \"\n \"IMDB ratings, seen dates and PLEX seen dates will have prevalence.\\n\",\n )\n await update.message.reply_text(\"Now please update the .csv file.\")\n return NETFLIX_CSV\n elif update.message.text == menu_keyboard[2][1]:\n await update.message.reply_text(\"Ok, we've started the process, we'll let you know once it's done\\.\")\n\n return await download_csv(update, context)\n message = 'Please choose one of the options\\.'\n return await start(update, context, message)\n\n\n@auth_wrap\nasync def parse_imdb_id(update: Update, context: CallbackContext) -> int:\n \"\"\"Get data about movie, using the IMDB id.\n Queries the internal database and calls the APIs if necessary.\"\"\"\n\n await update.message.reply_text(\"Just a sec until we get data about this title...\")\n # We need number so filter out the number from the user input:\n imdb_id = ''.join([x for x in update.message.text if x.isdigit()]).lstrip('0')\n\n # Get IMDB data\n pkg = get_movie_from_all_databases(imdb_id, update.effective_user['id'])\n context.user_data['pkg'] = pkg\n context.user_data['more_options'] = False\n\n message, image = make_movie_reply(pkg)\n await update.effective_message.reply_photo(\n photo=image,\n caption=message,\n reply_markup=ReplyKeyboardMarkup(movie_selection_keyboard,\n one_time_keyboard=True,\n resize_keyboard=True,\n ),\n )\n return CHOOSE_ONE\n\n\n@auth_wrap\nasync def parse_imdb_text(update: Update, context: CallbackContext) -> int:\n \"\"\"Route the query if the string is a link or a title.\"\"\"\n\n await update.message.reply_text(\"Just a sec until we get data about this title...\")\n # Is it a link?\n try:\n imdb_id = re.search(r\"[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)\",\n update.message.text).group(0)\n\n # We need number so filter out the number from the user input:\n imdb_id = ''.join([x for x in imdb_id if x.isdigit()]).lstrip('0')\n\n # Get IMDB data\n pkg = get_movie_from_all_databases(imdb_id, update.effective_user['id'])\n context.user_data['pkg'] = pkg\n\n message, image = make_movie_reply(pkg)\n await update.effective_message.reply_photo(\n photo=image,\n caption=message,\n reply_markup=ReplyKeyboardMarkup(movie_selection_keyboard,\n one_time_keyboard=True,\n resize_keyboard=True,\n ),\n )\n return CHOOSE_ONE\n except AttributeError:\n # Yes but wrong link or no match\n if 'https://' in update.message.text:\n await update.effective_message.reply_text(\"Couldn't find the specified ID in the link, are you\"\n \"sure it's an IMDB link? Try pasting only the ID, as in\"\n \"`tt0903624`.\")\n return DOWNLOAD_MOVIE\n else:\n # Test for title\n movies = search_imdb_title(update.message.text)\n context.user_data['potential_titles'] = movies\n\n return await choose_multiple(update, context)\n\n\n@auth_wrap\nasync def choose_multiple(update: Update, context: CallbackContext) -> int:\n \"\"\"Loop through potential movie matches\"\"\"\n\n movies = context.user_data['potential_titles']\n if movies:\n if type(movies) == str:\n await update.effective_message.reply_text(\"We're having trouble with our IMDB API, please\"\n \"insert an IMDB ID or paste a link.\")\n return DOWNLOAD_MOVIE\n movie = movies.pop(0)\n # Check again if we can find it\n pkg = get_movie_from_all_databases(movie['id'], update.effective_user['id'])\n # context.user_data['pkg'] = pkg\n if pkg:\n context.user_data['pkg'] = pkg\n message, image = make_movie_reply(pkg)\n await update.effective_message.reply_photo(\n photo=image,\n caption=message,\n reply_markup=ReplyKeyboardMarkup(movie_selection_keyboard,\n one_time_keyboard=True,\n resize_keyboard=True,\n ),\n )\n return CHOOSE_ONE\n else:\n return await choose_multiple(update, context)\n else:\n await update.effective_message.reply_text(\"Couldn't find the specified movie.\"\n \" Check your spelling or try pasting the IMDB id or a link\"\n \"`tt0903624`.\")\n return DOWNLOAD_MOVIE\n\n\n@auth_wrap\nasync def accept_reject_title(update: Update, context: CallbackContext) -> int:\n \"\"\"Accept, reject the match or exit\"\"\"\n if update.message.text == 'Yes':\n if context.user_data['action'] == 'download':\n return await check_movie_status(update, context)\n else:\n return await rating_movie_info(update, context)\n elif update.message.text == 'No':\n if context.user_data['potential_titles']:\n await update.effective_message.reply_text(\"Ok, trying next hit...\")\n return await choose_multiple(update, context)\n else:\n await update.effective_message.reply_text(\"These were all the hits. Sorry. Feel free to type anything \"\n \"to start again\")\n return await reset(update, context)\n elif update.message.text == 'Exit':\n return await reset(update, context)\n else:\n await update.effective_message.reply_text(\"Please choose one of the options.\")\n\n\n@auth_wrap\nasync def check_movie_status(update: Update, context: CallbackContext) -> int:\n \"\"\"Customise the message depending on the status of the movie\n (seen, already downloaded)\"\"\"\n\n movie = context.user_data['pkg']\n # Check if you've already seen it and send info\n if movie['already_in_my_movies']:\n message = f\"Looks like you've already seen this movie.\"\n if 'my_score' in movie.keys():\n message += f\"\\nYour score: {movie['my_score']}\"\n if 'seen_date' in movie.keys():\n message += f\"\\nAnd you've seen it on {movie['seen_date']}\"\n await update.message.reply_text(message)\n if movie['torr_result']:\n message = f\"Looks like the movie is also downloaded in {movie['resolution']}p\\n\" \\\n f\"Torrent status: {movie['torr_status']}\\n\" \\\n f\"Would you still like to proceed to download?\"\n else:\n message = f\"\\nWould you still like to proceed to download?\"\n\n await update.effective_message.reply_html(message, reply_markup=ReplyKeyboardMarkup(bool_keyboard,\n one_time_keyboard=True,\n resize_keyboard=True,\n ))\n return CONFIRM_REDOWNLOAD_ACTION\n else:\n return await search_for_torrents(update, context)\n\n\n@auth_wrap\nasync def search_for_torrents(update: Update, context: CallbackContext) -> int:\n \"\"\"Search for torrents for the given IMDB id\n Build keyboard to show them\"\"\"\n\n await update.message.reply_text('Searching for available torrents...')\n torrents = get_torrents_for_imdb_id(context.user_data['pkg']['imdb'])\n torrents = sorted(torrents, key=lambda k: k['size'])\n if torrents:\n context.user_data['pkg']['torrents'] = sorted(torrents, key=lambda k: k['size'])\n keyboard = [[]]\n \"\"\"\n # Check if we need to filter excluded resolutions\n # Removed functionality, left here for reference or other further uses\n if 'from_watchlist' in context.user_data.keys():\n movie_id = deconvert_imdb_id(torrents[0]['imdb'])\n excluded_resolutions = get_excluded_resolutions(movie_id, update.effective_user['id'])\n torrents = [x for x in torrents if x['id'] not in excluded_resolutions]\n \"\"\"\n for pos, item in enumerate(torrents):\n pos += 1 # exclude 0\n btn_text = (\n f\"🖥 Q: {str(item['resolution'])}\"\n f\"🗳 S: {str(round(item['size'] / 1000000000, 2))} GB\"\n f\"🌱 S/P: {str(item['seeders'])}/{str(item['leechers'])}\"\n )\n btn = InlineKeyboardButton(btn_text, callback_data=item['id'])\n keyboard.append([btn])\n # Add button for None\n keyboard.append([InlineKeyboardButton('None, thanks', callback_data=0)])\n await update.message.reply_text(\n f\"Please select one of the torrents\",\n reply_markup=InlineKeyboardMarkup(keyboard, one_time_keyboard=True),\n )\n return DOWNLOAD_TORRENT\n else:\n await update.message.reply_text(\n \"We couldn't find any torrents for this title.\\n\"\n \"Would you like to add it to your watchlist?\",\n reply_markup=ReplyKeyboardMarkup(bool_keyboard, one_time_keyboard=True, resize_keyboard=True),\n )\n return WATCHLIST_NO_TORR\n\n\n@auth_wrap\nasync def confirm_redownload_action(update: Update, context: CallbackContext) -> int:\n \"\"\"Ask user if he really wants to download the movie given that\n he's aready seen it or it's already in transmission\"\"\"\n\n if update.message.text == 'Yes':\n if context.user_data['action'] == 'download':\n return await search_for_torrents(update, context)\n else:\n return await rate_title(update, context)\n else:\n return await reset(update, context)\n\n\n@auth_wrap\nasync def download_torrent(update: Update, context: CallbackContext) -> int:\n \"\"\"Send download request to transmission\"\"\"\n\n query = update.callback_query\n await query.answer()\n if query.data != '0':\n await query.edit_message_text(text=f\"Thanks, sending download request...\")\n # Send download request\n try:\n torr = [x for x in context.user_data['pkg']['torrents'] if query.data == str(x['id'])][0]\n # Send torrent to daemon\n torr_client_resp = send_torrent(compose_link(query.data))\n # Update torrent DB\n update_torr_db(torr, torr_client_resp, update.effective_user['id'])\n message = f\"Download started, have a great day!\"\n except TransmissionError as e:\n logger.error(f\"Error on torrent send: {e}\")\n message = f\"Download failed, please check logs and try again.\"\n await query.edit_message_text(text=message)\n if 'from_watchlist' in context.user_data.keys():\n return ConversationHandler.END\n return CHOOSE_TASK\n else:\n if 'from_watchlist' in context.user_data.keys():\n await query.edit_message_text(text=\"Ok, i'll remove these torrent options from future watchlist alerts \"\n \"regarding this movie.\")\n return await exclude_res_from_watchlist(update, context)\n else:\n await update.effective_message.reply_text('Would you like to add it to your watchlist?',\n reply_markup=ReplyKeyboardMarkup(bool_keyboard,\n one_time_keyboard=True,\n resize_keyboard=True))\n return WATCHLIST_NO_TORR\n\n\n@auth_wrap\nasync def exclude_res_from_watchlist(update: Update, context: CallbackContext) -> int:\n \"\"\"Function gets called only when a watchlist allert appears.\n If the user refuses to download, the current movie resolution will be\n excluded from further alerts.\"\"\"\n\n torrents = context.user_data['pkg']['torrents']\n movie_id = deconvert_imdb_id(torrents[0]['imdb'])\n exclude_torrents_from_watchlist(movie_id, update.effective_user['id'], [x['id'] for x in torrents])\n await update.callback_query.edit_message_text(text=\"Removed these torrent quality for future recommendations \"\n \"on this title. Type anything to get started\")\n return ConversationHandler.END\n\n\n@auth_wrap\nasync def add_to_watchlist_no_torrent(update: Update, context: CallbackContext) -> int:\n \"\"\"Add movie to watchlist if no torrent is currently available.\n If torrents for the movie ARE available but the user still wants to add to\n watchlist, the movie is added but user will be notified only when another\n resolution for the movie becomes available.\"\"\"\n\n if update.message.text == 'Yes':\n # Try to get user's IMDB id if he has any\n try:\n user = get_user_by_tgram_id(update.effective_user['id'])\n except Exception as e:\n logger.warning(f\"Error upon retrieving IMDB id for user with tgram_id {update.effective_user['id']} \"\n f\"might not have any. Error: {e}\")\n user = None\n if 'torrents' not in context.user_data['pkg'].keys():\n add_to_watchlist(deconvert_imdb_id(context.user_data['pkg']['imdb']), user, 'new')\n else:\n add_to_watchlist(deconvert_imdb_id(context.user_data['pkg']['imdb']), user, 'new',\n [x['id'] for x in context.user_data['pkg']['torrents']])\n message = \"Added to watchlist!\"\n await update.message.reply_text(message)\n\n return await reset(update, context)\n\n\n\"\"\"<< CHECK DOWNLOAD PROGRESS >>\"\"\"\n\n\n@auth_wrap\nasync def get_download_progress(update: Update, context: CallbackContext) -> int:\n \"\"\"Return the status for the last 10 torrents for this user\"\"\"\n\n user = update.effective_user['id']\n torrents = get_progress(user, logger=logger)\n if torrents:\n for torrent in torrents[:5]:\n await update.message.reply_text(f\"{torrent['TorrentName']}\\n\"\n f\"Resolution: {torrent['Resolution']}\\n\"\n f\"Status: {torrent['Status']}\\n\"\n f\"Progress: {torrent['Progress']}\\n\"\n f\"ETA: {torrent['ETA']}\")\n else:\n await update.message.reply_text(\"No torrents to show :(.\")\n return await reset(update, context)\n\n\n\"\"\"<< UPLOAD ACTIVITY >>\"\"\"\n\n\n@auth_wrap\nasync def netflix_rate_or_not(update: Update, context: CallbackContext) -> int:\n \"\"\"User chooses to receive or not notifications for unrated titles.\"\"\"\n\n if update.message.text == 'No':\n context.user_data['send_notifications'] = False\n else:\n context.user_data['send_notifications'] = True\n await update.message.reply_text(\"K, now upload the .csv file please.\")\n return NETFLIX_CSV\n\n\n@auth_wrap\nasync def netflix_csv(update: Update, context: CallbackContext) -> int:\n \"\"\"Sends CSV file in order to be processed\"\"\"\n\n csv_context = {\n 'user': update.effective_user.id,\n 'file': update.message.document.file_id,\n }\n await update.message.reply_text(\"Thanks!We started the upload process, we'll let you know \"\n \"when it's done or if there's any trouble.\")\n context.job_queue.run_once(\n callback=csv_upload_handler,\n context=csv_context,\n when=10\n )\n return await reset(update, context)\n\n\n@auth_wrap\nasync def netflix_no_csv(update: Update, context: CallbackContext) -> int:\n await update.message.reply_text(\"Upload the .csv or hit /reset.\")\n return NETFLIX_CSV\n\n\n\"\"\"<< RATE A TITLE >>\"\"\"\n\n\n@auth_wrap\nasync def choose_what_to_rate(update: Update, context: CallbackContext) -> int:\n if update.message.text == 'New title':\n message = 'Great, give me an IMDB id, a title or an IMDB link.'\n context.user_data['action'] = 'rate'\n await update.message.reply_text(message)\n return DOWNLOAD_MOVIE\n\n elif update.message.text == 'Rate seen movies':\n await update.message.reply_text(\"Preparing movies...\")\n context.user_data['unrated_movies'] = get_movies_for_bulk_rating(update.effective_user['id'])\n if context.user_data['unrated_movies']:\n return await rate_multiple(update, context)\n else:\n await update.message.reply_text(\"You have no unrated movies!\")\n return await start(update, context, \"Can i help you with anything else?\")\n\n\n@auth_wrap\nasync def rate_multiple(update: Update, context: CallbackContext) -> int:\n movies = context.user_data['unrated_movies']\n if movies:\n movie = movies.pop(0)\n # Check again if we can find it\n pkg = get_movie_from_all_databases(movie['imdb_id'], update.effective_user['id'])\n if pkg:\n context.user_data['pkg'] = pkg\n message, image = make_movie_reply(pkg)\n message += \"\\nPlease choose a rating\"\n await update.effective_message.reply_photo(\n photo=image,\n caption=message,\n reply_markup=ReplyKeyboardMarkup(rate_keyboard_bulk,\n one_time_keyboard=True,\n resize_keyboard=True,\n ),\n )\n context.user_data['rate_origin'] = 'multiple'\n return SUBMIT_RATING\n else:\n return await rate_multiple(update, context)\n else:\n await update.effective_message.reply_text(\"No more movies left, good job!\")\n return await start(update, context, \"Can i help you with anything else?\")\n\n\n@auth_wrap\nasync def rating_movie_info(update: Update, context: CallbackContext) -> int:\n movie = context.user_data['pkg']\n # Check if you've already seen it and send info\n if movie['already_in_my_movies']:\n message = f\"Movie seen\"\n if 'seen_date' in movie.keys():\n message = message + f\" on {movie['seen_date']}\"\n if 'my_score' in movie.keys():\n message += f\"\\nYour score: {movie['my_score']}\"\n await update.message.reply_text(message)\n message = f\"\\nWould you like to rate it again?\"\n await update.effective_message.reply_html(message, reply_markup=ReplyKeyboardMarkup(bool_keyboard,\n one_time_keyboard=True,\n resize_keyboard=True,\n ))\n return CONFIRM_REDOWNLOAD_ACTION\n else:\n return await rate_title(update, context)\n\n\n@auth_wrap\nasync def rate_title(update: Update, context: CallbackContext) -> int:\n context.user_data['rate_origin'] = 'simple'\n message = f\"Great, please choose a rating:\"\n await update.effective_message.reply_html(message, reply_markup=ReplyKeyboardMarkup(rate_keyboard,\n one_time_keyboard=True,\n resize_keyboard=True,\n ))\n return SUBMIT_RATING\n\n\n@auth_wrap\nasync def rate_title_plex_triggered(update: Update, context: CallbackContext, passed_args) -> int:\n context.user_data['pkg'] = {\n 'imdb': int(passed_args)\n }\n return await rate_title(update, context)\n\n\n@auth_wrap\nasync def submit_rating(update: Update, context: CallbackContext) -> int:\n \"\"\"User receives a message from an external routine\n If he clicks on it this function gets triggered.\"\"\"\n if context.user_data['rate_origin'] == 'simple':\n return1_func = reset\n message1 = \"Ok, no worries! I won't bother you about this title anymore.\\n\" \\\n \"Have a great day!\"\n return2_func = reset\n else:\n return1_func = rate_multiple\n message1 = \"Ok, no worries! I won't bother you about this title anymore.\\n\"\n return2_func = rate_multiple\n\n if update.message.text in [str(x) for x in list(range(1, 11))]:\n # Got rating\n item = get_my_movie_by_imdb(context.user_data['pkg']['imdb'], update.effective_user['id'])\n if item:\n item['rating_status'] = 'rated in telegram'\n item['my_score'] = int(update.message.text)\n item['seen_date'] = datetime.datetime.now()\n else:\n item = {\n 'imdb_id': context.user_data['pkg']['imdb'],\n 'my_score': int(update.message.text),\n 'rating_status': 'rated in telegram',\n 'user_id': update.effective_user['id'],\n 'seen_date': datetime.datetime.now(),\n }\n update_many([item], Movie, Movie.id)\n await update.effective_message.reply_text(f\"Ok, great! Here's a link if you also want to rate it on IMDB:\\n\"\n f\"https://www.imdb.com/title/\"\n f\"{convert_imdb_id(context.user_data['pkg']['imdb'])}/\",\n disable_web_page_preview=True)\n return await return1_func(update, context)\n\n elif update.message.text in [rate_keyboard[-1][0], rate_keyboard_bulk[-2][0]]:\n item = get_my_movie_by_imdb(context.user_data['pkg']['imdb'], update.effective_user['id'])\n if item:\n item['rating_status'] = 'refused to rate'\n else:\n item = {\n 'imdb_id': context.user_data['pkg']['imdb'],\n 'rating_status': 'refused to rate',\n 'user_id': update.effective_user['id'],\n }\n update_many([item], Movie, Movie.id)\n await update.effective_message.reply_text(message1)\n return await return2_func(update, context)\n elif update.message.text == rate_keyboard_bulk[-1][0]:\n await update.effective_message.reply_text(\"Ok, your progress is saved, come back anytime.\")\n return await start(update, context)\n else:\n await update.effective_message.reply_text(\"Please choose an option from the keyboard.\")\n return SUBMIT_RATING\n\n\n\"\"\"<< AUTHENTICATION >>\"\"\"\n\n\nasync def check_user(update: Update, context: CallbackContext):\n if context.user_data['user_type'] == 'user':\n onetime_passwords = get_onetimepasswords()\n passwords = [x['password'] for x in onetime_passwords]\n expiry_dates = [x['expiry'] for x in onetime_passwords]\n user_types = [x['user_type'] for x in onetime_passwords]\n try:\n pwd = int(update.message.text)\n if pwd in passwords and datetime.datetime.now() < expiry_dates[passwords.index(pwd)]:\n remove_onetimepassword(pwd)\n context.user_data['user_type'] = user_types[passwords.index(pwd)]\n return await password_ok(update, context)\n else:\n await update.effective_message.reply_text(\"Password expired, please contact \"\n \"the admin and try again.\")\n return REGISTER_USER\n except ValueError:\n pass\n else:\n if update.message.text.lower() == SUPERADMIN_PASSWORD:\n return await password_ok(update, context)\n await update.effective_message.reply_text(\"Incorrect password\")\n return REGISTER_USER\n\n\nasync def password_ok(update: Update, context: CallbackContext):\n await update.effective_message.reply_photo(\n photo=open(TELEGRAM_AUTH_APPROVE, 'rb'),\n caption=\"Welcome! Just a few more steps to configure your preferences. \"\n \"First, please type in your email so that we can add you \"\n \"to our PLEX users.\",\n )\n return CHECK_EMAIL\n\n\nasync def check_email(update: Update, context: CallbackContext):\n # Invite to PLEX server\n email_invite = invite_friend(update.message.text)\n if email_invite:\n message = \"Great! An invitation for PLEX has been sent to your email.\\n\"\n else:\n message = \"Looks like either this email is already in our PLEX users database \" \\\n \"OR you're not planning to use PLEX.\\n\" \\\n \"If this is not the case, please contact the admin.\\n\\n\"\n\n # Continue to IMDB stuff\n context.user_data['new_user'] = {\n 'telegram_chat_id': update.message.chat_id,\n 'telegram_name': update.effective_user.first_name,\n 'email': update.message.text,\n 'email_newsletters': True,\n 'scan_watchlist': False,\n 'user_type': context.user_data['user_type']\n\n }\n message += \"Would you like to connect your IMDB account? \" \\\n \"In this way we'll be able to pull your movie \" \\\n \"ratings and warn you when you'll search for a movie \" \\\n \"you've already seen.\\n\" \\\n \"We'll also scan your watchlist periodically and notify you \" \\\n \"when we'll be able to download any of the titles there.\\n\" \\\n \"In the future we're planning to be able to \" \\\n \"give ratings here and transfer them to IMDB.\"\n await update.effective_message.reply_text(message, reply_markup=ReplyKeyboardMarkup(bool_keyboard,\n one_time_keyboard=True,\n resize_keyboard=True,\n ))\n return GIVE_IMDB\n\n\nasync def give_imdb(update: Update, context: CallbackContext):\n if update.message.text == 'Yes':\n await update.effective_message.reply_photo(\n photo=open(TELEGRAM_IMDB_RATINGS, 'rb'),\n caption=\"I'll need you to go to your IMDB account and copy here your user ID, like the one in the photo, \"\n \"ur77571297. Also make sure that your Ratings are PUBLIC and so is your Watchlist (10 pages max).\\n\"\n \"If this is too much, just type 'fuck it' and skip this step.\\n\"\n \"https://www.imdb.com/\",\n )\n return CHECK_IMDB\n else:\n return await register_user(update, context)\n\n\nasync def check_imdb(update: Update, context: CallbackContext):\n if update.message.text.lower() != 'fuck it':\n context.user_data['new_user']['scan_watchlist'] = True\n context.user_data['new_user']['imdb_id'] = ''.join([x for x in update.message.text if x.isdigit()])\n return await register_user(update, context)\n\n\nasync def register_user(update: Update, context: CallbackContext):\n global USERS\n # Update user to database\n update_many([context.user_data['new_user']], User, User.telegram_chat_id)\n USERS = get_telegram_users()\n message = \"Ok, that's it\\. I'll take care of the rest, from now on \" \\\n \"anytime you type something i'll be here to help you out\\. Enjoy\\!\\n\" \\\n \"Type /help to find out more\\.\"\n return await start(update, context, message)\n\n\ndef wrong_input(update: Update, context: CallbackContext):\n update.effective_message.reply_text(\"Wrong input, please try again.\")\n return CHECK_EMAIL\n\n\ndef wrong_input_imdb(update: Update, context: CallbackContext):\n update.effective_message.reply_text(\"Wrong input, please try again.\")\n return CHECK_IMDB\n\n\n\"\"\"<< DOWNLOAD MOVIE DATABASE (CSV) >>\"\"\"\n\n\n@auth_wrap\nasync def download_csv(update: Update, context: CallbackContext) -> None:\n csv_context = {\n 'user': update.effective_user.id,\n }\n context.job_queue.run_once(\n callback=csv_download_handler,\n context=csv_context,\n when=0\n )\n return None\n\n\n\"\"\"<< OTHER FUNCTIONS >>\"\"\"\n\n\n@auth_wrap\nasync def help_command(update: Update, context: CallbackContext) -> None:\n \"\"\"Displays info on how to use the bot.\"\"\"\n\n watchlist_status = 'MONITORING' if USERS[update.effective_user.id]['scan_watchlist'] == 1 else 'NOT MONITORING'\n email_status = 'RECEIVING' if USERS[update.effective_user.id]['email_newsletters'] else 'NOT RECEIVING'\n generate_password = '\\n\\nGENERATE CODE FOR NEW USER: run command /generate_pass. If you want the user to have ' \\\n 'admin privileges, use -admin flag (/generate_pass -admin)' if \\\n USERS[update.effective_user.id]['user_type'] == 'admin' else ' '\n await update.message.reply_text(\"Type anything for the bot to start.\\n\\n\"\n \"If i lose my shit just type /reset anytime.\\n\\n\"\n f\"Right now we are {watchlist_status} your watchlist. \"\n f\"Type /change_watchlist \"\n \"to reverse the status.\\n\\n\"\n f\"Right now you are {email_status} the email newsletters. Type /change_newsletter \"\n \"to reverse the status.\\n\\n\"\n \"If you want to change your email address or your imdb ID type /update_user \"\n \"and we'll ask you to retake the login process. Once started, you must complete \"\n \"the entire process.\"\n f\"{generate_password}\")\n # don't change state\n return None\n\n\n@auth_wrap\nasync def generate_password(update: Update, context: CallbackContext) -> None:\n def insert_pwd(pwd):\n try:\n insert_onetimepasswords(pwd)\n except sqlalchemy.exc.IntegrityError:\n pwd['password'] = randint(10000, 99999)\n insert_pwd(pwd)\n return pwd['password']\n\n if not USERS[update.effective_user.id]['user_type'] == 'admin':\n return None\n else:\n arguments = (' '.join(context.args)).strip()\n pwd = {\n 'password': randint(10000, 99999),\n 'expiry': datetime.datetime.now() + datetime.timedelta(days=1)\n }\n if arguments == '-admin':\n pwd['user_type'] = 'admin'\n else:\n pwd['user_type'] = 'user'\n pwd = insert_pwd(pwd)\n await update.message.reply_text(f\"Token {pwd} available for 24 hours\")\n return None\n\n\n@auth_wrap\nasync def update_user(update: Update, context: CallbackContext) -> None:\n await update.message.reply_text('Type anything to get started.')\n del USERS[update.effective_user.id]\n\n\n@auth_wrap\nasync def watchlist_entry(update: Update, context: CallbackContext, *passed_args) -> int:\n context.user_data['pkg'] = {\n 'imdb': int(passed_args[0]),\n }\n context.user_data['from_watchlist'] = True\n await update.message.reply_text('Watchlist entry')\n return await search_for_torrents(update, context)\n\n\n@auth_wrap\nasync def remove_watchlist_entry(update: Update, context: CallbackContext, *passed_args) -> int:\n movie_id = int(passed_args[0])\n update_watchlist_item_status(movie_id, update.effective_user['id'], 'closed')\n await update.message.reply_text(\"Done, no more watchlist updates for this movie.\")\n return ConversationHandler.END\n\n\n@auth_wrap\nasync def keep_torrent(update: Update, context: CallbackContext, *passed_args) -> int:\n torr_id = int(passed_args[0])\n update_torrent_grace_days(torr_id, update.effective_user['id'])\n await update.message.reply_text(\"Ok, done.\")\n return ConversationHandler.END\n\n\n@auth_wrap\nasync def remove_torrent(update: Update, context: CallbackContext, *passed_args) -> int:\n db_torr_id = int(passed_args[0])\n # remove torrent and data\n client = make_client()\n torrents = client.get_torrents()\n db_torr = get_torrent_by_torr_id_user(db_torr_id, update.effective_user['id'])\n try:\n torrent = [x for x in torrents if x.hashString == db_torr['torr_hash']][0]\n except IndexError:\n await update.message.reply_text(\"Error while removing torrent,\\n\"\n \"please contact admin:).\")\n return ConversationHandler.END\n client.remove_torrent(torrent.id, delete_data=True)\n # change status\n update_torrent_status(db_torr_id, 'removed')\n await update.message.reply_text(\"Torrent and files removed.\")\n return ConversationHandler.END\n\n\n@auth_wrap\nasync def seed_forever_torrent(update: Update, context: CallbackContext, *passed_args) -> int:\n torr_id = int(passed_args[0])\n update_torrent_grace_days(torr_id, update.effective_user['id'], 99999)\n await update.message.reply_text(\"Done, SeedMaster.\")\n return ConversationHandler.END\n\n\n@auth_wrap\nasync def change_watchlist_command(update: Update, context: CallbackContext) -> None:\n pkg = USERS[update.effective_user.id]\n pkg['telegram_chat_id'] = update.effective_user.id\n if pkg['scan_watchlist'] == 0:\n pkg['scan_watchlist'] = 1\n else:\n pkg['scan_watchlist'] = 0\n update_many([pkg], User, User.telegram_chat_id)\n await update.message.reply_text(\"Updated your watchlist preferences.\")\n\n\n@auth_wrap\nasync def change_newsletter_command(update: Update, context: CallbackContext) -> None:\n pkg = USERS[update.effective_user.id]\n pkg['telegram_chat_id'] = update.effective_user.id\n if pkg['email_newsletters'] == 0:\n pkg['email_newsletters'] = 1\n else:\n pkg['email_newsletters'] = 0\n update_many([pkg], User, User.telegram_chat_id)\n await update.message.reply_text(\"Updated your newsletter preferences.\")\n\n\ndef main() -> None:\n \"\"\"\n Main function, runs bot and all other services\n \"\"\"\n\n global USERS\n check_database()\n USERS = get_telegram_users()\n\n application = ApplicationBuilder().token(TELEGRAM_TOKEN).build()\n\n download_movie_conversation_handler = ConversationHandler(\n entry_points=[\n RegexpCommandHandler(r'WatchMatch_[\\d]+', watchlist_entry),\n MessageHandler(filters.Regex('^([tT]{2})?\\d+$') & (~filters.COMMAND), parse_imdb_id),\n MessageHandler(filters.TEXT & (~filters.COMMAND), parse_imdb_text),\n ],\n states={\n CHOOSE_MULTIPLE: [\n MessageHandler(filters.TEXT & (~filters.COMMAND), choose_multiple)],\n CHOOSE_ONE: [\n MessageHandler(filters.TEXT & (~filters.COMMAND), accept_reject_title)],\n CONFIRM_REDOWNLOAD_ACTION: [\n MessageHandler(filters.TEXT & (~filters.COMMAND), confirm_redownload_action)],\n SEARCH_FOR_TORRENTS: [\n MessageHandler(filters.TEXT & (~filters.COMMAND), search_for_torrents)],\n DOWNLOAD_TORRENT: [\n CallbackQueryHandler(download_torrent)],\n WATCHLIST_NO_TORR: [\n MessageHandler(filters.TEXT & (~filters.COMMAND), add_to_watchlist_no_torrent), ],\n },\n fallbacks=[CommandHandler(\"reset\", reset)],\n map_to_parent={\n CHOOSE_TASK: CHOOSE_TASK,\n DOWNLOAD_MOVIE: DOWNLOAD_MOVIE,\n SUBMIT_RATING: SUBMIT_RATING,\n ConversationHandler.END: ConversationHandler.END\n }\n )\n\n check_progress_conversation_handler = ConversationHandler(\n entry_points=[\n MessageHandler(filters.TEXT, get_download_progress),\n CallbackQueryHandler(get_download_progress)],\n states={},\n fallbacks=[],\n map_to_parent={}\n )\n\n rate_title_conversation_handler = ConversationHandler(\n entry_points=[\n RegexpCommandHandler(r'RateTitle_[\\d]+', rate_title_plex_triggered),\n MessageHandler(filters.TEXT & (~filters.COMMAND), choose_what_to_rate), ],\n states={\n DOWNLOAD_MOVIE: [\n download_movie_conversation_handler\n ],\n SUBMIT_RATING: [\n MessageHandler(filters.TEXT & (~filters.COMMAND), submit_rating, )],\n },\n fallbacks=[],\n map_to_parent={\n CHOOSE_TASK: CHOOSE_TASK,\n RATE_TITLE: RATE_TITLE,\n ConversationHandler.END: ConversationHandler.END\n }\n )\n\n register_user_conversation_handler = ConversationHandler(\n entry_points=[\n MessageHandler(filters.TEXT & (~filters.COMMAND), check_user)],\n states={\n CHECK_EMAIL: [\n MessageHandler(filters.Regex('[^@]+@[^@]+\\.[^@]+') & (~filters.COMMAND), check_email),\n MessageHandler(filters.TEXT & (~filters.COMMAND), wrong_input, )],\n GIVE_IMDB: [\n MessageHandler(filters.TEXT & (~filters.COMMAND), give_imdb, )],\n CHECK_IMDB: [\n MessageHandler(filters.Regex('^[u]?[r]?\\d+$') & (~filters.COMMAND), check_imdb),\n MessageHandler(filters.TEXT & (~filters.COMMAND), wrong_input_imdb),\n ],\n },\n fallbacks=[CommandHandler('reset', reset)],\n map_to_parent={\n REGISTER_USER: REGISTER_USER,\n CHOOSE_TASK: CHOOSE_TASK,\n ConversationHandler.END: ConversationHandler.END\n }\n )\n\n conversation_handler = ConversationHandler(\n entry_points=[\n RegexpCommandHandler(r'WatchMatch_[\\d]+', watchlist_entry),\n RegexpCommandHandler(r'RateTitle_[\\d]+', rate_title_plex_triggered),\n MessageHandler(filters.TEXT & (~filters.COMMAND), start),\n ],\n states={\n CHOOSE_TASK: [MessageHandler(filters.TEXT & (~filters.COMMAND), choose_task)],\n DOWNLOAD_MOVIE: [download_movie_conversation_handler],\n CHECK_PROGRESS: [check_progress_conversation_handler],\n NETFLIX_CSV: [\n MessageHandler(filters.Document.FileExtension('csv') & (~filters.COMMAND), netflix_csv),\n MessageHandler(filters.TEXT & (~filters.COMMAND), netflix_no_csv), ],\n RATE_TITLE: [rate_title_conversation_handler],\n REGISTER_USER: [register_user_conversation_handler],\n DOWNLOAD_TORRENT: [CallbackQueryHandler(download_torrent)],\n SUBMIT_RATING: [MessageHandler(filters.TEXT & (~filters.COMMAND), submit_rating)],\n },\n fallbacks=[\n CommandHandler(\"reset\", reset),\n CommandHandler('help', help_command),\n CommandHandler('generate_pass', generate_password),\n CommandHandler('update_user', update_user),\n CommandHandler('change_watchlist', change_watchlist_command),\n CommandHandler('change_newsletter', change_newsletter_command),\n (RegexpCommandHandler(r'RateTitle_[\\d]+', rate_title_plex_triggered)),\n (RegexpCommandHandler(r'WatchMatch_[\\d]+', watchlist_entry)),\n (RegexpCommandHandler(r'UnWatchMatch_[\\d]+', remove_watchlist_entry)),\n (RegexpCommandHandler(r'Keep_[\\d]+', keep_torrent)),\n (RegexpCommandHandler(r'Remove_[\\d]+', remove_torrent)),\n (RegexpCommandHandler(r'SeedForever_[\\d]+', seed_forever_torrent)),\n\n ]\n )\n\n application.add_handler(conversation_handler)\n application.add_handler(CommandHandler('help', help_command))\n application.add_handler(CommandHandler('generate_pass', generate_password))\n application.add_handler(CommandHandler('update_user', update_user))\n application.add_handler(RegexpCommandHandler(r'RateTitle_[\\d]+', rate_title_plex_triggered))\n application.add_handler(RegexpCommandHandler(r'WatchMatch_[\\d]+', watchlist_entry))\n application.add_handler(RegexpCommandHandler(r'UnWatchMatch_[\\d]+', remove_watchlist_entry))\n application.add_handler(RegexpCommandHandler(r'Keep_[\\d]+', keep_torrent))\n application.add_handler(RegexpCommandHandler(r'Remove_[\\d]+', remove_torrent))\n application.add_handler(RegexpCommandHandler(r'SeedForever_[\\d]+', seed_forever_torrent))\n application.add_handler(CommandHandler('change_watchlist', change_watchlist_command))\n application.add_handler(CommandHandler('change_newsletter', change_newsletter_command))\n application.run_polling(stop_signals=None)\n\n\nif __name__ == '__main__':\n main()\n", "repo_name": "ironsilk/mSquaredPlex", "sub_path": "telegram_service/bot.py", "file_name": "bot.py", "file_ext": "py", "file_size_in_byte": 47995, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "25", "api": [{"api_name": "logging.basicConfig", "line_number": 33, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 34, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 37, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 39, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 41, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 42, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 43, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 44, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 45, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 46, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 108, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 108, "usage_type": "name"}, {"api_name": "functools.wraps", "line_number": 107, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 137, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 137, "usage_type": "name"}, {"api_name": "telegram.ReplyKeyboardMarkup", "line_number": 146, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 152, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext.DEFAULT_TYPE", "line_number": 152, "usage_type": "attribute"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 152, "usage_type": "name"}, {"api_name": "telegram.ext.ConversationHandler.END", "line_number": 157, "usage_type": "attribute"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 157, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 161, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 161, "usage_type": "name"}, {"api_name": "telegram.ReplyKeyboardMarkup", "line_number": 178, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 206, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 206, "usage_type": "name"}, {"api_name": "bot_utils.get_movie_from_all_databases", "line_number": 215, "usage_type": "call"}, {"api_name": "bot_utils.make_movie_reply", "line_number": 219, "usage_type": "call"}, {"api_name": "telegram.ReplyKeyboardMarkup", "line_number": 223, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 232, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 232, "usage_type": "name"}, {"api_name": "re.search", "line_number": 238, "usage_type": "call"}, {"api_name": "bot_utils.get_movie_from_all_databases", "line_number": 245, "usage_type": "call"}, {"api_name": "bot_utils.make_movie_reply", "line_number": 248, "usage_type": "call"}, {"api_name": "telegram.ReplyKeyboardMarkup", "line_number": 252, "usage_type": "call"}, {"api_name": "bot_utils.search_imdb_title", "line_number": 267, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 274, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 274, "usage_type": "name"}, {"api_name": "bot_utils.get_movie_from_all_databases", "line_number": 285, "usage_type": "call"}, {"api_name": "bot_utils.make_movie_reply", "line_number": 289, "usage_type": "call"}, {"api_name": "telegram.ReplyKeyboardMarkup", "line_number": 293, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 309, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 309, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 331, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 331, "usage_type": "name"}, {"api_name": "telegram.ReplyKeyboardMarkup", "line_number": 351, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 361, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 361, "usage_type": "name"}, {"api_name": "bot_watchlist.get_torrents_for_imdb_id", "line_number": 366, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 386, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 389, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardMarkup", "line_number": 392, "usage_type": "call"}, {"api_name": "telegram.ReplyKeyboardMarkup", "line_number": 399, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 405, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 405, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 419, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 419, "usage_type": "name"}, {"api_name": "utils.send_torrent", "line_number": 430, "usage_type": "call"}, {"api_name": "utils.compose_link", "line_number": 430, "usage_type": "call"}, {"api_name": "bot_utils.update_torr_db", "line_number": 432, "usage_type": "call"}, {"api_name": "transmission_rpc.TransmissionError", "line_number": 434, "usage_type": "name"}, {"api_name": "telegram.ext.ConversationHandler.END", "line_number": 439, "usage_type": "attribute"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 439, "usage_type": "name"}, {"api_name": "telegram.ReplyKeyboardMarkup", "line_number": 448, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 455, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 455, "usage_type": "name"}, {"api_name": "utils.deconvert_imdb_id", "line_number": 461, "usage_type": "call"}, {"api_name": "bot_utils.exclude_torrents_from_watchlist", "line_number": 462, "usage_type": "call"}, {"api_name": "telegram.ext.ConversationHandler.END", "line_number": 465, "usage_type": "attribute"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 465, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 469, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 469, "usage_type": "name"}, {"api_name": "utils.get_user_by_tgram_id", "line_number": 478, "usage_type": "call"}, {"api_name": "bot_utils.add_to_watchlist", "line_number": 484, "usage_type": "call"}, {"api_name": "utils.deconvert_imdb_id", "line_number": 484, "usage_type": "call"}, {"api_name": "bot_utils.add_to_watchlist", "line_number": 486, "usage_type": "call"}, {"api_name": "utils.deconvert_imdb_id", "line_number": 486, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 498, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 498, "usage_type": "name"}, {"api_name": "bot_get_progress.get_progress", "line_number": 502, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 519, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 519, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 531, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 531, "usage_type": "name"}, {"api_name": "bot_csv.csv_upload_handler", "line_number": 541, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 549, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 549, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 558, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 558, "usage_type": "name"}, {"api_name": "utils.get_movies_for_bulk_rating", "line_number": 567, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 576, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 576, "usage_type": "name"}, {"api_name": "bot_utils.get_movie_from_all_databases", "line_number": 581, "usage_type": "call"}, {"api_name": "bot_utils.make_movie_reply", "line_number": 584, "usage_type": "call"}, {"api_name": "telegram.ReplyKeyboardMarkup", "line_number": 589, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 604, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 604, "usage_type": "name"}, {"api_name": "telegram.ReplyKeyboardMarkup", "line_number": 615, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 625, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 625, "usage_type": "name"}, {"api_name": "telegram.ReplyKeyboardMarkup", "line_number": 628, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 636, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 636, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 644, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 644, "usage_type": "name"}, {"api_name": "utils.get_my_movie_by_imdb", "line_number": 659, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 663, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 663, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 670, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 670, "usage_type": "attribute"}, {"api_name": "utils.update_many", "line_number": 672, "usage_type": "call"}, {"api_name": "utils.Movie", "line_number": 672, "usage_type": "argument"}, {"api_name": "utils.Movie.id", "line_number": 672, "usage_type": "attribute"}, {"api_name": "utils.convert_imdb_id", "line_number": 675, "usage_type": "call"}, {"api_name": "utils.get_my_movie_by_imdb", "line_number": 680, "usage_type": "call"}, {"api_name": "utils.update_many", "line_number": 689, "usage_type": "call"}, {"api_name": "utils.Movie", "line_number": 689, "usage_type": "argument"}, {"api_name": "utils.Movie.id", "line_number": 689, "usage_type": "attribute"}, {"api_name": "telegram.Update", "line_number": 703, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 703, "usage_type": "name"}, {"api_name": "utils.get_onetimepasswords", "line_number": 705, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 711, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 711, "usage_type": "attribute"}, {"api_name": "utils.remove_onetimepassword", "line_number": 712, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 728, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 728, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 738, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 738, "usage_type": "name"}, {"api_name": "bot_utils.invite_friend", "line_number": 740, "usage_type": "call"}, {"api_name": "telegram.ReplyKeyboardMarkup", "line_number": 766, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 773, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 773, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 787, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 787, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 794, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 794, "usage_type": "name"}, {"api_name": "utils.update_many", "line_number": 797, "usage_type": "call"}, {"api_name": "utils.User", "line_number": 797, "usage_type": "argument"}, {"api_name": "utils.User.telegram_chat_id", "line_number": 797, "usage_type": "attribute"}, {"api_name": "bot_utils.get_telegram_users", "line_number": 798, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 805, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 805, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 810, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 810, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 819, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 819, "usage_type": "name"}, {"api_name": "bot_csv.csv_download_handler", "line_number": 824, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 835, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 835, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 859, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 859, "usage_type": "name"}, {"api_name": "utils.insert_onetimepasswords", "line_number": 862, "usage_type": "call"}, {"api_name": "sqlalchemy.exc", "line_number": 863, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 864, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 873, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 874, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 874, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 874, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 886, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 886, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 892, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 892, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 902, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 902, "usage_type": "name"}, {"api_name": "bot_watchlist.update_watchlist_item_status", "line_number": 904, "usage_type": "call"}, {"api_name": "telegram.ext.ConversationHandler.END", "line_number": 906, "usage_type": "attribute"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 906, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 910, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 910, "usage_type": "name"}, {"api_name": "utils.update_torrent_grace_days", "line_number": 912, "usage_type": "call"}, {"api_name": "telegram.ext.ConversationHandler.END", "line_number": 914, "usage_type": "attribute"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 914, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 918, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 918, "usage_type": "name"}, {"api_name": "utils.make_client", "line_number": 921, "usage_type": "call"}, {"api_name": "utils.get_torrent_by_torr_id_user", "line_number": 923, "usage_type": "call"}, {"api_name": "telegram.ext.ConversationHandler.END", "line_number": 929, "usage_type": "attribute"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 929, "usage_type": "name"}, {"api_name": "utils.update_torrent_status", "line_number": 932, "usage_type": "call"}, {"api_name": "telegram.ext.ConversationHandler.END", "line_number": 934, "usage_type": "attribute"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 934, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 938, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 938, "usage_type": "name"}, {"api_name": "utils.update_torrent_grace_days", "line_number": 940, "usage_type": "call"}, {"api_name": "telegram.ext.ConversationHandler.END", "line_number": 942, "usage_type": "attribute"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 942, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 946, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 946, "usage_type": "name"}, {"api_name": "utils.update_many", "line_number": 953, "usage_type": "call"}, {"api_name": "utils.User", "line_number": 953, "usage_type": "argument"}, {"api_name": "utils.User.telegram_chat_id", "line_number": 953, "usage_type": "attribute"}, {"api_name": "telegram.Update", "line_number": 958, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackContext", "line_number": 958, "usage_type": "name"}, {"api_name": "utils.update_many", "line_number": 965, "usage_type": "call"}, {"api_name": "utils.User", "line_number": 965, "usage_type": "argument"}, {"api_name": "utils.User.telegram_chat_id", "line_number": 965, "usage_type": "attribute"}, {"api_name": "utils.check_database", "line_number": 975, "usage_type": "call"}, {"api_name": "bot_utils.get_telegram_users", "line_number": 976, "usage_type": "call"}, {"api_name": "telegram.ext.ApplicationBuilder", "line_number": 978, "usage_type": "call"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 980, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 982, "usage_type": "call"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 983, "usage_type": "call"}, {"api_name": "telegram.ext.filters.Regex", "line_number": 983, "usage_type": "call"}, {"api_name": "telegram.ext.filters", "line_number": 983, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 983, "usage_type": "attribute"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 984, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 984, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 984, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 984, "usage_type": "attribute"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 988, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 988, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 988, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 988, "usage_type": "attribute"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 990, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 990, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 990, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 990, "usage_type": "attribute"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 992, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 992, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 992, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 992, "usage_type": "attribute"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 994, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 994, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 994, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 994, "usage_type": "attribute"}, {"api_name": "telegram.ext.CallbackQueryHandler", "line_number": 996, "usage_type": "call"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 998, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 998, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 998, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 998, "usage_type": "attribute"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 1000, "usage_type": "call"}, {"api_name": "telegram.ext.ConversationHandler.END", "line_number": 1005, "usage_type": "attribute"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 1005, "usage_type": "name"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 1009, "usage_type": "call"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 1011, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 1011, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 1011, "usage_type": "name"}, {"api_name": "telegram.ext.CallbackQueryHandler", "line_number": 1012, "usage_type": "call"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 1018, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 1020, "usage_type": "call"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 1021, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 1021, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 1021, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 1021, "usage_type": "attribute"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 1027, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 1027, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 1027, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 1027, "usage_type": "attribute"}, {"api_name": "telegram.ext.ConversationHandler.END", "line_number": 1033, "usage_type": "attribute"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 1033, "usage_type": "name"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 1037, "usage_type": "call"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 1039, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 1039, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 1039, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 1039, "usage_type": "attribute"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 1042, "usage_type": "call"}, {"api_name": "telegram.ext.filters.Regex", "line_number": 1042, "usage_type": "call"}, {"api_name": "telegram.ext.filters", "line_number": 1042, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 1042, "usage_type": "attribute"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 1043, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 1043, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 1043, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 1043, "usage_type": "attribute"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 1045, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 1045, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 1045, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 1045, "usage_type": "attribute"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 1047, "usage_type": "call"}, {"api_name": "telegram.ext.filters.Regex", "line_number": 1047, "usage_type": "call"}, {"api_name": "telegram.ext.filters", "line_number": 1047, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 1047, "usage_type": "attribute"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 1048, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 1048, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 1048, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 1048, "usage_type": "attribute"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 1051, "usage_type": "call"}, {"api_name": "telegram.ext.ConversationHandler.END", "line_number": 1055, "usage_type": "attribute"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 1055, "usage_type": "name"}, {"api_name": "telegram.ext.ConversationHandler", "line_number": 1059, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 1061, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 1062, "usage_type": "call"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 1063, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 1063, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 1063, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 1063, "usage_type": "attribute"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 1066, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 1066, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 1066, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 1066, "usage_type": "attribute"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 1070, "usage_type": "call"}, {"api_name": "telegram.ext.filters.Document.FileExtension", "line_number": 1070, "usage_type": "call"}, {"api_name": "telegram.ext.filters.Document", "line_number": 1070, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 1070, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 1070, "usage_type": "attribute"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 1071, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 1071, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 1071, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 1071, "usage_type": "attribute"}, {"api_name": "telegram.ext.CallbackQueryHandler", "line_number": 1074, "usage_type": "call"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 1075, "usage_type": "call"}, {"api_name": "telegram.ext.filters.TEXT", "line_number": 1075, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 1075, "usage_type": "name"}, {"api_name": "telegram.ext.filters.COMMAND", "line_number": 1075, "usage_type": "attribute"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 1078, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 1079, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 1080, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 1081, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 1082, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 1083, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 1084, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 1085, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 1086, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 1087, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 1088, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 1089, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 1095, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 1096, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 1097, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 1098, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 1099, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 1100, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 1101, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 1102, "usage_type": "call"}, {"api_name": "command_regex_handler.RegexpCommandHandler", "line_number": 1103, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 1104, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 1105, "usage_type": "call"}]} +{"seq_id": "31212702663", "text": "'''\nYou are given a stream of points on the X-Y plane. Design an algorithm that:\n\n- Adds new points from the stream into a data structure. Duplicate points are allowed and should be treated as different points.\n- Given a query point, counts the number of ways to choose three points from the data structure such that the three points and the query point form an axis-aligned square with positive area.\n\nAn axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis.\n\nImplement the DetectSquares class:\n\n- DetectSquares() Initializes the object with an empty data structure.\n- void add(int[] point) Adds a new point point = [x, y] to the data structure.\n- int count(int[] point) Counts the number of ways to form axis-aligned squares with point point = [x, y] as described above.\n'''\nfrom time import time\nfrom typing import List\n\n\nclass DetectSquares:\n def __init__(self, debug=False):\n # Need at least 2x 2 different points for each\n self.p_count = {}\n self.p_arr = []\n self.debug = debug\n\n def add(self, point: List[int]) -> None:\n x, y = point\n if (x, y) not in self.p_count:\n self.p_count[(x, y)] = 1\n else:\n self.p_count[(x, y)] += 1\n self.p_arr.append(point)\n\n def count(self, point: List[int]) -> int:\n res = 0\n px, py = point\n for x, y in self.p_arr:\n if (abs(px - x) != abs(py - y)) or x == px or y == py:\n continue\n a = self.p_count[(x, py)]\n b = self.p_count[(px, y)]\n res += a * b\n\n if self.debug:\n print(res)\n\n return res\n\n\nif __name__ == '__main__':\n test = DetectSquares(debug=True)\n sol_start = time()\n test.add([3, 10])\n test.add([11, 2])\n test.add([3, 2])\n test.count([11, 10]) # Return 1\n test.count([14, 8]) # Return 0\n test.add([11, 2]) # Duplicate allowed\n test.add([11, 1]) # Testing, should not add another square\n test.add([3, 1]) # Testing, should not add another square\n test.count([11, 10]) # Return 2\n print(f'Runtime for our solution: {time() - sol_start}\\n')\n", "repo_name": "stevenxchung/l33t-code-problems", "sub_path": "NeetCode +75/17 - Math and Geometry/2013-detect-squares.py", "file_name": "2013-detect-squares.py", "file_ext": "py", "file_size_in_byte": 2199, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "typing.List", "line_number": 26, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 34, "usage_type": "name"}, {"api_name": "time.time", "line_number": 52, "usage_type": "call"}, {"api_name": "time.time", "line_number": 62, "usage_type": "call"}]} +{"seq_id": "41061890223", "text": "import os\nimport pandas as pd\nimport numpy as np\n#import nltk\nimport cytoolz\n#%%\nfrom suggestion import clustering\nfrom scipy.misc import logsumexp\n#%%\nfrom suggestion.paths import paths\nclizer = pd.read_pickle(os.path.join(paths.parent, 'models', 'goal_oriented_suggestion_data.pkl'))\n#%%\ndata = pd.read_pickle(os.path.join(paths.parent, 'yelp_preproc/all_data.pkl'))\nreviews = data['data'].reset_index(drop=True)\n\n#%%\ndef get_topic_distribution(clizer, target_dist, sent_cluster_distribs, new_dists_opts):\n from scipy.special import kl_div\n with_new_dist = np.array([np.concatenate((sent_cluster_distribs, new_dist_opt[None]), axis=0) for new_dist_opt in new_dists_opts])\n dist_with_new_dist = clustering.normalize_dists(np.mean(with_new_dist, axis=1))\n return kl_div(dist_with_new_dist, target_dist).sum(axis=1)\n\n#%%\nif False:\n scores_by_cluster = clizer.scores_by_cluster.copy()\n likelihood_bias = logsumexp(scores_by_cluster, axis=1, keepdims=True)\n scores_by_cluster -= .85 * likelihood_bias\n scores_by_cluster[suggested_already] = -np.inf\n scores_by_cluster[clizer.omit] = -np.inf\n most_distinctive = np.argmax(scores_by_cluster, axis=0)\n#%%\ntopic_tags = [f'' for i in range(10)]\n\n#%%\n\n# FIXME: this approach is super-biased for predicting topic tags because the topic tags repeat for every sentence.\n# Better would be to separately train topics.\ndef review_to_tagged_sents(sents):\n cluster_distances = cytoolz.thread_first(\n sents,\n clizer.vectorize_sents,\n clustering.normalize_vecs,\n clizer.clusterer.transform)\n clusters_for_sents = np.argmin(cluster_distances, axis=1)\n\n res = []\n for i, sent in enumerate(sents):\n res.append([topic_tags[c] for c in clusters_for_sents[:i+1][-4:]] + sent.lower().split())\n return res\n\nimport tqdm\nfrom suggestion import util\nutil.dump_kenlm('yelp_topic_tagged', [\n ' '.join(s)\n for tokenized in tqdm.tqdm(reviews.tokenized)\n for s in review_to_tagged_sents(tokenized.split('\\n'))])\n#%%\nfrom suggestion import lang_model\ntopic2sentence_lm = lang_model.Model.from_basename(paths.model_basename('yelp_topic_tagged'))\n#%%\nimport itertools\ntopic_transitions_indices = list(itertools.product(range(10), range(10)))\nrev_topic_transitions_indices = [10*i+i for i in range(10)]\n#%%\ntransition_log_likelihoods = np.array([[topic2sentence_lm.score_seq(topic2sentence_lm.get_state([topic_tags[c1], topic_tags[c2]], bos=True)[0], k)[0] for c1, c2 in itertools.product(range(10), range(10))] for k in tqdm.tqdm(clizer.unique_starts, desc=\"Score starts\")])\n#%%\n#scores_by_cluster = scores_by_cluster_raw.copy()\n#likelihood_bias = logsumexp(scores_by_cluster, axis=1, keepdims=True)\n#%%\n#unconditional_likelihood_bias = np.array([[topic2sentence_lm.score_seq(topic2sentence_lm.get_state([topic_tags[c]], bos=True)[0], k)[0] for c in range(10)] for k in tqdm.tqdm(clizer.unique_starts, desc=\"Score starts\")])\nunconditional_likelihood_bias_2 = np.array([\n logsumexp(scores_by_cluster_raw[:,10*i:10*(i+1)], axis=1) for i in range(10)]).T\n#%%\nscores_by_cluster = transition_log_likelihoods - .9*logsumexp(transition_log_likelihoods, axis=1, keepdims=True)#[:,rev_topic_transitions_indices] - 1. * unconditional_likelihood_bias_2\nscores_by_cluster = scores_by_cluster[:,rev_topic_transitions_indices]\nfor cluster_idx in range(clizer.n_clusters):\n i = cluster_idx# + cluster_idx*10\n# print(topic_transitions_indices[i])\n print(i)\n for idx in np.argsort(scores_by_cluster[:,i])[-5:][::-1]:\n print(' '.join(clizer.unique_starts[idx]))\n print('\\n\\n')\n#%%\nfor i in np.argsort(scores_by_cluster[:,8])[-10:]: print(' '.join(clizer.unique_starts[i]))\n#%%\nnp.save('topic_continuation_scores.npy', scores_by_cluster)\n\n#%%\n#%%\ndef get_topic_seq(sents):\n cluster_distances = cytoolz.thread_first(\n sents,\n clizer.vectorize_sents,\n clustering.normalize_vecs,\n clizer.clusterer.transform)\n return np.argmin(cluster_distances, axis=1)\ntopic_seqs = [get_topic_seq(tokenized.split('\\n')) for tokenized in tqdm.tqdm(reviews.tokenized)]\n#%%\n# TODO: This actually needs to pass --discount_fallback to lmplz, and may want to use a high order like 12-gram\nutil.dump_kenlm('yelp_topic_seqs', [' '.join(topic_tags[c] for c in seq) for seq in topic_seqs])\n#%%\ndef review_to_tagged_sents(topic_seq, sents):\n res = []\n for i, sent in enumerate(sents):\n res.append([topic_tags[c] for c in topic_seq[:i+1][-4:]] + sent.lower().split())\n return res\n#%%\n\ntopic_seq_model = suggestion_generator.get_model('yelp_topic_seqs')\ntopic_word_indices = [topic_seq_model.model.vocab_index(tag) for tag in suggestion_generator.topic_tags]", "repo_name": "kcarnold/suggestion", "sub_path": "tmp/tagged_sents.py", "file_name": "tagged_sents.py", "file_ext": "py", "file_size_in_byte": 4707, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "26", "api": [{"api_name": "pandas.read_pickle", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "suggestion.paths.paths.parent", "line_number": 11, "usage_type": "attribute"}, {"api_name": "suggestion.paths.paths", "line_number": 11, "usage_type": "name"}, {"api_name": "pandas.read_pickle", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "suggestion.paths.paths.parent", "line_number": 13, "usage_type": "attribute"}, {"api_name": "suggestion.paths.paths", "line_number": 13, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 19, "usage_type": "call"}, {"api_name": "suggestion.clustering.normalize_dists", "line_number": 20, "usage_type": "call"}, {"api_name": "suggestion.clustering", "line_number": 20, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 20, "usage_type": "call"}, {"api_name": "scipy.special.kl_div", "line_number": 21, "usage_type": "call"}, {"api_name": "scipy.misc.logsumexp", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 28, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 29, "usage_type": "attribute"}, {"api_name": "numpy.argmax", "line_number": 30, "usage_type": "call"}, {"api_name": "cytoolz.thread_first", "line_number": 39, "usage_type": "call"}, {"api_name": "suggestion.clustering.normalize_vecs", "line_number": 42, "usage_type": "attribute"}, {"api_name": "suggestion.clustering", "line_number": 42, "usage_type": "name"}, {"api_name": "numpy.argmin", "line_number": 44, "usage_type": "call"}, {"api_name": "suggestion.util.dump_kenlm", "line_number": 53, "usage_type": "call"}, {"api_name": "suggestion.util", "line_number": 53, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 55, "usage_type": "call"}, {"api_name": "suggestion.lang_model.Model.from_basename", "line_number": 59, "usage_type": "call"}, {"api_name": "suggestion.lang_model.Model", "line_number": 59, "usage_type": "attribute"}, {"api_name": "suggestion.lang_model", "line_number": 59, "usage_type": "name"}, {"api_name": "suggestion.paths.paths.model_basename", "line_number": 59, "usage_type": "call"}, {"api_name": "suggestion.paths.paths", "line_number": 59, "usage_type": "name"}, {"api_name": "itertools.product", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 65, "usage_type": "call"}, {"api_name": "itertools.product", "line_number": 65, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 71, "usage_type": "call"}, {"api_name": "scipy.misc.logsumexp", "line_number": 72, "usage_type": "call"}, {"api_name": "scipy.misc.logsumexp", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 86, "usage_type": "call"}, {"api_name": "cytoolz.thread_first", "line_number": 91, "usage_type": "call"}, {"api_name": "suggestion.clustering.normalize_vecs", "line_number": 94, "usage_type": "attribute"}, {"api_name": "suggestion.clustering", "line_number": 94, "usage_type": "name"}, {"api_name": "numpy.argmin", "line_number": 96, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 97, "usage_type": "call"}, {"api_name": "suggestion.util.dump_kenlm", "line_number": 100, "usage_type": "call"}, {"api_name": "suggestion.util", "line_number": 100, "usage_type": "name"}]} +{"seq_id": "14244890128", "text": "import os\nimport requests\nimport time\nimport sched, time\nimport get_temp\n\nserver = \"https://nikitech.eu/\"\ncontroller = \"nikihome/\"\nfunction = \"temperature_post.php\"\nurl = server + controller + function\n\nhour = 60 * 60\n\nscheduler = sched.scheduler(time.time, time.sleep)\n\ndef post_temperature(scheduler_param):\n \n inside_temp = get_temp.read_temp(get_temp.inside_device)\n outside_temp = get_temp.read_temp(get_temp.outside_device)\n date = int(round(time.time() * 1000))\n \n inside_temp = str(inside_temp)\n outside_temp = str(outside_temp)\n date = str(date)\n \n print(\"Posting temperature: \")\n print(\"inside: \" + inside_temp)\n print(\"outside: \" + outside_temp)\n print(\"______________________\")\n print(\"\\n\")\n \n data = {\n 'inside': inside_temp,\n 'outside': outside_temp,\n 'date': date\n }\n\n\n request = requests.post(url, data = data)\n print(\"Response: \" + request.text)\n \n if scheduler_param is not None:\n scheduler.enter(hour, 1, post_temperature, (scheduler_param,))\n\nprint(\"Uploading current temperature\")\npost_temperature(None)\n\nprint(\"Next upload will be in one hour\")\nscheduler.enter(hour, 1, post_temperature, (scheduler,))\nscheduler.run()\n\n\n\n\n", "repo_name": "Nikituh/scripts", "sub_path": "nikiberry/post_temp.py", "file_name": "post_temp.py", "file_ext": "py", "file_size_in_byte": 1239, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "sched.scheduler", "line_number": 14, "usage_type": "call"}, {"api_name": "time.time", "line_number": 14, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 14, "usage_type": "attribute"}, {"api_name": "get_temp.read_temp", "line_number": 18, "usage_type": "call"}, {"api_name": "get_temp.inside_device", "line_number": 18, "usage_type": "attribute"}, {"api_name": "get_temp.read_temp", "line_number": 19, "usage_type": "call"}, {"api_name": "get_temp.outside_device", "line_number": 19, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 20, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 39, "usage_type": "call"}]} +{"seq_id": "40564563018", "text": "# coding=utf-8\n\nimport requests\nimport grequests\nfrom lxml import html\n\nfrom metacrawler.base import Element\nfrom metacrawler.fields import Field\n\n\nclass Crawler(Element):\n\n \"\"\"Crawler parse page use fields as rules. May be nested.\"\"\"\n\n def __init__(self):\n super().__init__()\n\n self.data = []\n\n if not self.fields:\n raise ValueError('Cannot use `Crawler` without fields.')\n\n if len(self.fields) > 1 and self.collapse:\n raise ValueError(\n 'Must not use `collapse` with few fields or/and crawlers.'\n )\n\n @property\n def fields(self):\n fields = {}\n\n candidates = {}\n candidates.update(self.__dict__)\n candidates.update(self.__class__.__dict__)\n\n for name, attribute in candidates.items():\n if isinstance(attribute, (Crawler, Field)):\n fields[name] = attribute\n\n return fields\n\n def get_url(self):\n return getattr(self.__class__, 'url', None)\n\n def get_pagination(self):\n return getattr(self.__class__, 'pagination', None)\n\n def get_collapse(self):\n return getattr(self.__class__, 'collapse', False)\n\n def get_limit(self):\n return getattr(self.__class__, 'limit', None)\n\n def get_session(self):\n return getattr(self.__class__, 'session', requests.Session())\n\n def get_timeout(self):\n return getattr(self.__class__, 'timeout', 3.0)\n\n def get_authentication(self):\n return getattr(self.__class__, 'authentication', None)\n\n def crawl(self, *args, **kwargs):\n \"\"\"Crawl page.\n\n :returns: `dict` data.\n \"\"\"\n self.before()\n data = []\n\n if self.authentication is not None:\n self.session = self.authentication.authentication(self.session)\n\n def parse(response):\n page = html.fromstring(response.content)\n\n if self.limit is not None and int(self.limit) <= len(data):\n return page\n\n if self.collapse:\n field = list(self.fields.items())[0][1]\n if field.to is list:\n data.extend(field.crawl(page))\n else:\n data.append(field.crawl(page))\n else:\n data.append({n: f.crawl(page) for n, f in self.fields.items()})\n\n return page\n\n try:\n iterator = iter(self.pagination)\n except TypeError:\n iterator = None\n\n if iterator:\n requests_list = []\n\n for url in iterator:\n requests_list.append(grequests.request(\n 'GET', url, session=self.session, timeout=self.timeout\n ))\n\n for response in grequests.map(requests_list):\n if response:\n parse(response)\n else:\n while self.url:\n page = parse(self.session.get(self.url, verify=False))\n self.paginate(page)\n\n if self.pagination:\n self.data.extend(data)\n else:\n self.data = data[0]\n\n return self.clean(self.data)\n\n def paginate(self, page):\n \"\"\"Paginate.\n\n :param page: `lxml.Element` instance.\n \"\"\"\n if self.pagination:\n self.url = self.pagination.next(page)\n else:\n self.url = None\n", "repo_name": "dvemnt/metacrawler", "sub_path": "metacrawler/crawlers.py", "file_name": "crawlers.py", "file_ext": "py", "file_size_in_byte": 3365, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "metacrawler.base.Element", "line_number": 11, "usage_type": "name"}, {"api_name": "metacrawler.fields.Field", "line_number": 37, "usage_type": "name"}, {"api_name": "requests.Session", "line_number": 55, "usage_type": "call"}, {"api_name": "lxml.html.fromstring", "line_number": 75, "usage_type": "call"}, {"api_name": "lxml.html", "line_number": 75, "usage_type": "name"}, {"api_name": "grequests.request", "line_number": 100, "usage_type": "call"}, {"api_name": "grequests.map", "line_number": 104, "usage_type": "call"}]} +{"seq_id": "37642706514", "text": "from flask import Flask, render_template, redirect, request, url_for\nfrom functools import wraps\nfrom functions import get_necessary_number_of_card_names\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index_page():\n return render_template('index.html')\n\n\n@app.route('/game', methods=['GET'])\ndef game_page():\n rows = int(request.args.get('row_num'))\n cols = int(request.args.get('column_num'))\n if rows == 0 or cols == 0:\n return redirect(url_for('index_page'))\n cards = get_necessary_number_of_card_names(cols, rows)\n return render_template('game.html', rows=rows, cols=cols, cards=cards)\n\n\n@app.errorhandler(404)\ndef handle_404(e):\n return render_template('error.html', code=404), 404\n\n\nif __name__ == '__main__':\n app.secret_key = 'magic'\n app.run(debug=True, port=5000)\n", "repo_name": "CodecoolBP20172/wswp-memory-game-DanielKnoll", "sub_path": "server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 805, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "flask.Flask", "line_number": 4, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 9, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 14, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 14, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 14, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 15, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 15, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 15, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 17, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 17, "usage_type": "call"}, {"api_name": "functions.get_necessary_number_of_card_names", "line_number": 18, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 19, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 24, "usage_type": "call"}]} +{"seq_id": "35641561695", "text": "from tqdm import tqdm\nimport torch\nimport csv\nimport numpy as np\nfrom loss import IOU\n\ndef Train(model, epochs, optimizer, scheduler, loss_fn, train_iter, val_iter, device, early_stopping, DeepLab=False):\n # Create dictionary to store history\n Loss = {\"val_iou\":[]}\n\n with open('./models/readme.txt', 'w') as f:\n f.write('Model: {} \\n Max Epochs: {} \\n Optimizer: {} \\n Scheduler: {} \\n Loss Function: {} \\n Device: {} \\n Early Stopping: {}'.format(model, epochs, optimizer, scheduler, loss_fn, device, early_stopping))\n\n with open('./models/log.csv', 'w') as f:\n writer = csv.writer(f)\n writer.writerow([\"epoch\",\"train_loss\",\"train_iou\",\"val_loss\",\"val_iou\"])\n \n # Set patience to zero.\n patience = 0\n\n for epoch in range(epochs):\n # Set model in training mode\n model.train()\n\n # Initialise cumulative loss\n train_loss, train_iou, val_loss, val_iou = 0, 0, 0, 0\n \n # Print LR if it has decreased.\n if epoch != 0:\n if optimizer.param_groups[0]['lr'] < LR:\n print('Learning rate decreased to ', optimizer.param_groups[0]['lr'])\n else:\n print('Initial learning rate set to ', optimizer.param_groups[0]['lr'])\n LR = optimizer.param_groups[0]['lr']\n\n # Loop over the training set\n for i, data in enumerate(tqdm(train_iter)):\n inputs, labels = data[0].to(device), data[1].to(device)\n\n # Zero previous gradients\n optimizer.zero_grad()\n \n \n # Generate predictions and loss with current model parameters\n if DeepLab == True:\n outputs = model(inputs)[\"out\"]\n else:\n outputs = model(inputs)\n loss = loss_fn(outputs, labels)\n\n # Initiate backpropagation to adjust loss weights\n loss.backward()\n optimizer.step()\n\n # Update total training loss\n train_loss += loss\n train_iou += IOU(outputs, labels, device)\n train_steps = i+1\n\n with torch.no_grad():\n # Set the model to evaluation mode\n model.eval()\n\n # Loop over the validation set\n for i, data in enumerate(tqdm(val_iter)):\n inputs, labels = data[0].to(device), data[1].to(device)\n\n # Calculate validation loss\n if DeepLab == True:\n outputs = model(inputs)[\"out\"]\n else:\n outputs = model(inputs)\n val_loss += loss_fn(outputs, labels)\n val_iou += IOU(outputs, labels, device)\n val_steps = i+1\n \n # Calculate the average training and validation loss\n avg_train_loss = float(train_loss / train_steps)\n avg_train_iou = float(train_iou / train_steps)\n avg_val_loss = float(val_loss / val_steps)\n avg_val_iou = float(val_iou / val_steps)\n \n if scheduler is not None:\n scheduler.step(avg_val_loss)\n\n # Save the best model if appropriate, else continue.\n if epoch == 0:\n torch.save(model.state_dict(), \"./models/model.pth\")\n print(\"Saved best model!\")\n elif avg_val_iou > np.max(Loss[\"val_iou\"]):\n torch.save(model.state_dict(), './models/model.pth')\n print(\"Saved best model!\")\n patience = 0\n else:\n patience += 1\n\n # Update train and val loss history\n Loss[\"val_iou\"].append(avg_val_iou)\n\n with open('./models/log.csv', 'a') as csv_file:\n dict_object = csv.DictWriter(csv_file, fieldnames=[\"epoch\",\"train_loss\",\"train_iou\",\"val_loss\",\"val_iou\"])\n dict_object.writerow({\"epoch\":epoch,\"train_loss\":avg_train_loss,\"train_iou\":avg_train_iou,\"val_loss\":avg_val_loss,\"val_iou\":avg_val_iou})\n\n print(\"Epoch {}, Train Loss {:3f}, Train IOU {:3f}, Val Loss {:3f}, Val IOU {:3f}\".format(\n epoch, avg_train_loss, avg_train_iou, avg_val_loss, avg_val_iou))\n \n if patience > early_stopping:\n print(\"Early stopping triggered, best val IOU: {}\".format(np.max(Loss[\"val_iou\"])))\n break", "repo_name": "christianmcb/Deep-Learning-Project", "sub_path": "code/training.py", "file_name": "training.py", "file_ext": "py", "file_size_in_byte": 4212, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "csv.writer", "line_number": 15, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 37, "usage_type": "call"}, {"api_name": "loss.backward", "line_number": 52, "usage_type": "call"}, {"api_name": "loss.IOU", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 60, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 65, "usage_type": "call"}, {"api_name": "loss.IOU", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 91, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 108, "usage_type": "call"}]} +{"seq_id": "17126482545", "text": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\n# Specify the path to your browser driver executable\n# Example: For Chrome, you may use chromedriver.exe\ndriver_path = '/path/to/driver'\n\n# Create a new instance of the browser driver\ndriver = webdriver.Chrome(executable_path=driver_path)\n\n# Open the website in the browser\nwebsite_url = 'https://www.example.com'\ndriver.get(website_url)\n\n# Perform an action on the website\nelement = driver.find_element_by_id('button-id') # Replace 'button-id' with the actual ID of the button\nelement.click()\n\n# Additional actions can be performed here, such as filling forms or navigating through the website\n\n# Extract information from the web page\nelement = driver.find_element_by_xpath('//div[@class=\"info\"]') # Replace with the appropriate XPath to locate the desired element\ntext = element.text\nprint(f\"Extracted information: {text}\")\n\n# Close the browser\ndriver.quit()\n", "repo_name": "drissraki/test1", "sub_path": "arkx/test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 943, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "selenium.webdriver.Chrome", "line_number": 9, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 9, "usage_type": "name"}]} +{"seq_id": "1800374324", "text": "from flask import Flask, request, render_template\nimport Bot\nimport wikipedia as wk\nimport wolframalpha\n\nAPIkey = \"R62U64-JYYVGAVHHU\"\nwolf = wolframalpha.Client(APIkey)\n\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n@app.route(\"/get\")\ndef chat():\n flag = True\n while (flag == True):\n user_response = request.args.get('msg')\n\n user_response = user_response.lower()\n if (user_response != 'bye'):\n if (user_response == 'thanks' or user_response == 'thank you'):\n flag = False\n response = \"You are welcome..\"\n return response\n else:\n if (Bot.greeting(user_response) != None):\n response = Bot.greeting(user_response)\n return response\n else:\n try:\n res = wolf.query(user_response)\n response = next(res.results).text\n except:\n try:\n response = wk.summary(user_response, sentences = 3)\n except:\n response = \"May you try to refine your query, I am still learning please be patient with me\"\n\n return response\n else:\n flag = False\n response = \"Good Bye! \"\n return response\n\nif __name__ == \"__main__\":\n app.run()\n", "repo_name": "rapha18th/phonicwolf", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1453, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "wolframalpha.Client", "line_number": 7, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 10, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 14, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 19, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 19, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 19, "usage_type": "name"}, {"api_name": "Bot.greeting", "line_number": 28, "usage_type": "call"}, {"api_name": "Bot.greeting", "line_number": 29, "usage_type": "call"}, {"api_name": "wikipedia.summary", "line_number": 37, "usage_type": "call"}]} +{"seq_id": "45085745510", "text": "\"\"\"\nCreated on Fri Feb 12 12:54:33 2021\n\n@author: Ben Horowitz (and friends)\n\nFrom lenspack implementation\n\"\"\"\nimport tensorflow as tf\nimport numpy as np\nimport tensorflow_probability as tfp\nfrom DifferentiableHOS.transforms import starlet2d\n\n\ndef _kernel(bw, X, x):\n \"\"\"Gaussian kernel for KDE\"\"\"\n return (1.0 / np.sqrt(2 * np.pi) / bw) * tf.math.exp(-((X - x)**2) /\n (bw**2 * 2.0))\n\n\ndef _get_wavelet_normalization(image, nscales):\n \"\"\" Computes normalizing constant for starlet, for given image.\n \"\"\"\n _, nx, ny = image.get_shape()\n knorm = tf.ones((1, 1, 1, 1), dtype=tf.float32)\n knorm = tf.image.resize_with_crop_or_pad(knorm, nx, ny)\n wt = starlet2d(knorm[..., 0], nscales=nscales)\n return [tf.math.sqrt(tf.reduce_sum(c**2)) for c in wt]\n\n\n@tf.function\ndef find_peaks2d_tf(image, mask=None, ordered=True, threshold=None):\n if mask is not None:\n # mask = np.atleast_2d(mask)\n if mask.shape != image.shape:\n print(\"Warning: mask not compatible with image -> ignoring.\")\n mask = tf.ones(image.shape)\n else:\n # Make sure mask is binary, i.e. turn nonzero values into ones\n mask = tf.cast(tf.cast(mask, bool), float)\n else:\n mask = tf.ones(image.shape)\n\n if threshold is None:\n threshold = tf.math.reduce_min(image)\n else:\n threshold = tf.math.reduce_max((threshold, tf.math.reduce_min(image)))\n\n offset = tf.math.reduce_min(image)\n threshold = threshold - offset\n image = image - offset\n\n map0 = image[1:-1, 1:-1]\n\n # Extract shifted maps\n map1 = image[0:-2, 0:-2]\n map2 = image[1:-1, 0:-2]\n map3 = image[2:, 0:-2]\n map4 = image[0:-2, 1:-1]\n map5 = image[2:, 1:-1]\n map6 = image[0:-2, 2:]\n map7 = image[1:-1, 2:]\n map8 = image[2:, 2:]\n\n merge = ((map0 > map1) & (map0 > map2) & (map0 > map3) & (map0 > map4) &\n (map0 > map5) & (map0 > map6) & (map0 > map7) & (map0 > map8))\n\n bordered = tf.pad(merge,\n tf.constant(((1, 1), (1, 1))),\n constant_values=0.0)\n peaksmap = tf.cast(bordered, float) * image * mask\n XY = tf.where(peaksmap > threshold)\n heights = tf.gather_nd(image, XY) + offset\n\n if ordered:\n ind = tf.argsort(heights)[::-1]\n return tf.gather(XY[:, 0],\n ind), tf.gather(XY[:, 1],\n ind), tf.gather(heights, ind)\n return XY[:, 0], XY[:, 1], heights\n\n\n@tf.function\ndef peaks_histogram_tf_mulscale(image,\n nscales=3,\n bins=None,\n mask=None,\n name='peakscount',\n bw_factor=2.):\n \"\"\"Compute a histogram of peaks in a 2d Starlet transform of the input image.\n\n Parameters\n ----------\n image : tensor (2D)\n Two-dimensional input tensor\n nscales: int\n Number of wavelet scales to include\n in the decomposition.\n value_range: Shape [2] Tensor of same dtype as image\n Range of values in the Histogram.\n bins : int or tensor (1D), optional\n Specification of centers or the number of bins to use for the\n histogram. If not provided, a default of 10 bins linearly spaced\n between the image minimum and maximum (inclusive) is used.\n mask : tensor (same shape as `image`), optional\n Tensor identifying which pixels of `image` to consider/exclude\n in finding peaks. Can either either be numeric (0 or 1) or boolean \n (false or true)\n bw_factor: float\n Factor by which to divide the bin width to define the bandwidth of the\n smoothing kernel.\n Returns\n -------\n results, bins : list of 1D tensors\n Histogram and bin boundary values. \n \"\"\"\n with tf.name_scope(name):\n image = tf.cast(image, dtype=tf.float32)\n\n # Compute the wavelet normalization factor\n norm_factors = _get_wavelet_normalization(image, nscales)\n\n # Compute wavelet transform\n wt = starlet2d(image, nscales)\n results = []\n # Loop over all wavelet scales\n for coeffs, factor in zip(wt, norm_factors):\n # Normalizing coefficients to preserve standard deviations\n # across scales\n coeffs = coeffs / factor\n\n # Histogram the coefficient values\n image = tf.reshape(coeffs, [coeffs.shape[1], coeffs.shape[2]])\n if bins is None:\n bins = tf.linspace(tf.math.reduce_min(image),\n tf.math.reduce_max(image), 10)\n elif isinstance(bins, int):\n bins = tf.linspace(tf.math.reduce_min(image),\n tf.math.reduce_max(image), bins)\n else:\n bins = bins\n\n x, y, heights = find_peaks2d_tf(image, threshold=None, mask=mask)\n\n # To avoid issues, we clip the image to within the peaks\n heights = tf.clip_by_value(heights, bins[0], bins[-1])\n w = tf.reshape(tf.ones_like(heights), [-1])\n k = _kernel(\n tf.reduce_mean((bins[1:] - bins[:-1])) / bw_factor,\n tf.reshape(heights, [-1, 1]), bins)\n k = k / tf.reduce_sum(k, axis=1, keepdims=True)\n counts = tf.tensordot(k, w, axes=[[0], [0]])\n results.append(counts)\n return results, bins\n\n\n@tf.function\ndef peaks_histogram_tf(image, bins=None, mask=None, bw_factor=2.):\n \"\"\"Compute a histogram of peaks in a 2d image.\n Parameters\n ----------\n image : tensor (2D)\n Two-dimensional input tensor\n bins : int or tensor (1D), optional\n Specification of centers or the number of bins to use for the\n histogram. If not provided, a default of 10 bins linearly spaced\n between the image minimum and maximum (inclusive) is used.\n mask : tensor (same shape as `image`), optional\n Tensor identifying which pixels of `image` to consider/exclude\n in finding peaks. Can either either be numeric (0 or 1) or boolean \n (false or true)\n bw_factor: float\n Factor by which to divide the bin width to define the bandwidth of the\n smoothing kernel.\n Returns\n -------\n counts, bins : tuple of 1D tensors\n Histogram and bin boundary values. If the returned `counts` has \n N values, `bin_edges` will have N + 1 values.\n \"\"\"\n image = tf.cast(image, dtype=tf.float32)\n if bins is None:\n bins = tf.linspace(tf.math.reduce_min(image),\n tf.math.reduce_max(image), 10)\n elif isinstance(bins, int):\n bins = tf.linspace(tf.math.reduce_min(image),\n tf.math.reduce_max(image), bins)\n else:\n bins = bins\n\n x, y, heights = find_peaks2d_tf(image, threshold=None, mask=mask)\n\n # To avoid issues, we clip the image to within the peaks\n heights = tf.clip_by_value(heights, bins[0], bins[-1])\n\n w = tf.reshape(tf.ones_like(heights), [-1])\n k = _kernel(\n tf.reduce_mean((bins[1:] - bins[:-1])) / bw_factor,\n tf.reshape(heights, [-1, 1]), bins)\n k = k / tf.reduce_sum(k, axis=1, keepdims=True)\n counts = tf.tensordot(k, w, axes=[[0], [0]])\n\n return counts, bins\n\n\n@tf.function\ndef non_diffable_peaks_histogram_tf(image, bins=None, mask=None):\n \"\"\"Compute a histogram of peaks in a 2d image.\n\n CAREFULL: This implementation is not differentiable\n\n Parameters\n ----------\n image : tensor (2D)\n Two-dimensional input tensor\n bins : int or tensor (1D), optional\n Specification of bin edges or the number of bins to use for the\n histogram. If not provided, a default of 10 bins linearly spaced\n between the image minimum and maximum (inclusive) is used.\n mask : tensor (same shape as `image`), optional\n Tensor identifying which pixels of `image` to consider/exclude\n in finding peaks. Can either either be numeric (0 or 1) or boolean \n (false or true)\n Returns\n -------\n counts, bins : tuple of 1D tensors\n Histogram and bin boundary values. If the returned `counts` has \n N values, `bin_edges` will have N + 1 values.\n \"\"\"\n if bins is None:\n bins = tf.linspace(tf.math.reduce_min(image),\n tf.math.reduce_max(image), 10)\n elif isinstance(bins, int):\n bins = tf.linspace(tf.math.reduce_min(image),\n tf.math.reduce_max(image), bins)\n else:\n bins = bins\n\n x, y, heights = find_peaks2d_tf(image, threshold=None, mask=mask)\n # To avoid issues, we clip the image to within the peaks\n heights = tf.clip_by_value(heights, bins[0], bins[-1])\n\n counts = tfp.stats.histogram(heights, bins)\n return counts, bins\n", "repo_name": "LSSTDESC/DifferentiableHOS", "sub_path": "DifferentiableHOS/statistics/peak_counts_tf.py", "file_name": "peak_counts_tf.py", "file_ext": "py", "file_size_in_byte": 8896, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "26", "api": [{"api_name": "numpy.sqrt", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 16, "usage_type": "attribute"}, {"api_name": "tensorflow.math.exp", "line_number": 16, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 16, "usage_type": "attribute"}, {"api_name": "tensorflow.ones", "line_number": 24, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 24, "usage_type": "attribute"}, {"api_name": "tensorflow.image.resize_with_crop_or_pad", "line_number": 25, "usage_type": "call"}, {"api_name": "tensorflow.image", "line_number": 25, "usage_type": "attribute"}, {"api_name": "DifferentiableHOS.transforms.starlet2d", "line_number": 26, "usage_type": "call"}, {"api_name": "tensorflow.math.sqrt", "line_number": 27, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 27, "usage_type": "attribute"}, {"api_name": "tensorflow.reduce_sum", "line_number": 27, "usage_type": "call"}, {"api_name": "tensorflow.ones", "line_number": 36, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.ones", "line_number": 41, "usage_type": "call"}, {"api_name": "tensorflow.math.reduce_min", "line_number": 44, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 44, "usage_type": "attribute"}, {"api_name": "tensorflow.math.reduce_max", "line_number": 46, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 46, "usage_type": "attribute"}, {"api_name": "tensorflow.math.reduce_min", "line_number": 46, "usage_type": "call"}, {"api_name": "tensorflow.math.reduce_min", "line_number": 48, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 48, "usage_type": "attribute"}, {"api_name": "tensorflow.pad", "line_number": 67, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 68, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 70, "usage_type": "call"}, {"api_name": "tensorflow.where", "line_number": 71, "usage_type": "call"}, {"api_name": "tensorflow.gather_nd", "line_number": 72, "usage_type": "call"}, {"api_name": "tensorflow.argsort", "line_number": 75, "usage_type": "call"}, {"api_name": "tensorflow.gather", "line_number": 76, "usage_type": "call"}, {"api_name": "tensorflow.gather", "line_number": 77, "usage_type": "call"}, {"api_name": "tensorflow.gather", "line_number": 78, "usage_type": "call"}, {"api_name": "tensorflow.function", "line_number": 30, "usage_type": "attribute"}, {"api_name": "tensorflow.name_scope", "line_number": 116, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 117, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 117, "usage_type": "attribute"}, {"api_name": "DifferentiableHOS.transforms.starlet2d", "line_number": 123, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 132, "usage_type": "call"}, {"api_name": "tensorflow.linspace", "line_number": 134, "usage_type": "call"}, {"api_name": "tensorflow.math.reduce_min", "line_number": 134, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 134, "usage_type": "attribute"}, {"api_name": "tensorflow.math.reduce_max", "line_number": 135, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 135, "usage_type": "attribute"}, {"api_name": "tensorflow.linspace", "line_number": 137, "usage_type": "call"}, {"api_name": "tensorflow.math.reduce_min", "line_number": 137, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 137, "usage_type": "attribute"}, {"api_name": "tensorflow.math.reduce_max", "line_number": 138, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 138, "usage_type": "attribute"}, {"api_name": "tensorflow.clip_by_value", "line_number": 145, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 146, "usage_type": "call"}, {"api_name": "tensorflow.ones_like", "line_number": 146, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 148, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 149, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 150, "usage_type": "call"}, {"api_name": "tensorflow.tensordot", "line_number": 151, "usage_type": "call"}, {"api_name": "tensorflow.function", "line_number": 82, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 180, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 180, "usage_type": "attribute"}, {"api_name": "tensorflow.linspace", "line_number": 182, "usage_type": "call"}, {"api_name": "tensorflow.math.reduce_min", "line_number": 182, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 182, "usage_type": "attribute"}, {"api_name": "tensorflow.math.reduce_max", "line_number": 183, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 183, "usage_type": "attribute"}, {"api_name": "tensorflow.linspace", "line_number": 185, "usage_type": "call"}, {"api_name": "tensorflow.math.reduce_min", "line_number": 185, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 185, "usage_type": "attribute"}, {"api_name": "tensorflow.math.reduce_max", "line_number": 186, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 186, "usage_type": "attribute"}, {"api_name": "tensorflow.clip_by_value", "line_number": 193, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 195, "usage_type": "call"}, {"api_name": "tensorflow.ones_like", "line_number": 195, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 197, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 198, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 199, "usage_type": "call"}, {"api_name": "tensorflow.tensordot", "line_number": 200, "usage_type": "call"}, {"api_name": "tensorflow.function", "line_number": 156, "usage_type": "attribute"}, {"api_name": "tensorflow.linspace", "line_number": 230, "usage_type": "call"}, {"api_name": "tensorflow.math.reduce_min", "line_number": 230, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 230, "usage_type": "attribute"}, {"api_name": "tensorflow.math.reduce_max", "line_number": 231, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 231, "usage_type": "attribute"}, {"api_name": "tensorflow.linspace", "line_number": 233, "usage_type": "call"}, {"api_name": "tensorflow.math.reduce_min", "line_number": 233, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 233, "usage_type": "attribute"}, {"api_name": "tensorflow.math.reduce_max", "line_number": 234, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 234, "usage_type": "attribute"}, {"api_name": "tensorflow.clip_by_value", "line_number": 240, "usage_type": "call"}, {"api_name": "tensorflow_probability.stats.histogram", "line_number": 242, "usage_type": "call"}, {"api_name": "tensorflow_probability.stats", "line_number": 242, "usage_type": "attribute"}, {"api_name": "tensorflow.function", "line_number": 205, "usage_type": "attribute"}]} +{"seq_id": "38595173578", "text": "from django.shortcuts import render\nfrom .models import Book, Person\nfrom datetime import date\n\n# Create your views here.\ndef home(request):\n # pass Books and people from database to template\n books = Book.objects.all()\n people = Person.objects.all().count()\n\n # keeps count of how many books are checked out, late, and due today\n late = 0\n due_today = 0\n\n # counts how many books are late and due today\n today = date.today()\n today = int(str(today.year)+str(today.month).zfill(2)+str(today.day).zfill(2))\n for book in books.filter(available=False):\n if today > int(book.due_date): # count how many books are late\n late = late + 1\n if today == int(book.due_date): # count how many books are due today\n due_today = due_today + 1\n checked_out = books.filter(available=False).count() - due_today - late\n context ={\n 'books': books,\n 'person': people,\n 'out': checked_out,\n 'late': late,\n 'today': due_today,\n 'Home': \"active\",\n }\n return render(request, 'active_template/index.html', context)\n\ndef checkedout_books(request):\n today = date.today()\n todays_date = int(str(today.year)+str(today.month).zfill(2)+str(today.day).zfill(2))\n books_out = Book.objects.filter(available=False).order_by('due_date')\n\n context = {\n 'books_out': books_out,\n 'today': todays_date\n }\n return render(request, 'active_template/checkedout.html', context)\n\ndef due_today(request):\n today = date.today()\n todays_date = int(str(today.year)+str(today.month).zfill(2)+str(today.day).zfill(2))\n due = Book.objects.filter(due_date=todays_date)\n return render(request, 'active_template/duetoday.html', {'due': due})\n\ndef overdue(request):\n today = date.today()\n todays_date = int(str(today.year) + str(today.month).zfill(2) + str(today.day).zfill(2))\n overdue = Book.objects.filter(available=False).order_by('-due_date')\n\n context = {\n 'overdue': overdue,\n 'today': todays_date\n }\n return render(request, 'active_template/overdue.html', context)\n\ndef help(request):\n return render(request, 'active_template/help.html', {'Help': 'active'})", "repo_name": "luismoralesXD/FBLA_Coding_and_Programming", "sub_path": "BookManager/Database/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2210, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "models.Book.objects.all", "line_number": 8, "usage_type": "call"}, {"api_name": "models.Book.objects", "line_number": 8, "usage_type": "attribute"}, {"api_name": "models.Book", "line_number": 8, "usage_type": "name"}, {"api_name": "models.Person.objects.all", "line_number": 9, "usage_type": "call"}, {"api_name": "models.Person.objects", "line_number": 9, "usage_type": "attribute"}, {"api_name": "models.Person", "line_number": 9, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 16, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 32, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 35, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 35, "usage_type": "name"}, {"api_name": "models.Book.objects.filter", "line_number": 37, "usage_type": "call"}, {"api_name": "models.Book.objects", "line_number": 37, "usage_type": "attribute"}, {"api_name": "models.Book", "line_number": 37, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 43, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 46, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 46, "usage_type": "name"}, {"api_name": "models.Book.objects.filter", "line_number": 48, "usage_type": "call"}, {"api_name": "models.Book.objects", "line_number": 48, "usage_type": "attribute"}, {"api_name": "models.Book", "line_number": 48, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 49, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 52, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 52, "usage_type": "name"}, {"api_name": "models.Book.objects.filter", "line_number": 54, "usage_type": "call"}, {"api_name": "models.Book.objects", "line_number": 54, "usage_type": "attribute"}, {"api_name": "models.Book", "line_number": 54, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 60, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 63, "usage_type": "call"}]} +{"seq_id": "660704872", "text": "import os\nimport re\nfrom utils import getLines, mkFileIfNot\n\n\nINIT_ENVS = {\n \"DJA_PATH\": os.path.dirname(__file__)\n}\n\n\nclass Env:\n def __init__(self, v=False):\n self.v = v\n mkFileIfNot('.djaenv')\n\n \n def getEnvs(self):\n envs = {}\n lines = getLines('.djaenv')\n\n for i in range(len(lines)):\n match = re.match(r'([A-Z_]+)=(.+)', lines[i])\n \n if re.match:\n envs[match.group(1)] = match.group(2)\n \n return envs\n\n\n def getEnv(self, name):\n envs = self.getEnvs()\n if name in envs:\n return envs[name]\n else:\n if self.v == True:\n print(f'env \"{name}\" not found /_/')\n return -1\n\n\n def setEnv(self, name, value):\n \"\"\"\n If env found set value of env and return 0\n If env not found create env and return 1 \n \"\"\"\n rv = 0\n envs = self.getEnvs()\n if not name in envs:\n rv = 1\n\n envs[name] = value\n with open(\".djaenv\", \"w\") as f:\n f.write(\"\\n\".join([f'{k}={envs[k]}' for k in envs]))\n \n return rv\n\nENV = Env()\n\nfor k, v in INIT_ENVS.items():\n ENV.setEnv(k, v)", "repo_name": "naraSokami/djaVite", "sub_path": "env.py", "file_name": "env.py", "file_ext": "py", "file_size_in_byte": 1242, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.path.dirname", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "utils.mkFileIfNot", "line_number": 14, "usage_type": "call"}, {"api_name": "utils.getLines", "line_number": 19, "usage_type": "call"}, {"api_name": "re.match", "line_number": 22, "usage_type": "call"}, {"api_name": "re.match", "line_number": 24, "usage_type": "attribute"}]} +{"seq_id": "39481577064", "text": "import os\nfrom typing import Optional\n\nimport yaml\n\nfrom agent.commons.collector_exceptions import CollectorException\n\n\nclass CollectorDefinitions:\n COLLECTOR_DEFINITIONS_FILENAME = \"collector_definitions.yaml\"\n\n _collector_globals: Optional[dict] = None\n _collector_inputs: Optional[dict] = None\n\n @staticmethod\n def get_collector_globals() -> dict:\n if CollectorDefinitions._collector_globals is None:\n CollectorDefinitions._load_collector_definitions()\n\n return CollectorDefinitions._collector_globals\n\n @staticmethod\n def get_input_definitions(input_name: str) -> dict:\n if CollectorDefinitions._collector_inputs is None:\n CollectorDefinitions._load_collector_definitions()\n\n return CollectorDefinitions._collector_inputs.get(input_name)\n\n @staticmethod\n def _load_collector_definitions() -> None:\n loaded_collector_definitions = False\n with open(\n os.path.join(\n os.getcwd(),\n \"config_internal\",\n CollectorDefinitions.COLLECTOR_DEFINITIONS_FILENAME\n )\n ) as service_definitions_file:\n service_definitions_content = yaml.safe_load(service_definitions_file)\n if service_definitions_content:\n CollectorDefinitions._collector_globals = service_definitions_content.get(\"collector_globals\")\n CollectorDefinitions._collector_inputs = service_definitions_content.get(\"collector_inputs\")\n loaded_collector_definitions = True\n if loaded_collector_definitions is False:\n raise CollectorException(0, \"Collector definitions were not loaded\")\n", "repo_name": "sahil-metron/All-neccessary-code-check", "sub_path": "agent/collectordefinitions/collector_definitions.py", "file_name": "collector_definitions.py", "file_ext": "py", "file_size_in_byte": 1704, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.Optional", "line_number": 12, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 13, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 34, "usage_type": "call"}, {"api_name": "yaml.safe_load", "line_number": 39, "usage_type": "call"}, {"api_name": "agent.commons.collector_exceptions.CollectorException", "line_number": 45, "usage_type": "call"}]} +{"seq_id": "74408059907", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Refer from: https://github.com/MaybeShewill-CV/CRNN_Tensorflow/blob/master/crnn_model/crnn_model.py\n# @Site : http://github.com/TJCVRS\n\n\"\"\"\nImplement the crnn model mentioned in An End-to-End Trainable Neural Network for Image-based Sequence\nRecognition and Its Application to Scene Text Recognition paper\n\"\"\"\nimport os\nimport os.path as ops\nimport time\n\nimport numpy as np\nfrom collections import namedtuple\nfrom utils import tf_utils,log_utils\n\nimport tensorflow as tf\n#from utils import tf_extended\n\nfrom tensorflow.contrib import layers as tflayers\nfrom tensorflow.contrib import rnn\n\n\nfrom nets.crnn import cnn_basenet\nlogger = log_utils.init_logger()\n\nHIDDEN_NUMS = 256\nNUM_CLASSES = 10\n\n# Test setting\nis_recursive = False # Recursively test the dataset \nloops_nums = 100\n\nclass CRNNnet(cnn_basenet.CNNBaseModel):\n \"\"\"\n Implement the crnn model for squence recognition\n \"\"\"\n #def __init__(self, phase, hidden_nums, layers_nums, seq_length, num_classes):\n def __init__(self, phase, num_classes=NUM_CLASSES+1):\n \"\"\"\n\n :param phase:\n \"\"\"\n super(CRNNnet, self).__init__()\n self.__phase = phase\n #self.__hidden_nums = hidden_nums\n #self.__layers_nums = layers_nums\n #self.__seq_length = seq_length\n self.__num_classes = num_classes\n return\n\n @property\n def phase(self):\n \"\"\"\n\n :return:\n \"\"\"\n return self.__phase\n\n @phase.setter\n def phase(self, value):\n \"\"\"\n\n :param value:\n :return:\n \"\"\"\n if not isinstance(value, str):\n raise TypeError('value should be a str \\'Test\\' or \\'Train\\'')\n if value.lower() not in ['test', 'train']:\n raise ValueError('value should be a str \\'Test\\' or \\'Train\\'')\n self.__phase = value.lower()\n return\n\n def __conv_stage(self, inputdata, out_dims, name=None):\n \"\"\"\n Traditional conv stage in VGG format\n :param inputdata:\n :param out_dims:\n :return:\n \"\"\"\n conv = self.conv2d(inputdata=inputdata, out_channel=out_dims, kernel_size=3, stride=1, use_bias=False, name=name)\n relu = self.relu(inputdata=conv)\n max_pool = self.maxpooling(inputdata=relu, kernel_size=2, stride=2)\n return max_pool\n\n def __feature_sequence_extraction(self, inputdata):\n \"\"\"\n Implement the 2.1 Part Feature Sequence Extraction\n :param inputdata: eg. batch*32*128*3 NHWC format\n :return:\n end_points: a set of activations for external use, for example summaries or\n losses.\n \"\"\"\n # end_points collect relevant activations for external use.\n end_points = {}\n \n conv1 = self.__conv_stage(inputdata=inputdata, out_dims=64, name='conv1') # batch*16*64*64\n end_points['conv1'] = conv1\n conv2 = self.__conv_stage(inputdata=conv1, out_dims=128, name='conv2') # batch*8*32*128\n end_points['conv2'] = conv2\n conv3 = self.conv2d(inputdata=conv2, out_channel=256, kernel_size=3, stride=1, use_bias=False, name='conv3') # batch*8*32*256 \n relu3 = self.relu(conv3) # batch*8*32*256 \n end_points['conv3'] = relu3\n conv4 = self.conv2d(inputdata=relu3, out_channel=256, kernel_size=3, stride=1, use_bias=False, name='conv4') # batch*8*32*256\n relu4 = self.relu(conv4) # batch*8*32*256\n max_pool4 = self.maxpooling(inputdata=relu4, kernel_size=[2, 1], stride=[2, 1], padding='VALID') # batch*4*32*256\n end_points['conv4'] = max_pool4\n conv5 = self.conv2d(inputdata=max_pool4, out_channel=512, kernel_size=3, stride=1, use_bias=False, name='conv5') # batch*4*32*512\n relu5 = self.relu(conv5) # batch*4*32*512\n if self.phase.lower() == 'train':\n bn5 = self.layerbn(inputdata=relu5, is_training=True)\n else:\n bn5 = self.layerbn(inputdata=relu5, is_training=False) # batch*4*32*512\n max_pool5 = self.maxpooling(inputdata=bn5, kernel_size=2, stride=2) #maxpool H and W\n end_points['conv5'] = max_pool5\n conv6 = self.conv2d(inputdata=max_pool5, out_channel=512, kernel_size=3, stride=1, use_bias=False, name='conv6') # batch*4*32*512\n relu6 = self.relu(conv6) # batch*4*32*512\n if self.phase.lower() == 'train':\n bn6 = self.layerbn(inputdata=relu6, is_training=True)\n else:\n bn6 = self.layerbn(inputdata=relu6, is_training=False) # batch*4*32*512\n max_pool6 = self.maxpooling(inputdata=bn6, kernel_size=[2, 1], stride=[2, 1]) # batch*2*32*512\n end_points['conv6'] = max_pool6\n conv7 = self.conv2d(inputdata=max_pool6, out_channel=512, kernel_size=2, stride=[2, 1], use_bias=False, name='conv7') # batch*1*32*512\n relu7 = self.relu(conv7) # batch*1*32*512\n end_points['conv7'] = relu7\n return relu7, end_points\n\n def __map_to_sequence(self, inputdata):\n \"\"\"\n Implement the map to sequence part of the network mainly used to convert the cnn feature map to sequence used in\n later stacked lstm layers\n :param inputdata:\n :return:\n \"\"\"\n shape = inputdata.get_shape().as_list()\n assert shape[1] == 1 # H of the feature map must equal to 1\n return self.squeeze(inputdata=inputdata, axis=1)\n\n def __sequence_label(self, inputdata):\n \"\"\"\n Implement the sequence label part of the network\n :param inputdata:\n :return:\n \"\"\"\n list_n_hidden = [HIDDEN_NUMS, HIDDEN_NUMS]\n \n with tf.variable_scope('LSTMLayers'):\n # construct stack lstm rcnn layer\n # forward lstm cell\n fw_cell_list = [rnn.BasicLSTMCell(nh, forget_bias=1.0) for nh in list_n_hidden]\n # Backward direction cells\n bw_cell_list = [rnn.BasicLSTMCell(nh, forget_bias=1.0) for nh in list_n_hidden]\n\n stack_lstm_layer, _, _ = rnn.stack_bidirectional_dynamic_rnn(fw_cell_list, bw_cell_list, inputdata,\n dtype=tf.float32)\n\n if self.phase.lower() == 'train':\n stack_lstm_layer = self.dropout(inputdata=stack_lstm_layer, keep_prob=0.5)\n\n [batch_s, _, hidden_nums] = inputdata.get_shape().as_list() # [batch, width, 2*n_hidden]\n rnn_reshaped = tf.reshape(stack_lstm_layer, [-1, hidden_nums]) # [batch x width, 2*n_hidden]\n\n w = tf.Variable(tf.truncated_normal([hidden_nums, self.__num_classes], stddev=0.1), name=\"w\")\n # Doing the affine projection\n\n logits = tf.matmul(rnn_reshaped, w)\n\n logits = tf.reshape(logits, [batch_s, -1, self.__num_classes])\n\n raw_pred = tf.argmax(tf.nn.softmax(logits), axis=2, name='raw_prediction')\n\n # Swap batch and batch axis\n rnn_out = tf.transpose(logits, (1, 0, 2), name='transpose_time_major') # [width, batch, n_classes]\n\n return rnn_out, raw_pred\n\n def build_CRNNnet(self, inputdata):\n \"\"\"\n\n :param inputdata:\n :return:\n net_out:output tensor corresponding to the final_endpoint.\n end_points: a set of activations for external use, for example summaries or\n losses.\n \"\"\"\n # first apply the cnn feature extraction stage\n cnn_out,end_points = self.__feature_sequence_extraction(inputdata=inputdata)\n print(\"====##===cnn_out:%s\",cnn_out.get_shape().as_list() )\n # second apply the map to sequence stage\n sequence = self.__map_to_sequence(inputdata=cnn_out)\n print(\"====##===sequence:%s\",sequence.get_shape().as_list() )\n # third apply the sequence label stage\n net_out, raw_pred = self.__sequence_label(inputdata=sequence)\n print(\"====net_out===:\",net_out.get_shape().as_list() )\n print(\"====Predictions===:\",raw_pred.get_shape().as_list() )\n end_points['Logits'] = net_out\n end_points['Predictions'] = raw_pred\n\n return net_out, end_points\n\n\n def train_crnn(self, FLAGS,global_step,cost,sequence_dist,input_labels,pred_labels):\n \"\"\"\n Train crnn model, collect summaries, save model.\n :param inputdata:\n FLAGS: config parameters\n global_step: global step of optimizer\n cost: loss cost\n sequence_dist:\n input_labels: ground true labels\n pred_labels: predict labels\n :return:\n \"\"\"\n learning_rate = tf.train.exponential_decay(FLAGS.LEARNING_RATE, global_step,\n FLAGS.LR_DECAY_STEPS, FLAGS.LR_DECAY_RATE,\n staircase=True)\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n \n with tf.control_dependencies(update_ops):\n optimizer = tf.train.AdadeltaOptimizer(learning_rate=learning_rate).minimize(loss=cost, global_step=global_step)\n \n # Set tf summary\n tboard_save_path = 'tboard/crnn'\n if not ops.exists(tboard_save_path):\n os.makedirs(tboard_save_path)\n tf.summary.scalar(name='Cost', tensor=cost)\n tf.summary.scalar(name='Learning_Rate', tensor=learning_rate)\n tf.summary.scalar(name='Seq_Dist', tensor=sequence_dist)\n merge_summary_op = tf.summary.merge_all()\n \n # Set the training parameters\n train_epochs = FLAGS.EPOCHS\n checkpoint_path = FLAGS.checkpoint_path\n \n # Set saver configuration\n #saver = tf.train.Saver(write_version = saver_pb2.SaverDef.V1)\n saver = tf.train.Saver()\n model_save_dir = 'checkpoints/crnn'\n #model_save_dir = FLAGS.checkpoint_path\n if not ops.exists(model_save_dir):\n os.makedirs(model_save_dir)\n train_start_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))\n model_name = 'crnn_{:s}.ckpt'.format(str(train_start_time))\n model_save_path = ops.join(model_save_dir, model_name)\n \n # Set sess configuration\n sess_config = tf.ConfigProto()\n sess_config.gpu_options.per_process_gpu_memory_fraction = FLAGS.gpu_memory_fraction\n sess_config.gpu_options.allow_growth = FLAGS.TF_ALLOW_GROWTH\n \n sess = tf.Session(config=sess_config)\n \n summary_writer = tf.summary.FileWriter(tboard_save_path)\n summary_writer.add_graph(sess.graph)\n \n with sess.as_default():\n if checkpoint_path is None:\n logger.info('Training from scratch')\n init = tf.global_variables_initializer()\n sess.run(init)\n else:\n logger.info('Restore model from {:s}'.format(checkpoint_path))\n saver.restore(sess=sess, save_path=checkpoint_path)\n \n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n \n for epoch in range(train_epochs):\n _, c, seq_distance, preds, gt_labels, summary = sess.run(\n [optimizer, cost, sequence_dist, pred_labels, input_labels, merge_summary_op])\n \n # calculate the precision \n preds = tf_utils.sparse_tensor_to_str(preds[0])\n gt_labels = tf_utils.sparse_tensor_to_str(gt_labels)\n \n accuracy = [] \n \n for index, gt_label in enumerate(gt_labels):\n pred = preds[index]\n totol_count = len(gt_label)\n correct_count = 0\n try:\n for i, tmp in enumerate(gt_label):\n #import ipdb; ipdb.set_trace()\n #print(\"tmp,pred:\",tmp, pred[i])\n if tmp == pred[i]:\n correct_count += 1\n except IndexError:\n continue\n finally:\n try:\n accuracy.append(correct_count / totol_count)\n except ZeroDivisionError:\n if len(pred) == 0:\n accuracy.append(1)\n else:\n accuracy.append(0)\n accuracy = np.mean(np.array(accuracy).astype(np.float32), axis=0)\n #\n if epoch % FLAGS.DISPLAY_STEP == 0:\n logger.info('Epoch: {:d} cost= {:9f} seq distance= {:9f} train accuracy= {:9f}'.format(\n epoch + 1, c, seq_distance, accuracy))\n \n summary_writer.add_summary(summary=summary, global_step=epoch)\n #logger.info('Save model to {:s}'.format(model_save_path))\n saver.save(sess=sess, save_path=model_save_path, global_step=epoch)\n #saver.save(sess,\"/tmp/crnn.ckpt\")\n \n coord.request_stop()\n coord.join(threads=threads)\n \n sess.close()\n \n return\n\n\n def eval_crnn(self, FLAGS, decoded, images_sh, labels_sh):\n \"\"\"\n Evaluation crnn model, collect summaries, save model.\n :param inputdata:\n FLAGS: config parameters\n decoded: predict labels\n images_sh: image data\n labels_sh: ground true labels\n :return:\n \"\"\" \n # config tf session\n sess_config = tf.ConfigProto()\n sess_config.gpu_options.per_process_gpu_memory_fraction = FLAGS.gpu_memory_fraction\n sess_config.gpu_options.allow_growth = FLAGS.TF_ALLOW_GROWTH\n \n # config tf saver\n #saver = tf.train.Saver(variables_to_restore)\n saver = tf.train.Saver()\n \n if tf.gfile.IsDirectory(FLAGS.checkpoint_path):\n checkpoint_path = tf.train.latest_checkpoint(FLAGS.checkpoint_path)\n else:\n checkpoint_path = FLAGS.checkpoint_path\n \n sess = tf.Session(config=sess_config)\n #checkpoint_path = \"checkpoints/crnn/crnn_2018-07-20-12-09-01.ckpt-99\"\n #module_file = tf.train.latest_checkpoint('/Users/simon/Desktop/OCR/Handwritting_recognition/checkpoints/crnn')\n \"\"\"\n test_sample_count = 0\n for record in tf.python_io.tf_record_iterator(ops.join(dataset_dir, 'test_feature.tfrecords')):\n test_sample_count += 1\n loops_nums = int(math.ceil(test_sample_count / 32))\n # loops_nums = 100\n \"\"\"\n \n with sess.as_default():\n \n # restore the model weights\n saver.restore(sess=sess, save_path=checkpoint_path)\n #saver.restore(sess,\"/tmp/crnn.ckpt\")\n \n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n \n print('Start predicting ......')\n #if not is_recursive:\n if not is_recursive:\n predictions, images, labels = sess.run([decoded, images_sh, labels_sh])\n \n preds_res = tf_utils.sparse_tensor_to_str(predictions[0])\n gt_res = tf_utils.sparse_tensor_to_str(labels)\n #preds_res = tf_utils.decode_sparse_tensor(predictions[0])\n #gt_res = tf_utils.decode_sparse_tensor(labels)\n print(\"$$$$$preds:\",preds_res)\n print(\"$$$$$gt_labels:\",gt_res)\n accuracy = []\n #true_numer = 0\n \n for index, gt_label in enumerate(gt_res):\n pred = preds_res[index]\n total_count = len(gt_label)\n\n correct_count = 0\n try:\n for i, tmp in enumerate(gt_label):\n if tmp == pred[i]:\n correct_count += 1\n except IndexError:\n continue\n finally:\n try:\n accuracy.append(correct_count / total_count)\n except ZeroDivisionError:\n if len(pred) == 0:\n accuracy.append(1)\n else:\n accuracy.append(0)\n\n accuracy = np.mean(np.array(accuracy).astype(np.float32), axis=0)\n logger.info('Mean test accuracy is {:5f}'.format(accuracy))\n print('Mean test accuracy is {:5f}'.format(accuracy))\n \n #for index, image in enumerate(images):\n #print('Predict image with gt label: {:s} **** predict label: {:s}'.format(\n # gt_res[index], preds_res[index]))\n #if is_vis:\n # plt.imshow(image[:, :, (2, 1, 0)])\n # plt.show()\n else:\n accuracy = []\n for epoch in range(loops_nums):\n predictions, images, labels = sess.run([decoded, images_sh, labels_sh])\n\n preds_res = tf_utils.sparse_tensor_to_str(predictions[0])\n gt_res = tf_utils.sparse_tensor_to_str(labels)\n \n for index, gt_label in enumerate(gt_res):\n pred = preds_res[index]\n totol_count = len(gt_label)\n correct_count = 0\n try:\n for i, tmp in enumerate(gt_label):\n if tmp == pred[i]:\n correct_count += 1\n except IndexError:\n continue\n finally:\n try:\n accuracy.append(correct_count / totol_count)\n except ZeroDivisionError:\n if len(pred) == 0:\n accuracy.append(1)\n else:\n accuracy.append(0)\n \n for index, image in enumerate(images):\n print('Predict image with gt label: {:s} **** predict label: {:s}'.format(\n gt_res[index], preds_res[index]))\n \n # if is_vis:\n # plt.imshow(image[:, :, (2, 1, 0)])\n # plt.show()\n \n accuracy = np.mean(np.array(accuracy).astype(np.float32), axis=0)\n print('Test accuracy is {:5f}'.format(accuracy))\n \n \n coord.request_stop()\n coord.join(threads=threads)\n \n sess.close()\n \n return\n\n\n# Temporary setting for OCR Telnumber \nCRNNnet.default_image_size = (32,256)\n#CRNNnet.default_image_size = (64,512)\n\n \ndef crnn_arg_scope(weight_decay=0.0005, data_format='NHWC'):\n \"\"\"Defines the arg scope.\n Args:\n weight_decay: The l2 regularization coefficient.\n Returns:\n An arg_scope.\n \"\"\"\n \"\"\"\n with slim.arg_scope([slim.conv2d, slim.fully_connected],\n activation_fn=tf.nn.relu,\n weights_regularizer=slim.l2_regularizer(weight_decay),\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n biases_initializer=tf.zeros_initializer()):\n with slim.arg_scope([slim.conv2d, slim.max_pool2d],\n padding='SAME',\n data_format=data_format):\n with slim.arg_scope([custom_layers.pad2d,\n custom_layers.l2_normalization,\n custom_layers.channel_to_last],\n data_format=data_format) as sc:\n return sc\n \"\"\" ", "repo_name": "funhere/Handwritting_recognition", "sub_path": "nets/crnn/crnn.py", "file_name": "crnn.py", "file_ext": "py", "file_size_in_byte": 20009, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "26", "api": [{"api_name": "utils.log_utils.init_logger", "line_number": 26, "usage_type": "call"}, {"api_name": "utils.log_utils", "line_number": 26, "usage_type": "name"}, {"api_name": "nets.crnn.cnn_basenet.CNNBaseModel", "line_number": 35, "usage_type": "attribute"}, {"api_name": "nets.crnn.cnn_basenet", "line_number": 35, "usage_type": "name"}, {"api_name": "tensorflow.variable_scope", "line_number": 149, "usage_type": "call"}, {"api_name": "tensorflow.contrib.rnn.BasicLSTMCell", "line_number": 152, "usage_type": "call"}, {"api_name": "tensorflow.contrib.rnn", "line_number": 152, "usage_type": "name"}, {"api_name": "tensorflow.contrib.rnn.BasicLSTMCell", "line_number": 154, "usage_type": "call"}, {"api_name": "tensorflow.contrib.rnn", "line_number": 154, "usage_type": "name"}, {"api_name": "tensorflow.contrib.rnn.stack_bidirectional_dynamic_rnn", "line_number": 156, "usage_type": "call"}, {"api_name": "tensorflow.contrib.rnn", "line_number": 156, "usage_type": "name"}, {"api_name": "tensorflow.float32", "line_number": 157, "usage_type": "attribute"}, {"api_name": "tensorflow.reshape", "line_number": 163, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 165, "usage_type": "call"}, {"api_name": "tensorflow.truncated_normal", "line_number": 165, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 168, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 170, "usage_type": "call"}, {"api_name": "tensorflow.argmax", "line_number": 172, "usage_type": "call"}, {"api_name": "tensorflow.nn.softmax", "line_number": 172, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 172, "usage_type": "attribute"}, {"api_name": "tensorflow.transpose", "line_number": 175, "usage_type": "call"}, {"api_name": "tensorflow.train.exponential_decay", "line_number": 216, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 216, "usage_type": "attribute"}, {"api_name": "tensorflow.get_collection", "line_number": 219, "usage_type": "call"}, {"api_name": "tensorflow.GraphKeys", "line_number": 219, "usage_type": "attribute"}, {"api_name": "tensorflow.control_dependencies", "line_number": 221, "usage_type": "call"}, {"api_name": "tensorflow.train.AdadeltaOptimizer", "line_number": 222, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 222, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 226, "usage_type": "call"}, {"api_name": "os.path", "line_number": 226, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 227, "usage_type": "call"}, {"api_name": "tensorflow.summary.scalar", "line_number": 228, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 228, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.scalar", "line_number": 229, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 229, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.scalar", "line_number": 230, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 230, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.merge_all", "line_number": 231, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 231, "usage_type": "attribute"}, {"api_name": "tensorflow.train.Saver", "line_number": 239, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 239, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 242, "usage_type": "call"}, {"api_name": "os.path", "line_number": 242, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 243, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 244, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 244, "usage_type": "call"}, {"api_name": "time.time", "line_number": 244, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 246, "usage_type": "call"}, {"api_name": "os.path", "line_number": 246, "usage_type": "name"}, {"api_name": "tensorflow.ConfigProto", "line_number": 249, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 253, "usage_type": "call"}, {"api_name": "tensorflow.summary.FileWriter", "line_number": 255, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 255, "usage_type": "attribute"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 261, "usage_type": "call"}, {"api_name": "tensorflow.train.Coordinator", "line_number": 267, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 267, "usage_type": "attribute"}, {"api_name": "tensorflow.train.start_queue_runners", "line_number": 268, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 268, "usage_type": "attribute"}, {"api_name": "utils.tf_utils.sparse_tensor_to_str", "line_number": 275, "usage_type": "call"}, {"api_name": "utils.tf_utils", "line_number": 275, "usage_type": "name"}, {"api_name": "utils.tf_utils.sparse_tensor_to_str", "line_number": 276, "usage_type": "call"}, {"api_name": "utils.tf_utils", "line_number": 276, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 300, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 300, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 300, "usage_type": "attribute"}, {"api_name": "tensorflow.ConfigProto", "line_number": 330, "usage_type": "call"}, {"api_name": "tensorflow.train.Saver", "line_number": 336, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 336, "usage_type": "attribute"}, {"api_name": "tensorflow.gfile.IsDirectory", "line_number": 338, "usage_type": "call"}, {"api_name": "tensorflow.gfile", "line_number": 338, "usage_type": "attribute"}, {"api_name": "tensorflow.train.latest_checkpoint", "line_number": 339, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 339, "usage_type": "attribute"}, {"api_name": "tensorflow.Session", "line_number": 343, "usage_type": "call"}, {"api_name": "tensorflow.train.Coordinator", "line_number": 360, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 360, "usage_type": "attribute"}, {"api_name": "tensorflow.train.start_queue_runners", "line_number": 361, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 361, "usage_type": "attribute"}, {"api_name": "utils.tf_utils.sparse_tensor_to_str", "line_number": 368, "usage_type": "call"}, {"api_name": "utils.tf_utils", "line_number": 368, "usage_type": "name"}, {"api_name": "utils.tf_utils.sparse_tensor_to_str", "line_number": 369, "usage_type": "call"}, {"api_name": "utils.tf_utils", "line_number": 369, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 397, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 397, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 397, "usage_type": "attribute"}, {"api_name": "utils.tf_utils.sparse_tensor_to_str", "line_number": 412, "usage_type": "call"}, {"api_name": "utils.tf_utils", "line_number": 412, "usage_type": "name"}, {"api_name": "utils.tf_utils.sparse_tensor_to_str", "line_number": 413, "usage_type": "call"}, {"api_name": "utils.tf_utils", "line_number": 413, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 442, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 442, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 442, "usage_type": "attribute"}]} +{"seq_id": "16069374510", "text": "import xml.etree.ElementTree as ET\nimport re\nimport chardet\nimport argparse\nimport os.path\n\n# Create an argument parser\nparser = argparse.ArgumentParser(description='ADMX Policy Parser')\n\n# Add a command-line argument for the input filename\nparser.add_argument('filename', help='Path to the ADMX file')\n\n# Parse the command-line arguments\nargs = parser.parse_args()\n\n# Validate the input filename\nif not os.path.isfile(args.filename):\n print(f\"Error: The provided file '{args.filename}' does not exist.\")\n exit(1)\n\n# Detect the encoding of the XML file\nwith open(args.filename, 'rb') as file:\n detector = chardet.universaldetector.UniversalDetector()\n for line in file.readlines():\n detector.feed(line)\n if detector.done:\n break\n encoding = detector.result['encoding']\n\n# Read the XML file\nwith open(args.filename, 'r', encoding=encoding) as file:\n xml_data = file.read()\n\n# Remove the entire xmlns attribute using regular expressions\nmodified_xml_data = re.sub(r'\\s?xmlns=\"[^\"]+\"', '', xml_data)\n\n# Parse the modified XML\nroot = ET.fromstring(modified_xml_data)\n\n# Initialiser un dictionnaire pour stocker les policies par catégorie\npolicies_by_category = {}\n\n# Parcourir toutes les catégories\nfor category in root.iter('category'):\n category_name = category.attrib['name']\n \n # Créer une liste pour chaque catégorie dans le dictionnaire\n if category_name not in policies_by_category:\n policies_by_category[category_name] = []\n \n # Parcourir toutes les policies qui ont cette catégorie comme parentCategory\n for policy in root.iter('policy'):\n parent_category = policy.find('parentCategory')\n \n # Si la policy appartient à la catégorie courante, ajouter son nom à la liste\n if parent_category is not None and parent_category.attrib['ref'] == category_name:\n policies_by_category[category_name].append(policy.attrib['name'])\n\n# Afficher les policies triées par catégorie\nfor category, policies in policies_by_category.items():\n print(f'Category: {category}')\n for policy in policies:\n print(f' - {policy}')\n", "repo_name": "SeiyaGame/admx-policy-parser", "sub_path": "admx-policy-parser.py", "file_name": "admx-policy-parser.py", "file_ext": "py", "file_size_in_byte": 2144, "program_lang": "python", "lang": "fr", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path.path.isfile", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 17, "usage_type": "name"}, {"api_name": "chardet.universaldetector.UniversalDetector", "line_number": 23, "usage_type": "call"}, {"api_name": "chardet.universaldetector", "line_number": 23, "usage_type": "attribute"}, {"api_name": "re.sub", "line_number": 35, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.fromstring", "line_number": 38, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 38, "usage_type": "name"}]} +{"seq_id": "26286285095", "text": "import re\nimport json\nfrom nltk.corpus import stopwords\nfrom rake_nltk import Rake\nimport nltk\n\n\n# this line for download of nltk files here we dowmload stopwords and keyword etractons \n# nltk.download()\n\n## read json file\ndata_json = json.load(open('data.json'))\n\n\n## this will only work when you download stopwords from nltk to your local machine alternatively you can run this ode on colab or kaggle. process is automatic there\nstop_words =stopwords.words('english')\n\n## remove html tages and get pure text\ndef get_pure_text(temp):\n pure_text= ''\n for item in temp:\n# item = re.sub(r'[^\\w\\s]','',item) \n pure_text+=re.sub(r'<.*?>', \"\", item)\n return pure_text\n\n\n## stop words remove\ndef remove_stop_words(temp):\n pure_text = get_pure_text(temp)\n final=''\n for word in pure_text.split():\n if word.lower() not in stop_words:\n# text = re.sub(r'[^a-zA-Z0-9. ]','',word) # remove punctuations\n final += word+' '\n return final\n\n## this will extract keywords from given text\ndef get_keywords(json_text):\n stop_words_removed_text = remove_stop_words(json_text)\n r= Rake()\n r.extract_keywords_from_text(stop_words_removed_text)\n keywords = r.get_ranked_phrases()\n # print(f'html text : {json_text} \\n\\n stopword removed text : {stop_words_removed_text}\\n\\n keywords : {set(keywords)}')\n# print(keywords)\n# print(len(keywords))\n return list(set(keywords))\n\n\n## this will update json data by adding keywords to the file\ndef update_json_with_keywords(jsonData):\n for i in range(len(jsonData)):\n jsonData[i].update({\n 'keywords' : get_keywords(jsonData[i]['data']),\n 'data' : get_pure_text(jsonData[i]['data'])\n })\n return jsonData\n\n## following is the driver code\nnew_json = json.dumps(update_json_with_keywords(data_json))\nwith open(\"datawithkeywords.json\", \"w\") as outfile:\n outfile.write(new_json)\n ", "repo_name": "vattevaii/scraping", "sub_path": "keyword extraction.py", "file_name": "keyword extraction.py", "file_ext": "py", "file_size_in_byte": 1933, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "json.load", "line_number": 12, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 16, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 16, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 23, "usage_type": "call"}, {"api_name": "rake_nltk.Rake", "line_number": 40, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 59, "usage_type": "call"}]} +{"seq_id": "12736564103", "text": "from newspaper import Article, ArticleException\nfrom multiprocessing import Pool, cpu_count\nfrom functools import wraps, partial\nfrom urllib.parse import urlparse\nimport traceback\nimport datetime\nimport calendar\nimport psycopg2\nimport requests\nimport tempfile\nimport zipfile\nimport shutil\nimport json\nimport sys\nimport csv\nimport re\nimport os\n\n\nclass Extractor(object):\n\n def __init__(self, config):\n\n self.config = self.read_config(config)\n\n self.db_name = self.config['db_name']\n self.db_user = self.config['db_user']\n self.db_pass = self.config['db_pass']\n self.db_host = self.config['db_host']\n\n @staticmethod\n def read_config(config):\n\n try:\n return config if isinstance(config, dict) else json.load(open(config))\n\n except ValueError as val_err:\n print(f'Configuration Input \"{config}\" is Not Valid: {val_err}')\n sys.exit(1)\n\n @staticmethod\n def get_date_range(y, m):\n\n return [\n datetime.date(y, m, day).strftime('%Y%m%d') for day in range(1, calendar.monthrange(y, m)[1] + 1)\n ]\n\n @staticmethod\n def extract_daily_csv(target_date):\n\n # Pull CSV from GDELT Repository\n date_zip = '{}.export.CSV.zip'.format(target_date)\n event_url = 'http://data.gdeltproject.org/events/{}'.format(date_zip)\n response = requests.get(event_url, stream=True)\n\n if response.status_code != 200:\n return None\n\n # Dumpt to Local CSV\n temp_dir = tempfile.mkdtemp(dir=r'C:\\Temp', prefix='{}_'.format(target_date))\n zip_file = '{}/{}.zip'.format(temp_dir, target_date)\n with open(zip_file, 'wb') as f: f.write(response.content)\n with zipfile.ZipFile(zip_file, 'r') as the_zip: the_zip.extractall(temp_dir)\n\n return '{}/{}.export.CSV'.format(temp_dir, target_date)\n\n @staticmethod\n def text_filter(text):\n\n return re.sub('[^a-zA-Z0-9 \\n]', '', text)\n\n def get_connection(self):\n\n return psycopg2.connect(dbname=self.db_name, user=self.db_user, password=self.db_pass, host=self.db_host)\n\n def process_article(self, source_url):\n\n # Parse GDELT Source\n article = Article(source_url)\n article.download()\n article.parse()\n article.nlp()\n\n # Unpack Article Properties & Replace Special Characters\n title = self.text_filter(article.title)\n summary = '{} . . . '.format(self.text_filter(article.summary)[:500])\n keywords = ', '.join(sorted([self.text_filter(key) for key in article.keywords]))\n meta_keys = ', '.join(sorted([self.text_filter(key) for key in article.meta_keywords]))\n site = urlparse(article.source_url).netloc\n\n return [title, site, summary, keywords, meta_keys]\n\n def process_events(self, year, target_csv):\n\n # Tracking\n seen_urls = []\n proc_urls = 0\n\n # Extract Records\n with open(target_csv, newline='', encoding='utf8') as the_csv:\n\n the_reader = csv.reader(the_csv, delimiter='\\t')\n\n for idx, row in enumerate(the_reader, start=1):\n\n # Pull Filter Attributes\n avg_tone = float(row[34]) # Average Tone\n src_url = row[57] # Source URL\n a1_geo_lat = row[39] # Latitude Check\n a1_gc = row[37] # Actor1Geo_Country\n a2_geo_lat = row[39] # Longitude Check\n a2_gc = row[44] # Actor1Geo_Country\n\n try:\n # TODO - Actor1Geo_Type in ('2', '3')\n if all([v == 'US' for v in [a1_gc, a2_gc]]) \\\n and avg_tone < 0 \\\n and src_url not in seen_urls \\\n and all([a1_geo_lat, a2_geo_lat]):\n\n # Extract NLP Values with Article\n derived_attributes = self.process_article(src_url)\n\n # Push Values into Master Table\n with self.get_connection() as conn:\n with conn.cursor() as cur:\n cur.execute(\n '''\n insert into gdelt_{}\n values {}\n '''.format(year, tuple(row + derived_attributes))\n )\n\n proc_urls += 1\n\n except ArticleException:\n pass\n\n except:\n print(f'{traceback.format_exc()}')\n\n finally:\n seen_urls.append(src_url)\n\n def process_day(self, year, the_day):\n\n print(f'Processing Day: {the_day}')\n\n # Download GDELT Records Locally for Processing\n daily_csv = self.extract_daily_csv(the_day)\n\n # Ignore Bad CSV Requests\n if not daily_csv: return\n\n # Collect Enriched Values & Push Into Table\n self.process_events(year, daily_csv)\n\n # Remove Temporary Directory\n shutil.rmtree(os.path.dirname(daily_csv))\n\n def run_month(self, month, year):\n\n date_range = self.get_date_range(year, month)\n\n # Create Pool & Run Records\n pool = Pool(processes=cpu_count() - 1)\n pool.map(partial(self.process_day, year), date_range)\n pool.close()\n pool.join()\n", "repo_name": "Jwmazzi/media_research", "sub_path": "py/extractor.py", "file_name": "extractor.py", "file_ext": "py", "file_size_in_byte": 5398, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "json.load", "line_number": 35, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 45, "usage_type": "call"}, {"api_name": "calendar.monthrange", "line_number": 45, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 54, "usage_type": "call"}, {"api_name": "tempfile.mkdtemp", "line_number": 60, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 63, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 70, "usage_type": "call"}, {"api_name": "psycopg2.connect", "line_number": 74, "usage_type": "call"}, {"api_name": "newspaper.Article", "line_number": 79, "usage_type": "call"}, {"api_name": "urllib.parse.urlparse", "line_number": 89, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 102, "usage_type": "call"}, {"api_name": "newspaper.ArticleException", "line_number": 136, "usage_type": "name"}, {"api_name": "traceback.format_exc", "line_number": 140, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 159, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 159, "usage_type": "call"}, {"api_name": "os.path", "line_number": 159, "usage_type": "attribute"}, {"api_name": "multiprocessing.Pool", "line_number": 166, "usage_type": "call"}, {"api_name": "multiprocessing.cpu_count", "line_number": 166, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 167, "usage_type": "call"}]} +{"seq_id": "71825724547", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nInput: \nconfig - filename of json file containing the configuration parameters.\n\nIf no input is passed, run with hard-coded config that does not download \nviews and scheduled queries.\n\nThis function downloads all table names and types from BigQuery, \noptionally downloads view and scheduled queries or loads the previously\ndownloaded (and locally stored) views and scheduled queries, cleanes queries of comments,\nclassify tables into types EXTERNAL, TABLE, VIEW and SCHEDULED. It then creates a \nflowchart that is saved to a file.\n\nCreated by: Henrique S. Xavier, hsxavier@if.usp.br, 12/sep/2019.\n\"\"\"\n\nimport sys\nimport create_flowchart_functions as cf\nimport download_bigquery_info as di\nimport json\n\n# Docstring output:\nif len(sys.argv) > 1 + 1: \n print(__doc__)\n sys.exit(1)\n\n# Get input config:\nelif len(sys.argv) == 1 + 1:\n config = sys.argv[1]\n \n# Set default config:\nelse:\n config = {\n \"credentials\": \"/home/skems/gabinete/projetos/keys-configs/gabinete-compartilhado.json\",\n \"printout\": False,\n \"get_views\": False,\n \"views_path\": \"../views/\",\n \"get_scheduled\": False,\n \"scheduled_path\": \"../scheduled_queries/\",\n \"flowchart\": True,\n \"flowchart_file\": \"this_file.pdf\"\n }\n\n \n### MAIN CODE ###\n\n# Load config from file:\nif type(config)==str:\n with open(config, 'r') as f:\n config = json.load(f) \n\nif config['get_scheduled']:\n di.get_scheduled_queries(config)\n \nif config['flowchart']:\n all_table_query_dict, all_table_type_dict = cf.structure_bigquery_data(config)\n all_tables_list = list(all_table_type_dict.keys())\n\n cf.create_flowchart(all_table_query_dict, all_table_type_dict, all_tables_list, config['flowchart_file'])\n", "repo_name": "hsxavier/bigQuery_mapper", "sub_path": "create_flowchart.py", "file_name": "create_flowchart.py", "file_ext": "py", "file_size_in_byte": 1788, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sys.argv", "line_number": 26, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 28, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 31, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 32, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 53, "usage_type": "call"}, {"api_name": "download_bigquery_info.get_scheduled_queries", "line_number": 56, "usage_type": "call"}, {"api_name": "create_flowchart_functions.structure_bigquery_data", "line_number": 59, "usage_type": "call"}, {"api_name": "create_flowchart_functions.create_flowchart", "line_number": 62, "usage_type": "call"}]} +{"seq_id": "41847149548", "text": "\"\"\"\nHOW-TO\n\nfrom server import BaseExceptionContainer,declare_exc\n\nclass my_exceptions(BaseExceptionContainer):\n exc_code_prefix = '11'\n ExceptionA = declare_exc(code='01',default_message='Error MSG',base=True)\n ExceptionB = declare_exc('02','Error MSG')\n\nraise my_exceptions.ExceptionA\nraise my_exceptions.ExceptionA(data=None)\n\n所有用BaseExceptionContainer实现的异常均为NLPException的子类\n同一个BaseExceptionContainer下均以base=True的异常作为父类\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Dict, Tuple\n\n\nclass NLPException(Exception):\n default_message = 'unknown error'\n code = '999999'\n\n def __init__(self, message: str = '', data: dict = None) -> None:\n self.message = message or self.default_message\n self.data = data\n\n def __str__(self) -> str:\n return f'{self.code}-{self.message}-{self.data}'\n\n\n@dataclass\nclass declared_exc:\n code: str\n default_message: str = '未知错误'\n base: bool = False\n\n\ndeclared_exceptions: Dict[str, NLPException] = {}\n\n\nclass BaseExceptionContainerMeta(type):\n\n def __new__(cls, name: str, bases: tuple, attrs: dict):\n new_cls = super().__new__(cls, name, bases, attrs)\n if not bases:\n return new_cls\n\n assert isinstance(\n getattr(new_cls, 'exc_code_prefix', None),\n str\n ), (f'{new_cls.__module__}-{new_cls.__name__} expected \"exc_code_prefix\" is a string.')\n\n def new_exc(\n exc_name: str,\n declared_exc: declared_exc,\n bases: Tuple = (NLPException,),\n ) -> NLPException:\n exc_attrs = declared_exc.__dict__.copy()\n exc_attrs['code'] = f'{new_cls.exc_code_prefix}{declared_exc.code}'\n exc_attrs['_container'] = new_cls\n\n return type(exc_name, bases, exc_attrs)\n\n cls_declared_exceptions: Dict[str, Tuple[str, declared_exc]] = {}\n base_exc_code = None\n for k, v in attrs.items():\n if isinstance(v, declared_exc):\n code = f'{new_cls.exc_code_prefix}{v.code}'\n if code in declared_exceptions or code in cls_declared_exceptions:\n e = declared_exceptions.get(code)\n if not e:\n _, e = cls_declared_exceptions[code]\n\n raise RuntimeError(\n 'Multiple exceptions were defined with code'\n f\"{v.code}:{new_cls.__name__}.{k},\"\n f'{e._container.__name__}.{e.__name__}'\n )\n\n if v.base:\n if base_exc_code:\n raise RuntimeError(\n 'Expected only one declared_exc(base=True) in'\n f'{new_cls.__name__}'\n )\n base_exc_code = code\n\n cls_declared_exceptions[code] = (k, v)\n\n if not base_exc_code:\n base_exc_name, base_exc_declared = (\n 'BaseException', declared_exc('0000', base=True))\n else:\n base_exc_name, base_exc_declared = (\n cls_declared_exceptions[base_exc_code])\n\n base_exc = new_exc(base_exc_name, base_exc_declared)\n\n declared_exceptions[base_exc.code] = base_exc\n setattr(new_cls, base_exc_name, base_exc)\n\n for code, (exc_name, exc_declared) in cls_declared_exceptions.items():\n if exc_name != base_exc_name:\n exc = new_exc(exc_name, exc_declared, bases=(base_exc,))\n setattr(new_cls, exc_name, exc)\n declared_exceptions[code] = exc\n\n return new_cls\n\n\nclass BaseExceptionContainer(metaclass=BaseExceptionContainerMeta):\n exc_code_prefix = None\n", "repo_name": "niubiqigai/address_ner", "sub_path": "server/exceptions.py", "file_name": "exceptions.py", "file_ext": "py", "file_size_in_byte": 3787, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 16, "dataset": "github-code", "pt": "25", "api": [{"api_name": "dataclasses.dataclass", "line_number": 34, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 41, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 59, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 67, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 67, "usage_type": "name"}]} +{"seq_id": "20556829729", "text": "from django.urls import path\nfrom . import views\n\napp_name = 'member'\nurlpatterns = [\n path('registration/', views.RegisterUserView.as_view(), name='registration'),\n path('login', views.BlogLoginView.as_view(), name='login'),\n path('logout', views.LogoutUserView.as_view(), name='logout'),\n\n]", "repo_name": "Cyber0x/News_site", "sub_path": "mysite/member/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 301, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}]} +{"seq_id": "5990130185", "text": "\nimport csv\nimport logging\nimport os\n\nICGC_SAMPLE_ID_KEY=\"ICGC Submitted Sample ID\"\nSEQUENCING_STRATEGY_KEY='ICGC Submitted Sequencing Strategy'\nEGAF_ACCESSION_KEY='EGA File Accession'\nDELIMITER='\\t'\n\nclass EGAAudit:\n\n def __init__(self, csv_file):\n self._csv_file = open(csv_file,'r')\n self._rows = []\n self._load_csv()\n return\n\n def _load_csv(self):\n csv_reader = csv.DictReader(self._csv_file, delimiter=DELIMITER)\n for row in csv_reader:\n self._rows.append(row)\n\n def get_ids(self, seq_strategy=None):\n ids = []\n for row in self._rows:\n if seq_strategy != None:\n if row['ICGC Submitted Sequencing Strategy'] == seq_strategy:\n ids.append({'ICGC_SAMPLE_ID_KEY':row[ICGC_SAMPLE_ID_KEY],'SEQUENCING_STRATEGY_KEY':row[SEQUENCING_STRATEGY_KEY],'EGAF_ACCESSION_KEY':row[EGAF_ACCESSION_KEY]})\n else:\n ids.append({'ICGC_SAMPLE_ID_KEY':row[ICGC_SAMPLE_ID_KEY],'SEQUENCING_STRATEGY_KEY':row[SEQUENCING_STRATEGY_KEY],'EGAF_ACCESSION_KEY':row[EGAF_ACCESSION_KEY]})\n return ids\n\n def get_row(self,icgc_sample_id, egaf, seq_strategy):\n for row in self._rows:\n if row[ICGC_SAMPLE_ID_KEY] == icgc_sample_id and row[SEQUENCING_STRATEGY_KEY] == seq_strategy and row[EGAF_ACCESSION_KEY] == egaf:\n return row\n raise Exception(\"There is no row found with the following informations: icgc_sample_id=%s, egafid=%s, seq_strategy=%s\" % (icgc_sample_id, egaf, seq_strategy))\n\n def _get_key(self, icgc_sample_id, egaf, seq_strategy, key):\n self._csv_file.seek(0)\n row = self.get_row(icgc_sample_id, egaf, seq_strategy)\n return row[key]\n\n def get_egaf_id(self, icgc_sample_id, egaf, seq_strategy):\n return self._get_key(icgc_sample_id, egaf, seq_strategy,EGAF_ACCESSION_KEY)\n\n def get_egaf_ids(self, ids=[]):\n if len(ids) == 0:\n ids = self.get_ids()\n fids = []\n for id in ids:\n logging.debug(\"EGAFID added: %s\" % (id))\n fids.append(self.get_egaf_id(id['ICGC_SAMPLE_ID_KEY'],id['EGAF_ACCESSION_KEY'],id['SEQUENCING_STRATEGY_KEY']))\n return fids\n\n def find_rows(self, egaf_id):\n self._csv_file.seek(0)\n rows = []\n csv_reader = csv.DictReader(self._csv_file, delimiter=DELIMITER)\n for row in csv_reader:\n if row[EGAF_ACCESSION_KEY] == egaf_id:\n rows.append(row)\n return rows\n\n def find_rows_with_bundle_id(self, bundle_id):\n rows = []\n for row in self._rows:\n if row['EGA Analysis Accession'] == bundle_id or row['EGA Run Accession'] == bundle_id:\n rows.append(row)\n return rows\n\n def get_job(self, egaf_id, metadata_repo):\n job = {}\n rows = self.find_rows(egaf_id)\n\n job['bundle_id'] = self._get_bundle_id(rows[0]['EGA Analysis Accession'],rows[0]['EGA Run Accession'])\n job['name'] = job['bundle_id']\n job['bundle_type'] = self._get_bundle_type(rows[0]['EGA Analysis Accession'],rows[0]['EGA Run Accession'])\n job['donor_gender'] = rows[0][\"Donor Gender\"] if rows[0][\"Donor Gender\"] in ['male','female'] else 'unspecified'\n job['ega_analysis_id'] = rows[0]['EGA Analysis Accession']\n job['ega_dataset_id'] = rows[0][\"EGA Dataset Accession\"]\n job['ega_experiment_id'] = rows[0][\"EGA Experiment Accession\"]\n job['ega_metadata_file_name'] = 'bundle.'+job['bundle_id']+'.xml'\n job['ega_metadata_repo'] = metadata_repo\n job['ega_run_id'] = rows[0][\"EGA Run Accession\"]\n job['ega_sample_id'] = rows[0][\"EGA Sample Accession\"]\n job['ega_study_id'] = rows[0][\"EGA Study Accession\"]\n job['insert_size'] = rows[0][\"Insert Size\"]\n job['library_strategy'] = rows[0][SEQUENCING_STRATEGY_KEY]\n job['paired_end'] = rows[0][\"Paired-End\"]\n job['project_code'] = rows[0][\"ICGC DCC Project Code\"]\n job['reference_genome'] = rows[0][\"Reference Genome\"]\n job['submitter'] = rows[0][\"ICGC DCC Project Code\"]\n job['submitter_donor_id'] = rows[0][\"ICGC Submitted Donor ID\"]\n job['submitter_sample_id'] = rows[0][\"ICGC Submitted Sample ID\"]\n job['submitter_specimen_id'] = rows[0][\"ICGC Submitted Specimen ID\"]\n job['submitter_specimen_type'] = rows[0][\"ICGC Submitted Specimen Type\"]\n\n job['files'] = []\n for row in self.find_rows_with_bundle_id(job['bundle_id']):\n file = {}\n file['ega_file_id'] = row[EGAF_ACCESSION_KEY]\n file['file_md5sum'] = row['Unencrypted Checksum']\n file['file_name'] = row['Unencrypted Checksum']+'.'+os.path.basename(row['EGA Raw Sequence Filename'][:-4] if str(row['EGA Raw Sequence Filename']).endswith('.gpg') else row['EGA Raw Sequence Filename'])\n file['size'] = row['File Size']\n job['files'].append(file)\n\n return \".\".join(['job',job['bundle_id'],job['project_code'],job['submitter_sample_id'],job['ega_sample_id']]),job\n\n def _get_bundle_type(self, analysis_accession, run_accession):\n if analysis_accession != None and analysis_accession != \"\":\n return \"analysis\"\n if run_accession != None and run_accession != \"\":\n return \"run\"\n return None\n\n def _get_bundle_id(self, analysis_accession, run_accession):\n if analysis_accession != None and analysis_accession != \"\":\n return analysis_accession\n if run_accession != None and run_accession != \"\":\n return run_accession\n return None\n\n def get_info_from_egafid(self, egafid, *args):\n print(egafid)\n row = self.find_rows(egafid)[0]\n return [row[x] for x in args]\n\n", "repo_name": "icgc-dcc/JTrackerTransferOperations", "sub_path": "operations/ega/utils/ega_audit.py", "file_name": "ega_audit.py", "file_ext": "py", "file_size_in_byte": 5778, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "csv.DictReader", "line_number": 20, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 53, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 105, "usage_type": "call"}, {"api_name": "os.path", "line_number": 105, "usage_type": "attribute"}]} +{"seq_id": "39839761163", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 26 13:58:02 2017\nTesting suite for landspy Grid class\n@author: J. Vicente Perez\n@email: geolovic@hotmail.com\n@last_modified: 04 october, 2022\n\"\"\"\n\nimport unittest\nimport sys\nimport numpy as np\nfrom osgeo import gdal\n# Add to the path code folder and data folder\nsys.path.append(\"../src/\")\nfrom landspy import PRaster\ninfolder = \"data/in\"\n\nclass TestPRaster00(unittest.TestCase):\n \n def test_properties(self):\n # Test PRaster getters\n files = [\"small25.tif\", \"tunez.tif\", \"jebja30.tif\"]\n for file in files:\n raster = PRaster(infolder + \"/{0}\".format(file))\n size = raster.getSize()\n dims = raster.getDims()\n ncells = raster.getNCells()\n cellsize = raster.getCellSize()\n geot = raster.getGeot()\n computed = (size, dims, ncells, cellsize, geot)\n graster = gdal.Open(infolder + \"/{0}\".format(file))\n band = graster.GetRasterBand(1)\n arr = band.ReadAsArray()\n ggeot = graster.GetGeoTransform()\n expected = ((band.XSize, band.YSize), arr.shape, arr.size, (ggeot[1], ggeot[5]), ggeot)\n self.assertEqual(computed, expected)\n\n def test_projections(self):\n # Test PRaster getters\n files = [\"small25.tif\", \"tunez.tif\", \"jebja30.tif\"]\n \n for file in files:\n # Test PRaster getters for a raster\n raster = PRaster(infolder + \"/{0}\".format(file))\n graster = gdal.Open(infolder + \"/{0}\".format(file))\n self.assertEqual(raster.getCRS(), graster.GetProjection())\n \n def test_empty(self):\n # Test PRaster getters in an empty PRaster\n raster = PRaster()\n size = raster.getSize()\n dims = raster.getDims()\n ncells = raster.getNCells()\n cellsize = raster.getCellSize()\n geot = raster.getGeot()\n proj = raster.getCRS()\n computed = (size, dims, ncells, cellsize, geot, proj)\n expected = ((1, 1), (1, 1), 1, (1.0, -1.0), (0., 1., 0., 1., 0., -1.), \"\")\n self.assertEqual(computed, expected)\n \n def test_copy_layout(self):\n # Test copy_layout for some rasters\n files = [\"small25.tif\", \"tunez.tif\", \"jebja30.tif\"]\n for file in files:\n b_raster = PRaster()\n c_raster = PRaster(infolder + \"/{0}\".format(file))\n b_raster.copyLayout(c_raster)\n \n size = c_raster.getSize()\n dims = c_raster.getDims()\n ncells = c_raster.getNCells()\n cellsize = c_raster.getCellSize()\n geot = c_raster.getGeot()\n proj = c_raster.getCRS()\n computed = (size, dims, ncells, cellsize, geot, proj)\n \n size = b_raster.getSize()\n dims = b_raster.getDims()\n ncells = b_raster.getNCells()\n cellsize = b_raster.getCellSize()\n geot = b_raster.getGeot()\n proj = b_raster.getCRS()\n expected = (size, dims, ncells, cellsize, geot, proj)\n \n self.assertEqual(computed, expected)\n\nclass TestPRaster01(unittest.TestCase):\n \n def setUp(self): \n # Load test data\n self.ids = np.load(infolder + \"/np_files/small25_100rnd_id.npy\")\n self.rows = np.load(infolder + \"/np_files/small25_100rnd_row.npy\")\n self.cols = np.load(infolder + \"/np_files/small25_100rnd_col.npy\")\n self.xi = np.load(infolder + \"/np_files/small25_100rnd_X.npy\")\n self.yi = np.load(infolder + \"/np_files/small25_100rnd_Y.npy\")\n \n def test_xy_2_cell_01(self): \n raster = PRaster(infolder + \"/small25.tif\")\n xi = self.xi\n yi = self.yi\n rows = self.rows\n cols = self.cols\n c_rows, c_cols = raster.xyToCell(xi, yi)\n res = (np.array_equal(rows, c_rows), np.array_equal(cols, c_cols))\n self.assertEqual(res, (True, True))\n \n def test_xy_2_cell_02(self):\n raster = PRaster(infolder + \"/small25.tif\")\n x = 471927\n y = 4116048\n row, col = raster.xyToCell(x, y)\n self.assertEqual((43, 71), (row, col))\n \n def test_xy_2_cell_03(self):\n raster = PRaster(infolder + \"/small25.tif\")\n xi = self.xi.tolist()\n yi = self.yi.tolist()\n rows = self.rows\n cols = self.cols\n c_rows, c_cols = raster.xyToCell(xi, yi)\n res = (np.array_equal(rows, c_rows), np.array_equal(cols, c_cols))\n self.assertEqual(res, (True, True))\n \n \n def test_cell_2_xy_01(self): \n raster = PRaster(infolder + \"/small25.tif\")\n xi = self.xi\n yi = self.yi\n rows = self.rows\n cols = self.cols\n cxi, cyi = raster.cellToXY(rows, cols)\n res = (np.array_equal(cxi, xi), np.array_equal(cyi, yi))\n self.assertEqual(res, (True, True))\n \n def test_cell_2_xy_02(self):\n raster = PRaster(infolder + \"/small25.tif\")\n x = 471927.1\n y = 4116048.5\n row = 43\n col = 71\n cx, cy = raster.cellToXY(row, col)\n self.assertEqual((x, y), (cx, cy))\n \n def test_cell_2_xy_03(self):\n raster = PRaster(infolder + \"/small25.tif\")\n xi = self.xi\n yi = self.yi\n rows = self.rows.tolist()\n cols = self.cols.tolist()\n cxi, cyi = raster.cellToXY(rows, cols)\n res = (np.array_equal(xi, cxi), np.array_equal(yi, cyi))\n self.assertEqual(res, (True, True)) \n \n def test_cell_2_ind_01(self): \n raster = PRaster(infolder + \"/small25.tif\")\n rows = self.rows\n cols = self.cols\n ids = self.ids\n cids = raster.cellToInd(rows, cols)\n self.assertEqual(np.array_equal(ids, cids), True)\n \n def test_cell_2_ind_02(self):\n raster = PRaster(infolder + \"/small25.tif\")\n row = 25\n col = 11\n ids = 4986\n cids = raster.cellToInd(row, col)\n self.assertEqual(ids, cids)\n \n def test_cell_2_ind_03(self): \n raster = PRaster(infolder + \"/small25.tif\")\n rows = self.rows.tolist()\n cols = self.cols.tolist()\n ids = self.ids\n cids = raster.cellToInd(rows, cols)\n self.assertEqual(np.array_equal(ids, cids), True)\n \n def test_is_inside(self):\n # points 1, 2, 4, 8 --> -Fuera de ráster\n # points 3, 5 --> Dentro de ráster, pero en NoData\n # points 6, 7, 9 --> Dentro de ráster\n \n puntos = np.array([[476154., 4115084.],\n [472289., 4112838.],\n [471317., 4114050.],\n [472874., 4117717.],\n [472205., 4114091.],\n [470795., 4116411.],\n [472257., 4115565.],\n [469572., 4115376.],\n [473877., 4114844.]])\n x = puntos[:,0]\n y = puntos[:,1]\n raster = PRaster(infolder + \"/small25.tif\")\n computed = raster.isInside(x, y)\n expected = np.array([False, False, True, False, True, True, True, False, True])\n self.assertEqual(np.array_equal(computed, expected), True)\n \nif __name__ == \"__main__\":\n unittest.main()", "repo_name": "geolovic/landspy", "sub_path": "tests/test_00_PRaster.py", "file_name": "test_00_PRaster.py", "file_ext": "py", "file_size_in_byte": 7308, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sys.path.append", "line_number": 15, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "unittest.TestCase", "line_number": 19, "usage_type": "attribute"}, {"api_name": "landspy.PRaster", "line_number": 25, "usage_type": "call"}, {"api_name": "osgeo.gdal.Open", "line_number": 32, "usage_type": "call"}, {"api_name": "osgeo.gdal", "line_number": 32, "usage_type": "name"}, {"api_name": "landspy.PRaster", "line_number": 45, "usage_type": "call"}, {"api_name": "osgeo.gdal.Open", "line_number": 46, "usage_type": "call"}, {"api_name": "osgeo.gdal", "line_number": 46, "usage_type": "name"}, {"api_name": "landspy.PRaster", "line_number": 51, "usage_type": "call"}, {"api_name": "landspy.PRaster", "line_number": 66, "usage_type": "call"}, {"api_name": "landspy.PRaster", "line_number": 67, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 88, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 96, "usage_type": "call"}, {"api_name": "landspy.PRaster", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 105, "usage_type": "call"}, {"api_name": "landspy.PRaster", "line_number": 109, "usage_type": "call"}, {"api_name": "landspy.PRaster", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 122, "usage_type": "call"}, {"api_name": "landspy.PRaster", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 133, "usage_type": "call"}, {"api_name": "landspy.PRaster", "line_number": 137, "usage_type": "call"}, {"api_name": "landspy.PRaster", "line_number": 146, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 152, "usage_type": "call"}, {"api_name": "landspy.PRaster", "line_number": 156, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 161, "usage_type": "call"}, {"api_name": "landspy.PRaster", "line_number": 164, "usage_type": "call"}, {"api_name": "landspy.PRaster", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 184, "usage_type": "call"}, {"api_name": "landspy.PRaster", "line_number": 195, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 197, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 198, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 201, "usage_type": "call"}]} +{"seq_id": "19200079903", "text": "\"\"\"\nDefines:\n - Cart3D(log=None, debug=False)\n - read_cart3d(self, infilename, result_names=None)\n - write_cart3d(self, outfilename, is_binary=False, float_fmt='%6.7f')\n\n - flip_model()\n - make_mirror_model(self, nodes, elements, regions, loads, axis='y', tol=0.000001)\n - make_half_model(self, axis='y', remap_nodes=True)\n - get_free_edges(self, elements)\n - get_area(self)\n - get_normals(self)\n - get_normals_at_nodes(self, cnormals)\n\n - comp2tri(in_filenames, out_filename,\n is_binary=False, float_fmt='%6.7f')\n\"\"\"\nfrom __future__ import print_function, unicode_literals\nimport sys\nfrom struct import pack, unpack\nfrom math import ceil\nfrom collections import defaultdict\nfrom codecs import open as codec_open\n\nfrom six import iteritems, PY2\nfrom six.moves import zip, range\n\nimport numpy as np\n\nfrom pyNastran.utils import is_binary_file, _filename, b\nfrom pyNastran.utils.log import get_logger2\n\nif PY2:\n string_type = unicode\n bytes_type = str\n write_ascii = 'wb'\nelse:\n string_type = str\n bytes_type = bytes\n write_ascii = 'wb'\n\n\ndef read_cart3d(cart3d_filename, log=None, debug=False, result_names=None):\n \"\"\"loads a Cart3D file\"\"\"\n model = Cart3D(log=log, debug=debug)\n model.read_cart3d(cart3d_filename, result_names)\n return model\n\n\ndef comp2tri(in_filenames, out_filename,\n is_binary=False, float_fmt='%6.7f'):\n \"\"\"\n Combines multiple Cart3d files (binary or ascii) into a single file.\n\n Parameters\n ----------\n in_filenames : List[str]\n list of filenames\n out_filename : str\n output filename\n is_binary : bool; default=False\n is the output filename binary\n float_fmt : str; default='%6.7f'\n the format string to use for ascii writing\n\n .. note:: assumes loads is None\n \"\"\"\n points = []\n elements = []\n regions = []\n\n #ne = 0\n npoints = 0\n nregions = 0\n model = Cart3D()\n for infilename in in_filenames:\n model.read_cart3d(infilename)\n npointsi = model.nodes.shape[0]\n nregionsi = len(np.unique(model.regions))\n #element += npoints - 1\n #region += nregions\n\n points.append(model.nodes)\n elements.append(model.elements)\n regions.append(model.regions)\n npoints += npointsi\n nregions += nregionsi\n\n points = np.vstack(points)\n elements = np.vstack(elements)\n regions = np.vstack(regions)\n model.points = points\n model.elements = elements\n model.regions = regions\n\n model.write_cart3d(out_filename, is_binary=False, float_fmt=float_fmt)\n\n\nclass Cart3dIO(object):\n \"\"\"\n Cart3d IO class\n \"\"\"\n def __init__(self, log=None, debug=False):\n self.log = get_logger2(log, debug=debug)\n self._endian = b''\n self._encoding = 'latin1'\n self.n = 0\n self.infile = None\n # self.readHalf = False\n # self.nPoints = None\n # self.nElements = None\n self.infilename = None\n self.points = None\n self.elements = None\n self.regions = None\n self.loads = {}\n\n def _write_header(self, outfile, points, elements, is_loads, is_binary=False):\n \"\"\"\n writes the cart3d header\n\n Without results\n ---------------\n npoints nelements\n\n With results\n ------------\n npoints nelements nresults\n\n \"\"\"\n npoints = points.shape[0]\n nelements = elements.shape[0]\n\n if is_binary:\n if is_loads:\n fmt = self._endian + b('iiiii')\n msg = pack(fmt, 3*4, npoints, nelements, 6, 4)\n else:\n fmt = self._endian + b('iiii')\n msg = pack(fmt, 2*4, npoints, nelements, 4)\n\n int_fmt = None\n else:\n # this is ASCII data\n if is_loads:\n msg = b(\"%i %i 6\\n\" % (npoints, nelements))\n else:\n msg = b(\"%i %i\\n\" % (npoints, nelements))\n\n # take the max value, string it, and length it\n # so 123,456 is length 6\n int_fmt = b('%%%si' % len(str(nelements)))\n outfile.write(msg)\n return int_fmt\n\n def _write_points(self, outfile, points, is_binary, float_fmt='%6.6f'):\n \"\"\"writes the points\"\"\"\n if is_binary:\n four = pack(self._endian + b('i'), 4)\n outfile.write(four)\n\n npoints = points.shape[0]\n fmt = self._endian + b('%if' % (npoints * 3))\n floats = pack(fmt, *np.ravel(points))\n\n outfile.write(floats)\n outfile.write(four)\n else:\n if isinstance(float_fmt, bytes_type):\n fmt_ascii = float_fmt\n else:\n fmt_ascii = float_fmt.encode('latin1')\n np.savetxt(outfile, points, fmt_ascii)\n\n def _write_elements(self, outfile, elements, is_binary, int_fmt='%6i'):\n \"\"\"writes the triangles\"\"\"\n min_e = elements.min()\n assert min_e == 0, 'min(elements)=%s' % min_e\n if is_binary:\n fmt = self._endian + b('i')\n four = pack(fmt, 4)\n outfile.write(four)\n nelements = elements.shape[0]\n fmt = self._endian + b('%ii' % (nelements * 3))\n ints = pack(fmt, *np.ravel(elements+1))\n\n outfile.write(ints)\n outfile.write(four)\n else:\n if isinstance(int_fmt, bytes_type):\n fmt_ascii = int_fmt\n else:\n fmt_ascii = int_fmt.encode('latin1')\n np.savetxt(outfile, elements+1, fmt_ascii)\n\n def _write_regions(self, outfile, regions, is_binary):\n \"\"\"writes the regions\"\"\"\n if is_binary:\n fmt = self._endian + b('i')\n four = pack(fmt, 4)\n outfile.write(four)\n\n nregions = len(regions)\n fmt = self._endian + b('%ii' % nregions)\n ints = pack(fmt, *regions)\n outfile.write(ints)\n\n outfile.write(four)\n else:\n fmt = b'%i'\n np.savetxt(outfile, regions, fmt)\n\n def _write_loads(self, outfile, loads, is_binary, float_fmt='%6.6f'):\n \"\"\"writes the *.triq loads\"\"\"\n if is_binary:\n raise NotImplementedError('is_binary=%s' % is_binary)\n else:\n Cp = loads['Cp']\n rho = loads['rho']\n rhoU = loads['rhoU']\n rhoV = loads['rhoV']\n rhoW = loads['rhoW']\n E = loads['E']\n npoints = self.points.shape[0]\n assert len(Cp) == npoints, 'len(Cp)=%s npoints=%s' % (len(Cp), npoints)\n #nrows = len(Cp)\n fmt = '%s\\n%s %s %s %s %s\\n' % (float_fmt, float_fmt, float_fmt,\n float_fmt, float_fmt, float_fmt)\n for (cpi, rhoi, rhou, rhov, rhoe, e) in zip(Cp, rho, rhoU, rhoV, rhoW, E):\n outfile.write(fmt % (cpi, rhoi, rhou, rhov, rhoe, e))\n\n def _read_header_ascii(self):\n line = self.infile.readline()\n sline = line.strip().split()\n if len(sline) == 2:\n npoints, nelements = int(sline[0]), int(sline[1])\n nresults = 0\n elif len(sline) == 3:\n npoints = int(sline[0])\n nelements = int(sline[1])\n nresults = int(sline[2])\n else:\n raise ValueError('invalid result type')\n return npoints, nelements, nresults\n\n @property\n def nresults(self):\n \"\"\"get the number of results\"\"\"\n if isinstance(self.loads, dict):\n return len(self.loads)\n return 0\n\n @property\n def nnodes(self):\n \"\"\"alternate way to access number of points\"\"\"\n return self.npoints\n\n @property\n def npoints(self):\n \"\"\"get the number of points\"\"\"\n return self.points.shape[0]\n\n @property\n def nodes(self):\n \"\"\"alternate way to access the points\"\"\"\n return self.points\n\n @nodes.setter\n def nodes(self, points):\n \"\"\"alternate way to access the points\"\"\"\n self.points = points\n\n @property\n def nelements(self):\n \"\"\"get the number of elements\"\"\"\n return self.elements.shape[0]\n\n def _read_points_ascii(self, npoints):\n \"\"\"\n A point is defined by x,y,z and the ID is the location in points.\n \"\"\"\n p = 0\n data = []\n assert npoints > 0, 'npoints=%s' % npoints\n points = np.zeros((npoints, 3), dtype='float32')\n while p < npoints:\n data += self.infile.readline().strip().split()\n while len(data) > 2:\n x = data.pop(0)\n y = data.pop(0)\n z = data.pop(0)\n points[p] = [x, y, z]\n p += 1\n\n #maxX = self.get_max(points, 0)\n #maxY = self.get_max(points, 1)\n #maxZ = self.get_max(points, 2)\n\n #minX = self.get_min(points, 0)\n #minY = self.get_min(points, 1)\n #minZ = self.get_min(points, 2)\n\n #self.log.debug(\"X max=%g min=%g\" % (maxX, minX))\n #self.log.debug(\"Y max=%g min=%g\" % (maxY, minY))\n #self.log.debug(\"Z max=%g min=%g\" % (maxZ, minZ))\n return points\n\n def _read_elements_ascii(self, nelements):\n \"\"\"\n An element is defined by n1,n2,n3 and the ID is the location in elements.\n \"\"\"\n assert nelements > 0, 'npoints=%s nelements=%s' % (self.npoints, nelements)\n elements = np.zeros((nelements, 3), dtype='int32')\n\n e = 0\n data = []\n while e < nelements:\n data += self.infile.readline().strip().split()\n while len(data) > 2:\n n1 = int(data.pop(0))\n n2 = int(data.pop(0))\n n3 = int(data.pop(0))\n elements[e] = [n1, n2, n3]\n e += 1\n assert elements.min() == 1, elements.min()\n return elements - 1\n\n def _read_regions_ascii(self, nelements):\n regions = np.zeros(nelements, dtype='int32')\n r = 0\n data = []\n while r < nelements:\n data = self.infile.readline().strip().split()\n ndata = len(data)\n regions[r : r + ndata] = data\n r += ndata\n return regions\n\n def _read_header_binary(self):\n data = self.infile.read(4)\n size_little, = unpack(b'i', data)\n if size_big in [12, 8]:\n self._endian = b'>'\n size = size_big\n elif size_little in [8, 12]:\n self._endian = b'<'\n size = size_little\n else:\n self._rewind()\n self.show(100)\n raise RuntimeError('unknown endian')\n\n self.n += 4\n data = self.infile.read(size)\n self.n += size\n\n so4 = size // 4 # size over 4\n if so4 == 3:\n (npoints, nelements, nresults) = unpack(self._endian + b('iii'), data)\n self.log.info(\"npoints=%s nelements=%s nresults=%s\" % (npoints, nelements, nresults))\n elif so4 == 2:\n (npoints, nelements) = unpack(self._endian + b('ii'), data)\n nresults = 0\n self.log.info(\"npoints=%s nelements=%s\" % (npoints, nelements))\n else:\n self._rewind()\n self.show(100)\n raise RuntimeError('in the wrong spot...endian...size/4=%s' % so4)\n self.infile.read(8) # end of first block, start of second block\n return (npoints, nelements, nresults)\n\n def _read_points_binary(self, npoints):\n \"\"\"reads the xyz points\"\"\"\n size = npoints * 12 # 12=3*4 all the points\n data = self.infile.read(size)\n\n dtype = np.dtype(self._endian + b('f4'))\n points = np.fromstring(data, dtype=dtype).reshape((npoints, 3))\n\n self.infile.read(8) # end of second block, start of third block\n return points\n\n def _read_elements_binary(self, nelements):\n \"\"\"reads the triangles\"\"\"\n size = nelements * 12 # 12=3*4 all the elements\n data = self.infile.read(size)\n\n dtype = np.dtype(self._endian + b('i4'))\n elements = np.fromstring(data, dtype=dtype).reshape((nelements, 3))\n\n self.infile.read(8) # end of third (element) block, start of regions (fourth) block\n assert elements.min() == 1, elements.min()\n return elements - 1\n\n def _read_regions_binary(self, nelements):\n \"\"\"reads the regions\"\"\"\n size = nelements * 4 # 12=3*4 all the elements\n data = self.infile.read(size)\n\n regions = np.zeros(nelements, dtype='int32')\n dtype = self._endian + b'i'\n regions = np.fromstring(data, dtype=dtype)\n\n self.infile.read(4) # end of regions (fourth) block\n return regions\n\n def _read_results_binary(self, i, infile, result_names=None):\n \"\"\"binary results are not supported\"\"\"\n pass\n\n def _rewind(self):\n \"\"\"go back to the beginning of the file\"\"\"\n self.n = 0\n self.infile.seek(self.n)\n\n def show(self, n, types='ifs', endian=None):\n assert self.n == self.infile.tell(), 'n=%s tell=%s' % (self.n, self.infile.tell())\n nints = n // 4\n data = self.infile.read(4 * n)\n strings, ints, floats = self.show_data(data, types=types, endian=endian)\n self.infile.seek(self.n)\n return strings, ints, floats\n\n def show_data(self, data, types='ifs', endian=None):\n return self._write_data(sys.stdout, data, types=types, endian=endian)\n\n def _write_data(self, outfile, data, types='ifs', endian=None):\n \"\"\"\n Useful function for seeing what's going on locally when debugging.\n \"\"\"\n n = len(data)\n nints = n // 4\n ndoubles = n // 8\n strings = None\n ints = None\n floats = None\n longs = None\n\n if endian is None:\n endian = self._endian\n\n if 's' in types:\n strings = unpack(b'%s%is' % (endian, n), data)\n outfile.write(\"strings = %s\\n\" % str(strings))\n if 'i' in types:\n ints = unpack(b'%s%ii' % (endian, nints), data)\n outfile.write(\"ints = %s\\n\" % str(ints))\n if 'f' in types:\n floats = unpack(b'%s%if' % (endian, nints), data)\n outfile.write(\"floats = %s\\n\" % str(floats))\n\n if 'l' in types:\n longs = unpack(b'%s%il' % (endian, nints), data)\n outfile.write(\"long = %s\\n\" % str(longs))\n if 'I' in types:\n ints2 = unpack(b'%s%iI' % (endian, nints), data)\n outfile.write(\"unsigned int = %s\\n\" % str(ints2))\n if 'L' in types:\n longs2 = unpack(b'%s%iL' % (endian, nints), data)\n outfile.write(\"unsigned long = %s\\n\" % str(longs2))\n if 'q' in types:\n longs = unpack(b'%s%iq' % (endian, ndoubles), data[:ndoubles*8])\n outfile.write(\"long long = %s\\n\" % str(longs))\n return strings, ints, floats\n\n def show_ndata(self, n, types='ifs'):\n return self._write_ndata(sys.stdout, n, types=types)\n\n def _write_ndata(self, outfile, n, types='ifs'):\n \"\"\"\n Useful function for seeing what's going on locally when debugging.\n \"\"\"\n nold = self.n\n data = self.infile.read(n)\n self.n = nold\n self.infile.seek(self.n)\n return self._write_data(outfile, data, types=types)\n\n\nclass Cart3D(Cart3dIO):\n \"\"\"\n Cart3d interface class\n \"\"\"\n model_type = 'cart3d'\n isStructured = False\n isOutwardNormals = True\n\n def __init__(self, log=None, debug=False):\n Cart3dIO.__init__(self, log=log, debug=debug)\n self.loads = {}\n self.points = None\n self.elements = None\n\n def flip_model(self):\n \"\"\"flip the model about the y-axis\"\"\"\n self.points[:, 1] *= -1.\n self.elements = np.hstack([\n self.elements[:, 0:1],\n self.elements[:, 2:3],\n self.elements[:, 1:2],\n ])\n print(self.elements.shape)\n\n def make_mirror_model(self, nodes, elements, regions, loads, axis='y', tol=0.000001):\n \"\"\"\n Makes a full cart3d model about the given axis.\n\n Parameters\n ----------\n nodes : (nnodes, 3) ndarray\n the nodes\n elements : (nelements, 3) ndarray\n the elmements\n regions : (nelements) ndarray\n the regions\n loads : dict[str] = (nnodes) ndarray\n not supported\n axis : str; {\"x\", \"y\", \"z\", \"-x\", \"-y\", \"-z\"}\n a string of the axis\n tol : float; default=0.000001\n the tolerance for the centerline points\n \"\"\"\n raise NotImplementedError()\n self.log.info('---starting make_mirror_model---')\n assert tol >= 0, 'tol=%r' % tol # prevents hacks to the axis\n\n nnodes = nodes.shape[0]\n assert nnodes > 0, 'nnodes=%s' % nnodes\n\n nelements = elements.shape[0]\n assert nelements > 0, 'nelements=%s' % nelements\n\n ax = self._get_ax(axis)\n if ax in [0, 1, 2]: # positive x, y, z values; mirror to -side\n iy0 = np.where(nodes[:, ax] > tol)[0]\n ax2 = ax\n elif ax in [3, 4, 5]: # negative x, y, z values; mirror to +side\n iy0 = np.where(nodes[:, ax-3] < -tol)[0]\n ax2 = ax - 3 # we create ax2 in order to generalize the data updating\n else:\n raise NotImplementedError(axis)\n\n # the nodes to be duplicated are the nodes that aren't below the tolerance\n nodes_upper = nodes[iy0]\n nodes_upper[:, ax2] *= -1.0 # flip the nodes about the axis\n\n nodes2 = np.vstack([nodes, nodes_upper])\n nnodes2 = nodes2.shape[0]\n assert nnodes2 > nnodes, 'nnodes2=%s nnodes=%s' % (nnodes2, nnodes)\n\n nnodes_upper = nodes_upper.shape[0]\n elements_upper = elements.copy()\n nelements = elements.shape[0]\n\n # remap the mirrored nodes with the new node ids\n for eid in range(nelements):\n element = elements_upper[eid, :]\n for i, eidi in enumerate(element):\n if eidi in iy0:\n elements_upper[eid][i] = nnodes_upper + eidi\n\n # we need to reverse the element in order to get\n # the proper normal vector\n elements_upper[eid] = elements_upper[eid, ::-1]\n\n elements2 = np.vstack([elements, elements_upper])\n nelements2 = elements2.shape[0]\n assert nelements2 > nelements, 'nelements2=%s nelements=%s' % (nelements2, nelements)\n\n nregions = len(np.unique(regions))\n regions_upper = regions.copy() + nregions\n regions2 = np.hstack([regions, regions_upper])\n\n loads2 = {}\n for key, data in iteritems(loads):\n\n # flip the sign on the flipping axis terms\n if((key in ['U', 'rhoU'] and ax2 == 0) or\n (key in ['V', 'rhoV'] and ax2 == 1) or\n (key in ['W', 'rhoW'] and ax2 == 2)):\n data_upper = -data[iy0]\n else:\n data_upper = data[iy0]\n loads2[key] = np.hstack([data, data_upper])\n\n self.log.info('---finished make_mirror_model---')\n return (nodes2, elements2, regions2, loads2)\n\n def _get_ax(self, axis):\n \"\"\"helper method to convert an axis_string into an integer\"\"\"\n axis = axis.lower().strip()\n if axis in ['+x', 'x', 0]:\n ax = 0\n elif axis in ['+y', 'y', 1]:\n ax = 1\n elif axis in ['+z', 'z', 2]:\n ax = 2\n\n elif axis in ['-x', 3]:\n ax = 3\n elif axis == ['-y', 4]:\n ax = 4\n elif axis == ['-z', 5]:\n ax = 5\n else:\n raise NotImplementedError('axis=%r' % axis)\n self.log.info(\"axis=%r ax=%s\" % (axis, ax))\n return ax\n\n def make_half_model(self, axis='y', remap_nodes=True):\n \"\"\"\n Makes a half model from a full model\n\n ... note:: Cp is really loads['Cp'] and was meant for loads analysis only\n \"\"\"\n nodes = self.nodes\n elements = self.elements\n regions = self.regions\n loads = self.loads\n if loads is None:\n loads = {}\n\n nnodes = nodes.shape[0]\n assert nnodes > 0, 'nnodes=%s' % nnodes\n\n nelements = elements.shape[0]\n assert nelements > 0, 'nelements=%s' % nelements\n\n inodes_remove = set([])\n self.log.info('---starting make_half_model---')\n ax = self._get_ax(axis)\n\n if ax in [0, 1, 2]: # remove values > 0\n inodes_save = np.where(nodes[:, ax] >= 0.0)[0]\n elif ax in [3, 4, 5]: # remove values < 0\n inodes_save = np.where(nodes[:, ax-3] <= 0.0)[0]\n else:\n raise NotImplementedError('axis=%r ax=%s' % (axis, ax))\n inodes_save.sort()\n\n inodes_map = np.arange(len(inodes_save))\n if not(0 < len(inodes_save) < nnodes):\n msg = 'len(inodes_save)=%s nnodes=%s' % (len(inodes_save), nnodes)\n raise RuntimeError(msg)\n\n nodes2 = nodes[inodes_save, :]\n nnodes2 = nodes2.shape[0]\n assert 0 < nnodes2 < nnodes, 'nnodes=%s nnodes2=%s' % (nnodes, nnodes2)\n\n inodes_save += 1 # +1 is so we don't have to shift inode\n # .. todo:: still need to handle element's node id renumbering\n ielements_save = set([])\n for ielement in range(nelements):\n save_element = True\n element = elements[ielement, :]\n\n # could be faster...\n for inode in element:\n if inode not in inodes_save:\n save_element = False\n break\n\n if save_element:\n ielements_save.add(ielement)\n\n ielements_save_lst = list(ielements_save)\n ielements_save_lst.sort()\n\n elements2 = elements[ielements_save_lst]\n regions2 = regions[ielements_save_lst]\n\n # renumbers mesh\n nelements2 = elements2.shape[0]\n assert 0 < nelements2 < nelements, 'nelements=%s nelements2=%s' % (nelements, nelements2)\n\n remap_nodes = False\n if np.amax(elements2) > len(inodes_save):\n # build a dictionary of old node ids to new node ids\n nodes_map = {}\n for i in range(1, len(inodes_save) + 1):\n nid = inodes_save[i - 1]\n nodes_map[nid] = i\n\n # update the node ids\n for ielement in range(nelements2):\n element = elements2[ielement, :]\n elements[ielement, :] = [nodes_map[nid] for nid in element]\n\n loads2 = {} # 'Cp', 'Mach', 'U', etc.\n for key, load in iteritems(loads):\n loads2[key] = load[inodes_save]\n\n self.log.info('---finished make_half_model---')\n return (nodes2, elements2, regions2, loads2)\n\n def get_free_edges(self, elements):\n \"\"\"\n Cart3d must be a closed model with each edge shared by 2 elements\n The free edges indicate the problematic areas.\n\n Returns\n -------\n free edges : (nedges, 2) int ndarray\n the free edge node ids\n \"\"\"\n edge_to_eid_map = defaultdict(list)\n for i, element in enumerate(elements):\n edge1 = tuple(sorted([element[0], element[1]]))\n edge2 = tuple(sorted([element[1], element[2]]))\n edge3 = tuple(sorted([element[2], element[0]]))\n edge_to_eid_map[edge1].append(i)\n edge_to_eid_map[edge2].append(i)\n edge_to_eid_map[edge3].append(i)\n\n free_edges = []\n for edge, eids in sorted(iteritems(edge_to_eid_map)):\n if len(eids) != 2:\n free_edges.append(edge)\n return np.array(free_edges, dtype='int32')\n\n def read_cart3d(self, infilename, result_names=None):\n \"\"\"extracts the points, elements, and Cp\"\"\"\n self.infilename = infilename\n self.log.info(\"---reading cart3d...%r---\" % self.infilename)\n\n self.infilename = infilename\n if is_binary_file(infilename):\n with open(infilename, 'rb') as self.infile:\n try:\n npoints, nelements, nresults = self._read_header_binary()\n self.points = self._read_points_binary(npoints)\n self.elements = self._read_elements_binary(nelements)\n self.regions = self._read_regions_binary(nelements)\n # TODO: loads\n except:\n msg = 'failed reading %r' % infilename\n self.log.error(msg)\n raise\n\n else:\n with codec_open(_filename(infilename), 'r', encoding=self._encoding) as self.infile:\n try:\n npoints, nelements, nresults = self._read_header_ascii()\n self.points = self._read_points_ascii(npoints)\n self.elements = self._read_elements_ascii(nelements)\n self.regions = self._read_regions_ascii(nelements)\n self._read_results_ascii(0, self.infile, nresults, result_names=result_names)\n except:\n msg = 'failed reading %r' % infilename\n self.log.error(msg)\n raise\n\n self.log.debug(\"npoints=%s nelements=%s\" % (self.npoints, self.nelements))\n assert self.npoints > 0, 'npoints=%s' % self.npoints\n assert self.nelements > 0, 'nelements=%s' % self.nelements\n\n def write_cart3d(self, outfilename, is_binary=False, float_fmt='%6.7f'):\n \"\"\"\n writes a cart3d file\n \"\"\"\n assert len(self.points) > 0, 'len(self.points)=%s' % len(self.points)\n\n if self.loads is None or self.loads == {}:\n loads = {}\n is_loads = False\n else:\n is_loads = True\n\n self.log.info(\"---writing cart3d...%r---\" % outfilename)\n if is_binary:\n form = 'wb'\n else:\n form = write_ascii\n\n with codec_open(outfilename, form) as outfile:\n int_fmt = self._write_header(outfile, self.points, self.elements, is_loads, is_binary)\n self._write_points(outfile, self.points, is_binary, float_fmt)\n self._write_elements(outfile, self.elements, is_binary, int_fmt)\n self._write_regions(outfile, self.regions, is_binary)\n\n if is_loads:\n assert is_binary is False, 'is_binary=%r is not supported for loads' % is_binary\n self._write_loads(outfile, self.loads, is_binary, float_fmt)\n\n\n def get_min(self, points, i):\n return np.amin(points[:, i])\n\n def get_max(self, points, i):\n return np.amax(points[:, i])\n\n def _read_results_ascii(self, i, infile, nresults, result_names=None):\n \"\"\"\n Reads the Cp results.\n Results are read on a nodal basis from the following table:\n Cp\n rho,rhoU,rhoV,rhoW,rhoE\n\n With the following definitions:\n Cp = (p - 1/gamma) / (0.5*M_inf*M_inf)\n rhoVel^2 = rhoU^2+rhoV^2+rhoW^2\n M^2 = rhoVel^2/rho^2\n\n Thus:\n p = (gamma-1)*(e- (rhoU**2+rhoV**2+rhoW**2)/(2.*rho))\n p_dimensional = qInf * Cp + pInf\n\n # ???\n rho,rhoU,rhoV,rhoW,rhoE\n\n Parameters\n ----------\n result_names : List[str]; default=None (All)\n result_names = ['Cp', 'rho', 'rhoU', 'rhoV', 'rhoW', 'rhoE',\n 'Mach', 'U', 'V', 'W', 'E']\n \"\"\"\n if nresults == 0:\n return\n loads = {}\n if result_names is None:\n result_names = ['Cp', 'rho', 'rhoU', 'rhoV', 'rhoW', 'rhoE',\n 'Mach', 'U', 'V', 'W', 'E', 'a', 'T', 'Pressure', 'q']\n self.log.debug('---starting read_results---')\n\n results = np.zeros((self.npoints, 6), dtype='float32')\n\n nresult_lines = int(ceil(nresults / 5.)) - 1\n for ipoint in range(self.npoints):\n # rho rhoU,rhoV,rhoW,pressure/rhoE/E\n sline = infile.readline().strip().split()\n i += 1\n for n in range(nresult_lines):\n sline += infile.readline().strip().split() # Cp\n i += 1\n #gamma = 1.4\n #else:\n # p=0.\n sline = _get_list(sline)\n\n # Cp\n # rho rhoU rhoV rhoW E\n # 0.416594\n # 1.095611 0.435676 0.003920 0.011579 0.856058\n results[ipoint, :] = sline\n\n #p=0\n #cp = sline[0]\n #rho = float(sline[1])\n #if(rho > abs(0.000001)):\n #rhoU = float(sline[2])\n #rhoV = float(sline[3])\n #rhoW = float(sline[4])\n #rhoE = float(sline[5])\n #mach2 = (rhoU) ** 2 + (rhoV) ** 2 + (rhoW) ** 2 / rho ** 2\n #mach = sqrt(mach2)\n #if mach > 10:\n #print(\"nid=%s Cp=%s mach=%s rho=%s rhoU=%s rhoV=%s rhoW=%s\" % (\n #pointNum, cp, mach, rho, rhoU, rhoV, rhoW))\n #print(\"pt=%s i=%s Cp=%s p=%s\" %(pointNum,i,sline[0],p))\n del sline\n self.loads = self._calculate_results(result_names, results)\n\n def _calculate_results(self, result_names, results, loads=None):\n \"\"\"\n Takes the Cart3d variables and calculates additional variables\n\n Parameters\n ----------\n result_names : List[str]\n the variables to calculate\n results : (n,6) ndarray\n the non-dimensional prmitive flow variables\n loads : dict; default=None -> {}\n key : ???\n value : ???\n \"\"\"\n if loads is None:\n loads = {}\n Cp = results[:, 0]\n rho = results[:, 1]\n rhoU = results[:, 2]\n rhoV = results[:, 3]\n rhoW = results[:, 4]\n E = results[:, 5]\n\n ibad = np.where(rho <= 0.000001)[0]\n if len(ibad) > 0:\n\n if 'Mach' in result_names:\n Mach = np.sqrt(rhoU**2 + rhoV**2 + rhoW**2)# / rho\n Mach[ibad] = 0.0\n if 'U' in result_names:\n U = rhoU / rho\n U[ibad] = 0.0\n if 'U' in result_names:\n V = rhoV / rho\n V[ibad] = 0.0\n if 'W' in result_names:\n W = rhoW / rho\n W[ibad] = 0.0\n #if 'rhoE' in result_names:\n #rhoE = rhoE / rho\n #e[ibad] = 0.0\n\n is_bad = True\n n = 0\n #for i in ibad:\n #print(\"nid=%s Cp=%s mach=%s rho=%s rhoU=%s rhoV=%s rhoW=%s\" % (\n #i, Cp[i], Mach[i], rho[i], rhoU[i], rhoV[i], rhoW[i]))\n #Mach[i] = 0.0\n #n += 1\n #if n > 10:\n # break\n else:\n is_bad = False\n\n\n #loc = locals()\n if 'Cp' in result_names:\n loads['Cp'] = Cp\n if 'rhoU' in result_names:\n loads['rhoU'] = rhoU\n if 'rhoV' in result_names:\n loads['rhoV'] = rhoV\n if 'rhoW' in result_names:\n loads['rhoW'] = rhoW\n #if 'rhoE' in result_names:\n #loads['rhoE'] = rhoE\n\n if 'rho' in result_names:\n loads['rho'] = rho\n\n if 'Mach' in result_names:\n if not is_bad:\n #Mach = np.sqrt(rhoU**2 + rhoV**2 + rhoW**2) / rho\n Mach = np.sqrt(rhoU**2 + rhoV**2 + rhoW**2)\n loads['Mach'] = Mach\n\n if 'U' in result_names:\n if not is_bad:\n U = rhoU / rho\n loads['U'] = U\n if 'V' in result_names:\n if not is_bad:\n V = rhoV / rho\n loads['V'] = V\n if 'W' in result_names:\n if not is_bad:\n W = rhoW / rho\n loads['W'] = W\n if 'E' in result_names:\n #if not is_bad:\n #E = rhoE / rho\n loads['E'] = E\n\n gamma = 1.4\n qinf = 1.0\n pinf = 1. / gamma\n Tinf = 1.0\n #Cp = (p - pinf) / qinf\n p = Cp * qinf + pinf\n\n T = (Tinf * gamma) * p / rho\n q = 0.5 * rho * Mach ** 2\n\n if 'a' in result_names:\n #print('T: min=%s max=%s' % (T.min(), T.max()))\n loads['a'] = np.sqrt(T)\n if 'T' in result_names:\n loads['T'] = T\n\n if 'Pressure' in result_names:\n loads['Pressure'] = p\n if 'q' in result_names:\n loads['q'] = q\n # dynamic pressure\n # speed of sound\n # total pressure = p0/rhoi*ainf**2\n # total density\n # entropy\n # kinetic energy\n # enthalpy\n # energy, E\n # total energy\n # total enthalpy\n\n #i = where(Mach == max(Mach))[0][0]\n #self.log.info(\"i=%s Cp=%s rho=%s rhoU=%s rhoV=%s rhoW=%s Mach=%s\" % (\n #i, Cp[i], rho[i], rhoU[i], rhoV[i], rhoW[i], Mach[i]))\n self.log.debug('---finished read_results---')\n return loads\n\n def _get_area_vector(self):\n \"\"\"\n Gets the area vector (unnormalized normal vector)\n Returns\n -------\n normals : (n, 3) ndarray\n unnormalized centroidal normal vectors\n \"\"\"\n elements = self.elements\n nodes = self.nodes\n p1 = nodes[elements[:, 0], :]\n p2 = nodes[elements[:, 1], :]\n p3 = nodes[elements[:, 2], :]\n\n ne = elements.shape[0]\n avec = p2 - p1\n bvec = p3 - p1\n n = np.cross(avec, bvec)\n assert len(n) == ne, 'len(n)=%s ne=%s' % (len(n), ne)\n\n return n\n\n def get_area(self):\n \"\"\"\n Gets the element area\n\n Returns\n -------\n area : (n, 3) ndarray\n the element areas\n \"\"\"\n ne = self.elements.shape[0]\n n = self._get_area_vector()\n ni = np.linalg.norm(n, axis=1)\n assert len(ni) == ne, 'len(ni)=%s ne=%s' % (len(ni), ne)\n return 0.5 * ni\n\n def get_normals(self):\n \"\"\"\n Gets the centroidal normals\n\n Returns\n -------\n cnormals : (n, 3) ndarray\n normalized centroidal normal vectors\n \"\"\"\n ne = self.elements.shape[0]\n n = self._get_area_vector()\n ni = np.linalg.norm(n, axis=1)\n assert len(ni) == ne, 'len(ni)=%s ne=%s' % (len(ni), ne)\n\n assert ni.min() > 0.0, ni[np.where(ni <= 0.0)[0]]\n n /= ni[:, None] # normal vector\n return n\n\n def get_normals_at_nodes(self, cnormals):\n \"\"\"\n Gets the nodal normals\n\n Parameters\n ----------\n cnormals : (n, 3) ndarray\n normalized centroidal normal vectors\n\n Returns\n -------\n nnormals : (n, 3) ndarray\n normalized nodal normal vectors\n \"\"\"\n elements = self.elements\n nodes = self.nodes\n nnodes = self.nnodes\n nid_to_eids = defaultdict(list)\n\n # find the elements to consider for each node\n for eid, element in enumerate(elements):\n n1, n2, n3 = element\n nid_to_eids[n1].append(eid)\n nid_to_eids[n2].append(eid)\n nid_to_eids[n3].append(eid)\n\n nnormals = np.zeros((nnodes, 3), dtype='float64')\n for nid in range(nnodes):\n eids = nid_to_eids[nid]\n if len(eids) == 0:\n raise RuntimeError('nid=%s is not used' % nid)\n ni_avg = cnormals[eids, :]\n nnormals[nid] = cnormals[eids, :].sum(axis=0)\n ni = np.linalg.norm(nnormals, axis=1)\n assert ni.min() > 0, ni\n nnormals /= ni[:, None] # normal vector\n return nnormals\n\ndef convert_to_float(svalues):\n \"\"\"Takes a list of strings and converts them to floats.\"\"\"\n values = []\n for value in svalues:\n values.append(float(value))\n return values\n\ndef _get_list(sline):\n \"\"\"Takes a list of strings and converts them to floats.\"\"\"\n try:\n sline2 = convert_to_float(sline)\n except ValueError:\n print(\"sline = %s\" % sline)\n raise SyntaxError('cannot parse %s' % sline)\n return sline2\n", "repo_name": "EmanueleCannizzaro/pynastran2", "sub_path": "pynastran2/cart3d.py", "file_name": "cart3d.py", "file_ext": "py", "file_size_in_byte": 36284, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "25", "api": [{"api_name": "six.PY2", "line_number": 33, "usage_type": "name"}, {"api_name": "numpy.unique", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 91, "usage_type": "call"}, {"api_name": "pyNastran.utils.log.get_logger2", "line_number": 104, "usage_type": "call"}, {"api_name": "pyNastran.utils.b", "line_number": 136, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 137, "usage_type": "call"}, {"api_name": "pyNastran.utils.b", "line_number": 139, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 140, "usage_type": "call"}, {"api_name": "pyNastran.utils.b", "line_number": 146, "usage_type": "call"}, {"api_name": "pyNastran.utils.b", "line_number": 148, "usage_type": "call"}, {"api_name": "pyNastran.utils.b", "line_number": 152, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 159, "usage_type": "call"}, {"api_name": "pyNastran.utils.b", "line_number": 159, "usage_type": "call"}, {"api_name": "pyNastran.utils.b", "line_number": 163, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 164, "usage_type": "call"}, {"api_name": "numpy.ravel", "line_number": 164, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 173, "usage_type": "call"}, {"api_name": "pyNastran.utils.b", "line_number": 180, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 181, "usage_type": "call"}, {"api_name": "pyNastran.utils.b", "line_number": 184, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.ravel", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 194, "usage_type": "call"}, {"api_name": "pyNastran.utils.b", "line_number": 199, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 200, "usage_type": "call"}, {"api_name": "pyNastran.utils.b", "line_number": 204, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 205, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 211, "usage_type": "call"}, {"api_name": "six.moves.zip", "line_number": 229, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 285, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 313, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 329, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 341, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 342, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 360, "usage_type": "call"}, {"api_name": "pyNastran.utils.b", "line_number": 360, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 363, "usage_type": "call"}, {"api_name": "pyNastran.utils.b", "line_number": 363, "usage_type": "call"}, {"api_name": "numpy.dtype", "line_number": 378, "usage_type": "call"}, {"api_name": "pyNastran.utils.b", "line_number": 378, "usage_type": "call"}, {"api_name": "numpy.fromstring", "line_number": 379, "usage_type": "call"}, {"api_name": "numpy.dtype", "line_number": 389, "usage_type": "call"}, {"api_name": "pyNastran.utils.b", "line_number": 389, "usage_type": "call"}, {"api_name": "numpy.fromstring", "line_number": 390, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 401, "usage_type": "call"}, {"api_name": "numpy.fromstring", "line_number": 403, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 426, "usage_type": "attribute"}, {"api_name": "struct.unpack", "line_number": 444, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 447, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 450, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 454, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 457, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 460, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 463, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 468, "usage_type": "attribute"}, {"api_name": "numpy.hstack", "line_number": 498, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 536, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 539, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 548, "usage_type": "call"}, {"api_name": "six.moves.range", "line_number": 557, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 567, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 571, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 573, "usage_type": "call"}, {"api_name": "six.iteritems", "line_number": 576, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 585, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 635, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 637, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 642, "usage_type": "call"}, {"api_name": "six.moves.range", "line_number": 654, "usage_type": "call"}, {"api_name": "numpy.amax", "line_number": 678, "usage_type": "call"}, {"api_name": "six.moves.range", "line_number": 681, "usage_type": "call"}, {"api_name": "six.moves.range", "line_number": 686, "usage_type": "call"}, {"api_name": "six.iteritems", "line_number": 691, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 707, "usage_type": "call"}, {"api_name": "six.iteritems", "line_number": 717, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 720, "usage_type": "call"}, {"api_name": "pyNastran.utils.is_binary_file", "line_number": 728, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 742, "usage_type": "call"}, {"api_name": "pyNastran.utils._filename", "line_number": 742, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 776, "usage_type": "call"}, {"api_name": "numpy.amin", "line_number": 788, "usage_type": "call"}, {"api_name": "numpy.amax", "line_number": 791, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 826, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 828, "usage_type": "call"}, {"api_name": "six.moves.range", "line_number": 829, "usage_type": "call"}, {"api_name": "six.moves.range", "line_number": 833, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 887, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 891, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 937, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 969, "usage_type": "call"}, {"api_name": "numpy.cross", "line_number": 1011, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 1027, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 1027, "usage_type": "attribute"}, {"api_name": "numpy.linalg.norm", "line_number": 1042, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 1042, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 1045, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 1066, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 1075, "usage_type": "call"}, {"api_name": "six.moves.range", "line_number": 1076, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 1082, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 1082, "usage_type": "attribute"}]} +{"seq_id": "17702451898", "text": "from .. import PloneMessageFactory as _\nfrom ..browser import formhelper\nfrom ..portlets import base\nfrom Acquisition import aq_base\nfrom Acquisition import aq_inner\nfrom plone.base.interfaces.controlpanel import ISiteSchema\nfrom plone.i18n.normalizer.interfaces import IIDNormalizer\nfrom plone.memoize.instance import memoize\nfrom plone.portlets.interfaces import IPortletDataProvider\nfrom plone.registry.interfaces import IRegistry\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\nfrom zope import schema\nfrom zope.component import getMultiAdapter\nfrom zope.component import getUtility\nfrom zope.component import queryUtility\nfrom zope.interface import implementer\n\n\nclass IReviewPortlet(IPortletDataProvider):\n no_icons = schema.Bool(\n title=_(\"Suppress Icons\"),\n description=_(\"If enabled, the portlet will not show document type icons\"),\n required=False,\n default=False,\n )\n\n thumb_scale = schema.TextLine(\n title=_(\"Override thumb scale\"),\n description=_(\n \"Enter a valid scale name\"\n \" (see 'Image Handling' control panel) to override\"\n \" (e.g. icon, tile, thumb, mini, preview, ... ).\"\n \" Leave empty to use default (see 'Site' control panel).\"\n ),\n required=False,\n default=\"\",\n )\n\n no_thumbs = schema.Bool(\n title=_(\"Suppress thumbs\"),\n description=_(\"If enabled, the portlet will not show thumbs.\"),\n required=False,\n default=False,\n )\n\n\n@implementer(IReviewPortlet)\nclass Assignment(base.Assignment):\n no_icons = False\n thumb_scale = None\n no_thumbs = False\n\n def __init__(self, no_icons=False, thumb_scale=None, no_thumbs=False):\n self.no_icons = no_icons\n self.thumb_scale = thumb_scale\n self.no_thumbs = no_thumbs\n\n @property\n def title(self):\n return _(\"Review list\")\n\n\nclass Renderer(base.Renderer):\n render = ViewPageTemplateFile(\"review.pt\")\n\n title = _(\"box_review_list\", default=\"Review List\")\n\n def __init__(self, *args):\n base.Renderer.__init__(self, *args)\n\n @property\n def anonymous(self):\n context = aq_inner(self.context)\n portal_state = getMultiAdapter(\n (context, self.request), name=\"plone_portal_state\"\n )\n return portal_state.anonymous()\n\n @property\n def available(self):\n return not self.anonymous and len(self._data())\n\n def review_items(self):\n return self._data()\n\n def full_review_link(self):\n context = aq_inner(self.context)\n mtool = getToolByName(context, \"portal_membership\")\n # check if user is allowed to Review Portal Content here\n if mtool.checkPermission(\"Review portal content\", context):\n return \"%s/full_review_list\" % context.absolute_url()\n else:\n return None\n\n @memoize\n def _data(self):\n if self.anonymous:\n return []\n context = aq_inner(self.context)\n workflow = getToolByName(context, \"portal_workflow\")\n\n plone_view = getMultiAdapter((context, self.request), name=\"plone\")\n getMember = getToolByName(context, \"portal_membership\").getMemberById\n toLocalizedTime = plone_view.toLocalizedTime\n\n idnormalizer = queryUtility(IIDNormalizer)\n norm = idnormalizer.normalize\n objects = workflow.getWorklistsResults()\n items = []\n for obj in objects:\n review_state = workflow.getInfoFor(obj, \"review_state\")\n creator_id = obj.Creator()\n creator = getMember(creator_id)\n if creator:\n creator_name = creator.getProperty(\"fullname\", \"\") or creator_id\n else:\n creator_name = creator_id\n hasImage = True if getattr(aq_base(obj), \"image\", None) else False\n images = obj.restrictedTraverse(\"@@images\") if hasImage else None\n items.append(\n dict(\n path=obj.absolute_url(),\n title=obj.pretty_title_or_id(),\n item_class=\"contenttype-\" + norm(obj.portal_type),\n description=obj.Description(),\n creator=creator_name,\n review_state=review_state,\n review_state_class=\"state-%s \" % norm(review_state),\n mod_date=toLocalizedTime(obj.ModificationDate()),\n hasImage=hasImage,\n images=images,\n )\n )\n return items\n\n @memoize\n def thumb_scale(self):\n \"\"\"Use override value or read thumb_scale from registry.\n Image sizes must fit to value in allowed image sizes.\n None will suppress thumb.\n \"\"\"\n if getattr(self.data, \"no_thumbs\", False):\n # Individual setting overrides ...\n return None\n thsize = getattr(self.data, \"thumb_scale\", \"\")\n if thsize:\n return thsize\n registry = getUtility(IRegistry)\n settings = registry.forInterface(ISiteSchema, prefix=\"plone\", check=False)\n thumb_scale_portlet = settings.thumb_scale_portlet\n return thumb_scale_portlet\n\n\nclass AddForm(formhelper.AddForm):\n schema = IReviewPortlet\n label = _(\"Add Review Portlet\")\n description = _(\"This portlet displays a queue of documents awaiting \" \"review.\")\n\n def create(self, data):\n return Assignment(**data)\n\n\nclass EditForm(formhelper.EditForm):\n schema = IReviewPortlet\n label = _(\"Edit Review Portlet\")\n description = _(\"displays a queue of documents awaiting \" \"review.\")\n", "repo_name": "plone/plone.app.portlets", "sub_path": "plone/app/portlets/portlets/review.py", "file_name": "review.py", "file_ext": "py", "file_size_in_byte": 5686, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 12, "dataset": "github-code", "pt": "25", "api": [{"api_name": "plone.portlets.interfaces.IPortletDataProvider", "line_number": 20, "usage_type": "name"}, {"api_name": "zope.schema.Bool", "line_number": 21, "usage_type": "call"}, {"api_name": "zope.schema", "line_number": 21, "usage_type": "name"}, {"api_name": "zope.schema.TextLine", "line_number": 28, "usage_type": "call"}, {"api_name": "zope.schema", "line_number": 28, "usage_type": "name"}, {"api_name": "zope.schema.Bool", "line_number": 40, "usage_type": "call"}, {"api_name": "zope.schema", "line_number": 40, "usage_type": "name"}, {"api_name": "portlets.base.Assignment", "line_number": 49, "usage_type": "attribute"}, {"api_name": "portlets.base", "line_number": 49, "usage_type": "name"}, {"api_name": "zope.interface.implementer", "line_number": 48, "usage_type": "call"}, {"api_name": "portlets.base.Renderer", "line_number": 64, "usage_type": "attribute"}, {"api_name": "portlets.base", "line_number": 64, "usage_type": "name"}, {"api_name": "Products.Five.browser.pagetemplatefile.ViewPageTemplateFile", "line_number": 65, "usage_type": "call"}, {"api_name": "portlets.base.Renderer.__init__", "line_number": 70, "usage_type": "call"}, {"api_name": "portlets.base.Renderer", "line_number": 70, "usage_type": "attribute"}, {"api_name": "portlets.base", "line_number": 70, "usage_type": "name"}, {"api_name": "Acquisition.aq_inner", "line_number": 74, "usage_type": "call"}, {"api_name": "zope.component.getMultiAdapter", "line_number": 75, "usage_type": "call"}, {"api_name": "Acquisition.aq_inner", "line_number": 88, "usage_type": "call"}, {"api_name": "Products.CMFCore.utils.getToolByName", "line_number": 89, "usage_type": "call"}, {"api_name": "Acquisition.aq_inner", "line_number": 100, "usage_type": "call"}, {"api_name": "Products.CMFCore.utils.getToolByName", "line_number": 101, "usage_type": "call"}, {"api_name": "zope.component.getMultiAdapter", "line_number": 103, "usage_type": "call"}, {"api_name": "Products.CMFCore.utils.getToolByName", "line_number": 104, "usage_type": "call"}, {"api_name": "zope.component.queryUtility", "line_number": 107, "usage_type": "call"}, {"api_name": "plone.i18n.normalizer.interfaces.IIDNormalizer", "line_number": 107, "usage_type": "argument"}, {"api_name": "Acquisition.aq_base", "line_number": 119, "usage_type": "call"}, {"api_name": "plone.memoize.instance.memoize", "line_number": 96, "usage_type": "name"}, {"api_name": "zope.component.getUtility", "line_number": 149, "usage_type": "call"}, {"api_name": "plone.registry.interfaces.IRegistry", "line_number": 149, "usage_type": "argument"}, {"api_name": "plone.base.interfaces.controlpanel.ISiteSchema", "line_number": 150, "usage_type": "argument"}, {"api_name": "plone.memoize.instance.memoize", "line_number": 137, "usage_type": "name"}, {"api_name": "browser.formhelper.AddForm", "line_number": 155, "usage_type": "attribute"}, {"api_name": "browser.formhelper", "line_number": 155, "usage_type": "name"}, {"api_name": "zope.schema", "line_number": 156, "usage_type": "name"}, {"api_name": "browser.formhelper.EditForm", "line_number": 164, "usage_type": "attribute"}, {"api_name": "browser.formhelper", "line_number": 164, "usage_type": "name"}, {"api_name": "zope.schema", "line_number": 165, "usage_type": "name"}]} +{"seq_id": "33855853629", "text": "import common\nimport f_main\nfrom f_main import ( bail, diag, DIAG_COLUMN, DIAG_ERR, DIAG_FILE, DIAG_LINE )\nimport f_stmt\nimport f_token as tk\nimport f_expr\nimport b_opcode\n\nAREA_TOP = 0\nAREA_LOCAL = 1\nAREA_FOR = 2\nAREA_PARAM = 3\n\nMAX_MAP_LOCATIONS = 128\nMAX_WORLD_LOCATIONS = 256\nMAX_GLOBAL_LOCATIONS = 64\n\nSCRIPT_MIN_NUM = 0\nSCRIPT_MAX_NUM = 999\nSCRIPT_MAX_PARAMS = 3\n\ndef is_dec( front ):\n return front.tk in [ tk.T_INT, tk.T_STR, tk.T_BOOL, tk.T_VOID,\n tk.T_FUNCTION, tk.T_WORLD, tk.T_GLOBAL, tk.T_STATIC ]\n\ndef read( front, area ):\n dec = {\n 'area' : area,\n 'pos' : front.tk_pos,\n 'storage' : common.STORAGE_LOCAL,\n 'storage_pos' : None,\n 'storage_name' : 'local',\n 'value' : False,\n 'name' : '',\n 'name_pos' : None,\n 'dim' : [],\n 'dim_implicit' : None,\n 'initials' : []\n }\n func = False\n if front.tk == tk.T_FUNCTION and area == AREA_TOP:\n tk.read( front )\n func = True\n\n # Storage.\n if not func:\n if front.tk == tk.T_GLOBAL:\n dec[ 'storage' ] = common.STORAGE_GLOBAL\n dec[ 'storage_pos' ] = front.tk_pos\n dec[ 'storage_name' ] = front.tk_text\n tk.read( front )\n elif front.tk == tk.T_WORLD:\n dec[ 'storage' ] = common.STORAGE_WORLD\n dec[ 'storage_pos' ] = front.tk_pos\n dec[ 'storage_name' ] = front.tk_text\n tk.read( front )\n elif front.tk == tk.T_STATIC:\n dec[ 'storage' ] = common.STORAGE_MAP\n dec[ 'storage_name' ] = 'map'\n if area == AREA_FOR:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n front.tk_pos, 'static variable in for loop initialization' )\n elif area == AREA_PARAM:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n front.tk_pos, '\\'static\\' used in parameter' )\n elif area == AREA_TOP:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n front.tk_pos, '\\'static\\' used in top scope' )\n tk.read( front )\n elif area == AREA_TOP:\n dec[ 'storage' ] = common.STORAGE_MAP\n dec[ 'storage_name' ] = 'map'\n\n # Type.\n if front.tk in [ tk.T_INT, tk.T_STR, tk.T_BOOL ]:\n # Scripts can only have integer parameters.\n if area == AREA_PARAM and front.dec_params[ 'is_script' ] and \\\n front.tk != tk.T_INT:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n front.tk_pos, 'script parameter not of \\'int\\' type' )\n dec[ 'value' ] = True\n tk.read( front )\n elif front.tk == tk.T_VOID:\n tk.read( front )\n else:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n front.tk_pos, 'expecting type in declaration' )\n raise Exception\n bail( front )\n\n while True:\n # Storage index.\n if not func:\n if front.tk == tk.T_LIT_DECIMAL:\n pos = front.tk_pos\n dec[ 'storage_index' ] = f_expr.read_literal( front )\n tk.test( front, tk.T_COLON )\n tk.read( front )\n max_loc = MAX_WORLD_LOCATIONS\n if dec[ 'storage' ] != common.STORAGE_WORLD:\n if dec[ 'storage' ] == common.STORAGE_GLOBAL:\n max_loc = MAX_GLOBAL_LOCATIONS\n else:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n pos, 'index specified for %s storage',\n dec[ 'storage_name' ] )\n bail( front )\n if dec[ 'storage_index' ] >= max_loc:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n pos, 'index specified for %s storage',\n dec[ 'storage_name' ] )\n bail( front )\n else:\n # Index must be explicitly specified for these storages.\n if dec[ 'storage' ] == common.STORAGE_WORLD or \\\n dec[ 'storage' ] == common.STORAGE_GLOBAL:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n front.tk_pos, 'missing index for %s storage',\n dec[ 'storage_name' ] )\n bail( front )\n\n # Name.\n if front.tk == tk.T_ID:\n dec[ 'name_pos' ] = front.tk_pos\n dec[ 'name' ] = read_unique_name( front )\n else:\n # Parameters don't require a name.\n if area != AREA_PARAM:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n front.tk_pos, 'missing name in declaration' )\n bail( front )\n\n if func:\n tk.test( front, tk.T_PAREN_L )\n tk.read( front )\n f_main.add_scope( front )\n num_param = read_param_list( front, False )\n tk.test( front, tk.T_PAREN_R )\n tk.read( front )\n func = common.func_t()\n func.pos = dec[ 'name_pos' ]\n func.value = dec[ 'value' ]\n func.name = dec[ 'name' ]\n func.min_param = num_param\n func.max_param = num_param\n front.scopes[ 0 ].names[ func.name ] = func\n block = common.block_t()\n front.block = block\n front.func = func\n f_stmt.read_block( front )\n f_main.pop_scope( front )\n front.block = None\n front.func = None\n func.impl = {\n 'def' : True,\n 'def_params' : True,\n 'body' : block,\n 'index' : 0,\n 'size' : 0\n }\n front.module.funcs.append( func )\n break\n else:\n # Array dimension.\n if front.tk == tk.T_BRACKET_L:\n read_dim( front, dec )\n else:\n dec[ 'dim' ] = []\n dec[ 'dim_implicit' ] = None\n read_init( front, dec )\n if area == AREA_PARAM:\n if dec[ 'name' ]:\n pass\n break\n else:\n finish_var( front, dec )\n if front.tk == tk.T_COMMA:\n tk.read( front )\n else:\n tk.test( front, tk.T_SEMICOLON )\n tk.read( front )\n break\n\ndef read_unique_name( front ):\n tk.test( front, tk.T_ID )\n if front.tk_text in front.scope.names:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n front.tk_pos, 'name \\'%s\\' already used', front.tk_text )\n object = front.scope.names[ front.tk_text ]\n pos = None\n if object.node == common.NODE_VAR or \\\n object.node == common.NODE_CONSTANT:\n pos = object.pos\n elif object.node == common.NODE_FUNC:\n # These builtin functions are loaded internally by the compiler and\n # have no position of their definition given.\n if object.type != common.FUNC_DED and \\\n object.type != common.FUNC_FORMAT:\n pos = object.pos\n if pos:\n diag( front, DIAG_FILE | DIAG_LINE | DIAG_COLUMN, pos,\n 'name previously used here' )\n bail( front )\n else:\n name = front.tk_text\n tk.read( front )\n return name\n\ndef read_dim( front, dec ):\n # At this time, a local array is not allowed.\n if dec[ 'storage' ] == common.STORAGE_LOCAL:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n front.tk_pos, 'array in local scope' )\n bail( front )\n while front.tk == tk.T_BRACKET_L:\n pos = front.tk_pos\n tk.read( front )\n expr = None\n # Implicit size.\n if front.tk == tk.T_BRACKET_R:\n # Only the first dimension can have an implicit size.\n if len( dec[ 'dim' ] ):\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN, pos,\n 'implicit size in subsequent dimension' )\n bail( front )\n tk.read( front )\n else:\n expr = f_expr.read( front, True )\n tk.test( front, tk.T_BRACKET_R )\n tk.read( front )\n if not expr.folded:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n expr.pos, 'array size not a constant expression' )\n bail( front )\n elif expr.value <= 0:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n expr.pos, 'invalid array size' )\n bail( front )\n dim = common.dim_t()\n dec[ 'dim' ].append( dim )\n if not expr:\n dec[ 'dim_implicit' ] = dim\n else:\n dim.size = expr.value\n i = len( dec[ 'dim' ] ) - 1\n # For now, each element of the last dimension is 1 integer in size.\n dec[ 'dim' ][ i ].element_size = 1\n while i > 0:\n dec[ 'dim' ][ i - 1 ].element_size = (\n dec[ 'dim' ][ i ].element_size *\n dec[ 'dim' ][ i ].size )\n i -= 1\n\ndef read_init( front, dec ):\n if front.tk != tk.T_ASSIGN:\n if dec[ 'dim_implicit' ] and ( (\n dec[ 'storage' ] != common.STORAGE_WORLD and\n dec[ 'storage' ] != common.STORAGE_GLOBAL ) or\n len( dec[ 'dim' ] ) > 1 ):\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n front.tk_pos, 'missing initialization' )\n bail( front )\n return\n # At this time, there is no way to initialize at the top scope an array with\n # world or global storage.\n if ( dec[ 'storage' ] == common.STORAGE_WORLD or\n dec[ 'storage' ] == common.STORAGE_GLOBAL ) and \\\n len( front.scopes ) == 1:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n front.tk_pos, 'initialization of variable with %s storage '\n 'at top scope', dec[ 'storage_name' ] )\n bail( front )\n tk.read( front )\n if front.tk == tk.T_BRACE_L:\n read_initz( front, dec )\n else:\n if len( dec[ 'dim' ] ):\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n front.tk_pos, 'array initialization missing initializer' )\n bail( front )\n expr = f_expr.read( front, True )\n if dec[ 'storage' ] == common.STORAGE_MAP and not expr.folded:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN, expr.pos,\n 'initial value not constant' )\n bail( front )\n initial = common.initial_t()\n initial.value = expr.value\n dec[ 'initials' ].append( initial )\n\ndef finish_var( front, dec ):\n var = common.var_t()\n var.pos = dec[ 'name_pos' ]\n var.name = dec[ 'name' ]\n var.storage = dec[ 'storage' ]\n var.dim = dec[ 'dim' ]\n if var.dim:\n var.size = var.dim[ 0 ].size * var.dim[ 0 ].element_size\n var.initial = dec[ 'initials' ]\n else:\n var.size = 1\n if dec[ 'initials' ]:\n var.initial = dec[ 'initials' ].pop()\n front.scope.names[ var.name ] = var\n if var.dim:\n front.module.arrays.append( var )\n elif dec[ 'area' ] == AREA_TOP:\n # Variables with initials appear first.\n if var.initial:\n front.module.vars.insert( 0, var )\n else:\n front.module.vars.append( var )\n elif dec[ 'area' ] == AREA_LOCAL:\n var.index = alloc_index( front )\n front.block.stmts.append( var )\n else:\n var.index = alloc_index( front )\n front.dec_for_init.append( var )\n\ndef read_param_list( front, is_script ):\n return 0\n\ndef read_script( front ):\n tk.test( front, tk.T_SCRIPT )\n script = common.script_t()\n script.pos = front.tk_pos\n tk.read( front )\n # Script number.\n number_pos = None\n if front.tk == tk.T_SHIFT_L:\n tk.read( front )\n # The token between the << and >> tokens must be the digit zero.\n if front.tk == tk.T_LIT_DECIMAL and front.tk_text == '0':\n number_pos = front.tk_pos\n tk.read( front )\n tk.test( front, tk.T_SHIFT_R )\n tk.read( front )\n else:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n front.tk_pos, 'missing the digit 0' )\n bail( front )\n else:\n front.reading_script_number = True\n expr = f_expr.read( front, True )\n front.reading_script_number = False\n if not expr.folded:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n expr.pos, 'script number not a constant expression' )\n bail( front )\n elif expr.value < SCRIPT_MIN_NUM or expr.value > SCRIPT_MAX_NUM:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n expr.pos, 'script number not between %d and %d', SCRIPT_MIN_NUM,\n SCRIPT_MAX_NUM )\n bail( front )\n elif expr.value == 0:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n expr.pos, 'script number 0 not between << and >>' )\n bail( front )\n else:\n script.number = expr.value\n number_pos = expr.pos\n # There should be no duplicate scripts in the same module.\n for older_script in front.module.scripts:\n if script.number == older_script.number:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n number_pos, 'script number %d already used', script.number )\n diag( front, DIAG_FILE | DIAG_LINE | DIAG_COLUMN, older_script.pos,\n 'first script to use number found here' )\n break\n f_main.add_scope( front )\n # Parameter list.\n param_pos = None\n if front.tk == tk.T_PAREN_L:\n param_pos = front.tk_pos\n tk.read( front )\n script.num_param = read_param_list( front, True )\n tk.test( front, tk.T_PAREN_R )\n tk.read( front )\n # Script type.\n types = {\n tk.T_OPEN : common.SCRIPT_TYPE_OPEN,\n tk.T_RESPAWN : common.SCRIPT_TYPE_RESPAWN,\n tk.T_DEATH : common.SCRIPT_TYPE_DEATH,\n tk.T_ENTER : common.SCRIPT_TYPE_ENTER,\n tk.T_PICKUP : common.SCRIPT_TYPE_PICKUP,\n tk.T_BLUE_RETURN : common.SCRIPT_TYPE_BLUE_RETURN,\n tk.T_RED_RETURN : common.SCRIPT_TYPE_RED_RETURN,\n tk.T_WHITE_RETURN : common.SCRIPT_TYPE_WHITE_RETURN,\n tk.T_LIGHTNING : common.SCRIPT_TYPE_LIGHTNING,\n tk.T_DISCONNECT : common.SCRIPT_TYPE_DISCONNECT,\n tk.T_UNLOADING : common.SCRIPT_TYPE_UNLOADING,\n tk.T_RETURN : common.SCRIPT_TYPE_RETURN }\n name = ''\n if front.tk in types:\n script.type = types[ front.tk ]\n name = front.tk_text\n tk.read( front )\n if script.type == common.SCRIPT_TYPE_CLOSED:\n if script.num_param > SCRIPT_MAX_PARAMS:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n param_pos, 'script has over maximum %d parameters',\n SCRIPT_MAX_PARAMS )\n elif script.type == common.SCRIPT_TYPE_DISCONNECT:\n # A disconnect script must have a single parameter. It is the number of\n # the player who disconnected from the server.\n if script.num_param != 1:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n param_pos,\n 'disconnect script missing one player-number parameter' )\n else:\n if script.num_param != 0:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n param_pos, 'parameter list specified for %s script', name )\n # Script flags.\n while True:\n flag = common.SCRIPT_FLAG_NET\n if front.tk != tk.T_NET:\n if front.tk == tk.T_CLIENTSIDE:\n flag = common.SCRIPT_FLAG_CLIENTSIDE\n else:\n break\n if not ( script.flags & flag ):\n script.flags |= flag\n tk.read( front )\n else:\n diag( front, DIAG_ERR | DIAG_FILE | DIAG_LINE | DIAG_COLUMN,\n front.tk_pos, '%s flag already set', front.tk_text )\n tk.read( front )\n # Body.\n block = common.block_t()\n block.in_script = True\n front.block = block\n f_stmt.read_block( front )\n front.block = None\n script.body = block\n f_main.pop_scope( front )\n front.module.scripts.append( script )\n\ndef read_bfunc_list( front ):\n tk.test( front, tk.T_SPECIAL )\n tk.read( front )\n while True:\n ext = False\n if front.tk == tk.T_MINUS:\n tk.read( front )\n ext = True\n code = f_expr.read_literal( front )\n tk.test( front, tk.T_COLON )\n tk.read( front )\n name_pos = front.tk_pos\n name = read_unique_name( front )\n tk.test( front, tk.T_PAREN_L )\n tk.read( front )\n min_param = 0\n max_param = f_expr.read_literal( front )\n if front.tk == tk.T_COMMA:\n min_param = max_param\n tk.read( front )\n max_param = f_expr.read_literal( front )\n tk.test( front, tk.T_PAREN_R )\n tk.read( front )\n func = common.func_t()\n func.pos = name_pos\n func.value = True\n func.min_param = min_param\n func.max_param = max_param\n front.scopes[ 0 ].names[ name ] = func\n if ext:\n func.type = common.FUNC_EXT\n func.impl[ 'id' ] = code\n else:\n func.type = common.FUNC_ASPEC\n func.impl[ 'id' ] = code\n if front.tk == tk.T_COMMA:\n tk.read( front )\n else:\n tk.test( front, tk.T_SEMICOLON )\n tk.read( front )\n break\n\ndef load_ded_format_funcs( front ):\n ded = [\n # Format: name / returns-value / parameter-count / parameter-minimum /\n # opcode / is-latent.\n [ 'delay', False, 1, 1, b_opcode.k_delay, True ],\n [ 'random', True, 2, 2, b_opcode.k_random, False ],\n [ 'thingcount', True, 2, 2, b_opcode.k_thing_count, False ],\n [ 'tagwait', False, 1, 1, b_opcode.k_tag_wait, True ],\n [ 'polywait', False, 1, 1, b_opcode.k_poly_wait, True ],\n [ 'changefloor', False, 2, 2, b_opcode.k_change_floor, False ],\n [ 'changeceiling', False, 2, 2, b_opcode.k_change_ceiling, False ],\n [ 'lineside', True, 0, 0, b_opcode.k_line_side, False ],\n [ 'scriptwait', False, 1, 1, b_opcode.k_script_wait, True ],\n [ 'clearlinespecial', False, 0, 0, b_opcode.k_clear_line_special, False ],\n [ 'playercount', True, 0, 0, b_opcode.k_player_count, False ],\n [ 'gametype', True, 0, 0, b_opcode.k_game_type, False ],\n [ 'gameskill', True, 0, 0, b_opcode.k_game_skill, False ],\n [ 'timer', True, 0, 0, b_opcode.k_timer, False ],\n [ 'sectorsound', False, 2, 2, b_opcode.k_sector_sound, False ],\n [ 'ambientsound', False, 2, 2, b_opcode.k_ambient_sound, False ],\n [ 'soundsequence', False, 1, 1, b_opcode.k_sound_sequence, False ],\n [ 'setlinetexture', False, 4, 4, b_opcode.k_set_line_texture, False ],\n [ 'setlineblocking', False, 2, 2, b_opcode.k_set_line_blocking, False ],\n [ 'setlinespecial', False, 7, 2, b_opcode.k_set_line_special, False ],\n [ 'thingsound', False, 3, 3, b_opcode.k_thing_sound, False ],\n [ 'activatorsound', False, 2, 2, b_opcode.k_activator_sound, False ],\n [ 'localambientsound', False, 2, 2, b_opcode.k_local_ambient_sound,\n False ],\n [ 'setlinemonsterblocking', False, 2, 2,\n b_opcode.k_set_line_monster_blocking, False ],\n [ 'ismultiplayer', True, 0, 0, b_opcode.k_is_multiplayer, False ],\n [ 'playerteam', True, 0, 0, b_opcode.k_player_team, False ],\n [ 'playerhealth', True, 0, 0, b_opcode.k_player_health, False ],\n [ 'playerarmorpoints', True, 0, 0, b_opcode.k_player_armor_points,\n False ],\n [ 'playerfrags', True, 0, 0, b_opcode.k_player_frags, False ],\n [ 'bluecount', True, 0, 0, b_opcode.k_blue_team_count, False ],\n [ 'blueteamcount', True, 0, 0, b_opcode.k_blue_team_count, False ],\n [ 'redcount', True, 0, 0, b_opcode.k_red_team_count, False ],\n [ 'redteamcount', True, 0, 0, b_opcode.k_red_team_count, False ],\n [ 'bluescore', True, 0, 0, b_opcode.k_blue_team_score, False ],\n [ 'blueteamscore', True, 0, 0, b_opcode.k_blue_team_score, False ],\n [ 'redscore', True, 0, 0, b_opcode.k_red_team_score, False ],\n [ 'redteamscore', True, 0, 0, b_opcode.k_red_team_score, False ],\n [ 'isoneflagctf', True, 0, 0, b_opcode.k_is_one_flag_ctf, False ],\n [ 'getinvasionwave', True, 0, 0, b_opcode.k_get_invasion_wave, False ],\n [ 'getinvasionstate', True, 0, 0, b_opcode.k_get_invasion_state, False ],\n [ 'music_change', False, 2, 2, b_opcode.k_music_change, False ],\n [ 'consolecommand', False, 3, 1, b_opcode.k_console_command, False ],\n [ 'singleplayer', True, 0, 0, b_opcode.k_single_player, False ],\n [ 'fixedmul', True, 2, 2, b_opcode.k_fixed_mul, False ],\n [ 'fixeddiv', True, 2, 2, b_opcode.k_fixed_div, False ],\n [ 'setgravity', False, 1, 1, b_opcode.k_set_gravity, False ],\n [ 'setaircontrol', False, 1, 1, b_opcode.k_set_air_control, False ],\n [ 'clearinventory', False, 0, 0, b_opcode.k_clear_inventory, False ],\n [ 'giveinventory', False, 2, 2, b_opcode.k_give_inventory, False ],\n [ 'takeinventory', False, 2, 2, b_opcode.k_take_inventory, False ],\n [ 'checkinventory', True, 1, 1, b_opcode.k_check_inventory, False ],\n [ 'spawn', True, 6, 4, b_opcode.k_spawn, False ],\n [ 'spawnspot', True, 4, 2, b_opcode.k_spawn_spot, False ],\n [ 'setmusic', False, 3, 1, b_opcode.k_set_music, False ],\n [ 'localsetmusic', False, 3, 1, b_opcode.k_local_set_music, False ],\n [ 'setfont', False, 1, 1, b_opcode.k_set_font, False ],\n [ 'setthingspecial', False, 7, 2, b_opcode.k_set_thing_special, False ],\n [ 'fadeto', False, 5, 5, b_opcode.k_fade_to, False ],\n [ 'faderange', False, 9, 9, b_opcode.k_fade_range, False ],\n [ 'cancelfade', False, 0, 0, b_opcode.k_cancel_fade, False ],\n [ 'playmovie', True, 1, 1, b_opcode.k_play_movie, False ],\n [ 'setfloortrigger', False, 8, 3, b_opcode.k_set_floor_trigger, False ],\n [ 'setceilingtrigger', False, 8, 3, b_opcode.k_set_ceiling_trigger,\n False ],\n [ 'getactorx', True, 1, 1, b_opcode.k_get_actor_x, False ],\n [ 'getactory', True, 1, 1, b_opcode.k_get_actor_y, False ],\n [ 'getactorz', True, 1, 1, b_opcode.k_get_actor_z, False ],\n [ 'sin', True, 1, 1, b_opcode.k_sin, False ],\n [ 'cos', True, 1, 1, b_opcode.k_cos, False ],\n [ 'vectorangle', True, 2, 2, b_opcode.k_vector_angle, False ],\n [ 'checkweapon', True, 1, 1, b_opcode.k_check_weapon, False ],\n [ 'setweapon', True, 1, 1, b_opcode.k_set_weapon, False ],\n [ 'setmarineweapon', False, 2, 2, b_opcode.k_set_marine_weapon, False ],\n [ 'setactorproperty', False, 3, 3, b_opcode.k_set_actor_property, False ],\n [ 'getactorproperty', True, 2, 2, b_opcode.k_get_actor_property, False ],\n [ 'playernumber', True, 0, 0, b_opcode.k_player_number, False ],\n [ 'activatortid', True, 0, 0, b_opcode.k_activator_tid, False ],\n [ 'setmarinesprite', False, 2, 2, b_opcode.k_set_marine_sprite, False ],\n [ 'getscreenwidth', True, 0, 0, b_opcode.k_get_screen_width, False ],\n [ 'getscreenheight', True, 0, 0, b_opcode.k_get_screen_height, False ],\n [ 'thing_projectile2', False, 7, 7, b_opcode.k_thing_projectile2, False ],\n [ 'strlen', True, 1, 1, b_opcode.k_strlen, False ],\n [ 'sethudsize', False, 3, 3, b_opcode.k_set_hud_size, False ],\n [ 'getcvar', True, 1, 1, b_opcode.k_get_cvar, False ],\n [ 'setresultvalue', False, 1, 1, b_opcode.k_set_result_value, False ],\n [ 'getlinerowoffset', True, 0, 0, b_opcode.k_get_line_row_offset, False ],\n [ 'getactorfloorz', True, 1, 1, b_opcode.k_get_actor_floor_z, False ],\n [ 'getactorangle', True, 1, 1, b_opcode.k_get_actor_angle, False ],\n [ 'getsectorfloorz', True, 3, 3, b_opcode.k_get_sector_floor_z, False ],\n [ 'getsectorceilingz', True, 3, 3, b_opcode.k_get_sector_ceiling_z,\n False ],\n [ 'getsigilpieces', True, 0, 0, b_opcode.k_get_sigil_pieces, False ],\n [ 'getlevelinfo', True, 1, 1, b_opcode.k_get_level_info, False ],\n [ 'changesky', False, 2, 2, b_opcode.k_change_sky, False ],\n [ 'playeringame', True, 1, 1, b_opcode.k_player_in_game, False ],\n [ 'playerisbot', True, 1, 1, b_opcode.k_player_is_bot, False ],\n [ 'setcameratotexture', False, 3, 3, b_opcode.k_set_camera_to_texture,\n False ],\n [ 'getammocapacity', True, 1, 1, b_opcode.k_get_ammo_capacity, False ],\n [ 'setammocapacity', False, 2, 2, b_opcode.k_set_ammo_capacity, False ],\n [ 'setactorangle', False, 2, 2, b_opcode.k_set_actor_angle, False ],\n [ 'spawnprojectile', False, 7, 7, b_opcode.k_spawn_projectile, False ],\n [ 'getsectorlightlevel', True, 1, 1, b_opcode.k_get_sector_light_level,\n False ],\n [ 'getactorceilingz', True, 1, 1, b_opcode.k_get_actor_ceiling_z, False ],\n [ 'clearactorinventory', False, 1, 1, b_opcode.k_clear_actor_inventory,\n False ],\n [ 'giveactorinventory', False, 3, 3, b_opcode.k_give_actor_inventory,\n False ],\n [ 'takeactorinventory', False, 3, 3, b_opcode.k_take_actor_inventory,\n False ],\n [ 'checkactorinventory', True, 2, 2, b_opcode.k_check_actor_inventory,\n False ],\n [ 'thingcountname', True, 2, 2, b_opcode.k_thing_count_name, False ],\n [ 'spawnspotfacing', True, 3, 2, b_opcode.k_spawn_spot_facing, False ],\n [ 'playerclass', True, 1, 1, b_opcode.k_player_class, False ],\n [ 'getplayerinfo', True, 2, 2, b_opcode.k_get_player_info, False ],\n [ 'changelevel', False, 4, 3, b_opcode.k_change_level, False ],\n [ 'sectordamage', False, 5, 5, b_opcode.k_sector_damage, False ],\n [ 'replacetextures', False, 3, 2, b_opcode.k_replace_textures, False ],\n [ 'getactorpitch', True, 1, 1, b_opcode.k_get_actor_pitch, False ],\n [ 'setactorpitch', False, 2, 2, b_opcode.k_set_actor_pitch, False ],\n [ 'setactorstate', True, 3, 2, b_opcode.k_set_actor_state, False ],\n [ 'thing_damage2', True, 3, 3, b_opcode.k_thing_damage2, False ],\n [ 'useinventory', True, 1, 1, b_opcode.k_use_inventory, False ],\n [ 'useactorinventory', True, 2, 2, b_opcode.k_use_actor_inventory,\n False ],\n [ 'checkactorceilingtexture', True, 2, 2,\n b_opcode.k_check_actor_ceiling_texture, False ],\n [ 'checkactorfloortexture', True, 2, 2,\n b_opcode.k_check_actor_floor_texture, False ],\n [ 'getactorlightlevel', True, 1, 1, b_opcode.k_get_actor_light_level,\n False ],\n [ 'setmugshotstate', False, 1, 1, b_opcode.k_set_mugshot_state, False ],\n [ 'thingcountsector', True, 3, 3, b_opcode.k_thing_count_sector, False ],\n [ 'thingcountnamesector', True, 3, 3, b_opcode.k_thing_count_name_sector,\n False ],\n [ 'checkplayercamera', True, 1, 1, b_opcode.k_check_player_camera,\n False ],\n [ 'morphactor', True, 7, 7, b_opcode.k_morph_actor, False ],\n [ 'unmorphactor', True, 2, 1, b_opcode.k_unmorph_actor, False ],\n [ 'getplayerinput', True, 2, 2, b_opcode.k_get_player_input, False ],\n [ 'classifyactor', True, 1, 1, b_opcode.k_classify_actor, False ] ]\n for template in ded:\n name, value, max_param, min_param, opcode, latent = template\n func = common.func_t()\n func.type = common.FUNC_DED\n func.value = value\n func.min_param = min_param\n func.max_param = max_param\n func.impl = {\n 'opcode' : opcode,\n 'latent' : latent }\n front.scope.names[ name ] = func\n format = [\n # Format: name / returns-value / parameter-count / parameter-minimum /\n # terminating-opcode.\n # Note: The format items together count as a single parameter.\n [ 'print', False, 1, 1, b_opcode.k_end_print ],\n [ 'printbold', False, 1, 1, b_opcode.k_end_print_bold ],\n [ 'hudmessage', False, 9, 7, b_opcode.k_end_hud_message ],\n [ 'hudmessagebold', False, 9, 7, b_opcode.k_end_hud_message_bold ],\n [ 'log', False, 1, 1, b_opcode.k_end_log ],\n [ 'strparam', True, 1, 1, b_opcode.k_save_string ] ]\n for template in format:\n name, value, max_param, min_param, opcode = template\n func = common.func_t()\n func.type = common.FUNC_FORMAT\n func.value = value\n func.min_param = min_param\n func.max_param = max_param\n func.impl = {\n 'opcode' : opcode }\n front.scope.names[ name ] = func", "repo_name": "positively-charged/bcc-python", "sub_path": "src/f_dec.py", "file_name": "f_dec.py", "file_ext": "py", "file_size_in_byte": 27855, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "f_token.T_INT", "line_number": 23, "usage_type": "attribute"}, {"api_name": "f_token.T_STR", "line_number": 23, "usage_type": "attribute"}, {"api_name": "f_token.T_BOOL", "line_number": 23, "usage_type": "attribute"}, {"api_name": "f_token.T_VOID", "line_number": 23, "usage_type": "attribute"}, {"api_name": "f_token.T_FUNCTION", "line_number": 24, "usage_type": "attribute"}, {"api_name": "f_token.T_WORLD", "line_number": 24, "usage_type": "attribute"}, {"api_name": "f_token.T_GLOBAL", "line_number": 24, "usage_type": "attribute"}, {"api_name": "f_token.T_STATIC", "line_number": 24, "usage_type": "attribute"}, {"api_name": "common.STORAGE_LOCAL", "line_number": 30, "usage_type": "attribute"}, {"api_name": "f_token.T_FUNCTION", "line_number": 41, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 42, "usage_type": "call"}, {"api_name": "f_token.T_GLOBAL", "line_number": 47, "usage_type": "attribute"}, {"api_name": "common.STORAGE_GLOBAL", "line_number": 48, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 51, "usage_type": "call"}, {"api_name": "f_token.T_WORLD", "line_number": 52, "usage_type": "attribute"}, {"api_name": "common.STORAGE_WORLD", "line_number": 53, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 56, "usage_type": "call"}, {"api_name": "f_token.T_STATIC", "line_number": 57, "usage_type": "attribute"}, {"api_name": "common.STORAGE_MAP", "line_number": 58, "usage_type": "attribute"}, {"api_name": "f_main.diag", "line_number": 61, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 61, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 61, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 61, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 61, "usage_type": "name"}, {"api_name": "f_main.diag", "line_number": 64, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 64, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 64, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 64, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 64, "usage_type": "name"}, {"api_name": "f_main.diag", "line_number": 67, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 67, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 67, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 67, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 67, "usage_type": "name"}, {"api_name": "f_token.read", "line_number": 69, "usage_type": "call"}, {"api_name": "common.STORAGE_MAP", "line_number": 71, "usage_type": "attribute"}, {"api_name": "f_token.T_INT", "line_number": 75, "usage_type": "attribute"}, {"api_name": "f_token.T_STR", "line_number": 75, "usage_type": "attribute"}, {"api_name": "f_token.T_BOOL", "line_number": 75, "usage_type": "attribute"}, {"api_name": "f_token.T_INT", "line_number": 78, "usage_type": "attribute"}, {"api_name": "f_main.diag", "line_number": 79, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 79, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 79, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 79, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 79, "usage_type": "name"}, {"api_name": "f_token.read", "line_number": 82, "usage_type": "call"}, {"api_name": "f_token.T_VOID", "line_number": 83, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 84, "usage_type": "call"}, {"api_name": "f_main.diag", "line_number": 86, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 86, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 86, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 86, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 86, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 89, "usage_type": "call"}, {"api_name": "f_token.T_LIT_DECIMAL", "line_number": 94, "usage_type": "attribute"}, {"api_name": "f_expr.read_literal", "line_number": 96, "usage_type": "call"}, {"api_name": "f_token.test", "line_number": 97, "usage_type": "call"}, {"api_name": "f_token.T_COLON", "line_number": 97, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 98, "usage_type": "call"}, {"api_name": "common.STORAGE_WORLD", "line_number": 100, "usage_type": "attribute"}, {"api_name": "common.STORAGE_GLOBAL", "line_number": 101, "usage_type": "attribute"}, {"api_name": "f_main.diag", "line_number": 104, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 104, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 104, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 104, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 104, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 107, "usage_type": "call"}, {"api_name": "f_main.diag", "line_number": 109, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 109, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 109, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 109, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 109, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 112, "usage_type": "call"}, {"api_name": "common.STORAGE_WORLD", "line_number": 115, "usage_type": "attribute"}, {"api_name": "common.STORAGE_GLOBAL", "line_number": 116, "usage_type": "attribute"}, {"api_name": "f_main.diag", "line_number": 117, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 117, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 117, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 117, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 117, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 120, "usage_type": "call"}, {"api_name": "f_token.T_ID", "line_number": 123, "usage_type": "attribute"}, {"api_name": "f_main.diag", "line_number": 129, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 129, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 129, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 129, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 129, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 131, "usage_type": "call"}, {"api_name": "f_token.test", "line_number": 134, "usage_type": "call"}, {"api_name": "f_token.T_PAREN_L", "line_number": 134, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 135, "usage_type": "call"}, {"api_name": "f_main.add_scope", "line_number": 136, "usage_type": "call"}, {"api_name": "f_token.test", "line_number": 138, "usage_type": "call"}, {"api_name": "f_token.T_PAREN_R", "line_number": 138, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 139, "usage_type": "call"}, {"api_name": "common.func_t", "line_number": 140, "usage_type": "call"}, {"api_name": "common.block_t", "line_number": 147, "usage_type": "call"}, {"api_name": "f_stmt.read_block", "line_number": 150, "usage_type": "call"}, {"api_name": "f_main.pop_scope", "line_number": 151, "usage_type": "call"}, {"api_name": "f_token.T_BRACKET_L", "line_number": 165, "usage_type": "attribute"}, {"api_name": "f_token.T_COMMA", "line_number": 177, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 178, "usage_type": "call"}, {"api_name": "f_token.test", "line_number": 180, "usage_type": "call"}, {"api_name": "f_token.T_SEMICOLON", "line_number": 180, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 181, "usage_type": "call"}, {"api_name": "f_token.test", "line_number": 185, "usage_type": "call"}, {"api_name": "f_token.T_ID", "line_number": 185, "usage_type": "attribute"}, {"api_name": "f_main.diag", "line_number": 187, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 187, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 187, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 187, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 187, "usage_type": "name"}, {"api_name": "common.NODE_VAR", "line_number": 191, "usage_type": "attribute"}, {"api_name": "common.NODE_CONSTANT", "line_number": 192, "usage_type": "attribute"}, {"api_name": "common.NODE_FUNC", "line_number": 194, "usage_type": "attribute"}, {"api_name": "common.FUNC_DED", "line_number": 197, "usage_type": "attribute"}, {"api_name": "common.FUNC_FORMAT", "line_number": 198, "usage_type": "attribute"}, {"api_name": "f_main.diag", "line_number": 201, "usage_type": "call"}, {"api_name": "f_main.DIAG_FILE", "line_number": 201, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 201, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 201, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 203, "usage_type": "call"}, {"api_name": "f_token.read", "line_number": 206, "usage_type": "call"}, {"api_name": "common.STORAGE_LOCAL", "line_number": 211, "usage_type": "attribute"}, {"api_name": "f_main.diag", "line_number": 212, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 212, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 212, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 212, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 212, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 214, "usage_type": "call"}, {"api_name": "f_token.T_BRACKET_L", "line_number": 215, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 217, "usage_type": "call"}, {"api_name": "f_token.T_BRACKET_R", "line_number": 220, "usage_type": "attribute"}, {"api_name": "f_main.diag", "line_number": 223, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 223, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 223, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 223, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 223, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 225, "usage_type": "call"}, {"api_name": "f_token.read", "line_number": 226, "usage_type": "call"}, {"api_name": "f_expr.read", "line_number": 228, "usage_type": "call"}, {"api_name": "f_token.test", "line_number": 229, "usage_type": "call"}, {"api_name": "f_token.T_BRACKET_R", "line_number": 229, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 230, "usage_type": "call"}, {"api_name": "f_main.diag", "line_number": 232, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 232, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 232, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 232, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 232, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 234, "usage_type": "call"}, {"api_name": "f_main.diag", "line_number": 236, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 236, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 236, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 236, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 236, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 238, "usage_type": "call"}, {"api_name": "common.dim_t", "line_number": 239, "usage_type": "call"}, {"api_name": "f_token.T_ASSIGN", "line_number": 255, "usage_type": "attribute"}, {"api_name": "common.STORAGE_WORLD", "line_number": 257, "usage_type": "attribute"}, {"api_name": "common.STORAGE_GLOBAL", "line_number": 258, "usage_type": "attribute"}, {"api_name": "f_main.diag", "line_number": 260, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 260, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 260, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 260, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 260, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 262, "usage_type": "call"}, {"api_name": "common.STORAGE_WORLD", "line_number": 266, "usage_type": "attribute"}, {"api_name": "common.STORAGE_GLOBAL", "line_number": 267, "usage_type": "attribute"}, {"api_name": "f_main.diag", "line_number": 269, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 269, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 269, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 269, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 269, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 272, "usage_type": "call"}, {"api_name": "f_token.read", "line_number": 273, "usage_type": "call"}, {"api_name": "f_token.T_BRACE_L", "line_number": 274, "usage_type": "attribute"}, {"api_name": "f_main.diag", "line_number": 278, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 278, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 278, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 278, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 278, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 280, "usage_type": "call"}, {"api_name": "f_expr.read", "line_number": 281, "usage_type": "call"}, {"api_name": "common.STORAGE_MAP", "line_number": 282, "usage_type": "attribute"}, {"api_name": "f_main.diag", "line_number": 283, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 283, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 283, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 283, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 283, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 285, "usage_type": "call"}, {"api_name": "common.initial_t", "line_number": 286, "usage_type": "call"}, {"api_name": "common.var_t", "line_number": 291, "usage_type": "call"}, {"api_name": "f_token.test", "line_number": 323, "usage_type": "call"}, {"api_name": "f_token.T_SCRIPT", "line_number": 323, "usage_type": "attribute"}, {"api_name": "common.script_t", "line_number": 324, "usage_type": "call"}, {"api_name": "f_token.read", "line_number": 326, "usage_type": "call"}, {"api_name": "f_token.T_SHIFT_L", "line_number": 329, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 330, "usage_type": "call"}, {"api_name": "f_token.T_LIT_DECIMAL", "line_number": 332, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 334, "usage_type": "call"}, {"api_name": "f_token.test", "line_number": 335, "usage_type": "call"}, {"api_name": "f_token.T_SHIFT_R", "line_number": 335, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 336, "usage_type": "call"}, {"api_name": "f_main.diag", "line_number": 338, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 338, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 338, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 338, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 338, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 340, "usage_type": "call"}, {"api_name": "f_expr.read", "line_number": 343, "usage_type": "call"}, {"api_name": "f_main.diag", "line_number": 346, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 346, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 346, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 346, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 346, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 348, "usage_type": "call"}, {"api_name": "f_main.diag", "line_number": 350, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 350, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 350, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 350, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 350, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 353, "usage_type": "call"}, {"api_name": "f_main.diag", "line_number": 355, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 355, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 355, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 355, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 355, "usage_type": "name"}, {"api_name": "f_main.bail", "line_number": 357, "usage_type": "call"}, {"api_name": "f_main.diag", "line_number": 364, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 364, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 364, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 364, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 364, "usage_type": "name"}, {"api_name": "f_main.diag", "line_number": 366, "usage_type": "call"}, {"api_name": "f_main.DIAG_FILE", "line_number": 366, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 366, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 366, "usage_type": "name"}, {"api_name": "f_main.add_scope", "line_number": 369, "usage_type": "call"}, {"api_name": "f_token.T_PAREN_L", "line_number": 372, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 374, "usage_type": "call"}, {"api_name": "f_token.test", "line_number": 376, "usage_type": "call"}, {"api_name": "f_token.T_PAREN_R", "line_number": 376, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 377, "usage_type": "call"}, {"api_name": "f_token.T_OPEN", "line_number": 380, "usage_type": "attribute"}, {"api_name": "f_token.T_RESPAWN", "line_number": 381, "usage_type": "attribute"}, {"api_name": "f_token.T_DEATH", "line_number": 382, "usage_type": "attribute"}, {"api_name": "f_token.T_ENTER", "line_number": 383, "usage_type": "attribute"}, {"api_name": "f_token.T_PICKUP", "line_number": 384, "usage_type": "attribute"}, {"api_name": "f_token.T_BLUE_RETURN", "line_number": 385, "usage_type": "attribute"}, {"api_name": "f_token.T_RED_RETURN", "line_number": 386, "usage_type": "attribute"}, {"api_name": "f_token.T_WHITE_RETURN", "line_number": 387, "usage_type": "attribute"}, {"api_name": "f_token.T_LIGHTNING", "line_number": 388, "usage_type": "attribute"}, {"api_name": "f_token.T_DISCONNECT", "line_number": 389, "usage_type": "attribute"}, {"api_name": "f_token.T_UNLOADING", "line_number": 390, "usage_type": "attribute"}, {"api_name": "f_token.T_RETURN", "line_number": 391, "usage_type": "attribute"}, {"api_name": "common.SCRIPT_TYPE_OPEN", "line_number": 380, "usage_type": "attribute"}, {"api_name": "common.SCRIPT_TYPE_RESPAWN", "line_number": 381, "usage_type": "attribute"}, {"api_name": "common.SCRIPT_TYPE_DEATH", "line_number": 382, "usage_type": "attribute"}, {"api_name": "common.SCRIPT_TYPE_ENTER", "line_number": 383, "usage_type": "attribute"}, {"api_name": "common.SCRIPT_TYPE_PICKUP", "line_number": 384, "usage_type": "attribute"}, {"api_name": "common.SCRIPT_TYPE_BLUE_RETURN", "line_number": 385, "usage_type": "attribute"}, {"api_name": "common.SCRIPT_TYPE_RED_RETURN", "line_number": 386, "usage_type": "attribute"}, {"api_name": "common.SCRIPT_TYPE_WHITE_RETURN", "line_number": 387, "usage_type": "attribute"}, {"api_name": "common.SCRIPT_TYPE_LIGHTNING", "line_number": 388, "usage_type": "attribute"}, {"api_name": "common.SCRIPT_TYPE_DISCONNECT", "line_number": 389, "usage_type": "attribute"}, {"api_name": "common.SCRIPT_TYPE_UNLOADING", "line_number": 390, "usage_type": "attribute"}, {"api_name": "common.SCRIPT_TYPE_RETURN", "line_number": 391, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 396, "usage_type": "call"}, {"api_name": "common.SCRIPT_TYPE_CLOSED", "line_number": 397, "usage_type": "attribute"}, {"api_name": "f_main.diag", "line_number": 399, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 399, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 399, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 399, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 399, "usage_type": "name"}, {"api_name": "common.SCRIPT_TYPE_DISCONNECT", "line_number": 402, "usage_type": "attribute"}, {"api_name": "f_main.diag", "line_number": 406, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 406, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 406, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 406, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 406, "usage_type": "name"}, {"api_name": "f_main.diag", "line_number": 411, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 411, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 411, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 411, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 411, "usage_type": "name"}, {"api_name": "common.SCRIPT_FLAG_NET", "line_number": 415, "usage_type": "attribute"}, {"api_name": "f_token.T_NET", "line_number": 416, "usage_type": "attribute"}, {"api_name": "f_token.T_CLIENTSIDE", "line_number": 417, "usage_type": "attribute"}, {"api_name": "common.SCRIPT_FLAG_CLIENTSIDE", "line_number": 418, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 423, "usage_type": "call"}, {"api_name": "f_main.diag", "line_number": 425, "usage_type": "call"}, {"api_name": "f_main.DIAG_ERR", "line_number": 425, "usage_type": "name"}, {"api_name": "f_main.DIAG_FILE", "line_number": 425, "usage_type": "name"}, {"api_name": "f_main.DIAG_LINE", "line_number": 425, "usage_type": "name"}, {"api_name": "f_main.DIAG_COLUMN", "line_number": 425, "usage_type": "name"}, {"api_name": "f_token.read", "line_number": 427, "usage_type": "call"}, {"api_name": "common.block_t", "line_number": 429, "usage_type": "call"}, {"api_name": "f_stmt.read_block", "line_number": 432, "usage_type": "call"}, {"api_name": "f_main.pop_scope", "line_number": 435, "usage_type": "call"}, {"api_name": "f_token.test", "line_number": 439, "usage_type": "call"}, {"api_name": "f_token.T_SPECIAL", "line_number": 439, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 440, "usage_type": "call"}, {"api_name": "f_token.T_MINUS", "line_number": 443, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 444, "usage_type": "call"}, {"api_name": "f_expr.read_literal", "line_number": 446, "usage_type": "call"}, {"api_name": "f_token.test", "line_number": 447, "usage_type": "call"}, {"api_name": "f_token.T_COLON", "line_number": 447, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 448, "usage_type": "call"}, {"api_name": "f_token.test", "line_number": 451, "usage_type": "call"}, {"api_name": "f_token.T_PAREN_L", "line_number": 451, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 452, "usage_type": "call"}, {"api_name": "f_expr.read_literal", "line_number": 454, "usage_type": "call"}, {"api_name": "f_token.T_COMMA", "line_number": 455, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 457, "usage_type": "call"}, {"api_name": "f_expr.read_literal", "line_number": 458, "usage_type": "call"}, {"api_name": "f_token.test", "line_number": 459, "usage_type": "call"}, {"api_name": "f_token.T_PAREN_R", "line_number": 459, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 460, "usage_type": "call"}, {"api_name": "common.func_t", "line_number": 461, "usage_type": "call"}, {"api_name": "common.FUNC_EXT", "line_number": 468, "usage_type": "attribute"}, {"api_name": "common.FUNC_ASPEC", "line_number": 471, "usage_type": "attribute"}, {"api_name": "f_token.T_COMMA", "line_number": 473, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 474, "usage_type": "call"}, {"api_name": "f_token.test", "line_number": 476, "usage_type": "call"}, {"api_name": "f_token.T_SEMICOLON", "line_number": 476, "usage_type": "attribute"}, {"api_name": "f_token.read", "line_number": 477, "usage_type": "call"}, {"api_name": "b_opcode.k_delay", "line_number": 484, "usage_type": "attribute"}, {"api_name": "b_opcode.k_random", "line_number": 485, "usage_type": "attribute"}, {"api_name": "b_opcode.k_thing_count", "line_number": 486, "usage_type": "attribute"}, {"api_name": "b_opcode.k_tag_wait", "line_number": 487, "usage_type": "attribute"}, {"api_name": "b_opcode.k_poly_wait", "line_number": 488, "usage_type": "attribute"}, {"api_name": "b_opcode.k_change_floor", "line_number": 489, "usage_type": "attribute"}, {"api_name": "b_opcode.k_change_ceiling", "line_number": 490, "usage_type": "attribute"}, {"api_name": "b_opcode.k_line_side", "line_number": 491, "usage_type": "attribute"}, {"api_name": "b_opcode.k_script_wait", "line_number": 492, "usage_type": "attribute"}, {"api_name": "b_opcode.k_clear_line_special", "line_number": 493, "usage_type": "attribute"}, {"api_name": "b_opcode.k_player_count", "line_number": 494, "usage_type": "attribute"}, {"api_name": "b_opcode.k_game_type", "line_number": 495, "usage_type": "attribute"}, {"api_name": "b_opcode.k_game_skill", "line_number": 496, "usage_type": "attribute"}, {"api_name": "b_opcode.k_timer", "line_number": 497, "usage_type": "attribute"}, {"api_name": "b_opcode.k_sector_sound", "line_number": 498, "usage_type": "attribute"}, {"api_name": "b_opcode.k_ambient_sound", "line_number": 499, "usage_type": "attribute"}, {"api_name": "b_opcode.k_sound_sequence", "line_number": 500, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_line_texture", "line_number": 501, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_line_blocking", "line_number": 502, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_line_special", "line_number": 503, "usage_type": "attribute"}, {"api_name": "b_opcode.k_thing_sound", "line_number": 504, "usage_type": "attribute"}, {"api_name": "b_opcode.k_activator_sound", "line_number": 505, "usage_type": "attribute"}, {"api_name": "b_opcode.k_local_ambient_sound", "line_number": 506, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_line_monster_blocking", "line_number": 509, "usage_type": "attribute"}, {"api_name": "b_opcode.k_is_multiplayer", "line_number": 510, "usage_type": "attribute"}, {"api_name": "b_opcode.k_player_team", "line_number": 511, "usage_type": "attribute"}, {"api_name": "b_opcode.k_player_health", "line_number": 512, "usage_type": "attribute"}, {"api_name": "b_opcode.k_player_armor_points", "line_number": 513, "usage_type": "attribute"}, {"api_name": "b_opcode.k_player_frags", "line_number": 515, "usage_type": "attribute"}, {"api_name": "b_opcode.k_blue_team_count", "line_number": 516, "usage_type": "attribute"}, {"api_name": "b_opcode.k_blue_team_count", "line_number": 517, "usage_type": "attribute"}, {"api_name": "b_opcode.k_red_team_count", "line_number": 518, "usage_type": "attribute"}, {"api_name": "b_opcode.k_red_team_count", "line_number": 519, "usage_type": "attribute"}, {"api_name": "b_opcode.k_blue_team_score", "line_number": 520, "usage_type": "attribute"}, {"api_name": "b_opcode.k_blue_team_score", "line_number": 521, "usage_type": "attribute"}, {"api_name": "b_opcode.k_red_team_score", "line_number": 522, "usage_type": "attribute"}, {"api_name": "b_opcode.k_red_team_score", "line_number": 523, "usage_type": "attribute"}, {"api_name": "b_opcode.k_is_one_flag_ctf", "line_number": 524, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_invasion_wave", "line_number": 525, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_invasion_state", "line_number": 526, "usage_type": "attribute"}, {"api_name": "b_opcode.k_music_change", "line_number": 527, "usage_type": "attribute"}, {"api_name": "b_opcode.k_console_command", "line_number": 528, "usage_type": "attribute"}, {"api_name": "b_opcode.k_single_player", "line_number": 529, "usage_type": "attribute"}, {"api_name": "b_opcode.k_fixed_mul", "line_number": 530, "usage_type": "attribute"}, {"api_name": "b_opcode.k_fixed_div", "line_number": 531, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_gravity", "line_number": 532, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_air_control", "line_number": 533, "usage_type": "attribute"}, {"api_name": "b_opcode.k_clear_inventory", "line_number": 534, "usage_type": "attribute"}, {"api_name": "b_opcode.k_give_inventory", "line_number": 535, "usage_type": "attribute"}, {"api_name": "b_opcode.k_take_inventory", "line_number": 536, "usage_type": "attribute"}, {"api_name": "b_opcode.k_check_inventory", "line_number": 537, "usage_type": "attribute"}, {"api_name": "b_opcode.k_spawn", "line_number": 538, "usage_type": "attribute"}, {"api_name": "b_opcode.k_spawn_spot", "line_number": 539, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_music", "line_number": 540, "usage_type": "attribute"}, {"api_name": "b_opcode.k_local_set_music", "line_number": 541, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_font", "line_number": 542, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_thing_special", "line_number": 543, "usage_type": "attribute"}, {"api_name": "b_opcode.k_fade_to", "line_number": 544, "usage_type": "attribute"}, {"api_name": "b_opcode.k_fade_range", "line_number": 545, "usage_type": "attribute"}, {"api_name": "b_opcode.k_cancel_fade", "line_number": 546, "usage_type": "attribute"}, {"api_name": "b_opcode.k_play_movie", "line_number": 547, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_floor_trigger", "line_number": 548, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_ceiling_trigger", "line_number": 549, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_actor_x", "line_number": 551, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_actor_y", "line_number": 552, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_actor_z", "line_number": 553, "usage_type": "attribute"}, {"api_name": "b_opcode.k_sin", "line_number": 554, "usage_type": "attribute"}, {"api_name": "b_opcode.k_cos", "line_number": 555, "usage_type": "attribute"}, {"api_name": "b_opcode.k_vector_angle", "line_number": 556, "usage_type": "attribute"}, {"api_name": "b_opcode.k_check_weapon", "line_number": 557, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_weapon", "line_number": 558, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_marine_weapon", "line_number": 559, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_actor_property", "line_number": 560, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_actor_property", "line_number": 561, "usage_type": "attribute"}, {"api_name": "b_opcode.k_player_number", "line_number": 562, "usage_type": "attribute"}, {"api_name": "b_opcode.k_activator_tid", "line_number": 563, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_marine_sprite", "line_number": 564, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_screen_width", "line_number": 565, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_screen_height", "line_number": 566, "usage_type": "attribute"}, {"api_name": "b_opcode.k_thing_projectile2", "line_number": 567, "usage_type": "attribute"}, {"api_name": "b_opcode.k_strlen", "line_number": 568, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_hud_size", "line_number": 569, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_cvar", "line_number": 570, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_result_value", "line_number": 571, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_line_row_offset", "line_number": 572, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_actor_floor_z", "line_number": 573, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_actor_angle", "line_number": 574, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_sector_floor_z", "line_number": 575, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_sector_ceiling_z", "line_number": 576, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_sigil_pieces", "line_number": 578, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_level_info", "line_number": 579, "usage_type": "attribute"}, {"api_name": "b_opcode.k_change_sky", "line_number": 580, "usage_type": "attribute"}, {"api_name": "b_opcode.k_player_in_game", "line_number": 581, "usage_type": "attribute"}, {"api_name": "b_opcode.k_player_is_bot", "line_number": 582, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_camera_to_texture", "line_number": 583, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_ammo_capacity", "line_number": 585, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_ammo_capacity", "line_number": 586, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_actor_angle", "line_number": 587, "usage_type": "attribute"}, {"api_name": "b_opcode.k_spawn_projectile", "line_number": 588, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_sector_light_level", "line_number": 589, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_actor_ceiling_z", "line_number": 591, "usage_type": "attribute"}, {"api_name": "b_opcode.k_clear_actor_inventory", "line_number": 592, "usage_type": "attribute"}, {"api_name": "b_opcode.k_give_actor_inventory", "line_number": 594, "usage_type": "attribute"}, {"api_name": "b_opcode.k_take_actor_inventory", "line_number": 596, "usage_type": "attribute"}, {"api_name": "b_opcode.k_check_actor_inventory", "line_number": 598, "usage_type": "attribute"}, {"api_name": "b_opcode.k_thing_count_name", "line_number": 600, "usage_type": "attribute"}, {"api_name": "b_opcode.k_spawn_spot_facing", "line_number": 601, "usage_type": "attribute"}, {"api_name": "b_opcode.k_player_class", "line_number": 602, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_player_info", "line_number": 603, "usage_type": "attribute"}, {"api_name": "b_opcode.k_change_level", "line_number": 604, "usage_type": "attribute"}, {"api_name": "b_opcode.k_sector_damage", "line_number": 605, "usage_type": "attribute"}, {"api_name": "b_opcode.k_replace_textures", "line_number": 606, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_actor_pitch", "line_number": 607, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_actor_pitch", "line_number": 608, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_actor_state", "line_number": 609, "usage_type": "attribute"}, {"api_name": "b_opcode.k_thing_damage2", "line_number": 610, "usage_type": "attribute"}, {"api_name": "b_opcode.k_use_inventory", "line_number": 611, "usage_type": "attribute"}, {"api_name": "b_opcode.k_use_actor_inventory", "line_number": 612, "usage_type": "attribute"}, {"api_name": "b_opcode.k_check_actor_ceiling_texture", "line_number": 615, "usage_type": "attribute"}, {"api_name": "b_opcode.k_check_actor_floor_texture", "line_number": 617, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_actor_light_level", "line_number": 618, "usage_type": "attribute"}, {"api_name": "b_opcode.k_set_mugshot_state", "line_number": 620, "usage_type": "attribute"}, {"api_name": "b_opcode.k_thing_count_sector", "line_number": 621, "usage_type": "attribute"}, {"api_name": "b_opcode.k_thing_count_name_sector", "line_number": 622, "usage_type": "attribute"}, {"api_name": "b_opcode.k_check_player_camera", "line_number": 624, "usage_type": "attribute"}, {"api_name": "b_opcode.k_morph_actor", "line_number": 626, "usage_type": "attribute"}, {"api_name": "b_opcode.k_unmorph_actor", "line_number": 627, "usage_type": "attribute"}, {"api_name": "b_opcode.k_get_player_input", "line_number": 628, "usage_type": "attribute"}, {"api_name": "b_opcode.k_classify_actor", "line_number": 629, "usage_type": "attribute"}, {"api_name": "common.func_t", "line_number": 632, "usage_type": "call"}, {"api_name": "common.FUNC_DED", "line_number": 633, "usage_type": "attribute"}, {"api_name": "b_opcode.k_end_print", "line_number": 645, "usage_type": "attribute"}, {"api_name": "b_opcode.k_end_print_bold", "line_number": 646, "usage_type": "attribute"}, {"api_name": "b_opcode.k_end_hud_message", "line_number": 647, "usage_type": "attribute"}, {"api_name": "b_opcode.k_end_hud_message_bold", "line_number": 648, "usage_type": "attribute"}, {"api_name": "b_opcode.k_end_log", "line_number": 649, "usage_type": "attribute"}, {"api_name": "b_opcode.k_save_string", "line_number": 650, "usage_type": "attribute"}, {"api_name": "common.func_t", "line_number": 653, "usage_type": "call"}, {"api_name": "common.FUNC_FORMAT", "line_number": 654, "usage_type": "attribute"}]} +{"seq_id": "2622303921", "text": "import pickle\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport easygui as e\n\n\n# exports a single scan as a txt file\ndef print_to_file(name, mat):\n y = []\n path = \"C://Users//David//PycharmProjects//CalKit//exports\"\n filename = (name + \"_export.txt\")\n fullpath = os.path.join(path, filename)\n file = open(fullpath, \"w+\")\n # delimiter is set to space, this could be changed later\n file.writelines(\"labels\" + \", \" + name + \"\\n\")\n # generates the data for the file\n end = int(mat.x_end)\n start = int(mat.x_start)\n step = int(mat.step)\n steps = int((end - start) / step) + 1\n x = np.linspace(start, end, num=steps)\n for i in range(len(mat.spline)):\n spl = mat.spline[i]\n y.append(spl(x))\n # prints the data in procedurally\n for i in range(len(x)):\n file.write(str(x[i]) + \",\")\n for j in range(len(y)):\n temp = str(y[j][i])\n file.write(temp + \",\")\n file.write(\"\\n\")\n\n\n# saves to the .pkl file, functions via append\ndef save_file(library, ck, name):\n # adds kit to library\n if type(name) != str:\n ck.name = name.get()\n library.library = ck\n ck.print() # for testing\n dump_ck_list(library) # calls the library to dump to the pickle file\n for i in library.get_ck_list(): # testing function to validate what was printed\n i.print()\n\n\n# dumps the library to the .pkl\ndef dump_ck_list(self):\n with open(\"cklib.pkl\", \"wb\") as openfile:\n pickle.dump(self.library, openfile)\n\n\ndef plot_ck(mat, plt):\n if len(mat.spline) != 0:\n plt.clear()\n for i in range(len(mat.spline)):\n x = []\n y = []\n date = \"no date loaded\"\n if mat.date is not None:\n date = mat.date\n text_title = str(\"scan created date: \" + str(date))\n end = int(mat.x_end)\n start = int(mat.x_start)\n step = mat.step\n steps = int((end - start) / step) # determines the number of data-points\n x = np.linspace(mat.x_start, mat.x_end,\n num=steps) # extrapolates the X axis based on the start, stop and number of data-points\n try:\n spl = mat.spline[i]\n y = spl(x) # gets the Y axis data\n plt.set(xlabel=\"Wavelength, nm\", ylabel=\"Intensity, a.u.\", title=text_title)\n plt.plot(x, y) # plots it\n except TypeError:\n error_message(\"This calibration kit does not have a scan of the selected type stored\")\n plt.grid()\n else:\n error_message(\"This calibration kit does not have a scan of the selected type stored\")\n\n\ndef error_message(text):\n e.msgbox(text)\n\n\ndef plot_scans(scans):\n for scan in scans:\n plt.plot(scan[0][0], scan[0][1], label=scan[1])\n plt.legend()\n plt.show()\n", "repo_name": "dGakamsky/CalKit", "sub_path": "outputer.py", "file_name": "outputer.py", "file_ext": "py", "file_size_in_byte": 2882, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.path.join", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "numpy.linspace", "line_number": 22, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.clear", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.set", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "easygui.msgbox", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 87, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 88, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 89, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 89, "usage_type": "name"}]} +{"seq_id": "4060743827", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 7 14:28:12 2020\n\n@author: MAYANK\n\"\"\"\nimport pandas as pd\nimport mysql.connector\nimport datetime\nfrom datetime import timedelta\nfrom sklearn.linear_model import LinearRegression\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\ndatabase = mysql.connector.connect(host=\"localhost\", database=\"medical\", \n passwd=\"test\", user = 'root')\n\ndb = database.cursor()\nwhile True:\n db.execute(\"select max(s_no) from bill\")\n s_no = db.fetchall()\n print(s_no)\n while True:\n database = mysql.connector.connect(host=\"localhost\", database=\"medical\", \n passwd=\"test\", user = 'root')\n db = database.cursor()\n time.sleep(2)\n db = database.cursor()\n db.execute(\"select max(s_no) from bill\")\n s_no_temp = db.fetchall()\n print(s_no_temp)\n if(s_no_temp != s_no):\n break\n \n db.execute(\"select medicine_name,category from bill where bill_no = \"+\n \"(select bill_no from bill where s_no = (select max(s_no) from bill))\")\n data = db.fetchall()\n print(data, \"This is data\")\n print(len(data))\n regressor = LinearRegression()\n \n while len(data)>0:\n print(\"here\")\n nameandcategory = data.pop()\n med_name, category = nameandcategory[0], nameandcategory[1]\n startdate= datetime.date.today() + timedelta(days=-60)\n \n db.execute(\"select sum(bill_quantity),date from bill where medicine_name='\"\n +med_name+\"'and category='\"+category+\"' and date>='\"\n +str(startdate)+\"' group by date \")\n \n \n df = pd.DataFrame(db.fetchall())\n print(df)\n if(df.empty): continue\n parsedate = startdate\n while parsedate<=datetime.date.today():\n if parsedate not in df[1].values:\n df=df.append({0:0, 1:parsedate}, ignore_index=True)\n parsedate += timedelta(days=1)\n \n df=df.sort_values(1)\n \n samples = [10, 7, 3]\n need = []\n while len(samples)>0:\n \n df3=df[df[1]>datetime.date.today()+timedelta(days=-samples.pop())]\n \n regressor.fit(pd.to_datetime(df3[1]).values.reshape(-1,1), df3[0])\n \n today = datetime.date.today()\n upcoming_dates = pd.to_datetime(np.asarray([today, today+timedelta(days=1), \n today+timedelta(days=2),\n today+timedelta(days=3), \n today+timedelta(days=4), \n today+timedelta(days=5), \n today+timedelta(days=6), \n today+timedelta(days=7),\n today+timedelta(days=8),\n today+timedelta(days=9),\n today+timedelta(days=10)]))\n \n \n upcoming_dates_prediction = regressor.predict(upcoming_dates.values.astype(float).reshape(-1,1))\n plt.figure(figsize=(10,6))\n plt.plot(df3[1], df3[0], color='red')\n \n \n plt.plot(df3[1], regressor.predict(pd.to_datetime(df3[1]).values.astype(float).reshape(-1,1))) \n plt.plot(upcoming_dates, upcoming_dates_prediction)\n plt.xticks(df3[1], rotation=\"70\")\n \n \n upcoming_dates_prediction = [max(x,0) for x in upcoming_dates_prediction]\n \n need.append(sum(upcoming_dates_prediction))\n print(max(need), \" need\")\n \n db.execute(\"Select sum(total_quantity) from medicine where name = '\"+\n med_name+\"' and category='\"+category+\"'\") \n quantity_left = db.fetchall()[0][0]\n print(quantity_left)\n if(quantity_left 0 and self.solvent is None:\n nextdir = \"tddft\"\n self.calc_all_excited_states(namelist,prevdir,nextdir,self.wrapper.excitations,\n self.calc_params,self.nroots,charges=self.charges)\n # Vibrational frequency calculations, if requested and no higher\n # level of theory will follow later\n if self.vibrations and self.solvent is None:\n nextdir = \"freq\"\n self.calc_vib_freq(namelist,prevdir,nextdir,self.wrapper.freq,self.calc_params,charges=self.charges)\n # Solvated calculations\n if self.solvent is not None:\n nextdir = \"is_opt_\"+self.solvstr(self.solvent)\n if self.vibrations:\n driver_tol = 'tight'\n # Geometry Optimisation\n self.geom_opt_all(namelist,prevdir,nextdir,self.wrapper.geom_opt,\n self.calc_params,driver_tol,solvent=self.solvent,\n charges=self.charges)\n prevdir = nextdir\n # TDDFT calculations\n if self.nroots > 0:\n nextdir = \"is_tddft_\"+self.solvstr(self.solvent)\n self.calc_all_excited_states(namelist,prevdir,nextdir,self.wrapper.excitations,\n self.calc_params,nroots=self.nroots,\n solvent=self.solvent,charges=self.charges,\n plot_homo=self.plot_homo,plot_lumo=self.plot_lumo,\n plot_trans_den=self.plot_trans_den)\n # Vibrational frequency calculations, if requested\n if self.vibrations:\n nextdir = \"is_freq_\"+self.solvstr(self.solvent)\n self.calc_vib_freq(namelist,prevdir,nextdir,self.wrapper.freq,\n self.calc_params,solvent=self.solvent,\n charges=self.charges)\n\n from os import makedirs, path\n\n # Download xyz files if they do not already exist\n def get_xyz_files(self,namelist,out_path):\n \"\"\"\n Downloads initial geometries from the NCI's webserver cactus, based on their IUPAC names.\n\n These geometries are usually not great, but are a reasonable starting point for optimisation.\n\n Visit https://cactus.nci.nih.gov/chemical/structure to see what works and check your names before use.\n\n Uses ``wget``, so if the machine you are using does not have access to this command,\n this routine will fail, in which case put starting point geometries in the directory\n 'xyz'.\n\n namelist: dict\n Keys are shortnames (eg \"cate\"), entries are full names (eg \"catechol\" or \"1,2-dihydroxybenzene\")\n out_path: str\n String for directory name where xyz files will be written (eg \"xyz\"). Created if not present\n \"\"\"\n from os import path, makedirs\n import subprocess\n\n # Download sdf file from cactus.nci.nih.gov\n if not path.exists(out_path):\n makedirs(out_path)\n for seed in namelist:\n # TODO: use urllib here\n wget_str = (\"wget -O \\\"\"+out_path+\"/\" + seed + \".xyz\\\" \" +\n \"\\\"https://cactus.nci.nih.gov/chemical/structure/\" + \n namelist[seed] + \"/file?format=xyz\\\"\")\n if not path.exists(out_path+\"/\"+seed+\".xyz\"):\n print(wget_str)\n errorcode = subprocess.call(wget_str, shell=True)\n if errorcode:\n raise RuntimeError('{} returned an error: {}'\n .format('wget', errorcode))\n else:\n print(\"Skipping download: \"+out_path+\"/\"+seed+\".xyz already exists\")\n\n # strip out long names and convert to list\n shortnames = [x for x in namelist]\n return shortnames\n\n from os import path, makedirs, getcwd, chdir\n from ase.io import read, write\n\n def solvstr(self,solvent):\n if isinstance(solvent,str):\n return solvent\n if isinstance(solvent,dict):\n return solvent['solvent']\n\n # Optimize geometries of solute selection\n def geom_opt_all(self,solute_names,in_path,out_path,geom_opt_func,calc_params,\n driver_tol='default',solvent=None,charges={}):\n \"\"\"\n Geometry optimise all of a list of solutes\n\n solute_names: list of str\n Short names of the solutes to be optimised\n in_path: str\n Directory where .xyz files are expected to be found. Any not present are skipped.\n out_path: str\n Directory where optimised structure .xyz files are written. Created if not present.\n geom_opt_func: function\n A function wrapping creation of an ASE calculator and using it to perform geometry optimisation.\n calc_params: dict\n Contents varies between different wrappers, but generally specifies basis, functional etc\n driver_tol: str\n Geometry optimisation tolerance level (eg in NWChem)\n target: int\n Excited state index, or None for ground state\n solvent: str\n Implicit solvent name, or None for gas-phase\n charges: dict\n Keys are strings corresponding to some or all of the entries in solute names, entries are net charges on each molecule\n \"\"\"\n from ase.io import read, write\n from os import path, makedirs, getcwd, chdir\n\n # Make directory for optimised structures\n if not path.exists(out_path):\n makedirs(out_path)\n sol_str = ''\n target = calc_params['target']\n if solvent is not None:\n sol_str = f'in {self.solvstr(solvent)} solvent '\n\n for seed in solute_names:\n if target is not None and target!=0:\n baseseed = seed\n seed = seed+\"_es\"+str(target)\n if seed in charges:\n charge = charges[seed]\n else:\n charge = 0\n infile = in_path+\"/\"+seed+\".xyz\"\n outfile = out_path+\"/\"+seed+\".xyz\"\n if not path.exists(infile):\n # Try basename without _esX\n if target is not None and target !=0:\n infile = in_path+\"/\"+baseseed+\".xyz\"\n if not path.exists(infile):\n print(f'Skipping geometry optimisation {sol_str}'+\n f' for: {seed} - no input file')\n continue\n solute_opt = read(infile)\n if path.exists(outfile):\n print(f'Skipping geometry optimisation {sol_str}'+\n f' for: {seed} - output file already present')\n continue\n print(f'Geometry optimization {sol_str}for: {seed}')\n label = seed\n origdir = getcwd()\n wdir = f'geom/{seed}'\n if not path.exists(wdir):\n makedirs(wdir)\n chdir(wdir)\n if solvent is not None:\n label = label+\"_\"+self.solvstr(solvent)\n try:\n geom_opt_func(solute_opt,label,calc_params,driver_tol,solvent,charge)\n except KeyboardInterrupt:\n raise Exception('Keyboard Interrupt')\n except SyntaxError:\n raise Exception('Syntax Error')\n\n chdir(origdir)\n print('Writing to ',outfile)\n if '' in solute_opt.info:\n del solute_opt.info['']\n write(outfile,solute_opt)\n\n # Attempt to find best rotamer for each solute\n\n def find_best_rotas(self,solute_names,in_path,out_path,singlepoint_func,\n geom_opt_func,calc_params,solvent=None,charges={}):\n \"\"\"\n Finds the lowest energy rotamer for each of a list of solutes.\n Proceeds by identifying -OH groups attached to C-C units, and tries 'flipping' the dihedral, then optimising\n the resulting geometry if it within a certain tolerance of the original energy. If any lower energy structure\n is found, this will be returned instead of the original one.\n\n solute_names: list of str\n Short names of the solutes to be tested\n in_path: str\n Directory where .xyz files are expected to be found. Any not present are skipped.\n out_path: str\n Directory where best rotamer structure .xyz files are written. Created if not present.\n singlepoint_func: function\n A function wrapping creation of an ASE calculator and using it to perform a singlepoint calculation.\n geom_opt_func: function\n A function wrapping creation of an ASE calculator and using it to perform geometry optimisation.\n calc_params: dict\n Contents varies between different wrappers, but generally specifies basis, functional etc\n solvent: str\n Implicit solvent name, or None for gas-phase\n charges: dict\n Keys are strings corresponding to some or all of the entries in solute names, entries are net charges on each molecule\n \"\"\"\n from os import path, makedirs\n from ase.io import read, write\n\n # Hard-coded logic for what constitutes a rotatable bond\n # Works OK for -OH groups in organic compounds but will need editing\n # for anything else. Assumes anything within 1.5A is a bond.\n rota_elem = ['H','O','C','C']\n rota_max_dist = [1.5,1.5,1.5]\n rota_dih_range = 40\n rota_opt_thresh = 0.2\n\n # Make directory for optimised structures\n if not path.exists(out_path):\n makedirs(out_path)\n target = calc_params['target']\n\n for seed in solute_names:\n if seed in charges:\n charge = charges[seed]\n else:\n charge = 0\n if target is not None and target!=0:\n seed = seed+\"_es\"+str(target)\n outfile = out_path+'/'+seed+'.xyz'\n infile = in_path+\"/\"+seed+\".xyz\"\n if not path.exists(infile):\n print('Skipping Rotamer Search for: ',seed,\n ' - input structure not found')\n continue\n if path.exists(outfile):\n print('Skipping Rotamer Search for: ',seed,\n ' - output file already present')\n continue\n\n print('Finding best rotamer for: ',seed)\n sol_opt = read(infile)\n # Load defaults from module\n elem = rota_elem\n max_dist = rota_max_dist\n dih_range = rota_dih_range\n opt_thresh = rota_opt_thresh\n nrot = 0\n ijkl = []\n sym = sol_opt.get_chemical_symbols()\n for i in range(len(sol_opt)):\n if sym[i]==elem[0]:\n for j in range(len(sol_opt)):\n if sym[j]==elem[1] and sol_opt.get_distance(i,j) < max_dist[0]:\n for k in range(len(sol_opt)):\n if sym[k]==elem[2] and sol_opt.get_distance(j,k) < max_dist[1]:\n for l in range(len(sol_opt)):\n if l!=k and sym[l]==elem[3] and sol_opt.get_distance(k,l) < max_dist[2]:\n dih = sol_opt.get_dihedral(l,k,j,i)\n if dih>180-dih_range and dih<180+dih_range:\n ijkl.append([i,j,k,l])\n nrot = nrot + 1\n break\n if nrot==0:\n print('No rotatable OH bonds found')\n if '' in sol_opt.info:\n del sol_opt.info['']\n write(outfile,sol_opt)\n else:\n print(nrot, 'rotatable bonds found, generating all',2**nrot,\n 'rotamers')\n origdir = getcwd()\n wdir = f'{out_path}/{seed}'\n if not path.exists(wdir):\n makedirs(wdir)\n chdir(wdir)\n flip = [0 for i in range(len(ijkl))]\n sol_opt_rota = []\n energy_rota = []\n for rota in range(2**len(ijkl)):\n sol_opt_rota.append(sol_opt.copy())\n flip = [(rota&(2**(len(ijkl)-i-1)))>>(len(ijkl)-i-1) for i in range(len(ijkl))]\n for oH in range(len(ijkl)):\n i = ijkl[oH][0]; j = ijkl[oH][1]; k = ijkl[oH][2]; l = ijkl[oH][3];\n if flip[oH]:\n sol_opt_rota[rota].set_dihedral(l,k,j,i,0)\n label = 'rota'+repr(rota).zfill(3)\n driver_tol = 'loose'\n opt = 0\n try:\n energy,_ = singlepoint_func(sol_opt_rota[rota],label,calc_params,charge)\n if rota==0:\n energy_rota.append(energy)\n if rota>0:\n if energy pivot]\n quick_compare_count += len(greater)\n return quick_sort(less) + [pivot] + quick_sort(greater)\n\n\ndef QuickSort(l): # 封装一下排序和输出性能指标\n global quick_compare_count\n quick_compare_count = 0 # 重置全局变量\n result = quick_sort(l)\n return quick_compare_count\n\n\n##归并排序\nmerge_compare_count = 0\n\n\ndef merge(li, low, mid, high):\n global merge_compare_count\n # 列表,最开始的值,中间值(第一个有序列表的最后一位),最后面的值\n\n # 将两个有序列表的开头标记出来\n i = low\n j = mid + 1 # 第二段有序数列的开头\n list_1 = []\n while i <= mid and j <= high: # 限制条件(开头小于结尾)两边都有数\n merge_compare_count+=1\n if li[i] < li[j]:\n list_1.append(li[i])\n i += 1\n else:\n list_1.append(li[j])\n j += 1\n # while执行完成,,肯定有一部分没数了\n while i <= mid: # 左列表还有数\n list_1.append(li[i])\n i += 1\n while j <= high: # 右列表还有数\n list_1.append(li[j])\n j += 1\n # 再将list_1里的数放回li中\n li[low:high + 1] = list_1\n\n\ndef merge_sort(li, low, high):\n global merge_compare_count\n # 终止条件 只有一个元素\n if low < high: # 至少有两个,递归终止条件(只剩一个的时候)\n mid = (low + high) // 2 # 二分查找中间值\n merge_sort(li, low, mid) # 递归左边,左边排序\n\n merge_sort(li, mid + 1, high) # 递归右边,右边排序\n\n merge(li, low, mid, high)\n\n\n\ndef MergeSort(l=list):\n global merge_compare_count\n merge_compare_count = 0\n result = merge_sort(l,0,len(l)-1)\n return merge_compare_count\n\n\n\n##图像绘制\nx_axis_data = [10, 100, 1000, 2000, 5000, 10000]\ny_axis_data1 = [BubbleSort(l1), BubbleSort(l2), BubbleSort(l3), BubbleSort(l4), BubbleSort(l5), BubbleSort(l6)]\ny_axis_data2 = [MergeSort(l1), MergeSort(l2), MergeSort(l3), MergeSort(l4), MergeSort(l5), MergeSort(l6)]\ny_axis_data3 = [QuickSort(l1), QuickSort(l2), QuickSort(l3), QuickSort(l4), QuickSort(l5), QuickSort(l6)]\n\n# 画图\nplt.plot(x_axis_data, y_axis_data1, 'b*--', alpha=0.5, linewidth=1, label='BubbleSort')\nplt.plot(x_axis_data, y_axis_data2, 'rs--', alpha=0.5, linewidth=1, label='MergeSort')\nplt.plot(x_axis_data, y_axis_data3, 'go--', alpha=0.5, linewidth=1, label='QuickSort')\n\nplt.legend() # 显示上面的label\nplt.xlabel('Data Size')\nplt.ylabel('Number of Comparisons')\n\n# plt.ylim(-1,1)#仅设置y轴坐标范围\nplt.show()\n", "repo_name": "weixing18/Homework", "sub_path": "分治算法实验/Code.py", "file_name": "Code.py", "file_ext": "py", "file_size_in_byte": 3539, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sys.setrecursionlimit", "line_number": 5, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 8, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 9, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 10, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 11, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 12, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 13, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 112, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 112, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 113, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 117, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 117, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 118, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 121, "usage_type": "name"}]} +{"seq_id": "34292757989", "text": "# _*_coding:utf-8_*_\nimport json\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.views.generic.base import View\nfrom .models import Course,Lesson,Video\nfrom organization.models import CourseOrg\nfrom pure_pagination import Paginator, EmptyPage, PageNotAnInteger\nfrom operation.models import UserFavorite,CourseComment,UserCourse\nfrom utils.mixin_untils import LoginRequiredMixin\n# Create your views here.\n\n\nclass CourseList(View):\n def get(self,request):\n\n all_course = Course.objects.all()\n hot_course = all_course.order_by('-click_nums')[:5]\n # 按照最新,最热门,参与人数来排序,\n sort = request.GET.get('sort','')\n if sort:\n if sort == 'new':\n all_course = all_course.order_by('-add_time')\n if sort == 'hot':\n all_course = all_course.order_by('-click_nums')\n if sort == 'students':\n all_course = all_course.order_by('-students')\n\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n p = Paginator(all_course,3)\n course = p.page(page)\n return render(request,'course-list.html',\n {'all_course':course,\n 'hot_course':hot_course,\n })\n\n\nclass CourseDetail(View):\n def get(self,request,course_id):\n coursedetail = Course.objects.get(id=int(course_id))\n coursedetail.click_nums += 1\n coursedetail.save()\n lesson = coursedetail.lesson_set.all()\n # 获取对应id的机构对象\n org = CourseOrg.objects.get(id = int(course_id))\n # 机构老师对象\n org_teacher = org.teacher_set.all()\n #机构教师数量\n org_teacher_num = org_teacher.count()\n # 课程标签,用于做相关推荐\n tag = coursedetail.tag\n if tag:\n # 这是要展示的对象,标签和浏览的课程相同的话就会被推荐,这个可以自己在后台定义\n relate_course = Course.objects.filter(tag=tag)[:1]\n else:\n # 因为定了初始值是空,这里不设置空的就是空列表的话,html如果接收到空字符串,无法进行遍历\n relate_course = []\n # 课程收藏功能\n has_fav_c = False\n has_fav_o = False\n if request.user.is_authenticated():\n if UserFavorite.objects.filter(user=request.user, fav_id=coursedetail.id, fav_type=1):\n has_fav_c = True\n if UserFavorite.objects.filter(user=request.user, fav_id=coursedetail.courseorg.id, fav_type=2):\n has_fav_o = True\n return render(request,'course-detail.html',\n {'course_detail':coursedetail,\n 'lesson':lesson,\n 'org':org,\n 'org_teacher_num':org_teacher_num,\n 'relate_course':relate_course,\n 'has_fav_c': has_fav_c,\n 'has_fav_o': has_fav_o,\n })\n\n# 具体课程章节视频详情\n# @login_required\nclass CourseVideo(LoginRequiredMixin,View):\n def get(self,request,course_id):\n # 对应id课程的章节对象\n course_video = Course.objects.get(id=int(course_id))\n course_video.students += 1\n course_video.save()\n\n course_lesson = course_video.lesson_set.all()\n # 资源下载对象\n courseresource = course_video.courseresource_set.all()\n\n #查询用户是否关联了该课程\n user_course2 = UserCourse.objects.filter(user=request.user,course=course_video)\n if not user_course2:\n user_course3 = UserCourse(user=request.user,course=course_video)\n user_course3.save()\n # 筛选出用户的所有课程\n user_courses = UserCourse.objects.filter(course=course_video)\n # 用列表式取出遍历出所有学习用户的id\n user_ids = [user_course.user.id for user_course in user_courses]\n #获取所有课程\n all_user_courses = UserCourse.objects.filter(user_id__in=user_ids)\n # 取出所有课程id\n course_ids = [all_user_course.course.id for all_user_course in all_user_courses]\n # 获取学过该用户学过的其他课程\n relate_courses = Course.objects.filter(id__in=course_ids).order_by('-click_nums')[:5]\n return render(request,'course-video.html',\n {'course_video':course_video,\n 'course_lesson':course_lesson,\n 'courseresource':courseresource,\n 'relate_courses':relate_courses,\n })\n\n# 课程评论区2\nclass CourseComment2(LoginRequiredMixin,View):\n def get(self,request,course_id):\n course_comment = Course.objects.get(id=int(course_id))\n courseresource = course_comment.courseresource_set.all()\n comments = course_comment.coursecomment_set.all()\n return render(request,'course-comment.html',\n {'course_comment':course_comment,\n 'courseresource':courseresource,\n 'comments': comments,\n })\n\n# 添加评论功能2\nclass AddComment(View):\n def post(self,request):\n # 先监测是否登录\n if not request.user.is_authenticated():\n return HttpResponse(json.dumps({'status':'fail','msg':'用户未登录'}),content_type='application/json')\n\n course_id = request.POST.get('course_id',0)\n comments = request.POST.get('comments','')\n\n # 如果id和评论存在获取到了,把各项内容插入到数据库中\n if int(course_id) >0 and comments:\n course_comments = CourseComment()\n # 课程必须是对应id\n course = Course.objects.get(id=int(course_id))\n course_comments.course = course\n course_comments.comments = comments\n course_comments.user = request.user\n course_comments.save()\n return HttpResponse(json.dumps({'status':'success','msg':'发表评论成功'}),content_type='application/json')\n else:\n return HttpResponse(json.dumps({'status':'fail','msg':'评论失败'}),content_type='application/json')\n\n\nclass Video2(View):\n # 视频播放页面\n def get(self, request, video_id):\n # 对应id课程的章节对象\n video = Video.objects.get(id=int(video_id))\n course_video = video.lesson.course\n course_video.students += 1\n course_video.save()\n\n course_lesson = course_video.lesson_set.all()\n # 资源下载对象\n courseresource = course_video.courseresource_set.all()\n\n # 查询用户是否关联了该课程\n user_course2 = UserCourse.objects.filter(user=request.user, course=course_video)\n if not user_course2:\n user_course3 = UserCourse(user=request.user, course=course_video)\n user_course3.save()\n # 筛选出用户的所有课程\n user_courses = UserCourse.objects.filter(course=course_video)\n # 用列表式取出遍历出所有学习用户的id\n user_ids = [user_course.user.id for user_course in user_courses]\n # 获取所有课程\n all_user_courses = UserCourse.objects.filter(user_id__in=user_ids)\n # 取出所有课程id\n course_ids = [all_user_course.course.id for all_user_course in all_user_courses]\n # 获取学过该用户学过的其他课程\n relate_courses = Course.objects.filter(id__in=course_ids).order_by('-click_nums')[:5]\n return render(request, 'course-play.html',\n {'course_video': course_video,\n 'course_lesson': course_lesson,\n 'courseresource': courseresource,\n 'relate_courses': relate_courses,\n 'video' : course_video,\n 'videoplay': video,\n })\n\n\n", "repo_name": "wnbaed/selfproject", "sub_path": "MxOnline/apps/courses/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 8055, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.views.generic.base.View", "line_number": 15, "usage_type": "name"}, {"api_name": "models.Course.objects.all", "line_number": 18, "usage_type": "call"}, {"api_name": "models.Course.objects", "line_number": 18, "usage_type": "attribute"}, {"api_name": "models.Course", "line_number": 18, "usage_type": "name"}, {"api_name": "pure_pagination.PageNotAnInteger", "line_number": 32, "usage_type": "name"}, {"api_name": "pure_pagination.Paginator", "line_number": 34, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 36, "usage_type": "call"}, {"api_name": "django.views.generic.base.View", "line_number": 42, "usage_type": "name"}, {"api_name": "models.Course.objects.get", "line_number": 44, "usage_type": "call"}, {"api_name": "models.Course.objects", "line_number": 44, "usage_type": "attribute"}, {"api_name": "models.Course", "line_number": 44, "usage_type": "name"}, {"api_name": "organization.models.CourseOrg.objects.get", "line_number": 49, "usage_type": "call"}, {"api_name": "organization.models.CourseOrg.objects", "line_number": 49, "usage_type": "attribute"}, {"api_name": "organization.models.CourseOrg", "line_number": 49, "usage_type": "name"}, {"api_name": "models.Course.objects.filter", "line_number": 58, "usage_type": "call"}, {"api_name": "models.Course.objects", "line_number": 58, "usage_type": "attribute"}, {"api_name": "models.Course", "line_number": 58, "usage_type": "name"}, {"api_name": "operation.models.UserFavorite.objects.filter", "line_number": 66, "usage_type": "call"}, {"api_name": "operation.models.UserFavorite.objects", "line_number": 66, "usage_type": "attribute"}, {"api_name": "operation.models.UserFavorite", "line_number": 66, "usage_type": "name"}, {"api_name": "operation.models.UserFavorite.objects.filter", "line_number": 68, "usage_type": "call"}, {"api_name": "operation.models.UserFavorite.objects", "line_number": 68, "usage_type": "attribute"}, {"api_name": "operation.models.UserFavorite", "line_number": 68, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 70, "usage_type": "call"}, {"api_name": "utils.mixin_untils.LoginRequiredMixin", "line_number": 82, "usage_type": "name"}, {"api_name": "django.views.generic.base.View", "line_number": 82, "usage_type": "name"}, {"api_name": "models.Course.objects.get", "line_number": 85, "usage_type": "call"}, {"api_name": "models.Course.objects", "line_number": 85, "usage_type": "attribute"}, {"api_name": "models.Course", "line_number": 85, "usage_type": "name"}, {"api_name": "operation.models.UserCourse.objects.filter", "line_number": 94, "usage_type": "call"}, {"api_name": "operation.models.UserCourse.objects", "line_number": 94, "usage_type": "attribute"}, {"api_name": "operation.models.UserCourse", "line_number": 94, "usage_type": "name"}, {"api_name": "operation.models.UserCourse", "line_number": 96, "usage_type": "call"}, {"api_name": "operation.models.UserCourse.objects.filter", "line_number": 99, "usage_type": "call"}, {"api_name": "operation.models.UserCourse.objects", "line_number": 99, "usage_type": "attribute"}, {"api_name": "operation.models.UserCourse", "line_number": 99, "usage_type": "name"}, {"api_name": "operation.models.UserCourse.objects.filter", "line_number": 103, "usage_type": "call"}, {"api_name": "operation.models.UserCourse.objects", "line_number": 103, "usage_type": "attribute"}, {"api_name": "operation.models.UserCourse", "line_number": 103, "usage_type": "name"}, {"api_name": "models.Course.objects.filter", "line_number": 107, "usage_type": "call"}, {"api_name": "models.Course.objects", "line_number": 107, "usage_type": "attribute"}, {"api_name": "models.Course", "line_number": 107, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 108, "usage_type": "call"}, {"api_name": "utils.mixin_untils.LoginRequiredMixin", "line_number": 116, "usage_type": "name"}, {"api_name": "django.views.generic.base.View", "line_number": 116, "usage_type": "name"}, {"api_name": "models.Course.objects.get", "line_number": 118, "usage_type": "call"}, {"api_name": "models.Course.objects", "line_number": 118, "usage_type": "attribute"}, {"api_name": "models.Course", "line_number": 118, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 121, "usage_type": "call"}, {"api_name": "django.views.generic.base.View", "line_number": 128, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 132, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 132, "usage_type": "call"}, {"api_name": "operation.models.CourseComment", "line_number": 139, "usage_type": "call"}, {"api_name": "models.Course.objects.get", "line_number": 141, "usage_type": "call"}, {"api_name": "models.Course.objects", "line_number": 141, "usage_type": "attribute"}, {"api_name": "models.Course", "line_number": 141, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 146, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 146, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 148, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 148, "usage_type": "call"}, {"api_name": "django.views.generic.base.View", "line_number": 151, "usage_type": "name"}, {"api_name": "models.Video.objects.get", "line_number": 155, "usage_type": "call"}, {"api_name": "models.Video.objects", "line_number": 155, "usage_type": "attribute"}, {"api_name": "models.Video", "line_number": 155, "usage_type": "name"}, {"api_name": "operation.models.UserCourse.objects.filter", "line_number": 165, "usage_type": "call"}, {"api_name": "operation.models.UserCourse.objects", "line_number": 165, "usage_type": "attribute"}, {"api_name": "operation.models.UserCourse", "line_number": 165, "usage_type": "name"}, {"api_name": "operation.models.UserCourse", "line_number": 167, "usage_type": "call"}, {"api_name": "operation.models.UserCourse.objects.filter", "line_number": 170, "usage_type": "call"}, {"api_name": "operation.models.UserCourse.objects", "line_number": 170, "usage_type": "attribute"}, {"api_name": "operation.models.UserCourse", "line_number": 170, "usage_type": "name"}, {"api_name": "operation.models.UserCourse.objects.filter", "line_number": 174, "usage_type": "call"}, {"api_name": "operation.models.UserCourse.objects", "line_number": 174, "usage_type": "attribute"}, {"api_name": "operation.models.UserCourse", "line_number": 174, "usage_type": "name"}, {"api_name": "models.Course.objects.filter", "line_number": 178, "usage_type": "call"}, {"api_name": "models.Course.objects", "line_number": 178, "usage_type": "attribute"}, {"api_name": "models.Course", "line_number": 178, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 179, "usage_type": "call"}]} +{"seq_id": "25118929842", "text": "import mongomock\nfrom datetime import datetime\nfrom aggregation_builder import AggregationQueryBuilder\nfrom aggregation_builder.operators import *\nimport unittest\n\n\ndef ISODate(str):\n return datetime.strptime(str, '%Y-%m-%dT%H:%M:%SZ')\n\n\nclass QueryDictTests(unittest.TestCase):\n def test_limit(self):\n query = [\n {\n '$limit': 5\n }\n ]\n generated_query = AggregationQueryBuilder().limit(5).get_query()\n\n self.assertListEqual(generated_query, query)\n\n def test_skip(self):\n query = [\n {\n '$skip': 5\n }\n ]\n generated_query = AggregationQueryBuilder().skip(5).get_query()\n\n self.assertListEqual(generated_query, query)\n\n def test_project(self):\n query = [{'$project': {'title': 1, 'author': 1}}]\n generated_query = AggregationQueryBuilder().project(title=1, author=1).get_query()\n\n self.assertListEqual(generated_query, query)\n\n def test_project_computed_fields(self):\n query = [\n {\n '$project': {\n 'title': 1,\n 'isbn': {\n 'prefix': {'$substr': [\"$isbn\", 0, 3]},\n 'group': {'$substr': [\"$isbn\", 3, 2]},\n 'publisher': {'$substr': [\"$isbn\", 5, 4]},\n 'title': {'$substr': [\"$isbn\", 9, 3]},\n 'checkDigit': {'$substr': [\"$isbn\", 12, 1]}\n },\n 'lastName': \"$author.last\",\n 'copiesSold': \"$copies\"\n }\n }\n ]\n generated_query = AggregationQueryBuilder().project(\n title=1,\n isbn=dict(\n prefix=SUB_STR(\"$isbn\", 0, 3),\n group=SUB_STR(\"$isbn\", 3, 2),\n publisher=SUB_STR(\"$isbn\", 5, 4),\n title=SUB_STR(\"$isbn\", 9, 3),\n checkDigit=SUB_STR(\"$isbn\", 12, 1)\n ),\n lastName=\"$author.last\",\n copiesSold=\"$copies\"\n\n ).get_query()\n\n self.assertListEqual(generated_query, query)\n\n def test_match(self):\n query = [\n {\n '$match': {'author': \"dave\"}\n }\n ]\n generated_query = AggregationQueryBuilder().match(\n author=\"dave\"\n ).get_query()\n\n self.assertListEqual(generated_query, query)\n\n def test_match_count(self):\n query = [\n {'$match': {'$or': [{'$gt': [\"$score\", 70]}, {'$gte': [\"$views\", 1000]}]}},\n {'$group': {'_id': None, 'count': {'$sum': 1}}}\n ]\n generated_query = AggregationQueryBuilder().match(\n OR(GT('$score', 70), GTE('$views', 1000))\n ).group(id=None, count=SUM(1)).get_query()\n\n self.assertListEqual(generated_query, query)\n\n def test_unwind(self):\n query = [{'$unwind': \"$sizes\"}]\n generated_query = AggregationQueryBuilder().unwind(\n \"$sizes\"\n ).get_query()\n\n self.assertListEqual(generated_query, query)\n\n def test_unwind_with_params(self):\n query = [{'$unwind': \"$sizes\", 'preserveNullAndEmptyArrays': True, 'includeArrayIndex': \"arrayIndex\"}]\n generated_query = AggregationQueryBuilder().unwind(\n path=\"$sizes\",\n include_array_index=\"arrayIndex\",\n preserve_null_and_empty_arrays=True\n ).get_query()\n\n self.assertListEqual(generated_query, query)\n\n def test_sort(self):\n query = [\n {'$sort': {'age': -1, 'posts': 1}}\n ]\n generated_query = AggregationQueryBuilder().sort(age=-1, posts=1).get_query()\n\n self.assertListEqual(generated_query, query)\n\n def test_sort_metadata(self):\n query = [\n {'$match': {'$text': {'$search': \"operating\"}}},\n {'$sort': {'score': {'$meta': \"textScore\"}, 'posts': -1}}\n ]\n generated_query = AggregationQueryBuilder().match(\n TEXT_SEARCH(\"operating\")\n ).sort(\n score=TEXT_META,\n posts=-1\n ).get_query()\n self.assertListEqual(generated_query, query)\n\n def test_sample(self):\n query = [{'$sample': {'size': 3}}]\n generated_query = AggregationQueryBuilder().sample(size=3).get_query()\n self.assertListEqual(generated_query, query)\n\n def test_lookup(self):\n query = [\n {\n '$lookup':\n {\n 'from': \"inventory\",\n 'localField': \"item\",\n 'foreignField': \"sku\",\n 'as': \"inventory_docs\"\n }\n }\n ]\n\n generated_query = AggregationQueryBuilder().look_up(\n _from='inventory',\n _localField='item',\n _foreignField='sku',\n _as='inventory_docs'\n ).get_query()\n\n self.assertListEqual(generated_query, query)\n\n def test_lookup_with_array(self):\n query = [\n {\n '$unwind': \"$specs\"\n },\n {\n '$lookup':\n {\n 'from': \"inventory\",\n 'localField': \"specs\",\n 'foreignField': \"size\",\n 'as': \"inventory_docs\"\n }\n },\n {\n '$match': {\"inventory_docs\": {'$ne': []}}\n }\n ]\n\n generated_query = AggregationQueryBuilder().unwind(\n \"$specs\"\n ).look_up(\n _from='inventory',\n _localField='specs',\n _foreignField='size',\n _as='inventory_docs'\n ).match(\n inventory_docs=NE()\n ).get_query()\n\n self.assertListEqual(generated_query, query)\n\n def test_graph_look_up(self):\n query = [\n {\n '$graphLookup': {\n 'from': \"employees\",\n 'startWith': \"$reportsTo\",\n 'connectFromField': \"reportsTo\",\n 'connectToField': \"name\",\n 'as': \"reportingHierarchy\"\n }\n }\n ]\n generated_query = AggregationQueryBuilder().graph_look_up(\n _from='employees',\n _startWith=\"$reportsTo\",\n _connectFromField=\"reportsTo\",\n _connectToField=\"name\",\n _as=\"reportingHierarchy\"\n ).get_query()\n\n self.assertListEqual(generated_query, query)\n\n def test_add_fields(self):\n query = [\n {\n '$addFields': {\n 'totalHomework': {'$sum': \"$homework\"},\n 'totalQuiz': {'$sum': \"$quiz\"}\n }\n },\n {\n '$addFields': {'totalScore':\n {'$add': [\"$totalHomework\", \"$totalQuiz\", \"$extraCredit\"]}}\n }\n ]\n generated_query = AggregationQueryBuilder().add_fields(\n totalHomework=SUM(\"$homework\"),\n totalQuiz=SUM(\"$quiz\")\n ).add_fields(\n totalScore=ADD(\"$totalHomework\", \"$totalQuiz\", \"$extraCredit\")\n ).get_query()\n\n self.assertListEqual(generated_query, query)\n\n def test_group(self):\n query = [\n {\n '$group': {\n '_id': {'month': {'$month': \"$date\"}, 'day': {'$dayOfMonth': \"$date\"}, 'year': {'$year': \"$date\"}},\n 'totalPrice': {'$sum': {'$multiply': [\"$price\", \"$quantity\"]}},\n 'averageQuantity': {'$avg': \"$quantity\"},\n 'count': {'$sum': 1}\n }\n }\n ]\n\n generated_query = AggregationQueryBuilder().group(\n id=dict(\n month=MONTH(\"$date\"),\n day=DAY_OF_MONTH(\"$date\"),\n year=YEAR(\"$date\")\n ),\n totalPrice=SUM(MULTIPLY(\"$price\", \"$quantity\")),\n averageQuantity=AVG(\"$quantity\"),\n count=SUM(1)\n ).get_query()\n\n self.assertListEqual(generated_query, query)\n\n def test_null_group(self):\n query = [\n {\n '$group': {\n '_id': None,\n 'totalPrice': {'$sum': {'$multiply': [\"$price\", \"$quantity\"]}},\n 'averageQuantity': {'$avg': \"$quantity\"},\n 'count': {'$sum': 1}\n }\n }\n ]\n\n generated_query = AggregationQueryBuilder().group(\n id=None,\n totalPrice=SUM(MULTIPLY(\"$price\", \"$quantity\")),\n averageQuantity=AVG(\"$quantity\"),\n count=SUM(1)\n ).get_query()\n\n self.assertListEqual(generated_query, query)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "repo_name": "MosesSymeonidis/aggregation_builder", "sub_path": "tests/query_builder.py", "file_name": "query_builder.py", "file_ext": "py", "file_size_in_byte": 8823, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "25", "api": [{"api_name": "datetime.datetime.strptime", "line_number": 9, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 9, "usage_type": "name"}, {"api_name": "unittest.TestCase", "line_number": 12, "usage_type": "attribute"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 19, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 29, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 35, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 56, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 78, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 89, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 97, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 105, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 117, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 126, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 136, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 152, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 180, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 205, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 228, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 249, "usage_type": "call"}, {"api_name": "aggregation_builder.AggregationQueryBuilder", "line_number": 274, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 285, "usage_type": "call"}]} +{"seq_id": "12622774415", "text": "from chess.figures.figure import Figure\n\n\nclass Pawn(Figure):\n def __init__(self, *args, **kwargs):\n super(Pawn, self).__init__(*args, **kwargs)\n self.mega_step = False\n\n def check_move(self, cell_to):\n from_x, from_y = self.cell.coordinate\n to_x, to_y = cell_to.coordinate\n\n if from_x == to_x and from_y == to_y - 1:\n return True\n\n if from_x == to_x and from_y == to_y - 2 and from_y == 2:\n return True\n\n if (from_x == to_x + 1 or from_x == to_x - 1) and from_y == to_y - 1 and \\\n cell_to.figure and cell_to.figure.user != self.user:\n return True\n\n return False\n", "repo_name": "MykhailoKlimchuk/chess_prototype", "sub_path": "figures/pawn.py", "file_name": "pawn.py", "file_ext": "py", "file_size_in_byte": 669, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "chess.figures.figure.Figure", "line_number": 4, "usage_type": "name"}]} +{"seq_id": "28676150964", "text": "import urlopen\nimport requests \nfrom bs4 import BeautifulSoup\n\nimport csv\nimport pandas as pd\n\nimport regex as re\n\ncomplete_data, invalid_data = [], []\n\n\ndef preprocess_text(text):\n \n text = re.sub(r'[^0-9a-zA-Z]', ' ', text)\n text = re.sub(r'_', ' ', text)\n return \" \" .join(text.split())\n \n\ndef get_contents(data):\n \n modify_data = {}\n\n for name, url in data.items(): \n\n # Read the homepage of the teacher \n try:\n html = requests.get(url)\n html.raise_for_status()\n modify_data = {} \n soup = BeautifulSoup(html.text, 'html.parser')\n \n # Get phone number / email\n get_info, personal_info = ['Email', 'email'], []\n for string in soup.body.strings:\n if 'Email' in string or 'email' in string:\n personal_info.append(string.strip())\n \n # Save only relevant content for the teacher\n text_data = [preprocess_text(string) for string in soup.body.strings if preprocess_text(string)!='']\n text_data = ' '.join(text_data)\n\n # Add the data to a dict\n modify_data['name'] = name\n modify_data['personal_info'] = personal_info\n modify_data['content'] = text_data \n complete_data.append(modify_data)\n\n except:\n invalid_data.append((name, url))\n\n text_file = open(\"data/error_file.txt\",\"w\")\n for val in invalid_data:\n text_file.write(str(val) + \"\\n\")\n\n text_file = open(\"data/output.txt\",\"w\")\n text_file.write(str({'complete_data':complete_data}))\n\n\ndef main_csv():\n # Read csv file \n csv_file = pd.read_csv('data/csv_data/csrankings.csv') # ['name', 'affiliation', 'homepage', 'scholarid']\n data = dict(zip(csv_file.name, csv_file.homepage))\n \n # Use a sample size\n test_size = 20\n test_data = dict(list(data.items())[:test_size])\n #print(test_data)\n\n get_contents(test_data)\n\n", "repo_name": "AkashNagaraj/Teacher_search", "sub_path": "read_csv.py", "file_name": "read_csv.py", "file_ext": "py", "file_size_in_byte": 1918, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "regex.sub", "line_number": 15, "usage_type": "call"}, {"api_name": "regex.sub", "line_number": 16, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 28, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 31, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 62, "usage_type": "call"}]} +{"seq_id": "18390941441", "text": "import pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier,export_graphviz\nfrom sklearn import metrics\nfrom sklearn.cross_validation import cross_val_score\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ntrainX = pd.read_csv('P1_data/trainX.csv',header=None)\ntrainY = pd.read_csv('P1_data/trainY.csv',header=None)\n\ntestX = pd.read_csv('P1_data/testX.csv',header=None)\ntestY = pd.read_csv('P1_data/testY.csv',header=None)\n\n\nprint('Shape of training dataset '+ str(trainX.shape))\nprint('Shape of training label dataset '+ str(trainY.shape))\nprint('Shape of test dataset '+ str(testX.shape))\n\n\ndef MSE(predicted,Y):\n s=0\n for i in range(len(predicted)):\n s+=(predicted[i]-Y[i])**2\n s=s/len(predicted)\n return s\ndepth = []\nmaxnodes = list(range(10,101,10))\nvalidationX = trainX[0:int(0.3*len(trainX))]\nvalidationY = trainY[0:int(0.3*len(trainY))]\nvalidationY = validationY.values.tolist()\n\ntrainnewX = trainX[int(0.3*len(trainX)):]\ntrainnewY = trainY[int(0.3*len(trainY)):]\nfor i in range(3,10):\n clf = DecisionTreeClassifier(max_depth=i)\n# Perform 7-fold cross validation \n clf.fit(trainnewX,trainnewY)\n predicted = clf.predict(validationX)\n depth.append(MSE(predicted,validationY))\n# print(depth)\n\n\nmaxdepth = list(range(3,10))\n\nplt.plot(maxdepth,depth)\nplt.xlabel('Hyperparameter Maxdepth')\nplt.ylabel('Mean Sqaure Error of 10cv(MSE)')\nplt.title('Calculating Maxdepth hyperparameter with Least MSE ')\nprint('Hence, maxdepth is 7')\t\n\ndepth = []\nmaxnodes = list(range(10,101,10))\nfor i in maxnodes:\n clf = DecisionTreeClassifier(max_depth=7,max_leaf_nodes=i)\n# Perform 7-fold cross validation \n clf.fit(trainnewX,trainnewY)\n predicted = clf.predict(validationX)\n depth.append(MSE(predicted,validationY))\n# print(depth)\t\n\nmaxdepth = list(range(3,10))\n\nplt.plot(maxnodes,depth)\nplt.xlabel('Hyperparameter Maxdepth')\nplt.ylabel('Mean Sqaure Error of 10cv(MSE)')\nplt.title('Calculating Maxdepth hyperparameter with Least MSE ')\nprint('Hence, max_leaf_nodes are 90')\n\nmodel = DecisionTreeClassifier(max_depth=7,max_leaf_nodes=80)\nmodel.fit(trainX,trainY)\nprint(model)\t\n\nprint(' Classification Report')\npredicted = model.predict(testX)\nprint(metrics.classification_report(testY,predicted))\nprint('Confusion Matrix')\nprint(metrics.confusion_matrix(testY,predicted))\n\nprint('(b)Total no of nodes')\nprint(model.tree_.node_count)\n\nn_nodes = model.tree_.node_count\nchildren_left = model.tree_.children_left\nchildren_right = model.tree_.children_right\nfeature = model.tree_.feature\nthreshold = model.tree_.threshold\n\nnode_depth = np.zeros(shape=n_nodes, dtype=np.int64)\nis_leaves = np.zeros(shape=n_nodes, dtype=bool)\nstack = [(0, -1)] # seed is the root node id and its parent depth\nwhile len(stack) > 0:\n node_id, parent_depth = stack.pop()\n node_depth[node_id] = parent_depth + 1\n\n # If we have a test node\n if (children_left[node_id] != children_right[node_id]):\n stack.append((children_left[node_id], parent_depth + 1))\n stack.append((children_right[node_id], parent_depth + 1))\n else:\n is_leaves[node_id] = True\nprint('(c)Total Number of leaf nodes')\nprint(sum(is_leaves))\n\nfrom graphviz import Source\nfrom IPython.display import SVG\ngraph = Source(export_graphviz(model, out_file=None, feature_names=trainX.columns))\nSVG(graph.pipe(format='svg'))\n\ndef accuracy(predicted,trainY):\n s=0\n for i in range(len(trainY)):\n #print(predicted[i],trainY[i])\n if(predicted[i] == trainY[i]):\n s+=1\n return float(s)/float(len(trainY))\n\n\ntraininacc = []\ntestacc = []\ndatasetsize = list(range(1,11))\nfor i in range(1,11):\n trainnewX = trainX[0:int(i*0.1*len(trainX))]\n trainnewY = trainY[0:int(i*0.1*len(trainX))]\n model = DecisionTreeClassifier()\n model.fit(trainnewX,trainnewY)\n trainnewY = trainnewY.values.tolist()\n\n predicted = model.predict(trainnewX)\n\n traininacc.append(accuracy(predicted,trainnewY))\n predicted = model.predict(testX)\n testnewY = testY.values.tolist()\n testacc.append(accuracy(predicted,testnewY))\n\n\nplt.plot(datasetsize,traininacc)\nplt.plot(datasetsize,testacc)\nplt.xlabel('Dataset Size')\nplt.ylabel('Training/Test Accuracy')\nplt.title('Accuracy vs Dataset S')\n", "repo_name": "lavishm58/Decision-Tree-Classifier-And-Regression", "sub_path": "P1/P1.py", "file_name": "P1.py", "file_ext": "py", "file_size_in_byte": 4290, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "warnings.filterwarnings", "line_number": 8, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 10, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 11, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 13, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 14, "usage_type": "call"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 48, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 71, "usage_type": "call"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 77, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 77, "usage_type": "name"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 79, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 79, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.int64", "line_number": 90, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 91, "usage_type": "call"}, {"api_name": "graphviz.Source", "line_number": 108, "usage_type": "call"}, {"api_name": "sklearn.tree.export_graphviz", "line_number": 108, "usage_type": "call"}, {"api_name": "IPython.display.SVG", "line_number": 109, "usage_type": "call"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 138, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 138, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 139, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 139, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 140, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 140, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 141, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 141, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 142, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 142, "usage_type": "name"}]} +{"seq_id": "3577458269", "text": "# coding:utf-8\nimport requests, re\nfrom bs4 import BeautifulSoup\nimport lxml,sys,io,json\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030')\n\nwith open(r'C:\\Users\\Jhon117\\Desktop\\demo\\爬虫实战.sb.txt','w',encoding='utf-8')as F:\n for i in range(1,2):\n print('**********')\n url = 'http://search.chinahr.com/sh/job/pn' + str(i) + '/?key=python'\n r = requests.get(url)\n r.raise_for_status()\n r.encoding = r.apparent_encoding\n s = r.text\n bs = BeautifulSoup(s,'html.parser')\n tes = bs.find_all(name='div', attrs={'class':'jobList pc_search_listclick'})\n for t in tes:\n tname = t.find(name='li', attrs={'class': 'job-name'})\n tmp = t.find(name='li', attrs={'class': 'job-salary'})\n tc = t.find(name='li', attrs={'class': 'job-company'})\n tt = t.find_all(name='span')\n print(tname.get_text())\n F.write(json.dumps(tname.get_text(), ensure_ascii=False) + '\\n')\n print(tmp.get_text())\n F.write(json.dumps(tmp.get_text(), ensure_ascii=False) + '\\n')\n print(tc.get_text())\n F.write(json.dumps(tc.get_text(), ensure_ascii=False) + '\\n')\n for n in tt[1:]:\n print(n.get_text(), end=' ')\n F.write(json.dumps(n.get_text(), ensure_ascii=False) + '\\n')\n print('')\n print('********')\n\n\n", "repo_name": "YYN117/Demo", "sub_path": "爬虫实战/练习/职位.py", "file_name": "职位.py", "file_ext": "py", "file_size_in_byte": 1425, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sys.stdout", "line_number": 5, "usage_type": "attribute"}, {"api_name": "io.TextIOWrapper", "line_number": 5, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 11, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 15, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 23, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 25, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 27, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 30, "usage_type": "call"}]} +{"seq_id": "72510577984", "text": "\"\"\"\nCorrects costs in produce sales spreadsheet.\n\"\"\"\nfrom os.path import dirname\nfrom openpyxl import load_workbook\n\n\ndef wrapper():\n \"\"\"\n The produce types and their updated prices\n Loop through the rows and update the prices\n skip the first row\n \"\"\"\n path = dirname(__file__) + \"\\\\\"\n wbook = load_workbook(f\"{path}produce_sales.xlsx\")\n sheet = wbook[\"Sheet\"]\n price_updates = {\"Garlic\": 3.07, \"Celery\": 1.19, \"Lemon\": 1.27}\n for row_num in range(2, sheet.max_row):\n produce_name = sheet.cell(row=row_num, column=1).value\n if produce_name in price_updates:\n sheet.cell(row=row_num, column=2).value = price_updates[produce_name]\n wbook.save(f\"{path}updated_produce_sales.xlsx\")\n\n\nif __name__ == \"__main__\":\n wrapper()\n", "repo_name": "jgyy/py-automate", "sub_path": "13/update_produce.py", "file_name": "update_produce.py", "file_ext": "py", "file_size_in_byte": 779, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.path.dirname", "line_number": 14, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 15, "usage_type": "call"}]} +{"seq_id": "34690826948", "text": "from __future__ import print_function, division\n\nimport os\nimport sys\nimport shlex\nimport subprocess\n\nimport dirhash\n\nimport pytest\n\n\nconsole_script = os.path.join(\n os.path.dirname(sys.executable),\n 'dirhash'\n)\n\n\ndef dirhash_run(argstring, add_env=None):\n assert os.path.isfile(console_script)\n assert os.access(console_script, os.X_OK)\n if add_env:\n env = os.environ.copy()\n env.update(add_env)\n else:\n env = None\n process = subprocess.Popen(\n [console_script] + shlex.split(argstring),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n env=env\n )\n output, error = process.communicate()\n\n # in python3 output and error are `bytes` as opposed to `str` in python2\n if isinstance(output, bytes):\n output = output.decode('utf-8')\n if isinstance(error, bytes):\n error = error.decode('utf-8')\n\n return output, error, process.returncode\n\n\ndef create_default_tree(tmpdir):\n \"\"\"\n tmpdir/\n |__.dir/\n | |__file\n |__.file\n |__dir/\n | |__file\n |__empty/\n |__file\n |__file.ext1\n |__file.ext2\n \"\"\"\n dotdir = tmpdir.mkdir('.dir')\n dotdir.join('file').write('file in hidden sub-directory')\n tmpdir.join(\".file\").write('hidden file')\n dir = tmpdir.mkdir('dir')\n dir.join('file').write('file in sub-directory')\n tmpdir.mkdir('empty')\n tmpdir.join(\"file\").write('file')\n tmpdir.join(\"file.ext1\").write('file with extension .ext1')\n tmpdir.join(\"file.ext2\").write('file with extension .ext2')\n\n\nclass TestCLI(object):\n @pytest.mark.parametrize(\n 'argstring, non_default_kwargs',\n [\n (\n '. -a md5',\n {}\n ),\n (\n '.. -a md5',\n {'directory': '..'}\n ),\n (\n 'target-dir -a md5',\n {'directory': 'target-dir'}\n ),\n (\n '. -a sha256',\n {'algorithm': 'sha256'}\n ),\n # Filtering options\n (\n '. -a md5 -m \"*\" \"!.*\"',\n {'match': ['*', '!.*']}\n ),\n (\n '. -a md5 --match \"d1/*\" \"d2/*\" --ignore \"*.txt\"',\n {'match': ['d1/*', 'd2/*'], 'ignore': ['*.txt']}\n ),\n (\n '. -a md5 --empty-dirs',\n {'empty_dirs': True}\n ),\n (\n '. -a md5 --no-linked-dirs',\n {'linked_dirs': False}\n ),\n (\n '. -a md5 --no-linked-files',\n {'linked_files': False}\n ),\n # Protocol options\n (\n '. -a md5 --allow-cyclic-links',\n {'allow_cyclic_links': True}\n\n ),\n (\n '. -a md5 --properties name',\n {'entry_properties': ['name']}\n\n ),\n (\n '. -a md5 --properties name data',\n {'entry_properties': ['name', 'data']}\n\n ),\n # Implementation\n (\n '. -a md5 -j 10',\n {'jobs': 10}\n ),\n (\n '. -a md5 -s 32000',\n {'chunk_size': 32000}\n ),\n ]\n )\n def test_get_kwargs(self, argstring, non_default_kwargs):\n from dirhash.cli import get_kwargs\n kwargs_expected = {\n 'list': False,\n 'directory': '.',\n 'algorithm': 'md5',\n 'match': ['*'],\n 'ignore': None,\n 'empty_dirs': False,\n 'linked_dirs': True,\n 'linked_files': True,\n 'entry_properties': ['data', 'name'],\n 'allow_cyclic_links': False,\n 'chunk_size': 2 ** 20,\n 'jobs': 1\n }\n kwargs_expected.update(non_default_kwargs)\n kwargs = get_kwargs(shlex.split(argstring))\n assert kwargs == kwargs_expected\n\n @pytest.mark.parametrize(\n 'description, argstrings, output',\n [\n ('ARGS WITHOUT EFFECT WHEN LISTING',\n ['. -l',\n '. --list',\n '. -a md5 --list',\n '. -a sha256 --list',\n '. --properties name --list',\n '. --jobs 2 --list',\n '. --chunk-size 2 --list'],\n ('.dir/file\\n'\n '.file\\n'\n 'dir/file\\n'\n 'file\\n'\n 'file.ext1\\n'\n 'file.ext2\\n')),\n ('IGNORE EXTENSION',\n ['. -i \"*.ext1\" --list',\n '. --ignore \"*.ext1\" --list',\n '. -m \"*\" \"!*.ext1\" --list',\n '. --match \"*\" \"!*.ext1\" --list'],\n ('.dir/file\\n'\n '.file\\n'\n 'dir/file\\n'\n 'file\\n'\n 'file.ext2\\n')),\n ('IGNORE MULTIPLE EXTENSIONS',\n ['. -i \"*.ext1\" \"*.ext2\" --list',\n '. -i \"*.ext*\" --list'],\n ('.dir/file\\n'\n '.file\\n'\n 'dir/file\\n'\n 'file\\n')),\n ('IGNORE HIDDEN',\n ['. -i \".*\" \".*/\" --list'],\n ('dir/file\\n'\n 'file\\n'\n 'file.ext1\\n'\n 'file.ext2\\n')),\n ('INCLUDE EMPTY',\n ['. --empty-dirs --list'],\n ('.dir/file\\n'\n '.file\\n'\n 'dir/file\\n'\n 'empty/.\\n'\n 'file\\n'\n 'file.ext1\\n'\n 'file.ext2\\n')),\n ]\n )\n def test_list(self, description, argstrings, output, tmpdir):\n create_default_tree(tmpdir)\n with tmpdir.as_cwd():\n for argstring in argstrings:\n o, error, returncode = dirhash_run(argstring)\n assert returncode == 0\n assert error == ''\n assert o == output\n\n @pytest.mark.parametrize(\n 'argstring, kwargs, expected_hashes',\n [\n ('. -a md5',\n {'algorithm': 'md5'},\n ['594c48dde0776b03eddeeb0232190be7',\n 'd8ab965636d48e407b73b9dbba4cb928',\n '050e7bc9ffcb09c15186c04e0f8026df']\n ),\n ('. -a sha256',\n {'algorithm': 'sha256'},\n ['23a04964149889e932ba3348fe22442f4f6a3b3fec616a386a70579ee857ab7b',\n '7b76bac43e963f9561f37b96b92d7a174094bff230c6efbf1d8bf650e8b40b7a',\n '7156da2b2e5a2926eb4b72e65f389343cb6aca0578f0aedcd6f7457abd67d8f5']),\n ]\n )\n def test_hash_result(self, argstring, kwargs, expected_hashes, tmpdir):\n # verify same result from cmdline and library + regression test of actual\n # hashes\n create_default_tree(tmpdir)\n with tmpdir.as_cwd():\n for add_argstring, add_kwargs, expected_hash in zip(\n ['', ' -p data', ' -p name'],\n [\n {},\n {'entry_properties': ['data']},\n {'entry_properties': ['name']},\n ],\n expected_hashes\n ):\n # run CLI\n full_argstring = argstring + add_argstring\n cli_out, error, returncode = dirhash_run(full_argstring)\n assert error == ''\n assert returncode == 0\n assert cli_out[-1] == '\\n'\n cli_hash = cli_out[:-1]\n\n # run CLI multiproc\n full_argstring_mp = argstring + add_argstring + ' --jobs 2'\n cli_out_mp, error_mp, returncode_mp = dirhash_run(full_argstring_mp)\n assert error_mp == ''\n assert returncode_mp == 0\n assert cli_out_mp[-1] == '\\n'\n cli_hash_mp = cli_out_mp[:-1]\n\n # run lib function\n full_kwargs = kwargs.copy()\n full_kwargs.update(add_kwargs)\n lib_hash = dirhash.dirhash(str(tmpdir), **full_kwargs)\n\n assert cli_hash == cli_hash_mp == lib_hash == expected_hash\n\n def test_error_bad_argument(self, tmpdir):\n with tmpdir.as_cwd():\n o, error, returncode = dirhash_run('. --chunk-size not_an_int')\n assert returncode > 0\n assert error != ''\n", "repo_name": "andhus/dirhash-python", "sub_path": "tests/test_cli.py", "file_name": "test_cli.py", "file_ext": "py", "file_size_in_byte": 8290, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 35, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.path.join", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "sys.executable", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "os.access", "line_number": 21, "usage_type": "call"}, {"api_name": "os.X_OK", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.environ.copy", "line_number": 23, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 23, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 27, "usage_type": "call"}, {"api_name": "shlex.split", "line_number": 28, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 29, "usage_type": "attribute"}, {"api_name": "subprocess.PIPE", "line_number": 30, "usage_type": "attribute"}, {"api_name": "dirhash.cli.get_kwargs", "line_number": 153, "usage_type": "call"}, {"api_name": "shlex.split", "line_number": 153, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 69, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 69, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 156, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 156, "usage_type": "attribute"}, {"api_name": "dirhash.dirhash", "line_number": 265, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 216, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 216, "usage_type": "attribute"}]} +{"seq_id": "41361531981", "text": "import socket\nimport threading\nimport json\nimport numpy as np\nfrom naive_serial import Naive_serial\nfrom Constant import CommandEnum\nfrom Constant import EventEnum\nfrom Constant import frame_kind\nfrom Constant import Head\nfrom Constant import Status\n\nclass Gateway:\n \"\"\"\n 网关类\n \"\"\"\n\n def __init__(self):\n \"\"\"\n 构造\n \"\"\"\n self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.__chat_connections = {}\n self.__gobang_connections = {}\n self.__nicknames = {}\n self.totol_connect_num = 0\n self.black_player = None\n self.white_player = None\n self.qizi = np.zeros((15,15),dtype=np.int)\n self.naive_serial = Naive_serial()\n self.naive_serial.run()\n\n def __user_thread(self, user_id):\n \"\"\"\n 用户子线程\n :param user_id: 用户id\n \"\"\"\n connection = self.__chat_connections[user_id]\n nickname = self.__nicknames[user_id]\n print('[Server] 用户', user_id, nickname, '加入聊天室')\n #self.__broadcast(message='用户 ' + str(nickname) + '(' + str(user_id) + ')' + '加入聊天室')\n\n # 侦听\n while True: \n # noinspection PyBroadException\n try:\n buffer = connection.recv(1024).decode()\n # 解析成json数据\n obj = json.loads(buffer)\n # 如果是广播指令\n if obj['type'] == 'broadcast':\n #self.__broadcast(obj['sender_id'], obj['message'])\n self.broadcastToPotato(obj['sender_id'],obj['message'])\n elif obj['type'] == 'logout':\n self.logoutToPotato(user_id)\n\n\n break\n else:\n print('[Server] 无法解析json数据包:', connection.getsockname(), connection.fileno())\n except Exception:\n print('[Server] 连接失效:', connection.getsockname(), connection.fileno())\n #self.__chat_connections[user_id].close()\n self.__chat_connections.pop(user_id)\n self.__nicknames.pop(user_id)\n break\n\n def __gobang_thread(self, user_id, identity): \n \"\"\"\n gobang子线程\n :param user_id: 用户id\n \"\"\"\n connection = self.__gobang_connections[user_id]\n nickname = self.__nicknames[user_id]\n print('[Server] 用户', user_id, nickname, '加入gobang')\n self.__gobang_broadcast(message= identity +'' + str(nickname) + '(' + str(user_id) + ')' + '加入游戏', type=\"info\")\n\n # 侦听\n while True: \n # noinspection PyBroadException\n try:\n buffer = connection.recv(1024).decode()\n # 解析成json数据\n obj = json.loads(buffer)\n # 如果是广播指令\n if obj['type'] == 'xiaqi':\n self.__gobang_broadcast(sender_id=obj['sender_id'], type='xiaqi',identity=obj['identity'], pos=obj['pos'])\n x, y = obj['pos']\n self.qizi[x][y] = 1 if obj['identity']==\"black\" else 2\n winner = self.__check_winner(x,y,self.qizi[x][y])\n if winner:\n winner = 'black' if winner ==1 else 'white'\n message = \"winner is \" + winner\n self.__gobang_broadcast(sender_id=0, type='win',identity=obj['identity'], message=message)\n elif obj['type'] == 'logout':\n print('[Server] 用户', user_id, nickname, '退出游戏')\n if obj['identity'] != \"audience\":\n self.__gobang_broadcast(sender_id=0, type='logout',identity=obj['identity'])\n if identity == 'black':\n self.black_player = None\n if identity == 'white':\n self.white_player = None\n else:\n self.__gobang_broadcast(sender_id=0,message= identity +'' + str(nickname) + '(' + str(user_id) + ')' + '退出观看游戏', type=\"info\")\n\n self.__gobang_connections.pop(user_id)\n self.__nicknames.pop(user_id)\n \n thread = threading.Thread(target=self.__waitForLogin, args=(connection,user_id))\n thread.setDaemon(True)\n thread.start()\n break\n else:\n print('[Server] 无法解析json数据包:', connection.getsockname(), connection.fileno())\n except Exception as e:\n print(e)\n print(e.__traceback__.tb_lineno)\n print('[Server] 连接失效:', connection.getsockname(), connection.fileno())\n #self.__chat_connections[user_id].close()\n self.__gobang_connections.pop(user_id)\n self.__nicknames.pop(user_id)\n break\n\n def __broadcast(self, sender_id=0, message='', type='info',identity='', pos=(0,0)):\n \"\"\"\n 广播\n :param user_id: 用户id(0为系统)\n :param message: 广播内容\n \"\"\"\n for user_id, conection in self.__chat_connections.items():\n if user_id != sender_id and conection:\n conection.send(json.dumps({\n 'sender_id': sender_id,\n 'sender_nickname': self.__nicknames[sender_id],\n 'message': message\n }).encode())\n\n def __check_winner(self, x, y, turn):\n #沿x方向\n cnt = 0\n curx,cury = x,y\n while (0<=curx and curx<15 and 0<=cury and cury<15 and self.qizi[curx][cury]==turn):\n cnt += 1\n curx -= 1\n curx,cury = x,y\n while(0<=curx and curx<15 and 0<=cury and cury<15 and self.qizi[curx][cury]==turn):\n cnt += 1\n curx += 1\n if(cnt>5):\n return turn\n #沿y方向\n cnt=0\n curx,cury = x,y\n while(0<=curx and curx<15 and 0<=cury and cury<15 and self.qizi[curx][cury]==turn) :\n cnt+=1\n cury-=1\n curx,cury = x,y\n while(0<=curx and curx<15 and 0<=cury and cury<15 and self.qizi[curx][cury]==turn) :\n cnt+=1\n cury+=1\n if(cnt>5):\n return turn\n #沿右上方向\n cnt=0\n curx,cury = x,y\n while (0<=curx and curx<15 and 0<=cury and cury<15 and self.qizi[curx][cury]==turn) :\n cnt+=1\n curx+=1\n cury-=1\n curx,cury = x,y\n while (0<=curx and curx<15 and 0<=cury and cury<15 and self.qizi[curx][cury]==turn) :\n cnt+=1\n curx-=1\n cury+=1\n if(cnt>5):\n return turn\n #沿左上方向\n cnt=0\n curx,cury = x,y\n while(0<=curx and curx<15 and 0<=cury and cury<15 and self.qizi[curx][cury]==turn) :\n cnt+=1\n curx-=1\n cury-=1\n curx,cury = x,y\n while(0<=curx and curx<15 and 0<=cury and cury<15 and self.qizi[curx][cury]==turn):\n cnt+=1\n curx+=1\n cury+=1\n if (cnt>5):\n return turn\n return 0 # 没赢\n\n def __gobang_broadcast(self, sender_id=0, message='', type='info',identity='', pos=(0,0)):\n \"\"\"\n 广播\n :param user_id: 用户id(0为系统)\n :param message: 广播内容\n \"\"\"\n if type == \"info\":\n for user_id, conection in self.__gobang_connections.items():\n if user_id != sender_id and conection:\n conection.send(json.dumps({\n 'sender_id': sender_id,\n 'sender_nickname': self.__nicknames[sender_id],\n 'type': type,\n 'message': message\n }).encode())\n elif type == \"xiaqi\":\n for user_id, conection in self.__gobang_connections.items():\n if user_id != sender_id and conection:\n conection.send(json.dumps({\n 'sender_id': sender_id,\n 'sender_nickname': self.__nicknames[sender_id],\n 'type': type,\n 'identity': identity,\n 'pos': pos\n }).encode())\n elif type == \"logout\": # player logout\n for user_id, conection in self.__gobang_connections.items():\n if user_id != sender_id and conection:\n conection.send(json.dumps({\n 'sender_id': sender_id,\n 'sender_nickname': self.__nicknames[sender_id],\n 'identity': identity,\n 'type': type,\n }).encode())\n elif type == \"win\": # player win\n for user_id, conection in self.__gobang_connections.items():\n if user_id != sender_id and conection:\n conection.send(json.dumps({\n 'sender_id': sender_id,\n 'sender_nickname': self.__nicknames[sender_id],\n 'message': message,\n 'identity': identity,\n 'type': type,\n }).encode())\n \n def __waitForLogin(self, connection, user_id):\n # 尝试接受数据\n # noinspection PyBroadException\n try:\n buffer = connection.recv(1024).decode()\n # 解析成json数据\n obj = json.loads(buffer)\n # 如果是连接指令,那么则返回一个新的用户编号,接收用户连接\n if obj['type'] == 'login':\n self.__chat_connections.update({user_id: connection})\n self.__nicknames.update({user_id: obj['nickname']})\n connection.send(json.dumps({\n 'id': user_id\n }).encode())\n # 给土豆发连接指令\n self.loginToPotato(user_id)\n\n # 开辟一个新的线程\n thread = threading.Thread(target=self.__user_thread, args=(user_id,))\n thread.setDaemon(True)\n thread.start()\n\n elif obj['type'] == 'gobang_login':\n if self.black_player == None:\n identity = \"black\"\n self.black_player = user_id\n elif self.white_player == None:\n identity = \"white\"\n self.white_player = user_id\n else:\n identity = \"audience\"\n self.__gobang_connections.update({user_id: connection})\n self.__nicknames.update({user_id: obj['nickname']})\n connection.send(json.dumps({\n 'id': user_id,\n 'identity': identity\n }).encode())\n # 开辟一个新的线程\n thread = threading.Thread(target=self.__gobang_thread, args=(user_id,identity))\n thread.setDaemon(True)\n thread.start()\n else:\n print('[Server] 无法解析json数据包:', connection.getsockname(), connection.fileno())\n except Exception as e:\n print(e)\n print(e.__traceback__.tb_lineno)\n print('[Server] 无法接受数据:', connection.getsockname(), connection.fileno())\n\n def __uart2tcp(self):\n while True:\n data = self.naive_serial.queue_from_uart.get(block=True)\n datalen = (data[0]<<8)+data[1]-1 # 除掉指令位的长度\n cmd =data[2]\n data = data[3:]\n if cmd == CommandEnum.BROADCAST:\n id = data[0]\n message = data[3:]\n message = message.decode(encoding=\"utf8\")\n connection = self.__chat_connections[id]\n connection.send(json.dumps({\n 'sender_id': id,\n 'sender_nickname': self.__nicknames[id],\n 'message': message\n }).encode())\n\n elif cmd == CommandEnum.LOGOUT:\n id = data[0]\n connection = self.__chat_connections[id]\n print('[Server] 用户', id, '退出聊天室')\n self.__chat_connections.pop(id)\n self.__nicknames.pop(id)\n thread = threading.Thread(target=self.__waitForLogin, args=(connection,id))\n thread.setDaemon(True)\n thread.start()\n \n elif cmd == CommandEnum.PRINT:\n print(data.decode(encoding=\"utf-8\",errors = \"replace\"))\n\n\n ### potato methods begin\n def loginToPotato(self, id):\n a=b'\\x11\\x22\\x33'\n a=bytearray(a)\n datalen = 2\n datalen_high8 = datalen//256\n datalen_low8 = datalen%256\n datalen_checksum = datalen_high8 + datalen_low8\n a.append(datalen_high8)\n a.append(datalen_low8)\n a.append(datalen_checksum)\n checksum = 0\n cmd = CommandEnum.LOGIN\n a.append(cmd)\n checksum += cmd\n a.append(id)\n checksum += id\n a.append(checksum%256)\n self.naive_serial.queue_to_uart.put(a)\n\n def broadcastToPotato(self, sender_id, message):\n # message是str\n a=b'\\x11\\x22\\x33'\n a=bytearray(a)\n messagelen = len(message)\n messagelen_high8 = messagelen//256\n messagelen_low8 = messagelen%256\n datalen = 2 + 2 + messagelen\n datalen_high8 = datalen//256\n datalen_low8 = datalen%256\n datalen_checksum = datalen_high8 + datalen_low8\n a.append(datalen_high8)\n a.append(datalen_low8)\n a.append(datalen_checksum)\n checksum = 0\n cmd = CommandEnum.BROADCAST\n a.append(cmd)\n checksum += cmd\n a.append(sender_id)\n checksum += sender_id\n a.append(messagelen_high8)\n checksum += messagelen_high8\n a.append(messagelen_low8)\n checksum += messagelen_low8\n message_bytes = message.encode(encoding = \"utf8\")\n for byte in message_bytes:\n a.append(byte)\n checksum += byte\n a.append(checksum%256)\n self.naive_serial.queue_to_uart.put(a)\n\n def logoutToPotato(self, id):\n a=b'\\x11\\x22\\x33'\n a=bytearray(a)\n datalen = 2\n datalen_high8 = datalen//256\n datalen_low8 = datalen%256\n datalen_checksum = datalen_high8 + datalen_low8\n a.append(datalen_high8)\n a.append(datalen_low8)\n a.append(datalen_checksum)\n checksum = 0\n cmd = CommandEnum.LOGOUT\n a.append(cmd)\n checksum += cmd\n a.append(id)\n checksum += id\n a.append(checksum%256)\n self.naive_serial.queue_to_uart.put(a)\n\n ### potato methods end\n\n def start(self):\n \"\"\"\n 启动服务器\n \"\"\"\n # 绑定端口\n self.__socket.bind(('127.0.0.1', 12345))\n # 启用监听\n self.__socket.listen(10)\n print('[Server] 服务器正在运行......')\n\n # 清空连接\n self.__chat_connections.clear()\n self.__nicknames.clear()\n\n self.__chat_connections.update({0: None})\n self.__nicknames.update({0: \"System\"})\n self.totol_connect_num += 1\n\n thread = threading.Thread(target=self.__uart2tcp, args=())\n thread.setDaemon(True)\n thread.start()\n\n # 开始侦听\n while True:\n connection, address = self.__socket.accept()\n print('[Server] 收到一个新连接', connection.getsockname(), connection.fileno())\n user_id = self.totol_connect_num \n self.totol_connect_num += 1\n\n thread = threading.Thread(target=self.__waitForLogin, args=(connection,user_id))\n thread.setDaemon(True)\n thread.start()\n\nif __name__ == '__main__':\n gateway = Gateway()\n gateway.start()", "repo_name": "SimonLiu1999/Potatotype", "sub_path": "gateway_python_pc/gateway.py", "file_name": "gateway.py", "file_ext": "py", "file_size_in_byte": 16144, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "socket.socket", "line_number": 21, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 21, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 21, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.int", "line_number": 28, "usage_type": "attribute"}, {"api_name": "naive_serial.Naive_serial", "line_number": 29, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 48, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 83, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 108, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 131, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 201, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 210, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 220, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 229, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 243, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 248, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 255, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 270, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 275, "usage_type": "call"}, {"api_name": "Constant.CommandEnum.BROADCAST", "line_number": 291, "usage_type": "attribute"}, {"api_name": "Constant.CommandEnum", "line_number": 291, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 296, "usage_type": "call"}, {"api_name": "Constant.CommandEnum.LOGOUT", "line_number": 302, "usage_type": "attribute"}, {"api_name": "Constant.CommandEnum", "line_number": 302, "usage_type": "name"}, {"api_name": "threading.Thread", "line_number": 308, "usage_type": "call"}, {"api_name": "Constant.CommandEnum.PRINT", "line_number": 312, "usage_type": "attribute"}, {"api_name": "Constant.CommandEnum", "line_number": 312, "usage_type": "name"}, {"api_name": "Constant.CommandEnum.LOGIN", "line_number": 328, "usage_type": "attribute"}, {"api_name": "Constant.CommandEnum", "line_number": 328, "usage_type": "name"}, {"api_name": "Constant.CommandEnum.BROADCAST", "line_number": 351, "usage_type": "attribute"}, {"api_name": "Constant.CommandEnum", "line_number": 351, "usage_type": "name"}, {"api_name": "Constant.CommandEnum.LOGOUT", "line_number": 378, "usage_type": "attribute"}, {"api_name": "Constant.CommandEnum", "line_number": 378, "usage_type": "name"}, {"api_name": "threading.Thread", "line_number": 406, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 417, "usage_type": "call"}]} +{"seq_id": "71837522945", "text": "from sqlalchemy.orm import DeclarativeBase\nfrom sqlalchemy import String, ForeignKey\nfrom sqlalchemy.orm import Mapped, mapped_column, relationship\n\n\nclass Base(DeclarativeBase):\n pass\n\n\nclass Portfolio(Base):\n __tablename__ = \"portfolios\"\n\n slug: Mapped[str] = mapped_column(String, primary_key=True, unique=True)\n title: Mapped[str]\n html_description_url: Mapped[str]\n image_url: Mapped[str]\n markdown_description_filename: Mapped[str]\n image_filename: Mapped[str]\n\n projects: Mapped[list[\"Project\"]] = relationship()\n\n\nclass Project(Base):\n __tablename__ = \"projects\"\n\n slug: Mapped[str] = mapped_column(String, primary_key=True, unique=True)\n portfolio_slug: Mapped[str] = mapped_column(\n ForeignKey(\"portfolios.slug\", ondelete=\"CASCADE\")\n )\n title: Mapped[str]\n html_description_url: Mapped[str]\n markdown_description_filename: Mapped[str]\n", "repo_name": "Uoyroem/Digit-Alem", "sub_path": "server/app/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 900, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sqlalchemy.orm.DeclarativeBase", "line_number": 6, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Mapped", "line_number": 13, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.mapped_column", "line_number": 13, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 13, "usage_type": "argument"}, {"api_name": "sqlalchemy.orm.Mapped", "line_number": 14, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Mapped", "line_number": 15, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Mapped", "line_number": 16, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Mapped", "line_number": 17, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Mapped", "line_number": 18, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Mapped", "line_number": 20, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.relationship", "line_number": 20, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.Mapped", "line_number": 26, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.mapped_column", "line_number": 26, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 26, "usage_type": "argument"}, {"api_name": "sqlalchemy.orm.Mapped", "line_number": 27, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.mapped_column", "line_number": 27, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 28, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.Mapped", "line_number": 30, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Mapped", "line_number": 31, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Mapped", "line_number": 32, "usage_type": "name"}]} +{"seq_id": "11893633713", "text": "from multiprocessing import Process\nimport os\n\n\ndef target_function() -> None:\n\n\tprint(f'\\niteration {os.getpid()}')\t\n\ndef main() -> None:\n\n\tfor i in range(100):\n\n\t\t# The constructor should always be called with keyword arguments. group \n\t\t# should always be None\n\n\t\tprocess = Process(\n\t\t\ttarget=target_function)\n\n\t\tprocess.start()\n\nif __name__ == '__main__':\n\n\tmain()\n", "repo_name": "software-foundations/learning-distributed-systems", "sub_path": "documentation_multiprocessing/08_reference/01_process_and_exceptions/process_and_exceptions_01.py", "file_name": "process_and_exceptions_01.py", "file_ext": "py", "file_size_in_byte": 369, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.getpid", "line_number": 7, "usage_type": "call"}, {"api_name": "multiprocessing.Process", "line_number": 16, "usage_type": "call"}]} +{"seq_id": "7564683960", "text": "import os\nimport random\nimport bpy\nimport math\nimport numpy as np\nfrom mathutils import Vector, Matrix\nfrom bpy_extras.object_utils import world_to_camera_view\nfrom rd.modify_material import set_modify_material, set_modify_raw_material, set_modify_table_material, set_modify_floor_material\n\n# render parameter \nRENDERING_PATH = os.getcwd()\nLIGHT_EMITTER_ENERGY = 5\nLIGHT_ENV_MAP_ENERGY_IR = 0.035 \nLIGHT_ENV_MAP_ENERGY_RGB = 1.0 \nCYCLES_SAMPLE = 32\nCAMERA_TYPE = \"realsense\"\nNUM_FRAME_PER_SCENE = 24\n\n# view point parameter\nlook_at_shift = np.array([0,0,0])\nnum_point_ver = 6\nnum_point_hor = 4\nbeta_range = (15*math.pi/180, 45*math.pi/180)\nr = 0.5\ntsdf2blender_coord_T_shift = np.array([-0.15, -0.15, -0.0503])\nTABLE_CAD_MODEL_HEIGHT = 0.75\n\n# material randomization mode (transparent, specular, mixed, raw)\nmy_material_randomize_mode = 'mixed'\n\n# set depth sensor parameter\ncamera_width = 640\ncamera_height = 360\nbaseline_distance = 0.055\n\n# set background parameter\nbackground_size = 3.\nbackground_position = (0., 0., 0.)\nbackground_scale = (1., 1., 1.)\n\n\n# set camera randomize paramater\nstart_point_range = ((0.5, 0.95), (-0.6, 0.6, -0.6, 0.6))\nup_range = (-0.18, -0.18, -0.18, 0.18)\nlook_at_range = (background_position[0] - 0.05, background_position[0] + 0.05, \n background_position[1] - 0.05, background_position[1] + 0.05,\n background_position[2] - 0.05, background_position[2] + 0.05)\n\n\ng_syn_light_num_lowbound = 4\ng_syn_light_num_highbound = 6\ng_syn_light_dist_lowbound = 8\ng_syn_light_dist_highbound = 12\ng_syn_light_azimuth_degree_lowbound = 0\ng_syn_light_azimuth_degree_highbound = 360\ng_syn_light_elevation_degree_lowbound = 0\ng_syn_light_elevation_degree_highbound = 90\ng_syn_light_energy_mean = 3\ng_syn_light_energy_std = 0.5\ng_syn_light_environment_energy_lowbound = 0\ng_syn_light_environment_energy_highbound = 1\n\n\ng_shape_synset_name_pairs_all = {'02691156': 'aeroplane',\n '02747177': 'ashtray',\n '02773838': 'backpack',\n '02801938': 'basket',\n '02808440': 'tub', # bathtub\n '02818832': 'bed',\n '02828884': 'bench',\n '02834778': 'bicycle',\n '02843684': 'mailbox', # missing in objectnet3d, birdhouse, use view distribution of mailbox\n '02858304': 'boat',\n '02871439': 'bookshelf',\n '02876657': 'bottle',\n '02880940': 'bowl', # missing in objectnet3d, bowl, use view distribution of plate\n '02924116': 'bus',\n '02933112': 'cabinet',\n '02942699': 'camera',\n '02946921': 'can',\n '02954340': 'cap',\n '02958343': 'car',\n '02992529': 'cellphone',\n '03001627': 'chair',\n '03046257': 'clock',\n '03085013': 'keyboard',\n '03207941': 'dishwasher',\n '03211117': 'tvmonitor',\n '03261776': 'headphone',\n '03325088': 'faucet',\n '03337140': 'filing_cabinet',\n '03467517': 'guitar',\n '03513137': 'helmet',\n '03593526': 'jar',\n '03624134': 'knife',\n '03636649': 'lamp',\n '03642806': 'laptop',\n '03691459': 'speaker',\n '03710193': 'mailbox',\n '03759954': 'microphone',\n '03761084': 'microwave',\n '03790512': 'motorbike',\n '03797390': 'mug', # missing in objectnet3d, mug, use view distribution of cup\n '03928116': 'piano',\n '03938244': 'pillow',\n '03948459': 'rifle', # missing in objectnet3d, pistol, use view distribution of rifle\n '03991062': 'pot',\n '04004475': 'printer',\n '04074963': 'remote_control',\n '04090263': 'rifle',\n '04099429': 'road_pole', # missing in objectnet3d, rocket, use view distribution of road_pole\n '04225987': 'skateboard',\n '04256520': 'sofa',\n '04330267': 'stove',\n '04379243': 'diningtable', # use view distribution of dining_table\n '04401088': 'telephone',\n '04460130': 'road_pole', # missing in objectnet3d, tower, use view distribution of road_pole\n '04468005': 'train',\n '04530566': 'washing_machine',\n '04554684': 'dishwasher'} # washer, use view distribution of dishwasher\n\ng_synset_name_label_pairs = {#'aeroplane': 7,\n #'bottle': 1,\n #'bowl': 2, \n #'camera': 3,\n #'can': 4,\n #'car': 5,\n #'mug': 6, \n 'other': 0} \n\nmaterial_class_instance_pairs = {'specular': ['metal', 'paintsp'], # 'porcelain','plasticsp',\n 'transparent': ['glass'],\n 'diffuse': ['plastic','rubber','paper','leather','wood','clay','fabric'],\n 'background': ['background']}\n\n\n# material list\nclass_material_pairs = {'specular': ['other'],\n 'transparent': ['other'],\n 'diffuse': ['other']}\n\ninstance_material_except_pairs = {'metal': [],\n 'porcelain': [],\n 'plasticsp': [],\n 'paintsp':[],\n\n 'glass': [],#[8,9,18,19,20,24,25,26,27,28,29,30,31,32,34,43,59,72],\n \n 'plastic': [],\n 'rubber': [], \n 'leather': [],\n 'wood':[],\n 'paper':[],\n 'fabric':[],\n 'clay':[], \n }\ninstance_material_include_pairs = {\n }\n\nmaterial_class_id_dict = {'raw': 0,\n 'diffuse': 1,\n 'transparent': 2,\n 'specular': 3}\n\nmaterial_type_id_dict = {'raw': 0,\n 'metal': 1,\n 'porcelain': 2,\n 'plasticsp': 3,\n 'paintsp':4,\n 'glass': 5, \n 'plastic': 6,\n 'rubber': 7, \n 'leather': 8,\n 'wood':9,\n 'paper':10,\n 'fabric':11,\n 'clay':12, \n }\n\n\ndef obj_centered_camera_pos(dist, azimuth_deg, elevation_deg):\n phi = float(elevation_deg) / 180 * math.pi\n theta = float(azimuth_deg) / 180 * math.pi\n x = (dist * math.cos(theta) * math.cos(phi))\n y = (dist * math.sin(theta) * math.cos(phi))\n z = (dist * math.sin(phi))\n return (x, y, z)\n\ndef quaternionFromYawPitchRoll(yaw, pitch, roll):\n c1 = math.cos(yaw / 2.0)\n c2 = math.cos(pitch / 2.0)\n c3 = math.cos(roll / 2.0) \n s1 = math.sin(yaw / 2.0)\n s2 = math.sin(pitch / 2.0)\n s3 = math.sin(roll / 2.0) \n q1 = c1 * c2 * c3 + s1 * s2 * s3\n q2 = c1 * c2 * s3 - s1 * s2 * c3\n q3 = c1 * s2 * c3 + s1 * c2 * s3\n q4 = s1 * c2 * c3 - c1 * s2 * s3\n return (q1, q2, q3, q4)\n\ndef camPosToQuaternion(cx, cy, cz):\n q1a = 0\n q1b = 0\n q1c = math.sqrt(2) / 2\n q1d = math.sqrt(2) / 2\n camDist = math.sqrt(cx * cx + cy * cy + cz * cz)\n cx = cx / camDist\n cy = cy / camDist\n cz = cz / camDist \n t = math.sqrt(cx * cx + cy * cy) \n tx = cx / t\n ty = cy / t\n yaw = math.acos(ty)\n if tx > 0:\n yaw = 2 * math.pi - yaw\n pitch = 0\n tmp = min(max(tx*cx + ty*cy, -1),1)\n #roll = math.acos(tx * cx + ty * cy)\n roll = math.acos(tmp)\n if cz < 0:\n roll = -roll \n print(\"%f %f %f\" % (yaw, pitch, roll))\n q2a, q2b, q2c, q2d = quaternionFromYawPitchRoll(yaw, pitch, roll) \n q1 = q1a * q2a - q1b * q2b - q1c * q2c - q1d * q2d\n q2 = q1b * q2a + q1a * q2b + q1d * q2c - q1c * q2d\n q3 = q1c * q2a - q1d * q2b + q1a * q2c + q1b * q2d\n q4 = q1d * q2a + q1c * q2b - q1b * q2c + q1a * q2d\n return (q1, q2, q3, q4)\n\ndef camRotQuaternion(cx, cy, cz, theta): \n theta = theta / 180.0 * math.pi\n camDist = math.sqrt(cx * cx + cy * cy + cz * cz)\n cx = -cx / camDist\n cy = -cy / camDist\n cz = -cz / camDist\n q1 = math.cos(theta * 0.5)\n q2 = -cx * math.sin(theta * 0.5)\n q3 = -cy * math.sin(theta * 0.5)\n q4 = -cz * math.sin(theta * 0.5)\n return (q1, q2, q3, q4)\n\ndef quaternionProduct(qx, qy): \n a = qx[0]\n b = qx[1]\n c = qx[2]\n d = qx[3]\n e = qy[0]\n f = qy[1]\n g = qy[2]\n h = qy[3]\n q1 = a * e - b * f - c * g - d * h\n q2 = a * f + b * e + c * h - d * g\n q3 = a * g - b * h + c * e + d * f\n q4 = a * h + b * g - c * f + d * e \n return (q1, q2, q3, q4)\n\ndef quaternionToRotation(q):\n w, x, y, z = q\n r00 = 1 - 2 * y ** 2 - 2 * z ** 2\n r01 = 2 * x * y + 2 * w * z\n r02 = 2 * x * z - 2 * w * y\n\n r10 = 2 * x * y - 2 * w * z\n r11 = 1 - 2 * x ** 2 - 2 * z ** 2\n r12 = 2 * y * z + 2 * w * x\n\n r20 = 2 * x * z + 2 * w * y\n r21 = 2 * y * z - 2 * w * x\n r22 = 1 - 2 * x ** 2 - 2 * y ** 2\n r = [[r00, r01, r02], [r10, r11, r12], [r20, r21, r22]]\n return r\n\ndef quaternionToRotation_xyzw(q):\n x, y, z, w = q\n r00 = 1 - 2 * y ** 2 - 2 * z ** 2\n r01 = 2 * x * y + 2 * w * z\n r02 = 2 * x * z - 2 * w * y\n\n r10 = 2 * x * y - 2 * w * z\n r11 = 1 - 2 * x ** 2 - 2 * z ** 2\n r12 = 2 * y * z + 2 * w * x\n\n r20 = 2 * x * z + 2 * w * y\n r21 = 2 * y * z - 2 * w * x\n r22 = 1 - 2 * x ** 2 - 2 * y ** 2\n r = [[r00, r01, r02], [r10, r11, r12], [r20, r21, r22]]\n return r\n\ndef quaternionFromRotMat(rotation_matrix):\n rotation_matrix = np.reshape(rotation_matrix, (1, 9))[0]\n w = math.sqrt(rotation_matrix[0]+rotation_matrix[4]+rotation_matrix[8]+1 + 1e-6)/2\n x = math.sqrt(rotation_matrix[0]-rotation_matrix[4]-rotation_matrix[8]+1 + 1e-6)/2\n y = math.sqrt(-rotation_matrix[0]+rotation_matrix[4]-rotation_matrix[8]+1 + 1e-6)/2\n z = math.sqrt(-rotation_matrix[0]-rotation_matrix[4]+rotation_matrix[8]+1 + 1e-6)/2\n a = [w,x,y,z]\n m = a.index(max(a))\n if m == 0:\n x = (rotation_matrix[7]-rotation_matrix[5])/(4*w)\n y = (rotation_matrix[2]-rotation_matrix[6])/(4*w)\n z = (rotation_matrix[3]-rotation_matrix[1])/(4*w)\n if m == 1:\n w = (rotation_matrix[7]-rotation_matrix[5])/(4*x)\n y = (rotation_matrix[1]+rotation_matrix[3])/(4*x)\n z = (rotation_matrix[6]+rotation_matrix[2])/(4*x)\n if m == 2:\n w = (rotation_matrix[2]-rotation_matrix[6])/(4*y)\n x = (rotation_matrix[1]+rotation_matrix[3])/(4*y)\n z = (rotation_matrix[5]+rotation_matrix[7])/(4*y)\n if m == 3:\n w = (rotation_matrix[3]-rotation_matrix[1])/(4*z)\n x = (rotation_matrix[6]+rotation_matrix[2])/(4*z)\n y = (rotation_matrix[5]+rotation_matrix[7])/(4*z)\n quaternion = (w,x,y,z)\n return quaternion\n\ndef quaternionFromRotMat_xyzw(rotation_matrix):\n rotation_matrix = np.reshape(rotation_matrix, (1, 9))[0]\n w = math.sqrt(rotation_matrix[0]+rotation_matrix[4]+rotation_matrix[8]+1 + 1e-6)/2\n x = math.sqrt(rotation_matrix[0]-rotation_matrix[4]-rotation_matrix[8]+1 + 1e-6)/2\n y = math.sqrt(-rotation_matrix[0]+rotation_matrix[4]-rotation_matrix[8]+1 + 1e-6)/2\n z = math.sqrt(-rotation_matrix[0]-rotation_matrix[4]+rotation_matrix[8]+1 + 1e-6)/2\n a = [x,y,z,w]\n m = a.index(max(a))\n if m == 0:\n x = (rotation_matrix[7]-rotation_matrix[5])/(4*w)\n y = (rotation_matrix[2]-rotation_matrix[6])/(4*w)\n z = (rotation_matrix[3]-rotation_matrix[1])/(4*w)\n if m == 1:\n w = (rotation_matrix[7]-rotation_matrix[5])/(4*x)\n y = (rotation_matrix[1]+rotation_matrix[3])/(4*x)\n z = (rotation_matrix[6]+rotation_matrix[2])/(4*x)\n if m == 2:\n w = (rotation_matrix[2]-rotation_matrix[6])/(4*y)\n x = (rotation_matrix[1]+rotation_matrix[3])/(4*y)\n z = (rotation_matrix[5]+rotation_matrix[7])/(4*y)\n if m == 3:\n w = (rotation_matrix[3]-rotation_matrix[1])/(4*z)\n x = (rotation_matrix[6]+rotation_matrix[2])/(4*z)\n y = (rotation_matrix[5]+rotation_matrix[7])/(4*z)\n quaternion = (x,y,z,w)\n return quaternion\n\ndef rotVector(q, vector_ori):\n r = quaternionToRotation(q)\n x_ori = vector_ori[0]\n y_ori = vector_ori[1]\n z_ori = vector_ori[2]\n x_rot = r[0][0] * x_ori + r[1][0] * y_ori + r[2][0] * z_ori\n y_rot = r[0][1] * x_ori + r[1][1] * y_ori + r[2][1] * z_ori\n z_rot = r[0][2] * x_ori + r[1][2] * y_ori + r[2][2] * z_ori\n return (x_rot, y_rot, z_rot)\n\ndef cameraLPosToCameraRPos(q_l, pos_l, baseline_dis):\n vector_camera_l_y = (1, 0, 0)\n vector_rot = rotVector(q_l, vector_camera_l_y)\n pos_r = (pos_l[0] + vector_rot[0] * baseline_dis,\n pos_l[1] + vector_rot[1] * baseline_dis,\n pos_l[2] + vector_rot[2] * baseline_dis)\n return pos_r\n\ndef getRTFromAToB(pointCloudA, pointCloudB):\n muA = np.mean(pointCloudA, axis=0)\n muB = np.mean(pointCloudB, axis=0)\n\n zeroMeanA = pointCloudA - muA\n zeroMeanB = pointCloudB - muB\n\n covMat = np.matmul(np.transpose(zeroMeanA), zeroMeanB)\n U, S, Vt = np.linalg.svd(covMat)\n R = np.matmul(Vt.T, U.T)\n\n if np.linalg.det(R) < 0:\n print(\"[V]getRTFromAToB: Reflection detected\")\n Vt[2, :] *= -1\n R = Vt.T * U.T\n T = (-np.matmul(R, muA.T) + muB.T).reshape(3, 1)\n return R, T\n\ndef cameraPositionRandomize(start_point_range, look_at_range, up_range):\n r_range, vector_range = start_point_range\n r_min, r_max = r_range\n x_min, x_max, y_min, y_max = vector_range\n r = random.uniform(r_min, r_max)\n x = random.uniform(x_min, x_max)\n y = random.uniform(y_min, y_max)\n z = math.sqrt(1 - x**2 - y**2)\n vector_camera_axis = np.array([x, y, z])\n\n x_min, x_max, y_min, y_max = up_range\n x = random.uniform(x_min, x_max)\n y = random.uniform(y_min, y_max) \n z = math.sqrt(1 - x**2 - y**2)\n up = np.array([x, y, z])\n\n x_min, x_max, y_min, y_max, z_min, z_max = look_at_range\n look_at = np.array([random.uniform(x_min, x_max),\n random.uniform(y_min, y_max),\n random.uniform(z_min, z_max)])\n position = look_at + r * vector_camera_axis\n\n vectorZ = - (look_at - position)/np.linalg.norm(look_at - position)\n vectorX = np.cross(up, vectorZ)/np.linalg.norm(np.cross(up, vectorZ))\n vectorY = np.cross(vectorZ, vectorX)/np.linalg.norm(np.cross(vectorX, vectorZ))\n\n # points in camera coordinates\n pointSensor= np.array([[0., 0., 0.], [1., 0., 0.], [0., 2., 0.], [0., 0., 3.]])\n\n # points in world coordinates \n pointWorld = np.array([position,\n position + vectorX,\n position + vectorY * 2,\n position + vectorZ * 3])\n\n resR, resT = getRTFromAToB(pointSensor, pointWorld)\n resQ = quaternionFromRotMat(resR)\n return resQ, resT \n\n\ndef genCameraPosition(look_at):\n quat_list = []\n rot_list = []\n trans_list = []\n position_list = []\n \n # alpha: \n alpha = 0\n alpha_delta = (2 * math.pi) / num_point_ver\n for i in range(num_point_ver):\n alpha = alpha + alpha_delta\n flag_x = 1\n flag_y = 1\n alpha1 = alpha\n if alpha > math.pi/2 and alpha <= math.pi: \n alpha1 = math.pi - alpha\n flag_x = -1\n flag_y = 1\n elif alpha > math.pi and alpha <= math.pi*(3/2):\n alpha1 = alpha - math.pi\n flag_x = -1\n flag_y = -1\n elif alpha > math.pi*(3/2):\n alpha1 = math.pi*2 - alpha\n flag_x = 1\n flag_y = -1\n \n beta = beta_range[0]\n beta_delta = (beta_range[1]-beta_range[0])/(num_point_hor-1)\n for j in range(num_point_hor):\n if j != 0:\n beta = beta + beta_delta\n\n x = flag_x * (r * math.sin(beta)) * math.cos(alpha1)\n y = flag_y * (r * math.sin(beta)) * math.sin(alpha1)\n z = r * math.cos(beta)\n position = np.array([x, y, z]) + look_at\n look_at = look_at\n up = np.array([0, 0, 1])\n\n vectorZ = - (look_at - position)/np.linalg.norm(look_at - position)\n vectorX = np.cross(up, vectorZ)/np.linalg.norm(np.cross(up, vectorZ))\n vectorY = np.cross(vectorZ, vectorX)/np.linalg.norm(np.cross(vectorX, vectorZ))\n\n # points in camera coordinates\n pointSensor= np.array([[0., 0., 0.], [1., 0., 0.], [0., 2., 0.], [0., 0., 3.]])\n\n # points in world coordinates \n pointWorld = np.array([position,\n position + vectorX,\n position + vectorY * 2,\n position + vectorZ * 3])\n\n resR, resT = getRTFromAToB(pointSensor, pointWorld)\n resQ = quaternionFromRotMat(resR)\n\n quat_list.append(resQ)\n rot_list.append(resR)\n trans_list.append(resT)\n position_list.append(position)\n return quat_list, trans_list, rot_list \n\n\ndef quanternion_mul(q1, q2):\n s1 = q1[0]\n v1 = np.array(q1[1:])\n s2 = q2[0]\n v2 = np.array(q2[1:])\n s = s1 * s2 - np.dot(v1, v2)\n v = s1 * v2 + s2 * v1 + np.cross(v1, v2)\n return (s, v[0], v[1], v[2])\n\nclass BlenderRenderer(object):\n def __init__(self, viewport_size_x=640, viewport_size_y=360, DEVICE_LIST=None):\n '''\n viewport_size_x, viewport_size_y: rendering viewport resolution\n '''\n\n self.DEVICE_LIST = DEVICE_LIST\n\n # remove all objects, cameras and lights\n for obj in bpy.data.meshes:\n bpy.data.meshes.remove(obj)\n\n for cam in bpy.data.cameras:\n bpy.data.cameras.remove(cam)\n\n for light in bpy.data.lights:\n bpy.data.lights.remove(light)\n\n for obj in bpy.data.objects:\n bpy.data.objects.remove(obj, do_unlink=True)\n\n render_context = bpy.context.scene.render\n\n # add left camera\n camera_l_data = bpy.data.cameras.new(name=\"camera_l\")\n camera_l_object = bpy.data.objects.new(name=\"camera_l\", object_data=camera_l_data)\n bpy.context.collection.objects.link(camera_l_object)\n\n # add right camera\n camera_r_data = bpy.data.cameras.new(name=\"camera_r\")\n camera_r_object = bpy.data.objects.new(name=\"camera_r\", object_data=camera_r_data)\n bpy.context.collection.objects.link(camera_r_object)\n\n camera_l = bpy.data.objects[\"camera_l\"]\n camera_r = bpy.data.objects[\"camera_r\"]\n\n # set the camera postion and orientation so that it is in\n # the front of the object\n camera_l.location = (1, 0, 0)\n camera_r.location = (1, 0, 0)\n\n # add emitter light\n light_emitter_data = bpy.data.lights.new(name=\"light_emitter\", type='SPOT')\n light_emitter_object = bpy.data.objects.new(name=\"light_emitter\", object_data=light_emitter_data)\n bpy.context.collection.objects.link(light_emitter_object)\n\n light_emitter = bpy.data.objects[\"light_emitter\"]\n light_emitter.location = (1, 0, 0)\n light_emitter.data.energy = LIGHT_EMITTER_ENERGY\n\n # render setting\n render_context.resolution_percentage = 100\n self.render_context = render_context\n\n self.camera_l = camera_l\n self.camera_r = camera_r\n\n self.light_emitter = light_emitter\n\n self.model_loaded = False\n self.background_added = None\n\n self.render_context.resolution_x = viewport_size_x\n self.render_context.resolution_y = viewport_size_y\n\n self.my_material = {}\n self.render_mode = 'IR'\n\n # output setting \n self.render_context.image_settings.file_format = 'PNG'\n self.render_context.image_settings.compression = 0\n self.render_context.image_settings.color_mode = 'BW'\n self.render_context.image_settings.color_depth = '8'\n\n # cycles setting\n self.render_context.engine = 'CYCLES'\n bpy.context.scene.cycles.progressive = 'BRANCHED_PATH'\n bpy.context.scene.cycles.use_denoising = True\n bpy.context.scene.cycles.denoiser = 'NLM'\n bpy.context.scene.cycles.film_exposure = 0.5\n\n # self.render_context.use_antialiasing = False\n ##########\n bpy.context.scene.view_layers[\"View Layer\"].use_sky = True\n ##########\n\n # switch on nodes\n bpy.context.scene.use_nodes = True\n tree = bpy.context.scene.node_tree\n links = tree.links\n \n # clear default nodes\n for n in tree.nodes:\n tree.nodes.remove(n)\n \n # create input render layer node\n rl = tree.nodes.new('CompositorNodeRLayers')\n\n # create output node\n self.fileOutput = tree.nodes.new(type=\"CompositorNodeOutputFile\")\n self.fileOutput.base_path = \"./new_data/0000\"\n self.fileOutput.format.file_format = 'OPEN_EXR'\n self.fileOutput.format.color_depth= '32'\n self.fileOutput.file_slots[0].path = 'depth#'\n links.new(rl.outputs[2], self.fileOutput.inputs[0])\n\n # depth sensor pattern\n self.pattern = []\n # environment map\n self.env_map = []\n self.realtable_img_list = []\n self.realfloor_img_list = []\n self.obj_texture_img_list = []\n\n self.src_energy_for_rgb_render = 0\n\n def loadImages(self, pattern_path, env_map_path, real_table_image_root_path, real_floor_image_root_path, obj_texture_image_root_path, obj_texture_image_idxfile, check_seen_scene):\n # load pattern image\n self.pattern = bpy.data.images.load(filepath=pattern_path)\n if check_seen_scene:\n env_map_path_list = os.listdir(env_map_path)\n real_table_image_root_path_list = os.listdir(real_table_image_root_path)\n real_floor_image_root_path_list = os.listdir(real_floor_image_root_path)\n else:\n env_map_path_list = sorted(os.listdir(env_map_path))\n real_table_image_root_path_list = sorted(os.listdir(real_table_image_root_path))\n real_floor_image_root_path_list = sorted(os.listdir(real_floor_image_root_path))\n # load env map\n for item in env_map_path_list:\n if item.split('.')[-1] == 'hdr':\n self.env_map.append(bpy.data.images.load(filepath=os.path.join(env_map_path, item)))\n # load real table images\n for item in real_table_image_root_path_list:\n if item.split('.')[-1] == 'jpg':\n self.realtable_img_list.append(bpy.data.images.load(filepath=os.path.join(real_table_image_root_path, item)))\n # load real floor images\n for item in real_floor_image_root_path_list:\n if item.split('.')[-1] == 'jpg':\n self.realfloor_img_list.append(bpy.data.images.load(filepath=os.path.join(real_floor_image_root_path, item)))\n # load obj texture images\n f_teximg_idx = open(os.path.join(obj_texture_image_root_path, obj_texture_image_idxfile),\"r\")\n lines = f_teximg_idx.readlines() \n for item in lines:\n item = item[:-1] \n self.obj_texture_img_list.append(bpy.data.images.load(filepath=os.path.join(obj_texture_image_root_path, \"images\", item)))\n\n\n def addEnvMap(self):\n # Get the environment node tree of the current scene\n node_tree = bpy.context.scene.world.node_tree\n tree_nodes = node_tree.nodes\n\n # Clear all nodes\n tree_nodes.clear()\n\n # Add Background node\n node_background = tree_nodes.new(type='ShaderNodeBackground')\n\n # Add Environment Texture node\n node_environment = tree_nodes.new('ShaderNodeTexEnvironment')\n # Load and assign the image to the node property\n # node_environment.image = bpy.data.images.load(\"/Users/zhangjiyao/Desktop/test_addon/envmap_lib/autoshop_01_1k.hdr\") # Relative path\n node_environment.location = -300,0\n\n node_tex_coord = tree_nodes.new(type='ShaderNodeTexCoord')\n node_tex_coord.location = -700,0\n\n node_mapping = tree_nodes.new(type='ShaderNodeMapping')\n node_mapping.location = -500,0\n\n # Add Output node\n node_output = tree_nodes.new(type='ShaderNodeOutputWorld') \n node_output.location = 200,0\n\n # Link all nodes\n links = node_tree.links\n links.new(node_environment.outputs[\"Color\"], node_background.inputs[\"Color\"])\n links.new(node_background.outputs[\"Background\"], node_output.inputs[\"Surface\"])\n links.new(node_tex_coord.outputs[\"Generated\"], node_mapping.inputs[\"Vector\"])\n links.new(node_mapping.outputs[\"Vector\"], node_environment.inputs[\"Vector\"])\n\n #### bpy.data.worlds[\"World\"].node_tree.nodes[\"Background\"].inputs[1].default_value = 1.0\n random_energy = random.uniform(LIGHT_ENV_MAP_ENERGY_RGB * 0.8, LIGHT_ENV_MAP_ENERGY_RGB * 1.2)\n bpy.data.worlds[\"World\"].node_tree.nodes[\"Background\"].inputs[1].default_value = random_energy\n ####\n\n\n def setEnvMap(self, env_map_id, rotation_elur_z):\n # Get the environment node tree of the current scene\n node_tree = bpy.context.scene.world.node_tree\n\n # Get Environment Texture node\n node_environment = node_tree.nodes['Environment Texture']\n # Load and assign the image to the node property\n node_environment.image = self.env_map[env_map_id]\n\n node_mapping = node_tree.nodes['Mapping']\n node_mapping.inputs[2].default_value[2] = rotation_elur_z\n\n\n def addMaskMaterial(self, num=20):\n background_material_name_list = [\"mask_background\", \"mask_table\", \"mask_tableplane\"]\n for material_name in background_material_name_list:\n material_class = (bpy.data.materials.get(material_name) or bpy.data.materials.new(material_name)) # test if material exists, if it does not exist, create it:\n\n # enable 'Use nodes'\n material_class.use_nodes = True\n node_tree = material_class.node_tree\n\n # remove default nodes\n material_class.node_tree.nodes.clear()\n\n # add new nodes \n node_1 = node_tree.nodes.new('ShaderNodeOutputMaterial')\n node_2= node_tree.nodes.new('ShaderNodeBrightContrast')\n\n # link nodes\n node_tree.links.new(node_1.inputs[0], node_2.outputs[0])\n node_2.inputs[0].default_value = (1, 1, 1, 1)\n self.my_material[material_name] = material_class\n\n\n for i in range(num):\n class_name = str(i + 1)\n # set the material of background \n material_name = \"mask_\" + class_name\n\n # test if material exists\n # if it does not exist, create it:\n material_class = (bpy.data.materials.get(material_name) or \n bpy.data.materials.new(material_name))\n\n # enable 'Use nodes'\n material_class.use_nodes = True\n node_tree = material_class.node_tree\n\n # remove default nodes\n material_class.node_tree.nodes.clear()\n\n # add new nodes \n node_1 = node_tree.nodes.new('ShaderNodeOutputMaterial')\n node_2= node_tree.nodes.new('ShaderNodeBrightContrast')\n\n # link nodes\n node_tree.links.new(node_1.inputs[0], node_2.outputs[0])\n\n if class_name.split('_')[0] == 'background' or class_name.split('_')[0] == 'table' or class_name.split('_')[0] == 'tableplane':\n node_2.inputs[0].default_value = (1, 1, 1, 1)\n else:\n node_2.inputs[0].default_value = ((i + 1)/255., 0., 0., 1)\n\n self.my_material[material_name] = material_class\n\n\n def addNOCSMaterial(self):\n material_name = 'coord_color'\n mat = (bpy.data.materials.get(material_name) or bpy.data.materials.new(material_name))\n\n mat.use_nodes = True\n node_tree = mat.node_tree\n nodes = node_tree.nodes\n nodes.clear() \n\n links = node_tree.links\n links.clear()\n\n vcol_R = nodes.new(type=\"ShaderNodeVertexColor\")\n vcol_R.layer_name = \"Col_R\" # the vertex color layer name\n vcol_G = nodes.new(type=\"ShaderNodeVertexColor\")\n vcol_G.layer_name = \"Col_G\" # the vertex color layer name\n vcol_B = nodes.new(type=\"ShaderNodeVertexColor\")\n vcol_B.layer_name = \"Col_B\" # the vertex color layer name\n\n node_Output = node_tree.nodes.new('ShaderNodeOutputMaterial')\n node_Emission = node_tree.nodes.new('ShaderNodeEmission')\n node_LightPath = node_tree.nodes.new('ShaderNodeLightPath')\n node_Mix = node_tree.nodes.new('ShaderNodeMixShader')\n node_Combine = node_tree.nodes.new(type=\"ShaderNodeCombineRGB\")\n\n\n # make links\n node_tree.links.new(vcol_R.outputs[1], node_Combine.inputs[0])\n node_tree.links.new(vcol_G.outputs[1], node_Combine.inputs[1])\n node_tree.links.new(vcol_B.outputs[1], node_Combine.inputs[2])\n node_tree.links.new(node_Combine.outputs[0], node_Emission.inputs[0])\n\n node_tree.links.new(node_LightPath.outputs[0], node_Mix.inputs[0])\n node_tree.links.new(node_Emission.outputs[0], node_Mix.inputs[2])\n node_tree.links.new(node_Mix.outputs[0], node_Output.inputs[0])\n\n self.my_material[material_name] = mat\n\n\n def addNormalMaterial(self):\n material_name = 'normal'\n mat = (bpy.data.materials.get(material_name) or bpy.data.materials.new(material_name))\n mat.use_nodes = True\n node_tree = mat.node_tree\n nodes = node_tree.nodes\n nodes.clear()\n \n links = node_tree.links\n links.clear()\n \n # Nodes :\n new_node = nodes.new(type='ShaderNodeMath')\n new_node.active_preview = False\n new_node.color = (0.6079999804496765, 0.6079999804496765, 0.6079999804496765)\n new_node.location = (151.59744262695312, 854.5482177734375)\n new_node.name = 'Math'\n new_node.operation = 'MULTIPLY'\n new_node.select = False\n new_node.use_clamp = False\n new_node.width = 140.0\n new_node.inputs[0].default_value = 0.5\n new_node.inputs[1].default_value = 1.0\n new_node.inputs[2].default_value = 0.0\n new_node.outputs[0].default_value = 0.0\n\n new_node = nodes.new(type='ShaderNodeLightPath')\n new_node.active_preview = False\n new_node.color = (0.6079999804496765, 0.6079999804496765, 0.6079999804496765)\n new_node.location = (602.9912719726562, 1046.660888671875)\n new_node.name = 'Light Path'\n new_node.select = False\n new_node.width = 140.0\n new_node.outputs[0].default_value = 0.0\n new_node.outputs[1].default_value = 0.0\n new_node.outputs[2].default_value = 0.0\n new_node.outputs[3].default_value = 0.0\n new_node.outputs[4].default_value = 0.0\n new_node.outputs[5].default_value = 0.0\n new_node.outputs[6].default_value = 0.0\n new_node.outputs[7].default_value = 0.0\n new_node.outputs[8].default_value = 0.0\n new_node.outputs[9].default_value = 0.0\n new_node.outputs[10].default_value = 0.0\n new_node.outputs[11].default_value = 0.0\n new_node.outputs[12].default_value = 0.0\n\n new_node = nodes.new(type='ShaderNodeOutputMaterial')\n new_node.active_preview = False\n new_node.color = (0.6079999804496765, 0.6079999804496765, 0.6079999804496765)\n new_node.is_active_output = True\n new_node.location = (1168.93017578125, 701.84033203125)\n new_node.name = 'Material Output'\n new_node.select = False\n new_node.target = 'ALL'\n new_node.width = 140.0\n new_node.inputs[2].default_value = [0.0, 0.0, 0.0]\n\n new_node = nodes.new(type='ShaderNodeBsdfTransparent')\n new_node.active_preview = False\n new_node.color = (0.6079999804496765, 0.6079999804496765, 0.6079999804496765)\n new_node.location = (731.72900390625, 721.4832763671875)\n new_node.name = 'Transparent BSDF'\n new_node.select = False\n new_node.width = 140.0\n new_node.inputs[0].default_value = [1.0, 1.0, 1.0, 1.0]\n\n new_node = nodes.new(type='ShaderNodeCombineXYZ')\n new_node.active_preview = False\n new_node.color = (0.6079999804496765, 0.6079999804496765, 0.6079999804496765)\n new_node.location = (594.4229736328125, 602.9271240234375)\n new_node.name = 'Combine XYZ'\n new_node.select = False\n new_node.width = 140.0\n new_node.inputs[0].default_value = 0.0\n new_node.inputs[1].default_value = 0.0\n new_node.inputs[2].default_value = 0.0\n new_node.outputs[0].default_value = [0.0, 0.0, 0.0]\n\n new_node = nodes.new(type='ShaderNodeMixShader')\n new_node.active_preview = False\n new_node.color = (0.6079999804496765, 0.6079999804496765, 0.6079999804496765)\n new_node.location = (992.7239990234375, 707.2142333984375)\n new_node.name = 'Mix Shader'\n new_node.select = False\n new_node.width = 140.0\n new_node.inputs[0].default_value = 0.5\n\n new_node = nodes.new(type='ShaderNodeEmission')\n new_node.active_preview = False\n new_node.color = (0.6079999804496765, 0.6079999804496765, 0.6079999804496765)\n new_node.location = (774.0802612304688, 608.2547607421875)\n new_node.name = 'Emission'\n new_node.select = False\n new_node.width = 140.0\n new_node.inputs[0].default_value = [1.0, 1.0, 1.0, 1.0]\n new_node.inputs[1].default_value = 1.0\n\n new_node = nodes.new(type='ShaderNodeSeparateXYZ')\n new_node.active_preview = False\n new_node.color = (0.6079999804496765, 0.6079999804496765, 0.6079999804496765)\n new_node.location = (-130.12167358398438, 558.1497802734375)\n new_node.name = 'Separate XYZ'\n new_node.select = False\n new_node.width = 140.0\n new_node.inputs[0].default_value = [0.0, 0.0, 0.0]\n new_node.outputs[0].default_value = 0.0\n new_node.outputs[1].default_value = 0.0\n new_node.outputs[2].default_value = 0.0\n\n new_node = nodes.new(type='ShaderNodeMath')\n new_node.active_preview = False\n new_node.color = (0.6079999804496765, 0.6079999804496765, 0.6079999804496765)\n new_node.location = (162.43240356445312, 618.8094482421875)\n new_node.name = 'Math.002'\n new_node.operation = 'MULTIPLY'\n new_node.select = False\n new_node.use_clamp = False\n new_node.width = 140.0\n new_node.inputs[0].default_value = 0.5\n new_node.inputs[1].default_value = 1.0\n new_node.inputs[2].default_value = 0.0\n new_node.outputs[0].default_value = 0.0\n\n new_node = nodes.new(type='ShaderNodeMath')\n new_node.active_preview = False\n new_node.color = (0.6079999804496765, 0.6079999804496765, 0.6079999804496765)\n new_node.location = (126.8158187866211, 364.5539855957031)\n new_node.name = 'Math.001'\n new_node.operation = 'MULTIPLY'\n new_node.select = False\n new_node.use_clamp = False\n new_node.width = 140.0\n new_node.inputs[0].default_value = 0.5\n new_node.inputs[1].default_value = -1.0\n new_node.inputs[2].default_value = 0.0\n new_node.outputs[0].default_value = 0.0\n\n new_node = nodes.new(type='ShaderNodeVectorTransform')\n new_node.active_preview = False\n new_node.color = (0.6079999804496765, 0.6079999804496765, 0.6079999804496765)\n new_node.convert_from = 'WORLD'\n new_node.convert_to = 'CAMERA'\n new_node.location = (-397.0209045410156, 594.7037353515625)\n new_node.name = 'Vector Transform'\n new_node.select = False\n new_node.vector_type = 'VECTOR'\n new_node.width = 140.0\n new_node.inputs[0].default_value = [0.5, 0.5, 0.5]\n new_node.outputs[0].default_value = [0.0, 0.0, 0.0]\n\n new_node = nodes.new(type='ShaderNodeNewGeometry')\n new_node.active_preview = False\n new_node.color = (0.6079999804496765, 0.6079999804496765, 0.6079999804496765)\n new_node.location = (-651.8067016601562, 593.0455932617188)\n new_node.name = 'Geometry'\n new_node.width = 140.0\n new_node.outputs[0].default_value = [0.0, 0.0, 0.0]\n new_node.outputs[1].default_value = [0.0, 0.0, 0.0]\n new_node.outputs[2].default_value = [0.0, 0.0, 0.0]\n new_node.outputs[3].default_value = [0.0, 0.0, 0.0]\n new_node.outputs[4].default_value = [0.0, 0.0, 0.0]\n new_node.outputs[5].default_value = [0.0, 0.0, 0.0]\n new_node.outputs[6].default_value = 0.0\n new_node.outputs[7].default_value = 0.0\n new_node.outputs[8].default_value = 0.0\n\n # Links :\n\n links.new(nodes[\"Light Path\"].outputs[0], nodes[\"Mix Shader\"].inputs[0]) \n links.new(nodes[\"Separate XYZ\"].outputs[0], nodes[\"Math\"].inputs[0]) \n links.new(nodes[\"Separate XYZ\"].outputs[1], nodes[\"Math.002\"].inputs[0]) \n links.new(nodes[\"Separate XYZ\"].outputs[2], nodes[\"Math.001\"].inputs[0]) \n links.new(nodes[\"Vector Transform\"].outputs[0], nodes[\"Separate XYZ\"].inputs[0]) \n links.new(nodes[\"Combine XYZ\"].outputs[0], nodes[\"Emission\"].inputs[0]) \n links.new(nodes[\"Math\"].outputs[0], nodes[\"Combine XYZ\"].inputs[0]) \n links.new(nodes[\"Math.002\"].outputs[0], nodes[\"Combine XYZ\"].inputs[1]) \n links.new(nodes[\"Math.001\"].outputs[0], nodes[\"Combine XYZ\"].inputs[2]) \n links.new(nodes[\"Transparent BSDF\"].outputs[0], nodes[\"Mix Shader\"].inputs[1]) \n links.new(nodes[\"Emission\"].outputs[0], nodes[\"Mix Shader\"].inputs[2]) \n links.new(nodes[\"Mix Shader\"].outputs[0], nodes[\"Material Output\"].inputs[0]) \n links.new(nodes[\"Geometry\"].outputs[1], nodes[\"Vector Transform\"].inputs[0]) \n\n self.my_material[material_name] = mat\n\n def addMaterialLib(self, material_class_instance_pairs):\n for mat in bpy.data.materials:\n name = mat.name\n name_class = str(name.split('_')[0])\n if name_class != 'Dots Stroke' and name_class != 'default': \n if name_class not in self.my_material:\n self.my_material[name_class] = [mat]\n else:\n self.my_material[name_class].append(mat) # e.g. self.my_material['metal'] = [.....]\n ###\n\n def setCamera(self, quaternion, translation, fov, baseline_distance):\n self.camera_l.data.angle = fov\n self.camera_r.data.angle = self.camera_l.data.angle\n cx = translation[0]\n cy = translation[1]\n cz = translation[2]\n\n self.camera_l.location[0] = cx\n self.camera_l.location[1] = cy \n self.camera_l.location[2] = cz\n\n self.camera_l.rotation_mode = 'QUATERNION'\n self.camera_l.rotation_quaternion[0] = quaternion[0]\n self.camera_l.rotation_quaternion[1] = quaternion[1]\n self.camera_l.rotation_quaternion[2] = quaternion[2]\n self.camera_l.rotation_quaternion[3] = quaternion[3]\n\n self.camera_r.rotation_mode = 'QUATERNION'\n self.camera_r.rotation_quaternion[0] = quaternion[0]\n self.camera_r.rotation_quaternion[1] = quaternion[1]\n self.camera_r.rotation_quaternion[2] = quaternion[2]\n self.camera_r.rotation_quaternion[3] = quaternion[3]\n cx, cy, cz = cameraLPosToCameraRPos(quaternion, (cx, cy, cz), baseline_distance)\n self.camera_r.location[0] = cx\n self.camera_r.location[1] = cy \n self.camera_r.location[2] = cz\n\n\n def setLighting(self):\n # emitter \n #self.light_emitter.location = self.camera_r.location\n self.light_emitter.location = self.camera_l.location + 0.51 * (self.camera_r.location - self.camera_l.location)\n self.light_emitter.rotation_mode = 'QUATERNION'\n self.light_emitter.rotation_quaternion = self.camera_r.rotation_quaternion\n\n # emitter setting\n bpy.context.view_layer.objects.active = None\n # bpy.ops.object.select_all(action=\"DESELECT\")\n self.render_context.engine = 'CYCLES'\n self.light_emitter.select_set(True)\n self.light_emitter.data.use_nodes = True\n self.light_emitter.data.type = \"POINT\"\n self.light_emitter.data.shadow_soft_size = 0.001\n random_energy = random.uniform(LIGHT_EMITTER_ENERGY * 0.9, LIGHT_EMITTER_ENERGY * 1.1)\n self.light_emitter.data.energy = random_energy\n\n # remove default node\n light_emitter = bpy.data.objects[\"light_emitter\"].data\n light_emitter.node_tree.nodes.clear()\n\n # add new nodes\n light_output = light_emitter.node_tree.nodes.new(\"ShaderNodeOutputLight\")\n node_1 = light_emitter.node_tree.nodes.new(\"ShaderNodeEmission\")\n node_2 = light_emitter.node_tree.nodes.new(\"ShaderNodeTexImage\")\n node_3 = light_emitter.node_tree.nodes.new(\"ShaderNodeMapping\")\n node_4 = light_emitter.node_tree.nodes.new(\"ShaderNodeVectorMath\")\n node_5 = light_emitter.node_tree.nodes.new(\"ShaderNodeSeparateXYZ\")\n node_6 = light_emitter.node_tree.nodes.new(\"ShaderNodeTexCoord\")\n\n # link nodes\n light_emitter.node_tree.links.new(light_output.inputs[0], node_1.outputs[0])\n light_emitter.node_tree.links.new(node_1.inputs[0], node_2.outputs[0])\n light_emitter.node_tree.links.new(node_2.inputs[0], node_3.outputs[0])\n light_emitter.node_tree.links.new(node_3.inputs[0], node_4.outputs[0])\n light_emitter.node_tree.links.new(node_4.inputs[0], node_6.outputs[1])\n light_emitter.node_tree.links.new(node_4.inputs[1], node_5.outputs[2])\n light_emitter.node_tree.links.new(node_5.inputs[0], node_6.outputs[1])\n\n # set parameter of nodes\n node_1.inputs[1].default_value = 1.0 # scale\n node_2.extension = 'CLIP'\n # node_2.interpolation = 'Cubic'\n\n node_3.inputs[1].default_value[0] = 0.5\n node_3.inputs[1].default_value[1] = 0.5\n node_3.inputs[1].default_value[2] = 0\n node_3.inputs[2].default_value[0] = 0\n node_3.inputs[2].default_value[1] = 0\n node_3.inputs[2].default_value[2] = 0.05\n\n # scale of pattern\n node_3.inputs[3].default_value[0] = 0.6\n node_3.inputs[3].default_value[1] = 0.85\n node_3.inputs[3].default_value[2] = 0\n node_4.operation = 'DIVIDE'\n\n # pattern path\n node_2.image = self.pattern\n\n\n def lightModeSelect(self, light_mode):\n if light_mode == \"RGB\":\n self.light_emitter.hide_render = True\n ###\n bpy.data.worlds[\"World\"].node_tree.nodes[\"Background\"].inputs[1].default_value = self.src_energy_for_rgb_render\n\n elif light_mode == \"IR\":\n self.light_emitter.hide_render = False\n # set the environment map energy\n random_energy = random.uniform(LIGHT_ENV_MAP_ENERGY_IR * 0.8, LIGHT_ENV_MAP_ENERGY_IR * 1.2)\n bpy.data.worlds[\"World\"].node_tree.nodes[\"Background\"].inputs[1].default_value = random_energy\n \n elif light_mode == \"Mask\" or light_mode == \"NOCS\" or light_mode == \"Normal\":\n self.light_emitter.hide_render = True\n bpy.data.worlds[\"World\"].node_tree.nodes[\"Background\"].inputs[1].default_value = 0\n else:\n raise NotImplementedError \n\n\n def outputModeSelect(self, output_mode):\n if output_mode == \"RGB\":\n self.render_context.image_settings.file_format = 'PNG'\n self.render_context.image_settings.compression = 0\n self.render_context.image_settings.color_mode = 'RGB'\n self.render_context.image_settings.color_depth = '8'\n bpy.context.scene.view_settings.view_transform = 'Filmic'\n bpy.context.scene.render.filter_size = 1.5\n self.render_context.resolution_x = 640 ### 1280\n self.render_context.resolution_y = 360 ### 720\n elif output_mode == \"IR\":\n self.render_context.image_settings.file_format = 'PNG'\n self.render_context.image_settings.compression = 0\n self.render_context.image_settings.color_mode = 'BW'\n self.render_context.image_settings.color_depth = '8'\n bpy.context.scene.view_settings.view_transform = 'Filmic'\n bpy.context.scene.render.filter_size = 1.5\n self.render_context.resolution_x = 640 ### 1280\n self.render_context.resolution_y = 360 ### 720\n elif output_mode == \"Mask\":\n self.render_context.image_settings.file_format = 'OPEN_EXR'\n self.render_context.image_settings.color_mode = 'RGB'\n bpy.context.scene.view_settings.view_transform = 'Raw'\n bpy.context.scene.render.filter_size = 0\n self.render_context.resolution_x = 640\n self.render_context.resolution_y = 360\n elif output_mode == \"NOCS\":\n # self.render_context.image_settings.file_format = 'OPEN_EXR'\n self.render_context.image_settings.file_format = 'PNG' \n self.render_context.image_settings.color_mode = 'RGB'\n self.render_context.image_settings.color_depth = '8'\n bpy.context.scene.view_settings.view_transform = 'Raw'\n bpy.context.scene.render.filter_size = 0\n self.render_context.resolution_x = 640\n self.render_context.resolution_y = 360\n elif output_mode == \"Normal\":\n self.render_context.image_settings.file_format = 'OPEN_EXR'\n self.render_context.image_settings.color_mode = 'RGB'\n bpy.context.scene.view_settings.view_transform = 'Raw'\n bpy.context.scene.render.filter_size = 1.5\n self.render_context.resolution_x = 640\n self.render_context.resolution_y = 360\n else:\n raise NotImplementedError\n\n def renderEngineSelect(self, engine_mode):\n\n if engine_mode == \"CYCLES\":\n self.render_context.engine = 'CYCLES'\n bpy.context.scene.cycles.progressive = 'BRANCHED_PATH'\n bpy.context.scene.cycles.use_denoising = True\n bpy.context.scene.cycles.denoiser = 'NLM'\n bpy.context.scene.cycles.film_exposure = 1.0\n bpy.context.scene.cycles.aa_samples = CYCLES_SAMPLE\n\n ## Set the device_type\n bpy.context.preferences.addons[\"cycles\"].preferences.compute_device_type = \"CUDA\" # or \"OPENCL\"\n\n ## get_devices() to let Blender detects GPU device\n cuda_devices, _ = bpy.context.preferences.addons[\"cycles\"].preferences.get_devices()\n #print(bpy.context.preferences.addons[\"cycles\"].preferences.compute_device_type)\n for d in bpy.context.preferences.addons[\"cycles\"].preferences.devices:\n d[\"use\"] = 1 # Using all devices, include GPU and CPU\n #print(d[\"name\"], d[\"use\"])\n device_list = self.DEVICE_LIST\n activated_gpus = []\n for i, device in enumerate(cuda_devices):\n if (i in device_list):\n device.use = True\n activated_gpus.append(device.name)\n else:\n device.use = False\n\n\n elif engine_mode == \"EEVEE\":\n bpy.context.scene.render.engine = 'BLENDER_EEVEE'\n else:\n print(\"Not support the mode!\") \n\n\n def addBackground(self, size, position, scale, default_background_texture_path):\n # set the material of background \n material_name = \"default_background\"\n\n # test if material exists\n # if it does not exist, create it:\n material_background = (bpy.data.materials.get(material_name) or \n bpy.data.materials.new(material_name))\n\n # enable 'Use nodes'\n material_background.use_nodes = True\n node_tree = material_background.node_tree\n\n # remove default nodes\n material_background.node_tree.nodes.clear()\n\n # add new nodes \n node_1 = node_tree.nodes.new('ShaderNodeOutputMaterial')\n node_2 = node_tree.nodes.new('ShaderNodeBsdfPrincipled')\n node_3 = node_tree.nodes.new('ShaderNodeTexImage')\n\n # link nodes\n node_tree.links.new(node_1.inputs[0], node_2.outputs[0])\n node_tree.links.new(node_2.inputs[0], node_3.outputs[0])\n\n # add texture image\n node_3.image = bpy.data.images.load(filepath=default_background_texture_path)\n self.my_material['default_background'] = material_background\n\n # add background plane\n for i in range(-2, 3, 1):\n for j in range(-2, 3, 1):\n position_i_j = (i * size + position[0], j * size + position[1], position[2] - TABLE_CAD_MODEL_HEIGHT)\n bpy.ops.mesh.primitive_plane_add(size=size, enter_editmode=False, align='WORLD', location=position_i_j, scale=scale)\n bpy.ops.rigidbody.object_add()\n bpy.context.object.rigid_body.type = 'PASSIVE'\n bpy.context.object.rigid_body.collision_shape = 'BOX'\n for i in range(-2, 3, 1):\n for j in [-2, 2]:\n position_i_j = (i * size + position[0], j * size + position[1], position[2] - 0.25)# - TABLE_CAD_MODEL_HEIGHT)\n rotation_elur = (math.pi / 2., 0., 0.)\n bpy.ops.mesh.primitive_plane_add(size=size, enter_editmode=False, align='WORLD', location=position_i_j, rotation = rotation_elur)\n bpy.ops.rigidbody.object_add()\n bpy.context.object.rigid_body.type = 'PASSIVE'\n bpy.context.object.rigid_body.collision_shape = 'BOX' \n for j in range(-2, 3, 1):\n for i in [-2, 2]:\n position_i_j = (i * size + position[0], j * size + position[1], position[2] - 0.25)# - TABLE_CAD_MODEL_HEIGHT)\n rotation_elur = (0, math.pi / 2, 0)\n bpy.ops.mesh.primitive_plane_add(size=size, enter_editmode=False, align='WORLD', location=position_i_j, rotation = rotation_elur)\n bpy.ops.rigidbody.object_add()\n bpy.context.object.rigid_body.type = 'PASSIVE'\n bpy.context.object.rigid_body.collision_shape = 'BOX' \n count = 0\n for obj in bpy.data.objects:\n if obj.type == \"MESH\":\n obj.name = \"background_\" + str(count)\n obj.data.name = \"background_\" + str(count)\n obj.active_material = material_background\n count += 1\n\n self.background_added = True\n\n\n def clearModel(self):\n '''\n # delete all meshes\n for item in bpy.data.meshes:\n bpy.data.meshes.remove(item)\n for item in bpy.data.materials:\n bpy.data.materials.remove(item)\n '''\n\n # remove all objects except background\n for obj in bpy.data.objects:\n if obj.type == 'MESH' and not obj.name.split('_')[0] == 'background':\n bpy.data.meshes.remove(obj.data)\n for obj in bpy.data.objects:\n if obj.type == 'MESH' and not obj.name.split('_')[0] == 'background':\n bpy.data.objects.remove(obj, do_unlink=True)\n\n # remove all default material\n for mat in bpy.data.materials:\n name = mat.name.split('.')\n if name[0] == 'Material':\n bpy.data.materials.remove(mat)\n\n\n def loadModel(self, file_path):\n self.model_loaded = True\n try:\n if file_path.endswith('obj'):\n bpy.ops.import_scene.obj(filepath=file_path)\n elif file_path.endswith('3ds'):\n bpy.ops.import_scene.autodesk_3ds(filepath=file_path)\n elif file_path.endswith('dae'):\n # Must install OpenCollada. Please read README.md\n bpy.ops.wm.collada_import(filepath=file_path)\n else:\n self.model_loaded = False\n raise Exception(\"Loading failed: %s\" % (file_path))\n except Exception:\n self.model_loaded = False\n\n\n def render(self, image_name=\"tmp\", image_path=RENDERING_PATH):\n # Render the object\n if not self.model_loaded:\n print(\"[W]render: Model not loaded.\")\n return \n\n if self.render_mode == \"IR\":\n bpy.context.scene.use_nodes = False\n # set light and render mode\n self.lightModeSelect(\"IR\")\n self.outputModeSelect(\"IR\")\n self.renderEngineSelect(\"CYCLES\")\n\n elif self.render_mode == 'RGB':\n bpy.context.scene.use_nodes = False\n # set light and render mode\n self.lightModeSelect(\"RGB\")\n self.outputModeSelect(\"RGB\")\n self.renderEngineSelect(\"CYCLES\")\n\n elif self.render_mode == \"Mask\":\n bpy.context.scene.use_nodes = False\n # set light and render mode\n self.lightModeSelect(\"Mask\")\n self.outputModeSelect(\"Mask\")\n # self.renderEngineSelect(\"EEVEE\")\n self.renderEngineSelect(\"CYCLES\")\n bpy.context.scene.cycles.use_denoising = False\n bpy.context.scene.cycles.aa_samples = 1\n\n elif self.render_mode == \"NOCS\":\n bpy.context.scene.use_nodes = False\n # set light and render mode\n self.lightModeSelect(\"NOCS\")\n self.outputModeSelect(\"NOCS\")\n # self.renderEngineSelect(\"EEVEE\")\n self.renderEngineSelect(\"CYCLES\")\n bpy.context.scene.cycles.use_denoising = False\n bpy.context.scene.cycles.aa_samples = 1\n\n elif self.render_mode == \"Normal\":\n bpy.context.scene.use_nodes = True\n self.fileOutput.base_path = image_path.replace(\"normal\",\"depth\")\n self.fileOutput.file_slots[0].path = image_name[:4]+\"_#\"# + 'depth_#'\n\n # set light and render mode\n self.lightModeSelect(\"Normal\")\n self.outputModeSelect(\"Normal\")\n # self.renderEngineSelect(\"EEVEE\")\n self.renderEngineSelect(\"CYCLES\")\n bpy.context.scene.cycles.use_denoising = False\n bpy.context.scene.cycles.aa_samples = 32\n\n else:\n print(\"[W]render: The render mode is not supported\")\n return \n\n bpy.context.scene.render.filepath = os.path.join(image_path, image_name)\n bpy.ops.render.render(write_still=True) # save straight to file\n\n\n def set_material_randomize_mode(self, class_material_pairs, mat_randomize_mode, instance, material_type_in_mixed_mode):\n if mat_randomize_mode in ['mixed','diffuse','transparent','specular_tex','specular_texmix','specular_and_transparent']:\n if material_type_in_mixed_mode == 'raw':\n print(\"[V]set_material_randomize_mode\", instance.name, 'material type: raw')\n set_modify_raw_material(instance)\n else:\n material = random.sample(self.my_material[material_type_in_mixed_mode], 1)[0]\n print(\"[V]set_material_randomize_mode\", instance.name, 'material type: ', material_type_in_mixed_mode)\n ## graspnet\n set_modify_material(instance, material, self.obj_texture_img_list, mat_randomize_mode=mat_randomize_mode)\n elif mat_randomize_mode == 'specular':\n material = random.sample(self.my_material[material_type_in_mixed_mode], 1)[0]\n print(\"[V]set_material_randomize_mode\", instance.name, 'material type: ', material_type_in_mixed_mode)\n set_modify_material(instance, material, self.obj_texture_img_list, mat_randomize_mode=mat_randomize_mode,\n is_transfer=False)\n else:\n raise NotImplementedError(\"No such mat_randomize_mode!\")\n\n\n def get_instance_pose(self):\n instance_pose = {}\n bpy.context.view_layer.update()\n cam = self.camera_l\n mat_rot_x = Matrix.Rotation(math.radians(180.0), 4, 'X')\n for obj in bpy.data.objects:\n if obj.type == 'MESH' and not obj.name.split('_')[0] == 'background':\n instance_id = obj.name.split('_')[0]\n mat_rel = cam.matrix_world.inverted() @ obj.matrix_world\n # location\n relative_location = [mat_rel.translation[0],\n - mat_rel.translation[1],\n - mat_rel.translation[2]]\n # rotation\n # relative_rotation_euler = mat_rel.to_euler() # must be converted from radians to degrees\n relative_rotation_quat = [mat_rel.to_quaternion()[0],\n mat_rel.to_quaternion()[1],\n mat_rel.to_quaternion()[2],\n mat_rel.to_quaternion()[3]]\n quat_x = [0, 1, 0, 0]\n quat = quanternion_mul(quat_x, relative_rotation_quat)\n quat = [quat[0], - quat[1], - quat[2], - quat[3]]\n instance_pose[str(instance_id)] = [quat, relative_location]\n\n return instance_pose\n\n\n def check_visible(self, threshold=(0.1, 0.9, 0.1, 0.9)):\n w_min, x_max, h_min, h_max = threshold\n visible_objects_list = []\n bpy.context.view_layer.update()\n cs, ce = self.camera_l.data.clip_start, self.camera_l.data.clip_end\n for obj in bpy.data.objects:\n if obj.type == 'MESH' and not obj.name.split('_')[0] == 'background':\n obj_center = obj.matrix_world.translation\n co_ndc = world_to_camera_view(scene, self.camera_l, obj_center)\n if (w_min < co_ndc.x < x_max and\n h_min < co_ndc.y < h_max and\n cs < co_ndc.z < ce):\n obj.select_set(True)\n visible_objects_list.append(obj)\n else:\n obj.select_set(False)\n return visible_objects_list\n\n\ndef setModelPosition(instance, location, quaternion):\n instance.rotation_mode = 'QUATERNION'\n instance.rotation_quaternion[0] = quaternion[0]\n instance.rotation_quaternion[1] = quaternion[1]\n instance.rotation_quaternion[2] = quaternion[2]\n instance.rotation_quaternion[3] = quaternion[3]\n instance.location = location\n###\n\ndef setRigidBody(instance):\n bpy.context.view_layer.objects.active = instance \n object_single = bpy.context.active_object\n\n # add rigid body constraints to cube\n bpy.ops.rigidbody.object_add()\n bpy.context.object.rigid_body.mass = 1\n bpy.context.object.rigid_body.kinematic = True\n bpy.context.object.rigid_body.collision_shape = 'CONVEX_HULL'\n bpy.context.object.rigid_body.restitution = 0.01\n bpy.context.object.rigid_body.angular_damping = 0.8\n bpy.context.object.rigid_body.linear_damping = 0.99\n\n bpy.context.object.rigid_body.kinematic = False\n object_single.keyframe_insert(data_path='rigid_body.kinematic', frame=0)\n\n\ndef set_visiable_objects(visible_objects_list):\n for obj in bpy.data.objects:\n if obj.type == 'MESH' and not obj.name.split('_')[0] == 'background':\n if obj in visible_objects_list:\n obj.hide_render = False\n else:\n obj.hide_render = True\n\n\ndef generate_CAD_model_list(scene_type, urdf_path_list, obj_uid_list):\n CAD_model_list = {}\n ###\n for idx in range(len(urdf_path_list)):\n urdf_path = urdf_path_list[idx]\n obj_uid = obj_uid_list[idx]\n class_name = 'other'\n urdf_path = str(urdf_path).replace(\"\\\\\",\"/\").split(\"/\")\n if scene_type == \"blocks\":\n instance_path = \"/\".join(urdf_path[:-1]) + \"/\" + urdf_path[-1][:-5]+\".obj\"\n else:\n instance_path = \"/\".join(urdf_path[:-1])+\"/\"+urdf_path[-1][:-5]+\"_visual.obj\"\n class_list = []\n class_list.append([instance_path, class_name, obj_uid])\n if class_name == 'other' and 'other' in CAD_model_list:\n CAD_model_list[class_name] = CAD_model_list[class_name] + class_list\n else:\n CAD_model_list[class_name] = class_list\n \n return CAD_model_list\n\n\ndef generate_material_type(obj_name, class_material_pairs, instance_material_except_pairs, instance_material_include_pairs, material_class_instance_pairs, material_type):\n ###\n specular_type_for_ins_list = []\n transparent_type_for_ins_list = []\n diffuse_type_for_ins_list = []\n for key in instance_material_except_pairs:\n if key in material_class_instance_pairs['specular']:\n specular_type_for_ins_list.append(key)\n elif key in material_class_instance_pairs['transparent']:\n transparent_type_for_ins_list.append(key)\n elif key in material_class_instance_pairs['diffuse']:\n diffuse_type_for_ins_list.append(key)\n for key in instance_material_include_pairs:\n if key in material_class_instance_pairs['specular']:\n specular_type_for_ins_list.append(key)\n elif key in material_class_instance_pairs['transparent']:\n transparent_type_for_ins_list.append(key)\n elif key in material_class_instance_pairs['diffuse']:\n diffuse_type_for_ins_list.append(key)\n\n if material_type == \"transparent\":\n return random.sample(transparent_type_for_ins_list, 1)[0]\n elif material_type == \"diffuse\":\n return random.sample(diffuse_type_for_ins_list, 1)[0]\n elif material_type == \"specular\" or material_type == \"specular_tex\" or material_type == \"specular_texmix\":\n return random.sample(specular_type_for_ins_list, 1)[0]\n elif material_type == \"specular_and_transparent\":\n flag = random.randint(0, 2)\n if flag == 0:\n return random.sample(specular_type_for_ins_list, 1)[0] ### 'specular'\n else:\n return random.sample(transparent_type_for_ins_list, 1)[0] ### 'transparent'\n elif material_type == \"mixed\":\n # randomly pick material class\n flag = random.randint(0, 2) # D:S:T=1:2:2\n # select the raw material\n if flag == 0:\n return random.sample(diffuse_type_for_ins_list, 1)[0] ### 'diffuse'\n # select one from specular and transparent\n elif flag == 1:\n return random.sample(specular_type_for_ins_list, 1)[0] ### 'specular'\n else:\n return random.sample(transparent_type_for_ins_list, 1)[0] ### 'transparent'\n else:\n raise ValueError(f\"Material type error: {material_type}\")", "repo_name": "PKU-EPIC/GraspNeRF", "sub_path": "src/rd/render_utils.py", "file_name": "render_utils.py", "file_ext": "py", "file_size_in_byte": 64167, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 92, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.getcwd", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 20, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 23, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 25, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 182, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 183, "usage_type": "attribute"}, {"api_name": "math.cos", "line_number": 184, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 185, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 185, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 186, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 190, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 191, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 192, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 193, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 194, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 195, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 205, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 206, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 207, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 211, "usage_type": "call"}, {"api_name": "math.acos", "line_number": 214, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 216, "usage_type": "attribute"}, {"api_name": "math.acos", "line_number": 220, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 232, "usage_type": "attribute"}, {"api_name": "math.sqrt", "line_number": 233, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 237, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 238, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 239, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 240, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 291, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 292, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 293, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 294, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 295, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 318, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 319, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 320, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 321, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 322, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 363, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 364, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 369, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 369, "usage_type": "call"}, {"api_name": "numpy.linalg.svd", "line_number": 370, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 370, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 371, "usage_type": "call"}, {"api_name": "numpy.linalg.det", "line_number": 373, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 373, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 377, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 384, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 385, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 386, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 387, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 388, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 391, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 392, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 393, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 394, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 397, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 397, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 398, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 399, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 402, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 402, "usage_type": "attribute"}, {"api_name": "numpy.cross", "line_number": 403, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 403, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 403, "usage_type": "attribute"}, {"api_name": "numpy.cross", "line_number": 404, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 404, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 404, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 407, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 410, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 428, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 434, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 435, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 438, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 439, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 442, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 443, "usage_type": "attribute"}, {"api_name": "math.sin", "line_number": 453, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 453, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 454, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 455, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 456, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 458, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 460, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 460, "usage_type": "attribute"}, {"api_name": "numpy.cross", "line_number": 461, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 461, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 461, "usage_type": "attribute"}, {"api_name": "numpy.cross", "line_number": 462, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 462, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 462, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 465, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 468, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 485, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 487, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 488, "usage_type": "call"}, {"api_name": "numpy.cross", "line_number": 489, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 501, "usage_type": "attribute"}, {"api_name": "bpy.data.meshes.remove", "line_number": 502, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 502, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 504, "usage_type": "attribute"}, {"api_name": "bpy.data.cameras.remove", "line_number": 505, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 505, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 507, "usage_type": "attribute"}, {"api_name": "bpy.data.lights.remove", "line_number": 508, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 508, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 510, "usage_type": "attribute"}, {"api_name": "bpy.data.objects.remove", "line_number": 511, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 511, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 513, "usage_type": "attribute"}, {"api_name": "bpy.data.cameras.new", "line_number": 516, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 516, "usage_type": "attribute"}, {"api_name": "bpy.data.objects.new", "line_number": 517, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 517, "usage_type": "attribute"}, {"api_name": "bpy.context.collection.objects.link", "line_number": 518, "usage_type": "call"}, {"api_name": "bpy.context", "line_number": 518, "usage_type": "attribute"}, {"api_name": "bpy.data.cameras.new", "line_number": 521, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 521, "usage_type": "attribute"}, {"api_name": "bpy.data.objects.new", "line_number": 522, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 522, "usage_type": "attribute"}, {"api_name": "bpy.context.collection.objects.link", "line_number": 523, "usage_type": "call"}, {"api_name": "bpy.context", "line_number": 523, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 525, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 526, "usage_type": "attribute"}, {"api_name": "bpy.data.lights.new", "line_number": 534, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 534, "usage_type": "attribute"}, {"api_name": "bpy.data.objects.new", "line_number": 535, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 535, "usage_type": "attribute"}, {"api_name": "bpy.context.collection.objects.link", "line_number": 536, "usage_type": "call"}, {"api_name": "bpy.context", "line_number": 536, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 538, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 568, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 569, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 570, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 571, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 575, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 579, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 580, "usage_type": "attribute"}, {"api_name": "bpy.data.images.load", "line_number": 610, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 610, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 612, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 613, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 614, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 616, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 617, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 618, "usage_type": "call"}, {"api_name": "bpy.data.images.load", "line_number": 622, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 622, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 622, "usage_type": "call"}, {"api_name": "os.path", "line_number": 622, "usage_type": "attribute"}, {"api_name": "bpy.data.images.load", "line_number": 626, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 626, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 626, "usage_type": "call"}, {"api_name": "os.path", "line_number": 626, "usage_type": "attribute"}, {"api_name": "bpy.data.images.load", "line_number": 630, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 630, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 630, "usage_type": "call"}, {"api_name": "os.path", "line_number": 630, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 632, "usage_type": "call"}, {"api_name": "os.path", "line_number": 632, "usage_type": "attribute"}, {"api_name": "bpy.data.images.load", "line_number": 636, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 636, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 636, "usage_type": "call"}, {"api_name": "os.path", "line_number": 636, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 641, "usage_type": "attribute"}, {"api_name": "random.uniform", "line_number": 674, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 675, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 681, "usage_type": "attribute"}, {"api_name": "bpy.data.materials.get", "line_number": 695, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 695, "usage_type": "attribute"}, {"api_name": "bpy.data.materials.new", "line_number": 695, "usage_type": "call"}, {"api_name": "bpy.data.materials.get", "line_number": 721, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 721, "usage_type": "attribute"}, {"api_name": "bpy.data.materials.new", "line_number": 722, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 722, "usage_type": "attribute"}, {"api_name": "bpy.data.materials.get", "line_number": 748, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 748, "usage_type": "attribute"}, {"api_name": "bpy.data.materials.new", "line_number": 748, "usage_type": "call"}, {"api_name": "bpy.data.materials.get", "line_number": 787, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 787, "usage_type": "attribute"}, {"api_name": "bpy.data.materials.new", "line_number": 787, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 971, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1017, "usage_type": "attribute"}, {"api_name": "random.uniform", "line_number": 1024, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 1028, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 1075, "usage_type": "attribute"}, {"api_name": "random.uniform", "line_number": 1080, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 1081, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 1085, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1096, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1097, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1105, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1106, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1112, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1113, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1121, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1122, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1128, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1129, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1139, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1140, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1141, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1142, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1143, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1146, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1149, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1151, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1165, "usage_type": "attribute"}, {"api_name": "bpy.data.materials.get", "line_number": 1176, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 1176, "usage_type": "attribute"}, {"api_name": "bpy.data.materials.new", "line_number": 1177, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 1177, "usage_type": "attribute"}, {"api_name": "bpy.data.images.load", "line_number": 1196, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 1196, "usage_type": "attribute"}, {"api_name": "bpy.ops.mesh.primitive_plane_add", "line_number": 1203, "usage_type": "call"}, {"api_name": "bpy.ops", "line_number": 1203, "usage_type": "attribute"}, {"api_name": "bpy.ops.rigidbody.object_add", "line_number": 1204, "usage_type": "call"}, {"api_name": "bpy.ops", "line_number": 1204, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1205, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1206, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 1210, "usage_type": "attribute"}, {"api_name": "bpy.ops.mesh.primitive_plane_add", "line_number": 1211, "usage_type": "call"}, {"api_name": "bpy.ops", "line_number": 1211, "usage_type": "attribute"}, {"api_name": "bpy.ops.rigidbody.object_add", "line_number": 1212, "usage_type": "call"}, {"api_name": "bpy.ops", "line_number": 1212, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1213, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1214, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 1218, "usage_type": "attribute"}, {"api_name": "bpy.ops.mesh.primitive_plane_add", "line_number": 1219, "usage_type": "call"}, {"api_name": "bpy.ops", "line_number": 1219, "usage_type": "attribute"}, {"api_name": "bpy.ops.rigidbody.object_add", "line_number": 1220, "usage_type": "call"}, {"api_name": "bpy.ops", "line_number": 1220, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1221, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1222, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 1224, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 1244, "usage_type": "attribute"}, {"api_name": "bpy.data.meshes.remove", "line_number": 1246, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 1246, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 1247, "usage_type": "attribute"}, {"api_name": "bpy.data.objects.remove", "line_number": 1249, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 1249, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 1252, "usage_type": "attribute"}, {"api_name": "bpy.data.materials.remove", "line_number": 1255, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 1255, "usage_type": "attribute"}, {"api_name": "bpy.ops.import_scene.obj", "line_number": 1262, "usage_type": "call"}, {"api_name": "bpy.ops", "line_number": 1262, "usage_type": "attribute"}, {"api_name": "bpy.ops.import_scene.autodesk_3ds", "line_number": 1264, "usage_type": "call"}, {"api_name": "bpy.ops", "line_number": 1264, "usage_type": "attribute"}, {"api_name": "bpy.ops.wm.collada_import", "line_number": 1267, "usage_type": "call"}, {"api_name": "bpy.ops", "line_number": 1267, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1282, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1289, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1296, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1302, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1303, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1306, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1312, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1313, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1316, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1325, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1326, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1332, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 1332, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1332, "usage_type": "attribute"}, {"api_name": "bpy.ops.render.render", "line_number": 1333, "usage_type": "call"}, {"api_name": "bpy.ops", "line_number": 1333, "usage_type": "attribute"}, {"api_name": "rd.modify_material.set_modify_raw_material", "line_number": 1340, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 1342, "usage_type": "call"}, {"api_name": "rd.modify_material.set_modify_material", "line_number": 1345, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 1347, "usage_type": "call"}, {"api_name": "rd.modify_material.set_modify_material", "line_number": 1349, "usage_type": "call"}, {"api_name": "bpy.context.view_layer.update", "line_number": 1357, "usage_type": "call"}, {"api_name": "bpy.context", "line_number": 1357, "usage_type": "attribute"}, {"api_name": "mathutils.Matrix.Rotation", "line_number": 1359, "usage_type": "call"}, {"api_name": "mathutils.Matrix", "line_number": 1359, "usage_type": "name"}, {"api_name": "math.radians", "line_number": 1359, "usage_type": "call"}, {"api_name": "bpy.data", "line_number": 1360, "usage_type": "attribute"}, {"api_name": "bpy.context.view_layer.update", "line_number": 1385, "usage_type": "call"}, {"api_name": "bpy.context", "line_number": 1385, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 1387, "usage_type": "attribute"}, {"api_name": "bpy_extras.object_utils.world_to_camera_view", "line_number": 1390, "usage_type": "call"}, {"api_name": "bpy.context", "line_number": 1411, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1412, "usage_type": "attribute"}, {"api_name": "bpy.ops.rigidbody.object_add", "line_number": 1415, "usage_type": "call"}, {"api_name": "bpy.ops", "line_number": 1415, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1416, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1417, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1418, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1419, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1420, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1421, "usage_type": "attribute"}, {"api_name": "bpy.context", "line_number": 1423, "usage_type": "attribute"}, {"api_name": "bpy.data", "line_number": 1428, "usage_type": "attribute"}, {"api_name": "random.sample", "line_number": 1479, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 1481, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 1483, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 1485, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 1487, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 1489, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 1492, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 1495, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 1498, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 1500, "usage_type": "call"}]} +{"seq_id": "27897716078", "text": "import numpy as np\nfrom math import log\nfrom scipy.special import erf\nimport matplotlib.pyplot as plt\n\n\ndef modulate(x, constel):\n return constel[x]\n\n\ndef demodulate(x, constel):\n samples = len(x)\n result = np.zeros(x.shape)\n for i in range(samples):\n # Медленно, но работает для любой модуляции\n j = np.argmin(np.abs(constel - x[i]))\n result[i] = j\n \n return result.astype(int)\n\n\ndef norm(constel):\n dot = np.dot(constel, np.conj(constel))\n return constel / np.sqrt(dot / len(constel))\n\n\ndef constellation(M):\n if np.fix(log(M, 4)) != log(M,4):\n raise ValueError(\"M must be power of 4!\")\n\n nbits = int(np.log2(M))\n x = np.arange(M)\n\n nbitsBy2 = nbits >> 1\n symbolI = x >> nbitsBy2\n symbolQ = x & ((M-1) >> nbitsBy2)\n\n i = 1\n while i < nbitsBy2:\n tmpI = symbolI\n tmpI = tmpI >> i\n symbolI = symbolI ^ tmpI\n\n tmpQ = symbolQ\n tmpQ = tmpQ >> i\n symbolQ = symbolQ ^ tmpQ\n i = i + i\n\n gray = (symbolI << nbitsBy2) + symbolQ\n\n x = x[gray]\n c = int(np.sqrt(M))\n I = -2 * np.mod(x, c) + c - 1\n Q = 2 * np.floor(x / c) - c + 1\n IQ = I + 1j*Q\n IQ = -np.transpose(np.reshape(IQ, (c, c)))\n return norm(IQ.flatten())\n\n\ndef qfunc(x):\n return 0.5 - 0.5 * erf(x / np.sqrt(2))\n\n\n# Only for square QAM\n# Source: https://www.mathworks.com/help/comm/ug/analytical-expressions-used-in-berawgn-function-and-bit-error-rate-analysis-app.html \ndef theory_ber(EbN0, M):\n if np.fix(log(M, 4)) != log(M,4):\n raise ValueError(\"M must be power of 4!\")\n \n if M == 4:\n ber = qfunc(np.sqrt(2*EbN0))\n elif M == 16:\n ber = 3/4*qfunc(np.sqrt(4/5*EbN0)) \n + 1/2*qfunc(3*np.sqrt(4/5*EbN0)) \n - 1/4*qfunc(5*np.sqrt(4/5*EbN0))\n elif M == 64:\n ber = 7/12*qfunc(np.sqrt(2/7*EbN0)) \n + 1/2*qfunc(3*np.sqrt(2/7*EbN0)) \n - 1/12*qfunc(5*np.sqrt(2/7*EbN0)) \n + 1/12*qfunc(9*np.sqrt(2/7*EbN0)) \n - 1/12*qfunc(13*np.sqrt(2/7*EbN0))\n else:\n k = np.log2(M)\n c = np.sqrt(M)\n ber = np.zeros(EbN0.shape)\n for i in range(1, round(np.log2(c)) + 1):\n berk = np.zeros(EbN0.shape)\n for j in range(0,round((1-2**(-i))*c)):\n berk = berk + (-1)**(np.floor(j*2**(i-1)/c)) * (2**(i-1) \n - np.floor(j*2**(i-1)/c+1/2)) * qfunc((2*j+1) * np.sqrt(6*k*EbN0/(2*(M-1))))\n berk = berk * 2 / c\n ber = ber + berk\n\n ber = ber / np.log2(c)\n\n return ber\n\n\ndef plot_constel(iq):\n count = len(iq)\n bits = np.log2(count)\n spec = '#0{}b'.format((bits + 2).astype(int))\n\n plt.figure(dpi = 80)\n for n in range(count):\n factor = np.log2(np.sqrt(count))\n d = 0.04 / factor\n i = np.real(iq[n])\n q = np.imag(iq[n])\n label = format(n, spec)\n plt.text(i + d, q + d, label[2::], fontsize = 30 / factor)\n\n scale = np.max(np.abs(iq))\n plt.scatter(np.real(iq), np.imag(iq), s = 120 / factor)\n plt.title('QAM{} constellation'.format(count))\n plt.xlim([-scale, scale])\n plt.ylim([-scale, scale])\n plt.xlabel('I')\n plt.ylabel('Q')\n plt.grid()\n plt.show()\n\n\ndef add_ber_plot(EbN0, OSNR, BER, spec='--'):\n plt.subplot(1,2,1)\n plt.semilogy(EbN0, BER, spec, markersize=8, linewidth=3)\n plt.xlabel('Eb/N0, dB')\n plt.ylabel('BER')\n plt.grid(b=True, which='major', color='k', linestyle='-')\n plt.grid(b=True, which='minor', color='k', linestyle='--')\n\n plt.subplot(1,2,2)\n plt.semilogy(OSNR, BER, spec, markersize=8, linewidth=3)\n plt.xlabel('OSNR, dB')\n plt.ylabel('BER')\n plt.grid(b=True, which='major', color='k', linestyle='-')\n plt.grid(b=True, which='minor', color='k', linestyle='--')\n\n\ndef hamming(str1,str2):\n result=0\n for _,(i,j) in enumerate(zip(str1, str2)):\n if i!=j:\n result+=1\n return result\n\n\ndef ber(input, output, M):\n bits_per_symbol = np.log2(M)\n symbols = len(input)\n diff = []\n for i in range(symbols):\n in_bits = format(input[i], '016b')\n out_bits = format(output[i], '016b')\n diff.append(hamming(in_bits, out_bits))\n\n return np.sum(diff) / (symbols * bits_per_symbol)\n\n\ndef save_ber(OSNR_dB, EbN0_db, BER, M):\n data = {\n 'M' : M,\n 'OSNR_dB' : OSNR_dB,\n 'EbN0_db' : EbN0_db,\n 'BER' : BER\n }\n np.save('QAM{}.npy'.format(M), data)", "repo_name": "Dirog/qam", "sub_path": "qam.py", "file_name": "qam.py", "file_ext": "py", "file_size_in_byte": 4440, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.zeros", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.conj", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.fix", "line_number": 28, "usage_type": "call"}, {"api_name": "math.log", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.log2", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.mod", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 56, "usage_type": "call"}, {"api_name": "scipy.special.erf", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.fix", "line_number": 67, "usage_type": "call"}, {"api_name": "math.log", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.log2", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.log2", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.log2", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.log2", "line_number": 101, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 104, "usage_type": "name"}, {"api_name": "numpy.log2", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.real", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.imag", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.text", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 111, "usage_type": "name"}, {"api_name": "numpy.max", "line_number": 113, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "numpy.real", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.imag", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 115, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 117, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 117, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 118, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 121, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.semilogy", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 126, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 129, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 129, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 130, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 132, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 132, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.semilogy", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 133, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 134, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 134, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 135, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 135, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 136, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 136, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 137, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 137, "usage_type": "name"}, {"api_name": "numpy.log2", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 167, "usage_type": "call"}]} +{"seq_id": "8276734940", "text": "import praw\nimport pandas as pd\nimport requests\nfrom textblob import TextBlob\nimport plotly.express as px\n\ndef get_sentiment(text):\n blob = TextBlob(text)\n sentiment = blob.sentiment.polarity\n return sentiment\n\n\ndef get_posts(subreddit, limit):\n posts = []\n for post in subreddit.hot(limit=limit):\n posts.append([post.title, post.score, post.id, post.subreddit, post.url, post.num_comments, post.selftext, post.created])\n return pd.DataFrame(posts, columns=['title', 'score', 'id', 'subreddit', 'url', 'num_comments', 'body', 'created'])\n\n\nurl = \"https://www.sec.gov/files/company_tickers.json\"\nresponse = requests.get(url)\n\ndata = response.json()\ntickers = [info['ticker'] for info in data.values()]\ncompanies = {info['ticker']: info['title'] for info in data.values()}\n\n\nreddit = praw.Reddit(client_id='######',\n client_secret='########',\n user_agent='#######')\n\nsubreddit = reddit.subreddit('wallstreetbets')\nposts = get_posts(subreddit, 1000)\n\nposts['sentiment'] = posts['body'].apply(get_sentiment)\n\nsentiments = {ticker: [] for ticker in tickers}\nfor ticker in tickers:\n relevant_posts = posts[posts['body'].str.contains(ticker)]\n sentiments[ticker] = list(relevant_posts['sentiment'])\n\nsentiments_df = pd.DataFrame(list(sentiments.items()), columns=['Ticker', 'SentimentList'])\n\nsentiments_df['NumPosts'] = sentiments_df['SentimentList'].apply(len)\nsentiments_df = sentiments_df[sentiments_df['NumPosts'] >= 5]\n\nsentiments_df['Sentiment'] = sentiments_df['SentimentList'].apply(lambda x: sum(x) / len(x))\n\nsentiments_df = sentiments_df.sort_values('Sentiment')\n\nfig = px.bar(sentiments_df, x='Ticker', y='Sentiment', \n title='Sentiment Analysis of Stocks on r/wallstreetbets',\n labels={'Sentiment': 'Sentiment', 'Ticker': 'Stock'},\n hover_data=['Ticker'])\n\nfig.show()", "repo_name": "dhruvnanavati/Portfolio", "sub_path": "College/Python/wsb_crawler.py", "file_name": "wsb_crawler.py", "file_ext": "py", "file_size_in_byte": 1881, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "textblob.TextBlob", "line_number": 8, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 17, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 21, "usage_type": "call"}, {"api_name": "praw.Reddit", "line_number": 28, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 42, "usage_type": "call"}, {"api_name": "plotly.express.bar", "line_number": 51, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 51, "usage_type": "name"}]} +{"seq_id": "21590752747", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nfrom matplotlib.patches import Circle\nimport cv22_lab1_part3_utils as p3\n\ndef LoG(x, y, s):\n nom = y**2 + x**2 - 2*s**2 \n denom = 2*np.pi*(s**6)\n expo = np.exp(-(x**2 + y**2)/(2*s**2))\n return nom*expo/denom\n\ndef disk_strel(n):\n r = int(np.round(n))\n d = 2*r+1\n x = np.arange(d) - r\n y = np.arange(d) - r\n x, y = np.meshgrid(x,y)\n strel = x**2 + y**2 <= r**2\n return strel.astype(np.uint8)\n\ndef interest_points_visualization(I_, kp_data_, ax=None):\n I = np.array(I_)\n kp_data = np.array(kp_data_)\n assert(len(I.shape) == 2 or (len(I.shape) == 3 and I.shape[2] == 3))\n assert(len(kp_data.shape) == 2 and kp_data.shape[1] == 3)\n\n if ax is None:\n _, ax = plt.subplots()\n\n ax.set_aspect('equal')\n ax.imshow(I, 'gray')\n ax.tick_params(bottom=False, left=False, labelbottom=False, labelleft=False)\n\n for i in range(len(kp_data)):\n x, y, sigma = kp_data[i]\n circ = Circle((x, y), 3*sigma, edgecolor='g', fill=False, linewidth=1)\n ax.add_patch(circ)\n\n return ax\n\ndef EdgeDetect(img, s = 2, theta = 0.1, linear = False):\n n = int(np.ceil(3*s)*2 + 1)\n B = np.array([\n [0,1,0],\n [1,1,1],\n [0,1,0]\n ], dtype=np.uint8)\n G1D = cv2.getGaussianKernel(n, s)\n G2D = G1D @ G1D.T\n smoothed_img = cv2.filter2D(img, -1, G2D)\n \n if linear == True:\n kernel = np.zeros((n,n))\n x = y = np.linspace(-(n-1)/2, (n-1)/2, n)\n x, y = np.meshgrid(x, y)\n kernel = LoG(x, y, s)\n \n# =============================================================================\n# print (kernel)\n# plt.figure()\n# ax = plt.axes(projection='3d')\n# ax.plot_surface(x, y, kernel)\n# ax.set_xlabel('x')\n# ax.set_ylabel('y')\n# ax.set_zlabel('z')\n# =============================================================================\n \n laplacian = cv2.filter2D(img, -1, kernel)\n \n# =============================================================================\n# plt.figure()\n# plt.imshow(laplacian, 'gray')\n# =============================================================================\n \n else:\n dilated_img = cv2.dilate(smoothed_img, B)\n eroded_img = cv2.erode(smoothed_img, B)\n \n laplacian = dilated_img + eroded_img - 2*smoothed_img\n \n# =============================================================================\n# plt.figure()\n# plt.imshow(laplacian, 'gray')\n# =============================================================================\n \n _, binary_img = cv2.threshold(laplacian, 0, 1, cv2.THRESH_BINARY)\n y = cv2.dilate(binary_img, B) - cv2.erode(binary_img, B)\n ix, iy = np.gradient(smoothed_img)\n ig = np.sqrt(ix**2 + iy**2)\n max_g = ig.max()\n y_final = np.zeros((y.shape[0], y.shape[1]))\n \n for i in range(y.shape[0]):\n for j in range(y.shape[1]):\n if y[i][j] == 1 and ig[i][j] > theta*max_g:\n y_final[i][j] = 1\n\n return y_final\n\ndef CornerDetect(img, s = 2, r = 2.5, k = 0.05, theta = 0.005):\n n = int(np.ceil(3*s)*2 + 1)\n \n G1D = cv2.getGaussianKernel(n, s)\n G2D = G1D @ G1D.T\n r1D = cv2.getGaussianKernel(n, r)\n r2D = r1D @ r1D.T\n \n smoothed_img = cv2.filter2D(img, -1, G2D)\n ix, iy = np.gradient(smoothed_img)\n \n j1 = cv2.filter2D(ix*ix, -1, r2D)\n j2 = cv2.filter2D(ix*iy, -1, r2D)\n j3 = cv2.filter2D(iy*iy, -1, r2D)\n\n l1 = (j1 + j3 + np.sqrt((j1 - j3)*(j1 - j3) + 4*j2*j2))/2\n l2 = (j1 + j3 - np.sqrt((j1 - j3)*(j1 - j3) + 4*j2*j2))/2\n \n# =============================================================================\n# plt.figure()\n# plt.imshow(l1, 'gray')\n# plt.figure()\n# plt.imshow(l2, 'gray')\n# =============================================================================\n \n R = l1*l2 - k*(l1 + l2)*(l1 + l2)\n B_sq = disk_strel(n)\n Cond1 = (R==cv2.dilate(R,B_sq))\n Cond2 = (R > theta*R.max())\n\n R = Cond1*Cond2\n \n x = []\n y = []\n \n for i in range(R.shape[0]):\n for j in range(R.shape[1]):\n if R[i][j]:\n x.append(int(j))\n y.append(int(i))\n \n S = len(x)*[s]\n interest_points = np.array([x, y, S]).T\n \n return interest_points\n\ndef MultiscaleCornerDetect(img, s1 = 2, r = 2.5, k = 0.05, theta = 0.005, s2 = 1.5, N = 4):\n LoG = []\n i_points = []\n s = []\n for i in range(N):\n s.append(s1*s2**i)\n r = r*s2**i\n \n interest_points = CornerDetect(img, s[i], r, k, theta)\n i_points.append(interest_points)\n \n n = int(np.ceil(3*s[i])*2 + 1)\n \n G1D = cv2.getGaussianKernel(n, s[i])\n G2D = G1D @ G1D.T\n \n smoothed_img = cv2.filter2D(img, -1, G2D)\n ix, iy = np.gradient(smoothed_img)\n ixx, _ = np.gradient(ix)\n _, iyy = np.gradient(iy)\n LoG.append(s[i]**2*np.abs(ixx + iyy))\n \n interest_points = []\n for i, scale_points in enumerate(i_points):\n for points in scale_points:\n x = int(points[0])\n y = int(points[1])\n s = points[2]\n if i == 0 and LoG[i][y][x] > LoG[i+1][y][x]:\n interest_points.append([x, y, s])\n elif i == N-1 and LoG[i][y][x] > LoG[i-1][y][x]:\n interest_points.append([x, y, s])\n elif LoG[i][y][x] > LoG[i-1][y][x] and LoG[i][y][x] > LoG[i+1][y][x]:\n interest_points.append([x, y, s])\n return np.array(interest_points)\n \ndef BlobDetect(img, s = 2, theta = 0.005):\n n = int(np.ceil(3*s)*2 + 1)\n \n G1D = cv2.getGaussianKernel(n, s)\n G2D = G1D @ G1D.T\n \n smoothed_img = cv2.filter2D(img, -1, G2D)\n ix, iy = np.gradient(smoothed_img)\n ixx, ixy = np.gradient(ix)\n _, iyy = np.gradient(iy)\n \n R = ixx*iyy - ixy*ixy\n \n B_sq = disk_strel(n)\n Cond1 = (R==cv2.dilate(R,B_sq))\n Cond2 = (R > theta*R.max())\n \n R = Cond1*Cond2\n \n x = []\n y = []\n \n for i in range(R.shape[0]):\n for j in range(R.shape[1]):\n if R[i][j]:\n x.append(int(j))\n y.append(int(i))\n \n S = len(x)*[s]\n interest_points = np.array([x, y, S]).T\n \n return interest_points\n\ndef MultiscaleBlobDetect(img, s1 = 2, theta = 0.005, s2 = 1.5, N = 4):\n LoG = []\n i_points = []\n s = []\n for i in range(N):\n s.append(s1*s2**i)\n \n blobs = BlobDetect(img, s[i], theta)\n i_points.append(blobs)\n \n n = int(np.ceil(3*s[i])*2 + 1)\n \n G1D = cv2.getGaussianKernel(n, s[i])\n G2D = G1D @ G1D.T\n \n smoothed_img = cv2.filter2D(img, -1, G2D)\n ix, iy = np.gradient(smoothed_img)\n ixx, _ = np.gradient(ix)\n _, iyy = np.gradient(iy)\n \n LoG.append(s[i]**2*np.abs(ixx + iyy))\n \n blobs = []\n for i, scale_points in enumerate(i_points):\n for points in scale_points:\n x = int(points[0])\n y = int(points[1])\n s = points[2]\n if i == 0 and LoG[i][y][x] > LoG[i+1][y][x]:\n blobs.append([x, y, s])\n elif i == N-1 and LoG[i][y][x] > LoG[i-1][y][x]:\n blobs.append([x, y, s])\n elif LoG[i][y][x] > LoG[i-1][y][x] and LoG[i][y][x] > LoG[i+1][y][x]:\n blobs.append([x, y, s])\n return np.array(blobs)\n\ndef BoxFilter(int_img, s):\n n = int(np.ceil(3*s)*2 + 1)\n \n h = 4*np.floor(n/6) + 1\n \n if h%3 != 0:\n h = h + 3 - h%3\n if (h/3) % 2 == 0:\n h += 3\n \n w = 2*np.floor(n/6) + 1\n \n padded_int_img = np.pad(int_img, (int((h-1)/2), int((h-1)/2))) \n \n x = padded_int_img - np.roll(padded_int_img, int((h-1)/2-1), axis = 0) - np.roll(padded_int_img, int((w-1)/2 - 1), axis = 1) + np.roll(padded_int_img, (int((h-1)/2-1), int((w-1)/2 - 1)), axis = (0, 1))\n lxx = x + np.roll(x, int(2*h/3), axis=0) - 2*np.roll(x, int(h/3), axis=0)\n\n y = padded_int_img - np.roll(padded_int_img, int((h-1)/2 - 1), axis = 1) - np.roll(padded_int_img, int((w-1)/2 - 1), axis = 0) + np.roll(padded_int_img, (int((w-1)/2 - 1), int((h-1)/2 - 1)), axis = (0, 1))\n lyy = y + np.roll(y, int(2*h/3), axis=1) - 2*np.roll(y, int(h/3), axis=1)\n \n xy = padded_int_img - np.roll(padded_int_img, int((w-1)/2 - 1), axis = 0) - np.roll(padded_int_img, int((w-1)/2 - 1), axis = 1) + np.roll(padded_int_img, (int((w-1)/2 - 1), int((w-1)/2 - 1)), axis = (0, 1))\n lxy = xy + np.roll(xy, (int((w-1)/2 - 1), int((w-1)/2 - 1)), axis = (0, 1)) - np.roll(xy, int((w-1)/2 - 1), axis = 0) - np.roll(xy, int((w-1)/2 - 1), axis = 1) \n \n return lxx, lyy, lxy\n\ndef BlobDetectWithBoxFilters(img, s = 2, theta = 0.005):\n n = int(np.ceil(3*s)*2 + 1)\n G1D = cv2.getGaussianKernel(n, s)\n G2D = G1D @ G1D.T\n \n smoothed_img = cv2.filter2D(img, -1, G2D)\n \n int_img = np.cumsum(np.cumsum(smoothed_img, axis = 1), axis = 0)\n \n lxx, lyy, lxy = BoxFilter(int_img, s)\n ix, iy = np.gradient(smoothed_img)\n \n f = 15\n lxx = lxx[f:-f, f:-f]\n lyy = lyy[f:-f, f:-f]\n lxy = lxy[f:-f, f:-f]\n \n R = lxx*lyy - 0.81*lxy*lxy\n \n padx = img.shape[0] - R.shape[0]\n pady = img.shape[1] - R.shape[1]\n \n B_sq = disk_strel(n)\n Cond1 = (R ==cv2.dilate(R ,B_sq))\n Cond2 = (R > theta*R.max())\n \n R = Cond1*Cond2\n \n if padx>0 and pady>0:\n R = np.pad(R, ((padx//2 , padx//2), (pady//2, pady//2)))\n else:\n R = R[padx//2:-padx//2, pady//2:-pady//2]\n \n x = []\n y = []\n \n for i in range(R.shape[0]):\n for j in range(R.shape[1]):\n if R[i][j]:\n x.append(int(j))\n y.append(int(i))\n \n S = len(x)*[s]\n interest_points = np.array([x, y, S]).T\n \n return interest_points\n\ndef MultiscaleBlobDetectWithBoxFilters(img, s1 = 1.7, theta = 0.005, s2 = 1.3, N = 4):\n LoG = []\n i_points = []\n s = []\n for i in range(N):\n s.append(s1*s2**i)\n \n blobs = BlobDetectWithBoxFilters(img, s[i], theta)\n i_points.append(blobs)\n \n n = int(np.ceil(3*s[i])*2 + 1)\n G1D = cv2.getGaussianKernel(n, s[i])\n G2D = G1D @ G1D.T\n smoothed_img = cv2.filter2D(img, -1, G2D)\n \n ix, iy = np.gradient(smoothed_img)\n ixx, _ = np.gradient(ix)\n _, iyy = np.gradient(iy)\n LoG.append(s[i]**2*np.abs(ixx + iyy))\n \n blobs = []\n for i, scale_points in enumerate(i_points):\n for points in scale_points:\n x = int(points[0])\n y = int(points[1])\n s = points[2]\n if i == 0 and LoG[i][y][x] > LoG[i+1][y][x]:\n blobs.append([x, y, s])\n elif i == N-1 and LoG[i][y][x] > LoG[i-1][y][x]:\n blobs.append([x, y, s])\n elif LoG[i][y][x] > LoG[i-1][y][x] and LoG[i][y][x] > LoG[i+1][y][x]:\n blobs.append([x, y, s])\n \n return np.array(blobs)\n\ndef MatchingEvaluation(detect_function, SURF):\n detect_fun = lambda I: detect_function(I)\n \n if SURF:\n desc_fun = lambda I, kp: p3.featuresSURF(I, kp)\n else:\n desc_fun = lambda I, kp: p3.featuresHOG(I, kp) \n \n avg_scale_errors, avg_theta_errors = p3.matching_evaluation(detect_fun, desc_fun)\n\n for i in range(3):\n print('Avg. Scale Error for Image {}: {:.3f}'.format(i, avg_scale_errors[i]))\n print('Avg. Theta Error for Image {}: {:.3f}'.format(i, avg_theta_errors[i]))\n \ndef Scale_Theta_Errors_for_every_combination():\n detect_functions = [CornerDetect, MultiscaleCornerDetect, BlobDetect, MultiscaleBlobDetect, MultiscaleBlobDetectWithBoxFilters]\n flags = [True, False]\n for flag in flags:\n if flag:\n print(\"For SURF as local desciptor:\")\n print()\n else:\n print(\"For HOG as local desciptor:\")\n print()\n for detect_function in detect_functions:\n print('With ' + str(detect_function.__name__) + ' as a detect function:')\n MatchingEvaluation(detect_function, flag)\n print()\n \ndef Model_Training_and_Evaluation(detect_function, SURF):\n detect_fun = lambda I: detect_function(I)\n if SURF:\n a = 'SURF'\n desc_fun = lambda I, kp: p3.featuresSURF(I, kp)\n else:\n a = 'HOG'\n desc_fun = lambda I, kp: p3.featuresHOG(I, kp)\n \n feats = p3.FeatureExtraction(detect_fun, desc_fun)\n \n accs = []\n for k in range(5):\n x_train, y_train, x_test, y_test = p3.createTrainTest(feats, k)\n \n BOF_train, BOF_test = p3.BagOfWords(x_train, x_test)\n acc, preds, probas = p3.svm(BOF_train, y_train, BOF_test, y_test)\n accs.append(acc)\n \n print('Mean accuracy for ' + str(detect_function.__name__) + ' with ' + a + ' descriptors: {:.3f}%'.format(100.0*np.mean(accs)))\n \ndef Metric_Extraction_for_every_multiscale_detector():\n detect_functions = [MultiscaleCornerDetect, MultiscaleBlobDetect, MultiscaleBlobDetectWithBoxFilters]\n flags = [True, False]\n for flag in flags:\n if flag:\n print(\"For SURF as local desciptor:\")\n print()\n else:\n print(\"For HOG as local desciptor:\")\n print()\n for detect_function in detect_functions:\n print('With ' + str(detect_function.__name__) + ' as a detect function:')\n Model_Training_and_Evaluation(detect_function, flag)\n print()\n \nimg = cv2.imread(\"data_part12/edgetest_22.png\", cv2.IMREAD_GRAYSCALE)\nimg = img.astype(np.float64)/255\n# =============================================================================\n# plt.imshow(img, cmap='gray')\n# print(img.shape)\n# \n# =============================================================================\n# =============================================================================\n# Imax = img.max()\n# Imin = img.min()\n# PSNR1 = 20\n# PSNR2 = 10\n# std1 = (Imax - Imin)/10**(PSNR1/20)\n# std2 = (Imax - Imin)/10**(PSNR2/20)\n# n1 = np.random.normal(0, std1, size = (img.shape[0], img.shape[1]))\n# n2 = np.random.normal(0, std2, size = (img.shape[0], img.shape[1]))\n# =============================================================================\n# =============================================================================\n# plt.figure()\n# plt.imshow(img+n1, cmap = 'gray')\n# plt.figure()\n# plt.imshow(img+n2, cmap = 'gray')\n# =============================================================================\n\n# =============================================================================\n# n_img = img + n1\n# D = EdgeDetect(n_img, 2, linear = False)\n# =============================================================================\n# =============================================================================\n# plt.figure()\n# plt.imshow(D, 'gray')\n# =============================================================================\n\n# =============================================================================\n# B = np.array([\n# [0,1,0],\n# [1,1,1],\n# [0,1,0]\n# ], dtype=np.uint8)\n# \n# M = cv2.dilate(img, B) - cv2.erode(img, B)\n# #plt.figure()\n# #plt.imshow(M, 'gray')\n# T = M > 0.1\n# # =============================================================================\n# # plt.figure()\n# # plt.imshow(T, 'gray')\n# # =============================================================================\n# \n# counter = 0\n# \n# for i in range(D.shape[0]):\n# for j in range(D.shape[1]):\n# if D[i][j] == 1 and T[i][j] == 1:\n# counter += 1\n# \n# precision = counter/T.sum()\n# recall = counter/D.sum()\n# C = (precision + recall)/2\n# print (precision, recall, C)\n# =============================================================================\n\ncolored_duomo = cv2.imread(\"data_part12/duomo_edges.jpg\")\ncolored_duomo = cv2.cvtColor(colored_duomo, cv2.COLOR_BGR2RGB)\n\nduomo = cv2.cvtColor(colored_duomo, cv2.COLOR_RGB2GRAY)\nduomo = duomo.astype(np.float64)/255\n\n# =============================================================================\n# plt.figure()\n# plt.imshow(duomo, 'gray')\n# =============================================================================\n\n# =============================================================================\n# D2 = EdgeDetect(duomo, 2, linear = True)\n# plt.figure()\n# plt.imshow(D2, 'gray')\n# \n# M2 = cv2.dilate(duomo, B) - cv2.erode(duomo, B)\n# #plt.figure()\n# #plt.imshow(M, 'gray')\n# T2 = M2 > 0.1\n# plt.figure()\n# plt.imshow(T2, 'gray')\n# \n# counter = 0\n# \n# for i in range(D2.shape[0]):\n# for j in range(D2.shape[1]):\n# if D2[i][j] == 1 and T2[i][j] == 1:\n# counter += 1\n# \n# precision = counter/T2.sum()\n# recall = counter/D2.sum()\n# C2 = (precision + recall)/2\n# print (precision, recall, C2)\n# =============================================================================\n\ncolored_donuts = cv2.imread(\"data_part12/donuts.jpg\")\ncolored_donuts = cv2.cvtColor(colored_donuts, cv2.COLOR_BGR2RGB)\n\ndonuts = cv2.cvtColor(colored_donuts, cv2.COLOR_RGB2GRAY)\ndonuts = donuts.astype(np.float64)/255\n\ncolored_cells = cv2.imread(\"data_part12/cells.jpg\")\ncolored_cells = cv2.cvtColor(colored_cells, cv2.COLOR_BGR2RGB)\n\ncells = cv2.cvtColor(colored_cells, cv2.COLOR_RGB2GRAY)\ncells = cells.astype(np.float64)/255\n\n# =============================================================================\n# interest_points = CornerDetect(duomo, s = 2)\n# interest_points_visualization(colored_duomo, interest_points)\n# \n# multiscale_interest_points = MultiscaleCornerDetect(duomo)\n# interest_points_visualization(colored_duomo, multiscale_interest_points)\n# =============================================================================\n\n# =============================================================================\n# blobs = BlobDetect(cells, s = 2)\n# interest_points_visualization(colored_cells, blobs)\n# \n# multiscale_blobs = MultiscaleBlobDetect(cells)\n# interest_points_visualization(colored_cells, multiscale_blobs)\n# =============================================================================\n\n# =============================================================================\n# box_blobs = BlobDetectWithBoxFilters(donuts)\n# interest_points_visualization(colored_donuts, box_blobs)\n# \n# multiscale_box_blobs = MultiscaleBlobDetectWithBoxFilters(donuts)\n# interest_points_visualization(colored_donuts, multiscale_box_blobs)\n# =============================================================================\n\n#Scale_Theta_Errors_for_every_combination()\n\n#Metric_Extraction_for_every_multiscale_detector()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "repo_name": "dbakalis8/Computer_Vision_NTUA_2021-2022", "sub_path": "Lab1/cv_lab1.py", "file_name": "cv_lab1.py", "file_ext": "py", "file_size_in_byte": 18818, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.pi", "line_number": 9, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 20, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.patches.Circle", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 48, "usage_type": "attribute"}, {"api_name": "cv2.getGaussianKernel", "line_number": 49, "usage_type": "call"}, {"api_name": "cv2.filter2D", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 56, "usage_type": "call"}, {"api_name": "cv2.filter2D", "line_number": 69, "usage_type": "call"}, {"api_name": "cv2.dilate", "line_number": 77, "usage_type": "call"}, {"api_name": "cv2.erode", "line_number": 78, "usage_type": "call"}, {"api_name": "cv2.threshold", "line_number": 87, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 87, "usage_type": "attribute"}, {"api_name": "cv2.dilate", "line_number": 88, "usage_type": "call"}, {"api_name": "cv2.erode", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 102, "usage_type": "call"}, {"api_name": "cv2.getGaussianKernel", "line_number": 104, "usage_type": "call"}, {"api_name": "cv2.getGaussianKernel", "line_number": 106, "usage_type": "call"}, {"api_name": "cv2.filter2D", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 110, "usage_type": "call"}, {"api_name": "cv2.filter2D", "line_number": 112, "usage_type": "call"}, {"api_name": "cv2.filter2D", "line_number": 113, "usage_type": "call"}, {"api_name": "cv2.filter2D", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 117, "usage_type": "call"}, {"api_name": "cv2.dilate", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 158, "usage_type": "call"}, {"api_name": "cv2.getGaussianKernel", "line_number": 160, "usage_type": "call"}, {"api_name": "cv2.filter2D", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 164, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 165, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 167, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 184, "usage_type": "call"}, {"api_name": "cv2.getGaussianKernel", "line_number": 186, "usage_type": "call"}, {"api_name": "cv2.filter2D", "line_number": 189, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 190, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 191, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 192, "usage_type": "call"}, {"api_name": "cv2.dilate", "line_number": 197, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 212, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 226, "usage_type": "call"}, {"api_name": "cv2.getGaussianKernel", "line_number": 228, "usage_type": "call"}, {"api_name": "cv2.filter2D", "line_number": 231, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 232, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 233, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 234, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 236, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 250, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 253, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 255, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 262, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 264, "usage_type": "call"}, {"api_name": "numpy.roll", "line_number": 266, "usage_type": "call"}, {"api_name": "numpy.roll", "line_number": 267, "usage_type": "call"}, {"api_name": "numpy.roll", "line_number": 269, "usage_type": "call"}, {"api_name": "numpy.roll", "line_number": 270, "usage_type": "call"}, {"api_name": "numpy.roll", "line_number": 272, "usage_type": "call"}, {"api_name": "numpy.roll", "line_number": 273, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 278, "usage_type": "call"}, {"api_name": "cv2.getGaussianKernel", "line_number": 279, "usage_type": "call"}, {"api_name": "cv2.filter2D", "line_number": 282, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 284, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 287, "usage_type": "call"}, {"api_name": "cv2.dilate", "line_number": 300, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 306, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 320, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 334, "usage_type": "call"}, {"api_name": "cv2.getGaussianKernel", "line_number": 335, "usage_type": "call"}, {"api_name": "cv2.filter2D", "line_number": 337, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 339, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 340, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 341, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 342, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 357, "usage_type": "call"}, {"api_name": "cv22_lab1_part3_utils.featuresSURF", "line_number": 363, "usage_type": "call"}, {"api_name": "cv22_lab1_part3_utils.featuresHOG", "line_number": 365, "usage_type": "call"}, {"api_name": "cv22_lab1_part3_utils.matching_evaluation", "line_number": 367, "usage_type": "call"}, {"api_name": "cv22_lab1_part3_utils.featuresSURF", "line_number": 392, "usage_type": "call"}, {"api_name": "cv22_lab1_part3_utils.featuresHOG", "line_number": 395, "usage_type": "call"}, {"api_name": "cv22_lab1_part3_utils.FeatureExtraction", "line_number": 397, "usage_type": "call"}, {"api_name": "cv22_lab1_part3_utils.createTrainTest", "line_number": 401, "usage_type": "call"}, {"api_name": "cv22_lab1_part3_utils.BagOfWords", "line_number": 403, "usage_type": "call"}, {"api_name": "cv22_lab1_part3_utils.svm", "line_number": 404, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 407, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 424, "usage_type": "call"}, {"api_name": "cv2.IMREAD_GRAYSCALE", "line_number": 424, "usage_type": "attribute"}, {"api_name": "numpy.float64", "line_number": 425, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 486, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 487, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 487, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 489, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2GRAY", "line_number": 489, "usage_type": "attribute"}, {"api_name": "numpy.float64", "line_number": 490, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 522, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 523, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 523, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 525, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2GRAY", "line_number": 525, "usage_type": "attribute"}, {"api_name": "numpy.float64", "line_number": 526, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 528, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 529, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 529, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 531, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2GRAY", "line_number": 531, "usage_type": "attribute"}, {"api_name": "numpy.float64", "line_number": 532, "usage_type": "attribute"}]} +{"seq_id": "19464114157", "text": "from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin as DefaultUserAdmin\n\nfrom .models import Competition, Submission, User\n\n\nclass UserAdmin(DefaultUserAdmin):\n model = User\n list_display = [\n 'username',\n 'is_staff',\n 'is_active',\n 'last_login',\n ]\n list_filter = [\n 'is_staff',\n 'is_active',\n 'last_login',\n ]\n fieldsets = [\n (\n None,\n {'fields': ('username', 'password')},\n ),\n ('Permissions', {'fields': ['is_staff', 'is_superuser', 'is_active']}),\n ]\n add_fieldsets = [\n (\n 'User Details',\n {\n 'classes': ('wide',),\n 'fields': ('username'),\n },\n ),\n (\n 'Password Details',\n {\n 'classes': ('wide',),\n 'fields': ('password1', 'password2'),\n },\n ),\n ('Permissions', {'fields': ('is_staff', 'is_superuser', 'is_active')}),\n ]\n search_fields = ['id', 'username']\n ordering = ['username']\n\n\nclass CompetitionAdmin(admin.ModelAdmin):\n model = Competition\n list_display = [\n 'id',\n 'name',\n ]\n search_fields = ['id', 'name']\n ordering = ['name']\n\n\nclass SubmissionAdmin(admin.ModelAdmin):\n model = Submission\n list_display = ['id', 'name', 'score', 'user', 'competition']\n list_filter = [\n 'user',\n 'competition',\n ]\n search_fields = ['name', 'user', 'competition']\n ordering = ['name']\n\n\nadmin.site.register(User, UserAdmin)\nadmin.site.register(Competition, CompetitionAdmin)\nadmin.site.register(Submission, SubmissionAdmin)\n", "repo_name": "DurzoB5/Photocrowd-TT", "sub_path": "leaderboard/admin.py", "file_name": "admin.py", "file_ext": "py", "file_size_in_byte": 1699, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.contrib.auth.admin.UserAdmin", "line_number": 7, "usage_type": "name"}, {"api_name": "models.User", "line_number": 8, "usage_type": "name"}, {"api_name": "django.contrib.admin.ModelAdmin", "line_number": 48, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 48, "usage_type": "name"}, {"api_name": "models.Competition", "line_number": 49, "usage_type": "name"}, {"api_name": "django.contrib.admin.ModelAdmin", "line_number": 58, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 58, "usage_type": "name"}, {"api_name": "models.Submission", "line_number": 59, "usage_type": "name"}, {"api_name": "django.contrib.admin.site.register", "line_number": 69, "usage_type": "call"}, {"api_name": "models.User", "line_number": 69, "usage_type": "argument"}, {"api_name": "django.contrib.admin.site", "line_number": 69, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 69, "usage_type": "name"}, {"api_name": "django.contrib.admin.site.register", "line_number": 70, "usage_type": "call"}, {"api_name": "models.Competition", "line_number": 70, "usage_type": "argument"}, {"api_name": "django.contrib.admin.site", "line_number": 70, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 70, "usage_type": "name"}, {"api_name": "django.contrib.admin.site.register", "line_number": 71, "usage_type": "call"}, {"api_name": "models.Submission", "line_number": 71, "usage_type": "argument"}, {"api_name": "django.contrib.admin.site", "line_number": 71, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 71, "usage_type": "name"}]} +{"seq_id": "27569215964", "text": "from __future__ import annotations\n\nfrom typing import Optional, List, Tuple, TYPE_CHECKING\n\nimport app.engine.config as cf\nfrom app.engine import engine\nfrom app.engine.movement.movement_component import MovementComponent\nfrom app.engine.movement.unit_path_movement_component import UnitPathMovementComponent\nfrom app.utilities import utils\n\nif TYPE_CHECKING:\n from app.engine import camera, cursor\n\nimport logging\n\nclass MovementSystem:\n \"\"\"\n Operates upon MovementComponents and handles moving the camera around\n \"\"\"\n def __init__(self, cursor: Optional[cursor.BaseCursor], camera: Optional[camera.Camera]):\n self.cursor = cursor\n self.camera = camera\n\n self.moving_entities: List[MovementComponent] = []\n self.camera_follow: Tuple[int, int] = None # What position to be over\n self.camera_center: bool = False # Whether to center on the position\n\n def __len__(self):\n return len(self.moving_entities)\n\n def add(self, mc: MovementComponent):\n self.moving_entities.append(mc)\n\n def check_if_occupied_in_future(self, pos: Tuple[int, int]):\n for movement_component in self.moving_entities:\n if movement_component.get_end_goal() == pos:\n return movement_component.unit\n return None\n\n def is_moving(self, unit) -> bool:\n for movement_component in self.moving_entities:\n if movement_component.unit == unit:\n return True\n return False\n\n def stop(self, unit):\n \"\"\"\n # Stop all movement components associated with the given unit\n \"\"\"\n for movement_component in self.moving_entities:\n if movement_component.unit == unit:\n movement_component.finish() \n\n def begin_move(self, unit, path: List[Tuple[int, int]], \n event=False, follow=True, speed=0):\n \"\"\"\n # Used for simple movement of a unit in the normal way\n \"\"\"\n\n logging.info(\"Unit %s to begin moving\", unit)\n speed = speed or cf.SETTINGS['unit_speed']\n movement_component = \\\n UnitPathMovementComponent(unit, path, event, follow, speed=speed)\n self.moving_entities.append(movement_component)\n\n def update(self):\n current_time = engine.get_time()\n old_follow = self.camera_follow\n\n # Update all remaining entities\n for entity in self.moving_entities[:]:\n entity.update(current_time)\n if entity.follow:\n self.camera_follow = entity.get_camera_position()\n self.camera_center = entity.should_camera_center()\n # Remove inactive entities\n if not entity.active:\n self.moving_entities.remove(entity)\n\n # Update camera follow only if it's changed\n if self.camera_follow and old_follow != self.camera_follow:\n if self.cursor:\n self.cursor.set_pos(utils.round_pos(self.camera_follow))\n if self.camera and self.camera_center:\n self.camera.set_center(*self.camera_follow)\n", "repo_name": "ViolaBuddy/UnderTheShadowOfGrima", "sub_path": "lex-talionis/app/engine/movement/movement_system.py", "file_name": "movement_system.py", "file_ext": "py", "file_size_in_byte": 3089, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.TYPE_CHECKING", "line_number": 11, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 20, "usage_type": "name"}, {"api_name": "app.engine.cursor.BaseCursor", "line_number": 20, "usage_type": "attribute"}, {"api_name": "app.engine.cursor", "line_number": 20, "usage_type": "name"}, {"api_name": "app.engine.camera.Camera", "line_number": 20, "usage_type": "attribute"}, {"api_name": "app.engine.camera", "line_number": 20, "usage_type": "name"}, {"api_name": "app.engine.cursor", "line_number": 21, "usage_type": "name"}, {"api_name": "app.engine.camera", "line_number": 22, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 24, "usage_type": "name"}, {"api_name": "app.engine.movement.movement_component.MovementComponent", "line_number": 24, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 25, "usage_type": "name"}, {"api_name": "app.engine.movement.movement_component.MovementComponent", "line_number": 31, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 34, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 54, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 54, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 60, "usage_type": "call"}, {"api_name": "app.engine.config.SETTINGS", "line_number": 61, "usage_type": "attribute"}, {"api_name": "app.engine.config", "line_number": 61, "usage_type": "name"}, {"api_name": "app.engine.movement.unit_path_movement_component.UnitPathMovementComponent", "line_number": 63, "usage_type": "call"}, {"api_name": "app.engine.engine.get_time", "line_number": 67, "usage_type": "call"}, {"api_name": "app.engine.engine", "line_number": 67, "usage_type": "name"}, {"api_name": "app.utilities.utils.round_pos", "line_number": 83, "usage_type": "call"}, {"api_name": "app.utilities.utils", "line_number": 83, "usage_type": "name"}]} +{"seq_id": "38218223787", "text": "import logging\nimport subprocess # nosec\n\nfrom tern.analyze.default.command_lib import command_lib\nfrom tern.report import errors\nfrom tern.utils import constants\nfrom tern.utils import rootfs\n\n# global logger\nlogger = logging.getLogger(constants.logger_name)\n\n\ndef get_snippet_list(invoke_step, work_dir=None, envs=None):\n \"\"\"Given the invoke step dictionary i.e. steps of commands to run either\n in the chroot or on the host environment, get a list of command snippets\n invoke_dict: the value from the 'invoke' key\n workdir: If WORKDIR was set to anything, provide it here\n envs: If any environment variables were set, enter the key-value pairs\n here\"\"\"\n if 'container' in invoke_step.keys():\n snippet_list = invoke_step.get('container')\n # If environment variables exist, set them\n if envs:\n for var in envs:\n snippet_list.insert(\n 0, 'export ' + var.split('=')[0] + '=' + var.split('=')[1])\n # If work_dir exist cd into it\n if work_dir is not None:\n snippet_list.insert(0, 'cd ' + work_dir)\n return 'container', snippet_list\n return '', []\n\n\ndef invoke_in_rootfs(snippet_list, shell, package=''):\n '''Invoke the commands from the invoke dictionary in a root filesystem\n assuming the root filesystem is ready to accept commands'''\n # construct the full command\n full_cmd = command_lib.collate_snippets(snippet_list, package)\n try:\n result = rootfs.run_chroot_command(full_cmd, shell)\n try:\n result = result.decode('utf-8')\n except AttributeError:\n pass\n return result\n except subprocess.CalledProcessError as error:\n logger.warning('Error executing snippets: %s', error)\n raise\n\n\ndef get_pkg_attrs(attr_dict, shell, work_dir=None, envs=None, package_name=''):\n \"\"\"Given the dictionary containing the steps to invoke either in\n the container or on the host, invoke the steps and return the results\n either in list form or in raw form\"\"\"\n error_msgs = ''\n # the invoke dictionary contains steps\n # for each step make a command to invoke\n # currently we only deal with 1 step\n # so we just return the last step's results\n result = \"\"\n if 'invoke' in attr_dict.keys():\n for step in range(1, len(attr_dict['invoke'].keys()) + 1):\n method, snippet_list = get_snippet_list(\n attr_dict['invoke'][step], work_dir, envs)\n if method == 'container':\n # invoke the snippet list in a chroot environment\n try:\n result = invoke_in_rootfs(\n snippet_list, shell, package=package_name)\n result = result[:-1]\n except subprocess.CalledProcessError as error:\n error_msgs = error_msgs + error.stderr\n if 'delimiter' in attr_dict.keys():\n res_list = result.split(attr_dict['delimiter'])\n if res_list[-1] == '':\n res_list.pop()\n return res_list, error_msgs\n return res_list, error_msgs\n # if there is no delimiter, return the result string\n return result, error_msgs\n\n\ndef collect_list_metadata(shell, listing, work_dir=None, envs=None):\n '''Given the shell and the listing for the package manager, collect\n metadata that gets returned as a list'''\n pkg_dict = {}\n msgs = ''\n warnings = ''\n # a valid shell needs to exist in the filesystem for this to work\n for item in command_lib.base_keys:\n # check if the supported items exist in the given listing\n if item in listing.keys():\n items, msg = get_pkg_attrs(listing[item], shell, work_dir, envs)\n msgs = msgs + msg\n if item == 'files':\n # convert this data into a list before adding it to the\n # package dictionary\n file_list = []\n for files_str in items:\n # convert the string into a list\n files = []\n for filepath in filter(bool, files_str.split('\\n')):\n files.append(filepath.lstrip('/'))\n file_list.append(files)\n pkg_dict.update({item: file_list})\n else:\n pkg_dict.update({item: items})\n else:\n warnings = warnings + errors.no_listing_for_base_key.format(\n listing_key=item)\n return pkg_dict, msgs, warnings\n", "repo_name": "m1-key/tern", "sub_path": "tern/analyze/default/collect.py", "file_name": "collect.py", "file_ext": "py", "file_size_in_byte": 4523, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "25", "api": [{"api_name": "logging.getLogger", "line_number": 10, "usage_type": "call"}, {"api_name": "tern.utils.constants.logger_name", "line_number": 10, "usage_type": "attribute"}, {"api_name": "tern.utils.constants", "line_number": 10, "usage_type": "name"}, {"api_name": "tern.analyze.default.command_lib.command_lib.collate_snippets", "line_number": 38, "usage_type": "call"}, {"api_name": "tern.analyze.default.command_lib.command_lib", "line_number": 38, "usage_type": "name"}, {"api_name": "tern.utils.rootfs.run_chroot_command", "line_number": 40, "usage_type": "call"}, {"api_name": "tern.utils.rootfs", "line_number": 40, "usage_type": "name"}, {"api_name": "subprocess.CalledProcessError", "line_number": 46, "usage_type": "attribute"}, {"api_name": "subprocess.CalledProcessError", "line_number": 71, "usage_type": "attribute"}, {"api_name": "tern.analyze.default.command_lib.command_lib.base_keys", "line_number": 90, "usage_type": "attribute"}, {"api_name": "tern.analyze.default.command_lib.command_lib", "line_number": 90, "usage_type": "name"}, {"api_name": "tern.report.errors.no_listing_for_base_key.format", "line_number": 109, "usage_type": "call"}, {"api_name": "tern.report.errors.no_listing_for_base_key", "line_number": 109, "usage_type": "attribute"}, {"api_name": "tern.report.errors", "line_number": 109, "usage_type": "name"}]} +{"seq_id": "24651098592", "text": "from imblearn.over_sampling import SMOTE as OrigModel\nimport lale.helpers\nimport lale.operators\nfrom typing import Any, Dict, Optional\n\nclass SMOTEImpl():\n\n def __init__(self, sampling_strategy='auto', random_state=None, k_neighbors=5, n_jobs=1):\n self._hyperparams = {\n 'sampling_strategy': sampling_strategy,\n 'random_state': random_state,\n 'k_neighbors': k_neighbors,\n 'n_jobs': n_jobs}\n \n self._sklearn_model = OrigModel(**self._hyperparams) #calling it _sklearn_model due to legacy :)\n\n def fit(self, X, y=None):\n if (y is not None):\n self._sklearn_model.fit(X, y)\n else:\n self._sklearn_model.fit(X)\n return self\n\n def transform(self, X, y=None):\n if y is None:\n #If y is not passed, or it is passed as None, we assume this means resampling is not to be applied.\n return X, y\n else:\n #If a not None value is passed for y, this would mean a call during fit, and hence resampling to be done.\n return self._sklearn_model.fit_resample(X, y)\n\n_input_fit_schema = {\n '$schema': 'http://json-schema.org/draft-04/schema#',\n 'type': 'object',\n 'required': ['X', 'y'],\n 'additionalProperties': False,\n 'properties': {\n 'X': {\n 'description': 'Features; the outer array is over samples.',\n 'type': 'array',\n 'items': {'type': 'array', 'items': {'type': 'number'}}},\n 'y': {\n 'description': 'Target class labels; the array is over samples.',\n 'anyOf': [\n {'type': 'array', 'items': {'type': 'number'}},\n {'type': 'array', 'items': {'type': 'string'}}]}}}\n\n_input_transform_schema = {\n '$schema': 'http://json-schema.org/draft-04/schema#',\n 'type': 'object',\n 'required': ['X', 'y'],\n 'additionalProperties': False,\n 'properties': {\n 'X': {\n 'description': 'Features; the outer array is over samples.',\n 'type': 'array',\n 'items': {'type': 'array', 'items': {'type': 'number'}}},\n 'y': {\n 'description': 'Target class labels; the array is over samples.',\n 'laleType': 'Any'\n}}}\n\n_output_transform_schema:Dict[str, Any] = {}\n\n_hyperparams_schema = {\n 'allOf': [\n { 'type': 'object',\n 'relevantToOptimizer': [],\n 'additionalProperties': False,\n 'properties': {\n 'sampling_strategy': {\n 'description': \"\"\"sampling_strategy : float, str, dict or callable, default='auto'. \nSampling information to resample the data set.\n\"\"\",\n 'anyOf': [\n { 'description':\"\"\"When ``float``, \nit corresponds to the desired ratio of the number of \nsamples in the minority class over the number of samples in the\nmajority class after resampling. Therefore, the ratio is expressed as\n:math:`\\\\alpha_{os} = N_{rm} / N_{M}` where :math:`N_{rm}` is the\nnumber of samples in the minority class after resampling and\n:math:`N_{M}` is the number of samples in the majority class.\n.. warning::\n ``float`` is only available for **binary** classification. An\n error is raised for multi-class classification.\"\"\",\n 'type': 'number'},\n { 'description':\"\"\"When ``str``, specify the class targeted by the resampling. \nThe number of samples in the different classes will be equalized.\nPossible choices are:\n``'minority'``: resample only the minority class;\n``'not minority'``: resample all classes but the minority class;\n``'not majority'``: resample all classes but the majority class;\n``'all'``: resample all classes;\n``'auto'``: equivalent to ``'not majority'``.\"\"\",\n 'enum': ['minority','not minority','not majority', 'all', 'auto']},\n { 'description':\"\"\"- When ``dict``, the keys correspond to the targeted classes. \nThe values correspond to the desired number of samples for each targeted\nclass.\"\"\",\n 'type': 'object'},\n { 'description':\"\"\"When callable, function taking ``y`` and returns a ``dict``. \nThe keys correspond to the targeted classes. The values correspond to the\ndesired number of samples for each class.\"\"\",\n 'laleType': 'Any'}],\n 'default': 'auto'},\n 'random_state': {\n 'description':\n 'Control the randomization of the algorithm.',\n 'anyOf': [\n { 'description': 'RandomState used by np.random',\n 'enum': [None]},\n { 'description': 'The seed used by the random number generator',\n 'type': 'integer'},\n { 'description': 'Random number generator instance.',\n 'laleType':'Any'}],\n 'default': None},\n 'k_neighbors':{\n 'description': \"\"\"If ``int``, number of nearest neighbours to used to construct synthetic samples. \nIf object, an estimator that inherits from\n:class:`sklearn.neighbors.base.KNeighborsMixin` that will be used to\nfind the k_neighbors.\"\"\",\n 'anyOf': [\n {'laleType':'Any'},\n {'type': 'integer'}],\n 'default': 5},\n 'n_jobs': {\n 'description': 'The number of threads to open if possible.',\n 'type': 'integer',\n 'default': 1}}}]}\n\n_combined_schemas = {\n '$schema': 'http://json-schema.org/draft-04/schema#',\n 'description': \"\"\" \"\"\",\n 'documentation_url': '',\n 'type': 'object',\n 'tags': {\n 'pre': ['~categoricals'],\n 'op': ['resampler'],\n 'post': []},\n 'properties': {\n 'hyperparams': _hyperparams_schema,\n 'input_fit': _input_fit_schema,\n 'input_transform': _input_transform_schema,\n 'output_transform': _output_transform_schema,\n}}\n\nSMOTE = lale.operators.make_operator(SMOTEImpl, _combined_schemas)", "repo_name": "somsirsa/lale", "sub_path": "lale/lib/imblearn/smote.py", "file_name": "smote.py", "file_ext": "py", "file_size_in_byte": 5841, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "25", "api": [{"api_name": "imblearn.over_sampling.SMOTE", "line_number": 15, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 63, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 63, "usage_type": "name"}, {"api_name": "lale.helpers.operators.make_operator", "line_number": 146, "usage_type": "call"}, {"api_name": "lale.helpers.operators", "line_number": 146, "usage_type": "attribute"}, {"api_name": "lale.helpers", "line_number": 146, "usage_type": "name"}]} +{"seq_id": "16635821260", "text": "#!/usr/bin/env python\n\nimport json\nimport argparse\nimport math\nimport os\n\ndef pretty_coord(x, y):\n\n def pretty(n):\n if n % 1 == 0.5:\n return f\"{math.floor(n)} ½\"\n else:\n return f\"{math.floor(n)}\"\n \n return f\"({pretty(x)}, {pretty(y)}) \"\n\ndef render_html(doc, output):\n '''Output an HTML description of the coordinates used.\n\n Being HTML, the styled text can then be copy-pasted into\n a Google Doc or similar.\n\n The implementation is deliberately very very simple (ugly, even).\n\n The document comes from a JSON document that has the following structure:\n\n {\n \"name\": \"Jerry, from Tom & Jerry\",\n \"author\": \"Conor Kerr\",\n \"world_coordinates\": {\n \"llx\": 0, \"lly\": 5, \"urx\": 20, \"ury\": 23\n },\n \"elements\": [\n {\n \"id\": \"A\",\n \"type\": \"filled_path\",\n \"coords\": [\n [3, 15], [1, 19], [1, 20], [1.5, 21], [2, 21.5],\n [3, 22], [4, 21.5], [5, 20], [5.5, 19], [5, 17.5],\n [4, 16], [3, 15]\n ],\n \"fill_color\": \"pink\" \n },\n {\n \"id\": \"N\",\n \"type\": \"path\",\n \"coords\": [\n [3, 22], [5, 21.5], [5.5, 20.5], [6, 19.5], [7, 18],\n [9, 19], [11, 19], [13, 18], [14, 19.5], [14.5, 20.5],\n [15, 21.5], [17, 22]\n ]\n }\n ]\n }\n\n At the root of the document, the c(name) and c(author) fields are\n currently not used.\n\n The c(world_coordinates) dictionary species the lower-left and\n upper-right x,y coordinates as used by turtle.set_worldcoordinates()\n\n The main element in the document is the c(elements) list. Each\n element of the list is drawn in the order given; so items earlier\n in the list will appear behind items that come later.\n\n Each element in the c(elements) list is a dictionary of that contains\n the following keys:\n\n * an c(id), which is just for identifying each element and can be\n useful in diagnostics.\n\n * a c(type), which currently must be one of \"path\" or \"filled_path\".\n The only difference currently is that \"filled_path\" may specify\n a fill colour and works on the assumption that the shape described\n is enclosed (the start and end coordinate is the same)\n\n * a c(coords) list of x,y coordinates. Each item is a list (not a\n tuple, but this is only due to the data coming from JSON)\n '''\n \n output.write('''\n \n \n \n {name} - by {author}\n \n \n \n

    {name}

    \n

    by {author}

    \n\n '''.format(\n name = doc.get('name', 'Unnamed masterpiece'),\n author = doc.get('author', 'unknown artist')))\n\n for element in doc.get('elements'):\n\n output.write('''

    {id}: '''.format(\n id = element.get('id')\n ))\n\n for coord in element.get('coords'):\n output.write(pretty_coord(coord[0], coord[1]))\n\n if element.get('type') == 'filled_path':\n output.write(''' Colour {colour}

    '''.format(\n colour = element.get('fill_color')))\n\n output.write('''

    ''')\n\n output.write('''\n \n \n ''')\n\ndef html_filename(fn):\n (root, ext) = os.path.splitext(fn)\n return f\"{root}.html\"\n\ndef main():\n\n parser = argparse.ArgumentParser(\n description='make simple html version of a coordinate picture')\n parser.add_argument(\n 'files', metavar='FILENAME', type=str, nargs='+',\n help='JSON file that contains the image to display')\n args = parser.parse_args()\n\n for input_fn in args.files:\n with open(input_fn, mode='rt', encoding='utf-8') as input:\n with open(html_filename(input_fn), mode='wt', encoding='utf-8') as output:\n document = json.load(input)\n render_html(document, output)\n\nif __name__ == '__main__':\n main()\n", "repo_name": "cameronkerrnz/xypics", "sub_path": "prettyprint.py", "file_name": "prettyprint.py", "file_ext": "py", "file_size_in_byte": 4200, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "math.floor", "line_number": 12, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 118, "usage_type": "call"}, {"api_name": "os.path", "line_number": 118, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 123, "usage_type": "call"}, {"api_name": "json.load", "line_number": 133, "usage_type": "call"}]} +{"seq_id": "31522030995", "text": "from datetime import datetime, timezone\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, redirect\n\nfrom .tokens.token import TokenGenerator\nfrom .forms import *\n\nfrom django.shortcuts import render, redirect \nfrom django.contrib.auth import login, authenticate,logout\nfrom django.contrib.sites.shortcuts import get_current_site \nfrom django.utils.encoding import force_bytes, force_str \nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode \nfrom django.template.loader import render_to_string \n\nfrom django.contrib.auth.models import User \nfrom django.core.mail import EmailMessage \n\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom .models import Profile\nfrom projects.models import Project,UserDonation,ProjectReport,ReportComment,Comment,Rating\nfrom django.db.models import Sum\n\n\n\n\n\n\n# Create your views here.\n# profile view\ndef user_profile(request):\n if (request.user.is_authenticated):\n # - He can view his profile\n loged_user = Profile.objects.get(user=request.user)\n # - He can view his projects\n user_projects = Project.objects.filter(project_owner=request.user)\n # - He can view his donations\n user_donations= UserDonation.objects.filter(user_donated=request.user)\n total_donations_amount = sum([donation.amount for donation in UserDonation.objects.filter(user_donated=request.user) ])\n reported_projects = ProjectReport.objects.all()\n reported_comments = ReportComment.objects.all()\n total_ratings = Rating.objects.all()\n #raters_count = Rating.objects.filter(project_id=self.kwargs[\"pk\"]).count()\n total_donations_project = UserDonation.objects.all()\n context = {'user': loged_user,'projects':user_projects,'donations':user_donations,'total_donations':total_donations_amount,'reported_projects':reported_projects,'reported_comments':reported_comments,'total_ratings':total_ratings,'total_donations_project':total_donations_project}\n return render(request, 'users/user_profile.html', context)\n else:\n return redirect('signin')\n\n\n\n\n# edit profile view\ndef update_profile(request):\n if (request.user.is_authenticated):\n if request.method == 'POST':\n # - He can edit all his data except for the email, done\n # - He can have extra optional info other than the info he added\n # while registration (Birthdate, facebook profile, country), done\n userform=EditUserForm(request.POST,instance=request.user)\n forminstance=UserProfileForm(request.POST, request.FILES,instance=Profile.objects.get(user=request.user))\n if userform.is_valid() and forminstance.is_valid():\n userform.save()\n updatedprofile=forminstance.save(commit=False)\n updatedprofile.user = request.user\n updatedprofile.save()\n return redirect('user_profile_page')\n else:\n userform = EditUserForm(instance=request.user)\n forminstance = UserProfileForm(instance=Profile.objects.get(user=request.user))\n context = {'form': forminstance,'userform':userform}\n return render(request, 'users/edit_user_profile.html', context)\n else:\n return redirect('signin')\n\n\ndef delete_profile(request):\n if (request.user.is_authenticated):\n # - User can delete his account (Note that there must be a\n # confirmation message before deleting), done\n User.objects.get(username=request.user.username).delete()\n return HttpResponse('User deleted successfully')\n else:\n return redirect('signin')\n \ndef signup(request): \n if request.method == 'POST': \n form = SignupForm(request.POST)\n profile = UserProfileForm(request.POST,request.FILES)\n if form.is_valid() and profile.is_valid(): \n # save form in the memory not in database \n user = form.save(commit=False) \n user.is_active = False \n user.save() \n uprofile=profile.save(commit=False)\n uprofile.user=user\n uprofile.save()\n \n # to get the domain of the current site \n current_site = get_current_site(request) \n mail_subject = 'Activation link has been sent to your email id' \n message = render_to_string('acc_active_email.html', { \n 'user': user, \n 'domain': current_site.domain, \n 'uid':urlsafe_base64_encode(force_bytes(user.pk)), \n 'token':TokenGenerator().make_token(user), \n }) \n to_email = form.cleaned_data.get('email') \n email = EmailMessage( \n mail_subject, message, to=[to_email] \n ) \n email.send() \n return HttpResponse('Please confirm your email address to complete the registration') \n else: \n form = SignupForm() \n profile= UserProfileForm()\n return render(request, 'signup.html', {'form': form,'profile':profile}) \n\n\ndef activate(request, uidb64, token):\n try: \n uid = force_str(urlsafe_base64_decode(uidb64)) \n user = User.objects.get(pk=uid) \n \n except(TypeError, ValueError, OverflowError, User.DoesNotExist): \n user = None \n if user is not None and TokenGenerator().check_token(user, token) and user.is_active == False: \n print(user.date_joined)\n email_sent_at = user.date_joined\n now = datetime.now(timezone.utc)\n date_diffrince = (\n now-email_sent_at \n ).seconds / 60\n print(date_diffrince)\n if date_diffrince < (24 * 60):\n user.is_active = True \n user.save()\n return render(request,'confirmation.html') \n else: \n return HttpResponse('Activation link is invalid!') \n \n \n \n \n \n \n#///////////////////////////sign in /////////////////\n\ndef signin_user(request):\n context={}\n if request.method==\"POST\":\n try:\n myform=SigninForm(request.POST)\n u = User.objects.get(email=request.POST['email'])\n user = authenticate(username=u.username,password=request.POST['password'])\n if u.is_active == True:\n login(request,user) \n return redirect(user_profile)\n else:\n return HttpResponse('you should active your acount first... chick your Email')\n except:\n myform = SigninForm()\n context['form']=myform\n context['msg']='Wrong password or username ... '\n return render(request,'signin.html',context)\n else:\n myform = SigninForm()\n context['form']=myform\n return render(request,'signin.html',context)\n\n#///////////////////////////logout /////////////////\n\ndef logout_user(request):\n request.session.clear()\n logout(request)\n return redirect('signin')\n", "repo_name": "ayazeid/Crowd-Funding-App-Django", "sub_path": "crowdfund/users/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 6830, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "models.Profile.objects.get", "line_number": 35, "usage_type": "call"}, {"api_name": "models.Profile.objects", "line_number": 35, "usage_type": "attribute"}, {"api_name": "models.Profile", "line_number": 35, "usage_type": "name"}, {"api_name": "projects.models.Project.objects.filter", "line_number": 37, "usage_type": "call"}, {"api_name": "projects.models.Project.objects", "line_number": 37, "usage_type": "attribute"}, {"api_name": "projects.models.Project", "line_number": 37, "usage_type": "name"}, {"api_name": "projects.models.UserDonation.objects.filter", "line_number": 39, "usage_type": "call"}, {"api_name": "projects.models.UserDonation.objects", "line_number": 39, "usage_type": "attribute"}, {"api_name": "projects.models.UserDonation", "line_number": 39, "usage_type": "name"}, {"api_name": "projects.models.UserDonation.objects.filter", "line_number": 40, "usage_type": "call"}, {"api_name": "projects.models.UserDonation.objects", "line_number": 40, "usage_type": "attribute"}, {"api_name": "projects.models.UserDonation", "line_number": 40, "usage_type": "name"}, {"api_name": "projects.models.ProjectReport.objects.all", "line_number": 41, "usage_type": "call"}, {"api_name": "projects.models.ProjectReport.objects", "line_number": 41, "usage_type": "attribute"}, {"api_name": "projects.models.ProjectReport", "line_number": 41, "usage_type": "name"}, {"api_name": "projects.models.ReportComment.objects.all", "line_number": 42, "usage_type": "call"}, {"api_name": "projects.models.ReportComment.objects", "line_number": 42, "usage_type": "attribute"}, {"api_name": "projects.models.ReportComment", "line_number": 42, "usage_type": "name"}, {"api_name": "projects.models.Rating.objects.all", "line_number": 43, "usage_type": "call"}, {"api_name": "projects.models.Rating.objects", "line_number": 43, "usage_type": "attribute"}, {"api_name": "projects.models.Rating", "line_number": 43, "usage_type": "name"}, {"api_name": "projects.models.UserDonation.objects.all", "line_number": 45, "usage_type": "call"}, {"api_name": "projects.models.UserDonation.objects", "line_number": 45, "usage_type": "attribute"}, {"api_name": "projects.models.UserDonation", "line_number": 45, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 47, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 49, "usage_type": "call"}, {"api_name": "models.Profile.objects.get", "line_number": 62, "usage_type": "call"}, {"api_name": "models.Profile.objects", "line_number": 62, "usage_type": "attribute"}, {"api_name": "models.Profile", "line_number": 62, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 68, "usage_type": "call"}, {"api_name": "models.Profile.objects.get", "line_number": 71, "usage_type": "call"}, {"api_name": "models.Profile.objects", "line_number": 71, "usage_type": "attribute"}, {"api_name": "models.Profile", "line_number": 71, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 73, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 75, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 82, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 82, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 82, "usage_type": "name"}, {"api_name": "django.http.HttpResponse", "line_number": 83, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 85, "usage_type": "call"}, {"api_name": "django.contrib.sites.shortcuts.get_current_site", "line_number": 101, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 103, "usage_type": "call"}, {"api_name": "django.utils.http.urlsafe_base64_encode", "line_number": 106, "usage_type": "call"}, {"api_name": "django.utils.encoding.force_bytes", "line_number": 106, "usage_type": "call"}, {"api_name": "tokens.token.TokenGenerator", "line_number": 107, "usage_type": "call"}, {"api_name": "django.core.mail.EmailMessage", "line_number": 110, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 114, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 118, "usage_type": "call"}, {"api_name": "django.utils.encoding.force_str", "line_number": 123, "usage_type": "call"}, {"api_name": "django.utils.http.urlsafe_base64_decode", "line_number": 123, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 124, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 124, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 124, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.DoesNotExist", "line_number": 126, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 126, "usage_type": "name"}, {"api_name": "tokens.token.TokenGenerator", "line_number": 128, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 131, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 131, "usage_type": "name"}, {"api_name": "datetime.timezone.utc", "line_number": 131, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 131, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 139, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 141, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 155, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 155, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 155, "usage_type": "name"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 156, "usage_type": "call"}, {"api_name": "django.contrib.auth.login", "line_number": 158, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 159, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 161, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 166, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 170, "usage_type": "call"}, {"api_name": "django.contrib.auth.logout", "line_number": 176, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 177, "usage_type": "call"}]} +{"seq_id": "43755336083", "text": "#!/usr/bin/env python\n# coding=utf-8\nfrom util.math_util import *\nfrom util.dtree_util import *\nimport numpy as np\nimport cPickle\nfrom nltk.corpus import stopwords\n\ndef load_data(data_path):\n vocab, rel_list, ans_list, tree_dict = cPickle.load(open(data_path,'r'))\n ans_list = [vocab.index(ans) for ans in ans_list]\n return vocab, rel_list, ans_list, tree_dict\n\ndef root(tree):\n return tree.get(0).kids[0][0]\n\ndef preprocess(tree_dict, ans_list, isTrain):\n for key in tree_dict:\n for tree in tree_dict[key]:\n tree.get(root(tree)).dist = tree.dist\n tree.get(root(tree)).qid = tree.qid\n for node in tree.get_nodes():\n if isTrain:\n node.ans = tree.ans_ind\n else:\n node.ans = tree.ans\n node.neg = ans_list[ans_list != tree.ans_ind]\n new_kids = []\n for kid in node.kids:\n new_kids.append((tree.get(kid[0]),kid[1]))\n node.kids = new_kids\n\n node_dict = {}\n for key in tree_dict:\n node_dict[key] = []\n for tree in tree_dict[key]:\n node_dict[key].append(root(tree))\n\n return node_dict\n\ndef word(node):\n return node.ind\n\ndef get_kids(node):\n return node.kids\n\ndef get_ans(node):\n return node.ans\n\ndef get_neg(node):\n neg = []\n neg.append(node.ans)\n neg_list = node.neg\n for i in xrange(100):\n neg.append(neg_list[i])\n return neg\n\n\ndef collapse_questions(train_trees, test_trees):\n train_q = {}\n for tree in train_trees:\n if tree.qid not in train_q:\n train_q[tree.qid] = {}\n train_q[tree.qid][tree.dist] = tree\n test_q = {}\n for tree in test_trees:\n if tree.qid not in test_q:\n test_q[tree.qid] = {}\n test_q[tree.qid][tree.dist] = tree\n return train_q, test_q\n\ndef shuffle_neg(trees):\n for tree in trees:\n for node in tree.get_nodes():\n random.shuffle(node.neg)\n\ndef isStop(node):\n stop = stopwords.words('english')\n if node.word in stop:\n return 0.0\n else:\n return 1.0\n", "repo_name": "acelove/Qanta-with-tensorflow_fold", "sub_path": "utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 2129, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "cPickle.load", "line_number": 10, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 78, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 78, "usage_type": "name"}]} +{"seq_id": "3991296028", "text": "from copy import deepcopy\nfrom itertools import product\nfrom collections import deque\nimport nnkit as nn\nimport numpy as np\n\n\ndef trainMNIST(trainingSet, validationSet, epochs, layers, batchSizes, learnRates, keepBest):\n \"\"\"Train and validate models on MNIST with different hyper parameter combinations.\n\n This function trains and validates one model per hyper parameter combination. It then returns\n all training stats and the n (keepBest) models that scored the highest validation accuracy.\n\n :param trainingSet: a 2-tuple where the first element contains the MNIST training set examples and\n the second element contains the target labels for each example in one-hot form.\n\n :param validationSet: a 2-tuple where the first element contains MNIST examples and\n the second element contains the target labels for each example in one-hot form.\n This set must be disjoint from the training set.\n\n :param epochs: a list of epochs to train for.\n i.e.: [10, 50, 100]\n\n :param layers: a list of tuples where each element represents the (hidden unit) size of a layer.\n i.e.: [(10,), (10,20)]\n\n :param batchSizes: a list of batch sizes to use when training.\n i.e.: [16, 32]\n\n :param learnRates: a list of 2-tuples where the first element is an arbitrary string id and the second element\n is a lambda taking the total number of epochs and the current epoch and returning the learning rate for that epoch.\n i.e.: [('fixed 0.4', lambda epochs, e: 0.4), ('decay-0.4-0.1', lambda epochs, e: nn.decay(e, epochs, (0.1, 0.4)))]\n\n :param keepBest: How many of the best models to return.\n\n :return: a 2-tuple where the first element is a dictionary of training stats for all models and the second element\n is a list of the highest n (keepBest) scoring models.\n \"\"\"\n # x = raw pixels, y = one-hot target for loss evaluation:\n x, y = nn.NetVar(), nn.NetVar()\n idx = list(range(len(trainingSet[0])))\n combinations = product(layers, batchSizes, learnRates)\n validationTarget = np.argmax(validationSet[1].data, axis=1)\n bestQueue = deque(maxlen=keepBest)\n allStats = {}\n\n # Train one model per hyper parameter combination:\n for layers, batchSize, learnRate in combinations:\n key = str((epochs, layers, batchSize, learnRate[0]))\n stats = {}\n allStats[key] = stats\n\n print('++ NEW MODEL: {} ++'.format(key))\n\n # Define model topology according to layers hyper param:\n topology = []\n\n for i in range(len(layers)):\n topology.extend([\n (nn.Multiply, nn.rand2(28 * 28 if not i else layers[i-1], layers[i])),\n (nn.Add, nn.rand2(layers[i])),\n (nn.ReLU,)\n ])\n\n topology.extend([\n (nn.Multiply, nn.rand2(layers[i], 10)),\n (nn.Add, nn.rand2(10)),\n (nn.Softmax,)\n ])\n\n net = nn.FFN(*topology)\n\n # Create optimizer and loss node:\n optimizer = nn.GD(net.vars)\n net.topology.append((nn.CELoss, y))\n\n for e in range(1, epochs+1):\n # Train on random minibatches:\n np.random.shuffle(idx)\n\n for i in range(0, len(idx), batchSize):\n x.data, y.data = trainingSet[0][idx[i:i + batchSize]], trainingSet[1][idx[i:i + batchSize]]\n trainingLoss = net(x)\n net.back()\n optimizer.learnRate = learnRate[1](epochs, e - 1)\n optimizer.step()\n\n # Validate:\n x.data, y.data = validationSet[0], validationSet[1]\n validationLoss = net(x)\n\n if np.isnan(validationLoss):\n print('numerical instability -- abort --.')\n break\n\n # Prediction is output of antepenultimate layer,\n # because last layer is loss node during training:\n prediction = net.layers[-2].data\n prediction = np.argmax(prediction, axis=1)\n validationAccuracy = np.mean(prediction == validationTarget) * 100\n stats[e] = (trainingLoss.item(), validationLoss.item(), validationAccuracy)\n\n # Keep best model so far:\n newBest = False\n if not len(bestQueue) or bestQueue[-1][2] < validationAccuracy:\n bestModel = deepcopy(net)\n bestModel.topology.pop()\n best = (key, e, validationAccuracy, bestModel)\n bestQueue.append(best)\n newBest = True\n\n print('\\t e:{} | train loss: {:,.3f} | val loss: {:,.3f} | val accuracy: {:,.2f}% | learn rate: {:,.2f} {}'.format(\n e, *stats[e], optimizer.learnRate, \" *\" if newBest else \"\"\n ))\n\n return allStats, bestQueue\n", "repo_name": "saldavonschwartz/digits", "sub_path": "python/training.py", "file_name": "training.py", "file_ext": "py", "file_size_in_byte": 4732, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "nnkit.NetVar", "line_number": 40, "usage_type": "call"}, {"api_name": "itertools.product", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 43, "usage_type": "call"}, {"api_name": "collections.deque", "line_number": 44, "usage_type": "call"}, {"api_name": "nnkit.Multiply", "line_number": 60, "usage_type": "attribute"}, {"api_name": "nnkit.rand2", "line_number": 60, "usage_type": "call"}, {"api_name": "nnkit.Add", "line_number": 61, "usage_type": "attribute"}, {"api_name": "nnkit.rand2", "line_number": 61, "usage_type": "call"}, {"api_name": "nnkit.ReLU", "line_number": 62, "usage_type": "attribute"}, {"api_name": "nnkit.Multiply", "line_number": 66, "usage_type": "attribute"}, {"api_name": "nnkit.rand2", "line_number": 66, "usage_type": "call"}, {"api_name": "nnkit.Add", "line_number": 67, "usage_type": "attribute"}, {"api_name": "nnkit.rand2", "line_number": 67, "usage_type": "call"}, {"api_name": "nnkit.Softmax", "line_number": 68, "usage_type": "attribute"}, {"api_name": "nnkit.FFN", "line_number": 71, "usage_type": "call"}, {"api_name": "nnkit.GD", "line_number": 74, "usage_type": "call"}, {"api_name": "nnkit.CELoss", "line_number": 75, "usage_type": "attribute"}, {"api_name": "numpy.random.shuffle", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 79, "usage_type": "attribute"}, {"api_name": "numpy.isnan", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 100, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 106, "usage_type": "call"}]} +{"seq_id": "16829165010", "text": "# import torch\n# import timm\n# from torch import nn\n#\n# class PrintLayer(nn.Module):\n# def __init__(self, layer):\n# super(PrintLayer, self).__init__()\n# self.layer = layer\n# self.layer.register_forward_hook(self.print_sizes)\n#\n# def print_sizes(self, module, input, output):\n# print(module.__class__.__name__, 'input size: ', input[0].size())\n# print(module.__class__.__name__, 'output size: ', output.size())\n#\n# def forward(self, x):\n# return self.layer(x)\n#\n# def __getattr__(self, name):\n# try:\n# return super().__getattr__(name)\n# except AttributeError:\n# return getattr(self.layer, name)\n#\n# model_name = 'twins_pcpvt_small'\n# model = timm.create_model(model_name, pretrained=True)\n#\n# model.blocks = model.blocks[:3] # Only use the first 3 blocks\n# model.norm = torch.nn.Identity() # Remove the normalization layer\n# model.head = torch.nn.Identity() # Remove the head layer\n# model.head_drop = torch.nn.Identity() # Remove the head layer\n# model.patch_embeds[3] = torch.nn.Identity() # Remove the head layer\n# model.pos_block[3] = torch.nn.Identity() # Remove the head layer\n#\n# print(model)\n#\n# def replace_with_printlayer(module):\n# for name, layer in module.named_children():\n# if list(layer.children()):\n# replace_with_printlayer(layer)\n# else:\n# setattr(module, name, PrintLayer(layer))\n#\n# replace_with_printlayer(model)\n#\n# input = torch.randn(1, 3, 400, 400)\n# output = model(input)\n\nimport torch\nimport torch.nn as nn\nimport timm\n\n\nclass PrintLayer(nn.Module):\n def __init__(self):\n super(PrintLayer, self).__init__()\n\n def forward(self, x, y):\n print(x.shape)\n d = x.clone()\n d = d.reshape(x.shape[0], x.shape[2], y[0], y[1])\n print(d.shape)\n return x\n\n\ndef print_output_size(module, input, output):\n print(module.__class__.__name__, \"output size: \", output.size())\n\n\nmodel_name = \"twins_pcpvt_small\"\nmodel = timm.create_model(model_name, pretrained=True)\n\nmodel.blocks = model.blocks[:3] # Only use the first 3 blocks\nmodel.norm = torch.nn.Identity() # Remove the normalization layer\nmodel.head = torch.nn.Identity() # Remove the head layer\nmodel.head_drop = torch.nn.Identity()\nmodel.patch_embeds[3] = torch.nn.Identity()\nmodel.pos_block[3] = torch.nn.Identity()\nmodel.blocks[0].add_module(\"print\", PrintLayer())\nmodel.blocks[1].add_module(\"print\", PrintLayer())\nmodel.blocks[2].add_module(\"print\", PrintLayer())\nprint(model)\n\ninput = torch.randn(1, 3, 400, 400)\noutput = model(input)\n", "repo_name": "spagnoloG/uav-localization-2023", "sub_path": "utils/modified_twins.py", "file_name": "modified_twins.py", "file_ext": "py", "file_size_in_byte": 2587, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "25", "api": [{"api_name": "torch.nn.Module", "line_number": 53, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 53, "usage_type": "name"}, {"api_name": "timm.create_model", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.nn.Identity", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 73, "usage_type": "attribute"}, {"api_name": "torch.nn.Identity", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 74, "usage_type": "attribute"}, {"api_name": "torch.nn.Identity", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 75, "usage_type": "attribute"}, {"api_name": "torch.nn.Identity", "line_number": 76, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 76, "usage_type": "attribute"}, {"api_name": "torch.nn.Identity", "line_number": 77, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 77, "usage_type": "attribute"}, {"api_name": "torch.randn", "line_number": 83, "usage_type": "call"}]} +{"seq_id": "12154033690", "text": "from typing import Callable, List, Union\n\nimport torch\nfrom torch import Tensor\n\nfrom torch_geometric.nn import GCNConv, TopKPooling\nfrom torch_geometric.nn.resolver import activation_resolver\nfrom torch_geometric.typing import OptTensor, PairTensor\nfrom torch_geometric.utils import (\n add_self_loops,\n remove_self_loops,\n to_torch_csr_tensor,\n)\nfrom torch_geometric.utils.repeat import repeat\n\n\nclass GraphUNet(torch.nn.Module):\n r\"\"\"The Graph U-Net model from the `\"Graph U-Nets\"\n `_ paper which implements a U-Net like\n architecture with graph pooling and unpooling operations.\n\n Args:\n in_channels (int): Size of each input sample.\n hidden_channels (int): Size of each hidden sample.\n out_channels (int): Size of each output sample.\n depth (int): The depth of the U-Net architecture.\n pool_ratios (float or [float], optional): Graph pooling ratio for each\n depth. (default: :obj:`0.5`)\n sum_res (bool, optional): If set to :obj:`False`, will use\n concatenation for integration of skip connections instead\n summation. (default: :obj:`True`)\n act (torch.nn.functional, optional): The nonlinearity to use.\n (default: :obj:`torch.nn.functional.relu`)\n \"\"\"\n def __init__(\n self,\n in_channels: int,\n hidden_channels: int,\n out_channels: int,\n depth: int,\n pool_ratios: Union[float, List[float]] = 0.5,\n sum_res: bool = True,\n act: Union[str, Callable] = 'relu',\n ):\n super().__init__()\n assert depth >= 1\n self.in_channels = in_channels\n self.hidden_channels = hidden_channels\n self.out_channels = out_channels\n self.depth = depth\n self.pool_ratios = repeat(pool_ratios, depth)\n self.act = activation_resolver(act)\n self.sum_res = sum_res\n\n channels = hidden_channels\n\n self.down_convs = torch.nn.ModuleList()\n self.pools = torch.nn.ModuleList()\n self.down_convs.append(GCNConv(in_channels, channels, improved=True))\n for i in range(depth):\n self.pools.append(TopKPooling(channels, self.pool_ratios[i]))\n self.down_convs.append(GCNConv(channels, channels, improved=True))\n\n in_channels = channels if sum_res else 2 * channels\n\n self.up_convs = torch.nn.ModuleList()\n for i in range(depth - 1):\n self.up_convs.append(GCNConv(in_channels, channels, improved=True))\n self.up_convs.append(GCNConv(in_channels, out_channels, improved=True))\n\n self.reset_parameters()\n\n def reset_parameters(self):\n r\"\"\"Resets all learnable parameters of the module.\"\"\"\n for conv in self.down_convs:\n conv.reset_parameters()\n for pool in self.pools:\n pool.reset_parameters()\n for conv in self.up_convs:\n conv.reset_parameters()\n\n def forward(self, x: Tensor, edge_index: Tensor,\n batch: OptTensor = None) -> Tensor:\n \"\"\"\"\"\" # noqa: D419\n if batch is None:\n batch = edge_index.new_zeros(x.size(0))\n edge_weight = x.new_ones(edge_index.size(1))\n\n x = self.down_convs[0](x, edge_index, edge_weight)\n x = self.act(x)\n\n xs = [x]\n edge_indices = [edge_index]\n edge_weights = [edge_weight]\n perms = []\n\n for i in range(1, self.depth + 1):\n edge_index, edge_weight = self.augment_adj(edge_index, edge_weight,\n x.size(0))\n x, edge_index, edge_weight, batch, perm, _ = self.pools[i - 1](\n x, edge_index, edge_weight, batch)\n\n x = self.down_convs[i](x, edge_index, edge_weight)\n x = self.act(x)\n\n if i < self.depth:\n xs += [x]\n edge_indices += [edge_index]\n edge_weights += [edge_weight]\n perms += [perm]\n\n for i in range(self.depth):\n j = self.depth - 1 - i\n\n res = xs[j]\n edge_index = edge_indices[j]\n edge_weight = edge_weights[j]\n perm = perms[j]\n\n up = torch.zeros_like(res)\n up[perm] = x\n x = res + up if self.sum_res else torch.cat((res, up), dim=-1)\n\n x = self.up_convs[i](x, edge_index, edge_weight)\n x = self.act(x) if i < self.depth - 1 else x\n\n return x\n\n def augment_adj(self, edge_index: Tensor, edge_weight: Tensor,\n num_nodes: int) -> PairTensor:\n edge_index, edge_weight = remove_self_loops(edge_index, edge_weight)\n edge_index, edge_weight = add_self_loops(edge_index, edge_weight,\n num_nodes=num_nodes)\n adj = to_torch_csr_tensor(edge_index, edge_weight,\n size=(num_nodes, num_nodes))\n adj = (adj @ adj).to_sparse_coo()\n edge_index, edge_weight = adj.indices(), adj.values()\n edge_index, edge_weight = remove_self_loops(edge_index, edge_weight)\n return edge_index, edge_weight\n\n def __repr__(self) -> str:\n return (f'{self.__class__.__name__}({self.in_channels}, '\n f'{self.hidden_channels}, {self.out_channels}, '\n f'depth={self.depth}, pool_ratios={self.pool_ratios})')\n", "repo_name": "pyg-team/pytorch_geometric", "sub_path": "torch_geometric/nn/models/graph_unet.py", "file_name": "graph_unet.py", "file_ext": "py", "file_size_in_byte": 5395, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 18979, "dataset": "github-code", "pt": "25", "api": [{"api_name": "torch.nn", "line_number": 17, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 41, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 41, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 43, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 43, "usage_type": "name"}, {"api_name": "torch_geometric.utils.repeat.repeat", "line_number": 51, "usage_type": "call"}, {"api_name": "torch_geometric.nn.resolver.activation_resolver", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.nn.ModuleList", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 57, "usage_type": "attribute"}, {"api_name": "torch.nn.ModuleList", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 58, "usage_type": "attribute"}, {"api_name": "torch_geometric.nn.GCNConv", "line_number": 59, "usage_type": "call"}, {"api_name": "torch_geometric.nn.TopKPooling", "line_number": 61, "usage_type": "call"}, {"api_name": "torch_geometric.nn.GCNConv", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.nn.ModuleList", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 66, "usage_type": "attribute"}, {"api_name": "torch_geometric.nn.GCNConv", "line_number": 68, "usage_type": "call"}, {"api_name": "torch_geometric.nn.GCNConv", "line_number": 69, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 82, "usage_type": "name"}, {"api_name": "torch_geometric.typing.OptTensor", "line_number": 83, "usage_type": "name"}, {"api_name": "torch.zeros_like", "line_number": 120, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 122, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 83, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 129, "usage_type": "name"}, {"api_name": "torch_geometric.utils.remove_self_loops", "line_number": 131, "usage_type": "call"}, {"api_name": "torch_geometric.utils.add_self_loops", "line_number": 132, "usage_type": "call"}, {"api_name": "torch_geometric.utils.to_torch_csr_tensor", "line_number": 134, "usage_type": "call"}, {"api_name": "torch_geometric.utils.remove_self_loops", "line_number": 138, "usage_type": "call"}, {"api_name": "torch_geometric.typing.PairTensor", "line_number": 130, "usage_type": "name"}]} +{"seq_id": "5977282683", "text": "\n#SIMPLE SNAKE GAME \n\nimport pygame\nimport time\nimport random\n\n#INIT PYGAME (INITIALIZATION)\npygame.init()\n\n#DEFINE COLORS\n#RGB MAX- MIN\n#white = snakecolor\n#black = background \n#red = overmessage\n#orange= foodchasing\n\nwhite = (255, 255, 255)\nblack = (0, 0, 0)\nred = (255, 0, 0)\norange = (255, 165, 0)\ngreen_snake = (108, 187,60)\n\n#DIMENSIONS\n\nwidth, height = 600, 400 \n\n#SETUP DISPLAY \n#SET MODE\n#SETUP TITILE\ngame_display = pygame.display.set_mode((width, height)) \npygame.display.set_caption(\"Snake Pet Game\")\n\n#TIME RUNNING\n\nclock = pygame.time.Clock()\n\n#SNAKE MODS\n\nsnake_size = 10\n\nsnake_speed = 15\n\n#FONT FOR MESSAGE\n\nmessage_font = pygame.font.SysFont('ubuntu', 30 )\n\n#FONT FOR SCORE\n\nscore_font = pygame.font.SysFont('ubuntu', 25)\n\n#DEFINE (DEF) TWO BASICS FUNCTIONS, UPDATING FUNCTIONS\n\ndef print_score(score):\n text = score_font.render(\"Score: \" + str(score), True, orange)\n game_display.blit(text, [5, 1])\n \ndef draw_snake(snake_size, snake_pixels):\n for pixel in snake_pixels:\n pygame.draw.rect(game_display, green_snake, [pixel[0], pixel[1], snake_size, snake_size])\n \n\n#RUN GAME FUNCTIONS (main function, dimension, game start, snake pixels in a list because is going to grow, target food, floating point), WITH VARIABLES\n\ndef run_game():\n \n game_over = False\n game_close = False\n \n x = width / 2\n y = height / 2\n \n x_speed = 0\n y_speed = 0\n \n snake_pixels = []\n snake_lenght = 1\n \n # THE POSITION ON THE TARGET IS RANDOM, STARTING WITH 0 AND IT'S GOING TO GO WITH MINUS SIZE\n \n target_x = round(random.randrange(0, width-snake_size) / 10.0) * 10.0\n target_y = round(random.randrange(0, height-snake_size) / 10.0) * 10.0\n \n #MAIN GAME LOOP, game over on the screen inside of the game loop, restart the game\n \n while not game_over:\n \n while game_close:\n game_display.fill(black)\n game_over_message = message_font.render(\"Game Over!\", True, red)\n game_display.blit(game_over_message, [width / 3, height / 3])\n print_score(snake_lenght - 1)\n pygame.display.update()\n \n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_1:\n game_over = True\n game_close = False\n if event.key == pygame.K_2:\n run_game()\n \n #alternative \n \n if event.type == pygame.QUIT:\n game_over = True\n game_over = False\n \n \n \n \n for event in pygame.event.get():\n \n if event.type == pygame.QUIT:\n game_over = True\n \n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT :\n x_speed = -snake_size\n y_speed = 0\n if event.key == pygame.K_RIGHT:\n x_speed = snake_size\n y_speed = 0\n if event.key == pygame.K_UP:\n x_speed = 0\n y_speed = -snake_size\n if event.key == pygame.K_DOWN:\n x_speed = 0\n y_speed = snake_size \n\n #if we hit the bounderies, out of the screen we have to close the game as well\n \n if x >= width or x < 0 or y >= height or y < 0: \n game_close = True\n \n #we need to advance, depending of the speed (MOVEMENT)\n \n x += x_speed\n y += y_speed\n \n #SET THE BACKGROUND, THE BASIC TARGET (BACKGROUND) UPDATE THE SNAKE(REMOVE-INCREASE BY ACOMPLISH TARGET)\n \n game_display.fill(black) \n pygame.draw.rect(game_display, orange, [target_x, target_y, snake_size, snake_size])\n \n snake_pixels.append([x, y])\n \n if len(snake_pixels) > snake_lenght:\n del snake_pixels[0]\n \n for pixel in snake_pixels[: - 1]:\n if pixel == [x, y]:\n game_close = True\n \n draw_snake(snake_size, snake_pixels)\n print_score(snake_lenght - 1)\n \n pygame.display.update()\n \n if x == target_x and y == target_y:\n target_x = round(random.randrange(0, width-snake_size) / 10.0) * 10.0\n target_y = round(random.randrange(0, height-snake_size) / 10.0) * 10.0\n snake_lenght += 1 \n \n clock.tick(snake_speed)\n \n #game over\n \n pygame.quit()\n quit()\n \nrun_game()\n ", "repo_name": "Miladatasys/2022-CODES", "sub_path": "2022-CODIGOS/snake_game.py", "file_name": "snake_game.py", "file_ext": "py", "file_size_in_byte": 4784, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pygame.init", "line_number": 9, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 31, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 31, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 32, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 32, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 36, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 36, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 46, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 46, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 50, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 50, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 60, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 60, "usage_type": "attribute"}, {"api_name": "random.randrange", "line_number": 81, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 82, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 93, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 93, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 95, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 95, "usage_type": "attribute"}, {"api_name": "pygame.KEYDOWN", "line_number": 96, "usage_type": "attribute"}, {"api_name": "pygame.K_1", "line_number": 97, "usage_type": "attribute"}, {"api_name": "pygame.K_2", "line_number": 100, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 105, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 112, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 112, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 114, "usage_type": "attribute"}, {"api_name": "pygame.KEYDOWN", "line_number": 117, "usage_type": "attribute"}, {"api_name": "pygame.K_LEFT", "line_number": 118, "usage_type": "attribute"}, {"api_name": "pygame.K_RIGHT", "line_number": 121, "usage_type": "attribute"}, {"api_name": "pygame.K_UP", "line_number": 124, "usage_type": "attribute"}, {"api_name": "pygame.K_DOWN", "line_number": 127, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 144, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 144, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 158, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 158, "usage_type": "attribute"}, {"api_name": "random.randrange", "line_number": 161, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 162, "usage_type": "call"}, {"api_name": "pygame.quit", "line_number": 169, "usage_type": "call"}]} +{"seq_id": "38127110956", "text": "import json\nimport random\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.views.generic import TemplateView, ListView, DetailView, DeleteView\nfrom django.urls import reverse\nfrom .models import Category, Product, Banner\nfrom .forms import ProductForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import JsonResponse\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import HttpResponseRedirect\n\n\nclass MainPageView(TemplateView):\n template_name = 'products/index.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"categories\"] = Category.objects.filter(parent__isnull=True)\n context[\"products\"] = Product.objects.with_discount()[:8]\n return context\n\n\nclass ProductListView(ListView):\n \"\"\"\n product list queryset can be a filtered by category\n name, or include all products ordered by creation date\n \"\"\"\n model = Product\n template_name = 'products/list.html'\n paginate_by = 24\n\n def get_queryset(self, **kwargs):\n category = None\n qs = super().get_queryset(**kwargs)\n cat_slug = self.kwargs.get('cat_slug')\n if cat_slug:\n \"\"\"\n use get_descendants() to include all children's\n category products in queryset\n \"\"\"\n category = get_object_or_404(\n Category,\n slug=cat_slug).get_descendants(include_self=True)\n qs = qs.filter(category__in=category)\n return qs\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n cat_slug = self.kwargs.get('cat_slug')\n if cat_slug:\n context['cat_obj'] = get_object_or_404(\n Category, slug=cat_slug)\n return context\n\n\nclass ProductSearchResult(ListView):\n model = Product\n template_name = 'products/list.html'\n paginate_by = 24\n\n def get_queryset(self, *args, **kwargs):\n qs = super().get_queryset()\n query = self.request.GET.get('query')\n qs = qs.filter(name__icontains=query)\n return qs\n\n\ndef get_products_qs(request):\n if request.is_ajax():\n query = request.GET.get('query')\n products = Product.objects.filter(name__icontains=query)\n counter = 0\n response = dict()\n for item in products:\n context = {\n \"name\": item.name,\n \"link\": f\"/products/detail/{item.id}/{item.slug}/\"\n }\n response[str(counter)] = context\n counter += 1\n return JsonResponse(json.dumps(response), safe=False)\n return JsonResponse({'error': 'all bad'})\n\n\nclass ProductDetailView(DetailView):\n model = Product\n template_name = 'products/detail.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['images'] = self.get_object().images.all()\n cat = self.get_object().category\n context['sugested'] = Product.objects.filter(\n category=cat).order_by('-timestamp')[:2]\n return context\n\n\n@login_required\ndef add_product(request, **kwargs):\n if request.method == 'POST':\n product_form = ProductForm(request.POST)\n print(product_form.errors)\n if product_form.is_valid():\n new = product_form.save(commit=False)\n new.owner = request.user\n new.save()\n product_form.save_m2m()\n for f in request.FILES.keys():\n new.images.create(image=request.FILES[f])\n return redirect(reverse('products:detail',\n kwargs={'pk': new.pk,\n 'slug': new.slug}))\n product_form = ProductForm()\n categories = Category.objects.all()\n return render(request, 'products/create.html', {\n 'product_form': product_form,\n 'categories': categories})\n\n\nclass ProductDeleteView(LoginRequiredMixin, DeleteView):\n model = Product\n\n def get_success_url(self):\n return reverse('adminpanel:main')\n\n\nclass CategoryListView(TemplateView):\n template_name = 'products/categories.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['categories'] = Category.objects.filter(parent__isnull=True)\n return context\n", "repo_name": "HeorhiiPotapov/localMokal", "sub_path": "products/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 4426, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.views.generic.TemplateView", "line_number": 14, "usage_type": "name"}, {"api_name": "models.Category.objects.filter", "line_number": 19, "usage_type": "call"}, {"api_name": "models.Category.objects", "line_number": 19, "usage_type": "attribute"}, {"api_name": "models.Category", "line_number": 19, "usage_type": "name"}, {"api_name": "models.Product.objects.with_discount", "line_number": 20, "usage_type": "call"}, {"api_name": "models.Product.objects", "line_number": 20, "usage_type": "attribute"}, {"api_name": "models.Product", "line_number": 20, "usage_type": "name"}, {"api_name": "django.views.generic.ListView", "line_number": 24, "usage_type": "name"}, {"api_name": "models.Product", "line_number": 29, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 42, "usage_type": "call"}, {"api_name": "models.Category", "line_number": 43, "usage_type": "argument"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 52, "usage_type": "call"}, {"api_name": "models.Category", "line_number": 53, "usage_type": "argument"}, {"api_name": "django.views.generic.ListView", "line_number": 57, "usage_type": "name"}, {"api_name": "models.Product", "line_number": 58, "usage_type": "name"}, {"api_name": "models.Product.objects.filter", "line_number": 72, "usage_type": "call"}, {"api_name": "models.Product.objects", "line_number": 72, "usage_type": "attribute"}, {"api_name": "models.Product", "line_number": 72, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 82, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 82, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 83, "usage_type": "call"}, {"api_name": "django.views.generic.DetailView", "line_number": 86, "usage_type": "name"}, {"api_name": "models.Product", "line_number": 87, "usage_type": "name"}, {"api_name": "models.Product.objects.filter", "line_number": 94, "usage_type": "call"}, {"api_name": "models.Product.objects", "line_number": 94, "usage_type": "attribute"}, {"api_name": "models.Product", "line_number": 94, "usage_type": "name"}, {"api_name": "forms.ProductForm", "line_number": 102, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 111, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 111, "usage_type": "call"}, {"api_name": "forms.ProductForm", "line_number": 114, "usage_type": "call"}, {"api_name": "models.Category.objects.all", "line_number": 115, "usage_type": "call"}, {"api_name": "models.Category.objects", "line_number": 115, "usage_type": "attribute"}, {"api_name": "models.Category", "line_number": 115, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 116, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 99, "usage_type": "name"}, {"api_name": "django.contrib.auth.mixins.LoginRequiredMixin", "line_number": 121, "usage_type": "name"}, {"api_name": "django.views.generic.DeleteView", "line_number": 121, "usage_type": "name"}, {"api_name": "models.Product", "line_number": 122, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 125, "usage_type": "call"}, {"api_name": "django.views.generic.TemplateView", "line_number": 128, "usage_type": "name"}, {"api_name": "models.Category.objects.filter", "line_number": 133, "usage_type": "call"}, {"api_name": "models.Category.objects", "line_number": 133, "usage_type": "attribute"}, {"api_name": "models.Category", "line_number": 133, "usage_type": "name"}]} +{"seq_id": "18180491885", "text": "import json\nimport os\nfrom uuid import uuid4\nfrom flask import Flask, request, abort, Response\nfrom flask_socketio import SocketIO\nfrom flask_sqlalchemy import SQLAlchemy\nfrom srcs.helpers import send_alerts, WebhookSender\nfrom threading import Lock\nimport time\nfrom sqlalchemy import ForeignKey\nfrom sqlalchemy.orm import relationship\n\nenv_data = json.load(open('srcs/env.json', 'r'))\n\ncooldown = env_data[\"data\"][\"general\"][\"cooldown\"]\nserver = env_data[\"data\"][\"general\"][\"server\"]\n\nhook_url = env_data[\"data\"][\"general\"][\"webhook\"]\nWebhook = WebhookSender(hook_url)\n\nasync_mode = None\n\napp = Flask(__name__)\nsocket_ = SocketIO(app, async_mode=async_mode)\n\n# database\nfile_path = \"data.db\"\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + file_path\ndb = SQLAlchemy(app)\n\nthread = None\nthread_lock = Lock()\n\n\n@app.route('/')\ndef index():\n return 'Success'\n\n\nif env_data[\"development\"]:\n @app.route('/api/test')\n def test():\n if request.args.get('event') == 'test':\n socket_.emit('test_event')\n Webhook.send_event('Test Event', 'n/a')\n elif request.args.get('event') == 'raid':\n socket_.emit('raid', server)\n Webhook.send_event('Raid Alarm', 'TEST EVENT')\n else:\n abort(400)\n\n return Response('200')\n\n\n@app.route('/phone', methods=[\"POST\"])\ndef number_actions():\n data = request.json\n if data[\"password\"] != env_data[\"data\"][\"general\"][\"password\"]:\n return Response(status=401)\n\n phone = str(data[\"number\"])\n if data[\"action\"] == \"add\":\n if not (phone.isdigit() and len(phone) == 10):\n return Response(status=400) # if not valid\n\n if Phone.query.filter_by(phone=phone).first() is not None:\n return Response(status=400) # if not unique\n\n new_phone = Phone(phone, data[\"hostname\"])\n db.session.add(new_phone)\n db.session.commit()\n\n Webhook.send_event('Phone Added', new_phone.user)\n return Response(status=200)\n\n if data[\"action\"] == \"remove\":\n phone_object = Phone.query.filter_by(phone=phone).first()\n if phone_object is None:\n return Response(status=400)\n\n db.session.delete(phone_object)\n db.session.commit()\n\n Webhook.send_event('Phone Removed', phone_object.user)\n return Response(status=200)\n\n\n@app.route('/api/alarm', methods=[\"POST\"])\ndef rust():\n if request.headers.get('x-auth-key') != env_data[\"data\"][\"general\"][\"auth_key\"]:\n abort(403)\n else:\n data = request.json\n alarm_id = data[\"body\"].replace(' ', '').split(\"id:\")[1]\n try:\n alarm_id = int(alarm_id)\n except ValueError:\n return Response(status=400)\n\n db.session.add(AlarmLog(alarm_id))\n db.session.commit()\n\n alarm = Alarm.query.filter_by(id=alarm_id).first()\n\n if alarm.cooldown_expiration > time.time():\n return 'Success [Cooldown]'\n\n if alarm.send_notification: # Courtyard, Roof, SAM, Open Core [Ignore Doorcamp]\n user_body = data[\"body\"].replace(f'id:{alarm_id}', '')\n\n send_alerts(db.session.query(Phone.phone).all(), body=user_body)\n\n socket_.emit('raid', server)\n\n alarm.cooldown_expiration = int(time.time()) + cooldown\n db.session.commit()\n\n Webhook.send_event('Raid Alarm', alarm_id)\n return 'Success'\n\n\nclass Phone(db.Model):\n __tablename__ = \"phones\"\n\n id = db.Column(db.String, primary_key=True)\n phone = db.Column(db.String, nullable=False)\n user = db.Column(db.String, nullable=False)\n\n def __init__(self, phone, user):\n self.id = str(uuid4())\n self.phone = phone\n self.user = user\n\n def __repr__(self):\n return ''.format(self.phone)\n\n\nclass AlarmLog(db.Model):\n __tablename__ = \"alarm_log\"\n id = db.Column(db.String, primary_key=True)\n alarm_id = db.Column(db.String, ForeignKey('alarm.id'), nullable=False)\n time = db.Column(db.String, nullable=False)\n\n def __init__(self, alarm_id):\n self.id = str(uuid4())\n if Alarm.query.filter_by(id=alarm_id).first() is None:\n db.session.add(Alarm(alarm_id))\n self.alarm_id = alarm_id\n self.time = time.time()\n\n def __repr__(self):\n return ''.format(self.id)\n\n\nclass Alarm(db.Model):\n __tablename__ = \"alarm\"\n id = db.Column(db.Integer, primary_key=True) # use Rust alarm ID (not UUID)\n\n send_notification = db.Column(db.Boolean, nullable=False)\n cooldown_expiration = db.Column(db.Integer, nullable=False)\n history = relationship(AlarmLog)\n\n def __init__(self, alarm_id):\n self.id = alarm_id\n if alarm_id >= 0:\n self.send_notification = True\n else:\n self.send_notification = False\n\n self.cooldown_expiration = 0\n\n def __repr__(self):\n return ''.format(self.id)\n\n\nif __name__ == \"__main__\":\n socket_.run(app, port=6262, allow_unsafe_werkzeug=True)", "repo_name": "Cats0001/rust-defense", "sub_path": "rustDefense/server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 5026, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "json.load", "line_number": 13, "usage_type": "call"}, {"api_name": "srcs.helpers.WebhookSender", "line_number": 19, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 23, "usage_type": "call"}, {"api_name": "flask_socketio.SocketIO", "line_number": 24, "usage_type": "call"}, {"api_name": "flask_sqlalchemy.SQLAlchemy", "line_number": 29, "usage_type": "call"}, {"api_name": "threading.Lock", "line_number": 32, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 43, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 43, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 43, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 46, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 46, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 46, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 50, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 57, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 57, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 59, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 64, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 67, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 74, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 79, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 85, "usage_type": "call"}, {"api_name": "flask.request.headers.get", "line_number": 90, "usage_type": "call"}, {"api_name": "flask.request.headers", "line_number": 90, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 90, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 91, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 93, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 93, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 98, "usage_type": "call"}, {"api_name": "time.time", "line_number": 105, "usage_type": "call"}, {"api_name": "srcs.helpers.send_alerts", "line_number": 111, "usage_type": "call"}, {"api_name": "time.time", "line_number": 115, "usage_type": "call"}, {"api_name": "uuid.uuid4", "line_number": 130, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 141, "usage_type": "call"}, {"api_name": "uuid.uuid4", "line_number": 145, "usage_type": "call"}, {"api_name": "time.time", "line_number": 149, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.relationship", "line_number": 161, "usage_type": "call"}]} +{"seq_id": "38699174362", "text": "from urllib.request import urlopen\n\nfrom bs4 import BeautifulSoup\nfrom nltk.corpus import wordnet\n\nstart = \"Reindeer\"\ngoal = \"Flying Saucer\"\nsatisfiablePercent = .75\nwiki = \"https://en.wikipedia.org/wiki/\"\nnext_from_start = \"\"\nnext_from_goal = \"\"\n\n\ndef next_page(page, visited):\n url = wiki\n url += page\n website = urlopen(url)\n html = website.read()\n soup = BeautifulSoup(html, \"html.parser\")\n links = soup.findAll('a', href=True)\n current_best = [\"\", -1]\n for link in links:\n link = link['href']\n if not (link[:5] != \"/wiki\" or link[:-3] == (\"JPG\" or \"jpg\" or \"png\") or (\n len(link) >= 14 and link[6:14] == \"Category\") or (len(link) >= 16 and link[6:16] == \"Wikipedia:\") or (\n len(link) >= 14 and link[6:14] == \"Special:\") or (len(link) >= 10 and link[6:10] == \"File\") or (\n len(link) >= 13 and link[6:13] == \"Portal:\") or (\n len(link) >= 15 and link[6:15] == \"Main_Page\") or (\n len(link) >= 10 and link[6:10] == \"Help\") or (\n len(link) > 16 and link[-16] == \"(disambiguation)\")):\n link = link[6:]\n if link not in visited and link == goal:\n return link\n synsets = wordnet.synsets(link)\n if synsets and link not in visited:\n w1 = synsets[0]\n score = w1.wup_similarity(goal_synset)\n if score >= satisfiablePercent:\n return link\n elif score > current_best[1]:\n current_best[0] = link\n current_best[1] = score\n return current_best[0]\n\n\ndef bidirectional_wall(next_start, next_goal, s_v, g_v):\n global next_from_goal, next_from_start, satisfiablePercent\n keep_going = True\n if s_v:\n start_visited = s_v\n else:\n start_visited = [next_start]\n if g_v:\n goal_visited = g_v\n else:\n goal_visited = [next_goal]\n if start:\n if next_start == goal:\n total = len(start_visited)\n print(\"You can reach the goal in \" + str(total - 1) + \" clicks.\")\n print(start_visited)\n print_wiki_links(start_visited)\n keep_going = False\n if next_start in goal_visited and keep_going:\n i = goal_visited.index(next_start)\n goal_visited = goal_visited[:i]\n goal_visited = goal_visited[::-1]\n path = start_visited\n path.extend(goal_visited[:i + 1])\n total = len(path) - 2\n print(\"You can reach the goal in \" + str(total) + \" clicks.\")\n print(path)\n print_wiki_links(path)\n keep_going = False\n else:\n next_from_start = next_page(next_start, start_visited)\n retries = 5\n while next_from_start == \"\" and retries > 0:\n satisfiablePercent -= 0.08\n next_from_start = next_page(next_start, start_visited)\n retries -= 1\n print(\n \"Retrying with next_start: \" + str(next_start) + \", start_visited: \" + str(start_visited) +\n \", satisfiablePercent: \" + str(satisfiablePercent))\n if next_from_start == \"\":\n raise Exception(\"Unable to find a path\")\n start_visited.append(next_from_start)\n if keep_going:\n if next_goal in start_visited:\n r = start_visited.index(next_goal)\n goal_visited = goal_visited[::-1]\n path = start_visited[:r + 1]\n path.extend(goal_visited[1:])\n total = len(path) - 2\n print(\"You can reach the goal in \" + str(total) + \" clicks.\")\n print(path)\n print_wiki_links(path)\n keep_going = False\n else:\n next_from_goal = next_page(next_goal, goal_visited)\n goal_visited.append(next_from_goal)\n if keep_going:\n if next_from_start != \"\":\n print(\"next_from_start: \" + next_from_start)\n if next_from_goal != \"\":\n print(\"next_from_goal: \" + next_from_goal)\n bidirectional_wall(next_from_start, next_from_goal,\n start_visited, goal_visited)\n\n\ndef print_wiki_links(visited_strings):\n for item in visited_strings:\n print(wiki + item)\n\n\ndef multiple_word_wiki_link(target_words):\n target_parts = target_words.split(\" \")\n is_first = True\n result = \"\"\n sep = \"\"\n for part in target_parts:\n if is_first:\n is_first = False\n else:\n sep = \"_\"\n part = part.lower()\n result = result + sep + part\n return result\n\n\nif ' ' in goal:\n goal = multiple_word_wiki_link(goal)\nif ' ' in start:\n start = multiple_word_wiki_link(start)\n\nprint(\"goal_string: \" + goal)\ngoal_synset = wordnet.synset(goal + \".n.01\")\nbidirectional_wall(start, goal, [], [])\n", "repo_name": "ekitrak/Wikipedia-Challenge-Solver-Python3", "sub_path": "Bwall.py", "file_name": "Bwall.py", "file_ext": "py", "file_size_in_byte": 4937, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "25", "api": [{"api_name": "urllib.request.urlopen", "line_number": 17, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 19, "usage_type": "call"}, {"api_name": "nltk.corpus.wordnet.synsets", "line_number": 34, "usage_type": "call"}, {"api_name": "nltk.corpus.wordnet", "line_number": 34, "usage_type": "name"}, {"api_name": "nltk.corpus.wordnet.synset", "line_number": 137, "usage_type": "call"}, {"api_name": "nltk.corpus.wordnet", "line_number": 137, "usage_type": "name"}]} +{"seq_id": "33009383194", "text": "import numpy as np\nimport sys\nimport datasets\nimport copy\nimport pickle\n\nmodels_stem = '/om/user/scasper/workspace/models/'\ncsvs_stem = '/om/user/scasper/workspace/csvs/'\n\nclass DNN(object):\n\n def __init__(self):\n self.name = \"ResNet\"\n self.layers = 5 # not including the logits output layer\n self.factor = 1\n self.factor_end = 1\n\n\nclass Hyperparameters(object):\n\n def __init__(self):\n self.batch_size = 3072\n\n\nclass Experiments(object):\n\n def __init__(self, id, dataset, output_path, family_id, family_name,\n results_dir=models_stem + 'resnet_imagenet/',\n csv_dir=csvs_stem + 'resnet_imagenet/'):\n self.log_dir_base = output_path\n self.results_dir = results_dir\n self.csv_dir = csv_dir\n\n # Recordings\n self.max_to_keep_checkpoints = 2\n\n # Test after training:\n self.skip_train = False\n\n # Start from scratch even if it existed\n self.restart = False\n\n # Skip running experiments\n self.skip = False\n\n # Save extense summary\n self.extense_summary = True\n\n self.ID = id\n self.name = \"ID\" + str(id)\n\n self.family_ID = family_id\n self.family_name = family_name\n\n # Add additional descriptors to Experiments\n self.dataset = dataset\n self.dnn = DNN()\n self.hyper = Hyperparameters()\n\n self.time_step = 0\n\n\ndef get_experiments(output_path, dataset_path):\n\n opt_data = datasets.get_datasets(dataset_path)\n\n # # #\n # Create set of experiments\n opt = []\n\n idx_base = 0\n idx_family = 0\n\n # RESNETS\n\n # Maximum batch size per size\n # id 0-4\n for n_multiplier, batch_size in zip([0.25, 0.5, 1, 2, 4], [8192, 4096, 3072, 1024, 512]):\n opt_handle = Experiments(id=idx_base,\n dataset=opt_data[0], output_path=output_path,\n family_id=idx_family, family_name=\"ResNet18\")\n\n opt_handle.skip_train = False\n opt_handle.dnn.name = \"resnet\"\n opt_handle.dnn.factor = n_multiplier\n opt_handle.hyper.batch_size = batch_size\n opt += [copy.deepcopy(opt_handle)]\n idx_base += 1\n\n # batch size = 4096\n ### 0.5 already calculated!\n # id 5\n for n_multiplier in [0.25]:\n opt_handle = Experiments(id=idx_base,\n dataset=opt_data[0], output_path=output_path,\n family_id=idx_family, family_name=\"ResNet18\")\n\n opt_handle.skip_train = False\n opt_handle.dnn.name = \"resnet\"\n opt_handle.dnn.factor = n_multiplier\n opt_handle.hyper.batch_size = 4096\n opt += [copy.deepcopy(opt_handle)]\n idx_base += 1\n\n # batch size = 2048\n # id 6 - 8\n for n_multiplier in [0.25, 0.5, 1]:\n opt_handle = Experiments(id=idx_base,\n dataset=opt_data[0], output_path=output_path,\n family_id=idx_family, family_name=\"ResNet18\")\n\n opt_handle.skip_train = False\n opt_handle.dnn.name = \"resnet\"\n opt_handle.dnn.factor = n_multiplier\n opt_handle.hyper.batch_size = 2048\n opt += [copy.deepcopy(opt_handle)]\n idx_base += 1\n\n # batch size = 1024\n ### 2 already calculated!\n # id 9 - 11\n for n_multiplier in [0.25, 0.5, 1]:\n opt_handle = Experiments(id=idx_base,\n dataset=opt_data[0], output_path=output_path,\n family_id=idx_family, family_name=\"ResNet18\")\n\n opt_handle.skip_train = False\n opt_handle.dnn.name = \"resnet\"\n opt_handle.dnn.factor = n_multiplier\n opt_handle.hyper.batch_size = 1024\n opt += [copy.deepcopy(opt_handle)]\n idx_base += 1\n\n # INCEPTIONS\n\n # Maximum batch size per size\n # id 12-14\n for n_multiplier, batch_size in zip([1, 0.25, 0.5], [512, 512, 512]):\n opt_handle = Experiments(id=idx_base,\n dataset=opt_data[0], output_path=output_path,\n family_id=idx_family, family_name=\"Inception_v3\")\n\n opt_handle.skip_train = False\n opt_handle.dnn.name = 'inception'\n opt_handle.dnn.factor = n_multiplier\n opt_handle.hyper.batch_size = batch_size\n opt_handle.dnn.layers = 16 # not including the logits output layer\n opt_handle.results_dir = models_stem + 'inception_imagenet/'\n opt_handle.csv_dir = csvs_stem + 'inception_imagenet/'\n opt += [copy.deepcopy(opt_handle)]\n idx_base += 1\n\n # Maximum batch size per size\n # id 15-18\n for n_multiplier, batch_size in zip([0.25, 0.5, 2, 4], [512, 512, 512, 512]):\n opt_handle = Experiments(id=idx_base,\n dataset=opt_data[0], output_path=output_path,\n family_id=idx_family, family_name=\"Inception_v3\")\n\n opt_handle.skip_train = False\n opt_handle.dnn.name = 'inception'\n opt_handle.dnn.factor = 1\n opt_handle.dnn.factor_end = n_multiplier\n opt_handle.hyper.batch_size = batch_size\n opt_handle.dnn.layers = 16 # not including the logits output layer\n opt_handle.results_dir = models_stem + 'inception_imagenet/'\n opt_handle.csv_dir = csvs_stem + 'inception_imagenet/'\n opt += [copy.deepcopy(opt_handle)]\n idx_base += 1\n\n # RESNET timesteps\n # id 19-38\n for step in range(4):\n for n_multiplier, batch_size in zip([0.25, 0.5, 1, 2, 4], [8192, 4096, 3072, 1024, 512]):\n opt_handle = Experiments(id=idx_base,\n dataset=opt_data[0], output_path=output_path,\n family_id=idx_family, family_name=\"ResNet18\")\n\n opt_handle.time_step = step\n opt_handle.skip_train = False\n opt_handle.dnn.name = \"resnet\"\n opt_handle.dnn.factor = n_multiplier\n opt_handle.hyper.batch_size = batch_size\n opt += [copy.deepcopy(opt_handle)]\n idx_base += 1\n print('OPTS LOOKUP:')\n for ID in range(len(opt)):\n print('ID: ' + str(ID) + ', ' + str(opt[ID].dnn.name) + ', factor: ' +\n str(opt[ID].dnn.factor) + ', batch_size:' + str(opt[ID].hyper.batch_size))\n\n # print(\"Number of experiments:\", len(opt))\n\n return opt\n", "repo_name": "xboix/frivolous_dnns", "sub_path": "ImageNet/experiments/experiments.py", "file_name": "experiments.py", "file_ext": "py", "file_size_in_byte": 6411, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "datasets.get_datasets", "line_number": 65, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 87, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 102, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 116, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 131, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 150, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 168, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 184, "usage_type": "call"}]} +{"seq_id": "24340538155", "text": "import discord\nfrom discord.ext import commands\nimport asyncpraw\nimport asyncio\nimport random\n\n# Create a new Discord client\nintents = discord.Intents().all()\nintents.members = True\nclient = discord.Client(intents=intents)\n\n@client.event\nasync def on_message(message):\n if message.author == client.user:\n return\n # meme me daddy\n reddit = asyncpraw.Reddit(\n client_id=\"REDDIT ID GOES HERE\",\n client_secret=\"REDDIT SECRECT GOES HERE\",\n user_agent=\"Discord_bot\",\n aiohttp_kwargs={\"timeout\": 10},\n )\n list = []\n subreddit = await reddit.subreddit(\"memes\")\n async for submission in subreddit.hot(limit=50):\n list.append(submission)\n await message.channel.send(random.choice(list).url)\n\n# Run the bot\nclient.run('DISCORD TOKEN GOES HERE')\n", "repo_name": "Bread-sauce/Discord_things", "sub_path": "MemeBot/memebot.py", "file_name": "memebot.py", "file_ext": "py", "file_size_in_byte": 804, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "discord.Intents", "line_number": 8, "usage_type": "call"}, {"api_name": "discord.Client", "line_number": 10, "usage_type": "call"}, {"api_name": "asyncpraw.Reddit", "line_number": 17, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 27, "usage_type": "call"}]} +{"seq_id": "73686001984", "text": "from asyncore import read\nfrom urllib import response\nfrom aiohttp import request\nfrom numpy import require\nfrom rest_framework import serializers\n\n# Import Utils models\nfrom apps.trading.models import trading_config, strategy\nfrom apps.strategy.models import strategyNews\nfrom apps.authentication.models import User\nfrom apps.broker.models import broker\nfrom apps.transaction.models import transactions\nfrom django.db.models import Sum\n\n\nclass tradingConfigSerializerPut(serializers.ModelSerializer):\n\n # Bool params not required\n is_active_short = serializers.BooleanField(required=False)\n is_active_long = serializers.BooleanField(required=False)\n quantityUSDLong = serializers.FloatField(required=False)\n useLong = serializers.BooleanField(required=False)\n stopLossLong = serializers.FloatField(required=False)\n takeProfitLong = serializers.FloatField(required=False)\n consecutiveLossesLong = serializers.IntegerField(required=False)\n quantityUSDShort = serializers.FloatField(required=False)\n useShort = serializers.BooleanField(required=False)\n stopLossShort = serializers.FloatField(required=False)\n takeProfitShort = serializers.FloatField(required=False)\n consecutiveLossesShort = serializers.IntegerField(required=False)\n\n is_active = serializers.BooleanField(required=False)\n close_trade_long_and_deactivate = serializers.BooleanField(required=False)\n close_trade_short_and_deactivate = serializers.BooleanField(required=False)\n\n\n class Meta:\n model = trading_config\n # not mandatory fields declaration\n fields = [\n 'is_active_short',\n 'is_active_long',\n 'quantityUSDLong',\n 'useLong',\n 'stopLossLong',\n 'takeProfitLong',\n 'consecutiveLossesLong',\n 'quantityUSDShort',\n 'useShort',\n 'stopLossShort',\n 'takeProfitShort',\n 'consecutiveLossesShort',\n 'is_active',\n 'close_trade_long_and_deactivate',\n 'close_trade_short_and_deactivate',\n ]\n\n \nclass tradingConfigSerializers(serializers.ModelSerializer):\n\n # Declarate the next serializer to use\n owner = serializers.PrimaryKeyRelatedField(\n read_only=False, queryset=User.objects.all())\n strategyNews = serializers.PrimaryKeyRelatedField(\n read_only=False, queryset=strategyNews.objects.all())\n broker = serializers.PrimaryKeyRelatedField(\n read_only=False, queryset=broker.objects.all())\n \n quantityUSDLong = serializers.FloatField(default=0.0, required=False)\n quantityUSDShort = serializers.FloatField(default=0.0, required=False)\n quantityQTYLong = serializers.FloatField(default=0.0, required=False)\n quantityQTYShort = serializers.FloatField(default=0.0, required=False)\n\n useLong = serializers.BooleanField(default=True)\n stopLossLong = serializers.FloatField(default=-1)\n takeProfitLong = serializers.FloatField(default=-1)\n consecutiveLossesLong = serializers.IntegerField(default=-1)\n\n useShort = serializers.BooleanField(default=False)\n stopLossShort = serializers.FloatField(default=-1)\n takeProfitShort = serializers.FloatField(default=-1)\n consecutiveLossesShort = serializers.IntegerField(default=-1)\n\n is_active = serializers.BooleanField(default=True)\n is_active_short = serializers.BooleanField(default=True)\n is_active_long = serializers.BooleanField(default=True)\n\n close_trade_long_and_deactivate = serializers.BooleanField(default=False)\n close_trade_short_and_deactivate = serializers.BooleanField(default=False)\n\n initialCapitalUSDLong = serializers.FloatField(default=0)\n initialCapitalUSDShort = serializers.FloatField(default=0)\n initialCapitalUSDLong = serializers.FloatField(default=0)\n initialCapitalUSDShort = serializers.FloatField(default=0)\n\n winTradeLong = serializers.FloatField(default=0)\n winTradeShort = serializers.FloatField(default=0)\n closedTradeShort = serializers.FloatField(default=0)\n closedTradeLong = serializers.FloatField(default=0)\n profitPorcentageShort = serializers.FloatField(default=0)\n profitPorcentageLong = serializers.FloatField(default=0)\n\n class Meta:\n\n model = trading_config\n\n fields = [\n 'owner',\n 'strategyNews',\n 'broker',\n 'useLong',\n 'stopLossLong',\n 'takeProfitLong',\n 'consecutiveLossesLong',\n 'quantityUSDShort',\n 'quantityUSDLong',\n 'quantityQTYShort',\n 'quantityQTYLong',\n 'useShort',\n 'stopLossShort',\n 'takeProfitShort',\n 'consecutiveLossesShort',\n 'is_active',\n 'is_active_short',\n 'is_active_long',\n 'close_trade_long_and_deactivate',\n 'close_trade_short_and_deactivate',\n 'initialCapitalUSDLong',\n 'initialCapitalUSDShort',\n 'initialCapitalQTYLong',\n 'initialCapitalQTYShort', \n 'winTradeLong',\n 'winTradeShort',\n 'closedTradeShort',\n 'closedTradeLong',\n 'profitPorcentageShort',\n 'profitPorcentageLong',\n\n ]\n\n def to_representation(self, instance):\n\n\n transactionsData = transactions.objects.filter(\n owner_id=instance.owner.id,\n symbol=instance.strategyNews.symbol,\n isClosed__in=[True],\n strategyNews_id=instance.strategyNews.id,\n trading_config_id=instance.id,\n )\n\n \n transactionsDataLong = transactionsData.filter(\n operation=\"long\",\n is_winner__in=[True]\n\n )\n\n transactionsDataShort = transactionsData.filter(\n operation=\"short\",\n is_winner__in=[True]\n )\n\n transactionsDataTotalShort = transactionsData.filter(\n operation=\"short\",\n )\n \n transactionsDataTotalLong = transactionsData.filter(\n operation=\"long\",\n )\n\n # Count data\n\n transactionsDataLongCount = transactionsDataLong.count()\n transactionsDataShortCount = transactionsDataShort.count() \n transactionsDataTotalLongCount = transactionsDataTotalLong.count()\n transactionsDataTotalShortCount = transactionsDataTotalShort.count()\n\n\n # Get Total Profit\n\n #? ------------------------------------------------------------ \n\n response = super(tradingConfigSerializers,\n self).to_representation(instance)\n\n response['strategyNews_id'] = instance.strategyNews.id\n # Get the strategyNews name\n response['strategyNews_name'] = instance.strategyNews.strategyNews\n response['strategyNews_pusher'] = instance.strategyNews.pusher\n response['symbol_url'] = instance.strategyNews.symbol.url\n response['symbol_name'] = instance.strategyNews.symbol.symbolName\n\n response['symbol_symbolName'] = instance.strategyNews.symbol.symbolName\n\n response['symbol_time'] = str(\n instance.strategyNews.timer) + instance.strategyNews.period[0:1]\n\n response['broker_name'] = instance.broker.broker.title()\n \n response['broker_brokerName'] = instance.broker.brokerName.title()\n\n response['totalNumberOfWinTrades'] = transactionsDataLongCount + transactionsDataShortCount\n\n transactionsDataPrifitData = transactionsData.aggregate(Sum('profit_percentage'))\n if transactionsDataPrifitData['profit_percentage__sum'] is None:\n transactionsDataPrifitData['profit_percentage__sum'] = 0.0\n\n response['totalTradingProfit'] = round(transactionsDataPrifitData['profit_percentage__sum'],1)\n\n response['totalOfTrades'] = transactionsDataTotalLongCount + transactionsDataTotalShortCount\n\n totalProfitUSDSum = transactionsData.aggregate(Sum('profit'))\n if totalProfitUSDSum['profit__sum'] is None:\n totalProfitUSDSum['profit__sum'] = 0.0\n\n response['totalProfitUSD'] =round(totalProfitUSDSum['profit__sum'],1)\n\n response['closedTradeLong'] = transactionsDataTotalLong.count()\n response['closedTradeShort'] = transactionsDataTotalShort.count()\n\n response['initialCapitalUSDLong'] = instance.initialCapitalUSDLong\n response['initialCapitalUSDShort'] = instance.initialCapitalUSDShort\n\n transactionsDataTotalLongSum = transactionsDataTotalLong.aggregate(Sum('profit'))\n\n if transactionsDataTotalLongSum['profit__sum'] is None:\n transactionsDataTotalLongSum['profit__sum'] = 0.0\n\n response['quantityUSDLong'] = instance.initialCapitalUSDShort + round(transactionsDataTotalLongSum['profit__sum'],1)\n\n transactionsDataTotalShortSum = transactionsDataTotalShort.aggregate(Sum('profit'))\n if transactionsDataTotalShortSum['profit__sum'] is None:\n transactionsDataTotalShortSum['profit__sum'] = 0.0\n \n response['quantityUSDShort'] = instance.initialCapitalUSDShort + round(transactionsDataTotalShortSum['profit__sum'],1)\n\n\n\n transactionsDataTotalLongSumPorcentage = transactionsDataTotalLong.aggregate(Sum('profit_percentage'))\n if transactionsDataTotalLongSumPorcentage['profit_percentage__sum'] is None:\n transactionsDataTotalLongSumPorcentage['profit_percentage__sum'] = 0.0\n\n transactionsDataTotalShortSumPorcentage = transactionsDataTotalShort.aggregate(Sum('profit_percentage'))\n if transactionsDataTotalShortSumPorcentage['profit_percentage__sum'] is None:\n transactionsDataTotalShortSumPorcentage['profit_percentage__sum'] = 0.0\n\n\n response['profitPorcentageLong'] = round(transactionsDataTotalLongSumPorcentage['profit_percentage__sum'],1)\n response['profitPorcentageShort'] = round(transactionsDataTotalShortSumPorcentage['profit_percentage__sum'],1)\n \n\n response['id'] = instance.id\n\n return response\n\n\nclass strategySerializers(serializers.ModelSerializer):\n\n class Meta:\n model = strategy\n\n fields = [\n 'strategy',\n 'order',\n 'contracts',\n 'ticker',\n 'position_size',\n ]\n\n\n", "repo_name": "cannavit/tactictrade-api", "sub_path": "apps/trading/serializers.py", "file_name": "serializers.py", "file_ext": "py", "file_size_in_byte": 10429, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 16, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 16, "usage_type": "name"}, {"api_name": "rest_framework.serializers.BooleanField", "line_number": 19, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 19, "usage_type": "name"}, {"api_name": "rest_framework.serializers.BooleanField", "line_number": 20, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 20, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 21, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 21, "usage_type": "name"}, {"api_name": "rest_framework.serializers.BooleanField", "line_number": 22, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 22, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 23, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 23, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 24, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 24, "usage_type": "name"}, {"api_name": "rest_framework.serializers.IntegerField", "line_number": 25, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 25, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 26, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 26, "usage_type": "name"}, {"api_name": "rest_framework.serializers.BooleanField", "line_number": 27, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 27, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 28, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 28, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 29, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 29, "usage_type": "name"}, {"api_name": "rest_framework.serializers.IntegerField", "line_number": 30, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 30, "usage_type": "name"}, {"api_name": "rest_framework.serializers.BooleanField", "line_number": 32, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 32, "usage_type": "name"}, {"api_name": "rest_framework.serializers.BooleanField", "line_number": 33, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 33, "usage_type": "name"}, {"api_name": "rest_framework.serializers.BooleanField", "line_number": 34, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 34, "usage_type": "name"}, {"api_name": "apps.trading.models.trading_config", "line_number": 38, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 59, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 59, "usage_type": "name"}, {"api_name": "rest_framework.serializers.PrimaryKeyRelatedField", "line_number": 62, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 62, "usage_type": "name"}, {"api_name": "apps.authentication.models.User.objects.all", "line_number": 63, "usage_type": "call"}, {"api_name": "apps.authentication.models.User.objects", "line_number": 63, "usage_type": "attribute"}, {"api_name": "apps.authentication.models.User", "line_number": 63, "usage_type": "name"}, {"api_name": "apps.strategy.models.strategyNews", "line_number": 64, "usage_type": "name"}, {"api_name": "rest_framework.serializers.PrimaryKeyRelatedField", "line_number": 64, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 64, "usage_type": "name"}, {"api_name": "apps.strategy.models.strategyNews.objects.all", "line_number": 65, "usage_type": "call"}, {"api_name": "apps.strategy.models.strategyNews.objects", "line_number": 65, "usage_type": "attribute"}, {"api_name": "apps.strategy.models.strategyNews", "line_number": 65, "usage_type": "name"}, {"api_name": "apps.broker.models.broker", "line_number": 66, "usage_type": "name"}, {"api_name": "rest_framework.serializers.PrimaryKeyRelatedField", "line_number": 66, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 66, "usage_type": "name"}, {"api_name": "apps.broker.models.broker.objects.all", "line_number": 67, "usage_type": "call"}, {"api_name": "apps.broker.models.broker.objects", "line_number": 67, "usage_type": "attribute"}, {"api_name": "apps.broker.models.broker", "line_number": 67, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 69, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 69, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 70, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 70, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 71, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 71, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 72, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 72, "usage_type": "name"}, {"api_name": "rest_framework.serializers.BooleanField", "line_number": 74, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 74, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 75, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 75, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 76, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 76, "usage_type": "name"}, {"api_name": "rest_framework.serializers.IntegerField", "line_number": 77, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 77, "usage_type": "name"}, {"api_name": "rest_framework.serializers.BooleanField", "line_number": 79, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 79, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 80, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 80, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 81, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 81, "usage_type": "name"}, {"api_name": "rest_framework.serializers.IntegerField", "line_number": 82, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 82, "usage_type": "name"}, {"api_name": "rest_framework.serializers.BooleanField", "line_number": 84, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 84, "usage_type": "name"}, {"api_name": "rest_framework.serializers.BooleanField", "line_number": 85, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 85, "usage_type": "name"}, {"api_name": "rest_framework.serializers.BooleanField", "line_number": 86, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 86, "usage_type": "name"}, {"api_name": "rest_framework.serializers.BooleanField", "line_number": 88, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 88, "usage_type": "name"}, {"api_name": "rest_framework.serializers.BooleanField", "line_number": 89, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 89, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 91, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 91, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 92, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 92, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 93, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 93, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 94, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 94, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 96, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 96, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 97, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 97, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 98, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 98, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 99, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 99, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 100, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 100, "usage_type": "name"}, {"api_name": "rest_framework.serializers.FloatField", "line_number": 101, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 101, "usage_type": "name"}, {"api_name": "apps.trading.models.trading_config", "line_number": 105, "usage_type": "name"}, {"api_name": "apps.transaction.models.transactions.objects.filter", "line_number": 144, "usage_type": "call"}, {"api_name": "apps.transaction.models.transactions.objects", "line_number": 144, "usage_type": "attribute"}, {"api_name": "apps.transaction.models.transactions", "line_number": 144, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 184, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 187, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 189, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 190, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 191, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 192, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 194, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 196, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 199, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 201, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 203, "usage_type": "name"}, {"api_name": "django.db.models.Sum", "line_number": 205, "usage_type": "call"}, {"api_name": "urllib.response", "line_number": 209, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 211, "usage_type": "name"}, {"api_name": "django.db.models.Sum", "line_number": 213, "usage_type": "call"}, {"api_name": "urllib.response", "line_number": 217, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 219, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 220, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 222, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 223, "usage_type": "name"}, {"api_name": "django.db.models.Sum", "line_number": 225, "usage_type": "call"}, {"api_name": "urllib.response", "line_number": 230, "usage_type": "name"}, {"api_name": "django.db.models.Sum", "line_number": 232, "usage_type": "call"}, {"api_name": "urllib.response", "line_number": 236, "usage_type": "name"}, {"api_name": "django.db.models.Sum", "line_number": 240, "usage_type": "call"}, {"api_name": "django.db.models.Sum", "line_number": 244, "usage_type": "call"}, {"api_name": "urllib.response", "line_number": 249, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 250, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 253, "usage_type": "name"}, {"api_name": "urllib.response", "line_number": 255, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 258, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 258, "usage_type": "name"}, {"api_name": "apps.trading.models.strategy", "line_number": 261, "usage_type": "name"}]} +{"seq_id": "19709159779", "text": "import unittest\nfrom collections import namedtuple\nfrom difflib import unified_diff\nfrom pathlib import Path\n\nfrom commands import Init, Checkout, Commit, Add\nfrom commitobject import CommitObject\nfrom message_writer import MessageWriter\nfrom repository import Repository\nfrom tests.testcases import RepositoryTestCase\nfrom utils.file_utils import write_file, get_files, read_file\nfrom utils.main_file_utils import write_main_file\n\n\nclass TestCommit(RepositoryTestCase):\n def setUp(self):\n super().setUp()\n\n # как будто пишем в /dev/null, эта часть логов не нужна\n Init().execute(Repository(), None, MessageWriter())\n files = list(get_files('*', filter_by_gitignore=True))\n\n _commits_dir = Path('.goodgit') / 'commits'\n _commit1 = CommitObject('', '', files, None, 1)\n write_file(_commits_dir / '1_info', (str(_commit1),))\n _commits_dir /= '1'\n _commits_dir.mkdir()\n\n for i in files:\n write_file(_commits_dir / str(i),\n (j.strip('\\n')\n for j in unified_diff(list(), list(read_file(i)))))\n\n _branches = {'master': _commit1, 'head': _commit1}\n _tags = {'release-1': _commit1}\n write_main_file('master', _branches, _tags)\n\n self._repo = Repository()\n self._args = namedtuple('CommitArgs', ['message'])\n\n def test_commit_to_tag_is_restricted(self):\n Checkout().execute(self._repo,\n namedtuple('name', ['pointer'])('release-1'),\n MessageWriter())\n\n Commit().execute(self._repo, self._args('1'), self._writer)\n self.assertFileContentsEqual(self._log, ('it\\'s impossible to commit '\n 'to this pointer! checkout '\n 'branch before',))\n\n def test_commit_to_commit_is_restricted(self):\n Checkout().execute(self._repo,\n namedtuple('name', ['pointer'])('1'),\n MessageWriter())\n\n Commit().execute(self._repo, self._args('1'), self._writer)\n self.assertFileContentsEqual(self._log, ('it\\'s impossible to commit '\n 'to this pointer! checkout '\n 'branch before',))\n\n def test_commit_when_nothing_in_index(self):\n Commit().execute(self._repo, self._args('1'), self._writer)\n self.assertFileContentsEqual(self._log, ('nothing to commit!',))\n\n def test_commit_if_nothing_changed(self):\n Add().execute(self._repo, namedtuple('Add', ['path'])('*'),\n MessageWriter())\n\n Commit().execute(self._repo, self._args('1'), self._writer)\n self.assertFileContentsEqual(self._log, ('nothing to commit!',))\n\n\nif __name__ == '__main__':\n unittest.main()\n", "repo_name": "Themplarer/cvs", "sub_path": "tests/test_commit.py", "file_name": "test_commit.py", "file_ext": "py", "file_size_in_byte": 2926, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "tests.testcases.RepositoryTestCase", "line_number": 15, "usage_type": "name"}, {"api_name": "commands.Init", "line_number": 20, "usage_type": "call"}, {"api_name": "repository.Repository", "line_number": 20, "usage_type": "call"}, {"api_name": "message_writer.MessageWriter", "line_number": 20, "usage_type": "call"}, {"api_name": "utils.file_utils.get_files", "line_number": 21, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 23, "usage_type": "call"}, {"api_name": "commitobject.CommitObject", "line_number": 24, "usage_type": "call"}, {"api_name": "utils.file_utils.write_file", "line_number": 25, "usage_type": "call"}, {"api_name": "utils.file_utils.write_file", "line_number": 30, "usage_type": "call"}, {"api_name": "difflib.unified_diff", "line_number": 32, "usage_type": "call"}, {"api_name": "utils.file_utils.read_file", "line_number": 32, "usage_type": "call"}, {"api_name": "utils.main_file_utils.write_main_file", "line_number": 36, "usage_type": "call"}, {"api_name": "repository.Repository", "line_number": 38, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 39, "usage_type": "call"}, {"api_name": "commands.Checkout", "line_number": 42, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 43, "usage_type": "call"}, {"api_name": "message_writer.MessageWriter", "line_number": 44, "usage_type": "call"}, {"api_name": "commands.Commit", "line_number": 46, "usage_type": "call"}, {"api_name": "commands.Checkout", "line_number": 52, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 53, "usage_type": "call"}, {"api_name": "message_writer.MessageWriter", "line_number": 54, "usage_type": "call"}, {"api_name": "commands.Commit", "line_number": 56, "usage_type": "call"}, {"api_name": "commands.Commit", "line_number": 62, "usage_type": "call"}, {"api_name": "commands.Add", "line_number": 66, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 66, "usage_type": "call"}, {"api_name": "message_writer.MessageWriter", "line_number": 67, "usage_type": "call"}, {"api_name": "commands.Commit", "line_number": 69, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 74, "usage_type": "call"}]} +{"seq_id": "28799909796", "text": "## (Squeeze-Excite) SE-XResNet v0.1 compiled by Michael M. Pieler\n# Based on the following resources:\n# https://github.com/fastai/fastai_dev/blob/master/dev/11_layers.ipynb\n# https://github.com/fastai/fastai_dev/blob/master/dev/11a_vision_models_xresnet.ipynb\n# https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/senet.py#L85\n\nfrom fastai.torch_core import *\nimport torch.nn as nn\nimport torch,math,sys\nimport torch.utils.model_zoo as model_zoo\nfrom functools import partial\nfrom fastai.torch_core import Module\nimport torch.nn.functional as F\n\n\n## Try self-attention module?\n## Try better init?\n\n\n# Unmodified from: https://github.com/fastai/fastai_dev/blob/master/dev/11_layers.ipynb\nNormType = Enum('NormType', 'Batch BatchZero Weight Spectral')\n\ndef BatchNorm(nf, norm_type=NormType.Batch, ndim=2, **kwargs):\n \"BatchNorm layer with `nf` features and `ndim` initialized depending on `norm_type`.\"\n assert 1 <= ndim <= 3\n bn = getattr(nn, f\"BatchNorm{ndim}d\")(nf, **kwargs)\n bn.bias.data.fill_(1e-3)\n bn.weight.data.fill_(0. if norm_type==NormType.BatchZero else 1.)\n return bn\n\n\n# Unmodified from: https://github.com/fastai/fastai_dev/blob/master/dev/11_layers.ipynb\ndef _conv_func(ndim=2, transpose=False):\n \"Return the proper conv `ndim` function, potentially `transposed`.\"\n assert 1 <= ndim <=3\n return getattr(nn, f'Conv{\"Transpose\" if transpose else \"\"}{ndim}d')\n \ndefaults.activation=nn.ReLU\n\nclass ConvLayer(nn.Sequential):\n \"Create a sequence of convolutional (`ni` to `nf`), ReLU (if `use_activ`) and `norm_type` layers.\"\n def __init__(self, ni, nf, ks=3, stride=1, padding=None, bias=None, ndim=2, norm_type=NormType.Batch,\n act_cls=defaults.activation, transpose=False, init=nn.init.kaiming_normal_, xtra=None):\n if padding is None: padding = ((ks-1)//2 if not transpose else 0)\n bn = norm_type in (NormType.Batch, NormType.BatchZero)\n if bias is None: bias = not bn\n conv_func = _conv_func(ndim, transpose=transpose)\n conv = init_default(conv_func(ni, nf, kernel_size=ks, bias=bias, stride=stride, padding=padding), init)\n if norm_type==NormType.Weight: conv = weight_norm(conv)\n elif norm_type==NormType.Spectral: conv = spectral_norm(conv)\n layers = [conv]\n if act_cls is not None: layers.append(act_cls())\n if bn: layers.append(BatchNorm(nf, norm_type=norm_type, ndim=ndim))\n if xtra: layers.append(xtra)\n super().__init__(*layers)\n\nclass AdaptiveConcatPool2d(nn.Module):\n \"Layer that concats `AdaptiveAvgPool2d` and `AdaptiveMaxPool2d`\"\n def __init__(self, size=None):\n super().__init__()\n self.size = size or 1\n self.ap = nn.AdaptiveAvgPool2d(self.size)\n self.mp = nn.AdaptiveMaxPool2d(self.size)\n def forward(self, x): return torch.cat([self.mp(x), self.ap(x)], 1)\n\n\nclass Flatten(Module):\n \"Flatten `x` to a single dimension, often used at the end of a model. `full` for rank-1 tensor\"\n def __init__(self, full=False): self.full = full\n def forward(self, x): return x.view(-1) if self.full else x.view(x.size(0), -1)\n\n\n# SE block based on: https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/senet.py#L85\nclass SE_Module(Module): # change nn.Module to Module\n\n def __init__(self, channels, reduction=16):\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\n self.fc1 = nn.Conv2d(channels, channels // reduction, kernel_size=1,\n padding=0)\n self.relu = nn.ReLU(inplace=True)\n self.fc2 = nn.Conv2d(channels // reduction, channels, kernel_size=1,\n padding=0)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n module_input = x\n x = self.avg_pool(x)\n x = self.fc1(x)\n x = self.relu(x)\n x = self.fc2(x)\n x = self.sigmoid(x)\n return module_input * x\n\n\n# Based on: https://github.com/fastai/fastai_dev/blob/master/dev/11_layers.ipynb\nclass SE_ResBlock(nn.Module):\n \"Resnet block from `ni` to `nh` with `stride`\"\n def __init__(self, expansion, ni, nh, stride=1, norm_type=NormType.Batch, **kwargs):\n super().__init__()\n norm2 = NormType.BatchZero if norm_type==NormType.Batch else norm_type\n nf,ni = nh*expansion,ni*expansion\n layers = [ConvLayer(ni, nh, 3, stride=stride, norm_type=norm_type, **kwargs),\n ConvLayer(nh, nf, 3, norm_type=norm2, act_cls=None)\n ] if expansion == 1 else [\n ConvLayer(ni, nh, 1, norm_type=norm_type, **kwargs),\n ConvLayer(nh, nh, 3, stride=stride, norm_type=norm_type, **kwargs),\n ConvLayer(nh, nf, 1, norm_type=norm2, act_cls=None, **kwargs)\n ]\n self.convs = nn.Sequential(*layers, SE_Module(nf))\n self.idconv = noop if ni==nf else ConvLayer(ni, nf, 1, act_cls=None, **kwargs)\n self.pool = noop if stride==1 else nn.AvgPool2d(2, ceil_mode=True)\n #self.act = defaults.activation(inplace=True)\n self.act = defaults.activation() # does not work with Mish\n\n def forward(self, x): return self.act(self.convs(x) + self.idconv(self.pool(x)))\n\n\n# Unmodified from: https://github.com/fastai/fastai_dev/blob/master/dev/11a_vision_models_xresnet.ipynb\ndef init_cnn(m):\n if getattr(m, 'bias', None) is not None: nn.init.constant_(m.bias, 0)\n if isinstance(m, (nn.Conv2d,nn.Linear)): nn.init.kaiming_normal_(m.weight)\n for l in m.children(): init_cnn(l)\n\n\n# Based on: https://github.com/fastai/fastai_dev/blob/master/dev/11a_vision_models_xresnet.ipynb\nclass SE_XResNet(nn.Sequential):\n def __init__(self, expansion, layers, c_in=3, c_out=1000):\n \n stem = []\n sizes = [c_in,32,32,64]\n \n for i in range(3):\n stem.append(ConvLayer(sizes[i], sizes[i+1], stride=2 if i==0 else 1))\n\n block_szs = [64//expansion,64,128,256,512]\n blocks = [self._make_layer(expansion, block_szs[i], block_szs[i+1], l, 1 if i==0 else 2)\n for i,l in enumerate(layers)]\n super().__init__(\n *stem,\n nn.MaxPool2d(kernel_size=3, stride=2, padding=1),\n *blocks,\n AdaptiveConcatPool2d(), Flatten(), # instead of nn.AdaptiveAvgPool2d(1)\n nn.Linear(block_szs[-1]*expansion*2, c_out) # multiply by 2 because we use AdaptiveConcatPool2d()!\n )\n init_cnn(self)\n\n def _make_layer(self, expansion, ni, nf, blocks, stride):\n return nn.Sequential(\n *[SE_ResBlock(expansion, ni if i==0 else nf, nf, stride if i==0 else 1)\n for i in range(blocks)])", "repo_name": "MicPie/pytorch", "sub_path": "se_xresnet.py", "file_name": "se_xresnet.py", "file_ext": "py", "file_size_in_byte": 6706, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "25", "api": [{"api_name": "torch.nn", "line_number": 26, "usage_type": "argument"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "argument"}, {"api_name": "torch.nn.ReLU", "line_number": 38, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 38, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 40, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 40, "usage_type": "name"}, {"api_name": "torch.nn.init", "line_number": 43, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 43, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 57, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 57, "usage_type": "name"}, {"api_name": "torch.nn.AdaptiveAvgPool2d", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 62, "usage_type": "name"}, {"api_name": "torch.nn.AdaptiveMaxPool2d", "line_number": 63, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 63, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 64, "usage_type": "call"}, {"api_name": "fastai.torch_core.Module", "line_number": 67, "usage_type": "name"}, {"api_name": "fastai.torch_core.Module", "line_number": 74, "usage_type": "name"}, {"api_name": "torch.nn.AdaptiveAvgPool2d", "line_number": 77, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 77, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 78, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 80, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 81, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 81, "usage_type": "name"}, {"api_name": "torch.nn.Sigmoid", "line_number": 83, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 83, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 96, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 96, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 109, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 109, "usage_type": "name"}, {"api_name": "torch.nn.AvgPool2d", "line_number": 111, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 111, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 120, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 120, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 120, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 121, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 121, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 121, "usage_type": "attribute"}, {"api_name": "torch.nn.init.kaiming_normal_", "line_number": 121, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 121, "usage_type": "attribute"}, {"api_name": "torch.nn.Sequential", "line_number": 126, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 126, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 140, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 140, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 143, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 143, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 148, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 148, "usage_type": "name"}]} +{"seq_id": "35074716846", "text": "# -*- coding: utf-8 -*-\nfrom time import sleep\nimport requests\nimport datetime\nimport sqlite3\nimport datetime\nimport time\nimport json\nimport schedule\nimport sys\nimport os\nimport config_file as cfg_file\n\n\ndef make_print_to_file(path='./'):\n '''\n path, it is a path for save your log about fuction print\n example:\n use make_print_to_file() and the all the information of funtion print , will be write in to a log file\n :return:\n '''\n \n class Logger(object):\n def __init__(self, filename=\"Default.log\", path=\"./\"):\n self.terminal = sys.stdout\n self.log = open(os.path.join(path, filename), \"a\", encoding='utf8',)\n \n def write(self, message):\n self.terminal.write(message)\n self.log.write(message)\n \n def flush(self):\n pass\n \n \n fileName = 'add_article.py'+datetime.datetime.now().strftime('day'+'%Y_%m_%d')\n sys.stdout = Logger(fileName + '.log', path=path)\n\n print(fileName.center(60,'*'))\n\n\ndef track(url):\n con = sqlite3.connect('track_db.db')\n cursorObj = con.cursor()\n print (\"DB連接成功...\")\n cursorObj.execute('SELECT * FROM track_list ')\n try:\n sql = f\"INSERT INTO track_list (article_url) VALUES ('{url}')\"\n #print(sql)\n cursorObj.execute(sql)\n con.commit()\n con.close()\n return \"文章新增成功\"\n except:\n return \"文章新增失敗\"\n \n\ndef call_server(today_st_int,today_ed_int):\n url_list=[]\n key_list = ['戴帽子','賊頭','有牌的流氓','波麗士','條子','警察','警官','阿sir','刑事伯','警員','警署','分局','警員','鴿子','派出所']\n my_headers = {'cookie': 'over18=1;'}\n for key in key_list:\n URL = f\"http://140.120.13.248:31111/api/GetByContent?content={key}&start={today_st_int}&end={today_ed_int}&size=200&from=0\"\n response = requests.get(URL, headers = my_headers)\n context = json.loads(response.text)\n #print(context)\n for i in context[\"hits\"]:\n if(i[\"_source\"][\"type\"]==\"article\"):\n print(\"新增\",i[\"_source\"][\"article_title\"])\n url_list.append(i[\"_source\"][\"article_url\"])\n #去掉重複URL\n unique_set = set(url_list)\n url_list = list(unique_set) \n #print(url_list)\n return url_list\n\ndef set_schedule():\n #先抓時間區間轉成時間戳\n today_ed= datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n today_st= (datetime.datetime.now()+datetime.timedelta(hours=-2)).strftime('%Y-%m-%d %H:%M:%S')\n today_st_int = int(time.mktime(time.strptime(today_st, \"%Y-%m-%d %H:%M:%S\")))\n today_ed_int = int(time.mktime(time.strptime(today_ed, \"%Y-%m-%d %H:%M:%S\")))\n print(today_ed)\n url_list = call_server(today_st_int,today_ed_int)\n for url in url_list:\n print(url,track(url))\n print(\"作業完畢...兩小時後再次執行\")\n \n\nif __name__ == '__main__':\n make_print_to_file(path='log')\n print(\"執行中\")\n set_schedule() #先執行一次\n schedule.every(2).hours.do(set_schedule) #每隔一小時執行一次任務\n while(True):\n schedule.run_pending() #run_pending:執行所有可以執行的任務\n sleep(1) #睡眠1秒\n \n \n\n\n", "repo_name": "ioveeagle/LineBot-Ptt_tracker", "sub_path": "add_article.py", "file_name": "add_article.py", "file_ext": "py", "file_size_in_byte": 3270, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sys.stdout", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 36, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 36, "usage_type": "attribute"}, {"api_name": "sys.stdout", "line_number": 37, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 43, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 64, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 65, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 79, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 79, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 80, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 80, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 80, "usage_type": "call"}, {"api_name": "time.mktime", "line_number": 81, "usage_type": "call"}, {"api_name": "time.strptime", "line_number": 81, "usage_type": "call"}, {"api_name": "time.mktime", "line_number": 82, "usage_type": "call"}, {"api_name": "time.strptime", "line_number": 82, "usage_type": "call"}, {"api_name": "schedule.every", "line_number": 94, "usage_type": "call"}, {"api_name": "schedule.run_pending", "line_number": 96, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 97, "usage_type": "call"}]} +{"seq_id": "19998724827", "text": "from fastapi import APIRouter, Depends, HTTPException\nfrom sqlalchemy import select, insert\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom src.auth.auth import current_active_user\nfrom src.auth.models import User\nfrom src.booking.models import apartment, booking\nfrom src.booking.schemas import Apartment, ApartmentCreate, UserApartments, BookingCreate, BookingRead\nfrom src.database import get_async_session\n\nrouter = APIRouter(\n prefix=\"/apartment\",\n tags=['Apartment']\n)\n\n\n@router.get(\"/list/{city}\", response_model=list[Apartment])\nasync def apartment_list_route(city: int, session: AsyncSession = Depends(get_async_session)):\n query = select(apartment).where(apartment.c.city_id == city)\n result = await session.execute(query)\n return result.all()\n\n\n@router.post(\"/create\")\nasync def apartment_create_route(\n new_apartment: ApartmentCreate,\n session: AsyncSession = Depends(get_async_session),\n user: User = Depends(current_active_user),\n):\n try:\n new_apartment.user_id = user.id\n stmt = insert(apartment).values(**new_apartment.dict())\n await session.execute(stmt)\n await session.commit()\n return {\"status\": \"success\"}\n except Exception as e22:\n raise HTTPException(status_code=500, detail={\n \"status\": \"error\",\n \"data\": None,\n \"details\": None\n })\n\n\n@router.get(\"/user-apartments\", response_model=list[UserApartments])\nasync def current_user_apartment_list_route(\n user: User = Depends(current_active_user),\n session: AsyncSession = Depends(get_async_session)\n):\n try:\n query = select(apartment).where(apartment.c.user_id == user.id)\n result = await session.execute(query)\n return result.all()\n except Exception:\n raise HTTPException(status_code=403, detail={\n \"status\": \"error\",\n \"data\": None,\n \"details\": None\n })\n\n\n\n@router.post(\"/booking/create\")\nasync def current_user_booking_list_route(\n new_booking: BookingCreate,\n session: AsyncSession = Depends(get_async_session),\n user: User = Depends(current_active_user),\n):\n try:\n new_booking.user_id = user.id\n stmt = insert(booking).values(**new_booking.dict())\n await session.execute(stmt)\n await session.commit()\n return {\"status\": \"success\"}\n except Exception:\n raise HTTPException(status_code=403, detail={\n \"status\": \"error\",\n \"data\": None,\n \"details\": None\n })\n\n\n@router.get(\"/booking/current-user-list\", response_model=list[BookingRead])\nasync def current_user_booking_list_route(\n user: User = Depends(current_active_user),\n session: AsyncSession = Depends(get_async_session)\n):\n try:\n query = select(booking).where(booking.c.user_id == user.id)\n results = await session.execute(query)\n return results.all()\n except Exception as e:\n print(e)\n raise HTTPException(status_code=403, detail={\n \"status\": \"Error\",\n \"data\": None,\n \"details\": None\n })\n\n\n@router.get(\"/booking/apartment/{apartment_id}\", response_model=list[BookingRead])\nasync def current_user_booking_list_route(\n apartment_id: int,\n session: AsyncSession = Depends(get_async_session)\n):\n try:\n query = select(booking).where(booking.c.apartment_id == apartment_id)\n results = await session.execute(query)\n return results.all()\n except Exception:\n raise HTTPException(status_code=404, detail={\n \"status\": \"Error\",\n \"data\": None,\n \"details\": None\n })", "repo_name": "Artlikeme/nearsea", "sub_path": "src/booking/router.py", "file_name": "router.py", "file_ext": "py", "file_size_in_byte": 3684, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "fastapi.APIRouter", "line_number": 11, "usage_type": "call"}, {"api_name": "sqlalchemy.ext.asyncio.AsyncSession", "line_number": 18, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 18, "usage_type": "call"}, {"api_name": "src.database.get_async_session", "line_number": 18, "usage_type": "argument"}, {"api_name": "sqlalchemy.select", "line_number": 19, "usage_type": "call"}, {"api_name": "src.booking.models.apartment", "line_number": 19, "usage_type": "argument"}, {"api_name": "src.booking.models.apartment.c", "line_number": 19, "usage_type": "attribute"}, {"api_name": "src.booking.schemas.Apartment", "line_number": 17, "usage_type": "name"}, {"api_name": "src.booking.schemas.ApartmentCreate", "line_number": 26, "usage_type": "name"}, {"api_name": "sqlalchemy.ext.asyncio.AsyncSession", "line_number": 27, "usage_type": "name"}, {"api_name": "src.auth.models.User", "line_number": 28, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 27, "usage_type": "call"}, {"api_name": "src.database.get_async_session", "line_number": 27, "usage_type": "argument"}, {"api_name": "fastapi.Depends", "line_number": 28, "usage_type": "call"}, {"api_name": "src.auth.auth.current_active_user", "line_number": 28, "usage_type": "argument"}, {"api_name": "sqlalchemy.insert", "line_number": 32, "usage_type": "call"}, {"api_name": "src.booking.models.apartment", "line_number": 32, "usage_type": "argument"}, {"api_name": "fastapi.HTTPException", "line_number": 37, "usage_type": "call"}, {"api_name": "src.auth.models.User", "line_number": 46, "usage_type": "name"}, {"api_name": "sqlalchemy.ext.asyncio.AsyncSession", "line_number": 47, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 46, "usage_type": "call"}, {"api_name": "src.auth.auth.current_active_user", "line_number": 46, "usage_type": "argument"}, {"api_name": "fastapi.Depends", "line_number": 47, "usage_type": "call"}, {"api_name": "src.database.get_async_session", "line_number": 47, "usage_type": "argument"}, {"api_name": "sqlalchemy.select", "line_number": 50, "usage_type": "call"}, {"api_name": "src.booking.models.apartment", "line_number": 50, "usage_type": "argument"}, {"api_name": "src.booking.models.apartment.c", "line_number": 50, "usage_type": "attribute"}, {"api_name": "fastapi.HTTPException", "line_number": 54, "usage_type": "call"}, {"api_name": "src.booking.schemas.UserApartments", "line_number": 44, "usage_type": "name"}, {"api_name": "src.booking.schemas.BookingCreate", "line_number": 64, "usage_type": "name"}, {"api_name": "sqlalchemy.ext.asyncio.AsyncSession", "line_number": 65, "usage_type": "name"}, {"api_name": "src.auth.models.User", "line_number": 66, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 65, "usage_type": "call"}, {"api_name": "src.database.get_async_session", "line_number": 65, "usage_type": "argument"}, {"api_name": "fastapi.Depends", "line_number": 66, "usage_type": "call"}, {"api_name": "src.auth.auth.current_active_user", "line_number": 66, "usage_type": "argument"}, {"api_name": "sqlalchemy.insert", "line_number": 70, "usage_type": "call"}, {"api_name": "src.booking.models.booking", "line_number": 70, "usage_type": "argument"}, {"api_name": "fastapi.HTTPException", "line_number": 75, "usage_type": "call"}, {"api_name": "src.auth.models.User", "line_number": 84, "usage_type": "name"}, {"api_name": "sqlalchemy.ext.asyncio.AsyncSession", "line_number": 85, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 84, "usage_type": "call"}, {"api_name": "src.auth.auth.current_active_user", "line_number": 84, "usage_type": "argument"}, {"api_name": "fastapi.Depends", "line_number": 85, "usage_type": "call"}, {"api_name": "src.database.get_async_session", "line_number": 85, "usage_type": "argument"}, {"api_name": "sqlalchemy.select", "line_number": 88, "usage_type": "call"}, {"api_name": "src.booking.models.booking", "line_number": 88, "usage_type": "argument"}, {"api_name": "src.booking.models.booking.c", "line_number": 88, "usage_type": "attribute"}, {"api_name": "fastapi.HTTPException", "line_number": 93, "usage_type": "call"}, {"api_name": "src.booking.schemas.BookingRead", "line_number": 82, "usage_type": "name"}, {"api_name": "sqlalchemy.ext.asyncio.AsyncSession", "line_number": 103, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 103, "usage_type": "call"}, {"api_name": "src.database.get_async_session", "line_number": 103, "usage_type": "argument"}, {"api_name": "sqlalchemy.select", "line_number": 106, "usage_type": "call"}, {"api_name": "src.booking.models.booking", "line_number": 106, "usage_type": "argument"}, {"api_name": "src.booking.models.booking.c", "line_number": 106, "usage_type": "attribute"}, {"api_name": "fastapi.HTTPException", "line_number": 110, "usage_type": "call"}, {"api_name": "src.booking.schemas.BookingRead", "line_number": 100, "usage_type": "name"}]} +{"seq_id": "27856222735", "text": "def estimateParams(N,E,I,R,D):\n \"\"\"\n Defines a whole set of parameters to search best fit from\n \"\"\"\n # import dependencies\n import numpy as np\n from lmfit import Parameters\n\n # get values for susceptible population group\n S = [N - (e+i+r+d) for e,i,r,d in zip(E,I,R,D)]\n\n # initialize lists of population groups and rates\n dE, dI, dR, dD = [], [], [], []\n alphas, betas, gammas, deltas = [],[],[],[]\n \n # create lists of all possible parameter values\n for i in range(len(S)-1):\n # update list of population groups\n dE.append(E[i+1]-E[i])\n dI.append(I[i+1]-I[i])\n dR.append(R[i+1]-R[i])\n dD.append(D[i+1]-D[i])\n\n # update list of rates\n alphas.append((dI[-1]+dR[-1]+dD[-1])/E[i])\n betas.append((N*(dE[-1]+dI[-1]+dR[-1]+dD[-1]))/(S[i]*I[i]))\n gammas.append(dR[-1]/I[i])\n deltas.append(dD[-1]/I[i])\n\n # define initial parameters\n params = Parameters()\n params.add(\"alpha\", np.average(alphas), min=min(alphas), max=max(alphas))\n params.add(\"beta\", np.average(betas), min=min(betas), max=max(betas))\n params.add(\"gamma\", np.average(gammas), min=min(gammas), max=max(gammas))\n if min(deltas) != max(deltas):\n params.add(\"delta\", np.average(deltas), min=min(deltas), max=max(deltas))\n else:\n params.add(\"delta\", np.average(deltas), vary=False) \n return params\n\ndef error(params,inits,timespan,data):\n \"\"\"\n Calculates the residual values of estimates\n \"\"\"\n # calls the solver to grab solution\n soln = solver(timespan, inits, params)\n\n return (soln[:,1:]-data).ravel()\n\ndef solver(t, vals, params):\n \"\"\"\n Defines the system of ODEs and uses passed values to update the model\n \"\"\"\n # import dependency (ODE solver) \n from scipy.integrate import odeint\n\n # grab values from passed parameters\n n, e, i, r, d = vals\n\n # calculate s population\n s = n - (e + i + r + d)\n\n # define parameters\n alpha, beta = params[\"alpha\"].value, params[\"beta\"].value\n gamma, delta = params[\"gamma\"].value, params[\"delta\"].value\n\n return odeint(SEIRDModel,[s,e,i,r,d],t,args=(alpha,beta,gamma,delta))\n \ndef SEIRDModel(z, t, alpha, beta, gamma, delta):\n \"\"\"\n Defines the system of ODEs\n \"\"\"\n # grab values\n s, e, i, r, d = z\n N = s + e + i + r + d\n\n # define the differential system\n dS = -(beta*s*e)/N\n dE = (beta*s*e)/N - alpha*e\n dI = alpha*e - gamma*i - delta*i\n dR = gamma*i\n dD = delta*i\n\n return [dS, dE, dI, dR, dD]\n\ndef loadData(path,county,year=2021,months=[10],records=14):\n \"\"\"\n Loads in source data from json file and returns distinct population lists\n \"\"\"\n # import dependencies for loading and reading source files\n from time import strptime\n import json\n\n # initialize lists of distinct population groups\n tested,confirmed,recovered,deceased = [],[],[],[]\n\n # open the file, iterate over each nested dictionary, and append appropriate data\n with open(path) as f:\n data = json.load(f)\n for day, data in data[county][\"dates\"].items():\n day = strptime(day,\"%Y-%m-%d\")\n is_from_last_month = (day.tm_year == year and day.tm_mon in months) \n if data.get(\"total\") and is_from_last_month:\n tested.append(data[\"total\"].get(\"tested\") if data[\"total\"].get(\"tested\") else 0)\n confirmed.append(data[\"total\"].get(\"confirmed\") if data[\"total\"].get(\"confirmed\") else 0)\n recovered.append(data[\"total\"].get(\"recovered\") if data[\"total\"].get(\"recovered\") else 0)\n deceased.append(data[\"total\"].get(\"deceased\") if data[\"total\"].get(\"deceased\") else 0)\n return tested[-records:], confirmed[-records:], recovered[-records:], deceased[-records:]\n\ndef plotCompare(actual,predicted,t,title=\"Population over Time\"):\n \"\"\"\n Plots simulated values against source data values\n \"\"\"\n # import dependencies for plotting\n import matplotlib\n matplotlib.use(\"TkAgg\")\n import matplotlib.pyplot as plt\n\n # plot the comparison\n plt.figure(figsize=(16,9))\n plt.plot(t, actual, color=\"blue\", lw=2, label=\"actual\")\n plt.plot(t, predicted, color=\"orange\", lw=2, label=\"predicted\")\n plt.ylabel(\"Proportion of Population\")\n plt.xlabel(\"Time in days\")\n plt.title(title)\n plt.legend()\n plt.show()\n\n# # # # # #\n\nif __name__ == \"__main__\":\n # import dependencies\n import os\n import numpy as np\n from lmfit import minimize\n\n # define filters\n YEAR = 2021\n MONTHS = [10]\n RECORDS = 14\n COUNTIES = [\"AP\", \"CH\", \"DL\", \"MH\"]\n names = {\"AP\":\"Andhra Pradesh\", \"CH\":\"Chandigarh\", \"DL\":\"Delhi\", \"MH\":\"Maharashtra\"}\n TRAINDAYS = 7\n\n # define population as a constant\n N = 1398705031\n\n # define path to data\n path = os.path.join(\"data\",\"india-data.json\")\n\n # Run simulation for each desired county\n for county in COUNTIES:\n # load data into lists\n E, I, R, D = loadData(path, county, year=YEAR, months=MONTHS, records=RECORDS)\n\n # get parameter estimation ranges based on tdays of data\n params = estimateParams(N,E[:TRAINDAYS],I[:TRAINDAYS],R[:TRAINDAYS],D[:TRAINDAYS])\n\n # convert input data to array to feed into optimizer for residuals calculations\n data = np.concatenate([np.array(i) for i in [E,I,R,D]]).reshape((4,14)).T\n\n # define the initial conditions and period of simulation\n x0 = [N,E[0],I[0],R[0],D[0]]\n period = list(range(len(E)))\n\n # Run the model through optimizer to get best parameters\n result = minimize(error,params,args=(x0,period,data),method=\"leastsq\")\n\n # Run the model using the best parameters\n soln = solver(period,x0,result.params)\n S_p,E_p,I_p,R_p,D_p = soln[:,0],soln[:,1],soln[:,2],soln[:,3],soln[:,4]\n\n # compare the plots of different interest groups\n plotCompare(I,I_p,period,title=f\"{names[county]} Infected Pop over Time\")\n plotCompare(R,R_p,period,title=f\"{names[county]} Recovered Pop over Time\")\n plotCompare(D,D_p,period,title=f\"{names[county]} Deceased Pop over Time\")\n", "repo_name": "factormrp/SEIRD-Model-Simulation", "sub_path": "archivedcomplexmodel.py", "file_name": "archivedcomplexmodel.py", "file_ext": "py", "file_size_in_byte": 6172, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "lmfit.Parameters", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.average", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.average", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.average", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.average", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.average", "line_number": 38, "usage_type": "call"}, {"api_name": "scipy.integrate.odeint", "line_number": 67, "usage_type": "call"}, {"api_name": "json.load", "line_number": 99, "usage_type": "call"}, {"api_name": "time.strptime", "line_number": 101, "usage_type": "call"}, {"api_name": "matplotlib.use", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 121, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 122, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 122, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 123, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 123, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 124, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 126, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 149, "usage_type": "call"}, {"api_name": "os.path", "line_number": 149, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 160, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 160, "usage_type": "call"}, {"api_name": "lmfit.minimize", "line_number": 167, "usage_type": "call"}]} +{"seq_id": "42901605249", "text": "'''\n有许多类别分类器,假设每个分类器准确率有50%,\n如果有1000个分类器\n假设你创建了一个包含1000个分类器的集成,每个分类器都只有51%的概率是\n正确的(几乎不比随机猜测强多少)。如果你以大多数投票的类别作为预测结果,可以期\n待的准确率高达75%。但是,这基于的前提是所有的分类器都是完全独立的,彼此的错误\n毫不相关。显然这是不可能的,因为它们都是在相同的数据上训练的,很可能会犯相同的\n错误,所以也会有很多次大多数投给了错误的类别,导致集成的准确率有所降低\n总之利用多个分类器,再从分类器的各个预测结果情况,预测出最佳预测\n'''\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import make_moons\nimport matplotlib.pyplot as plt\n\n#数据准备\nX, y = make_moons(n_samples=500, noise=0.30, random_state=42)\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\nplt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", alpha=0.5)\nplt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", alpha=0.5)\nplt.show()\n\nlog_clf=LogisticRegression(solver=\"lbfgs\", random_state=42)\nrnd_clf=RandomForestClassifier(n_estimators=100, random_state=42)\nsvm_clf=SVC(gamma=\"scale\", random_state=42)\n\n#训练模型\nvoting_clf = VotingClassifier(\n estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n voting='hard')\nvoting_clf.fit(X_train, y_train)\n\n# 使用投票器分类模型进行预测\nfrom sklearn.metrics import accuracy_score\n\nprint(\"硬投票: \")\nfor clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n #y_probability=clf.predict_proba(X_test)\n print(clf.__class__.__name__, accuracy_score(y_test, y_pred))\n #print(\"概率 : \",y_probability)\n'''\n与可见投票器分类器 更加准确较高\nLogisticRegression 0.864\nRandomForestClassifier 0.896\nSVC 0.896\nVotingClassifier 0.912\n'''\n\n\n\n# 软投票\n'''\n将概率在所有单个分类器上平均,然后让Scikit-Learn给出平均概率最高的类别作为预\n测。这被称为软投票法。\n'''\n'''\n做的就是用voting=\"soft\"代替voting=\"hard\",并确保所\n有分类器都可以估算出概率。默认情况下,SVC类是不行的,所以你需要将其超参数\nprobability设置为True(这会导致SVC使用交叉验证来估算类别概率,减慢训练速度,并\n会添加predict_proba()方法)\n'''\nlog_clf = LogisticRegression(solver=\"lbfgs\", random_state=42)\nrnd_clf = RandomForestClassifier(n_estimators=100, random_state=42)\nsvm_clf = SVC(gamma=\"scale\", probability=True, random_state=42)\n#训练软投票分类器\nvoting_clf = VotingClassifier(\n estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n voting='soft')\nvoting_clf.fit(X_train, y_train)\n\n#使用测试集预测\nprint(\"软投票: \");\nfor clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n print(clf.__class__.__name__, accuracy_score(y_test, y_pred))\n\n", "repo_name": "TdRoseval/machineLearning-deepLearning", "sub_path": "集成学习和随机森林/VotingClassifier.py", "file_name": "VotingClassifier.py", "file_ext": "py", "file_size_in_byte": 3279, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sklearn.datasets.make_moons", "line_number": 21, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "sklearn.linear_model.LogisticRegression", "line_number": 27, "usage_type": "call"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 28, "usage_type": "call"}, {"api_name": "sklearn.svm.SVC", "line_number": 29, "usage_type": "call"}, {"api_name": "sklearn.ensemble.VotingClassifier", "line_number": 32, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 45, "usage_type": "call"}, {"api_name": "sklearn.linear_model.LogisticRegression", "line_number": 68, "usage_type": "call"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 69, "usage_type": "call"}, {"api_name": "sklearn.svm.SVC", "line_number": 70, "usage_type": "call"}, {"api_name": "sklearn.ensemble.VotingClassifier", "line_number": 72, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 82, "usage_type": "call"}]} +{"seq_id": "1962957928", "text": "import imageio\nimport argparse\nimport numpy as np\nfrom glob import glob\nimport os\nimport os.path as osp\nfrom jutils import web_utils\n\nexp2hoi4d_fig = {\n 'ours': 'which_prior_w0.01_exp/{}_suf_smooth_100_CondGeomGlide_cond_all_linear_catTrue_cfgFalse',\n 'ours_wild': 'wild/{}{}',\n 'ihoi_wild': '../ihoi/light_mow/hoi4d/{}',\n\n 'obj_prior': 'which_prior_w0.01_exp/{}_suf_smooth_100_ObjGeomGlide_cond_all_linear_catTrue_cfgFalse',\n 'hand_prior': 'which_prior_w0.01_exp/{}_suf_smooth_100_CondGeomGlide_cond_all_linear_catFalse_cfgFalse',\n 'no_prior': 'pred_no_prior/{}_suf_smooth_100',\n\n 'w_normal': 'ablate_weight/{}_m1.0_n0_d1.0',\n 'w_mask': 'ablate_weight/{}_m0_n1.0_d1.0',\n 'w_depth': 'ablate_weight/{}_m1.0_n1.0_d0',\n 'w_color': 'ablate_color/{}_rgb0',\n 'anneal': 'which_prior_w0.01/{}_suf_smooth_100_CondGeomGlide_cond_all_linear_catTrue_cfgFalse',\n\n 'ihoi': '../ihoi/light_mow/hoi4d/{}',\n 'hhor': '../hhor/hoi4d_go/{}/handscanner',\n 'gt': 'gt/{}',\n\n}\n# exp2hoi4d_fig.format(method)/vis_clip\n\n\n\ndegree_list = [0, 60, 90, 180, 270, 300]\ndata_dir = '/home/yufeiy2/scratch/result/vhoi'\nsave_dir = '/home/yufeiy2/scratch/result/figs/'\nfig_dir = '/home/yufeiy2/scratch/result/figs_row/'\n\ndef cp_fig():\n # for key in ['anneal']:\n # for key in exp2hoi4d_fig:\n for key in args.method.split(','):\n for index in index_list:\n for degree in degree_list:\n for suf in ['_hoi', '_obj',]: \n if 'wild' in key:\n query = osp.join(data_dir, exp2hoi4d_fig[key].format(data,index), 'vis_clip', f'*_{degree}{suf}.png')\n else:\n query = osp.join(data_dir, exp2hoi4d_fig[key].format(index), 'vis_clip', f'*_{degree}{suf}.png')\n src_list = glob(query)\n if len(src_list) == 0:\n print(query)\n for src_file in src_list:\n t = osp.basename(src_file).split('_')[0]\n if key == 'hhor':\n t = osp.basename(src_file).split('_')[1]\n dst = osp.join(save_dir, data, key, index, f'{t}_{degree}{suf}.png')\n os.makedirs(osp.dirname(dst), exist_ok=True)\n print(dst)\n os.system(f'cp {src_file} {dst}')\n\ndef cp_inp():\n key = 'input'\n suf = '_gt'\n for index in index_list:\n # query = osp.join(data_dir, exp2hoi4d_fig['ours'].format(index), 'vis_clip', f'*{suf}.png')\n key = args.method.split(',')[0]\n if 'wild' in key:\n query = osp.join(data_dir, exp2hoi4d_fig[key].format(data,index), 'vis_clip', f'*{suf}.png')\n else:\n query = osp.join(data_dir, exp2hoi4d_fig[key].format(index), 'vis_clip', f'*{suf}.png')\n\n src_list = glob(query)\n if len(src_list) == 0:\n print(len(src_list), query)\n for src_file in src_list:\n t = osp.basename(src_file).split('_')[0]\n if key == 'hhor':\n t = osp.basename(src_file).split('_')[1]\n dst = osp.join(save_dir, data, 'input', index, f'{t}_inp.png')\n os.makedirs(osp.dirname(dst), exist_ok=True)\n os.system(f'cp {src_file} {dst}')\n print(dst)\n\n\ndef merge_fig():\n if args.method is None:\n method_list = exp2hoi4d_fig.keys()\n else:\n method_list = args.method.split(',')\n # cp input to index_inp.png\n for index in index_list:\n method = 'input'\n img_list = sorted(glob(osp.join(save_dir, args.data, method, index, f'*_inp.png')))\n t = min(args.t, len(img_list))\n if t == 0:\n print(osp.join(save_dir, args.data, method, index, f'*_inp.png'))\n continue\n row = imageio.imread(img_list[t])\n\n fname = osp.join(row_dir, f'{index}_{method}.png')\n os.makedirs(osp.dirname(fname), exist_ok=True)\n print(fname)\n imageio.imwrite(fname, row)\n\n for index in index_list:\n row_list = []\n for method in method_list:\n image_list = []\n for suf in args.suf.split(','):\n suf = '_' + suf\n for degree in args.degree.split(','):\n img_list = sorted(glob(osp.join(save_dir, args.data, method, index, f'*_{degree}{suf}.png')))\n if len(img_list) == 0:\n continue\n t = min(args.t, len(img_list))\n image_list.append(imageio.imread(img_list[t]))\n if len(image_list) == 0:\n continue\n elif len(image_list) == 2:\n row = put_one_col(image_list)\n elif len(image_list) == 4:\n row = put_to_2x2(image_list)\n else:\n row = put_one_row(image_list)\n row_list.append(row)\n if len(row_list) == 0:\n continue\n row = put_one_row(row_list)\n name = ','.join(method_list)\n fname = osp.join(row_dir, f'{index}_{name}.png')\n os.makedirs(osp.dirname(fname), exist_ok=True)\n imageio.imwrite(fname, row)\n\n return\n\n\ndef put_one_col(image_list):\n # 2 element, make 2x1 grid\n a = np.concatenate(image_list, axis=0)\n return a\n\ndef put_one_row(image_list):\n # 2 element, make 1x2 grid\n a = np.concatenate(image_list, axis=1)\n return a\n\ndef put_to_2x2(image_list):\n # 4 element, make 2x2 grid\n N = len(image_list)\n a = np.concatenate(image_list[0:N//2], axis=0)\n b = np.concatenate(image_list[N//2:], axis=0)\n c = np.concatenate([a,b], axis=1)\n return c\n\ndef to_web():\n web_dir = osp.join(row_dir, 'web')\n method_list = ['input', 'gt', 'ours', 'ihoi', 'hhor', 'no_prior', 'obj_prior', 'hand_prior', 'w_mask', 'w_normal', 'w_depth', 'anneal']\n cell_list = []\n for index in index_list:\n line = []\n for method in method_list:\n fname = osp.join(row_dir, f'{index}_{method}.png')\n line.append(fname)\n cell_list.append(line)\n web_utils.run(web_dir, cell_list, height=200)\n\n\ndef web_merge():\n web_dir = osp.join(row_dir, 'web')\n cell_list = []\n for index in index_list:\n line = []\n query = osp.join(row_dir, f'{index}_*.png')\n a_list = sorted(glob(query))\n for fname in a_list:\n line.append(fname)\n cell_list.append(line)\n web_utils.run(web_dir, cell_list, height=200)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--data', type=str, default='hoi4d')\nparser.add_argument('--degree', type=str, default='overlay,90')\nparser.add_argument('--suf', type=str, default='hoi,obj')\n\nparser.add_argument('--t', type=int, default=1)\nparser.add_argument('--method', type=str, default=None)\nparser.add_argument('--fig', type=str, default='default')\nargs = parser.parse_args()\nrow_dir = osp.join(fig_dir, args.fig)\n\nif args.data == 'hoi4d':\n data = 'hoi4d'\n cat_list = \"Mug,Bottle,Kettle,Bowl,Knife,ToyCar\".split(',')\n ind_list = [1,2]\n index_list = [f\"{cat}_{ind}\" for ind in ind_list for cat in cat_list ]\nelif args.data == '3rd':\n data = '3rd_nocrop'\n cat_list = \"Mug,Bottle,Kettle,Bowl,Knife,ToyCar\".split(',')\n ind_list = list(range(10))\n index_list = [f\"{cat.lower()}{ind}\" for ind in ind_list for cat in cat_list ]\nelif args.data == 'visor':\n data = 'VISOR'\n cat_list = \"Kettle,Bowl,Knife,ToyCar\".split(',')\n # ind_list = \n index_list ='Kettle_101,Kettle_102,Bottle_102'.split(',')\nelif args.data == '1st':\n data = '1st_nocrop'\n cat_list = \"Mug,Bottle,Kettle,Bowl,Knife,ToyCar\".split(',')\n ind_list = list(range(10))\n index_list = [f\"{cat.lower()}_{ind}\" for ind in ind_list for cat in cat_list ]\n\n# cp_fig()\n\ncp_inp()\nmerge_fig()\n# web_merge()\n# to_merge()\n", "repo_name": "JudyYe/diffhoi_barely_clean", "sub_path": "tools/make_fig.py", "file_name": "make_fig.py", "file_ext": "py", "file_size_in_byte": 7831, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.path.join", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path", "line_number": 46, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path", "line_number": 48, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path", "line_number": 53, "usage_type": "name"}, {"api_name": "os.path.basename", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path", "line_number": 55, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path", "line_number": 56, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path", "line_number": 57, "usage_type": "name"}, {"api_name": "os.system", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path", "line_number": 68, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path", "line_number": 70, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path", "line_number": 76, "usage_type": "name"}, {"api_name": "os.path.basename", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path", "line_number": 78, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 79, "usage_type": "call"}, {"api_name": "os.path", "line_number": 79, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path", "line_number": 80, "usage_type": "name"}, {"api_name": "os.system", "line_number": 81, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 93, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 93, "usage_type": "call"}, {"api_name": "os.path", "line_number": 93, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 96, "usage_type": "call"}, {"api_name": "os.path", "line_number": 96, "usage_type": "name"}, {"api_name": "imageio.imread", "line_number": 98, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 100, "usage_type": "call"}, {"api_name": "os.path", "line_number": 100, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 101, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 101, "usage_type": "call"}, {"api_name": "os.path", "line_number": 101, "usage_type": "name"}, {"api_name": "imageio.imwrite", "line_number": 103, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 112, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 112, "usage_type": "call"}, {"api_name": "os.path", "line_number": 112, "usage_type": "name"}, {"api_name": "imageio.imread", "line_number": 116, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 130, "usage_type": "call"}, {"api_name": "os.path", "line_number": 130, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 131, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 131, "usage_type": "call"}, {"api_name": "os.path", "line_number": 131, "usage_type": "name"}, {"api_name": "imageio.imwrite", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 144, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 152, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 156, "usage_type": "call"}, {"api_name": "os.path", "line_number": 156, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 162, "usage_type": "call"}, {"api_name": "os.path", "line_number": 162, "usage_type": "name"}, {"api_name": "jutils.web_utils.run", "line_number": 165, "usage_type": "call"}, {"api_name": "jutils.web_utils", "line_number": 165, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 169, "usage_type": "call"}, {"api_name": "os.path", "line_number": 169, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 173, "usage_type": "call"}, {"api_name": "os.path", "line_number": 173, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 174, "usage_type": "call"}, {"api_name": "jutils.web_utils.run", "line_number": 178, "usage_type": "call"}, {"api_name": "jutils.web_utils", "line_number": 178, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 180, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 189, "usage_type": "call"}, {"api_name": "os.path", "line_number": 189, "usage_type": "name"}]} +{"seq_id": "35501767802", "text": "from pypresence import Presence\nimport requests, time, config\n\nclient_id = int(config.client_id)\nRPC = Presence(client_id)\nRPC.connect()\n\nwhile True:\n response = requests.get(f\"https://lichess.org/api/user/{config.lichess_username}\")\n try:\n stat = response.json()\n except:\n pass\n\n if str(response) == \"\":\n if stat[\"online\"]:\n RPC.update(\n large_image=\"lichess-icon\",\n buttons =\n [\n {\n \"label\": \"Playing on Lichess.org\",\n \"url\": f\"https://lichess.org/@/{config.lichess_username}/tv\"\n }\n ]\n )\n if not stat[\"online\"]:\n RPC.update(\n large_image=\"lichess-icon\",\n buttons = [\n {\n \"label\": \"Idling on Lichess.org\",\n \"url\": f\"https://lichess.org/@/{config.lichess_username}\"\n }\n ]\n )\n\n time.sleep(5)", "repo_name": "hetnxik/lichessorg-discordrpc", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1067, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "config.client_id", "line_number": 4, "usage_type": "attribute"}, {"api_name": "pypresence.Presence", "line_number": 5, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 9, "usage_type": "call"}, {"api_name": "config.lichess_username", "line_number": 9, "usage_type": "attribute"}, {"api_name": "config.lichess_username", "line_number": 23, "usage_type": "attribute"}, {"api_name": "config.lichess_username", "line_number": 33, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 38, "usage_type": "call"}]} +{"seq_id": "23324716337", "text": "import logging\n\nfrom django.db import models\nfrom django.contrib.postgres import fields\nfrom core.base import BaseModel\nfrom workflow.models import Workflow\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass CaseWorkflowManager(models.Manager):\n def snapshot_from_template(self, case, template, reset_state=False, requested_by=None):\n created = True\n try:\n case_workflow = CaseWorkflow.objects.get(case=case)\n created = False\n except CaseWorkflow.DoesNotExist:\n case_workflow = CaseWorkflow.objects.create(case=case, user_context=requested_by)\n case_workflow.set_user_context(requested_by)\n case_workflow.workflow = template.workflow\n case_workflow.save()\n if reset_state:\n CaseWorkflowState.objects.filter(case=case).delete()\n return case_workflow, created\n\n\nclass CaseWorkflow(BaseModel):\n case = models.OneToOneField(\n \"cases.Case\", related_name=\"workflow\", null=False, blank=False, on_delete=models.PROTECT\n )\n workflow = models.JSONField(default=dict)\n\n objects = CaseWorkflowManager()\n\n BUILT_IN_STATE_KEYS = (\n \"CURRENT_ACTION\",\n \"CURRENT_ACTION_DUE_DATE\",\n )\n\n def __str__(self):\n return f\"Workflow: {self.case}\"\n\n def as_workflow(self):\n return Workflow(self.workflow)\n\n @property\n def meta(self):\n return self.workflow.get(\"meta\", {})\n\n def replace_workflow(self, workflow):\n self.workflow = workflow\n return self.save()\n\n def state_index(self):\n \"\"\"\n Return an index of saved key values as a dict of key: (value, due_date)\n \"\"\"\n values = CaseWorkflowState.objects.filter(case=self.case, deleted_at__isnull=True)\n return {cws.key: (cws.value, cws.due_date) for cws in values}\n\n def get_state(self):\n \"\"\"\n Return the current state data or a fresh one from workflow\n \"\"\"\n # return Workflow(self.state) if self.state else self.as_workflow()\n state = self.as_workflow()\n value_index = self.state_index()\n for key in state.key_index:\n _value = value_index.get(key, (None, None))\n state.key_index[key][\"value\"] = _value[0]\n if _value[1]: # due_date\n state.key_index[key][\"due_date\"] = _value[1]\n\n state[\"meta\"] = {}\n for key in self.BUILT_IN_STATE_KEYS:\n _value = value_index.get(key, (None, None))\n state[\"meta\"][key] = _value[0]\n return state\n\n\nclass CaseWorkflowStateManager(models.Manager):\n def set_forward_value(\n self, key, case, value, due_date=None, requested_by=None, reset_due_date=False\n ):\n current_value = self.current_value(case, key)\n workflow = case.workflow.as_workflow()\n if value and (not current_value or workflow.key_precedes(current_value, value)):\n state, created = self.set_value(\n case,\n key,\n value,\n due_date=due_date,\n requested_by=requested_by,\n reset_due_date=reset_due_date,\n )\n return state, created\n else:\n logger.info(\"Unable to set key %s: %s precedes %s\", key, value, current_value)\n return None, False\n\n def set_next_action(self, case, value, due_date=None, requested_by=None):\n return self.set_forward_value(\n \"CURRENT_ACTION\", case, value, due_date=due_date, requested_by=requested_by\n )\n\n def set_next_notice(self, case, value, due_date=None, requested_by=None, reset_due_date=False):\n \"\"\"\n Set the next action state key and it's due date if provided.\n If the reset_due_date argument is True,\n the due date will be reset to None regardless of due date provided\n \"\"\"\n return self.set_forward_value(\n \"NEXT_NOTICE\",\n case,\n value,\n due_date=due_date,\n requested_by=requested_by,\n reset_due_date=reset_due_date,\n )\n\n def current_value(self, case, key):\n \"\"\"\n Get the current (latest) value assigned to a workflow node\n \"\"\"\n try:\n value = CaseWorkflowState.objects.get(case=case, key=key)\n return value.value\n except CaseWorkflowState.DoesNotExist:\n return None\n\n def current_due_date(self, case, key):\n \"\"\"\n Get the current due date\n \"\"\"\n try:\n value = CaseWorkflowState.objects.get(case=case, key=key)\n return value.due_date\n except CaseWorkflowState.DoesNotExist:\n return None\n\n def set_value(\n self, case, key, value, due_date=None, requested_by=None, mutate=True, reset_due_date=False\n ):\n \"\"\"\n Set a value on a case state item.\n Returns a tuple of the state model and a boolean if it was created\n (new state value) or updated.\n If mutate is False, and a value already exists,\n it will be marked deleted and a new one created.\n If reset_due_date is True,\n the due date will be set to None regardless of the due date provided\n \"\"\"\n created = None\n try:\n state = CaseWorkflowState.objects.get(case=case, key=key, deleted_at__isnull=True)\n created = False\n if state.value == value and state.due_date == due_date:\n return state, created\n if not mutate:\n state.delete()\n raise CaseWorkflowState.DoesNotExist()\n except CaseWorkflowState.DoesNotExist:\n state = CaseWorkflowState.objects.create(case=case, key=key)\n created = True\n state.set_user_context(requested_by)\n state.value = value\n if due_date or reset_due_date:\n state.due_date = None if reset_due_date else due_date\n state.save()\n state.save()\n return state, created\n\n def value_index(self, case, keys=None):\n \"\"\"\n Index all or a list of given keys\n into a dict of tuples each in the shape of (value, due_date)\n \"\"\"\n values = self.filter(case=case, deleted_at__isnull=True)\n if keys:\n values = values.filter(key__in=keys)\n return {val.key: (val.value, val.due_date) for val in values}\n\n\nclass CaseWorkflowState(BaseModel):\n \"\"\"\n Workflow state is an insert only hold of updates regarding the\n progress of the case's workflow.\n Each item in this model represents an acknowledgement taken on\n any of the workflow's nodes. The item is indexed by the node key and\n can be used to construct the state of the case.\n It is allowed to insert multiple updates to this model, though only the last\n one is considered current.\n \"\"\"\n\n case = models.ForeignKey(\"cases.Case\", null=False, blank=False, on_delete=models.PROTECT)\n key = models.CharField(max_length=250, null=False, blank=False, db_index=True)\n value = models.JSONField(null=True, blank=True)\n due_date = models.DateTimeField(null=True, blank=True)\n\n objects = CaseWorkflowStateManager()\n\n class Meta:\n index_together = [[\"case\", \"key\"]]\n\n def __str__(self):\n return f\"{self.key}={self.value}\"\n", "repo_name": "uktrade/trade-remedies-api", "sub_path": "trade_remedies_api/cases/models/workflow.py", "file_name": "workflow.py", "file_ext": "py", "file_size_in_byte": 7275, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "logging.getLogger", "line_number": 9, "usage_type": "call"}, {"api_name": "django.db.models.Manager", "line_number": 12, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 12, "usage_type": "name"}, {"api_name": "core.base.BaseModel", "line_number": 28, "usage_type": "name"}, {"api_name": "django.db.models.OneToOneField", "line_number": 29, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 29, "usage_type": "name"}, {"api_name": "django.db.models.PROTECT", "line_number": 30, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 30, "usage_type": "name"}, {"api_name": "workflow.models", "line_number": 32, "usage_type": "name"}, {"api_name": "django.db.models.JSONField", "line_number": 32, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 32, "usage_type": "name"}, {"api_name": "workflow.models.Workflow", "line_number": 45, "usage_type": "call"}, {"api_name": "workflow.models", "line_number": 52, "usage_type": "name"}, {"api_name": "django.db.models.Manager", "line_number": 82, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 82, "usage_type": "name"}, {"api_name": "workflow.models", "line_number": 87, "usage_type": "name"}, {"api_name": "workflow.models.key_precedes", "line_number": 88, "usage_type": "call"}, {"api_name": "workflow.models", "line_number": 88, "usage_type": "name"}, {"api_name": "core.base.BaseModel", "line_number": 185, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 196, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 196, "usage_type": "name"}, {"api_name": "django.db.models.PROTECT", "line_number": 196, "usage_type": "attribute"}, {"api_name": "django.db.models.CharField", "line_number": 197, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 197, "usage_type": "name"}, {"api_name": "django.db.models.JSONField", "line_number": 198, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 198, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 199, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 199, "usage_type": "name"}]} +{"seq_id": "25700362585", "text": "from typing import Tuple, Callable, Dict\nfrom sklearn.model_selection import ParameterGrid\n\n\nclass AbstractStepFactory:\n\n components = {\n 'step_name': {\n 'full_name': 'Step full name',\n 'type': 'Callable type',\n 'hyperparams': {\n 'h1': [1, 2, 3]\n }\n }\n }\n\n @classmethod\n def get_all_names(cls):\n return list(cls.components.keys())\n\n @classmethod\n def get(cls, name: str):\n names = cls.get_all_names()\n assert name in names, print(f\"name should be in {names}\")\n return cls.components[name]\n\n @classmethod\n def get_tuple_for_pipe(cls, name: str) -> Tuple[str, object, Dict]:\n \"\"\"\n Returns a given step\n :param name: name of the step\n :return: tuple containing the step name, type and hyperparameters dict\n \"\"\"\n\n cls_object = cls.get(name)\n return name, cls_object['type'], cls_object['hyperparams']\n\n @classmethod\n def get_type(cls, name: str):\n return cls.get(name)['type']\n\n @classmethod\n def get_hyperparams(cls, name: str):\n return cls.get(name)['hyperparams']\n\n @classmethod\n def get_full_name(cls, name: str):\n return cls.get(name)['full_name']\n\n @classmethod\n def get_all(cls):\n return cls.components\n\n @staticmethod\n def unzip_hyperparams(hyperparams):\n output_hyperparams = {}\n for k, v in hyperparams.items():\n h = []\n for el in v:\n if isinstance(el, dict):\n args_combination = list(ParameterGrid(el['args']))\n for c in args_combination:\n for t in el['type']:\n h.append(t(**c))\n else:\n h.append(el)\n output_hyperparams.update({k: h})\n return output_hyperparams\n", "repo_name": "gozderam/MachineLearning_FeatureSelection", "sub_path": "code/factories/abstract_factory.py", "file_name": "abstract_factory.py", "file_ext": "py", "file_size_in_byte": 1892, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.Tuple", "line_number": 28, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 28, "usage_type": "name"}, {"api_name": "sklearn.model_selection.ParameterGrid", "line_number": 61, "usage_type": "call"}]} +{"seq_id": "10650727346", "text": "import pandas as pd\nimport nltk\nimport string\nfrom nltk.tokenize import TweetTokenizer\n\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\n\nnltk.download('vader_lexicon')\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nimport time\nfrom sklearn import svm\nfrom sklearn.metrics import classification_report\nimport csv\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\ntweetFile = pd.read_csv(\"Tweets-Data.csv\")\ndataFrame = pd.DataFrame(tweetFile[['tweet_data']])\ntweetData = tweetFile['tweet_data']\n\ntknzr = TweetTokenizer()\nstopWords = set(stopwords.words(\"english\"))\n\n\n\ncleanedData = []\ncleaned = []\n\nfor line in tweetData:\n tweet = tknzr.tokenize(str(line))\n\n for word in tweet:\n if word not in string.punctuation:\n if '@' not in word:\n cleaned.append(word)\n\n cleanedData.append(cleaned)\n cleaned = []\n\nsentencedData = []\n\nfor sentence in cleanedData:\n sentencedData.append(\" \".join(sentence))\n\ntweetFile.insert(4, \"clean_data\", \"\")\n\ncleanData = tweetFile['clean_data']\ni = 0\n\nfor row in sentencedData:\n cleanData[i] = sentencedData[i]\n i = i + 1\n\nloopData = [0, 1, 2, 3, 4]\ntime_linear_train = []\ntime_linear_predict = []\n\nfor loop in loopData:\n t0 = 0\n t1 = 0\n t2 = 0\n\n tweetDataCopy = tweetFile.copy()\n\n trainedTweetData = tweetDataCopy.sample(frac=.8, random_state=0)\n testTweetData = tweetDataCopy.drop(trainedTweetData.index)\n\n sid = SentimentIntensityAnalyzer()\n i = 0\n sentimentData = []\n\n for sentence in trainedTweetData['clean_data']:\n sentimentData.append(sid.polarity_scores(sentence)['compound'])\n\n sentimentLabel = []\n\n for sentiment in sentimentData:\n if sentiment >= 0.05:\n sentimentLabel.append(\"pos\")\n elif sentiment <= -0.05:\n sentimentLabel.append(\"neg\")\n else:\n sentimentLabel.append(\"neu\")\n\n i = 0\n sentimentTestData = []\n\n for sentence in testTweetData['clean_data']:\n sentimentTestData.append(sid.polarity_scores(sentence)['compound'])\n\n sentimentForTestLabel = []\n\n for sentiment in sentimentTestData:\n if sentiment >= 0.05:\n sentimentForTestLabel.append(\"pos\")\n elif sentiment <= -0.05:\n sentimentForTestLabel.append(\"neg\")\n else:\n sentimentForTestLabel.append(\"neu\")\n\n data = {'clean_data': testTweetData.clean_data, 'sentiment': sentimentForTestLabel}\n df = pd.DataFrame(data)\n df.to_csv('test-data.csv')\n\n data = {'clean_data': trainedTweetData.clean_data, 'sentiment': sentimentLabel}\n df = pd.DataFrame(data)\n df.to_csv('train-data.csv')\n\n testData = pd.read_csv('test-data.csv')\n trainData = pd.read_csv('train-data.csv')\n\n \n vectorizer = TfidfVectorizer(min_df=5, max_df=0.8, sublinear_tf=True, use_idf=True)\n\n train_vectors = vectorizer.fit_transform(trainData['clean_data'].values.astype('U'))\n test_vectors = vectorizer.transform(testData['clean_data'].values.astype('U'))\n\n \n classifier_linear = svm.SVC(kernel='linear')\n\n t0 = time.time()\n\n classifier_linear.fit(train_vectors, trainData['sentiment'])\n\n t1 = time.time()\n\n prediction_linear = classifier_linear.predict(test_vectors)\n\n t2 = time.time()\n\n time_linear_train.append(t1 - t0)\n time_linear_predict.append(t2 - t1)\n\n \n print(\"Training time: %fs; Prediction time: %fs\" % (time_linear_train[loop], time_linear_predict[loop]))\n report = classification_report(testData['sentiment'], prediction_linear, output_dict=True)\n\n print('positive: ', report['pos'])\n print('negative: ', report['neg'])\n\ntotalTrainTime = 0\ntotalPredictTime = 0\n\nfor i in loopData:\n \n totalTrainTime = totalTrainTime + time_linear_train[i]\n totalPredictTime = totalPredictTime + time_linear_predict[i]\n\nprint(\"Average training time: %fs\" % (totalTrainTime / 5))\nprint(\"Average prediction time: %fs\" % (totalPredictTime / 5))", "repo_name": "barakadanny/Sentiment_Analyzer_with_Python", "sub_path": "SentimentAnalyzer.py", "file_name": "SentimentAnalyzer.py", "file_ext": "py", "file_size_in_byte": 3936, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "25", "api": [{"api_name": "nltk.download", "line_number": 6, "usage_type": "call"}, {"api_name": "nltk.download", "line_number": 9, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 17, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 18, "usage_type": "call"}, {"api_name": "nltk.tokenize.TweetTokenizer", "line_number": 21, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 22, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 22, "usage_type": "name"}, {"api_name": "string.punctuation", "line_number": 33, "usage_type": "attribute"}, {"api_name": "nltk.sentiment.vader.SentimentIntensityAnalyzer", "line_number": 68, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 102, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 106, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 109, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 110, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text.TfidfVectorizer", "line_number": 113, "usage_type": "call"}, {"api_name": "sklearn.svm.SVC", "line_number": 119, "usage_type": "call"}, {"api_name": "sklearn.svm", "line_number": 119, "usage_type": "name"}, {"api_name": "time.time", "line_number": 121, "usage_type": "call"}, {"api_name": "time.time", "line_number": 125, "usage_type": "call"}, {"api_name": "time.time", "line_number": 129, "usage_type": "call"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 136, "usage_type": "call"}]} +{"seq_id": "443204767", "text": "import os\nimport tempfile\nimport numpy as np\nimport struct\nimport pytest\nimport pickle\nimport popart\nfrom functools import reduce\nfrom itertools import chain\n\nfrom bert import bert_add_inputs\nfrom bert_model import Bert, BertConfig\nfrom bert_data.dataset import DataSet\nfrom bert_data.pretraining_dataset import (\n BinaryDataLoader,\n GeneratedDataLoader,\n BertDataTransform,\n data_file_format as pretraining_format,\n data_ranges as pretraining_ranges\n)\nfrom bert_data.squad_dataset import (\n SquadDataLoader,\n generate_random_features,\n get_bert_dataset\n)\n\n\ndef test_dataloader():\n sequence_length = 128\n mask_tokens = 20\n batch_size = 2\n\n ind = []\n pos = []\n lbl = []\n\n with tempfile.TemporaryDirectory() as pwd:\n input_path = os.path.join(pwd, \"input.bin\")\n with open(input_path, \"wb\") as f:\n for _ in range(batch_size):\n i = np.random.randint(0, sequence_length, (sequence_length))\n p = np.random.randint(0, sequence_length, (sequence_length))\n l = np.random.randint(0, sequence_length, (mask_tokens))\n\n line = reduce(lambda accl, i: accl + struct.pack(' vocab_length\n assert(np.all(ind[OutOfBounds] == 100))\n\n assert(np.all(lbl < vocab_length))\n OutOfBounds = data[5] > vocab_length\n assert(np.all(lbl[OutOfBounds] == 0))\n\n\ndef test_dataset():\n sequence_length = 128\n mask_tokens = 20\n batch_size = 2\n vocab_length = 9728\n batches_per_step = 100\n replication_factor = 2\n accumulation_factor = 3\n samples_per_step = batches_per_step * batch_size * replication_factor * accumulation_factor\n\n data = [\n # indicies\n np.random.randint(0, 2 * vocab_length, (samples_per_step, sequence_length)).astype(np.uint32),\n # position\n np.random.randint(0, sequence_length, (samples_per_step, sequence_length)).astype(np.uint32),\n # masks\n np.random.randint(0, sequence_length, (samples_per_step,)).astype(np.uint32),\n np.random.randint(0, sequence_length, (samples_per_step,)).astype(np.uint32),\n # labels\n np.random.randint(0, 2 * vocab_length, (samples_per_step, mask_tokens)).astype(np.uint32),\n np.random.randint(0, 2, (samples_per_step,)).astype(np.uint32)\n ]\n\n # Simulate the BertDataTransform\n def dl():\n while True:\n yield data\n\n class TestDataLoader(object):\n def __len__(self):\n return 1\n\n def __iter__(self):\n return dl()\n\n ds = DataSet(TestDataLoader(),\n [\n (\"indices\", (sequence_length * batch_size,)),\n (\"positions\", (sequence_length * batch_size,)),\n (\"msk_mask\", (batch_size,)),\n (\"seq_mask\", (batch_size,)),\n (\"labels\", (mask_tokens * batch_size,)),\n (\"nsp_labels\", (batch_size,))\n ],\n batches_per_step,\n replication_factor,\n accumulation_factor)\n\n ds_iter = iter(ds)\n sample = next(ds)\n\n assert(np.all(sample[\"indices\"].shape == np.array(\n [batches_per_step, accumulation_factor, replication_factor, batch_size * sequence_length])))\n assert(np.all(sample[\"positions\"].shape == np.array(\n [batches_per_step, accumulation_factor, replication_factor, batch_size * sequence_length])))\n assert(np.all(sample[\"labels\"].shape == np.array(\n [batches_per_step, accumulation_factor, replication_factor, batch_size * mask_tokens])))\n\n assert(np.all(sample[\"indices\"].flatten() == data[0].flatten()))\n assert(np.all(sample[\"positions\"].flatten() == data[1].flatten()))\n assert(np.all(sample[\"labels\"].flatten() == data[4].flatten()))\n\n\n@pytest.fixture(scope=\"session\")\ndef get_squad(tmpdir_factory):\n # Generate a synthetic features cache file to avoid using the real dataset\n tmpdir = tmpdir_factory.mktemp(\"ndr_test_tmp_data\")\n input_file = str(tmpdir) + \"/inputfile\"\n dataset_size = 3333\n features = generate_random_features(128, 30, dataset_size)\n cache_file = input_file + f\".{128}.cache\"\n with open(cache_file, \"wb\") as f:\n pickle.dump(features, f)\n print(cache_file)\n return tmpdir\n\n\n@pytest.mark.parametrize('batch_size', [1, 2, 8, 13])\n@pytest.mark.parametrize('shuffle,mpi_size', [(False, 1), (True, 1), (False, 2)])\ndef test_no_drop_remainder(batch_size, shuffle, mpi_size, get_squad):\n tmpdir = get_squad\n batches_per_step = 128\n\n class MockArgs():\n def __init__(self, batches_per_step, batch_size, shuffle, mpi_size, tmpdir):\n self.batches_per_step = batches_per_step\n self.batch_size = batch_size\n self.sequence_length = 128\n self.hidden_size = 768\n self.vocab_length = 30\n self.host_embedding = \"NONE\"\n self.task = \"SQUAD\"\n self.inference = True\n self.synthetic_data = False\n self.generated_data = False\n self.input_files = str(tmpdir) + \"/inputfile\"\n self.output_dir = None\n self.vocab_file = None\n self.accumulation_factor = 1\n self.replication_factor = 1\n self.shuffle = shuffle\n self.mpi_size = mpi_size\n self.squad_lr_scale = None\n\n def create_dataset(args):\n # a simple copy of main bert.py until the dataset creation\n config = BertConfig()\n model = Bert(config, builder=popart.Builder())\n indices, positions, segments, masks, labels = bert_add_inputs(args, model)\n inputs = [indices, positions, segments, masks, labels]\n embedding_dict, positional_dict = model.get_model_embeddings()\n shapeOf = model.builder.getTensorShape\n inputs = reduce(chain, inputs[3:], inputs[:3])\n tensor_shapes = [(tensorId, shapeOf(tensorId)) for tensorId in inputs]\n dataset = get_bert_dataset(tensor_shapes,\n input_file=args.input_files,\n output_dir=args.output_dir,\n sequence_length=args.sequence_length,\n vocab_file=args.vocab_file,\n vocab_length=args.vocab_length,\n batch_size=args.batch_size,\n batches_per_step=args.batches_per_step,\n embedding_dict=embedding_dict,\n positional_dict=positional_dict,\n generated_data = args.generated_data,\n is_training=False,\n no_drop_remainder=True,\n shuffle = args.shuffle,\n mpi_size=args.mpi_size,\n is_distributed=(args.mpi_size > 1))\n return dataset\n\n def test(ds, args):\n datatransform = ds.loader\n loader = datatransform.dataloader\n sampler = loader.sampler\n dataset_size = len(sampler)\n div_factor = args.batch_size * args.replication_factor * args.accumulation_factor * args.batches_per_step\n # The aim of the option is to make the dataset size divisible by div_factor\n assert(dataset_size % div_factor == 0)\n assert(ds.n_extra < div_factor)\n\n # test\n args = MockArgs(batches_per_step, batch_size, shuffle, mpi_size, tmpdir)\n ds = create_dataset(args)\n test(ds, args)\n", "repo_name": "mlcommons/training_results_v1.0", "sub_path": "Graphcore/benchmarks/bert/implementations/popart/tests/unit/data_test.py", "file_name": "data_test.py", "file_ext": "py", "file_size_in_byte": 10817, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 36, "dataset": "github-code", "pt": "25", "api": [{"api_name": "tempfile.TemporaryDirectory", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path", "line_number": 38, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 41, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 42, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 43, "usage_type": "attribute"}, {"api_name": "functools.reduce", "line_number": 45, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 45, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.stack", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.stack", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.stack", "line_number": 55, "usage_type": "call"}, {"api_name": "bert_data.pretraining_dataset.BinaryDataLoader", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 67, "usage_type": "call"}, {"api_name": "bert_data.pretraining_dataset.data_file_format", "line_number": 76, "usage_type": "call"}, {"api_name": "bert_data.pretraining_dataset.data_ranges", "line_number": 77, "usage_type": "call"}, {"api_name": "bert_data.pretraining_dataset.GeneratedDataLoader", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 90, "usage_type": "call"}, {"api_name": "bert_data.squad_dataset.generate_random_features", "line_number": 99, "usage_type": "call"}, {"api_name": "bert_data.squad_dataset.SquadDataLoader", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 126, "usage_type": "attribute"}, {"api_name": "numpy.uint32", "line_number": 126, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 128, "usage_type": "attribute"}, {"api_name": "numpy.uint32", "line_number": 128, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 130, "usage_type": "attribute"}, {"api_name": "numpy.uint32", "line_number": 130, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 132, "usage_type": "attribute"}, {"api_name": "numpy.uint32", "line_number": 132, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 133, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 133, "usage_type": "attribute"}, {"api_name": "numpy.uint32", "line_number": 133, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 135, "usage_type": "attribute"}, {"api_name": "numpy.uint32", "line_number": 135, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 136, "usage_type": "attribute"}, {"api_name": "numpy.uint32", "line_number": 136, "usage_type": "attribute"}, {"api_name": "bert_data.pretraining_dataset.BertDataTransform", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 153, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 172, "usage_type": "attribute"}, {"api_name": "numpy.uint32", "line_number": 172, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 174, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 174, "usage_type": "attribute"}, {"api_name": "numpy.uint32", "line_number": 174, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 176, "usage_type": "attribute"}, {"api_name": "numpy.uint32", "line_number": 176, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 177, "usage_type": "attribute"}, {"api_name": "numpy.uint32", "line_number": 177, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 179, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 179, "usage_type": "attribute"}, {"api_name": "numpy.uint32", "line_number": 179, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 180, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 180, "usage_type": "attribute"}, {"api_name": "numpy.uint32", "line_number": 180, "usage_type": "attribute"}, {"api_name": "bert_data.dataset.DataSet", "line_number": 195, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 213, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 213, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 218, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 219, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 220, "usage_type": "call"}, {"api_name": "bert_data.squad_dataset.generate_random_features", "line_number": 229, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 232, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 223, "usage_type": "call"}, {"api_name": "bert_model.BertConfig", "line_number": 266, "usage_type": "call"}, {"api_name": "bert_model.Bert", "line_number": 267, "usage_type": "call"}, {"api_name": "popart.Builder", "line_number": 267, "usage_type": "call"}, {"api_name": "bert.bert_add_inputs", "line_number": 268, "usage_type": "call"}, {"api_name": "functools.reduce", "line_number": 272, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 272, "usage_type": "argument"}, {"api_name": "bert_data.squad_dataset.get_bert_dataset", "line_number": 274, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 237, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 237, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 238, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 238, "usage_type": "attribute"}]} +{"seq_id": "30521195329", "text": "from common.utils import get_ipc_address\n\nIPC_ADDRESS = get_ipc_address()\n\n# Timeout for nanomsg socket operations (in milliseconds)\nTIMEOUT = 1000\n\n# Client_API class instance\nweb_api = None\n\n# Sync class instance\nsync = None\n\n# Tracker class instance\ntracker = None\n\n# Signalling server client instance\nss_client = None\n\n# Instance of includes.config.ConfigLoader\ncfg = None\n\n# Instance of shell_integration.websocket_server.IPCWebSocketServer\nipc_ws_server = None\n\nget_shared_paths_func = None\n", "repo_name": "pvtbox/pvtbox-desktop", "sub_path": "service/shell_integration/params.py", "file_name": "params.py", "file_ext": "py", "file_size_in_byte": 497, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "common.utils.get_ipc_address", "line_number": 3, "usage_type": "call"}]} +{"seq_id": "32875249300", "text": "import argparse\n\nfrom utils.conf import TerraEnvs, Configuration\n\n\ndef parse_args_and_init_config(\n parser: argparse.ArgumentParser,\n) -> (dict, argparse.ArgumentParser):\n \"\"\"\n Parses args and initializes config from the supplied argument parser. Assumes\n an \"env\" arg on the command line. If the env is \"bee\", enforces the presence of \"bee\" arg as well for runtime\n specification of the bee name.\n :param parser:\n :return:\n \"\"\"\n subs = {}\n\n args = parser.parse_args()\n\n if args.env == TerraEnvs.BEE and args.bee is None:\n parser.error(\"BEE name is required when env is BEE\")\n elif args.env == TerraEnvs.BEE and args.bee:\n subs = {\"bee\": args.bee}\n\n Configuration.initialize(args.env, overrides=subs)\n return args\n", "repo_name": "aherbst-broad/dsp-terra-workspaces-scripts", "sub_path": "tools/utils/cli.py", "file_name": "cli.py", "file_ext": "py", "file_size_in_byte": 770, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 7, "usage_type": "attribute"}, {"api_name": "utils.conf.TerraEnvs.BEE", "line_number": 20, "usage_type": "attribute"}, {"api_name": "utils.conf.TerraEnvs", "line_number": 20, "usage_type": "name"}, {"api_name": "utils.conf.TerraEnvs.BEE", "line_number": 22, "usage_type": "attribute"}, {"api_name": "utils.conf.TerraEnvs", "line_number": 22, "usage_type": "name"}, {"api_name": "utils.conf.Configuration.initialize", "line_number": 25, "usage_type": "call"}, {"api_name": "utils.conf.Configuration", "line_number": 25, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 8, "usage_type": "attribute"}]} +{"seq_id": "28082435763", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n@ Description:Pytest hook Appium\n\n# @allure.feature # 用于定义被测试的功能,被测产品的需求点\n# @allure.story # 用于定义被测功能的用户场景,即子功能点\n# @allure.severity #用于定义用例优先级\n# @allure.issue #用于定义问题表识,关联标识已有的问题,可为一个url链接地址\n# @allure.testcase #用于用例标识,关联标识用例,可为一个url链接地址\n# @allure.attach # 用于向测试报告中输入一些附加的信息,通常是一些测试数据信息\n# @pytest.allure.step # 用于将一些通用的函数作为测试步骤输出到报告,调用此函数的地方会向报告中输出步骤\n# allure.environment(environment=env) #用于定义environment\n\n\"\"\"\nimport os,sys,subprocess,pytest,datetime,allure\nfrom sources.get_driver import DriverClient\nsys.path.append('..')\n\n\n\n# 当设置autouse为True时,\n # # 在一个session内的所有的test都会自动调用这个fixture\n# 该函数需要放置在 conftest.py, pytest 运行时会自动拾取\n# @pytest.fixture()\n# def driver_setup(request):\n# request.instance.Action = DriverClient().init_driver()\n# print('driver初始化')\n# def driver_teardown():\n# request.instance.Action.clear()\n# print('退出')\n# request.addfinalizer(driver_teardown)\n\n# def pytest_runtest_call(item):\n# # 每条用例代码执行之前,非用例执行之前\n# allure.dynamic.description('用例开始时间:{}'.format(datetime.datetime.now()))\n# Action = DriverClient().Action\n # if Action.get_app_pid() != Action.apppid:\n # raise Exception('设备进程 ID 变化,可能发生崩溃')\n\n@pytest.hookimpl(tryfirst=True, hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n # 用例报错捕捉\n Action = DriverClient().Action\n outcome = yield\n rep = outcome.get_result()\n if rep.when == \"call\" and rep.failed:\n f = Action.driver.get_screenshot_as_png()\n allure.attach(f, '失败截图', allure.attachment_type.PNG)\n logcat = Action.driver.get_log('logcat')\n c = '\\n'.join([i['message'] for i in logcat])\n allure.attach(c, 'APPlog', allure.attachment_type.TEXT)\n # if Action.get_app_pid() != Action.apppid:\n # raise Exception('设备进程 ID 变化,可能发生崩溃')\n", "repo_name": "0911Aa/python_CI_demo", "sub_path": "conftest.py", "file_name": "conftest.py", "file_ext": "py", "file_size_in_byte": 2358, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "sys.path.append", "line_number": 17, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "sources.get_driver.DriverClient", "line_number": 43, "usage_type": "call"}, {"api_name": "allure.attach", "line_number": 48, "usage_type": "call"}, {"api_name": "allure.attachment_type", "line_number": 48, "usage_type": "attribute"}, {"api_name": "allure.attach", "line_number": 51, "usage_type": "call"}, {"api_name": "allure.attachment_type", "line_number": 51, "usage_type": "attribute"}, {"api_name": "pytest.hookimpl", "line_number": 40, "usage_type": "call"}]} +{"seq_id": "21112713018", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport threading\n\nfrom VIGITIA_toolkit.data_transportation.VIGITIAVideoStreamReceiver import VIGITIAVideoStreamReceiver\nfrom VIGITIA_toolkit.utility.get_ip import get_ip_address\n\nfrom pythonosc.osc_server import ThreadingOSCUDPServer\nfrom pythonosc.dispatcher import Dispatcher\n\n# Port where this application will listen for incoming TUIO messages\nPORT = 8000\n\nDEBUG_MODE = False\n\n\n# The Singleton class is implemented like described here:\n# https://medium.com/better-programming/singleton-in-python-5eaa66618e3d\nclass Singleton:\n\n def __init__(self, cls):\n self._cls = cls\n\n def Instance(self):\n try:\n return self._instance\n except AttributeError:\n self._instance = self._cls()\n return self._instance\n\n def __call__(self):\n raise TypeError('Singletons must be accessed through `Instance()`.')\n\n def __instancecheck__(self, inst):\n return isinstance(inst, self._cls)\n\n\n@Singleton\nclass VIGITIASensorDataInterface:\n \"\"\" This class functions as a TUIO 2.0 client and decodes recieved TUIO messages using the python-osc library\n (https://github.com/attwad/python-osc).\n It also bundles incoming gstreamer video streams and provides a convenient way of applications\n\n \"\"\"\n\n def __init__(self):\n # IP needs to be always the IP of the computer\n self.ip = get_ip_address()\n\n # Using the Observer pattern\n self.subscribers = set()\n\n self.bundles = {}\n\n self.tokens = []\n self.pointers = []\n self.outer_contour_geometries = []\n self.bounding_boxes = []\n self.symbols = []\n\n self.available_video_streams = []\n\n self.camera_resolution = None\n self.screen_resolution = None\n\n self.init_tuio_interface()\n\n def register_subscriber(self, new_subscriber):\n self.subscribers.add(new_subscriber)\n\n def unregister_subscriber(self, subscriber):\n self.subscribers.discard(subscriber)\n\n def init_tuio_interface(self):\n dispatcher = Dispatcher()\n dispatcher.map(\"/tuio2/frm\", self.on_new_frame_message, needs_reply_address=True) # Also pass on the IP of the data origin\n dispatcher.map(\"/tuio2/ptr\", self.on_new_pointer_message, needs_reply_address=True)\n dispatcher.map(\"/tuio2/bnd\", self.on_new_bounding_box_message, needs_reply_address=True)\n dispatcher.map(\"/tuio2/tok\", self.on_new_token_message, needs_reply_address=True)\n dispatcher.map(\"/tuio2/dat\", self.on_new_data_message, needs_reply_address=True)\n dispatcher.map(\"/tuio2/ctl\", self.on_new_control_message, needs_reply_address=True)\n dispatcher.map(\"/tuio2/alv\", self.on_new_alive_message, needs_reply_address=True)\n\n print('IP, PORT', self.ip, PORT)\n osc_udp_server = ThreadingOSCUDPServer((self.ip, PORT), dispatcher)\n\n print('[SensorDataInterface]: Listening on {} for incoming TUIO messages'.format(osc_udp_server.server_address))\n\n server_thread = threading.Thread(target=osc_udp_server.serve_forever)\n server_thread.start()\n\n # Init a new video stream receiver and subscribe to it to receive new video streams\n def init_video_stream_receiver(self, name, origin_ip, port):\n receiver = VIGITIAVideoStreamReceiver(name, origin_ip, port=port)\n receiver.register_subscriber(self)\n receiver.start()\n\n # Forward a received video frame to all subscribers\n def on_new_video_frame(self, frame, name, origin_ip, port):\n # Directly forward frame to subscribers\n for subscriber in self.subscribers:\n subscriber.on_new_video_frame(frame, name, origin_ip, port)\n\n # Translate the dimension attribute from the TUIO protocoll into readable x and y coordinates\n def set_camera_resolution(self, dimension):\n dimension_split = dimension.split('x')\n self.camera_resolution = (int(dimension_split[0]), int(dimension_split[1]))\n\n def on_new_frame_message(self, *messages):\n\n if self.camera_resolution is None:\n self.set_camera_resolution(messages[4])\n\n if DEBUG_MODE:\n print('New frame arrived:', messages)\n origin_ip = messages[0][0]\n\n self.bundles[origin_ip] = {\n 'origin_ip': origin_ip,\n 'frame_id': messages[2],\n 'time_tag': messages[3],\n 'dimension': messages[4],\n 'source': messages[5],\n 'tokens': [],\n 'pointers': [],\n 'bounding_boxes': [],\n 'outer_contour_geometries': [],\n 'symbols': [],\n 'data': [],\n 'active_session_ids': []\n }\n\n # If the Sensor Data Interface does not know the output screen resolution, a toolkit application is asked for it\n def get_screen_resolution(self):\n if len(self.subscribers) > 0:\n self.screen_resolution = list(self.subscribers)[0].get_screen_resolution()\n\n # Translate coordinates from the camera resolution to the screen resolution\n def translate_coordinates(self, x, y):\n if self.camera_resolution is not None:\n\n x_translated = int(x / self.camera_resolution[0] * self.screen_resolution[0])\n y_translated = int(y / self.camera_resolution[1] * self.screen_resolution[1])\n\n return x_translated, y_translated\n\n else:\n return x, y\n\n def translate_x_coordinate(self, x):\n if self.camera_resolution is not None and self.screen_resolution is not None:\n return int(x / self.camera_resolution[0] * self.screen_resolution[0])\n else:\n return x\n\n def translate_y_coordinate(self, y):\n if self.camera_resolution is not None and self.screen_resolution is not None:\n return int(y / self.camera_resolution[1] * self.screen_resolution[1])\n else:\n return y\n\n def on_new_token_message(self, *messages):\n\n if self.screen_resolution is None or self.screen_resolution[0] <= 0 or self.screen_resolution[1] <= 0:\n self.get_screen_resolution()\n\n # Translate coordinates from camera space to screen space\n #x_translated, y_translated = self.translate_coordinates(messages[5], messages[6])\n\n if DEBUG_MODE:\n print(messages)\n\n origin_ip = messages[0][0]\n token_message = {\n 'session_id': messages[2],\n 'tuio_id': messages[3],\n 'component_id': messages[4],\n 'x_pos': self.translate_x_coordinate(messages[5]),\n 'y_pos': self.translate_y_coordinate(messages[6]),\n 'angle': messages[7]\n }\n self.bundles[origin_ip]['tokens'].append(token_message)\n\n def on_new_pointer_message(self, *messages):\n\n if self.screen_resolution is None or self.screen_resolution[0] <= 0 or self.screen_resolution[1] <= 0:\n self.get_screen_resolution()\n\n origin_ip = messages[0][0]\n pointer_message = {\n 'session_id': messages[2],\n 'tuio_id': messages[3],\n 'component_id': messages[4],\n 'x_pos': self.translate_x_coordinate(messages[5]),\n 'y_pos': self.translate_y_coordinate(messages[6]),\n 'angle': messages[7],\n 'shear': messages[8],\n 'radius': messages[9],\n 'press': messages[10]\n }\n self.bundles[origin_ip]['pointers'].append(pointer_message)\n\n def on_new_bounding_box_message(self, *messages):\n origin_ip = messages[0][0]\n bounding_box_message = {\n 'session_id': messages[2],\n 'x_pos': self.translate_x_coordinate(messages[3]),\n 'y_pos': self.translate_y_coordinate(messages[4]),\n 'angle': messages[5],\n 'width': self.translate_x_coordinate(messages[6]),\n 'height': self.translate_x_coordinate(messages[7]),\n 'area': messages[8]\n }\n self.bundles[origin_ip]['bounding_boxes'].append(bounding_box_message)\n\n def on_new_data_message(self, *messages):\n\n if DEBUG_MODE:\n print(messages)\n\n origin_ip = messages[0][0]\n self.bundles[origin_ip]['data'].append(messages[2:])\n\n message_type = messages[3]\n # Messages of type video indicate the presence of a video stream\n if message_type == 'video':\n stream_name = messages[4]\n stream_port = messages[7]\n\n stream_info = [stream_name, origin_ip, stream_port]\n stream_already_registered = False\n for entry in self.available_video_streams:\n if set(entry) == set(stream_info):\n stream_already_registered = True\n\n if not stream_already_registered:\n print('[SensorDataInterface]: New video stream available:', stream_name, origin_ip, stream_port)\n self.available_video_streams.append(stream_info)\n self.init_video_stream_receiver(stream_name, origin_ip, stream_port)\n\n def on_new_control_message(self, *messages):\n if DEBUG_MODE:\n print(messages)\n\n # Send control messages directly because they are currently not in a bundle (sent from a smartphone)\n for subscriber in self.subscribers:\n subscriber.on_new_control_messages(messages)\n\n def on_new_alive_message(self, *messages):\n origin_ip = messages[0][0]\n active_session_ids = messages[2:]\n self.bundles[origin_ip]['active_session_ids'].append(active_session_ids)\n\n if DEBUG_MODE:\n print(self.bundles[origin_ip])\n\n # Send new data to all subscribers\n try:\n for subscriber in self.subscribers:\n # The entire bundle\n subscriber.on_new_tuio_bundle(self.bundles[origin_ip])\n\n # Just certain components for quicker data access\n subscriber.on_new_token_messages(self.bundles[origin_ip]['tokens'])\n subscriber.on_new_pointer_messages(self.bundles[origin_ip]['pointers'])\n subscriber.on_new_bounding_box_messages(self.bundles[origin_ip]['bounding_boxes'])\n except RuntimeError as error:\n # Handle rare cases when the self.subscribers set changes while it is read\n print(error)\n\n # Applications can call this function to ask what video streams are available\n def get_available_video_streams(self):\n return self.available_video_streams\n\n\ndef main():\n VIGITIASensorDataInterface.Instance()\n sys.exit()\n\n\nif __name__ == '__main__':\n main()\n", "repo_name": "vigitia/VIGITIA-Toolkit", "sub_path": "VIGITIA_toolkit/core/VIGITIASensorDataInterface.py", "file_name": "VIGITIASensorDataInterface.py", "file_ext": "py", "file_size_in_byte": 10592, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "VIGITIA_toolkit.utility.get_ip.get_ip_address", "line_number": 50, "usage_type": "call"}, {"api_name": "pythonosc.dispatcher.Dispatcher", "line_number": 77, "usage_type": "call"}, {"api_name": "pythonosc.osc_server.ThreadingOSCUDPServer", "line_number": 87, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 91, "usage_type": "call"}, {"api_name": "VIGITIA_toolkit.data_transportation.VIGITIAVideoStreamReceiver.VIGITIAVideoStreamReceiver", "line_number": 96, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 280, "usage_type": "call"}]} +{"seq_id": "72134130304", "text": "#!/usr/bin/python3.11\nfrom datetime import datetime, timedelta\nimport io\nimport logging\n\nfrom model import load_model, classify\nfrom telegram import ChatPermissions, Message, Update\nfrom telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters\nfrom constants import ADMIN_CHAT, ADMIN_LIST, AUTO_CAPTION, TOKEN, USERS, USER_BLACK_LIST, FORWARD_CHAT_BLACK_LIST\n\nlogging.basicConfig(\n format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=logging.INFO\n)\n\nmodel = load_model()\nIS_TOTAL_CENSORSHIP = False\nALL_PERMISSIONS = ChatPermissions(can_send_messages=True,\n can_send_media_messages=True,\n can_send_other_messages=True,\n can_add_web_page_previews=True,\n can_send_polls=True)\nBAN_PERMISSIONS = ChatPermissions(can_send_messages=True,\n can_send_media_messages=False)\n\nasync def unban_user_media(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n if not is_admin(update.effective_message):\n return\n\n chat_id = update.effective_message.chat_id\n username = get_username_from_command(update.effective_message)\n user_id = USERS.get(username)\n logging.info(f\"User: {username}, {user_id}\")\n await update.effective_message.delete()\n await context.bot.restrict_chat_member(chat_id, user_id, ALL_PERMISSIONS)\n await context.bot.send_message(chat_id, f\"{username} media was unbunned.\")\n\n\nasync def ban_user_media(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n if not is_admin(update.effective_message):\n return\n\n chat_id = update.effective_message.chat_id\n username = get_username_from_command(update.effective_message)\n user_id = USERS.get(username)\n logging.info(f\"User: {username}, {user_id}\")\n await update.effective_message.delete()\n await context.bot.restrict_chat_member(chat_id, user_id, BAN_PERMISSIONS, datetime.now() + timedelta(hours=1))\n await context.bot.send_message(chat_id, f\"{username} media was bunned.\")\n\n\nasync def sloiler_nsfw_photo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n message = update.effective_message\n user_id = message.from_user.id\n username = message.from_user.username\n USERS[username] = user_id\n\n if not message.photo or message.has_media_spoiler:\n return\n\n custom_caption = f'From {username}: {message.caption}' if message.caption else f'From {username}'\n forward_from_chat = message.forward_from_chat\n\n if forward_from_chat and forward_from_chat.id in FORWARD_CHAT_BLACK_LIST or IS_TOTAL_CENSORSHIP:\n await resend_photo_with_spoiler(message, custom_caption, context)\n else:\n await spoiler_with_model_prediction(message, custom_caption, context)\n\n logging.info(f\"Chat {message.chat_id} - All users {USERS}, BLACK_LIST: {FORWARD_CHAT_BLACK_LIST}\")\n\n\nasync def spoiler_with_model_prediction(message: Message, custom_caption: str, context: ContextTypes.DEFAULT_TYPE):\n photo_file = await context.bot.get_file(message.photo[-2].file_id)\n logging.info(f\"File size: {message.photo[-2].file_size}\")\n photo_bytearray = await photo_file.download_as_bytearray()\n photo_bytes_io = io.BytesIO(photo_bytearray)\n try:\n predictions = classify(model, photo_bytes_io)\n logging.info(predictions)\n is_nsfw, prediction_caption = analyse_predictions(predictions)\n if is_nsfw:\n await resend_photo_with_spoiler(message, f\"{custom_caption} {prediction_caption}\", context)\n except Exception as e:\n logging.error(f\"Model error... {str(e)}\", exc_info=True)\n await context.bot.send_message(ADMIN_CHAT, \"Model error...\")\n\n\ndef analyse_predictions(predictions: dict) -> tuple:\n predictions.pop(\"Neutral\")\n if predictions[\"Drawing\"] > 49 and predictions[\"Hentai\"] > 29:\n return True, AUTO_CAPTION.format(f\"Drawing={predictions['Drawing']}, Hentai={predictions['Hentai']}\")\n predictions.pop(\"Drawing\")\n for name, probability in predictions.items():\n if probability > 49:\n return True, AUTO_CAPTION.format(f\"{name}={probability}\")\n return False, \"Photo is neutral\"\n\n\nasync def spoiler_reply_to_photo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n message = update.effective_message\n reply_to_message = update.message.reply_to_message\n\n if reply_to_message and reply_to_message.photo and reply_to_message.from_user.id != context.bot.id:\n reporter_username = message.from_user.username\n from_caption = f'From {reply_to_message.from_user.username} (spoilered by {reporter_username})'\n custom_caption = f'{from_caption}: {reply_to_message.caption}' if reply_to_message.caption else from_caption\n await resend_photo_with_spoiler(reply_to_message, custom_caption, context)\n\n await message.delete()\n\n\nasync def resend_photo_with_spoiler(message: Message, custom_caption: str, context: ContextTypes.DEFAULT_TYPE) -> None:\n await message.delete()\n await context.bot.send_photo(message.chat_id, message.photo[-1].file_id, caption=custom_caption, has_spoiler=True)\n\n\nasync def delete_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n chat_id = update.effective_message.chat_id\n message = update.effective_message\n if is_reply_command_valid(update.effective_message):\n await message.delete()\n await context.bot.delete_message(chat_id, message.reply_to_message.message_id)\n\n\nasync def add_forward_chat_to_black_list(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n reply_to_message = update.effective_message.reply_to_message\n if is_reply_command_valid(update.effective_message) and reply_to_message.forward_from_chat:\n FORWARD_CHAT_BLACK_LIST.add(reply_to_message.forward_from_chat.id)\n logging.info(\"Added chat to black list: {FORWARD_CHAT_BLACK_LIST}\")\n await spoiler_reply_to_photo(update, context)\n\n\nasync def toggle_total_censorship(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n global IS_TOTAL_CENSORSHIP\n chat_id = update.effective_message.chat_id\n if is_admin(update.effective_message):\n IS_TOTAL_CENSORSHIP = not IS_TOTAL_CENSORSHIP\n await context.bot.send_message(chat_id, f\"Total censorship set to {IS_TOTAL_CENSORSHIP}\")\n else:\n await context.bot.delete_message(chat_id, update.effective_message.message_id)\n\n\ndef error(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n logging.info(f\"Update {update} caused error {context.error}\")\n\n\ndef is_reply_command_valid(message: Message) -> bool:\n user_id = message.from_user.id\n reply_to_message = message.reply_to_message\n return user_id in ADMIN_LIST and reply_to_message\n\n\ndef is_admin(message: Message) -> bool:\n user_id = message.from_user.id\n return user_id in ADMIN_LIST\n\n\ndef get_username_from_command(message: Message) -> str:\n return message.text.split(\" \")[1].removeprefix(\"@\")\n\n\ndef main() -> None:\n application = Application.builder().token(TOKEN).build()\n\n application.add_handler(MessageHandler(filters.PHOTO, sloiler_nsfw_photo))\n application.add_handler(CommandHandler(\"blur\", spoiler_reply_to_photo))\n application.add_handler(CommandHandler(\"add\", add_forward_chat_to_black_list))\n application.add_handler(CommandHandler(\"delete\", delete_message))\n application.add_handler(CommandHandler(\"ban\", ban_user_media))\n application.add_handler(CommandHandler(\"unban\", unban_user_media))\n application.add_handler(CommandHandler(\"censor\", toggle_total_censorship))\n\n application.add_error_handler(error)\n\n application.run_polling()\n\n\nif __name__ == \"__main__\":\n main()\n", "repo_name": "Vekeryk/media-filter-bot", "sub_path": "media_filter_bot.py", "file_name": "media_filter_bot.py", "file_ext": "py", "file_size_in_byte": 7753, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "25", "api": [{"api_name": "logging.basicConfig", "line_number": 11, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 12, "usage_type": "attribute"}, {"api_name": "model.load_model", "line_number": 15, "usage_type": "call"}, {"api_name": "telegram.ChatPermissions", "line_number": 17, "usage_type": "call"}, {"api_name": "telegram.ChatPermissions", "line_number": 22, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 25, "usage_type": "name"}, {"api_name": "telegram.ext.ContextTypes.DEFAULT_TYPE", "line_number": 25, "usage_type": "attribute"}, {"api_name": "telegram.ext.ContextTypes", "line_number": 25, "usage_type": "name"}, {"api_name": "constants.USERS.get", "line_number": 31, "usage_type": "call"}, {"api_name": "constants.USERS", "line_number": 31, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 32, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 38, "usage_type": "name"}, {"api_name": "telegram.ext.ContextTypes.DEFAULT_TYPE", "line_number": 38, "usage_type": "attribute"}, {"api_name": "telegram.ext.ContextTypes", "line_number": 38, "usage_type": "name"}, {"api_name": "constants.USERS.get", "line_number": 44, "usage_type": "call"}, {"api_name": "constants.USERS", "line_number": 44, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 45, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 47, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 47, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 47, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 51, "usage_type": "name"}, {"api_name": "telegram.ext.ContextTypes.DEFAULT_TYPE", "line_number": 51, "usage_type": "attribute"}, {"api_name": "telegram.ext.ContextTypes", "line_number": 51, "usage_type": "name"}, {"api_name": "constants.USERS", "line_number": 55, "usage_type": "name"}, {"api_name": "constants.FORWARD_CHAT_BLACK_LIST", "line_number": 63, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 68, "usage_type": "call"}, {"api_name": "constants.USERS", "line_number": 68, "usage_type": "name"}, {"api_name": "constants.FORWARD_CHAT_BLACK_LIST", "line_number": 68, "usage_type": "name"}, {"api_name": "telegram.Message", "line_number": 71, "usage_type": "name"}, {"api_name": "telegram.ext.ContextTypes.DEFAULT_TYPE", "line_number": 71, "usage_type": "attribute"}, {"api_name": "telegram.ext.ContextTypes", "line_number": 71, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 73, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 75, "usage_type": "call"}, {"api_name": "model.classify", "line_number": 77, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 78, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 83, "usage_type": "call"}, {"api_name": "constants.ADMIN_CHAT", "line_number": 84, "usage_type": "argument"}, {"api_name": "constants.AUTO_CAPTION.format", "line_number": 90, "usage_type": "call"}, {"api_name": "constants.AUTO_CAPTION", "line_number": 90, "usage_type": "name"}, {"api_name": "constants.AUTO_CAPTION.format", "line_number": 94, "usage_type": "call"}, {"api_name": "constants.AUTO_CAPTION", "line_number": 94, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 98, "usage_type": "name"}, {"api_name": "telegram.ext.ContextTypes.DEFAULT_TYPE", "line_number": 98, "usage_type": "attribute"}, {"api_name": "telegram.ext.ContextTypes", "line_number": 98, "usage_type": "name"}, {"api_name": "telegram.Message", "line_number": 111, "usage_type": "name"}, {"api_name": "telegram.ext.ContextTypes.DEFAULT_TYPE", "line_number": 111, "usage_type": "attribute"}, {"api_name": "telegram.ext.ContextTypes", "line_number": 111, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 116, "usage_type": "name"}, {"api_name": "telegram.ext.ContextTypes.DEFAULT_TYPE", "line_number": 116, "usage_type": "attribute"}, {"api_name": "telegram.ext.ContextTypes", "line_number": 116, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 124, "usage_type": "name"}, {"api_name": "telegram.ext.ContextTypes.DEFAULT_TYPE", "line_number": 124, "usage_type": "attribute"}, {"api_name": "telegram.ext.ContextTypes", "line_number": 124, "usage_type": "name"}, {"api_name": "constants.FORWARD_CHAT_BLACK_LIST.add", "line_number": 127, "usage_type": "call"}, {"api_name": "constants.FORWARD_CHAT_BLACK_LIST", "line_number": 127, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 128, "usage_type": "call"}, {"api_name": "telegram.Update", "line_number": 132, "usage_type": "name"}, {"api_name": "telegram.ext.ContextTypes.DEFAULT_TYPE", "line_number": 132, "usage_type": "attribute"}, {"api_name": "telegram.ext.ContextTypes", "line_number": 132, "usage_type": "name"}, {"api_name": "telegram.Update", "line_number": 142, "usage_type": "name"}, {"api_name": "telegram.ext.ContextTypes.DEFAULT_TYPE", "line_number": 142, "usage_type": "attribute"}, {"api_name": "telegram.ext.ContextTypes", "line_number": 142, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 143, "usage_type": "call"}, {"api_name": "telegram.Message", "line_number": 146, "usage_type": "name"}, {"api_name": "constants.ADMIN_LIST", "line_number": 149, "usage_type": "name"}, {"api_name": "telegram.Message", "line_number": 152, "usage_type": "name"}, {"api_name": "constants.ADMIN_LIST", "line_number": 154, "usage_type": "name"}, {"api_name": "telegram.Message", "line_number": 157, "usage_type": "name"}, {"api_name": "constants.TOKEN", "line_number": 162, "usage_type": "argument"}, {"api_name": "telegram.ext.Application.builder", "line_number": 162, "usage_type": "call"}, {"api_name": "telegram.ext.Application", "line_number": 162, "usage_type": "name"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 164, "usage_type": "call"}, {"api_name": "telegram.ext.filters.PHOTO", "line_number": 164, "usage_type": "attribute"}, {"api_name": "telegram.ext.filters", "line_number": 164, "usage_type": "name"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 165, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 166, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 167, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 168, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 169, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 170, "usage_type": "call"}]} +{"seq_id": "30643757107", "text": "try:\r\n\timport time\r\n\timport os\r\n\timport sys\r\n\timport random as rd\r\n\timport requests\r\nexcept ImportError:\r\n\tprint(RED + \"[+] \" + WHITE + \"Ejecuta el instalador primero con 'python3 installer.py'\")\r\n\r\nBLACK = '\\033[1;30m'\r\nRED = '\\033[1;31m'\r\nGREEN = '\\033[1;32m'\r\nYELLOW = '\\033[1;33m'\r\nBLUE = '\\033[1;34m'\r\nMAGENTA = '\\033[1;35m'\r\nCYAN = '\\033[1;36m'\r\nWHITE = '\\033[1;37m'\r\nRESET = '\\033[1;39m'\r\n\r\ndef slowprint(s):\r\n for c in s + '\\n' :\r\n sys.stdout.write(c)\r\n sys.stdout.flush()\r\n time.sleep(10. / 100)\r\n\r\ndef banner():\r\n\tprint(RED + \"\"\"\r\n██╗ ██╗███████╗██████╗ ███████╗ ██╗ ██╗ █████╗ ████████╗\r\n██║ ██║██╔════╝██╔══██╗ ██╔════╝ ██║ ██║ ██╔══██╗╚══██╔══╝\r\n██║ █╗ ██║█████╗ ██████╔╝ ███████╗ ██║ █╗ ██║ ███████║ ██║ \r\n██║███╗██║██╔══╝ ██╔══██╗ ╚════██║ ██║███╗██║ ██╔══██║ ██║ \r\n╚███╔███╔╝███████╗██████╔╝ ███████║██╗╚███╔███╔╝██╗██║ ██║██╗██║ \r\n ╚══╝╚══╝ ╚══════╝╚═════╝ ╚══════╝╚═╝ ╚══╝╚══╝ ╚═╝╚═╝ ╚═╝╚═╝╚═╝ \r\n By Xaykz\r\n TikTok: @xaykz\r\n\"\"\")\r\n\r\ndef menu():\r\n\tprint(RED + \"==> \" + WHITE + \"Para poner tu index, ponelo en la ruta 'webs/'\")\r\n\tprint(RED + \"--> \" + WHITE + \"1 Defacear\")\r\n\tprint(RED + \"--> \" + WHITE + \"2 Generar webs\")\r\n\tprint(RED + \"--> \" + WHITE + \"3 Ver contenido del archivo de paginas a defacear\")\r\n\tprint(RED + \"--> \" + WHITE + \"4 Añadir una pagina a la lista de pagina a intentar defacear\")\r\n\tprint(RED + \"--> \" + WHITE + \"5 Ver paginas que probablemente se pudieron defacear\")\r\n\tprint()\r\n\r\ndef main():\r\n\tbanner()\r\n\twhile True:\r\n\t\tmenu()\r\n\t\tpeticion = input(RED + \"$ \" + WHITE + \"Selecciona una option > \")\r\n\t\tif peticion == \"2\":\r\n\t\t\ttry:\r\n\t\t\t\tprint(RED + \"$ \" + WHITE + \"Ejemplo: org, com, co.za, co.il, sa, gob, gov\")\r\n\t\t\t\tprint(RED + \"$ \" + WHITE + \"Recomendados: com, org, sa, co.il\")\r\n\t\t\t\textension = input(RED + \"$ \" + WHITE + \"Extension > \")\r\n\t\t\t\twhile True:\r\n\t\t\t\t\tl1 = rd.choice(\"abcdefghijklmnopqrstuvwxyz0123456789\")\r\n\t\t\t\t\tl2 = rd.choice(\"abcdefghijklmnopqrstuvwxyz0123456789\")\r\n\t\t\t\t\tl3 = rd.choice(\"abcdefghijklmnopqrstuvwxyz0123456789\")\r\n\t\t\t\t\tl4 = rd.choice(\"abcdefghijklmnopqrstuvwxyz0123456789\")\r\n\t\t\t\t\tl5 = rd.choice(\"abcdefghijklmnopqrstuvwxyz0123456789\")\r\n\t\t\t\t\tl6 = rd.choice(\"abcdefghijklmnopqrstuvwxyz0123456789\")\r\n\t\t\t\t\tpagina = \"http://\" + l1 + l2 + l3 + l4 + l5 + l6 + \".\" + extension + \"\\n\"\r\n\t\t\t\t\tpagina2 = \"http://\" + l1 + l2 + l3 + l4 + l5 + l6 + \".\" + extension\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\tr = requests.get(pagina2)\r\n\t\t\t\t\t\tif r.status_code == 200:\r\n\t\t\t\t\t\t\tprint(GREEN + \"$ \" + pagina2 + WHITE + \" - Existe\")\r\n\t\t\t\t\t\t\ta = open(\"webs/target.txt\", \"a\")\r\n\t\t\t\t\t\t\ta.write(pagina2+\"\\n\")\r\n\t\t\t\t\t\t\ta.close()\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\tprint(RED + \"$ \" + pagina2 + WHITE + \" - No existe\")\r\n\t\t\texcept KeyboardInterrupt:\r\n\t\t\t\tprint(\"Cerrando...\")\r\n\t\telif peticion == \"1\":\r\n\t\t\ttry:\r\n\t\t\t\tos.system(\"cd webs && python3 deface.py\")\r\n\t\t\texcept KeyboardInterrupt:\r\n\t\t\t\tprint(\"Cerrando...\")\r\n\t\telif peticion == \"3\":\r\n\t\t\tprint(RED + \"$ \" + WHITE + \"Contenido del archivo de paginas a defacear:\")\r\n\t\t\tprint()\r\n\t\t\ttry:\r\n\t\t\t\ta = open(\"webs/target.txt\", \"r\")\r\n\t\t\t\tb = a.read()\r\n\t\t\t\tprint(WHITE + b)\r\n\t\t\t\ta.close()\r\n\t\t\texcept FileNotFoundError:\r\n\t\t\t\tprint(RED + \"El archivo '\" + WHITE + \"target.txt\" + RED + \"' no fue encontrado\")\r\n\t\telif peticion == \"4\":\r\n\t\t\tprint(RED + \"$ \" + WHITE + \"Ejemplo: http://ejemplo.com\")\r\n\t\t\twhile True:\r\n\t\t\t\tpagina = input(RED + \"$ \" + WHITE + \"Pagina > \")\r\n\t\t\t\ttry:\r\n\t\t\t\t\tr = requests.get(pagina)\r\n\t\t\t\t\tif r.status_code == 200:\r\n\t\t\t\t\t\tprint(GREEN + \"$ \" + pagina + WHITE + \" - Existe\")\r\n\t\t\t\t\t\ta = open(\"webs/target.txt\", \"a\")\r\n\t\t\t\t\t\ta.write(pagina+\"\\n\")\r\n\t\t\t\t\t\ta.close()\r\n\t\t\t\texcept:\r\n\t\t\t\t\tprint(RED + \"$ \" + pagina + WHITE + \" - No Existe\")\r\n\t\telif peticion == \"5\":\r\n\t\t\tprint(RED + \"$ \" + WHITE + \"Paginas que probablemente se pudieron defacear:\")\r\n\t\t\tprint()\r\n\t\t\ttry:\r\n\t\t\t\ta = open(\"webs/defaceadas.txt\", \"r\")\r\n\t\t\t\tb = a.read()\r\n\t\t\t\tprint(WHITE + b)\r\n\t\t\t\ta.close()\r\n\t\t\texcept FileNotFoundError:\r\n\t\t\t\tprint(RED + \"El archivo '\" + WHITE + \"defaceadas.txt\" + RED + \"' no fue encontrado\")\r\n\r\nif __name__ == '__main__':\r\n\tmain()", "repo_name": "1099xaykz/WebSWAT", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 4752, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "sys.stdout.write", "line_number": 22, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 22, "usage_type": "attribute"}, {"api_name": "sys.stdout.flush", "line_number": 23, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 23, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 24, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 58, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 59, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 60, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 61, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 62, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 63, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 67, "usage_type": "call"}, {"api_name": "os.system", "line_number": 79, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 97, "usage_type": "call"}]} +{"seq_id": "1414225076", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render\nimport json\nimport requests\nfrom .forms import getWord\n\n# Create your views here.\ndef index(request):\n\n context = {}\n countries = {\n 'Iceland' : 'is',\n 'Spain' : 'es',\n 'Germany' : 'de',\n 'France' : 'fr',\n 'Ireland' : 'ga',\n 'England' : 'en',\n 'Scotland' : 'gd',\n 'Wales' : 'cy',\n 'Netherlands' : 'nl',\n 'Spain' : 'es',\n 'Portugal' : 'pt',\n 'Denmark' : 'da',\n 'Norway' : 'no',\n 'Sweden' : 'sv',\n 'Finland' : 'fi',\n 'Estonia' : 'et',\n 'Latvia' : 'lv',\n 'Lithuania' : 'lt',\n 'Luxembourg' : 'lb',\n 'Russia' : 'ru',\n 'Belarus' : 'be',\n 'Ukraine' : 'uk',\n 'Poland' : 'pl',\n 'Czechia' : 'cs',\n 'Slovakia' : 'sk',\n 'Slovenia' : 'sl',\n 'Romania' : 'ro',\n 'Bulgaria' : 'bg',\n 'Serbia' : 'sr',\n 'Hungary' : 'hu',\n 'Croatia' : 'hr',\n 'Greece' : 'el',\n 'Georgia' : 'ka',\n 'Italy' : 'it',\n 'Turkey' : 'tr',\n }\n\n form = getWordForm()\n word = post(request)\n\n if word != '':\n for country, code in countries.items():\n translation = getTranslation(code, word)\n context[country] = translation\n\n context[\"form\"] = form\n\n return render(request, 'TranslationMap/index.html', context)\n\ndef getWordForm():\n form = getWord()\n return form\n\ndef post(request):\n form = getWord(request.POST)\n text = ''\n if form.is_valid():\n text = form.cleaned_data['word']\n return text\n\ndef getTranslation(language, word):\n url = 'https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20180527T143501Z.a7a28c5351395283.7f23654a4c75fec66cba97a8d0f8be8008c1cee1&text=' + word + '&lang=' + language + '&[format=utf-8'\n response = requests.get(url)\n data = json.loads(response.content.decode('utf-8'))\n translation = ''.join(data['text'])\n return translation", "repo_name": "OisinNolan/Interactive-Translation-Map", "sub_path": "TranslationMapApp/TranslationMap/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2065, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "django.shortcuts.render", "line_number": 61, "usage_type": "call"}, {"api_name": "forms.getWord", "line_number": 64, "usage_type": "call"}, {"api_name": "forms.getWord", "line_number": 68, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 76, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 77, "usage_type": "call"}]} +{"seq_id": "23128975613", "text": "from datetime import timedelta\n\nfrom city_scrapers_core.constants import CITY_COUNCIL, COMMITTEE\nfrom city_scrapers_core.items import Meeting\nfrom city_scrapers_core.spiders import LegistarSpider\n\n\nclass PittCityCouncilSpider(LegistarSpider):\n name = \"pitt_city_council\"\n agency = \"Pittsburgh City Council\"\n timezone = \"America/New_York\"\n allowed_domains = [\"pittsburgh.legistar.com\"]\n start_urls = [\"https://pittsburgh.legistar.com\"]\n # Add the titles of any links not included in the scraped results\n link_types = []\n\n def parse_legistar(self, events):\n \"\"\"\n `parse_legistar` should always `yield` Meeting items.\n\n Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping\n needs.\n \"\"\"\n for event, _ in events:\n start = self.legistar_start(event)\n title = event.get(\"Name\")\n meeting = Meeting(\n title=title,\n description=self._parse_description(event),\n classification=self._parse_classification(title),\n start=start,\n end=self._parse_end(start),\n all_day=False,\n time_notes=\"Estimated 3 hour meeting length\",\n location=self._parse_location(event),\n links=self.legistar_links(event),\n source=self._parse_source(event),\n )\n\n meeting[\"status\"] = self._get_status(meeting)\n meeting[\"id\"] = self._get_id(meeting)\n\n yield meeting\n\n def _parse_end(self, start):\n return start + timedelta(hours=3)\n\n def _parse_description(self, item):\n \"\"\"\n Parse or generate meeting description.\n In Pittsburgh's case the meeting info comes on a new line\n in the location section, italicized.\n \"\"\"\n try:\n return item.get('Meeting Location').split('\\n')[1].split('--em--')[1]\n except IndexError:\n return \"\"\n\n def _parse_location(self, item):\n \"\"\"\n Parse or generate location.\n \"\"\"\n location = item.get('Meeting Location').split('\\n')[0]\n address = ''\n if 'Council Chambers' in location:\n address = '414 Grant Street, Pittsburgh, PA 15219'\n return {\n 'address': address,\n 'location': 'Council Chambers, 5th Floor',\n 'name': '',\n 'neighborhood': ''\n }\n\n def _parse_classification(self, title):\n \"\"\"Parse or generate classification from allowed options.\"\"\"\n if \"committee\" in title.lower():\n return COMMITTEE\n return CITY_COUNCIL\n\n def _parse_source(self, item):\n \"\"\"Parse source from meeting details if available\"\"\"\n default_source = \"{}/Calendar.aspx\".format(self.base_url)\n if isinstance(item.get(\"Meeting Details\"), dict):\n return item[\"Meeting Details\"].get(\"url\", default_source)\n return default_source\n", "repo_name": "cityscrapers-brian/cityscrapers1", "sub_path": "city_scrapers/spiders/pitt_city_council.py", "file_name": "pitt_city_council.py", "file_ext": "py", "file_size_in_byte": 2967, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "city_scrapers_core.spiders.LegistarSpider", "line_number": 8, "usage_type": "name"}, {"api_name": "city_scrapers_core.items.Meeting", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 46, "usage_type": "call"}, {"api_name": "city_scrapers_core.constants.COMMITTEE", "line_number": 77, "usage_type": "name"}, {"api_name": "city_scrapers_core.constants.CITY_COUNCIL", "line_number": 78, "usage_type": "name"}]} +{"seq_id": "72658072712", "text": "import sys\nfrom collections import deque\n\ninput = sys.stdin.readline\n\ndef bfs(s):\n q = deque()\n q.append(s)\n visited = [-1] * (N + 1)\n visited[s] = 0\n\n while q:\n now = q.popleft()\n for i in range(0, len(graph[now])):\n if visited[graph[now][i][0]] == -1:\n visited[graph[now][i][0]] = visited[now] + graph[now][i][1]\n q.append(graph[now][i][0])\n \n return {'node': visited.index(max(visited)), 'distance': max(visited)}\n\n\nN = int(input())\ngraph = [[] for _ in range(N + 1)]\n\nfor _ in range(N - 1):\n S, E, T = map(int, input().split())\n graph[S].append((E, T))\n graph[E].append((S, T))\n\nprint(bfs(bfs(1)['node'])['distance'])", "repo_name": "DasisCore/SSAFY_algorithm_study", "sub_path": "Choi_Inho/gold/1967.py", "file_name": "1967.py", "file_ext": "py", "file_size_in_byte": 706, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "sys.stdin", "line_number": 4, "usage_type": "attribute"}, {"api_name": "collections.deque", "line_number": 7, "usage_type": "call"}]} +{"seq_id": "32046236843", "text": "__all__ = [\"JWTBearer\", \"admin_user\", \"finnhub_client\"]\n\nfrom typing import Any\n\nimport finnhub\nimport jwt\nfrom fastapi import Depends, HTTPException, Request, status\nfrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearer\n\nfrom app.config import get_settings\nfrom app.models import User\n\nsettings = get_settings()\n\n\nclass JWTBearer(HTTPBearer):\n async def __call__(self, request: Request) -> User:\n credentials: HTTPAuthorizationCredentials = await super(\n JWTBearer, self\n ).__call__(request)\n if credentials:\n if credentials.scheme != \"Bearer\":\n raise HTTPException(\n status_code=status.HTTP_403_FORBIDDEN,\n detail=\"Invalid authentication scheme.\",\n )\n payload = self.get_jwt_payload(credentials.credentials)\n user = await self.identify_user(payload[\"name\"])\n if not user:\n raise HTTPException(\n status_code=status.HTTP_403_FORBIDDEN, detail=\"Invalid token.\"\n )\n return user\n\n @staticmethod\n def get_jwt_payload(token: str) -> dict[str, Any]:\n return jwt.decode(\n token, algorithms=\"HS256\", options={\"verify_signature\": False}\n )\n\n @staticmethod\n async def identify_user(user_name) -> User | None:\n return await User.get_or_none(full_name=user_name)\n\n\ndef admin_user(user: User = Depends(JWTBearer())):\n if not user.is_admin:\n raise HTTPException(\n status_code=status.HTTP_403_FORBIDDEN, detail=\"Admin permission required\"\n )\n\n\ndef finnhub_client() -> finnhub.Client:\n return finnhub.Client(api_key=settings.FINNHUB_SECRET)\n", "repo_name": "Four-Velocity/DarkStore", "sub_path": "app/dependencies.py", "file_name": "dependencies.py", "file_ext": "py", "file_size_in_byte": 1723, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "app.config.get_settings", "line_number": 13, "usage_type": "call"}, {"api_name": "fastapi.security.HTTPBearer", "line_number": 16, "usage_type": "name"}, {"api_name": "fastapi.Request", "line_number": 17, "usage_type": "name"}, {"api_name": "fastapi.security.HTTPAuthorizationCredentials", "line_number": 18, "usage_type": "name"}, {"api_name": "fastapi.HTTPException", "line_number": 23, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_403_FORBIDDEN", "line_number": 24, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 24, "usage_type": "name"}, {"api_name": "fastapi.HTTPException", "line_number": 30, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_403_FORBIDDEN", "line_number": 31, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 31, "usage_type": "name"}, {"api_name": "app.models.User", "line_number": 17, "usage_type": "name"}, {"api_name": "jwt.decode", "line_number": 37, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 36, "usage_type": "name"}, {"api_name": "app.models.User.get_or_none", "line_number": 43, "usage_type": "call"}, {"api_name": "app.models.User", "line_number": 43, "usage_type": "name"}, {"api_name": "app.models.User", "line_number": 42, "usage_type": "name"}, {"api_name": "app.models.User", "line_number": 46, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 46, "usage_type": "call"}, {"api_name": "fastapi.HTTPException", "line_number": 48, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_403_FORBIDDEN", "line_number": 49, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 49, "usage_type": "name"}, {"api_name": "finnhub.Client", "line_number": 54, "usage_type": "call"}, {"api_name": "finnhub.Client", "line_number": 53, "usage_type": "attribute"}]} +{"seq_id": "12157240170", "text": "from __future__ import absolute_import, print_function\n\nimport datetime\nimport os\nimport subprocess\n\n# PyLint cannot properly find names inside Cocoa libraries, so issues bogus\n# No name 'Foo' in module 'Bar' warnings. Disable them.\n# pylint: disable=E0611,E0401\nfrom Foundation import NSDate\n# pylint: enable=E0611,E0401\n\nfrom . import dmg\nfrom . import pkg\nfrom . import rmpkgs\n\nfrom .. import adobeutils\nfrom .. import constants\nfrom .. import display\nfrom .. import dmgutils\nfrom .. import munkistatus\nfrom .. import munkilog\nfrom .. import osinstaller\nfrom .. import pkgutils\nfrom .. import powermgr\nfrom .. import prefs\nfrom .. import processes\nfrom .. import profiles\nfrom .. import reports\nfrom .. import scriptutils\nfrom .. import FoundationPlist\n\nfrom ..updatecheck import catalogs\nfrom ..updatecheck import manifestutils\n\n# initialize our report fields\n# we do this here because appleupdates.installAppleUpdates()\n# calls install_with_info()\nreports.report['InstallResults'] = []\nreports.report['RemovalResults'] = []\n\n\ndef remove_copied_items(itemlist):\n '''Removes filesystem items based on info in itemlist.\n These items were typically installed via DMG'''\n retcode = 0\n if not itemlist:\n display.display_error(\"Nothing to remove!\")\n return -1\n\n for item in itemlist:\n if 'destination_item' in item:\n itemname = item.get(\"destination_item\")\n else:\n itemname = item.get(\"source_item\")\n if not itemname:\n display.display_error(\"Missing item name to remove.\")\n retcode = -1\n break\n destpath = item.get(\"destination_path\")\n if not destpath:\n display.display_error(\"Missing path for item to remove.\")\n retcode = -1\n break\n path_to_remove = os.path.join(destpath, os.path.basename(itemname))\n if os.path.exists(path_to_remove):\n display.display_status_minor('Removing %s' % path_to_remove)\n retcode = subprocess.call(['/bin/rm', '-rf', path_to_remove])\n if retcode:\n display.display_error(\n 'Removal error for %s', path_to_remove)\n break\n else:\n # path_to_remove doesn't exist\n # note it, but not an error\n display.display_detail(\"Path %s doesn't exist.\", path_to_remove)\n\n return retcode\n\n\ndef item_prereqs_in_skipped_items(item, skipped_items):\n '''Looks for item prerequisites (requires and update_for) in the list\n of skipped items. Returns a list of matches.'''\n\n # shortcut -- if we have no skipped items, just return an empty list\n # also reduces log noise in the common case\n if not skipped_items:\n return []\n\n display.display_debug1(\n 'Checking for skipped prerequisites for %s-%s'\n % (item['name'], item.get('version_to_install')))\n\n # get list of prerequisites for this item\n prerequisites = item.get('requires', [])\n prerequisites.extend(item.get('update_for', []))\n if not prerequisites:\n display.display_debug1(\n '%s-%s has no prerequisites.'\n % (item['name'], item.get('version_to_install')))\n return []\n display.display_debug1('Prerequisites: %s' % \", \".join(prerequisites))\n\n # build a dictionary of names and versions of skipped items\n skipped_item_dict = {}\n for skipped_item in skipped_items:\n if skipped_item['name'] not in skipped_item_dict:\n skipped_item_dict[skipped_item['name']] = []\n normalized_version = pkgutils.trim_version_string(\n skipped_item.get('version_to_install', '0.0'))\n display.display_debug1(\n 'Adding skipped item: %s-%s',\n skipped_item['name'], normalized_version)\n skipped_item_dict[skipped_item['name']].append(normalized_version)\n\n # now check prereqs against the skipped items\n matched_prereqs = []\n for prereq in prerequisites:\n (name, version) = catalogs.split_name_and_version(prereq)\n display.display_debug1(\n 'Comparing %s-%s against skipped items', name, version)\n if name in skipped_item_dict:\n if version:\n version = pkgutils.trim_version_string(version)\n if version in skipped_item_dict[name]:\n matched_prereqs.append(prereq)\n else:\n matched_prereqs.append(prereq)\n return matched_prereqs\n\n\ndef requires_restart(item):\n '''Returns boolean to indicate if the item needs a restart'''\n return (item.get(\"RestartAction\") == \"RequireRestart\" or\n item.get(\"RestartAction\") == \"RecommendRestart\")\n\n\ndef handle_apple_package_install(item, itempath):\n '''Process an Apple package for install. Returns retcode, needs_restart'''\n needs_restart = False\n suppress_bundle_relocation = item.get(\"suppress_bundle_relocation\", False)\n display.display_debug1(\n \"suppress_bundle_relocation: %s\", suppress_bundle_relocation)\n if pkgutils.hasValidDiskImageExt(itempath):\n display.display_status_minor(\n \"Mounting disk image %s\" % os.path.basename(itempath))\n mount_with_shadow = suppress_bundle_relocation\n # we need to mount the diskimage as read/write to be able to\n # modify the package to suppress bundle relocation\n mountpoints = dmgutils.mountdmg(\n itempath, use_shadow=mount_with_shadow, skip_verification=True)\n if not mountpoints:\n display.display_error(\n \"No filesystems mounted from %s\", item[\"installer_item\"])\n return (-99, False)\n if processes.stop_requested():\n dmgutils.unmountdmg(mountpoints[0])\n return (-99, False)\n\n retcode = -99 # in case we find nothing to install\n needtorestart = False\n if pkgutils.hasValidInstallerItemExt(item.get('package_path', '')):\n # admin has specified the relative path of the pkg on the DMG\n # this is useful if there is more than one pkg on the DMG,\n # or the actual pkg is not at the root of the DMG\n fullpkgpath = os.path.join(mountpoints[0], item['package_path'])\n if os.path.exists(fullpkgpath):\n (retcode, needtorestart) = pkg.install(fullpkgpath, item)\n else:\n # no relative path to pkg on dmg, so just install all\n # pkgs found at the root of the first mountpoint\n # (hopefully there's only one)\n (retcode, needtorestart) = pkg.installall(mountpoints[0], item)\n needs_restart = needtorestart or requires_restart(item)\n dmgutils.unmountdmg(mountpoints[0])\n elif pkgutils.hasValidPackageExt(itempath):\n (retcode, needtorestart) = pkg.install(itempath, item)\n needs_restart = needtorestart or requires_restart(item)\n else:\n # we didn't find anything we know how to install\n munkilog.log(\n \"Found nothing we know how to install in %s\" % itempath)\n retcode = -99\n\n return (retcode, needs_restart)\n\n\ndef install_with_info(\n dirpath, installlist, only_unattended=False, applesus=False):\n \"\"\"\n Uses the installlist to install items in the\n correct order.\n \"\"\"\n restartflag = False\n itemindex = 0\n skipped_installs = []\n for item in installlist:\n # Keep track of when this particular install started.\n utc_now = datetime.datetime.utcnow()\n itemindex = itemindex + 1\n\n if item.get('installer_type') == 'startosinstall':\n skipped_installs.append(item)\n display.display_debug1(\n 'Skipping install of %s because it\\'s a startosinstall item. '\n 'Will install later.' % item['name'])\n continue\n if only_unattended:\n if not item.get('unattended_install'):\n skipped_installs.append(item)\n display.display_detail(\n 'Skipping install of %s because it\\'s not unattended.'\n % item['name'])\n continue\n if processes.blocking_applications_running(item):\n skipped_installs.append(item)\n display.display_detail(\n 'Skipping unattended install of %s because blocking '\n 'application(s) running.' % item['name'])\n continue\n\n skipped_prereqs = item_prereqs_in_skipped_items(item, skipped_installs)\n if skipped_prereqs:\n # one or more prerequisite for this item was skipped or failed;\n # need to skip this item too\n skipped_installs.append(item)\n if only_unattended:\n format_str = ('Skipping unattended install of %s because these '\n 'prerequisites were skipped: %s')\n else:\n format_str = ('Skipping install of %s because these '\n 'prerequisites were not installed: %s')\n display.display_detail(\n format_str % (item['name'], \", \".join(skipped_prereqs)))\n continue\n\n if processes.stop_requested():\n return restartflag, skipped_installs\n\n display_name = item.get('display_name') or item.get('name')\n version_to_install = item.get('version_to_install', '')\n display.display_status_major(\n \"Installing %s (%s of %s)\"\n % (display_name, itemindex, len(installlist)))\n\n retcode = 0\n if 'preinstall_script' in item:\n retcode = scriptutils.run_embedded_script('preinstall_script', item)\n\n if retcode == 0 and 'installer_item' in item:\n installer_type = item.get(\"installer_type\", \"\")\n\n itempath = os.path.join(dirpath, item[\"installer_item\"])\n if installer_type != \"nopkg\" and not os.path.exists(itempath):\n # can't install, so we should stop. Since later items might\n # depend on this one, we shouldn't continue\n display.display_error(\n \"Installer item %s was not found.\", item[\"installer_item\"])\n return restartflag, skipped_installs\n # Adobe installs\n if installer_type.startswith(\"Adobe\"):\n retcode = adobeutils.do_adobe_install(item)\n if retcode == 0 and requires_restart(item):\n restartflag = True\n if retcode == 8:\n # Adobe Setup says restart needed.\n restartflag = True\n retcode = 0\n # stage_os_installer install\n elif installer_type == \"stage_os_installer\":\n retcode = dmg.copy_from_dmg(itempath, item.get('items_to_copy'))\n if retcode == 0:\n osinstaller.record_staged_os_installer(item)\n # copy_from_dmg install\n elif installer_type == \"copy_from_dmg\":\n retcode = dmg.copy_from_dmg(itempath, item.get('items_to_copy'))\n if retcode == 0 and requires_restart(item):\n restartflag = True\n # appdmg install (deprecated)\n elif installer_type == \"appdmg\":\n display.display_warning(\n \"install_type 'appdmg' is deprecated. Use 'copy_from_dmg'.\")\n retcode = dmg.copy_app_from_dmg(itempath)\n # configuration profile install\n elif installer_type == 'profile':\n # profiles.install_profile returns True/False\n retcode = 0\n identifier = item.get('PayloadIdentifier')\n if not profiles.install_profile(itempath, identifier):\n retcode = -1\n if retcode == 0 and requires_restart(item):\n restartflag = True\n # nopkg (Packageless) install\n elif installer_type == \"nopkg\":\n restartflag = restartflag or requires_restart(item)\n # unknown installer_type\n elif installer_type != \"\":\n # we've encountered an installer type\n # we don't know how to handle\n display.display_error(\n \"Unsupported install type: %s\" % installer_type)\n retcode = -99\n # better be Apple installer package\n else:\n (retcode, need_to_restart) = handle_apple_package_install(\n item, itempath)\n if need_to_restart:\n restartflag = True\n\n if processes.stop_requested():\n return restartflag, skipped_installs\n\n # install succeeded. Do we have a postinstall_script?\n if retcode == 0 and 'postinstall_script' in item:\n # only run embedded postinstall script if the install did not\n # return a failure code\n retcode = scriptutils.run_embedded_script(\n 'postinstall_script', item)\n if retcode:\n # we won't consider postinstall script failures as fatal\n # since the item has been installed via package/disk image\n # but admin should be notified\n display.display_warning(\n 'Postinstall script for %s returned %s'\n % (item['name'], retcode))\n # reset retcode to 0 so we will mark this install\n # as successful\n retcode = 0\n\n # if install was successful and this is a SelfService OnDemand install\n # remove the item from the SelfServeManifest's managed_installs\n if retcode == 0 and item.get('OnDemand'):\n manifestutils.remove_from_selfserve_installs(item['name'])\n\n # record install success/failure\n if not 'InstallResults' in reports.report:\n reports.report['InstallResults'] = []\n\n if applesus:\n message = \"Apple SUS install of %s-%s: %s\"\n else:\n message = \"Install of %s-%s: %s\"\n\n if retcode == 0:\n status = \"SUCCESSFUL\"\n else:\n status = \"FAILED with return code: %s\" % retcode\n # add this failed install to the skipped_installs list\n # so that any item later in the list that requires this\n # item is skipped as well.\n skipped_installs.append(item)\n\n log_msg = message % (display_name, version_to_install, status)\n munkilog.log(log_msg, \"Install.log\")\n\n # Calculate install duration; note, if a machine is put to sleep\n # during the install this time may be inaccurate.\n utc_now_complete = datetime.datetime.utcnow()\n duration_seconds = (utc_now_complete - utc_now).seconds\n\n download_speed = item.get('download_kbytes_per_sec', 0)\n install_result = {\n 'display_name': display_name,\n 'name': item['name'],\n 'version': version_to_install,\n 'applesus': applesus,\n 'status': retcode,\n 'time': NSDate.new(),\n 'duration_seconds': duration_seconds,\n 'download_kbytes_per_sec': download_speed,\n 'unattended': only_unattended,\n }\n reports.report['InstallResults'].append(install_result)\n\n # check to see if this installer item is needed by any additional\n # items in installinfo\n # this might happen if there are multiple things being installed\n # with choicesXML files applied to a metapackage or\n # multiple packages being installed from a single DMG\n stillneeded = False\n current_installer_item = item['installer_item']\n # are we at the end of the installlist?\n # (we already incremented itemindex for display\n # so with zero-based arrays itemindex now points to the item\n # after the current item)\n if itemindex < len(installlist):\n # nope, let's check the remaining items\n for lateritem in installlist[itemindex:]:\n if (lateritem.get('installer_item') ==\n current_installer_item):\n stillneeded = True\n break\n\n # check to see if the item is both precache and OnDemand\n if not stillneeded and item.get('precache') and item.get('OnDemand'):\n stillneeded = True\n break\n\n # need to check skipped_installs as well\n if not stillneeded:\n for skipped_item in skipped_installs:\n if (skipped_item.get('installer_item') ==\n current_installer_item):\n stillneeded = True\n break\n\n # ensure package is not deleted from cache if installation\n # fails by checking retcode\n if not stillneeded and retcode == 0:\n # now remove the item from the install cache\n # (if it's still there)\n itempath = os.path.join(dirpath, current_installer_item)\n if os.path.exists(itempath):\n if os.path.isdir(itempath):\n retcode = subprocess.call([\"/bin/rm\", \"-rf\", itempath])\n else:\n # flat pkg or dmg\n retcode = subprocess.call([\"/bin/rm\", itempath])\n if pkgutils.hasValidDiskImageExt(itempath):\n shadowfile = os.path.join(itempath, \".shadow\")\n if os.path.exists(shadowfile):\n retcode = subprocess.call([\"/bin/rm\", shadowfile])\n\n return (restartflag, skipped_installs)\n\n\ndef skipped_items_that_require_this(item, skipped_items):\n '''Looks for items in the skipped_items that require or are update_for\n the current item. Returns a list of matches.'''\n\n # shortcut -- if we have no skipped items, just return an empty list\n # also reduces log noise in the common case\n if not skipped_items:\n return []\n\n display.display_debug1(\n 'Checking for skipped items that require %s' % item['name'])\n\n matched_skipped_items = []\n for skipped_item in skipped_items:\n # get list of prerequisites for this skipped_item\n prerequisites = skipped_item.get('requires', [])\n prerequisites.extend(skipped_item.get('update_for', []))\n display.display_debug1(\n '%s has these prerequisites: %s'\n % (skipped_item['name'], ', '.join(prerequisites)))\n for prereq in prerequisites:\n (prereq_name, dummy_version) = catalogs.split_name_and_version(\n prereq)\n if prereq_name == item['name']:\n matched_skipped_items.append(skipped_item['name'])\n return matched_skipped_items\n\n\ndef process_removals(removallist, only_unattended=False):\n '''processes removals from the removal list'''\n restart_flag = False\n index = 0\n skipped_removals = []\n for item in removallist:\n if only_unattended:\n if not item.get('unattended_uninstall'):\n skipped_removals.append(item)\n display.display_detail(\n ('Skipping removal of %s because it\\'s not unattended.'\n % item['name']))\n continue\n if processes.blocking_applications_running(item):\n skipped_removals.append(item)\n display.display_detail(\n 'Skipping unattended removal of %s because '\n 'blocking application(s) running.' % item['name'])\n continue\n\n dependent_skipped_items = skipped_items_that_require_this(\n item, skipped_removals)\n if dependent_skipped_items:\n # need to skip this too\n skipped_removals.append(item)\n display.display_detail(\n 'Skipping removal of %s because these '\n 'skipped items required it: %s'\n % (item['name'], \", \".join(dependent_skipped_items)))\n continue\n\n if processes.stop_requested():\n return restart_flag, skipped_removals\n if not item.get('installed'):\n # not installed, so skip it (this shouldn't happen...)\n continue\n\n index += 1\n display_name = item.get('display_name') or item.get('name')\n display.display_status_major(\n \"Removing %s (%s of %s)...\", display_name, index, len(removallist))\n\n retcode = 0\n # run preuninstall_script if it exists\n if 'preuninstall_script' in item:\n retcode = scriptutils.run_embedded_script(\n 'preuninstall_script', item)\n\n if retcode == 0 and 'uninstall_method' in item:\n uninstallmethod = item['uninstall_method']\n if uninstallmethod == \"removepackages\":\n if 'packages' in item:\n restart_flag = requires_restart(item)\n retcode = rmpkgs.removepackages(item['packages'],\n forcedeletebundles=True)\n if retcode:\n if retcode == -128:\n message = (\n \"Uninstall of %s was cancelled.\" % display_name)\n else:\n message = \"Uninstall of %s failed.\" % display_name\n display.display_error(message)\n else:\n munkilog.log(\n \"Uninstall of %s was successful.\" % display_name)\n\n elif uninstallmethod == \"uninstall_package\":\n # install a package to remove the software\n if \"uninstaller_item\" in item:\n managedinstallbase = prefs.pref('ManagedInstallDir')\n itempath = os.path.join(managedinstallbase, 'Cache',\n item[\"uninstaller_item\"])\n if not os.path.exists(itempath):\n display.display_error(\n \"%s package for %s was missing from the cache.\"\n % (uninstallmethod, item['name']))\n continue\n (retcode, need_to_restart) = handle_apple_package_install(\n item, itempath)\n if need_to_restart:\n restart_flag = True\n else:\n display.display_error(\n \"No uninstall item specified for %s\" % item['name'])\n continue\n\n elif uninstallmethod.startswith(\"Adobe\"):\n retcode = adobeutils.do_adobe_removal(item)\n\n elif uninstallmethod == \"remove_copied_items\":\n retcode = remove_copied_items(item.get('items_to_remove'))\n\n elif uninstallmethod == \"remove_app\":\n # deprecated with appdmg!\n remove_app_info = item.get('remove_app_info', None)\n if remove_app_info:\n path_to_remove = remove_app_info['path']\n display.display_status_minor(\n 'Removing %s' % path_to_remove)\n retcode = subprocess.call(\n [\"/bin/rm\", \"-rf\", path_to_remove])\n if retcode:\n display.display_error(\n \"Removal error for %s\", path_to_remove)\n else:\n display.display_error(\n \"Application removal info missing from %s\",\n display_name)\n\n elif uninstallmethod == 'remove_profile':\n identifier = item.get('PayloadIdentifier')\n if identifier:\n retcode = 0\n if not profiles.remove_profile(identifier):\n retcode = -1\n display.display_error(\n \"Profile removal error for %s\", identifier)\n else:\n display.display_error(\n \"Profile removal info missing from %s\", display_name)\n\n elif uninstallmethod == 'uninstall_script':\n retcode = scriptutils.run_embedded_script(\n 'uninstall_script', item)\n if retcode == 0 and requires_restart(item):\n restart_flag = True\n\n elif (os.path.exists(uninstallmethod) and\n os.access(uninstallmethod, os.X_OK)):\n # it's a script or program to uninstall\n retcode = scriptutils.run_script(\n display_name, uninstallmethod, 'uninstall script')\n if retcode == 0 and requires_restart(item):\n restart_flag = True\n\n else:\n munkilog.log(\"Uninstall of %s failed because there was no \"\n \"valid uninstall method.\" % display_name)\n retcode = -99\n\n if retcode == 0 and item.get('postuninstall_script'):\n retcode = scriptutils.run_embedded_script(\n 'postuninstall_script', item)\n if retcode:\n # we won't consider postuninstall script failures as fatal\n # since the item has been uninstalled\n # but admin should be notified\n display.display_warning(\n 'Postuninstall script for %s returned %s'\n % (item['name'], retcode))\n # reset retcode to 0 so we will mark this uninstall\n # as successful\n retcode = 0\n\n # record removal success/failure\n if not 'RemovalResults' in reports.report:\n reports.report['RemovalResults'] = []\n if retcode == 0:\n success_msg = \"Removal of %s: SUCCESSFUL\" % display_name\n munkilog.log(success_msg, \"Install.log\")\n manifestutils.remove_from_selfserve_uninstalls(item['name'])\n else:\n failure_msg = \"Removal of %s: \" % display_name + \\\n \" FAILED with return code: %s\" % retcode\n munkilog.log(failure_msg, \"Install.log\")\n # append failed removal to skipped_removals so dependencies\n # aren't removed yet.\n skipped_removals.append(item)\n removal_result = {\n 'display_name': display_name,\n 'name': item['name'],\n 'status': retcode,\n 'time': NSDate.new(),\n 'unattended': only_unattended,\n }\n reports.report['RemovalResults'].append(removal_result)\n\n return (restart_flag, skipped_removals)\n\n\ndef run(only_unattended=False):\n \"\"\"Runs the install/removal session.\n\n Args:\n only_unattended: Boolean. If True, only do unattended_(un)install pkgs.\n \"\"\"\n # pylint: disable=unused-variable\n # prevent sleep when idle so our installs complete. The Caffeinator class\n # automatically releases the Power Manager assertion when the variable\n # goes out of scope, so we only need to create it and hold a reference\n caffeinator = powermgr.Caffeinator()\n # pylint: enable=unused-variable\n\n managedinstallbase = prefs.pref('ManagedInstallDir')\n installdir = os.path.join(managedinstallbase, 'Cache')\n\n removals_need_restart = installs_need_restart = False\n\n if only_unattended:\n munkilog.log(\"### Beginning unattended installer session ###\")\n else:\n munkilog.log(\"### Beginning managed installer session ###\")\n\n installinfopath = os.path.join(managedinstallbase, 'InstallInfo.plist')\n if os.path.exists(installinfopath):\n try:\n installinfo = FoundationPlist.readPlist(installinfopath)\n except FoundationPlist.NSPropertyListSerializationException:\n display.display_error(\"Invalid %s\" % installinfopath)\n return -1\n\n if prefs.pref('SuppressStopButtonOnInstall'):\n munkistatus.hideStopButton()\n\n if \"removals\" in installinfo:\n # filter list to items that need to be removed\n removallist = [item for item in installinfo['removals']\n if item.get('installed')]\n reports.report['ItemsToRemove'] = removallist\n if removallist:\n if len(removallist) == 1:\n munkistatus.message(\"Removing 1 item...\")\n else:\n munkistatus.message(\"Removing %i items...\" %\n len(removallist))\n munkistatus.detail(\"\")\n # set indeterminate progress bar\n munkistatus.percent(-1)\n munkilog.log(\"Processing removals\")\n (removals_need_restart,\n skipped_removals) = process_removals(\n removallist, only_unattended=only_unattended)\n # if any removals were skipped, record them for later\n installinfo['removals'] = skipped_removals\n\n if \"managed_installs\" in installinfo:\n if not processes.stop_requested():\n # filter list to items that need to be installed\n installlist = [item for item in\n installinfo['managed_installs']\n if item.get('installed') is False]\n reports.report['ItemsToInstall'] = installlist\n if installlist:\n if len(installlist) == 1:\n munkistatus.message(\"Installing 1 item...\")\n else:\n munkistatus.message(\n \"Installing %i items...\" % len(installlist))\n munkistatus.detail(\"\")\n # set indeterminate progress bar\n munkistatus.percent(-1)\n munkilog.log(\"Processing installs\")\n (installs_need_restart, skipped_installs) = (\n install_with_info(installdir, installlist,\n only_unattended=only_unattended))\n # if any installs were skipped record them for later\n installinfo['managed_installs'] = skipped_installs\n\n # update optional_installs with new installation/removal status\n for removal in reports.report.get('RemovalResults', []):\n matching_optional_installs = [\n item for item in installinfo.get('optional_installs', [])\n if item['name'] == removal['name']]\n if len(matching_optional_installs) == 1:\n if removal['status'] != 0:\n matching_optional_installs[0]['removal_error'] = True\n matching_optional_installs[0]['will_be_removed'] = False\n else:\n matching_optional_installs[0]['installed'] = False\n matching_optional_installs[0]['will_be_removed'] = False\n\n for install_item in reports.report.get('InstallResults', []):\n matching_optional_installs = [\n item for item in installinfo.get('optional_installs', [])\n if item['name'] == install_item['name']\n and item['version_to_install'] == install_item['version']]\n if len(matching_optional_installs) == 1:\n if install_item['status'] != 0:\n matching_optional_installs[0]['install_error'] = True\n matching_optional_installs[0]['will_be_installed'] = False\n elif matching_optional_installs[0].get('OnDemand'):\n matching_optional_installs[0]['installed'] = False\n matching_optional_installs[0]['needs_update'] = False\n matching_optional_installs[0]['will_be_installed'] = False\n else:\n matching_optional_installs[0]['installed'] = True\n matching_optional_installs[0]['needs_update'] = False\n matching_optional_installs[0]['will_be_installed'] = False\n\n # write updated installinfo back to disk to reflect current state\n try:\n FoundationPlist.writePlist(installinfo, installinfopath)\n except FoundationPlist.NSPropertyListWriteException:\n # not fatal\n display.display_warning(\n \"Could not write to %s\" % installinfopath)\n\n else:\n if not only_unattended: # no need to log that no unattended pkgs found.\n munkilog.log(\"No %s found.\" % installinfo)\n\n if only_unattended:\n munkilog.log(\"### End unattended installer session ###\")\n else:\n munkilog.log(\"### End managed installer session ###\")\n\n reports.savereport()\n if removals_need_restart or installs_need_restart:\n return constants.POSTACTION_RESTART\n return constants.POSTACTION_NONE\n\n\nif __name__ == '__main__':\n print('This is a library of support tools for the Munki Suite.')\n", "repo_name": "munki/munki", "sub_path": "code/client/munkilib/installer/core.py", "file_name": "core.py", "file_ext": "py", "file_size_in_byte": 33049, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2946, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.path.join", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path", "line_number": 66, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 68, "usage_type": "call"}, {"api_name": "updatecheck.catalogs.split_name_and_version", "line_number": 119, "usage_type": "call"}, {"api_name": "updatecheck.catalogs", "line_number": 119, "usage_type": "name"}, {"api_name": "os.path.basename", "line_number": 146, "usage_type": "call"}, {"api_name": "os.path", "line_number": 146, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 166, "usage_type": "call"}, {"api_name": "os.path", "line_number": 166, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 167, "usage_type": "call"}, {"api_name": "os.path", "line_number": 167, "usage_type": "attribute"}, {"api_name": "datetime.datetime.utcnow", "line_number": 199, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 199, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 253, "usage_type": "call"}, {"api_name": "os.path", "line_number": 253, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 254, "usage_type": "call"}, {"api_name": "os.path", "line_number": 254, "usage_type": "attribute"}, {"api_name": "updatecheck.manifestutils.remove_from_selfserve_installs", "line_number": 333, "usage_type": "call"}, {"api_name": "updatecheck.manifestutils", "line_number": 333, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 358, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 358, "usage_type": "attribute"}, {"api_name": "Foundation.NSDate.new", "line_number": 368, "usage_type": "call"}, {"api_name": "Foundation.NSDate", "line_number": 368, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 412, "usage_type": "call"}, {"api_name": "os.path", "line_number": 412, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 413, "usage_type": "call"}, {"api_name": "os.path", "line_number": 413, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 414, "usage_type": "call"}, {"api_name": "os.path", "line_number": 414, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 415, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 418, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 420, "usage_type": "call"}, {"api_name": "os.path", "line_number": 420, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 421, "usage_type": "call"}, {"api_name": "os.path", "line_number": 421, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 422, "usage_type": "call"}, {"api_name": "updatecheck.catalogs.split_name_and_version", "line_number": 448, "usage_type": "call"}, {"api_name": "updatecheck.catalogs", "line_number": 448, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 525, "usage_type": "call"}, {"api_name": "os.path", "line_number": 525, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 527, "usage_type": "call"}, {"api_name": "os.path", "line_number": 527, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 554, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 582, "usage_type": "call"}, {"api_name": "os.path", "line_number": 582, "usage_type": "attribute"}, {"api_name": "os.access", "line_number": 583, "usage_type": "call"}, {"api_name": "os.X_OK", "line_number": 583, "usage_type": "attribute"}, {"api_name": "updatecheck.manifestutils.remove_from_selfserve_uninstalls", "line_number": 615, "usage_type": "call"}, {"api_name": "updatecheck.manifestutils", "line_number": 615, "usage_type": "name"}, {"api_name": "Foundation.NSDate.new", "line_number": 627, "usage_type": "call"}, {"api_name": "Foundation.NSDate", "line_number": 627, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 649, "usage_type": "call"}, {"api_name": "os.path", "line_number": 649, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 658, "usage_type": "call"}, {"api_name": "os.path", "line_number": 658, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 659, "usage_type": "call"}, {"api_name": "os.path", "line_number": 659, "usage_type": "attribute"}]} +{"seq_id": "39546086145", "text": "import itertools\nfrom math import gamma\n\nimport numpy as np\nimport pytest\nfrom pytest import raises\n\nfrom mathematics.number_theory.combinatorics import *\nfrom mathematics.tools.decorators import timeout\n\nfrom .. import name_func\n\n\nclass TestRiffleShuffles:\n def test_riffle_shuffles(self):\n \"\"\"\n\t\thttps://en.wikipedia.org/wiki/Shuffle_algebra#Shuffle_product\n\t\t\"\"\"\n\n def expected_nof_shuffles(m, n):\n return int(gamma(len(m) + len(n) + 1) / (gamma(len(m) + 1) * gamma(len(n) + 1)))\n\n m = \"ab\"\n n = \"xy\"\n m_w_n = riffle_shuffles(m, n)\n assert \"abxy\" in m_w_n\n assert \"axby\" in m_w_n\n assert \"xaby\" in m_w_n\n assert \"axyb\" in m_w_n\n assert \"xayb\" in m_w_n\n assert \"xyab\" in m_w_n\n assert len(m_w_n) == expected_nof_shuffles(m, n)\n m = \"012\"\n n = \"34\"\n m_w_n = riffle_shuffles(m, n)\n assert len(m_w_n) == expected_nof_shuffles(m, n)\n\n\nclass TestPermutation:\n @timeout(handler=lambda: pytest.skip(\"timeout\"), seconds=1)\n def test_equivalence_of_parity_methods(self):\n permutation = np.random.permutation(range(0, 10))\n parities = [parity(permutation, method) for method in list(ParityMethod)]\n assert len(set(parities)) == 1\n\n @pytest.mark.parametrize(\n \"method,permutation,desired\",\n [\n (method, permutation, desired)\n for method in list(ParityMethod)\n for permutation, desired in zip([range(0, 10), [3, 4, 5, 2, 1]], [1, -1])\n ],\n ids=name_func,\n )\n @timeout(handler=lambda: pytest.skip(\"timeout\"), seconds=1)\n def test_parity_methods(self, method, permutation, desired):\n assert parity(permutation, method) == desired\n\n @pytest.mark.parametrize(\n \"permutation,desired\",\n [\n ([1, 2, 3, 4], [0, 0, 0, 0]),\n ([2, 1, 3, 4], [1, 0, 0, 0]),\n ([1, 3, 2, 4], [0, 1, 0, 0]),\n ([3, 1, 2, 4], [1, 1, 0, 0]),\n ([2, 3, 1, 4], [2, 0, 0, 0]),\n ([3, 2, 1, 4], [2, 1, 0, 0]),\n ([1, 2, 4, 3], [0, 0, 1, 0]),\n ([2, 1, 4, 3], [1, 0, 1, 0]),\n ([1, 4, 2, 3], [0, 1, 1, 0]),\n ([4, 1, 2, 3], [1, 1, 1, 0]),\n ([2, 4, 1, 3], [2, 0, 1, 0]),\n ([4, 2, 1, 3], [2, 1, 1, 0]),\n ([1, 3, 4, 2], [0, 2, 0, 0]),\n ([3, 1, 4, 2], [1, 2, 0, 0]),\n ([1, 4, 3, 2], [0, 2, 1, 0]),\n ([4, 1, 3, 2], [1, 2, 1, 0]),\n ([3, 4, 1, 2], [2, 2, 0, 0]),\n ([4, 3, 1, 2], [2, 2, 1, 0]),\n ([2, 3, 4, 1], [3, 0, 0, 0]),\n ([3, 2, 4, 1], [3, 1, 0, 0]),\n ([2, 4, 3, 1], [3, 0, 1, 0]),\n ([4, 2, 3, 1], [3, 1, 1, 0]),\n ([3, 4, 2, 1], [3, 2, 0, 0]),\n ([4, 3, 2, 1], [3, 2, 1, 0]),\n ],\n ids=name_func,\n ) # https://en.wikipedia.org/wiki/Inversion_(discrete_mathematics)\n @timeout(handler=lambda: pytest.skip(\"timeout\"), seconds=1)\n def test_inversion_vector(self, permutation, desired):\n assert inversion_vector(permutation) == desired\n\n @pytest.mark.parametrize(\n \"permutation,desired\",\n [\n ([1, 2, 3, 4], [0, 0, 0, 0]),\n ([2, 1, 3, 4], [0, 1, 0, 0]),\n ([1, 3, 2, 4], [0, 0, 1, 0]),\n ([3, 1, 2, 4], [0, 1, 1, 0]),\n ([2, 3, 1, 4], [0, 0, 2, 0]),\n ([3, 2, 1, 4], [0, 1, 2, 0]),\n ([1, 2, 4, 3], [0, 0, 0, 1]),\n ([2, 1, 4, 3], [0, 1, 0, 1]),\n ([1, 4, 2, 3], [0, 0, 1, 1]),\n ([4, 1, 2, 3], [0, 1, 1, 1]),\n ([2, 4, 1, 3], [0, 0, 2, 1]),\n ([4, 2, 1, 3], [0, 1, 2, 1]),\n ([1, 3, 4, 2], [0, 0, 0, 2]),\n ([3, 1, 4, 2], [0, 1, 0, 2]),\n ([1, 4, 3, 2], [0, 0, 1, 2]),\n ([4, 1, 3, 2], [0, 1, 1, 2]),\n ([3, 4, 1, 2], [0, 0, 2, 2]),\n ([4, 3, 1, 2], [0, 1, 2, 2]),\n ([2, 3, 4, 1], [0, 0, 0, 3]),\n ([3, 2, 4, 1], [0, 1, 0, 3]),\n ([2, 4, 3, 1], [0, 0, 1, 3]),\n ([4, 2, 3, 1], [0, 1, 1, 3]),\n ([3, 4, 2, 1], [0, 0, 2, 3]),\n ([4, 3, 2, 1], [0, 1, 2, 3]),\n ],\n ids=name_func,\n ) # https://en.wikipedia.org/wiki/Inversion_(discrete_mathematics)\n @timeout(handler=lambda: pytest.skip(\"timeout\"), seconds=1)\n def test_left_inversion_count(self, permutation, desired):\n assert left_inversion_count(permutation) == desired\n\n @pytest.mark.parametrize(\n \"permutation,desired\",\n [\n ([1, 2, 3, 4], [0, 0, 0, 0]),\n ([2, 1, 3, 4], [1, 0, 0, 0]),\n ([1, 3, 2, 4], [0, 1, 0, 0]),\n ([3, 1, 2, 4], [2, 0, 0, 0]),\n ([2, 3, 1, 4], [1, 1, 0, 0]),\n ([3, 2, 1, 4], [2, 1, 0, 0]),\n ([1, 2, 4, 3], [0, 0, 1, 0]),\n ([2, 1, 4, 3], [1, 0, 1, 0]),\n ([1, 4, 2, 3], [0, 2, 0, 0]),\n ([4, 1, 2, 3], [3, 0, 0, 0]),\n ([2, 4, 1, 3], [1, 2, 0, 0]),\n ([4, 2, 1, 3], [3, 1, 0, 0]),\n ([1, 3, 4, 2], [0, 1, 1, 0]),\n ([3, 1, 4, 2], [2, 0, 1, 0]),\n ([1, 4, 3, 2], [0, 2, 1, 0]),\n ([4, 1, 3, 2], [3, 0, 1, 0]),\n ([3, 4, 1, 2], [2, 2, 0, 0]),\n ([4, 3, 1, 2], [3, 2, 0, 0]),\n ([2, 3, 4, 1], [1, 1, 1, 0]),\n ([3, 2, 4, 1], [2, 1, 1, 0]),\n ([2, 4, 3, 1], [1, 2, 1, 0]),\n ([4, 2, 3, 1], [3, 1, 1, 0]),\n ([3, 4, 2, 1], [2, 2, 1, 0]),\n ([4, 3, 2, 1], [3, 2, 1, 0]),\n ],\n ids=name_func,\n ) # https://en.wikipedia.org/wiki/Inversion_(discrete_mathematics)\n @timeout(handler=lambda: pytest.skip(\"timeout\"), seconds=1)\n def test_right_inversion_count(self, permutation, desired):\n assert right_inversion_count(permutation) == desired\n\n @pytest.mark.parametrize(\n \"method,not_permutation\",\n itertools.product(\n [permutation_to_adjacent_transpositions, permutation_to_cycles, permutation_to_transpositions,],\n [[7, 13, 4, 5]],\n ),\n ids=name_func,\n )\n @timeout(handler=lambda: pytest.skip(\"timeout\"), seconds=1)\n def test_nontcontiguous_sequence_raises_exception(self, method, not_permutation):\n with raises(IndexError):\n method(not_permutation)\n\n @pytest.mark.parametrize(\n \"permutation, desired\",\n [\n ([2, 5, 4, 3, 1], {(1, 2, 5), (3, 4)}),\n ([4, 2, 7, 6, 5, 8, 1, 3], {(1, 4, 6, 8, 3, 7), (2,), (5,)}),\n ([4, 5, 7, 6, 8, 2, 1, 3], {(1, 4, 6, 2, 5, 8, 3, 7)}),\n ],\n ids=name_func,\n )\n @timeout(handler=lambda: pytest.skip(\"timeout\"), seconds=1)\n def test_permutation_to_cycle(self, permutation, desired):\n # assumes canonical order with min first is used\n actual = permutation_to_cycles(permutation)\n assert actual == desired\n\n @pytest.mark.parametrize(\n \"permutation,desired\",\n [\n ([1, 2, 3, 4], set()),\n ([2, 1, 3, 4], {(1, 2)}),\n ([3, 2, 1, 4], {(1, 3)}),\n ([4, 2, 3, 1], {(1, 4)}),\n ([1, 3, 2, 4], {(2, 3)}),\n ([1, 4, 3, 2], {(2, 4)}),\n ([1, 2, 4, 3], {(3, 4)}),\n ([2, 1, 4, 3], {(1, 2), (3, 4)}),\n ],\n ids=name_func,\n )\n @timeout(handler=lambda: pytest.skip(\"timeout\"), seconds=1)\n def test_permutation_to_transpositions(self, permutation, desired):\n # assumes canonical order with min first is used\n actual = permutation_to_transpositions(permutation)\n assert actual == desired\n", "repo_name": "emilberwald/mathematics", "sub_path": "tests/number_theory/test_combinatorics.py", "file_name": "test_combinatorics.py", "file_ext": "py", "file_size_in_byte": 7636, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "math.gamma", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.random.permutation", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 42, "usage_type": "attribute"}, {"api_name": "mathematics.tools.decorators.timeout", "line_number": 40, "usage_type": "call"}, {"api_name": "pytest.skip", "line_number": 40, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 46, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 46, "usage_type": "attribute"}, {"api_name": "mathematics.tools.decorators.timeout", "line_number": 55, "usage_type": "call"}, {"api_name": "pytest.skip", "line_number": 55, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 59, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 59, "usage_type": "attribute"}, {"api_name": "mathematics.tools.decorators.timeout", "line_number": 89, "usage_type": "call"}, {"api_name": "pytest.skip", "line_number": 89, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 93, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 93, "usage_type": "attribute"}, {"api_name": "mathematics.tools.decorators.timeout", "line_number": 123, "usage_type": "call"}, {"api_name": "pytest.skip", "line_number": 123, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 127, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 127, "usage_type": "attribute"}, {"api_name": "mathematics.tools.decorators.timeout", "line_number": 157, "usage_type": "call"}, {"api_name": "pytest.skip", "line_number": 157, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 171, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 161, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 161, "usage_type": "attribute"}, {"api_name": "itertools.product", "line_number": 163, "usage_type": "call"}, {"api_name": "mathematics.tools.decorators.timeout", "line_number": 169, "usage_type": "call"}, {"api_name": "pytest.skip", "line_number": 169, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 174, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 174, "usage_type": "attribute"}, {"api_name": "mathematics.tools.decorators.timeout", "line_number": 183, "usage_type": "call"}, {"api_name": "pytest.skip", "line_number": 183, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 189, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 189, "usage_type": "attribute"}, {"api_name": "mathematics.tools.decorators.timeout", "line_number": 203, "usage_type": "call"}, {"api_name": "pytest.skip", "line_number": 203, "usage_type": "call"}]} +{"seq_id": "70980970952", "text": "import multiprocessing\nfrom concurrent import futures\n\n_processes = multiprocessing.cpu_count()\n\ndef multiprocess(func, iter_args,processes=_processes):\n with futures.ProcessPoolExecutor(max_workers=processes) as ex:\n try:\n results = ex.map(func, iter_args)\n except futures.process.BrokenProcessPool as e:\n print('could not start new tasks: {}'.format(e))\n else:\n return results\n\n\ndef thread(func, iter_args,processes=_processes*2):\n with futures.ThreadPoolExecutor(max_workers=processes) as ex:\n results = ex.map(func, iter_args)\n return results\n\n\n\n\"\"\"\nfrom multiprocessing.dummy import Pool as ThreadPool\n\ndef multi(func, iter_args,processes=_processes):\n pool = multiprocessing.Pool(processes)\n results = pool.map(func, iter_args)\n pool.close()\n pool.join()\n return results\n\ndef thread(func, iter_args,processes=_processes*2):\n pool = ThreadPool(processes)\n results = pool.map(func, iter_args)\n pool.close()\n pool.join()\n return results\n\"\"\"\n\n", "repo_name": "guzdy/UrbanDictSpider", "sub_path": "multiprocess.py", "file_name": "multiprocess.py", "file_ext": "py", "file_size_in_byte": 1049, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "multiprocessing.cpu_count", "line_number": 4, "usage_type": "call"}, {"api_name": "concurrent.futures.ProcessPoolExecutor", "line_number": 7, "usage_type": "call"}, {"api_name": "concurrent.futures", "line_number": 7, "usage_type": "name"}, {"api_name": "concurrent.futures.process", "line_number": 10, "usage_type": "attribute"}, {"api_name": "concurrent.futures", "line_number": 10, "usage_type": "name"}, {"api_name": "concurrent.futures.ThreadPoolExecutor", "line_number": 17, "usage_type": "call"}, {"api_name": "concurrent.futures", "line_number": 17, "usage_type": "name"}]} +{"seq_id": "33978684605", "text": "import inspect\nimport threading\nfrom concurrent.futures import Future\nfrom typing import Callable, Generic, Type, TypeVar, _GenericAlias\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\n\ndef _map_future(fut: Future, func: Callable[[T], S]) -> \"RPCFuture[S]\":\n new_fut: RPCFuture[S] = RPCFuture()\n\n def _do_map(f):\n try:\n res = func(f.result())\n new_fut.set_result(res)\n except Exception as e:\n new_fut.set_exception(e)\n\n fut.add_done_callback(_do_map)\n return new_fut\n\n\nclass _OneShotConnection:\n \"\"\"\n Copies state from one completed future to another\n Used to propagate results and cancelations\n \"\"\"\n\n __slots__ = (\"_fired\", \"_lock\", \"_fut1\", \"_fut2\")\n\n def __init__(self, fut1: Future, fut2: Future) -> None:\n self._fired = False\n self._lock = threading.Lock()\n\n self._fut1 = fut1\n self._fut1.add_done_callback(self._handle_fut1_completion)\n\n self._fut2 = fut2\n self._fut2.add_done_callback(self._handle_fut2_completion)\n\n def _copy(self, src: Future, dst: Future) -> None:\n gotit = self._lock.acquire(blocking=False)\n if not gotit:\n return\n\n try:\n if self._fired:\n return\n\n self._fired = True\n\n if src.cancelled():\n dst.cancel()\n return\n\n try:\n dst.set_result(src.result())\n except Exception as e:\n dst.set_exception(e)\n finally:\n self._lock.release()\n\n def _handle_fut1_completion(self, fut):\n assert fut == self._fut1\n self._copy(fut, self._fut2)\n\n def _handle_fut2_completion(self, fut):\n assert fut == self._fut2\n self._copy(fut, self._fut1)\n\n\nclass RPCFuture(Future, Generic[T]):\n def __init__(self, timeout=None):\n self._timeout = timeout\n super().__init__()\n\n def attach(self, future):\n _OneShotConnection(self, future)\n\n def result(self, timeout=None):\n return super().result(timeout or self._timeout)\n\n def exception(self, timeout=None):\n return super().exception(timeout or self._timeout)\n\n def map(self, func: Callable[[T], S]) -> \"RPCFuture[S]\":\n \"\"\"\n Apply function and return new future\n Note: Function should return plain object not wrapped in future\n\n >>> fut = RPCFuture()\n >>> new_fut = fut.map(lambda val: val + 1)\n >>> fut.set_result(12)\n >>> new_fut.result()\n 13\n\n >>> fut = RPCFuture()\n >>> new_fut = fut.map(lambda val: val / 0)\n >>> fut.set_result(12)\n >>> new_fut.result()\n Traceback (most recent call last):\n ...\n ZeroDivisionError: division by zero\n \"\"\"\n return _map_future(self, func)\n\n\ndef _checkgenericfut(type_: Type) -> bool:\n # XXX: py3.7 regression isclass returns False on parametrized generics\n if not isinstance(type_, (type, _GenericAlias)):\n return False\n\n origin = getattr(type_, \"__origin__\", None)\n\n return origin and issubclass(origin, RPCFuture)\n\n\ndef isfutureret(func: Callable):\n sig = inspect.signature(func)\n ret = sig.return_annotation\n\n return (inspect.isclass(ret) and issubclass(sig.return_annotation, Future)) or _checkgenericfut(ret)\n", "repo_name": "ilastik/tiktorch", "sub_path": "tiktorch/rpc/types.py", "file_name": "types.py", "file_ext": "py", "file_size_in_byte": 3315, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 11, "dataset": "github-code", "pt": "27", "api": [{"api_name": "typing.TypeVar", "line_number": 6, "usage_type": "call"}, {"api_name": "typing.TypeVar", "line_number": 7, "usage_type": "call"}, {"api_name": "concurrent.futures.Future", "line_number": 10, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 10, "usage_type": "name"}, {"api_name": "concurrent.futures.Future", "line_number": 32, "usage_type": "name"}, {"api_name": "threading.Lock", "line_number": 34, "usage_type": "call"}, {"api_name": "concurrent.futures.Future", "line_number": 42, "usage_type": "name"}, {"api_name": "concurrent.futures.Future", "line_number": 73, "usage_type": "name"}, {"api_name": "typing.Generic", "line_number": 73, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 87, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 109, "usage_type": "name"}, {"api_name": "typing._GenericAlias", "line_number": 111, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 119, "usage_type": "name"}, {"api_name": "inspect.signature", "line_number": 120, "usage_type": "call"}, {"api_name": "inspect.isclass", "line_number": 123, "usage_type": "call"}, {"api_name": "concurrent.futures.Future", "line_number": 123, "usage_type": "argument"}]} +{"seq_id": "22596441695", "text": "import sys\nimport json\nimport collections\n\n# Change this it True if you want to format it to compare versions.\npretty = False\n\nwith open(sys.argv[1], \"r\") as f:\n config = json.load(f)\n\nprint(config.keys())\n\nconfig[\"middlewares\"].sort(key=lambda x: x[\"identifier\"])\nconfig[\"drivers\"].sort(key=lambda x: x[\"identifier\"])\n\nnew_root = collections.OrderedDict()\nfor key in ['jsonForm', 'formatVersion', 'board', 'identifier', 'name', 'details', 'application', 'middlewares', 'drivers', 'pads']:\n new_root[key] = config[key]\n\nwith open(sys.argv[1], \"w\") as f:\n indent = 2\n separators = (',', ': ')\n sort_keys = True\n if not pretty:\n indent = None\n separators = (',', ':')\n sort_keys = False\n json.dump(new_root, f,\n indent=indent, separators=separators, sort_keys=sort_keys)\n", "repo_name": "Kevincoooool/esp32s3_openmv_lvgl", "sub_path": "submodule/micropython/lib/asf4/tools/format_json.py", "file_name": "format_json.py", "file_ext": "py", "file_size_in_byte": 824, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 124, "dataset": "github-code", "pt": "27", "api": [{"api_name": "sys.argv", "line_number": 8, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 9, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 16, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 20, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 28, "usage_type": "call"}]} +{"seq_id": "26717072551", "text": "import asyncio\nimport time \n\n\ndef background(f):\n from functools import wraps\n @wraps(f)\n def wrapped(*args, **kwargs):\n loop = asyncio.get_event_loop()\n if callable(f):\n return loop.run_in_executor(None, f, *args, **kwargs)\n else:\n raise TypeError('Task must be a callable') \n return wrapped\n\n@background\ndef testDontWait():\n time.sleep(4)\n print(3)\n\nprint(1)\ntestDontWait()\nprint(2)\ntime.sleep(5)\n", "repo_name": "NPressInc/TinyWeb", "sub_path": "src/asyncIoTest.py", "file_name": "asyncIoTest.py", "file_ext": "py", "file_size_in_byte": 463, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "asyncio.get_event_loop", "line_number": 9, "usage_type": "call"}, {"api_name": "functools.wraps", "line_number": 7, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 18, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 24, "usage_type": "call"}]} +{"seq_id": "40283181013", "text": "from django.core.management import BaseCommand\nfrom django.db import connection\n\nfrom ngos.models import NGO\nfrom read.create_table_as import create_table_as\nfrom read_sessions.models import ReadSession\nfrom django.db.models import F, CharField\nfrom django.db.models import Value\nfrom django.db.models.functions import Concat\n\n\ndef _superset_init():\n with connection.cursor() as cursor:\n ngos = NGO.objects.all().values_list(\"name\", flat=True)\n\n # /Drop temporary tables in case the process got cut off before\n for ngo in ngos:\n drop_table_str = \"DROP TABLE IF EXISTS %s_sessions_feedback_master_details\" % ngo\n cursor.execute(\n drop_table_str\n )\n # Create the new table from the summary query\n ngo_filter = {\n 'readsessionclassroom__classroom__school__ngo__name': ngo,\n 'readsessionclassroom__classroom__school__ngo__is_active': True\n }\n feedback_sessions = ReadSession.objects.filter(**ngo_filter).annotate(\n session_id=F('id'),\n session_type=F('type'),\n session_academic_year=F('academic_year__name'),\n session_start_date_time=F('start_date_time'),\n session_end_date_time=F('end_date_time'),\n session_is_evaluated=F('is_evaluated'),\n session_is_verified=F('is_verified'),\n session_is_cancelled=F('is_cancelled'),\n session_level=F('studentfeedback__level__en_in'),\n session_feedback_comments=F('studentfeedback__comments'),\n school_name=F('readsessionclassroom__classroom__school__name'),\n school_ngo=F('readsessionclassroom__classroom__school__ngo__name'),\n school_category=F('readsessionclassroom__classroom__school__school_category__name'),\n school_type=F('readsessionclassroom__classroom__school__school_type__name'),\n school_medium=F('readsessionclassroom__classroom__school__medium__name'),\n school_is_active=F('readsessionclassroom__classroom__school__is_active'),\n classroom=Concat('readsessionclassroom__classroom__school__name',\n Value(' '),\n 'readsessionclassroom__classroom__standard',\n Value(' '),\n 'readsessionclassroom__classroom__division', output_field=CharField()),\n student_name=Concat('readsessionclassroom__classroom__classroomacademicyear__student__first_name',\n Value(' '),\n 'readsessionclassroom__classroom__classroomacademicyear__student__last_name'),\n student_gender=F('readsessionclassroom__classroom__classroomacademicyear__student__gender'),\n student_is_dropout=F('readsessionclassroom__classroom__classroomacademicyear__student__is_dropout'),\n student_has_attended_preschool=F(\n 'readsessionclassroom__classroom__classroomacademicyear__student__has_attended_preschool'),\n student_is_active=F('readsessionclassroom__classroom__classroomacademicyear__student__is_active'),\n student_attendance=F('studentfeedback__attendance')\n ).values_list(\n 'session_id',\n 'session_type',\n 'session_academic_year',\n 'session_start_date_time',\n 'session_end_date_time',\n 'session_is_evaluated',\n 'session_is_verified',\n 'session_is_cancelled',\n 'session_level',\n 'session_feedback_comments',\n 'school_name',\n 'school_ngo',\n 'school_category',\n 'school_type',\n 'school_medium',\n 'school_is_active',\n 'classroom',\n 'student_name',\n 'student_gender',\n 'student_is_dropout',\n 'student_has_attended_preschool',\n 'student_is_active',\n 'student_attendance'\n )\n create_table_str = \"%s_sessions_feedback_master_details\" % ngo\n create_table_as(\n create_table_str,\n feedback_sessions,\n )\n\n\nclass Command(BaseCommand):\n help = 'Create tables for superset'\n\n def add_arguments(self, parser):\n pass\n\n def handle(self, *args, **options):\n _superset_init()\n print(\"Finished\")\n return\n", "repo_name": "maverick-labs-pune/read-server", "sub_path": "read/users/management/commands/superset.py", "file_name": "superset.py", "file_ext": "py", "file_size_in_byte": 4657, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "django.db.connection.cursor", "line_number": 13, "usage_type": "call"}, {"api_name": "django.db.connection", "line_number": 13, "usage_type": "name"}, {"api_name": "ngos.models", "line_number": 14, "usage_type": "name"}, {"api_name": "ngos.models.NGO.objects.all", "line_number": 14, "usage_type": "call"}, {"api_name": "ngos.models.NGO.objects", "line_number": 14, "usage_type": "attribute"}, {"api_name": "ngos.models.NGO", "line_number": 14, "usage_type": "name"}, {"api_name": "ngos.models", "line_number": 17, "usage_type": "name"}, {"api_name": "read_sessions.models.ReadSession.objects.filter", "line_number": 27, "usage_type": "call"}, {"api_name": "read_sessions.models.ReadSession.objects", "line_number": 27, "usage_type": "attribute"}, {"api_name": "read_sessions.models.ReadSession", "line_number": 27, "usage_type": "name"}, {"api_name": "django.db.models.F", "line_number": 28, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 29, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 30, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 31, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 32, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 33, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 34, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 35, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 36, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 37, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 38, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 39, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 40, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 41, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 42, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 43, "usage_type": "call"}, {"api_name": "django.db.models.functions.Concat", "line_number": 44, "usage_type": "call"}, {"api_name": "django.db.models.Value", "line_number": 45, "usage_type": "call"}, {"api_name": "django.db.models.Value", "line_number": 47, "usage_type": "call"}, {"api_name": "django.db.models.CharField", "line_number": 48, "usage_type": "call"}, {"api_name": "django.db.models.functions.Concat", "line_number": 49, "usage_type": "call"}, {"api_name": "django.db.models.Value", "line_number": 50, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 52, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 53, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 54, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 56, "usage_type": "call"}, {"api_name": "django.db.models.F", "line_number": 57, "usage_type": "call"}, {"api_name": "read.create_table_as.create_table_as", "line_number": 84, "usage_type": "call"}, {"api_name": "django.core.management.BaseCommand", "line_number": 90, "usage_type": "name"}]} +{"seq_id": "577228989", "text": "\nimport unittest\nfrom unittest import mock\n\nfrom rds_cp import rds_cp\nfrom .data import describe_response\n\n\nclass TestCp(unittest.TestCase):\n \"\"\"\n Test the main functionality of rds_cp in a very mocky way.\n\n \"\"\"\n\n class Client(mock.MagicMock):\n describe_db_instances = mock.MagicMock(\n return_value=describe_response.response)\n\n def test_allgood(self):\n \"\"\"\n Test that when everything returns as expected, there're no\n errors.\n\n \"\"\"\n client = self.Client()\n call_to_count = {\n # Listed in order of occurrence\n 'create_db_snapshot': 1,\n 'modify_db_instance': 2,\n 'restore_db_instance_from_db_snapshot': 1,\n 'delete_db_instance': 1,\n 'delete_db_snapshot': 1,\n }\n\n self.assertEquals(\n rds_cp.cp(client, 'src', 'dest', 'db.m3.medium', 'newpass', True),\n 0,\n )\n\n self._check_call_counts(client, call_to_count)\n\n client.restore_db_instance_from_db_snapshot.assert_called_with(\n AvailabilityZone='us-west-1a',\n DBSecurityGroups=[],\n VpcSecurityGroupIds=['sg-bbbbbdd'],\n DBSubnetGroupName='rds',\n DBSnapshotIdentifier='src' + rds_cp.SNAPSHOT_SUFFIX,\n DBInstanceClass='db.m3.medium',\n MultiAZ=False,\n DBInstanceIdentifier='dest',\n )\n\n def test_no_dest(self):\n \"\"\"\n Ensure that when no destination exists, nothing is deleted or renamed.\n\n \"\"\"\n client = self.Client()\n call_to_count = {\n # Listed in order of occurrence\n 'create_db_snapshot': 1,\n 'modify_db_instance': 0,\n 'restore_db_instance_from_db_snapshot': 1,\n 'delete_db_instance': 0,\n 'delete_db_snapshot': 1,\n }\n\n def fake_instance_exists(rds, name):\n return name != 'dest'\n\n with mock.patch('rds_cp.rds_cp.instance_exists', fake_instance_exists):\n rds_cp.cp(client, 'src', 'dest', 'db.m3.medium', None, True)\n\n self._check_call_counts(client, call_to_count)\n\n def test_failed_snapshot(self):\n \"\"\"\n Ensure that when a snapshot fails, nothing else happens and\n we exit with the right code.\n\n \"\"\"\n call_to_count = {\n # Listed in order of occurrence\n 'create_db_snapshot': 1,\n 'modify_db_instance': 0,\n 'restore_db_instance_from_db_snapshot': 0,\n 'delete_db_instance': 0,\n 'delete_db_snapshot': 0,\n }\n\n class BadClient(self.Client):\n create_db_snapshot = mock.MagicMock(side_effect=Exception)\n\n client = BadClient()\n\n try:\n rds_cp.cp(client, 'src', 'dest', 'db.m3.medium', None, True)\n except SystemExit as e:\n self.assertTrue(isinstance(e, SystemExit))\n self.assertEquals(e.code, rds_cp.SNAPSHOT_FAILED_ERR)\n else:\n assert False, \"Should've raised an exit error.\"\n\n self._check_call_counts(client, call_to_count)\n\n def test_failed_restore(self):\n \"\"\"\n Failure to restore from a snapshot => roll back to the old instance.\n\n \"\"\"\n call_to_count = {\n # Listed in order of occurrence\n 'create_db_snapshot': 1,\n 'modify_db_instance': 2,\n 'restore_db_instance_from_db_snapshot': 1,\n 'delete_db_instance': 0,\n 'delete_db_snapshot': 1,\n }\n\n class BadClient(self.Client):\n restore_db_instance_from_db_snapshot = mock.MagicMock(\n side_effect=Exception)\n\n client = BadClient()\n\n exit_code = rds_cp.cp(\n client, 'src', 'dest', 'db.m3.medium', None, True)\n self.assertEquals(exit_code, rds_cp.DEST_CREATION_ERR)\n\n self._check_call_counts(client, call_to_count)\n\n def test_failed_dest_rename(self):\n \"\"\"\n Failure to rename the existing dest cleans up with proper exit code.\n\n \"\"\"\n call_to_count = {\n # Listed in order of occurrence\n 'create_db_snapshot': 1,\n 'modify_db_instance': 1,\n 'restore_db_instance_from_db_snapshot': 0,\n 'delete_db_instance': 0,\n 'delete_db_snapshot': 1,\n }\n\n class BadClient(self.Client):\n modify_db_instance = mock.MagicMock(side_effect=Exception)\n\n client = BadClient()\n\n exit_code = rds_cp.cp(\n client, 'src', 'dest', 'db.m3.medium', force=True)\n self.assertEquals(exit_code, rds_cp.DEST_RENAME_ERR)\n\n self._check_call_counts(client, call_to_count)\n\n def test_failed_restore_without_rollback(self):\n \"\"\"\n Failure to restore from a snapshot without an existing destination\n means no rollback.\n\n \"\"\"\n call_to_count = {\n # Listed in order of occurrence\n 'create_db_snapshot': 1,\n 'modify_db_instance': 0,\n 'restore_db_instance_from_db_snapshot': 1,\n 'delete_db_instance': 0,\n 'delete_db_snapshot': 1,\n }\n\n class BadClient(self.Client):\n restore_db_instance_from_db_snapshot = mock.MagicMock(\n side_effect=Exception)\n\n client = BadClient()\n\n def fake_instance_exists(rds, name):\n return name != 'dest'\n\n with mock.patch('rds_cp.rds_cp.instance_exists', fake_instance_exists):\n exit_code = rds_cp.cp(\n client, 'src', 'dest', 'db.m3.medium', force=True)\n\n self.assertEquals(exit_code, rds_cp.DEST_CREATION_ERR)\n\n self._check_call_counts(client, call_to_count)\n\n def test_cant_describe(self):\n \"\"\"\n Test that we exit early when we can't describe SRC.\n\n \"\"\"\n call_to_count = {\n # Listed in order of occurrence\n 'create_db_snapshot': 0,\n 'modify_db_instance': 0,\n 'restore_db_instance_from_db_snapshot': 0,\n 'delete_db_instance': 0,\n 'delete_db_snapshot': 0,\n }\n\n class BadClient(self.Client):\n describe_db_instances = mock.MagicMock(side_effect=Exception)\n\n client = BadClient()\n exit_code = rds_cp.cp(client, 'src', 'dest', 'db.m3.medium')\n\n self.assertEquals(exit_code, rds_cp.SRC_EXISTS_ERR)\n self._check_call_counts(client, call_to_count)\n\n def test_cant_change_password(self):\n \"\"\"\n Test that we rollback to original dest if we can't change password.\n\n \"\"\"\n client = self.Client()\n call_to_count = {\n 'create_db_snapshot': 1,\n\n # one for initial rename, one for dest rollback\n 'modify_db_instance': 2,\n\n 'restore_db_instance_from_db_snapshot': 1,\n 'delete_db_instance': 1,\n 'delete_db_snapshot': 1,\n }\n\n def fake_change_pass(rds, name, new_pass):\n return name != 'dest'\n\n with mock.patch('rds_cp.rds_cp.change_password', fake_change_pass):\n exit_code = rds_cp.cp(\n client, 'src', 'dest', 'db.m3.medium', 'pass', True)\n\n self.assertEquals(exit_code, rds_cp.DEST_CREATION_ERR)\n\n self._check_call_counts(client, call_to_count)\n\n def _check_call_counts(self,\n client: mock.MagicMock,\n call_to_count: {str: int}):\n \"\"\"\n Ensure that the client was called according to the number of calls\n listed for each method name.\n\n \"\"\"\n for method_name, exp_call_count in call_to_count.items():\n print(getattr(client, method_name))\n self.assertEquals(\n getattr(client, method_name).call_count,\n exp_call_count,\n \"%r should have been called %d times.\" %\n (method_name, exp_call_count)\n )\n\n\nclass TestSrcParams(unittest.TestCase):\n\n def test_from_describe_dict(self):\n src_params = rds_cp.SrcParams.from_describe_dict(\n describe_response.response)\n\n self.assertEquals(\n src_params.AvailabilityZone,\n 'us-west-1a',\n )\n\n self.assertEquals(\n src_params.DBSubnetGroupName,\n 'rds'\n )\n\n self.assertEquals(\n src_params.VpcSecurityGroupIds,\n ['sg-bbbbbdd'],\n )\n\n self.assertEquals(\n src_params.DBSecurityGroups,\n []\n )\n", "repo_name": "counsyl/rds_cp", "sub_path": "tests/tests.py", "file_name": "tests.py", "file_ext": "py", "file_size_in_byte": 8530, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "27", "api": [{"api_name": "unittest.TestCase", "line_number": 9, "usage_type": "attribute"}, {"api_name": "unittest.mock.MagicMock", "line_number": 15, "usage_type": "attribute"}, {"api_name": "unittest.mock", "line_number": 15, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 16, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 16, "usage_type": "name"}, {"api_name": "data.describe_response.response", "line_number": 17, "usage_type": "attribute"}, {"api_name": "data.describe_response", "line_number": 17, "usage_type": "name"}, {"api_name": "rds_cp.rds_cp.cp", "line_number": 36, "usage_type": "call"}, {"api_name": "rds_cp.rds_cp", "line_number": 36, "usage_type": "name"}, {"api_name": "rds_cp.rds_cp.SNAPSHOT_SUFFIX", "line_number": 47, "usage_type": "attribute"}, {"api_name": "rds_cp.rds_cp", "line_number": 47, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 71, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 71, "usage_type": "name"}, {"api_name": "rds_cp.rds_cp.cp", "line_number": 72, "usage_type": "call"}, {"api_name": "rds_cp.rds_cp", "line_number": 72, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 92, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 92, "usage_type": "name"}, {"api_name": "rds_cp.rds_cp.cp", "line_number": 97, "usage_type": "call"}, {"api_name": "rds_cp.rds_cp", "line_number": 97, "usage_type": "name"}, {"api_name": "rds_cp.rds_cp.SNAPSHOT_FAILED_ERR", "line_number": 100, "usage_type": "attribute"}, {"api_name": "rds_cp.rds_cp", "line_number": 100, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 121, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 121, "usage_type": "name"}, {"api_name": "rds_cp.rds_cp.cp", "line_number": 126, "usage_type": "call"}, {"api_name": "rds_cp.rds_cp", "line_number": 126, "usage_type": "name"}, {"api_name": "rds_cp.rds_cp.DEST_CREATION_ERR", "line_number": 128, "usage_type": "attribute"}, {"api_name": "rds_cp.rds_cp", "line_number": 128, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 147, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 147, "usage_type": "name"}, {"api_name": "rds_cp.rds_cp.cp", "line_number": 151, "usage_type": "call"}, {"api_name": "rds_cp.rds_cp", "line_number": 151, "usage_type": "name"}, {"api_name": "rds_cp.rds_cp.DEST_RENAME_ERR", "line_number": 153, "usage_type": "attribute"}, {"api_name": "rds_cp.rds_cp", "line_number": 153, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 173, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 173, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 181, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 181, "usage_type": "name"}, {"api_name": "rds_cp.rds_cp.cp", "line_number": 182, "usage_type": "call"}, {"api_name": "rds_cp.rds_cp", "line_number": 182, "usage_type": "name"}, {"api_name": "rds_cp.rds_cp.DEST_CREATION_ERR", "line_number": 185, "usage_type": "attribute"}, {"api_name": "rds_cp.rds_cp", "line_number": 185, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 204, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 204, "usage_type": "name"}, {"api_name": "rds_cp.rds_cp.cp", "line_number": 207, "usage_type": "call"}, {"api_name": "rds_cp.rds_cp", "line_number": 207, "usage_type": "name"}, {"api_name": "rds_cp.rds_cp.SRC_EXISTS_ERR", "line_number": 209, "usage_type": "attribute"}, {"api_name": "rds_cp.rds_cp", "line_number": 209, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 232, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 232, "usage_type": "name"}, {"api_name": "rds_cp.rds_cp.cp", "line_number": 233, "usage_type": "call"}, {"api_name": "rds_cp.rds_cp", "line_number": 233, "usage_type": "name"}, {"api_name": "rds_cp.rds_cp.DEST_CREATION_ERR", "line_number": 236, "usage_type": "attribute"}, {"api_name": "rds_cp.rds_cp", "line_number": 236, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 241, "usage_type": "attribute"}, {"api_name": "unittest.mock", "line_number": 241, "usage_type": "name"}, {"api_name": "unittest.TestCase", "line_number": 258, "usage_type": "attribute"}, {"api_name": "rds_cp.rds_cp.SrcParams.from_describe_dict", "line_number": 261, "usage_type": "call"}, {"api_name": "rds_cp.rds_cp.SrcParams", "line_number": 261, "usage_type": "attribute"}, {"api_name": "rds_cp.rds_cp", "line_number": 261, "usage_type": "name"}, {"api_name": "data.describe_response.response", "line_number": 262, "usage_type": "attribute"}, {"api_name": "data.describe_response", "line_number": 262, "usage_type": "name"}]} +{"seq_id": "25270172660", "text": "from flask import Flask, render_template, jsonify\nfrom flask_cors import CORS\n\n# configuration\nDEBUG = True\n\n# instantiate the app\napp = Flask(__name__, static_folder=\"./dist/static\", template_folder=\">/dist\")\napp.config.from_object(__name__)\n\n# enable CORS\nCORS(app, resources={r'/*': {'origins': '*'}})\n\n@app.route('/', defaults={'path': ''})\n@app.route('/')\ndef catch_all():\n return render_template(\"index.html\")\n\n\n@app.route('/api/random')\ndef random_number():\n print(\"YOU GOT HERE\")\n response = {\n 'data': \"HELLO!\"\n }\n return jsonify(response)\n\nif __name__ == '__main__':\n app.run()", "repo_name": "nancytaen/flask-vue", "sub_path": "server/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 623, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "flask.Flask", "line_number": 8, "usage_type": "call"}, {"api_name": "flask_cors.CORS", "line_number": 12, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 17, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 26, "usage_type": "call"}]} +{"seq_id": "13837373980", "text": "import os\nimport glob\nfrom setuptools import setup, find_packages\n\n\nwith open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:\n README = readme.read()\n\n\n# allow setup.py to be run from any path\nos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n\n\nsetup(\n name='nji',\n version='0.1.4',\n packages=find_packages('src'),\n package_dir={'': 'src'},\n package_data={'nji': ['templates/*']},\n scripts=glob.glob('scripts/*'),\n install_requires=['jinja2'],\n include_package_data=True,\n license='BSD License',\n description='Native Java Interface code generator.',\n long_description=README,\n author='greenbender',\n author_email='byron.platt@gmail.com',\n url='https://github.com/greenbender/libnji',\n zip_safe=False,\n classifiers=[\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n ],\n)\n", "repo_name": "greenbender/libnji", "sub_path": "tools/njic/setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 1053, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "os.path.join", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 6, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path.normpath", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 11, "usage_type": "call"}, {"api_name": "os.pardir", "line_number": 11, "usage_type": "attribute"}, {"api_name": "setuptools.setup", "line_number": 14, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 17, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 20, "usage_type": "call"}]} +{"seq_id": "9373577220", "text": "# Enter your code here. Read input from STDIN. Print output to STDOUT\nvar = list(map(int, input().split()))\n#print(var)\nn = var[0]\nq = var[1]\n\nnodes = []\nsets = []\nfor i in range(n-1): \n nodes.append(list(map(int, input().split())))\n#print(nodes)\n\nfor i in range(q): \n a = int(input())\n b = list(map(int, input().split()))\n sets.append(b)\n'''\nprint(\"q: \", q)\nprint(\"n: \", n)\nprint(\"nodes: \", nodes)\nprint(\"sets: \", sets)\n'''\n#DEFINITION OF NODE\nclass Node: \n def __init__(self, data): \n self.data = data\n self.link = []\n\n def appender(self, link): \n self.link.append(link)\nlst = []\n\n#BELOW IS MAKING TREE BASED ON THE ENTERED INPUTS\nfor nodeINPUT in nodes: \n if len(lst) == 0: \n node1 = Node(nodeINPUT[0])\n node2 = Node(nodeINPUT[1])\n lst.append(node1)\n lst.append(node2)\n else: \n for i in range(len(lst)): \n if lst[i].data == nodeINPUT[0]: \n node1 =lst[i]\n break\n else: \n node1 = Node(nodeINPUT[0])\n if i == len(lst)-1: \n lst.append(node1)\n\n for i in range(len(lst)): \n if lst[i].data == nodeINPUT[1]: \n node2 =lst[i]\n break\n else: \n node2 = Node(nodeINPUT[1])\n if i == len(lst)-1: \n lst.append(node2)\n node1.appender(node2)\n node2.appender(node1)\n\n\n'''\ndef levelofnode(root, key, level, avoid): \n if root == None: \n return -1\n if root.data == key: \n return level\n for i in range(len(root.link)): \n if i != avoid or avoid == -1: \n print('IT Ran! at', i)\n avoid = root.link[i].link.index(root)\n l = levelofnode(root.link[i], key, level+1, avoid)\n if l != -1 and l != None: \n return l\n if i == (len(root.link)-1): \n return levelofnode(root.link[i], key, level+1, avoid)\navoid = -1 #root address is not in it's link itself\nprint('OUTPUT OF THE FUNCTION IS:', levelofnode(root, 2, 0, avoid))\n'''\n#THIS FINDS OUT THE DISTANCE BETWEEN TWO NODES. HERE ROOT IS THE ADDRESS OF THE VALUE V1 AND 'AVOID' MAKES SURE IT DOES NOT COME BACK.\ndef dist(root, v2, avoid): \n if root == None: \n return -1\n if root.data == v2: \n return 0\n for i in range(len(root.link)): \n if i != avoid or avoid == -1: \n avoid = root.link[i].link.index(root)\n if dist(root.link[i], v2, avoid) != None: \n l = 1 + dist(root.link[i], v2, avoid)\n else: \n continue\n if l != -1 and l != None: \n return l\n\n'''\nroot.link.append(root)\ndef lca(root, v1, v2): \n i = 0\n for node in root.link: \n if i == 0:\n if node != root and root.data > max(v1, v2):\n return lca(root.link[i], v1, v2)\n else: \n if node != root and root.data < min(v1, v2):\n\n \n'''\nfrom itertools import combinations\nfor SET in sets: \n if len(SET) != 1: \n total = 0\n for pair in combinations(SET, 2): \n for node in lst: \n if node.data == pair[0]: \n root = node\n total = total + pair[0]*pair[1]*dist(root, pair[1], -1)\n print(total%1000000007)\n else:\n print(0)\n\n", "repo_name": "princesharma74/60DaysChallenge", "sub_path": "DAY49.py", "file_name": "DAY49.py", "file_ext": "py", "file_size_in_byte": 3366, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "itertools.combinations", "line_number": 113, "usage_type": "call"}]} +{"seq_id": "18871711758", "text": "import os\nimport subprocess\nfrom flask import jsonify, render_template, request, session\nfrom apiflask import APIFlask\nimport requests\nfrom requests.auth import HTTPBasicAuth\nfrom types import SimpleNamespace\n\napp = APIFlask(__name__)\napp.config.update(TESTING=True, SECRET_KEY=os.getenv(\"SECRET_KEY\"))\nIDRAC_HOST = None # noqa: F841\nIDRAC_USERNAME = None # noqa: F841\nIDRAC_PASSWORD = None # noqa: F841\n\nplaywright_working_dir = os.getenv(\n \"PLAYWRIGHT_WORKING_DIR\", \"../playwright-boostrap/\"\n) # noqa: E501\nPWDEBUG = os.getenv(\"PWDEBUG\", False)\nplaywright_headed = \"--headed\" if \"PWDEBUG\" in os.environ else \"\"\n\nIDRAC_SCRIPTS_BASE_PATH = os.getenv(\n \"IDRAC_SCRIPTS_BASE_PATH\", \"./iDRAC-Redfish-Scripting/Redfish Python/\"\n)\n\nsession_requests = requests.Session()\nsession_requests.verify = False\n\n\ndef api_response(req):\n error = None\n if req.status_code not in range(200, 299):\n error = req.text\n return jsonify({\"output\": req.text, \"error\": error}), req.status_code\n\n\ndef api_call(path=None, method=None, payload=None):\n breakpoint()\n assert method is not None\n url = f\"https://{session.get('IDRAC_HOST')}/redfish/v1/{path}\"\n authHeaders = HTTPBasicAuth(\n session.get(\"IDRAC_USERNAME\"), session.get(\"IDRAC_PASSWORD\")\n ) # noqa: E501\n\n # Making the request\n if method == \"GET\":\n req = requests.get(\n url,\n auth=authHeaders,\n verify=False,\n )\n elif method == \"POST\":\n req = requests.post(\n url,\n auth=authHeaders,\n verify=False,\n json=payload,\n headers={\"Content-Type\": \"application/json\"},\n )\n\n return req\n\n\n@app.before_request\ndef load_idrac_settings():\n \"\"\"\n Load settings in following order of presidence:\n - environment variable\n - session variable (from url GET paramenter)\n - default fallback\n\n \"\"\"\n settings = [\"IDRAC_HOST\", \"IDRAC_USERNAME\", \"IDRAC_PASSWORD\"]\n\n for setting in settings:\n # Default setting to None (meaning unset)\n exec(f\"{setting}=None\")\n # Check if setting is set in environment variable\n if os.getenv(setting, None):\n exec(f\"{setting}={os.getenv(setting)}\")\n # Check if setting is set in url get parameter\n if request.args.get(setting, None):\n session[setting] = request.args.get(setting)\n exec(f\"{setting}='{request.args.get(setting)}'\")\n\n breakpoint()\n\n\n@app.context_processor\ndef inject_settings():\n return dict(IDRAC_HOST=os.getenv(\"IDRAC_HOST\"))\n\n\n@app.route(\"/\")\ndef index():\n load_idrac_settings()\n return render_template(\"index.html\")\n\n\n@app.route(\"/wipefs\")\ndef wipefs():\n \"\"\"Wipe the entire server\"\"\"\n # Power off server\n # Mount & Boot into fedora live CD (there must be a better way...)\n # SSH into server\n # Run 'wip-all-disks.sh'\n # See https://github.com/KarmaComputing/server-bootstrap/blob/d9faddb3138d4ddb733dd9890d35a7c1296cdee7/src/playbooks/scripts/wipe-all-disks.sh#L1 # noqa: E501\n\n return {\"message\": \"Server has been wiped\"}\n\n\ndef execute_redfish_command(action):\n if action == \"Bootstrap\":\n VerifyiDRACAccess()\n ForceOff()\n sleepSecconds = 10\n print(f\"Sleeping for {sleepSecconds}\")\n iDRACSetVirtualTerminalHTML5()\n UnmountISO()\n UnmountISO()\n MountISO()\n MountISO()\n GetPowerState()\n from time import sleep\n\n sleepSecconds = 10\n print(f\"Sleeping for {sleepSecconds}\")\n sleep(sleepSecconds)\n return PowerOn()\n\n if action == \"ForceRestart\":\n url = f\"https://{IDRAC_HOST}/redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset\" # noqa: E501\n headers = {\"Content-Type\": \"application/json\"}\n payload = {\"ResetType\": \"ForceRestart\"}\n auth = (IDRAC_USERNAME, IDRAC_PASSWORD)\n\n req = requests.post(\n url, headers=headers, json=payload, auth=auth, verify=False\n ) # noqa: E501\n return api_response(req)\n\n if action == \"GetOnetimeBootValue\":\n # URL\n url = f\"https://{IDRAC_HOST}/redfish/v1/Systems/System.Embedded.1\"\n\n # Making the request\n req = requests.get(\n url,\n auth=HTTPBasicAuth(IDRAC_USERNAME, IDRAC_PASSWORD),\n verify=False,\n )\n return api_response(req)\n\n if action == \"ChangeBiosBootOrderREDFISH\":\n command = f\"python {IDRAC_SCRIPTS_BASE_PATH}ChangeBiosBootOrderREDFISH.py -ip {IDRAC_HOST} -u {IDRAC_USERNAME} -p {IDRAC_PASSWORD} --get\" # noqa: E501\n result = subprocess.run(command, capture_output=True, shell=True)\n\n else:\n command = f\"python {IDRAC_SCRIPTS_BASE_PATH}GetSetPowerStateREDFISH.py -ip {IDRAC_HOST} -u {IDRAC_USERNAME} -p {IDRAC_PASSWORD} --set {action}\" # noqa: E501\n result = subprocess.run(command, capture_output=True, shell=True)\n return (\n jsonify(\n {\n \"output\": result.stdout.decode(\"utf-8\"),\n \"error\": result.stderr.decode(\"utf-8\"),\n }\n ),\n result.returncode,\n )\n\n\n@app.route(\"/api/v1/Bootstrap\", methods=[\"POST\"])\ndef bootstrap():\n return execute_redfish_command(\"Bootstrap\")\n\n\n@app.route(\"/api/v1/VerifyiDRACAccess\", methods=[\"POST\"])\ndef VerifyiDRACAccess():\n url = f\"https://{IDRAC_HOST}/redfish/v1/Systems/\"\n headers = {\"Content-Type\": \"application/json\"}\n payload = {\"ResetType\": \"ForceRestart\"}\n auth = (IDRAC_USERNAME, IDRAC_PASSWORD)\n req = requests.get(\n url, headers=headers, json=payload, auth=auth, verify=False\n ) # noqa: E501\n return api_response(req)\n\n\n@app.route(\"/api/v1/ResetiDRAC\", methods=[\"POST\"])\ndef ResetiDRAC():\n return api_response(\"Not implemented\")\n\n\n@app.route(\"/api/v1/iDRACSetVirtualTerminalHTML5\", methods=[\"POST\"])\ndef iDRACSetVirtualTerminalHTML5():\n command = (\n f\"IDRAC_HOST=http://{IDRAC_HOST} IDRAC_USERNAME={IDRAC_USERNAME} \"\n f\"IDRAC_PASSWORD={IDRAC_PASSWORD} npx playwright test scripts/iDRAC-set-virtual-terminal-html5.spec.ts \" # noqa: E501\n f\" {playwright_headed}\"\n )\n result = subprocess.run(\n command,\n cwd=playwright_working_dir,\n env=os.environ,\n capture_output=True,\n shell=True,\n ) # noqa: E501\n return (\n jsonify(\n {\n \"output\": result.stdout.decode(\"utf-8\"),\n \"error\": result.stderr.decode(\"utf-8\"),\n }\n ),\n result.returncode,\n )\n\n\n@app.route(\"/api/v1/PowerOn\", methods=[\"POST\"])\ndef PowerOn():\n print(\"PowerOn\")\n breakpoint()\n data = {\"ResetType\": \"On\"}\n req = api_call(\n path=\"Systems/System.Embedded.1/Actions/ComputerSystem.Reset\",\n method=\"POST\", # noqa: E501\n payload=data,\n )\n\n return api_response(req)\n\n\n@app.route(\"/api/v1/ForceOff\", methods=[\"POST\"])\n@app.route(\"/api/v1/PowerOff\", methods=[\"POST\"])\ndef ForceOff():\n print(\"ForceOff\")\n # URL\n url = f\"https://{IDRAC_HOST}/redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset\" # noqa: E501\n\n # Headers\n headers = {\"Content-Type\": \"application/json\"}\n\n # Data\n data = {\"ResetType\": \"ForceOff\"}\n\n # Making the request\n req = requests.post(\n url,\n headers=headers,\n json=data,\n auth=HTTPBasicAuth(IDRAC_USERNAME, IDRAC_PASSWORD),\n verify=False,\n )\n return api_response(req)\n\n\n@app.route(\"/api/v1/ForceRestart\", methods=[\"POST\"])\ndef force_restart():\n return execute_redfish_command(\"ForceRestart\")\n\n\n@app.route(\"/api/v1/GracefulShutdown\", methods=[\"POST\"])\ndef set_power_graceful_shutdown():\n return execute_redfish_command(\"GracefulShutdown\")\n\n\n@app.route(\"/api/v1/GetPowerState\", methods=[\"POST\"])\ndef GetPowerState():\n print(\"GetPowerState\")\n req = api_call(path=\"Systems/System.Embedded.1\")\n\n if req.status_code == 200:\n response_text = (\n f\"Current server power state: {req.json()['PowerState']}\" # noqa: E501\n )\n req = SimpleNamespace()\n req.status_code = 200\n req.text = response_text\n return api_response(req)\n\n\n@app.route(\"/api/v1/ChangeBiosBootOrderREDFISH\", methods=[\"POST\"])\ndef get_bios_boot_order():\n return execute_redfish_command(\"ChangeBiosBootOrderREDFISH\")\n\n\n@app.route(\"/api/v1/MountISO\", methods=[\"POST\"])\ndef MountISO():\n print(\"MountISO\")\n # URL\n url = f\"https://{IDRAC_HOST}/redfish/v1/Managers/iDRAC.Embedded.1/VirtualMedia/CD/Actions/VirtualMedia.InsertMedia\" # noqa: E501\n\n # Headers\n headers = {\"Content-Type\": \"application/json\"}\n\n # Data\n data = {\"Image\": \"http://138.201.59.208/sites/default/files/ipxe.iso\"}\n\n # Making the request\n req = requests.post(\n url,\n headers=headers,\n json=data,\n auth=HTTPBasicAuth(IDRAC_USERNAME, IDRAC_PASSWORD),\n verify=False,\n )\n\n if req.status_code == \"500\":\n try:\n message = req.json()[\"error\"][\"@Message.ExtendedInfo\"][0][\n \"Message\"\n ] # noqa: E501\n if (\n message\n == \"The Virtual Media image server is already connected.\" # noqa: E501\n ): # noqa: E501\n print(\"The Virtual Media image server is already connected.\")\n else:\n breakpoint()\n except Exception as e:\n print(e)\n\n return api_response(req)\n\n\n@app.route(\"/api/v1/UnmountISO\", methods=[\"POST\"])\ndef UnmountISO():\n print(UnmountISO)\n # URL\n url = f\"https://{IDRAC_HOST}/redfish/v1/Managers/iDRAC.Embedded.1/VirtualMedia/CD/Actions/VirtualMedia.EjectMedia\" # noqa: E501\n\n # Headers\n headers = {\"Content-Type\": \"application/json\"}\n\n # Data\n data = {}\n\n # Making the request\n req = requests.post(\n url,\n headers=headers,\n json=data,\n auth=HTTPBasicAuth(IDRAC_USERNAME, IDRAC_PASSWORD),\n verify=False,\n )\n return api_response(req)\n\n\n@app.route(\"/api/v1/GetOnetimeBootValue\", methods=[\"POST\"])\ndef get_current_onetime_boot_order():\n return execute_redfish_command(\"GetOnetimeBootValue\")\n", "repo_name": "KarmaComputing/server-bootstrap", "sub_path": "src/web-ui/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 10150, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "apiflask.APIFlask", "line_number": 9, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 10, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 15, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 18, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 19, "usage_type": "attribute"}, {"api_name": "os.getenv", "line_number": 21, "usage_type": "call"}, {"api_name": "requests.Session", "line_number": 25, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 33, "usage_type": "call"}, {"api_name": "flask.session.get", "line_number": 39, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 39, "usage_type": "name"}, {"api_name": "requests.auth.HTTPBasicAuth", "line_number": 40, "usage_type": "call"}, {"api_name": "flask.session.get", "line_number": 41, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 41, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 46, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 52, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 78, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 79, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 81, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 81, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 81, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 82, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 82, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 82, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 82, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 83, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 83, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 83, "usage_type": "name"}, {"api_name": "os.getenv", "line_number": 90, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 96, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 127, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 136, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 146, "usage_type": "call"}, {"api_name": "requests.auth.HTTPBasicAuth", "line_number": 148, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 155, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 159, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 161, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 182, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 200, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 203, "usage_type": "attribute"}, {"api_name": "flask.jsonify", "line_number": 208, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 246, "usage_type": "call"}, {"api_name": "requests.auth.HTTPBasicAuth", "line_number": 250, "usage_type": "call"}, {"api_name": "types.SimpleNamespace", "line_number": 275, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 299, "usage_type": "call"}, {"api_name": "requests.auth.HTTPBasicAuth", "line_number": 303, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 338, "usage_type": "call"}, {"api_name": "requests.auth.HTTPBasicAuth", "line_number": 342, "usage_type": "call"}]} +{"seq_id": "37972040531", "text": "# Q-learning agent for MCML-Block chain\n# @author: Hieu Nguyen\n\nimport numpy as np\nimport gym\nimport matplotlib.pyplot as plt\nimport xlsxwriter\nimport random\nimport copy\nfrom environment import Environment, MyProcessor\nfrom writer_v1 import MCMLWriter\nfrom config import MEMPOOL_MAX, CPU_SHARES, CAPACITY_MAX, ENERGY_MAX, DATA_MAX, MINING_RATE, NB_DEVICES\nfrom policy_epgreedy import MyEpsGreedy\nimport json\n\n# For statistic\njson_data = {}\njson_data['episode'] = []\njson_data['episode_reward'] = []\njson_data['mean_q'] = []\njson_data['mean_eps'] = []\n\ndef array_to_scalar(arr, base1, base2):\n \"\"\"\n Convert state array to scalar to feed q-table\n\n :param a: input state array\n\n :return: state scalar\n \"\"\"\n base1 = base1\n base2 = base2\n scalar_state = 0\n state_size = len(arr)\n for i in range(state_size):\n if i < state_size:\n scalar_state += arr[i] * (base1 ** (state_size - 1 - i))\n else:\n scalar_state += arr[i] * (base2 ** (state_size - 1 - i))\n return scalar_state\n\n# Hyperparameters\nalpha = 0.1\ngamma = 0.99\nepsilon_max = 0.9\nepsilon_min = 0.05\nepsilon_trained = 2000\nepsilon_decay = (epsilon_max - epsilon_min) / epsilon_trained\n\n# Training parameters\nNB_EPISODES = 4000\nTEST_ID = 45\nepisode = 0\nepsilon = epsilon_max\n\n# Statistic\nmempool = []\nworkbook = xlsxwriter.Workbook('./build/q_learning-result-{}.xlsx'.format(TEST_ID))\nwriter = MCMLWriter(workbook)\n\n# Initialize q-table\nstate_space_size = (CPU_SHARES ** NB_DEVICES) * (CAPACITY_MAX ** NB_DEVICES) * MEMPOOL_MAX\naction_space_size = (ENERGY_MAX ** NB_DEVICES) * (DATA_MAX ** NB_DEVICES) * MINING_RATE\nq_table = np.zeros((state_space_size, action_space_size))\nprint(q_table.shape)\n\n# Environment set up\nenv = Environment(mempool, writer)\nenv.reset()\nprocessor = MyProcessor()\nprint(env.observation_space, env.action_space)\n\n# Training begins\nprint('********************* Start Q-Learning test-id: {} ***********************'.format(TEST_ID))\nfor i in range(NB_EPISODES):\n # state = env.reset()\n state = array_to_scalar(env.reset(), CPU_SHARES, MEMPOOL_MAX)\n episode_reward = 0\n steps, reward = 0, 0\n done = False\n max_q_array = []\n if epsilon >= epsilon_min + epsilon_decay:\n epsilon -= epsilon_decay\n else:\n epsilon = epsilon_min\n # print('Ep: {}, q_table shape: {}, state: {}'.format(episode+1, q_table.shape, state))\n while not done:\n action_scalar = 0\n if random.uniform(0, 1) < epsilon:\n action = env.action_space.sample()\n action_scalar = array_to_scalar(action, ENERGY_MAX, ENERGY_MAX)\n else:\n action_scalar = np.argmax(q_table[state])\n if action_scalar > action_space_size:\n print('invalid action: {}, q_table[state].shape: {}'.format(action_scalar, q_table[state].shape))\n action = processor.process_action(action_scalar)\n # print(action_scalar, action)\n next_state, reward, done, info = env.step(action)\n next_state_scalar = array_to_scalar(next_state, CPU_SHARES, MEMPOOL_MAX)\n old_value = q_table[state, action_scalar]\n next_max = np.max(q_table[next_state_scalar])\n\n new_value = (1 - alpha) * old_value + alpha * (reward + gamma * next_max)\n q_table[state, action_scalar] = new_value\n\n state = next_state_scalar\n episode_reward += reward\n steps += 1\n\n episode += 1\n # Save data to json file\n json_data['episode'].append(episode)\n json_data['episode_reward'].append(int(episode_reward))\n json_data['mean_eps'].append(epsilon)\n\n for k in range(state_space_size):\n max_q_array.append(np.amax(q_table[k]))\n json_data['mean_q'].append(np.mean(max_q_array))\n\n print('Episode: {}, Epsilon: {}, Total reward: {}, Steps: {}, Average reward: {}'\n .format(episode, epsilon, episode_reward, steps, episode_reward / steps))\n\nwith open('./build/q_learning_log_{}.json'.format(TEST_ID), 'w') as outfile:\n json.dump(json_data, outfile)\n# End of training\nprint('********************* End Q-Learning test-id: {} ***********************'.format(TEST_ID))\nworkbook.close()\n", "repo_name": "hieunq95/keras-rl", "sub_path": "mcml-blockchain/q-learning.py", "file_name": "q-learning.py", "file_ext": "py", "file_size_in_byte": 4148, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "27", "api": [{"api_name": "xlsxwriter.Workbook", "line_number": 58, "usage_type": "call"}, {"api_name": "writer_v1.MCMLWriter", "line_number": 59, "usage_type": "call"}, {"api_name": "config.CPU_SHARES", "line_number": 62, "usage_type": "name"}, {"api_name": "config.NB_DEVICES", "line_number": 62, "usage_type": "name"}, {"api_name": "config.CAPACITY_MAX", "line_number": 62, "usage_type": "name"}, {"api_name": "config.MEMPOOL_MAX", "line_number": 62, "usage_type": "name"}, {"api_name": "config.ENERGY_MAX", "line_number": 63, "usage_type": "name"}, {"api_name": "config.NB_DEVICES", "line_number": 63, "usage_type": "name"}, {"api_name": "config.DATA_MAX", "line_number": 63, "usage_type": "name"}, {"api_name": "config.MINING_RATE", "line_number": 63, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 64, "usage_type": "call"}, {"api_name": "environment.Environment", "line_number": 68, "usage_type": "call"}, {"api_name": "environment.MyProcessor", "line_number": 70, "usage_type": "call"}, {"api_name": "config.CPU_SHARES", "line_number": 77, "usage_type": "argument"}, {"api_name": "config.MEMPOOL_MAX", "line_number": 77, "usage_type": "argument"}, {"api_name": "random.uniform", "line_number": 89, "usage_type": "call"}, {"api_name": "config.ENERGY_MAX", "line_number": 91, "usage_type": "argument"}, {"api_name": "numpy.argmax", "line_number": 93, "usage_type": "call"}, {"api_name": "config.CPU_SHARES", "line_number": 99, "usage_type": "argument"}, {"api_name": "config.MEMPOOL_MAX", "line_number": 99, "usage_type": "argument"}, {"api_name": "numpy.max", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.amax", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 118, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 124, "usage_type": "call"}]} +{"seq_id": "31274104624", "text": "\nfrom flask import Flask, request, wrappers\nfrom cloudflare_wsgi import CloudFlareMiddleware\n\napp = Flask(__name__)\napp.wsgi_app = CloudFlareMiddleware(app.wsgi_app)\n\n@app.route(\"/\", methods=[\"GET\"])\ndef index_get():\n return f\"ok; {request.remote_addr}\", 200\n\nwith app.test_client() as client:\n resp: wrappers.Response = client.get(\n \"/\", headers={\"cf-connecting-ip\": \"10.10.10.10\"}\n )\n print(resp.data)\n", "repo_name": "IsThicc/CloudFlareWSGI", "sub_path": "cloudflare_wsgi/test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 423, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "27", "api": [{"api_name": "flask.Flask", "line_number": 5, "usage_type": "call"}, {"api_name": "cloudflare_wsgi.CloudFlareMiddleware", "line_number": 6, "usage_type": "call"}, {"api_name": "flask.request.remote_addr", "line_number": 10, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 10, "usage_type": "name"}, {"api_name": "flask.wrappers.Response", "line_number": 13, "usage_type": "attribute"}, {"api_name": "flask.wrappers", "line_number": 13, "usage_type": "name"}]} +{"seq_id": "1365293980", "text": "'''\n airline_client.py\n Ruben Boero 12/10/2022\n\n Thanks to David Lonoff for the massive help with this project.\n'''\n\nimport json\nimport requests\nimport flask\nfrom flask import request, redirect\nimport time\n\ndef get_all_flights(endpoint):\n response = requests.get(endpoint)\n flights = json.loads(response.text)\n flightsDict = dict(flights)\n flightList = []\n \n for flight in flightsDict:\n flightList.append({'number': flightsDict[flight]['number'], 'status': flightsDict[flight]['status']})\n\n return flightList\n\ndef check_in_flight():\n # get the flight number from the form\n flight_num = request.form['flight_number']\n\n # check that the user has input an integer\n if not flight_num.isdigit(): \n flightList = get_all_flights('http://127.0.0.1:5001/flights')\n \n return flask.render_template('error.html', inputError=True, flights=flightList)\n \n flight_num = int(request.form['flight_number'])\n\n check_in_response = requests.post(url = 'http://127.0.0.1:5001/check_in', data = {\"flight_number\": flight_num}) \n eligibility = check_in_response.json()['status']\n \n if eligibility == 'succeeded':\n return redirect('/')\n \n else:\n print('flight not checked in. checking again in 60 seconds')\n time.sleep(60)\n\n while True:\n print('attempting checkin')\n check_in_response = requests.post(url = 'http://127.0.0.1:5001/check_in', data = {\"flight_number\": flight_num}) \n eligibility = check_in_response.json()['status']\n if eligibility == 'succeeded':\n print('successfully checked in')\n break\n else:\n time.sleep(60)\n\n return redirect('/')", "repo_name": "rubenboero21/Careers-in-Software-Engineering", "sub_path": "Ruben-API/airline_client.py", "file_name": "airline_client.py", "file_ext": "py", "file_size_in_byte": 1755, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "requests.get", "line_number": 15, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 16, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 27, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 27, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 33, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 35, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 35, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 37, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 41, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 45, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 49, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 55, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 57, "usage_type": "call"}]} +{"seq_id": "19737308125", "text": "import numpy as np\nfrom functools import reduce\nfrom mindquantum.core.operators import FermionOperator,QubitOperator\nfrom mindquantum.core.operators.utils import hermitian_conjugated\nfrom pyscf import ao2mo, gto, scf,fci\nfrom .FerOp_QubitOp import (get_qubit_hamiltonian,get_qubit_operator,unitiy_mo_coeff_format,\\\n get_ao2so_h1_h2_int,get_qubit_adder_operator,get_qubit_na_nb_operator)\n\n##############################################\n#\n#\n#\n##############################################\n\ndef ABorder_qubit_hubbard_model_2D_molmf(size, U, beta0=0.0,beta1=0.0,pbc=False):\n \"\"\" SITE basis, and ABABAB order\"\"\"\n thop = get_Hubbard_2D_t(size,pbc)\n eri = get_Hubbard_2D_U(size,U)\n nbas = size[0]*size[1]\n \n mol = gto.M()\n mol.verbose = 3\n mol.nelectron = 2*(nbas//2)\n mf = scf.RHF(mol)\n mf.get_hcore = lambda *args: thop\n mf.get_ovlp = lambda *args: np.eye(nbas)\n mf._eri = ao2mo.restore(8, eri, nbas)\n mf.kernel()\n \n print('spin',mol.spin)\n molFCI = fci.FCI(mf) \n res = molFCI.kernel() \n eFCI = res[0]\n print('eFCI',eFCI)\n \n mo_coeff = np.eye(nbas) # mf.mo_coeff\n \n h1e = mf.get_hcore()\n h2e = mf._eri\n h1s,h2s = get_ao2so_h1_h2_int(mo_coeff,h1e,h2e)\n qham = get_qubit_hamiltonian(0.0,h1s,h2s,'jordan_wigner')\n\n qsp,qsm = get_qubit_adder_operator(np.eye(nbas), mo_coeff,'jordan_wigner')\n qna,qnb = get_qubit_na_nb_operator(nbas,'jordan_wigner')\n print('penalty hamiltonian: beta0-sp-sm',beta0,'beta1-na-nb',beta1)\n penalty_ham = qham + beta0*qsp*qsm + beta1*(qna-nbas//2)**2 + beta1*(qnb-nbas//2)**2\n return penalty_ham\n\n##########################################################\n# Hubbard model Hamiltonian \n# spin-orbital: A - A\n# | |\n# B - B \n# | |\n# A - A\n# | |\n# B - B\n##########################################################\n\ndef selforder_qubit_hubbard_model_2D(size, U, beta0=0.0,beta1=0.0,pbc=False):\n \"\"\" SITE basis, and AABB order\"\"\"\n thop = get_Hubbard_2D_t(size,pbc)\n eri = get_Hubbard_2D_U(size,U)\n nbas = size[0]*size[1]\n \n mol = gto.M()\n mol.verbose = 3\n mol.nelectron = 2*(nbas//2)\n mf = scf.RHF(mol)\n mf.get_hcore = lambda *args: thop\n mf.get_ovlp = lambda *args: np.eye(nbas)\n mf._eri = ao2mo.restore(8, eri, nbas)\n mf.kernel()\n \n print('spin',mol.spin)\n molFCI = fci.FCI(mf) \n res = molFCI.kernel() \n eFCI = res[0]\n print('eFCI',eFCI)\n \n mo_coeff = np.eye(nbas) # mf.mo_coeff\n h1m,h2m = get_RHF_int_h1h2(thop, eri, mo_coeff)\n h1s,h2s = get_SpinOrbital_h1h2_in_AAAABBBBorder(h1m,h2m)\n \n # in self order\n index = get_ix(size)\n h1ss = h1s[np.ix_(index,index)]\n h2ss = h2s[np.ix_(index,index,index,index)]\n qham = get_qubit_hamiltonian(0.0,h1ss,h2ss,'jordan_wigner')\n\n qsp,qsm = selforder_qsp_qsm(size)\n qna,qnb = selforder_qna_qnb(size)\n \n print('penalty hamiltonian: beta0-sp-sm',beta0,'beta1-na-nb',beta1)\n penalty_ham = qham + beta0*qsp*qsm + beta1*(qna-nbas//2)**2 + beta1*(qnb-nbas//2)**2\n return penalty_ham\n\ndef selforder_qna_qnb(size):\n nx,ny = size\n nsite = nx*ny\n nqubits = 2*nsite\n fna = FermionOperator()\n fnb = FermionOperator()\n for idx,i in enumerate(range(nx)):\n ia = 2*i\n ib = 2*i + 1\n ac = (ny*ia,ny*(ia+1))\n bc = (ny*ib,ny*(ib+1))\n for j in range(ac[0],ac[1]):\n fna += FermionOperator(str(j)+'^ '+str(j)+' ')\n for j in range(bc[0],bc[1]):\n fnb += FermionOperator(str(j)+'^ '+str(j)+' ')\n qna = get_qubit_operator(fna,'jordan_wigner')\n qnb = get_qubit_operator(fnb,'jordan_wigner')\n return qna,qnb\n\ndef selforder_qsp_qsm(size):\n nx,ny = size\n nsite = nx*ny\n nqubits = 2*nsite\n lsa = []\n lsb = []\n for idx,i in enumerate(range(nx)):\n ia = 2*i\n lsa += np.arange(ny*ia,ny*(ia+1)).tolist()\n ib = 2*i + 1\n lsb += np.arange(ny*ib,ny*(ib+1)).tolist()\n fsp = FermionOperator()\n for j in range(nsite):\n fsp += FermionOperator(str(lsa[j])+'^ '+str(lsb[j])+' ')\n fsm = hermitian_conjugated(fsp)\n qsp = get_qubit_operator(fsp,'jordan_wigner')\n qsm = get_qubit_operator(fsm,'jordan_wigner')\n return qsp,qsm\n\ndef get_ix(size):\n \"\"\"conver AAAA AAAA BBBB BBBB to \n AAAA\n BBBB\n AAAA\n BBBB\n \"\"\"\n nx,ny = size\n ls = []\n for idx,i in enumerate(range(nx)):\n ia = 2*i\n ls += np.arange(ny*ia,ny*(ia+1)).tolist()\n for idx,i in enumerate(range(nx)):\n ib = 2*i + 1\n ls += np.arange(ny*ib,ny*(ib+1)).tolist() \n return np.array(ls)\n\n##########################################################\n# Hubbard model Hamiltonian \n# spin-orbital: AAAABBBB\n# SITE basis\n##########################################################\n\ndef qubit_hubbard_hamiltonian(size, U, beta0=0.0,beta1=0.0,pbc=False):\n \"\"\" SITE basis, and AABB order\"\"\"\n thop = get_Hubbard_2D_t(size,pbc)\n eri = get_Hubbard_2D_U(size,U)\n nbas = size[0]*size[1]\n \n mol = gto.M()\n mol.verbose = 3\n mol.nelectron = 2*(nbas//2)\n mf = scf.RHF(mol)\n mf.get_hcore = lambda *args: thop\n mf.get_ovlp = lambda *args: np.eye(nbas)\n mf._eri = ao2mo.restore(8, eri, nbas)\n mf.kernel()\n \n print('spin',mol.spin)\n molFCI = fci.FCI(mf) \n res = molFCI.kernel() \n eFCI = res[0]\n print('eFCI',eFCI)\n \n mo_coeff = np.eye(nbas) # mf.mo_coeff\n h1m,h2m = get_RHF_int_h1h2(thop, eri, mo_coeff)\n h1s,h2s = get_SpinOrbital_h1h2_in_AAAABBBBorder(h1m,h2m)\n qham = get_qubit_hamiltonian(0.0,h1s,h2s,'jordan_wigner')\n\n qsp,qsm = get_qubit_adder_operator_AAAABBBB(np.eye(nbas), mo_coeff)\n qna,qnb = get_qubit_na_nb_operator_AAAABBBB(nbas)\n print('penalty hamiltonian: beta0-sp-sm',beta0,'beta1-na-nb',beta1)\n penalty_ham = qham + beta0*qsp*qsm + beta1*(qna-nbas//2)**2 + beta1*(qnb-nbas//2)**2\n return penalty_ham\n\ndef get_Hubbard_2D_t(size,pbc=False):\n t=1\n nx,ny = size\n nsite = nx*ny\n thop = np.zeros((nsite,nsite))\n # Row:\n for ix in range(nx):\n for iy in range(ny-1):\n thop[iy+ix*ny,iy+1+ix*ny] = -t\n thop[iy+1+ix*ny,iy+ix*ny] = -t\n if pbc and ny>2:\n thop[ix*ny,(ix+1)*ny-1] = -t\n thop[(ix+1)*ny-1,ix*ny] = -t\n # Up:\n for iy in range(ny):\n for ix in range(nx-1):\n thop[iy+ix*ny,iy+(ix+1)*ny] = -t\n thop[iy+(ix+1)*ny,iy+ix*ny] = -t\n if pbc and nx>2:\n thop[iy,iy+(nx-1)*ny] = -t \n thop[iy+(nx-1)*ny,iy] = -t \n return thop\n\ndef get_Hubbard_2D_U(size,U):\n #t=1, U/t=U\n nx,ny = size\n nbas = nx*ny\n h2e = np.zeros((nbas,nbas,nbas,nbas))\n for i in range(nbas):\n h2e[i,i,i,i] = U\n return h2e\n\n# spatial to spin-orbital integrals\ndef get_SpinOrbitalERI_h1_in_AAAABBBBorder(h1s):\n nb = h1s.shape[0]\n h1 = np.zeros((2*nb,2*nb))\n h1[:nb,:nb] = h1s # AA\n h1[nb:,nb:] = h1s # BB\n return h1\n\n# chemist notation [ij|kl]\ndef get_SpinOrbitalERI_h2_in_AAAABBBBorder(h2s):\n nb = h2s.shape[0]\n h2 = np.zeros((2*nb,2*nb,2*nb,2*nb))\n h2[:nb,:nb,:nb,:nb] = h2s # AAAA\n h2[nb:,nb:,nb:,nb:] = h2s # BBBB\n h2[:nb,:nb,nb:,nb:] = h2s # AABB\n h2[nb:,nb:,:nb,:nb] = h2s # BBAA\n return h2 # return h2*0.5 for Qiskit\n\ndef get_SpinOrbital_h1h2_in_AAAABBBBorder(h1s,h2s):\n h1 = get_SpinOrbitalERI_h1_in_AAAABBBBorder(h1s)\n h2 = get_SpinOrbitalERI_h2_in_AAAABBBBorder(h2s)\n return h1,h2\n\n# ao -> RHF mo\ndef get_RHF_int_h1h2(thop, eri, mo_coeff):\n h1 = mo_coeff.T.dot(thop).dot(mo_coeff)\n h2 = eri\n h2 = np.einsum(\"pqrs,pi->iqrs\",h2,mo_coeff)\n h2 = np.einsum(\"iqrs,qj->ijrs\",h2,mo_coeff)\n h2 = np.einsum(\"ijrs,rk->ijks\",h2,mo_coeff)\n h2 = np.einsum(\"ijks,sl->ijkl\",h2,mo_coeff)\n return h1,h2\n\ndef get_fermion_ss_operator_AAAABBBB(ovlp,mo_coeff,list_active=[]): \n # input mo_coeff = mf.mo_coeff\n \"\"\"ss = 1/2*(s_plus*s_minus + s_minus*s_plus) + s_z**2\"\"\"\n mo_coeff = unitiy_mo_coeff_format(mo_coeff)\n s_plus = FermionOperator()\n s_minus = FermionOperator()\n s_z = FermionOperator() \n ovlpab = reduce(np.dot, (mo_coeff[0].T, ovlp, mo_coeff[1]))\n if list_active:\n ovlpab = ovlpab[np.ix_(list_active,list_active)]\n k = ovlpab.shape[0]\n for p in range(k):\n for q in range(k):\n s_plus += ovlpab[p,q]*FermionOperator(((p,1),(q+k,0)))\n s_minus = hermitian_conjugated(s_plus)\n for p in range(k):\n s_z += 0.5*(FermionOperator(((p,1),(p,0)))-FermionOperator(((p+k,1),(p+k,0)))) \n ss = 1/2*(s_plus*s_minus + s_minus*s_plus) + s_z**2\n ss.compress()\n return ss\n\ndef get_qubit_ss_operator_AAAABBBB(ovlp,mo_coeff,fermion_transform='jordan_wigner',list_active=[]):\n \"\"\"return molecule Qubit ss operator \"\"\"\n ss = get_fermion_ss_operator_AAAABBBB(ovlp,mo_coeff,list_active)\n qubit_ss_operator = get_qubit_operator(ss,fermion_transform)\n return qubit_ss_operator\n\ndef get_fermion_adder_operator_AAAABBBB(ovlp,mo_coeff,list_active=[]):\n \"\"\"s_plus and s_minus\"\"\"\n mo_coeff = unitiy_mo_coeff_format(mo_coeff)\n s_plus = FermionOperator()\n ovlpab = reduce(np.dot, (mo_coeff[0].T, ovlp, mo_coeff[1]))\n if list_active:\n ovlpab = ovlpab[np.ix_(list_active,list_active)]\n nmo = ovlpab.shape[0]\n for p in range(nmo):\n for q in range(nmo):\n s_plus += ovlpab[p,q]*FermionOperator(((p,1),(q+nmo,0)))\n s_minus = hermitian_conjugated(s_plus)\n return s_plus,s_minus\n\ndef get_qubit_adder_operator_AAAABBBB(ovlp,mo_coeff,fermion_transform='jordan_wigner',list_active=[]):\n splus,sminus = get_fermion_adder_operator_AAAABBBB(ovlp,mo_coeff,list_active)\n qubit_splus = get_qubit_operator(splus,fermion_transform)\n qubit_sminus = get_qubit_operator(sminus,fermion_transform)\n return qubit_splus,qubit_sminus\n\ndef get_fermion_na_nb_operator_AAAABBBB(norb):\n \"\"\" nalpha and nbeta\"\"\"\n na = FermionOperator()\n nb = FermionOperator() # n_partical\n for p in range(norb): \n na += FermionOperator(((p,1),(p,0)))\n nb += FermionOperator(((p+norb,1),(p+norb,0)))\n return na,nb\n\ndef get_qubit_na_nb_operator_AAAABBBB(norb,fermion_transform='jordan_wigner'):\n \"\"\"return qubit nalpha nbeta operator\"\"\"\n na,nb = get_fermion_na_nb_operator_AAAABBBB(norb)\n qubit_na = get_qubit_operator(na,fermion_transform)\n qubit_nb = get_qubit_operator(nb,fermion_transform)\n return qubit_na,qubit_nb\n\n# 下面的模型是根据公式写的,可以用于验证。\ndef get_fermion_hubbard_model_2D(size,U,t=1,pbc=False):\n \"\"\" \n spin-orbital: AAAABBBB,\n SITE basis,\n \\hat{H} = -t\\sum_{}\\sum_{\\sigma}(a^{\\dagger}_{i\\sigma}a_{j\\sigma} + h.c.)\n +U\\sum_{i}\\hat{n}_{i\\alpha}\\hat{n}_{i\\beta},\n \"\"\"\n def subterm(label1,label2,nsite):\n alpha = FermionOperator(str(label1)+'^ ')*FermionOperator(str(label2)+' ')\n beta = FermionOperator(str(label1+nsite)+'^ ')*FermionOperator(str(label2+nsite)+' ')\n return alpha+beta\n nx, ny = size\n nsite = nx*ny\n # hopping \n ham1 = FermionOperator()\n for ix in range(nx):\n for iy in range(ny-1):\n ham1 += subterm(iy+ix*ny,iy+1+ix*ny,nsite)\n if pbc and ny>2:\n ham1 += subterm(ix*ny,(ix+1)*ny-1,nsite)\n for iy in range(ny):\n for ix in range(nx-1):\n ham1 += subterm(iy+ix*ny,iy+(ix+1)*ny,nsite)\n if pbc and nx>2:\n ham1 += subterm(iy,iy+(nx-1)*ny,nsite)\n # on-site\n ham2 = FermionOperator()\n for i in range(nsite):\n aa = FermionOperator(str(i)+'^ '+str(i)+' ')-0.5\n bb = FermionOperator(str(i+nsite)+'^ '+str(i+nsite)+' ')-0.5\n ham2 += aa*bb\n \n ham = (ham1+hermitian_conjugated(ham1))*-t + ham2*U/t\n \n print('Fermion-hubbard-model size:',size,', PBC:',pbc)\n return ham\n\ndef get_qubit_hubbard_model_2D(size,U,t=1,pbc=False,fermion_transform='jordan_wigner'):\n fh = get_fermion_hubbard_model_2D(size,U,t,pbc)\n qh = get_qubit_operator(fh, fermion_transform)\n return qh", "repo_name": "xiaoamero/QC5", "sub_path": "hamiltonians/hamiltonian_hubbard_model.py", "file_name": "hamiltonian_hubbard_model.py", "file_ext": "py", "file_size_in_byte": 12272, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "pyscf.gto.M", "line_number": 21, "usage_type": "call"}, {"api_name": "pyscf.gto", "line_number": 21, "usage_type": "name"}, {"api_name": "pyscf.scf.RHF", "line_number": 24, "usage_type": "call"}, {"api_name": "pyscf.scf", "line_number": 24, "usage_type": "name"}, {"api_name": "numpy.eye", "line_number": 26, "usage_type": "call"}, {"api_name": "pyscf.ao2mo.restore", "line_number": 27, "usage_type": "call"}, {"api_name": "pyscf.ao2mo", "line_number": 27, "usage_type": "name"}, {"api_name": "pyscf.fci.FCI", "line_number": 31, "usage_type": "call"}, {"api_name": "pyscf.fci", "line_number": 31, "usage_type": "name"}, {"api_name": "numpy.eye", "line_number": 36, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_ao2so_h1_h2_int", "line_number": 40, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_qubit_hamiltonian", "line_number": 41, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_qubit_adder_operator", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 43, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_qubit_na_nb_operator", "line_number": 44, "usage_type": "call"}, {"api_name": "pyscf.gto.M", "line_number": 66, "usage_type": "call"}, {"api_name": "pyscf.gto", "line_number": 66, "usage_type": "name"}, {"api_name": "pyscf.scf.RHF", "line_number": 69, "usage_type": "call"}, {"api_name": "pyscf.scf", "line_number": 69, "usage_type": "name"}, {"api_name": "numpy.eye", "line_number": 71, "usage_type": "call"}, {"api_name": "pyscf.ao2mo.restore", "line_number": 72, "usage_type": "call"}, {"api_name": "pyscf.ao2mo", "line_number": 72, "usage_type": "name"}, {"api_name": "pyscf.fci.FCI", "line_number": 76, "usage_type": "call"}, {"api_name": "pyscf.fci", "line_number": 76, "usage_type": "name"}, {"api_name": "numpy.eye", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.ix_", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.ix_", "line_number": 88, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_qubit_hamiltonian", "line_number": 89, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 102, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 103, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 110, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 112, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_qubit_operator", "line_number": 113, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_qubit_operator", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 127, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 128, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 130, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.utils.hermitian_conjugated", "line_number": 131, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_qubit_operator", "line_number": 132, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_qubit_operator", "line_number": 133, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 147, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 151, "usage_type": "call"}, {"api_name": "pyscf.gto.M", "line_number": 165, "usage_type": "call"}, {"api_name": "pyscf.gto", "line_number": 165, "usage_type": "name"}, {"api_name": "pyscf.scf.RHF", "line_number": 168, "usage_type": "call"}, {"api_name": "pyscf.scf", "line_number": 168, "usage_type": "name"}, {"api_name": "numpy.eye", "line_number": 170, "usage_type": "call"}, {"api_name": "pyscf.ao2mo.restore", "line_number": 171, "usage_type": "call"}, {"api_name": "pyscf.ao2mo", "line_number": 171, "usage_type": "name"}, {"api_name": "pyscf.fci.FCI", "line_number": 175, "usage_type": "call"}, {"api_name": "pyscf.fci", "line_number": 175, "usage_type": "name"}, {"api_name": "numpy.eye", "line_number": 180, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_qubit_hamiltonian", "line_number": 183, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 195, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 218, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 226, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 234, "usage_type": "call"}, {"api_name": "numpy.einsum", "line_number": 250, "usage_type": "call"}, {"api_name": "numpy.einsum", "line_number": 251, "usage_type": "call"}, {"api_name": "numpy.einsum", "line_number": 252, "usage_type": "call"}, {"api_name": "numpy.einsum", "line_number": 253, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.unitiy_mo_coeff_format", "line_number": 259, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 260, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 261, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 262, "usage_type": "call"}, {"api_name": "functools.reduce", "line_number": 263, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 263, "usage_type": "attribute"}, {"api_name": "numpy.ix_", "line_number": 265, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 269, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.utils.hermitian_conjugated", "line_number": 270, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 272, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_qubit_operator", "line_number": 280, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.unitiy_mo_coeff_format", "line_number": 285, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 286, "usage_type": "call"}, {"api_name": "functools.reduce", "line_number": 287, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 287, "usage_type": "attribute"}, {"api_name": "numpy.ix_", "line_number": 289, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 293, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.utils.hermitian_conjugated", "line_number": 294, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_qubit_operator", "line_number": 299, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_qubit_operator", "line_number": 300, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 305, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 306, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 308, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 309, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_qubit_operator", "line_number": 315, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_qubit_operator", "line_number": 316, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 328, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 329, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 334, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 346, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 348, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.FermionOperator", "line_number": 349, "usage_type": "call"}, {"api_name": "mindquantum.core.operators.utils.hermitian_conjugated", "line_number": 352, "usage_type": "call"}, {"api_name": "FerOp_QubitOp.get_qubit_operator", "line_number": 359, "usage_type": "call"}]} +{"seq_id": "6497735880", "text": "import re\nfrom os import path\n\nfrom gi.repository import Gst\n\nfrom galicaster.recorder import base\nfrom galicaster.recorder.utils import get_videosink, get_audiosink\n\nvideostr = (' ndivideosrc name=gc-ndi-src ! queue ! videoconvert ! videobox name=gc-ndi-videobox top=0 bottom=0 ! videorate ! '\n ' tee name=gc-ndi-tee ! queue ! caps-preview ! gc-vsink '\n ' gc-ndi-tee. ! queue ! valve drop=false name=gc-ndi-valve ! videoconvert ! queue ! '\n ' gc-ndi-enc ! queue ! gc-ndi-mux ! '\n ' queue ! filesink name=gc-ndi-sink async=false')\n\naudiostr = ( #AUDIO\n ' ndiaudiosrc name=gc-ndi-audiosrc ! queue ! '\n ' audiorate ! volume name=gc-ndi-volumeinput ! audioamplify name=gc-ndi-amplify amplification=1 ! decodebin async-handling=true ! '\n ' tee name=gc-ndi-audiotee ! queue ! '\n ' level name=gc-ndi-level message=true interval=100000000 ! '\n ' volume name=gc-ndi-volume ! queue ! gc-asink '\n # REC AUDIO\n ' gc-ndi-audiotee. ! queue ! valve drop=false name=gc-ndi-audio-valve ! '\n ' audioconvert ! gc-ndi-audioenc ! queue ! gc-ndi-mux. '\n)\n\n\nclass GCndi(Gst.Bin, base.Base):\n\n\n order = [\"name\",\"flavor\",\"location\",\"file\",\"caps\",\n \"videoencoder\", \"muxer\", \"caps-preview\"]\n\n gc_parameters = {\n \"name\": {\n \"type\": \"text\",\n \"default\": \"NDI\",\n \"description\": \"Name assigned to the device\",\n },\n \"flavor\": {\n \"type\": \"flavor\",\n \"default\": \"presenter\",\n \"description\": \"Opencast flavor associated to the track\",\n },\n \"location\": {\n \"type\": \"text\",\n \"default\": None,\n \"description\": \"NDI stream ip or name\",\n },\n \"file\": {\n \"type\": \"text\",\n \"default\": \"CAMERA.avi\",\n \"description\": \"The file name where the track will be recorded.\",\n },\n \"caps\": {\n \"type\": \"caps\",\n \"default\": \"video/x-raw,framerate=20/1,width=640,height=480\",\n # image/jpeg,framerate=10/1,width=640,height=480\",\n \"description\": \"Forced capabilities\",\n },\n \"audio\": {\n \"type\": \"boolean\",\n \"default\": \"False\",\n \"description\": \"Activate NDI audio\",\n },\n \"vumeter\": {\n \"type\": \"boolean\",\n \"default\": \"True\",\n \"description\": \"Activate Level message\",\n },\n \"player\": {\n \"type\": \"boolean\",\n \"default\": \"True\",\n \"description\": \"Enable sound play\",\n },\n \"amplification\": {\n \"type\": \"float\",\n \"default\": 1.0,\n \"range\": (1.0,10),\n \"description\": \"Audio amplification\",\n },\n \"videoencoder\": {\n \"type\": \"text\",\n \"default\": \"x264enc pass=5 quantizer=22 speed-preset=4\",\n \"description\": \"Gstreamer encoder element used in the bin\",\n },\n \"audioencoder\": {\n \"type\": \"text\",\n \"default\": \"lamemp3enc target=1 bitrate=192 cbr=true\",\n \"description\": \"Gstreamer audio encoder element used in the bin\",\n },\n \"muxer\": {\n \"type\": \"text\",\n \"default\": \"avimux\",\n \"description\": \"Gstreamer encoder muxer used in the bin\",\n },\n \"videosink\" : {\n \"type\": \"select\",\n \"default\": \"xvimagesink\",\n \"options\": [\"xvimagesink\", \"ximagesink\", \"autovideosink\", \"fpsdisplaysink\",\"fakesink\"],\n \"description\": \"Video sink\",\n },\n \"audiosink\" : {\n \"type\": \"select\",\n \"default\": \"pulsesink\",\n \"options\": [\"autoaudiosink\", \"alsasink\", \"pulsesink\", \"fakesink\"],\n \"description\": \"Audio sink\",\n },\n \"caps-preview\" : {\n \"type\": \"text\",\n \"default\": None,\n \"description\": \"Caps-preview\",\n },\n\n }\n\n is_pausable = False\n has_audio = True\n has_video = True\n\n __gstdetails__ = (\n \"Galicaster NDI Bin\",\n \"Generic/Video\",\n \"Generice bin to NDI interface devices\",\n \"Teltek Video Research\",\n )\n\n def __init__(self, options={}):\n base.Base.__init__(self, options)\n Gst.Bin.__init__(self)\n\n pipestr = videostr\n gcvideosink = get_videosink(videosink=self.options['videosink'], name='sink-'+self.options['name'], properties={\"sync\":\"true\"})\n gcaudiosink = get_audiosink(audiosink=self.options['audiosink'], name='sink-audio-'+self.options['name'], properties={\"sync\":\"true\"})\n aux = (pipestr.replace('gc-vsink', gcvideosink)\n .replace('gc-ndi-enc', self.options['videoencoder'])\n .replace('gc-ndi-mux', self.options['muxer'] + \" name=gc-ndi-mux\"))\n\n if self.options[\"audio\"]:\n self.has_audio = True\n aux += audiostr\n aux = aux.replace('gc-asink', gcaudiosink)\n aux = aux.replace('gc-ndi-audioenc', self.options['audioencoder'])\n\n else:\n self.has_audio = False\n\n if self.options[\"caps-preview\"]:\n aux = aux.replace(\"caps-preview !\",\"videoscale ! videorate ! \"+self.options[\"caps-preview\"]+\" !\")\n else:\n aux = aux.replace(\"caps-preview !\",\"\")\n\n # aux = (' ndivideosrc stream-name=\"GC-DEV2 (OBS)\" ! capsfilter name=gc-ndi-filter ! videobox name=gc-ndi-videobox top=0 bottom=0 ! videorate ! tee name=gc-ndi-tee ! xvimagesink name=sink-Webcam async=false qos=true force-aspect-ratio=true gc-ndi-tee. ! queue ! valve drop=false name=gc-ndi-valve ! videoconvert ! x264enc pass=5 quantizer=22 speed-preset=4 ! queue ! avimux name=gc-ndi-mux ! queue ! filesink location=/tmp/test.avi async=false ndiaudiosrc ! queue ! decodebin ! audiorate ! volume name=gc-ndi-volumeinput ! audioamplify name=gc-ndi-amplify amplification=1 ! tee name=gc-ndi-audiotee ! queue ! level name=gc-ndi-level message=true interval=100000000 ! volume name=gc-ndi-volume ! queue ! autoaudiosink async=false qos=true gc-ndi-audiotee. ! queue ! valve drop=false name=gc-ndi-audio-valve ! decodebin ! audioconvert ! lamemp3enc target=1 bitrate=192 cbr=true ! queue ! gc-ndi-mux.')\n\n #bin = Gst.parse_bin_from_description(aux, True)\n bin = Gst.parse_launch(\"( {} )\".format(aux))\n self.add(bin)\n\n test_ip = re.compile(\"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]):[0-9]+$\")\n if self.options['location']:\n if test_ip.match(self.options['location']):\n self.set_option_in_pipeline('location', 'gc-ndi-src', 'ip')\n self.set_option_in_pipeline('location', 'gc-ndi-audiosrc', 'ip')\n else:\n self.set_option_in_pipeline('location', 'gc-ndi-src', 'stream-name')\n self.set_option_in_pipeline('location', 'gc-ndi-audiosrc', 'stream-name')\n\n self.set_value_in_pipeline(path.join(self.options['path'], self.options['file']), 'gc-ndi-sink', 'location')\n\n # Audio properties\n if self.has_audio:\n if \"player\" in self.options and self.options[\"player\"] == False:\n self.mute = True\n element = self.get_by_name(\"gc-ndi-volume\")\n element.set_property(\"mute\", True)\n else:\n self.mute = False\n\n if \"vumeter\" in self.options:\n level = self.get_by_name(\"gc-ndi-level\")\n if self.options[\"vumeter\"] == False:\n level.set_property(\"message\", False)\n\n if \"amplification\" in self.options:\n ampli = self.get_by_name(\"gc-ndi-amplify\")\n ampli.set_property(\"amplification\", float(self.options[\"amplification\"]))\n\n\n def changeValve(self, value):\n valve1=self.get_by_name('gc-ndi-valve')\n if self.has_audio:\n valve2=self.get_by_name('gc-ndi-audio-valve')\n valve2.set_property('drop', value)\n valve1.set_property('drop', value)\n\n def getVideoSink(self):\n return self.get_by_name('sink-' + self.options['name'])\n\n def getAudioSink(self):\n return self.get_by_name('sink-audio-' + self.options['name'])\n\n def getSource(self):\n return self.get_by_name('gc-ndi-src')\n\n def mute_preview(self, value):\n if not self.mute:\n element = self.get_by_name(\"gc-ndi-volume\")\n element.set_property(\"mute\", value)\n\n def send_event_to_src(self, event):\n src1 = self.get_by_name('gc-ndi-src')\n src1.send_event(event)\n src2 = self.get_by_name('gc-ndi-audiosrc')\n if src2:\n src2.send_event(event)\n\n\n def disable_input(self):\n src1 = self.get_by_name('gc-ndi-videobox')\n src1.set_properties(top = -10000, bottom = 10000)\n if self.has_audio:\n element = self.get_by_name(\"gc-ndi-volumeinput\")\n element.set_property(\"mute\", True)\n\n def enable_input(self):\n src1 = self.get_by_name('gc-ndi-videobox')\n src1.set_property('top',0)\n src1.set_property('bottom',0)\n if self.has_audio:\n element = self.get_by_name(\"gc-ndi-volumeinput\")\n element.set_property(\"mute\", False)\n\n def disable_preview(self):\n src1 = self.get_by_name('sink-'+self.options['name'])\n src1.set_property('saturation', -1000)\n src1.set_property('contrast', -1000)\n if self.has_audio:\n element = self.get_by_name(\"gc-ndi-volume\")\n element.set_property(\"mute\", True)\n\n def enable_preview(self):\n src1 = self.get_by_name('sink-'+self.options['name'])\n src1.set_property('saturation',0)\n src1.set_property('contrast',0)\n if self.has_audio:\n element = self.get_by_name(\"gc-ndi-volume\")\n element.set_property(\"mute\", False)\n", "repo_name": "teltek/Galicaster", "sub_path": "galicaster/recorder/bins/ndi.py", "file_name": "ndi.py", "file_ext": "py", "file_size_in_byte": 9927, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 35, "dataset": "github-code", "pt": "27", "api": [{"api_name": "gi.repository.Gst.Bin", "line_number": 27, "usage_type": "attribute"}, {"api_name": "gi.repository.Gst", "line_number": 27, "usage_type": "name"}, {"api_name": "galicaster.recorder.base.Base", "line_number": 27, "usage_type": "attribute"}, {"api_name": "galicaster.recorder.base", "line_number": 27, "usage_type": "name"}, {"api_name": "galicaster.recorder.base.Base.__init__", "line_number": 128, "usage_type": "call"}, {"api_name": "galicaster.recorder.base.Base", "line_number": 128, "usage_type": "attribute"}, {"api_name": "galicaster.recorder.base", "line_number": 128, "usage_type": "name"}, {"api_name": "gi.repository.Gst.Bin.__init__", "line_number": 129, "usage_type": "call"}, {"api_name": "gi.repository.Gst.Bin", "line_number": 129, "usage_type": "attribute"}, {"api_name": "gi.repository.Gst", "line_number": 129, "usage_type": "name"}, {"api_name": "galicaster.recorder.utils.get_videosink", "line_number": 132, "usage_type": "call"}, {"api_name": "galicaster.recorder.utils.get_audiosink", "line_number": 133, "usage_type": "call"}, {"api_name": "gi.repository.Gst.parse_launch", "line_number": 155, "usage_type": "call"}, {"api_name": "gi.repository.Gst", "line_number": 155, "usage_type": "name"}, {"api_name": "re.compile", "line_number": 158, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 167, "usage_type": "call"}, {"api_name": "os.path", "line_number": 167, "usage_type": "name"}]} +{"seq_id": "39609088283", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Exercise 2 (Using Linear Regression). \n# Your task is to predict the quality score of red wine from its physicochemical properties using linear regression. You are going to learn a linear model t = f(x, w) = w0 + w1x1 + w2x2 + . . . + wDxD = wT x, where t is the predicted output variable (quality score), x = (1, x1, x2, . . . , xD) T is the vector-valued\n# input variable (physicochemical properties), and w = (w0, w1, . . . , wD) are the free parameters. The\n# parameters wi define the regression model, and once they have been estimated, the model can be used\n# to predict outputs for new input values x0.\n# a) Implement linear regression, call your function multivarlinreg(), a template is provided in\n# the multivarlinreg.py file. Your code should load the data matrix X containing the input\n# variables, as well as the output vector t, and output an estimate of the free parameters in the\n# model, that is the wi\n# in the form of the vector w. Remember the offset parameter w0. You\n# should not use a built-in function for regression.\n# b) Run your regression function on a version of the training set that only contains the first feature\n# (fixed acidity). Please report your weights. What can you learn from them?\n# c) Run your regression function on all the features in the training set and report your estimated\n# parameters wi\n# . What do they tell you about how the different physiochemical properties relate\n# to the wine quality?\n\n# In[1]:\n\n\n# import packages, data, & set figure sizes\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = (10,6)\n\ndataWineTrain = np.loadtxt('redwine_training.txt')\ndataWineTest = np.loadtxt('redwine_testing.txt')\n\nXWineTrain = dataWineTrain[:,:-1]\nYWineTrain =dataWineTrain[:,-1]\n\nXWineTest = dataWineTest[:,:-1]\nYWineTest =dataWineTest[:,-1]\n\nminstX = np.loadtxt('MNIST_179_digits.txt')\nminstY = np.loadtxt('MNIST_179_labels.txt')\n\nminstXTrain = minstX[:900]\nminstYTrain = minstY[:900]\n\nminstXTest = minstX[900:]\nminstYTest = minstY[900:]\n\n\n# a) Implement linear regression, call your function multivarlinreg(), a template is provided in\n# the multivarlinreg.py file. Your code should load the data matrix X containing the input\n# variables, as well as the output vector t, and output an estimate of the free parameters in the\n# model, that is the wi\n# in the form of the vector w. Remember the offset parameter w0. You\n# should not use a built-in function for regression.\n\n# In[2]:\n\n\n# input: 1) X: the independent variables (data matrix), an (N x D)-dimensional matrix, as a numpy array\n# 2) y: the dependent variable, an N-dimensional vector, as a numpy array\n#\n# output: 1) the regression coefficients, a (D+1)-dimensional vector, as a numpy array\n#\n# note: remember to either expect an initial column of 1's in the input X, or to append this within your code\ndef multivarlinreg(X, y):\n X = np.array(X)\n w = np.array((X.shape[0]))\n \n # add preceding 1 column if not given\n if not np.all(X[0,:] == 1):\n preced = np.ones((X.shape[0], 1))\n X = np.hstack((preced, X))\n \n # compute analytical solution for multivariat lin reg\n w = np.dot((np.linalg.inv(np.dot(X.T,X))),(np.dot(X.T,y)))\n return w\n\n\n# b) Run your regression function on a version of the training set that only contains the first feature (fixed acidity). Please report your weights. What can you learn from them?\n\n# In[3]:\n\n\n# run on only first column (fixed acidity)\nXWineTrainReduced = XWineTrain[:,:1]\nprint(f'Parameters w_i: {multivarlinreg(XWineTrainReduced, YWineTrain)}')\n\n# TODO: what can you learn from them?\n\n\n# c) Run your regression function on all the features in the training set and report your estimated\n# parameters wi\n# . What do they tell you about how the different physiochemical properties relate\n# to the wine quality?\n\n# In[4]:\n\n\n# run on all the data set\nprint(f'Parameters w_i: {multivarlinreg(XWineTrain, YWineTrain)}')\n\n# TODO: What do they tell you about the different properties & how they relate to the wine quality?\n\n\n# # Exercise 3 (Evaluating Linear Regression)\n# a) Implement the root means square error as function rmse() for the linear model. A template is provided in the rmse.py file . For a set of known input-output values (x1, y1), . . . ,(xN , yN ), where yi is the recorded output value associated to the i th data point xi in the dataset, the parameter w allows to compute f(xi, w), the output value associated to the input xi as predicted by your regression model. Your code should take as input the predicted values f(xi, w) and ground truth output values yi. You should not use a built-in function for RMSE.\n\n# In[5]:\n\n\n# input: 1) f: the predicted values of the dependent output variable, an N-dimensional vector, as a numpy array\n# 2) t: the ground truth values of dependent output variable, an N-dimensional vector, as a numpy array\n#\n# output: 1) the root mean square error (rmse) as a 1 x 1 numpy array\n\ndef rmse(f, t):\n error_sum = 0\n for i in range(len(f)):\n error_sum += (t[i] - f[i])**2\n return np.sqrt(error_sum/len(f))\n\n\n# In[6]:\n\n\ndef predict(test, weight):\n return weight[0] + np.dot(weight[1:], test.T)\n\n\n# b) Build the regression model for 1-dimensional input variables using the training set as in 1b).\n# Use the first feature for the test set to compute the RMSE of your model.\n\n# In[7]:\n\n\n# build regression model\nweight_first_col = multivarlinreg(XWineTrainReduced, YWineTrain)\n# get first feature of test set\nXWineTestReduced = XWineTest[:,:1]\npredict_first_col = predict(XWineTestReduced, weight_first_col)\n# compute RMSE\nprint(f'RMSE of first parameter \"fixed acidity\": {round(rmse(predict_first_col, YWineTest), 2)}')\n\n\n# c) Build the regression model for the full 11-dimensional input variables using the training set as in\n# 1c). Use the full-dimensional test set to compute the RMSE of this model. How does it compare\n# to your answer from b)?\n\n# In[8]:\n\n\n# build regression model\nweights_full = multivarlinreg(XWineTrain, YWineTrain)\npredict_full = predict(XWineTest, weights_full)\n# compute RMSE\nprint(f'RMSE of all parameters: {round(rmse(predict_full, YWineTest), 2)}')\n\n\n# # Exercise 5 (Applying random forrest ). \n# Train a random forest with 50 trees on IDSWeedCropTrain.csv from the previous assignment(s). Test the resulting classifier using the data in IDSWeedCropTest.csv.\n\n# In[9]:\n\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score\n\n# read in the data\nIDSTrain = np.loadtxt('IDSWeedCropTrain.csv', delimiter=',')\nIDSTest = np.loadtxt('IDSWeedCropTest.csv', delimiter=',')\n\n# split input variable & labels\nXIDSTrain = IDSTrain[:,:-1]\nYIDSTrain = IDSTrain[:,-1]\nXIDSTest = IDSTest[:,:-1]\nYIDSTest = IDSTest[:,-1]\n\nclf = RandomForestClassifier(n_estimators=50, random_state=0)\n\n\n# In[10]:\n\n\n# fit model, make prediction, print accuracy\nclf.fit(XIDSTrain, YIDSTrain)\npredictions = clf.predict(XIDSTest)\nprint(f'Accuracy of sklearn.ensemble.RandomForestClassifier on IDS Weed Crop data set: {round(accuracy_score(YIDSTest, predictions), 3)}')\n\n\n# # Exercise 6 (Gradient descent & learning rates).\n# Apply gradient descent to find the minimum of the\n# function f(x) = e^(−x/2) + 10x^2\n# \n# Detailed instructions:\n# 1. Compute the derivative of the function f.\n# 2. Apply gradient descent with learning rates η = 0.1, 0.01, 0.001, 0.0001.3\n# 3. For each of the learning rates do the following:\n# \n# (a) Take x = 1 as a starting point.\n# \n# (b) Visualize the tangent lines and gradient descent steps for the first three iterations (produce\n# 4 plots for your report corresponding to gradient descent with the four learning rates). The\n# first tangent line should be at the initial point x = 1.\n# \n# (c) Visualize gradient descent steps for the first 10 iterations (another 4 plots; no visualization\n# of tangent lines in this case).\n# \n# (d) Run the algorithm until the magnitude of the gradient falls below 10−10 or the algorithm\n# has exceeded 10,000 iterations. Report the number of iterations it took the algorithm to\n# converge and the function value at the final iteration (4 × 2 values corresponding to the\n# four learning rates).\n\n# In[11]:\n\n\ndef graddesc(rate, f, init=1, max_iters=10000):\n curr_min = init\n old_min = 0\n iters = 0\n precision = 0.000001\n x_coor = np.array(())\n \n while abs(curr_min - old_min) > precision and iters < max_iters:\n \n x_coor = np.append(x_coor, curr_min)\n \n # TODO: what does the gradient thing do?\n # TODO: what does the learning rate do?\n \n old_min = curr_min\n curr_min = old_min - (rate * f(old_min))\n iters += 1\n \n return x_coor, iters\n\n\n# In[12]:\n\n\ndef make_tangent(x_rang, x_val, func, deriv):\n y = np.array(len(x_rang))\n a = deriv(x_val)\n x = x_range-x_val\n b = func(x_val)\n y = a * x + b\n return y\n\n\n# In[13]:\n\n\nx_range = np.arange(-1.5, 1.5, 0.1)\n\nfig1, axes1 = plt.subplots(nrows=2, ncols=2)\nfig1.set_size_inches(10, 10)\n\nfig2, axes2 = plt.subplots(nrows=2, ncols=2)\nfig2.set_size_inches(10, 10)\n\nlearn_rates = [0.1, 0.01, 0.001, 0.0001]\nf = lambda x: np.exp(-x/2) + 10*x**2\ng = lambda x: 20*x - np.exp(-x/2)/2\n\nfor i, rate in enumerate(learn_rates):\n ax1 = axes1[i//2, i%2]\n ax2 = axes2[i//2, i%2]\n \n # plot original function f\n ax1.plot(x_range, f(x_range), label='f(x)')\n ax2.plot(x_range, f(x_range), label='f(x)')\n x_coor, num_iters = graddesc(rate, g)\n print(f'Function value for learning rate {rate} = ({round(f(x_coor[-1]), 10)}) after {num_iters} iterations')\n \n # fill gradient descent steps for both plots\n ax1.scatter(x_coor[:3], f(x_coor[:3]), c='r', label='Gradient steps')\n ax2.scatter(x_coor[:10], f(x_coor[:10]), c='r', label='Gradient steps')\n \n # plot tangent lines to first plot\n for i in range(3):\n ax1.plot(x_range, make_tangent(x_range, x_coor[i], f, g), c='g', label=f'Tangent line {i+1}')\n \n # set y lims & grid\n ax1.grid()\n ax1.legend()\n ax1.set_ylim(-1,20)\n ax2.grid()\n ax2.legend()\n ax2.set_ylim(-1,20)\n \n # set axes labels & titel\n fig1.suptitle('Visualization of first three gradient descent steps\\n+ respective tangent lines for 4 different learning rates')\n ax1.set_xlabel('x') \n ax1.set_ylabel('y')\n ax1.set_title(f'Learning rate {rate}')\n \n fig2.suptitle('Visualization of first 10 gradient descent steps for 4 different learning rates')\n ax2.set_xlabel('x') \n ax2.set_ylabel('y')\n ax2.set_title(f'Learning rate {rate}')\n \nplt.show()\n\n\n# # Logistic Regression\n\n# # Exercise 7 - Logistic regression implementation\n# In this exercise you will implement, run and test logistic regression on two simple data sets, made of\n# two classes each. They come from Fisher’s Iris dataset and are described below.\n\n# 1. Make a scatter plot of each dataset, with point color depending on classes. What do you observe?\n\n# In[14]:\n\n\n# import cmap\n# TODO INDEX DESCRIPTION VALUES\nblues = plt.get_cmap('Blues')\n\nfig, ax = plt.subplots(nrows=1, ncols=2)\nfig.set_size_inches(20, 10)\n\n# import data\niris2D2Train = np.loadtxt('Iris2D2_train.txt')\niris2D2Test = np.loadtxt('Iris2D2_test.txt')\n\niris2D1Train = np.loadtxt('Iris2D1_train.txt')\niris2D1Test = np.loadtxt('Iris2D1_test.txt')\n\ncumulative2D2 = np.vstack((iris2D2Train, iris2D2Test))\ncumulative2D1 = np.vstack((iris2D1Train, iris2D1Test))\n\nYcumulative2D2 = cumulative2D2[:,-1]\nYcumulative2D1 = cumulative2D1[:,-1]\n\nidx0 = np.where(Ycumulative2D2==0)\nidx1 = np.where(Ycumulative2D2==1)\n\nidx2 = np.where(Ycumulative2D1==0)\nidx3 = np.where(Ycumulative2D1==1)\n\nax[0].scatter(cumulative2D1[idx2,0], cumulative2D1[idx2,1], color=blues(0.3), label='Iris virginica')\nax[0].scatter(cumulative2D1[idx3,0], cumulative2D1[idx3,1], color=blues(0.8), label='Iris setosa')\nax[0].set_title('Iris2D1');\nax[0].set_xlabel('length of sepals') \nax[0].set_ylabel('width of sepals')\nax[0].grid(True)\nax[0].legend()\n\nax[1].scatter(cumulative2D2[idx0,0], cumulative2D2[idx0,1], color=blues(0.3), label='Iris virginica')\nax[1].scatter(cumulative2D2[idx1,0], cumulative2D2[idx1,1], color=blues(0.8), label='Iris versicolor')\nax[1].set_title('Iris2D2');\nax[1].set_xlabel('length of sepals') \nax[1].set_ylabel('length of petals')\nax[1].grid(True)\nax[1].legend()\n\nfig.suptitle('Data points of cumulative train & test data sets for Iris data');\nplt.show()\n\n\n# 2. Implement logistic regression as presented in the lectures. Your function should take as input\n# the training set data matrix, the training set label vector, and the test set data matrix.\n\n# ### $$ \\nabla_w E_{in} = -\\frac{1}{N}\\sum_{n=1}^N \\frac{y_n e^{-y_n w^\\top x_n}}{1 + e^{-y_n w^\\top x_n}}x_n $$\n\n# In[15]:\n\n\ndef log1px(x):\n return (x >= 0)*x + (np.log(1 + np.exp(-np.abs(x))))\n\ndef logistic(x):\n xp = (x > 0) * 1.0\n xm = (x <= 0) * 1.0\n return xm * (np.exp(x * xm))/(1 + np.exp(x * xm)) + xp * (1/(1 + np.exp(-xp * x)))\n\n\n# In[16]:\n\n\ndef logistic_insample(X, y, w):\n N = X.shape[0]\n return np.log(1 + np.exp(-y * (X @ w))).sum()/N \n\n\n# In[17]:\n\n\ndef logistic_gradient(X, y, w):\n N, _ = X.shape\n \n curr = y * np.exp(-y*(np.dot(X, w))) / (1 + (np.exp(-y*(np.dot(X, w)))))\n curr = curr.reshape(N, 1)\n \n return -np.mean(curr*X, axis=0)\n\n\n# In[18]:\n\n\ndef log_reg(Xorig, y, max_iter, tol=1e-5, step=1e-2): \n \n # X is a d by N data matrix of input values\n N, d = Xorig.shape\n X = np.hstack((np.ones((N, 1)), Xorig))\n \n # y is a N by 1 matrix of target values -1 and 1\n y = np.array((y-.5) * 2)\n \n # Initialize weights at time step 0 \n w = 0.1 * np.random.randn(d + 1)\n \n # Compute value of logistic log likelihood\n value = logistic_insample(X, y, w)\n \n # Keep track of function values\n E_in = [value]\n G_norm= []\n converged = False\n for num_iter in range(max_iter):\n # Compute gradient at current w, and take \n # its opposite as descent direction\n p = logistic_gradient(X, y, w)\n \n # Update weights\n w_new = w-step*p\n \n # Determine whether we have converged: Is gradient norm below\n # tolerance?\n \n g_norm = np.linalg.norm(p)\n G_norm.append(g_norm)\n if g_norm < tol:\n # converged!\n converged = True\n break\n \n w = w_new\n value = logistic_insample(X, y, w)\n E_in.append(value)\n \n if not converged:\n # We ran all the iterations, not reching the tolerance\n print(f\"The descent procedure did not converge after {max_iter} iterations, last gradient norm was {g_norm}.\")\n else:\n # we did actually converge!\n print(f'The descent converged after {num_iter} iterations with a gradient magnitude {g_norm}.')\n return w, E_in, G_norm\n\n\n# In[19]:\n\n\ndef log_pred(Xorig, w):\n N, d = Xorig.shape\n # add a first column with ones\n X = np.hstack((np.ones((N, 1)), Xorig))\n p = logistic(X @ w)\n pred = -(p < 0.5).astype(int) + (p >= 0.5).astype(int)\n return p, pred\n\n\n# In[20]:\n\n\ndef get_acc(x_train, x_test, y_train, y_test, name):\n N_train = x_train.shape[0]\n N_test = x_test.shape[0]\n \n w, E, G = log_reg(x_train, y_train, 100000, tol=0.5e-5)\n \n p_val, train_pred_cl = log_pred(x_train, w)\n y_train = (y_train-.5) * 2\n train_err_sum = (np.abs(train_pred_cl-y_train)/2).sum()\n train_err_rate = train_err_sum/N_train\n \n p_val, test_pred_cl = log_pred(x_test, w)\n y_test = (y_test-.5) * 2\n test_err_sum = (np.abs(test_pred_cl-y_test)/2).sum()\n test_err_rate = test_err_sum/N_test\n \n print(f'Logistic regression for {name}:\\nTrain error rate: {round(train_err_rate, 3)}\\nTest error rate: {round(test_err_rate, 3)}\\nParameters: {w}\\n')\n \n\n\n# In[21]:\n\n\niris2D2Train_X = iris2D2Train[:,:-1]\niris2D2Train_Y = iris2D2Train[:,-1]\niris2D2Test_X = iris2D2Test[:,:-1]\niris2D2Test_Y = iris2D2Test[:,-1]\n\niris2D1Train_X = iris2D1Train[:,:-1]\niris2D1Train_Y = iris2D1Train[:,-1]\niris2D1Test_X = iris2D1Test[:,:-1]\niris2D1Test_Y = iris2D1Test[:,-1]\n\n\n# In[22]:\n\n\nget_acc(iris2D2Train_X, iris2D2Test_X, iris2D2Train_Y, iris2D2Test_Y, 'Iris 2D2')\nget_acc(iris2D1Train_X, iris2D1Test_X, iris2D1Train_Y, iris2D1Test_Y, 'Iris 2D1')\n\n\n# # Exercise 9 - Clustering and classification I\n# In this exercise, you will use some of the algorithms you\n# used in previous assignments for clustering and classifying the dataset.\n# \n# \n# a) Run the k-Means algorithm with k = 3 to cluster the dataset. Are the results meaningful? As\n# the k-means algorithm will return labels 0, 1 and 2, you cannot compare them directly with the\n# 1, 7 and 9 from the label file. Count instead the proportion of 1s, 7s and 9s in each cluster. For\n# that you may want to prepend the label data to the image data, but not use it in the k-means\n# algorithm, e.g., by fitting all but the first column.\n# \n\n# In[23]:\n\n\nfrom sklearn.cluster import KMeans\nfrom collections import Counter\n\nkmeans = KMeans (n_clusters=3, random_state=42, algorithm='full', n_init=1)\nkmeans.fit(minstXTrain)\nreal_proportion = Counter(minstYTrain)\ntrue_labels = np.vstack((minstYTrain, kmeans.labels_))\npredict_proportion = Counter(zip(true_labels[0], true_labels[1]))\ncluster_proportion = Counter(kmeans.labels_)\ncenters = kmeans.cluster_centers_\nprint(f'predicted proportion: {cluster_proportion}\\nreal proportion: {real_proportion}\\nproportion per true label: {predict_proportion}')\n\nfig, ax = plt.subplots(nrows=1, ncols=3)\nfor i in range(3):\n this_digit = centers[i].reshape(28, 28)\n ax[i].imshow(this_digit,cmap='Greys_r',interpolation='none')\n ax[i].set_title(f\"Cluster center {i+1}\")\n ax[i].set_xlabel('num of pixels')\n ax[i].set_ylabel('num of pixels')\nfig.suptitle('Cluster Center for K-Means clustering of MNIST_179_digits data set');\nplt.show()\n\n\n# b) Classification. Train a k-NN classifier on the dataset, using n−fold validation to obtain the\n# optimal k. Report test accuracy. Note that if you use KNeighborsClassifier, you can pass it\n# the true labels as labels.\n\n# In[24]:\n\n\nfrom sklearn.model_selection import KFold\nfrom sklearn.neighbors import KNeighborsClassifier\n\ndef get_kbest_and_acc(ks, x_train, x_test, y_train, y_test, split=5):\n # create indices for CV\n cv = KFold(n_splits=split)\n # loop over CV folds\n acc_score = np.zeros((len(ks)))\n for i, k in enumerate(ks):\n # set up classifier with given k\n neigh = KNeighborsClassifier(n_neighbors=k)\n \n # split data and evaluate accuracy\n for train, test in cv.split(x_train):\n XTrainCV, XTestCV, YTrainCV, YTestCV = x_train[train], x_train[test], y_train[train], y_train[test]\n neigh.fit(XTrainCV, YTrainCV)\n acc_score[i] += 1 - (accuracy_score(YTestCV, neigh.predict(XTestCV)))\n acc_score[i] = acc_score[i] / split\n \n # find minimum acc & get value for kbest respectively\n idx_min = np.argmin(acc_score)\n kbest = ks[idx_min]\n \n # create new KNN classifier with freshly found kbest value\n neigh_test = KNeighborsClassifier(n_neighbors=kbest)\n neigh_test.fit(x_train, y_train)\n accTest = accuracy_score(y_test, neigh_test.predict(x_test))\n \n return kbest, accTest\n\nk_list = [1, 3, 5, 7, 9, 11]\nkb, acc = get_kbest_and_acc(k_list, minstXTrain, minstXTest, minstYTrain, minstYTest)\nprint(f'Accuracy for MNIST_179_digits data set: {round(acc,3)} with k_best={kb}')\n\n\n# # Exercise 10 - Clustering and classification after dimensionality reduction.\n# In the second part, you will use dimensionality reduction (i.e. PCA here) to first reduce the dimensionality, and then perform clustering and classification.\n\n# a) Compute the PCA of the training data. Plot the cumulative variance (in %) w.r.t. the principal\n# components.\n\n# In[25]:\n\n\n# function from assignment 3\ndef pca(data):\n # subtract off the mean for each dimension\n data_mean = data - np.mean(data, 0)\n \n # transpose data & calculate covariance matrix\n data_covar = np.cov(data_mean.T)\n \n # eigenvalues and eigenvectors\n data_eigenval, data_eigenvec = np.linalg.eigh(data_covar)\n \n # reverse with same indexing\n idx = data_eigenval.argsort()[::-1] \n data_eigenval = data_eigenval[idx]\n data_eigenvec = data_eigenvec[:,idx]\n \n return data_eigenval, data_eigenvec, np.mean(data, axis=0)\n\n\n# In[26]:\n\n\n# multidimensional scaling for input data & d number of dimensions\n# taken from assignment 3\ndef mds(data, d):\n # get PCA components\n variance, components, mean = pca(data)\n # slice number of PCs\n components = components[:,:d]\n # compute dot product to get projection\n matrix = np.dot(data, components)\n # compute cumulative variance\n cum_var = round(variance[:d].sum() * 100 / variance.sum(), 2)\n \n return matrix, cum_var\n\n\n# b) Run the k-Means algorithm, again with k = 3 to cluster the data projected on the first principal\n# components. Experiment with 20 and 200 components. Count the proportion of 1s, 7s and\n# 9s in each cluster. Again, you should prepend the labels to the projected data on the principal\n# components as first column, but take care of not using it in k-means. Compare with the non-PCA\n# clustering result in the previous exercise.\n\n# In[27]:\n\n\n# perform pca & calculate squareroots\neigval, eigvec, m = pca(minstXTrain)\nsigma = np.sqrt(eigval[i])\n\ndef print_pca_cluster(num_comp):\n mds_minst, var = mds(minstXTrain, num_comp)\n kmeans_2 = KMeans(n_clusters=3, random_state=42, algorithm='full', n_init=1)\n kmeans_2.fit(mds_minst)\n true_labels = np.vstack((minstYTrain, kmeans_2.labels_))\n predict_proportion = Counter(zip(true_labels[0], true_labels[1]))\n centers = kmeans_2.cluster_centers_\n center_projection = np.dot(centers, eigvec[:,:num_comp].T)\n #center_projection += m\n print(f'predicted proportion: {predict_proportion}')\n\n fig, ax = plt.subplots(nrows=1, ncols=3)\n \n for i in range(3):\n this_digit = center_projection[i].reshape(28,28)\n ax[i].imshow(this_digit,cmap='Greys_r',interpolation='none')\n ax[i].set_title(f\"Cluster center {i+1}\", size=14)\n ax[i].set_xlabel('num of pixels')\n ax[i].set_ylabel('num of pixels')\n \n fig.suptitle(f'Cluster Center for K-Means clustering of first {num_comp} PCs\\non MNIST_179_digits data set', size=16);\n plt.show()\n \n print(f'Cumulative Variance of first {num_comp} PCs: {var}%')\n\n\n# In[28]:\n\n\nx = np.arange(0, len(eigval), 1)\nc_val = np.cumsum(eigval/np.sum(eigval))\nplt.plot(x, c_val*100);\nplt.grid()\nplt.xlabel('Number of PCs')\nplt.ylabel('Cumulative percentage in %')\nplt.title('Cumulative percentage over number of PCs for MNIST_179_digits data set');\nplt.show()\n\n\n# In[29]:\n\n\nprint_pca_cluster(2)\n\n\n# In[30]:\n\n\nprint_pca_cluster(20)\n\n\n# In[31]:\n\n\nprint_pca_cluster(200)\n\n\n# c) Classification. Train a k-NN classifier on the dataset:\n# \n# – Do it using the first 20 principal components. Use n-fold validation to obtain the optimal k. Report test accuracy.\n# \n# – Do it again with the first 200 principal components. Use n-fold validation to obtain the optimal k. Report test accuracy.\n\n# In[32]:\n\n\ndef print_pca_classifier(num_comp):\n XTrain_minst_pca, _ = mds(minstXTrain, num_comp)\n XTest_minst_pca, _ = mds(minstXTest, num_comp)\n kb_pca, acc_pca = get_kbest_and_acc(k_list, XTrain_minst_pca, XTest_minst_pca, minstYTrain, minstYTest)\n print(f'Accuracy for MNIST_179_digits data set\\nwith train data for the first {num_comp} PCs: {round(acc_pca,4)} with k_best={kb}')\n\n\n# In[33]:\n\n\nprint_pca_classifier(20)\n\n\n# In[34]:\n\n\nprint_pca_classifier(200)\n\n\n# In[ ]:\n\n\n\n\n", "repo_name": "ninell-oldenburg/data-science-course", "sub_path": "5-bayes_and_regression/5-bayes_and_regression.py", "file_name": "5-bayes_and_regression.py", "file_ext": "py", "file_size_in_byte": 23784, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "matplotlib.pyplot.rcParams", "line_number": 28, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "numpy.loadtxt", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 75, "usage_type": "attribute"}, {"api_name": "numpy.sqrt", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 169, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 170, "usage_type": "call"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 178, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 187, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 221, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 225, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 241, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 252, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 254, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 254, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 257, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 257, "usage_type": "name"}, {"api_name": "numpy.exp", "line_number": 261, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 262, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 301, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 301, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.get_cmap", "line_number": 317, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 317, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 319, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 319, "usage_type": "name"}, {"api_name": "numpy.loadtxt", "line_number": 323, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 324, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 326, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 327, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 329, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 330, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 335, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 336, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 338, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 339, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 358, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 358, "usage_type": "name"}, {"api_name": "numpy.log", "line_number": 370, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 370, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 370, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 375, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 383, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 383, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 392, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 392, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 395, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 405, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 405, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 408, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 411, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 411, "usage_type": "attribute"}, {"api_name": "numpy.linalg.norm", "line_number": 431, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 431, "usage_type": "attribute"}, {"api_name": "numpy.hstack", "line_number": 457, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 457, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 474, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 479, "usage_type": "call"}, {"api_name": "sklearn.cluster.KMeans", "line_number": 525, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 527, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 528, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 529, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 530, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 534, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 534, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 542, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 542, "usage_type": "name"}, {"api_name": "sklearn.model_selection.KFold", "line_number": 557, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 559, "usage_type": "call"}, {"api_name": "sklearn.neighbors.KNeighborsClassifier", "line_number": 562, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 568, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 572, "usage_type": "call"}, {"api_name": "sklearn.neighbors.KNeighborsClassifier", "line_number": 576, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 578, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 599, "usage_type": "call"}, {"api_name": "numpy.cov", "line_number": 602, "usage_type": "call"}, {"api_name": "numpy.linalg.eigh", "line_number": 605, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 605, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 612, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 626, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 644, "usage_type": "call"}, {"api_name": "sklearn.cluster.KMeans", "line_number": 648, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 650, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 651, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 653, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 657, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 657, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 667, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 667, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 675, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 676, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 676, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 677, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 677, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 678, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 678, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 679, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 679, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 680, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 680, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 681, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 681, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 682, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 682, "usage_type": "name"}]} +{"seq_id": "23800192570", "text": "import boto3\n\naws_access_key_id = 'ASIAYRPWO7O5KIHQE54I'\naws_secret_access_key = 'EZIlK/M84dyDV1gqY0Zp12k2QFL8audwz/xuEAh1'\nregion_name = 'us-east-1'\naws_session_token = 'FwoGZXIvYXdzEBoaDHNRnLCqP5iW+AsCACLAAVHewpyXOJ52B4ffpESE80OFAgF8JJc0QUg3tg/v22KmaNlp7jiNAsO4tKVdNFq4WLHiSwlVCCr6aYXEifXjcC41y8v2bXusd1uA09znnuTO8pMw60y34j+B5sNlhKkisg+D4e/LsEgcX9gEsjOBdM1L4h3pys2V+FgAprBX1DoUFKNMlDcD6D7/n3kCSYWbRxXTnvd1ml15Ri6mWW1BbELpbLFXpOrWhBHAoAosAbH3T/8qdkqwDC9D9nlK4eiSXyidpOClBjItP939uEtQBCHETRU7oBeu13v/no1h/8iitSzaNbICGvEuLMOBwLQVThTwDlLo'\n\n# Create an S3 client\ns3 = boto3.client('s3', aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name,\n aws_session_token=aws_session_token)\n\n # Bucket names\nbucket_names = [\"samplesdatab00927718\", \"tagb00927718\"]\n\n\n# Function to create a bucket with retries\ndef create_bucket(s3_client, bucket_name, retries=2):\n for i in range(retries):\n s3_client.create_bucket(Bucket=bucket_name)\n print(f\"Bucket {bucket_name} created successfully.\")\n return True\n return False\n\n# Create buckets with retries\nfor bucket_name in bucket_names:\n create_bucket(s3, bucket_name)", "repo_name": "akshitpatel3189/cloudProject", "sub_path": "Serverless application with AWS Lambda/bucket_creation.py", "file_name": "bucket_creation.py", "file_ext": "py", "file_size_in_byte": 1207, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "boto3.client", "line_number": 9, "usage_type": "call"}]} +{"seq_id": "32890227117", "text": "__author__ = 'Levonne Key '\n__license__ = 'Apache License, Version 2.0'\n\n# Reference: http://docs.splunk.com/Documentation/Splunk/latest/AdvancedDev/SetupExampleCustom\n\nimport base64\nimport logging\nimport os\nimport shutil\nimport time\n\nimport splunk.admin\n\nTOKEN_DELIMITER = '###'\nlogger = logging.getLogger(__name__)\n\nclass SetupRoutr(splunk.admin.MConfigHandler):\n def setup(self):\n if self.requestedAction == splunk.admin.ACTION_EDIT:\n for arg in [\n 'twitter_consumer_key', 'twitter_consumer_secret',\n 'twitter_access_token', 'twitter_access_token_secret',\n 'tumblr_blogname', 'tumblr_consumer_key',\n 'tumblr_consumer_secret', 'tumblr_access_token',\n 'tumblr_access_token_secret']:\n self.supportedArgs.addOptArg(arg)\n\n def handleList(self, confInfo):\n '''\n Read the initial values of the parameters from the custom file\n routrcreds.conf, and write them to the setup screen. \n '''\n confDict = self.readConf('routrcreds')\n if confDict:\n for stanza, settings in confDict.items():\n compiled_creds = None\n if stanza == 'twittercreds':\n compiled_creds = [\n ['twitter_consumer_key', ''],\n ['twitter_consumer_secret', ''],\n ['twitter_access_token', ''],\n ['twitter_access_token_secret', '']]\n elif stanza == 'tumblrcreds':\n compiled_creds = [\n ['tumblr_blogname', ''],\n ['tumblr_consumer_key', ''],\n ['tumblr_consumer_secret', ''],\n ['tumblr_access_token', ''],\n ['tumblr_access_token_secret', '']]\n\n decoded_creds = base64.urlsafe_b64decode(settings['hashed_creds'])\n decoded_creds = decoded_creds.split(TOKEN_DELIMITER)\n for _index in range(0, len(decoded_creds)):\n compiled_creds[_index][1] = decoded_creds[_index]\n\n '''\n Dump all the values into the \"socialmediacreds\" entity in setup.xml\n The values are placed correctly based on the field names of the \n textfields in setup.xml\n For example, in the Twitter configuration section, the saved string\n of \"Twitter consumer key\" will be populated in the textfield with \n field name \"twitter_consumer_key\"\n '''\n for item in compiled_creds:\n confInfo['socialmediacreds'].append(item[0], item[1])\n\n def handleEdit(self, confInfo):\n '''\n After user clicks Save on setup screen, take updated parameters,\n normalize them, and save them into routrcreds.conf\n We check if each of the input is empty. Set the value to empty\n string if there is no input provided. Then break the loop and \n don't save the changes or updates\n '''\n save_twtr_creds = True\n twitter_dict_keys = [\n 'twitter_consumer_key', 'twitter_consumer_secret', \n 'twitter_access_token', 'twitter_access_token_secret']\n twitter_user_creds = []\n for twtr_dict_key in twitter_dict_keys:\n if twtr_dict_key in self.callerArgs.data:\n if self.callerArgs.data[twtr_dict_key][0] in [None, '']:\n self.callerArgs.data[twtr_dict_key][0] = ''\n save_twtr_creds = False\n break\n twitter_user_creds.append(\n self.callerArgs.data[twtr_dict_key][0])\n if save_twtr_creds:\n twitter_user_creds = TOKEN_DELIMITER.join(twitter_user_creds)\n self.writeConf('routrcreds', 'twittercreds',\n {'hashed_creds': base64.urlsafe_b64encode(twitter_user_creds)})\n self.install_alert_script(\n os.environ.get('SPLUNK_HOME'), 'tweetalert.py')\n\n save_tumblr_creds = True\n tumblr_dict_keys = [\n 'tumblr_blogname', 'tumblr_consumer_key',\n 'tumblr_consumer_secret', 'tumblr_access_token',\n 'tumblr_access_token_secret']\n tumblr_user_creds = []\n for tumblr_dict_key in tumblr_dict_keys:\n if tumblr_dict_key in self.callerArgs.data:\n if self.callerArgs.data[tumblr_dict_key][0] in [None, '']:\n self.callerArgs.data[tumblr_dict_key][0] = ''\n save_tumblr_creds = False\n break\n tumblr_user_creds.append(\n self.callerArgs.data[tumblr_dict_key][0])\n if save_tumblr_creds:\n tumblr_user_creds = TOKEN_DELIMITER.join(tumblr_user_creds)\n self.writeConf('routrcreds', 'tumblrcreds',\n {'hashed_creds': base64.urlsafe_b64encode(tumblr_user_creds)})\n self.install_alert_script(\n os.environ.get('SPLUNK_HOME'), 'tumblralert.py')\n\n def install_alert_script(self, splunk_home_dir, script_name):\n '''\n Move alert script into $SPLUNK_HOME/bin/scripts directory\n '''\n tweetalert_path = os.path.join(\n splunk_home_dir, 'etc', 'apps', 'routr', script_name)\n splunk_bin_scripts_dir = os.path.join(\n splunk_home_dir, 'bin', 'scripts')\n shutil.copy(tweetalert_path, splunk_bin_scripts_dir)\n\nif __name__ == '__main__':\n splunk.admin.init(SetupRoutr, splunk.admin.CONTEXT_NONE)\n", "repo_name": "asimchamp/Splunk_Apps", "sub_path": "SplunkBase/1823_routr/1.0.3/routr/bin/setup_routr.py", "file_name": "setup_routr.py", "file_ext": "py", "file_size_in_byte": 5654, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "logging.getLogger", "line_number": 15, "usage_type": "call"}, {"api_name": "splunk.admin.admin", "line_number": 17, "usage_type": "attribute"}, {"api_name": "splunk.admin", "line_number": 17, "usage_type": "name"}, {"api_name": "splunk.admin.admin", "line_number": 19, "usage_type": "attribute"}, {"api_name": "splunk.admin", "line_number": 19, "usage_type": "name"}, {"api_name": "base64.urlsafe_b64decode", "line_number": 51, "usage_type": "call"}, {"api_name": "base64.urlsafe_b64encode", "line_number": 91, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 93, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 93, "usage_type": "attribute"}, {"api_name": "base64.urlsafe_b64encode", "line_number": 112, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 114, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 114, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 120, "usage_type": "call"}, {"api_name": "os.path", "line_number": 120, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 122, "usage_type": "call"}, {"api_name": "os.path", "line_number": 122, "usage_type": "attribute"}, {"api_name": "shutil.copy", "line_number": 124, "usage_type": "call"}, {"api_name": "splunk.admin.admin.init", "line_number": 127, "usage_type": "call"}, {"api_name": "splunk.admin.admin", "line_number": 127, "usage_type": "attribute"}, {"api_name": "splunk.admin", "line_number": 127, "usage_type": "name"}]} +{"seq_id": "13862471866", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 29 18:35:18 2023\n\n@author: tercio\n\"\"\"\n\nimport cv2\nimport mediapipe as mp\nimport time\nimport pygame\n \n#https://github.com/google/mediapipe/blob/master/docs/solutions/pose.md\n\nmpDraw = mp.solutions.drawing_utils\nmpPose = mp.solutions.pose\npose = mpPose.Pose()\n\n\nWIDTH, HEIGHT = 500,500\n \ncap = cv2.VideoCapture(0)\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, WIDTH)\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, HEIGHT)\npTime = 0\n\n \n\nwhile True:\n \n success, img = cap.read()\n imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n results = pose.process(imgRGB)\n \n if results.pose_landmarks:\n mpDraw.draw_landmarks(img, results.pose_landmarks, mpPose.POSE_CONNECTIONS)\n h, w, c = img.shape\n nose_x = int(results.pose_landmarks.landmark[0].x*w)\n nose_y = int(results.pose_landmarks.landmark[0].y*h)\n cv2.circle(img, (nose_x, nose_y), 5, (255, 0, 0), cv2.FILLED)\n \n \n \n \n cTime = time.time()\n fps = 1 / (cTime - pTime)\n pTime = cTime\n \n cv2.putText(img, str(int(fps)), (70, 50), cv2.FONT_HERSHEY_PLAIN, 3,\n (255, 0, 0), 3)\n \n \n \n \n cv2.imshow(\"Image\", img)\n key = cv2.waitKey(1)\n \n if key == 27:\n break\n\ncap.release()\ncv2.destroyAllWindows()\n\n", "repo_name": "apolinario-souza/VR_Motor_learning", "sub_path": "Realidade_virutal_para_disciplina/v1/script1.py", "file_name": "script1.py", "file_ext": "py", "file_size_in_byte": 1309, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "mediapipe.solutions", "line_number": 16, "usage_type": "attribute"}, {"api_name": "mediapipe.solutions", "line_number": 17, "usage_type": "attribute"}, {"api_name": "cv2.VideoCapture", "line_number": 23, "usage_type": "call"}, {"api_name": "cv2.CAP_PROP_FRAME_WIDTH", "line_number": 24, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FRAME_HEIGHT", "line_number": 25, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 33, "usage_type": "attribute"}, {"api_name": "cv2.circle", "line_number": 41, "usage_type": "call"}, {"api_name": "cv2.FILLED", "line_number": 41, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 46, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 50, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_PLAIN", "line_number": 50, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 56, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 57, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 63, "usage_type": "call"}]} +{"seq_id": "71205488713", "text": "from PIL import Image\n\n\nd = fr'H:\\Programming\\Python\\Projects\\2018\\Autopilot\\pack_0.3\\image_line_d'\np = fr'H:\\Programming\\Python\\Projects\\2018\\Autopilot\\pack_0.3\\image_line_d_cut'\n\n\nfor directory in ['\\left']:\n for i in range(1, 2000):\n read = d + directory + f'\\{directory[1]}{i}.jpg'\n write = p + directory + f'\\{directory[1]}{i}.jpg'\n try:\n img = Image.open(read)\n print(i)\n except:\n continue\n else:\n (x, y, w, h) = (0, 230, 640, 250) # Set the size.\n img = img.crop((x, y, x + w, y + h))\n img.save(write)\n", "repo_name": "bugstop/hitsz-eie-codes", "sub_path": "Project2017/pack_0.3/cut_img.py", "file_name": "cut_img.py", "file_ext": "py", "file_size_in_byte": 614, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 18, "dataset": "github-code", "pt": "27", "api": [{"api_name": "PIL.Image.open", "line_number": 13, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 13, "usage_type": "name"}]} +{"seq_id": "4603978756", "text": "import numpy as np\nfrom typing import Tuple\nfrom numpy.random import default_rng \n\nclass Board:\n def __init__(self, max_food_number: int, max_size: Tuple[int, int]):\n self.max_size = max_size\n self.__max_food_number = max_food_number\n self.__rng = default_rng()\n self.foods = self.__rand_foods(max_food_number)\n\n def __rand_foods(self, n):\n x = (self.__rng.random(n)*self.max_size[0]).astype(int).tolist()\n y = (self.__rng.random(n)*self.max_size[1]).astype(int).tolist()\n return list(zip(x, y))\n\n def refill_food(self):\n eaten_food_number = self.__max_food_number - len(self.foods)\n self.foods += self.__rand_foods(eaten_food_number)\n", "repo_name": "Hergoln/pz-11-backend", "sub_path": "bots_battles/games/agarnt/board.py", "file_name": "board.py", "file_ext": "py", "file_size_in_byte": 707, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "typing.Tuple", "line_number": 6, "usage_type": "name"}, {"api_name": "numpy.random.default_rng", "line_number": 9, "usage_type": "call"}]} +{"seq_id": "39186037535", "text": "import mutagen.id3\nimport mutagen.mp3\n\n\nclass MetadataEditor:\n def __init__(self, path):\n self.song_path = path\n try:\n self.tags = mutagen.id3.ID3(self.song_path)\n self.audio = mutagen.mp3.MP3(path)\n try:\n self.audio.add_tags()\n except:\n pass\n\n except mutagen.id3.ID3NoHeaderError:\n self.tags = mutagen.id3.ID3()\n\n def tag(self, tag_data):\n for tag, value in tag_data.items():\n string = 'mutagen.id3.%s(encoding=3, text=u\"%s\")' % (tag, value)\n print(string)\n if tag != 'APIC':\n self.tags[tag] = eval(string)\n\n else:\n self.tags[tag] = mutagen.id3.APIC(\n encoding=3,\n mime=u'image/png',\n type=3,\n desc=u'Cover',\n data=value[1]\n )\n\n self.audio.tags.add(\n mutagen.id3.APIC(\n mime=u'image/png',\n type=3,\n desc=u'Cover',\n data=value[1]\n )\n )\n\n self.audio.save()\n # self.tags.save(self.song_path)\n", "repo_name": "carranz998/automatic-tag-editor", "sub_path": "metadata_editor.py", "file_name": "metadata_editor.py", "file_ext": "py", "file_size_in_byte": 1267, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "mutagen.id3.id3.ID3", "line_number": 9, "usage_type": "call"}, {"api_name": "mutagen.id3.id3", "line_number": 9, "usage_type": "attribute"}, {"api_name": "mutagen.id3", "line_number": 9, "usage_type": "name"}, {"api_name": "mutagen.id3.mp3.MP3", "line_number": 10, "usage_type": "call"}, {"api_name": "mutagen.id3.mp3", "line_number": 10, "usage_type": "attribute"}, {"api_name": "mutagen.id3", "line_number": 10, "usage_type": "name"}, {"api_name": "mutagen.id3.id3", "line_number": 16, "usage_type": "attribute"}, {"api_name": "mutagen.id3", "line_number": 16, "usage_type": "name"}, {"api_name": "mutagen.id3.id3.ID3", "line_number": 17, "usage_type": "call"}, {"api_name": "mutagen.id3.id3", "line_number": 17, "usage_type": "attribute"}, {"api_name": "mutagen.id3", "line_number": 17, "usage_type": "name"}, {"api_name": "mutagen.id3.id3.APIC", "line_number": 27, "usage_type": "call"}, {"api_name": "mutagen.id3.id3", "line_number": 27, "usage_type": "attribute"}, {"api_name": "mutagen.id3", "line_number": 27, "usage_type": "name"}, {"api_name": "mutagen.id3.id3.APIC", "line_number": 36, "usage_type": "call"}, {"api_name": "mutagen.id3.id3", "line_number": 36, "usage_type": "attribute"}, {"api_name": "mutagen.id3", "line_number": 36, "usage_type": "name"}]} +{"seq_id": "10538056703", "text": "import requests\r\nimport os\r\nimport json\r\nimport pdb\r\nfrom datetime import datetime, timedelta\r\nfrom dateutil.relativedelta import relativedelta\r\nimport time\r\nfrom tqdm import tqdm\r\nimport sys\r\n\r\nDATE_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'\r\nTWITTER_START_DATE = datetime.strptime('2006-03-21T00:00:00.000Z', DATE_FORMAT)\r\nSOME_DATE = datetime.strptime('2021-12-01T00:00:00.000Z', DATE_FORMAT)\r\nTODAY_DATE = datetime.now()\r\n\r\n# To set your environment variables in your terminal run the following line:\r\n# export 'BEARER_TOKEN'=''\r\n# bearer_token = os.environ.get(\"BEARER_TOKEN\")\r\nbearer_token = 'AAAAAAAAAAAAAAAAAAAAAERzUwEAAAAAt7fYxbA7j2P4n7R80nlo9GvnVUc%3DNFjB0C9tMJ1BjrhHr7AHj6p56d2Ux0EnKeS0a7pVJNdE55BfQY'\r\n\r\nsearch_url = \"https://api.twitter.com/2/tweets/search/all\"\r\n\r\ndef bearer_oauth(r):\r\n \"\"\"\r\n Method required by bearer token authentication.\r\n \"\"\"\r\n r.headers[\"Authorization\"] = f\"Bearer {bearer_token}\"\r\n r.headers[\"User-Agent\"] = \"v2FullArchiveSearchPython\"\r\n return r\r\n\r\n# Optional params: start_time,end_time,since_id,until_id,max_results,next_token,\r\n# expansions,tweet.fields,media.fields,poll.fields,place.fields,user.fields\r\ndef send_query(params):\r\n response = requests.request(\"GET\", search_url, auth=bearer_oauth, params=params)\r\n if response.status_code != 200:\r\n print(response.status_code, response.text)\r\n if response.status_code == 429:\r\n print('Sleep for 15 mins')\r\n for i in tqdm(range(15*60)):\r\n time.sleep(1)\r\n return send_query(params)\r\n else:\r\n #pdb.set_trace()\r\n print('Unexpected case')\r\n raise Exception(response.status_code, response.text)\r\n time.sleep(1)\r\n return response.json()\r\n\r\ndef id_to_username(twitter_id):\r\n response = requests.request(\"GET\", f'https://api.twitter.com/2/users/{twitter_id}', auth=bearer_oauth)\r\n time.sleep(1)\r\n return response.json()\r\n\r\ndef pull_tweets(keyword, filename):\r\n count = 0\r\n filename_base = filename.split('.')[0]\r\n os.makedirs(filename_base, exist_ok=True)\r\n start_time = SOME_DATE\r\n\r\n with open(filename, 'w', encoding='utf-8') as fout:\r\n tweets = []\r\n params ={ 'query': keyword, 'tweet.fields': 'id,text,author_id,created_at', 'max_results': 100, 'start_time': SOME_DATE.strftime(DATE_FORMAT), 'end_time': TODAY_DATE.strftime(DATE_FORMAT)}\r\n response = send_query(params)\r\n\r\n if response['meta']['result_count'] == 0:\r\n print('No tweet found')\r\n fout.write('No tweet found')\r\n return\r\n\r\n fout.write('id, author_id, created_at, text\\n')\r\n\r\n tweets += response['data']\r\n page = 0\r\n with open(f'{filename_base}/{start_time.strftime(\"%Y_%m_%d\")}_{page}.json', 'w') as f:\r\n json.dump(response, f)\r\n\r\n while 'next_token' in response['meta']:\r\n print('next_token', response['meta']['next_token'])\r\n params = {'query': keyword, 'tweet.fields': 'id,text,author_id,created_at', 'next_token': response['meta']['next_token'], 'max_results': 100, 'start_time': SOME_DATE.strftime(DATE_FORMAT), 'end_time': TODAY_DATE.strftime(DATE_FORMAT)}\r\n response = send_query(params)\r\n tweets += response['data']\r\n page += 1\r\n with open(f'{filename_base}/{start_time.strftime(\"%Y_%m_%d\")}_{page}.json', 'w') as f:\r\n json.dump(response, f)\r\n\r\n tweets.reverse()\r\n count += len(tweets)\r\n\r\n for t in tweets:\r\n fout.write('{}, {}, {}, {}\\n'.format(t['id'], t['author_id'], t['created_at'], t['text'].replace('\\n', ' ')))\r\n fout.flush()\r\n\r\nif __name__ == \"__main__\":\r\n keyswords = [\r\n 'video.foxbusiness.com/v/6285838417001',\r\n 'www.foxbusiness.com/technology/amazon-web-services-outage-impacts-thousands-of-users-online-services-what-to-know',\r\n 'www.foxbusiness.com/media/internet-experts-warning-on-another-amazon-web-services-outage',\r\n 'www.foxbusiness.com/technology/amazon-outage-disrupts-lives-surprising-people-cloud-dependency',\r\n 'video.foxbusiness.com/v/6285830607001',\r\n 'www.foxbusiness.com/lifestyle/amazon-rebuild-illinois-warehouse-tornado',\r\n 'www.foxbusiness.com/lifestyle/midwestern-tornadoes-walmart-lowes-donate-supplies-help-recovery-efforts',\r\n 'video.foxbusiness.com/v/6286489522001',\r\n 'www.foxbusiness.com/politics/kentucky-ag-daniel-cameron-tornado-price-gouging-scams-hotline',\r\n 'www.foxbusiness.com/economy/amazon-warehouse-collapse-6-fatalities-after-deadly-tornado-rips-through-area',\r\n 'www.foxbusiness.com/economy/tornado-amazon-deaths-warehouse-statement',\r\n 'www.foxbusiness.com/economy/tornadoes-extreme-weather-3-billion-insured-damage-report',\r\n 'video.foxbusiness.com/v/6286600650001',\r\n 'www.foxbusiness.com/lifestyle/power-outages-kentucky-deadly-tornadoes',\r\n 'video.foxbusiness.com/v/6286657045001/',\r\n 'www.foxbusiness.com/business-leaders/kentucky-candle-factory-ceo-says-staff-working-during-deadly-tornado-still-missing'\r\n ]\r\n\r\n for idx, k in enumerate(keyswords):\r\n pull_tweets(k, f'search_{idx}.csv')\r\n\r\n #twitter_id = '17941960'\r\n #res = id_to_username(twitter_id)\r\n #print(res)\r\n", "repo_name": "katelynnrachel/ckids_fred_morstatter", "sub_path": "get_twitter.py", "file_name": "get_twitter.py", "file_ext": "py", "file_size_in_byte": 5313, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "datetime.datetime.strptime", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 12, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 13, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 14, "usage_type": "name"}, {"api_name": "requests.request", "line_number": 34, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 39, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 40, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 46, "usage_type": "call"}, {"api_name": "requests.request", "line_number": 50, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 51, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 57, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 75, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 84, "usage_type": "call"}]} +{"seq_id": "30117913006", "text": "from tkinter import *\nfrom tkinter import ttk\nimport tkinter.messagebox\nimport time\nimport json\n\nimport socket\nimport mysql.connector\nimport urllib.request\n\n\nclass AuctionReminder:\n\n f_width = \"400\"\n f_height = \"375\"\n\n # MOST IMPORTANT VARIABLES\n internet_connection = False\n licence_status = \"Invalid\" # Expired licence or invalid aut hkey\n cloak_status = \"Inactive\"\n\n user_auth_key = \"\"\n auth_key_origin = \"\"\n\n licence_expiry_date = None\n current_server_date = None\n\n new_settings = None\n\n diode_error_label = \"hide\"\n\n # Main cloak variables\n freq_hour = \"01\"\n freq_minute = \"00\"\n freq_second = \"00\"\n\n start_hour = \"00\"\n star_minute = \"35\"\n start_second = \"00\"\n\n end_hour = \"23\"\n end_minute = \"59\"\n end_second = \"59\"\n\n remind_hour = \"--\"\n remind_minute = \"01\"\n remind_second = \"00\"\n\n # Next auction variables\n auctions_list = []\n auction_index = 0\n next_auction_time = \"\"\n\n def __init__(self, window):\n\n self.window = window\n self.window.title(\"Auction Reminder\")\n self.window.geometry(\"500x375+550+265\") # 400x300\n self.window.iconbitmap(\"Pictures/icon2.ico\")\n\n # self.window.resizable(0, 0)\n # self.window.wm_attributes(\"-topmost\", 1)\n\n self.initLayout()\n\n\n ''' Function initialize all aplication lalyouts'''\n def initLayout(self):\n\n #MAIN FRAMES\n self.mian_frame = ttk.Frame(self.window, height=self.f_height, width=self.f_width, ) #bg=\"lightgreen\"\n self.settings_frame = ttk.Frame(self.window, height=self.f_height, width=self.f_width, ) #bg=\"lightblue\"\n self.licecne_frame = ttk.Frame(self.window, height=self.f_height, width=self.f_width, ) #bg=\"lightyellow\"\n self.apperance_frame = ttk.Frame(self.window, height=self.f_height, width=self.f_width, ) #bg=\"#F5DEB3\"\n\n self.mian_frame.pack(side=LEFT, pady=10)\n self.mian_frame.pack_propagate(False)\n self.settings_frame.pack_propagate(False)\n self.licecne_frame.pack_propagate(False)\n self.apperance_frame.pack_propagate(False)\n\n #NAVBAR FRAME\n self.nav_bar = ttk.Frame(self.window)\n self.nav_bar.pack()\n\n\n #MAIN WINDOW LAYOUT\n self.main_window_layout()\n\n #SETTINGS WINDOW LAYOUT\n self.settings_window_layout()\n\n\n # APPEARANCE WINDOW LAYOUT\n self.appearance_window_layout()\n\n\n # LICENCE WINDOW LAYOUT\n self.licence_window_layout()\n\n\n #NAVBAR LAYOUT (buttons)\n self.main_window_img = PhotoImage(file=\"Pictures/home-page3-80.png\")\n self.main_window_button = ttk.Button(self.nav_bar, image=self.main_window_img, state=NORMAL, command=lambda: self.main_window() ) #bd=1\n self.main_window_button.pack(pady=2, padx=2)\n\n self.settings_img = PhotoImage(file=\"Pictures/settings2-80.png\")\n self.setting_button = ttk.Button(self.nav_bar, image=self.settings_img, state=NORMAL,command=lambda: self.settings_window() )\n self.setting_button.pack(pady=2, padx=2)\n\n self.paints_image = PhotoImage(file=\"Pictures/paints3-80.png\")\n self.paints_button = ttk.Button(self.nav_bar, image=self.paints_image, state=NORMAL, command=lambda: self.appearance_window() )\n self.paints_button.pack(pady=2, padx=2)\n\n self.key_img = PhotoImage(file=\"Pictures/key3-80.png\")\n self.key_button = ttk.Button(self.nav_bar, image=self.key_img, state=NORMAL, command=lambda: self.licence_window() )\n self.key_button.pack(pady=2, padx=2)\n\n\n ''' Smallest parts(different windows) of application layout'''\n def main_window_layout(self):\n\n\n #self.diodes_frame = Frame(self.window)\n #self.diodes_frame.place(x=280, y=13, bordermode=OUTSIDE)\n\n # FRAMES\n self.diodes_frame = Frame(self.mian_frame, bg=\"\")\n\n # LABELS\n self.invisible_sign_1 = Label(self.mian_frame, text=\"\", font=(\"Tiemes\", 1))\n self.invisible_sign_2 = Label(self.mian_frame, text=\"\", font=(\"Tiemes\", 1))\n self.invisible_sign_3 = Label(self.mian_frame, text=\"\", font=(\"Tiemes\", 1))\n\n self.info_label_1 = Label(self.mian_frame, text=\"Actual time:\", font=(\"Arial BOLD\", 16))\n self.info_label_2 = Label(self.mian_frame, text=\"Next auction:\", font=(\"Arial BOLD\", 15))\n self.info_label_3 = Label(self.mian_frame, text=\"Remaining time:\", font=(\"Arial BOLD\", 14))\n self.info_label_4 = Label(self.mian_frame, text=\"Error message:\", font=(\"Arial BOLD\", 14))\n self.info_label_5 = Label(self.mian_frame, text=\"You have\\nvalid licence\", fg=\"green\", font=(\"Franklin Gothic Medium\", 11)) # valid x=267, invalid x=262\n self.info_label_6 = Label(self.mian_frame, text=\"You have\\ninvalid licence\", fg=\"red\", font=(\"Franklin Gothic Medium\", 11))\n\n self.clock_label = Label(self.mian_frame, font=(\"Unispace\", 30), text=\"\")\n self.next_auction_label = Label(self.mian_frame, font=(\"Unispace\", 21), text=\"\")\n self.timer_label = Label(self.mian_frame, font=(\"Unispace\", 17), text=\"\")\n self.error_message_label = Label(self.mian_frame, font=(\"Arial BOLD\", 12), text=\"\", fg=\"red\")\n\n self.red = PhotoImage(file=\"Pictures/cancel-20.png\")\n self.red_diode = Button(self.diodes_frame, image=self.red, bd=0, command=lambda: self.show_licence_info(\"Invalid\"))\n self.red_diode.pack(side=LEFT, padx=5)\n\n self.green = PhotoImage(file=\"Pictures/ok-20.png\")\n self.green_diode = Button(self.diodes_frame, image=self.green, bd=0, command=lambda: self.show_licence_info(\"Valid\"))\n self.green_diode.pack(side=LEFT, padx=5)\n self.diodes_frame.place(x=270, y=20, bordermode=OUTSIDE)\n\n # MAIN_WINDOW_PACK()\n self.info_label_1.pack(padx=10, pady=1, anchor=NW)\n self.clock_label.pack(padx=20, anchor=W)\n self.invisible_sign_1.pack(pady=7)\n self.info_label_2.pack(padx=10, pady=1, anchor=W)\n self.next_auction_label.pack(padx=30, anchor=W)\n self.invisible_sign_2.pack(pady=7)\n self.info_label_3.pack(padx=10, pady=1, anchor=SW)\n self.timer_label.pack(padx=40, anchor=W)\n self.invisible_sign_3.pack(pady=7)\n self.info_label_4.pack(padx=10, pady=1, anchor=SW)\n self.error_message_label.pack(padx=30, anchor=SW)\n\n def settings_window_layout(self):\n\n #self.settings_label_info = Label(self.settings_frame, text=\"SETTINGS WINDOW\")\n #self.settings_label_info.pack()\n\n frame_frequency = Frame(self.settings_frame)\n frame_start = Frame(self.settings_frame)\n frame_ending = Frame(self.settings_frame)\n frame_reminder = Frame(self.settings_frame)\n\n # part0 - OTHERS_ELEMENTS\n label_frequency = Label(self.settings_frame, text=\"Frequency:\", font=(\"Arial BOLD\", 17))\n label_start = Label(self.settings_frame, text=\"Start reminding:\", font=(\"Arial BOLD\", 17))\n label_ending = Label(self.settings_frame, text=\"End reminding:\", font=(\"Arial BOLD\", 17))\n label_reminder = Label(self.settings_frame, text=\"Remind ... before:\", font=(\"Arial BOLD\", 17))\n label_info = Label(self.settings_frame, text=\"It is recommended to restart program, after every changes settings.\",\n font=(\"Arial BOLD\", 9), fg=\"red\")\n\n colon_1 = Label(frame_frequency, text=\":\", font=(\"Arial Black\", 15))\n colon_2 = Label(frame_frequency, text=\":\", font=(\"Arial Black\", 15))\n colon_3 = Label(frame_start, text=\":\", font=(\"Arial Black\", 15))\n colon_4 = Label(frame_start, text=\":\", font=(\"Arial Black\", 15))\n colon_5 = Label(frame_ending, text=\":\", font=(\"Arial Black\", 15))\n colon_6 = Label(frame_ending, text=\":\", font=(\"Arial Black\", 15))\n colon_7 = Label(frame_reminder, text=\":\", font=(\"Arial Black\", 15))\n colon_8 = Label(frame_reminder, text=\":\", font=(\"Arial Black\", 15))\n\n space_1 = Label(self.settings_frame, text=\"\", font=(\"Times\", 2))\n space_2 = Label(self.settings_frame, text=\"\", font=(\"Times\", 2))\n space_3 = Label(self.settings_frame, text=\"\", font=(\"Times\", 2))\n space_4 = Label(self.settings_frame, text=\"\", font=(\"Times\", 2))\n\n font_size = 17\n # part1 - FREQUENCY_FRAME\n self.text_freq_hour = Text(frame_frequency, bd=1, width=4, height=1, font=(\"Unispace\", font_size))\n self.text_freq_minute = Text(frame_frequency, bd=1, width=4, height=1, font=(\"Unispace\", font_size))\n self.text_freq_second = Text(frame_frequency, bd=1, width=4, height=1, font=(\"Unispace\", font_size))\n\n self.text_freq_hour.pack(side=LEFT, padx=5, pady=0)\n colon_1.pack(side=LEFT)\n self.text_freq_minute.pack(side=LEFT, padx=5, pady=0)\n colon_2.pack(side=LEFT)\n self.text_freq_second.pack(side=LEFT, padx=5, pady=0)\n\n # part2 - START_FRAME\n self.text_start_hour = Text(frame_start, bd=1, width=4, height=1, font=(\"Unispace\", font_size))\n self.text_start_minute = Text(frame_start, bd=1, width=4, height=1, font=(\"Unispace\", font_size))\n self.text_start_second = Text(frame_start, bd=1, width=4, height=1, font=(\"Unispace\", font_size))\n\n self.text_start_hour.pack(side=LEFT, padx=5, pady=0)\n colon_3.pack(side=LEFT)\n self.text_start_minute.pack(side=LEFT, padx=5, pady=3)\n colon_4.pack(side=LEFT)\n self.text_start_second.pack(side=LEFT, padx=5, pady=3)\n\n # part3 - END_FRAME\n self.text_end_hour = Text(frame_ending, bd=1, width=4, height=1, font=(\"Unispace\", font_size))\n self.text_end_minute = Text(frame_ending, bd=1, width=4, height=1, font=(\"Unispace\", font_size))\n self.text_end_second = Text(frame_ending, bd=1, width=4, height=1, font=(\"Unispace\", font_size))\n\n self.text_end_hour.pack(side=LEFT, padx=5, pady=3)\n colon_5.pack(side=LEFT)\n self.text_end_minute.pack(side=LEFT, padx=5, pady=3)\n colon_6.pack(side=LEFT)\n self.text_end_second.pack(side=LEFT, padx=5, pady=3)\n\n # part4 = REMIND_FRAME\n self.text_remind_hour = Text(frame_reminder, bd=1, width=4, height=1, font=(\"Unispace\", font_size))\n self.text_remind_minute = Text(frame_reminder, bd=1, width=4, height=1, font=(\"Unispace\", font_size))\n self.text_remind_second = Text(frame_reminder, bd=1, width=4, height=1, font=(\"Unispace\", font_size))\n\n self.text_remind_hour.insert(1.0, \" --\")\n self.text_remind_hour.config(state=DISABLED)\n\n self.text_remind_hour.pack(side=LEFT, padx=5, pady=3)\n colon_7.pack(side=LEFT)\n self.text_remind_minute.pack(side=LEFT, padx=5, pady=3)\n colon_8.pack(side=LEFT)\n self.text_remind_second.pack(side=LEFT, padx=5, pady=3)\n\n # part5 - BUTTONS\n self.button_save = ttk.Button(self.settings_frame, text=\"Save\", width=10, command=lambda: self.save(), state=DISABLED)\n self.button_default = ttk.Button(self.settings_frame, text=\"Default\", width=10, command=lambda: self.default_config())\n self.button_edit = ttk.Button(self.settings_frame, text=\"Edit\", width=10, command=lambda: self.edit())\n\n # SETTINGS_WINDOW\n space_1.pack()\n label_frequency.pack(anchor=NW, padx=5)\n frame_frequency.pack(anchor=NW, padx=20, pady=4)\n space_2.pack()\n label_start.pack(anchor=NW, padx=5)\n frame_start.pack(anchor=NW, padx=20, pady=4)\n space_3.pack()\n label_ending.pack(anchor=NW, padx=5)\n frame_ending.pack(anchor=NW, padx=20, pady=4)\n space_4.pack()\n label_reminder.pack(anchor=NW, padx=5)\n frame_reminder.pack(anchor=NW, padx=20, pady=4)\n #label_info.pack(anchor=NW, padx=5, pady=5)\n\n\n # button_default.place(x=305, y=190)\n # button_edit.place(x=305, y=217)\n # button_save.place(x=305, y=244)\n\n self.button_default.place(x=305, y=150)\n self.button_edit.place(x=305, y=177)\n self.button_save.place(x=305, y=204)\n\n def appearance_window_layout(self):\n\n self.apperance_label_info = Label(self.apperance_frame, text=\"APPEARANCE WINDOW\")\n self.apperance_label_info.pack()\n\n def licence_window_layout(self):\n # self.licence_label_info = Label(self.licecne_frame, text=\"LICENCE WINDOW\")\n # self.licence_label_info.pack()\n\n self.frame_licence_status = Frame(self.licecne_frame) #bg=\"#E1E1E1\"\n self.frame_auth_key = Frame(self.licecne_frame)\n self.frame_info = Frame(self.licecne_frame)\n self.frame_enter_licence = Frame(self.licecne_frame)\n\n self.label_licence_status = Label(self.frame_licence_status, text=\"Licence:\", font=(\"Times BOLD\", 16))\n self.label_valid_invalid = Label(self.frame_licence_status, text=\"Invalid\", fg=\"red\", font=(\"Arial BLOD\", 16))\n self.label_auth_key_info = Label(self.frame_auth_key, text=\"Auth key:\", font=(\"Arial BOLD\", 13))\n self.label_auth_key_value = Label(self.frame_auth_key, text=\"none\", fg=\"red\", font=(\"Arial BLOD\", 13))\n self.label_validation_info = Label(self.frame_info, text=\"\", fg=\"red\", font=(\"Arial BLOD\", 13))\n\n self.label_enter_licence_str = Label(self.frame_enter_licence, text=\"Enter auth key:\", font=(\"Arial BLOD\", 11))\n\n self.text_enter_licence = Text(self.frame_enter_licence, width=35, height=1, font=(\"Arial BLOD\", 12), padx=5, pady=5,\n bd=2, relief=\"solid\") #bg=\"#B9B9B9\"\n\n button_verify_licence = Button(self.frame_enter_licence, text=\"VERIFY\", font=(\"Arial BLOD\", 16), bd=3,\n relief=\"solid\", padx=3, justify=CENTER, command=lambda: self.verify_licence())\n\n space_1 = Label(self.licecne_frame, text=\"\", font=(\"Times\", 5))\n space_2 = Label(self.licecne_frame, text=\"\", font=(\"Times\", 5))\n\n # WINDOW LAYOUT\n space_1.pack()\n self.frame_licence_status.pack(anchor=NW)\n self.label_licence_status.pack(padx=10, pady=5, side=LEFT)\n self.label_valid_invalid.pack(side=LEFT)\n\n self.frame_auth_key.pack(anchor=NW)\n self.label_auth_key_info.pack(padx=12, side=LEFT)\n self.label_auth_key_value.pack(side=LEFT)\n\n space_2.pack(pady=10, anchor=NW)\n self.frame_info.pack(anchor=CENTER, pady=3)\n self.label_validation_info.pack(pady=15)\n\n self.frame_enter_licence.pack(anchor=CENTER)\n self.label_enter_licence_str.pack(anchor=NW, pady=1)\n self.text_enter_licence.pack()\n button_verify_licence.pack(pady=25, )\n\n\n ''' Funtctions responsible for change aplication frames '''\n\n def main_window(self):\n self.window.title(\"Auction Reminder\")\n\n self.licecne_frame.pack_forget()\n self.settings_frame.pack_forget()\n self.apperance_frame.pack_forget()\n self.nav_bar.pack_forget()\n\n self.mian_frame.pack(side=LEFT, pady=10)\n self.nav_bar.pack()\n\n def settings_window(self):\n self.window.title(\"Settings\")\n\n self.mian_frame.pack_forget()\n self.licecne_frame.pack_forget()\n self.apperance_frame.pack_forget()\n self.nav_bar.pack_forget()\n self.settings_frame.pack(side=LEFT)\n self.nav_bar.pack()\n\n def appearance_window(self):\n self.window.title(\"Appearance\")\n\n self.mian_frame.pack_forget()\n self.settings_frame.pack_forget()\n self.licecne_frame.pack_forget()\n self.nav_bar.pack_forget()\n self.apperance_frame.pack(side=LEFT)\n self.nav_bar.pack()\n\n def licence_window(self):\n self.window.title(\"Licence\")\n\n self.mian_frame.pack_forget()\n self.settings_frame.pack_forget()\n self.apperance_frame.pack_forget()\n self.nav_bar.pack_forget()\n self.licecne_frame.pack(side=LEFT)\n self.nav_bar.pack()\n\n # tutaj nalezy jeszcze dodac funkcje ktora bedzie sprawdzac\n # status licencji i renderowac okno\n\n # self.render_licence_window(self.licence_status, self.user_auth_key)\n # self.render_licence_window(None, None, None, \"Licence expired\")\n\n # lub w tym miejsu nic nie renderowac, tylko zmieniac okon, a renderowanie\n # wywolywac w funkcji okresowej ktora bedzie sprawdzac polaczenie z internetem\n # i sprawdzac status licencji\n\n\n ''' MAIN FRAME functions'''\n\n def light_diode_up(self):\n\n if self.licence_status == \"Valid\":\n self.green_diode.config(state=NORMAL)\n self.red_diode.config(state=DISABLED)\n self.info_label_6.place_forget()\n self.diode_error_label = \"hide\"\n else:\n self.green_diode.config(state=DISABLED)\n self.red_diode.config(state=NORMAL)\n self.info_label_5.place_forget()\n\n self.info_label_6.config(text=\"You have\\ninvalid licence\")\n self.diode_error_label = \"hide\"\n\n def show_licence_info(self, status):\n\n if status == \"Valid\":\n print(\"valid\")\n if self.diode_error_label == \"hide\":\n self.info_label_5.place(x=267, y=45)\n self.diode_error_label = \"on screen\"\n else:\n self.info_label_5.place_forget()\n self.diode_error_label = \"hide\"\n else:\n print(\"invalid\")\n if self.diode_error_label == \"hide\":\n self.info_label_6.place(x=260, y=45, bordermode=OUTSIDE)\n self.diode_error_label = \"on screen\"\n else:\n self.info_label_6.place_forget()\n self.diode_error_label = \"hide\"\n # -------------------------------------------\n def digital_clock(self):\n\n def unset_main_frame_values():\n\n self.clock_label.config(text=\"\")\n self.next_auction_label.config(text=\"\")\n self.timer_label.config(text=\"\")\n self.error_message_label.config(text=\"\")\n\n if self.new_settings is True:\n self.new_settings = None\n\n # tutaj wprowadze wszystkie zmiany zwiazane z ustawieniami\n # wywolam odpowiednie funkcje\n # self.next_auction()\n\n if self.licence_status == \"Valid\":\n time_string = time.strftime(\"%H:%M:%S\", time.localtime())\n self.clock_label.config(text=time_string)\n self.clock_label.after(1000, self.digital_clock)\n\n # tutaj bede wywylowyl inne funkcje\n self.next_auction()\n\n elif self.licence_status == \"Invalid\":\n print(\"Invalid licence\")\n self.cloak_status = \"Inactive\"\n unset_main_frame_values()\n elif self.internet_connection is False:\n print(\"No internet connection \")\n unset_main_frame_values()\n else:\n print(\"Unknown issue \")\n unset_main_frame_values()\n\n def next_auction(self):\n\n # gdy jest > odlicza (7 ... 1), gdy jest >= odlicza (6 ... 0)\n if self.auctions_list[self.auction_index] >= time.strftime(\"%H:%M:%S\", time.localtime()):\n self.next_auction_label.config(text=self.auctions_list[self.auction_index])\n next_auction_time = self.auctions_list[self.auction_index]\n else:\n\n if time.strftime(\"%H:%M:%S\", time.localtime()) < self.auctions_list[-1]:\n self.auction_index += 1\n\n else:\n self.auction_index = 0\n\n self.next_auction_label.config(text=self.auctions_list[self.auction_index])\n self.next_auction_time = self.auctions_list[self.auction_index]\n self.digital_timer()\n #self.next_auction_label.after(1000, self.next_auction)\n\n def find_auction_index(self):\n\n for clock in self.auctions_list:\n\n if clock > time.strftime(\"%H:%M:%S\", time.localtime()):\n self.auction_index = self.auctions_list.index(clock)\n break\n else:\n self.auction_index = 0\n\n print(\"auction index: \", self.auction_index)\n\n def make_auctions_list(self):\n\n def complete_time_value(value):\n # uzupelnia zmienne aby wyswietlac\n # prawidlowy format godziny, tj: dwa znaki\n\n value = str(value)\n\n if len(value) == 1:\n value = \"0\" + value\n\n return value\n\n def check_value(int_list):\n\n if int_list[2] >= 60:\n int_list[1] += 1\n int_list[2] = int_list[2] - 60\n\n if int_list[1] >= 60:\n int_list[0] += 1\n int_list[1] = int_list[1] - 60\n\n return int_list\n\n time_str = self.start_hour + \":\" + self.star_minute + \":\" + self.start_second\n end_str = self.end_hour + \":\" + self.end_minute + \":\" + self.end_second\n\n # te wartosci sa string-ami\n freq_list = [int(self.freq_hour), int(self.freq_minute), int(self.freq_second)]\n time_list = [int(self.start_hour), int(self.star_minute), int(self.start_second)]\n\n self.auctions_list = []\n\n while time_str <= end_str:\n self.auctions_list.append(time_str)\n # print(time_str)\n\n time_list[0] = time_list[0] + freq_list[0] # hour int\n time_list[1] = time_list[1] + freq_list[1] # minute int\n time_list[2] = time_list[2] + freq_list[2] # second int\n\n time_list = check_value(time_list)\n\n hour = complete_time_value(time_list[0])\n minute = complete_time_value(time_list[1])\n second = complete_time_value(time_list[2])\n\n time_str = hour + \":\" + minute + \":\" + second\n\n def digital_timer(self):\n\n def clock_calculator(next_time, current_time):\n\n if self.next_auction_time < actual_time:\n\n difference_time = [0, 0, 0]\n base_time = [24, 00, 00]\n\n next_time = next_time.split(\":\")\n current_time = current_time.split(\":\")\n remaining_time = [0, 0, 0]\n\n next_time[0] = int(next_time[0])\n next_time[1] = int(next_time[1])\n next_time[2] = int(next_time[2])\n\n current_time[0] = int(current_time[0])\n current_time[1] = int(current_time[1])\n current_time[2] = int(current_time[2])\n\n if current_time[2] < next_time[2]:\n current_time[1] -= 1\n current_time[2] += 60\n\n if current_time[1] < next_time[1]:\n current_time[0] -= 1\n current_time[1] += 60\n\n difference_time[0] = current_time[0] - next_time[0]\n difference_time[1] = current_time[1] - next_time[1]\n difference_time[2] = current_time[2] - next_time[2]\n\n if base_time[2] < difference_time[2]:\n base_time[1] -= 1\n base_time[2] += 60\n\n if base_time[1] < difference_time[1]:\n base_time[0] -= 1\n base_time[1] += 60\n\n remaining_time[0] = base_time[0] - difference_time[0]\n remaining_time[1] = base_time[1] - difference_time[1]\n remaining_time[2] = base_time[2] - difference_time[2]\n\n return remaining_time\n\n else:\n\n # print(next_time)\n next_time = next_time.split(\":\")\n current_time = current_time.split(\":\")\n remaining_time = [0, 0, 0]\n\n # str values, have to be changed\n next_time[0] = int(next_time[0])\n next_time[1] = int(next_time[1])\n next_time[2] = int(next_time[2])\n\n current_time[0] = int(current_time[0])\n current_time[1] = int(current_time[1])\n current_time[2] = int(current_time[2])\n\n if next_time[2] < current_time[2]:\n next_time[1] -= 1\n next_time[2] += 60\n\n if next_time[1] < current_time[1]:\n next_time[0] -= 1\n next_time[1] += 60\n\n # int values\n remaining_time[0] = next_time[0] - current_time[0]\n remaining_time[1] = next_time[1] - current_time[1]\n remaining_time[2] = next_time[2] - current_time[2]\n\n return remaining_time\n\n def complete_time_values(list_int):\n\n for i in range(3):\n if len(str(list_int[i])) < 2:\n list_int[i] = \"0\" + str(list_int[i])\n\n return str(list_int[0]) + \":\" + str(list_int[1]) + \":\" + str(list_int[2])\n\n\n\n actual_time = time.strftime(\"%H:%M:%S\", time.localtime())\n clock_calculator(str(self.next_auction_time), str(actual_time))\n\n remaining_time_str = complete_time_values(clock_calculator(str(self.next_auction_time), str(actual_time)))\n self.timer_label.config(text=remaining_time_str)\n self.display_prompt(remaining_time_str)\n\n def display_prompt(self, remaining_time):\n\n\n if remaining_time == \"00\" + \":\" + self.remind_minute + \":\" + self.remind_second:\n # alarm()\n if int(self.remind_minute) == 0:\n tkinter.messagebox.showinfo(\"Auction Reminder Assistant\",\n self.remind_second + \" seconds left to ending the auction.\")\n else:\n tkinter.messagebox.showinfo(\"Auction Reminder Assistant\", str(int(self.remind_minute)) + \":\" +\n self.remind_second + \" minutes left to ending the auction.\")\n\n\n ''' SETTINGS FRAME FUNCTIONS '''\n\n def render_settings_windows(self):\n print(\"\\nDISPLAY_settings\")\n\n #tutaj byly zmienne dotyczane godzin\n\n self.state_normal()\n self.clear()\n\n self.text_freq_hour.insert(1.0, str(self.freq_hour))\n self.text_freq_minute.insert(1.0, str(self.freq_minute))\n self.text_freq_second.insert(1.0, str(self.freq_second))\n\n self.text_start_hour.insert(1.0, str(self.start_hour))\n self.text_start_minute.insert(1.0, str(self.star_minute))\n self. text_start_second.insert(1.0, str(self.start_second))\n\n self.text_end_hour.insert(1.0, str(self.end_hour))\n self.text_end_minute.insert(1.0, str(self.end_minute))\n self.text_end_second.insert(1.0, str(self.end_second))\n\n # text_remind_hour.insert(1.0, \"00\")\n self.text_remind_minute.insert(1.0, str(self.remind_minute))\n self.text_remind_second.insert(1.0, str(self.remind_second))\n\n self.justify()\n self.state_disable()\n\n def default_config(self):\n self.edit()\n\n print(\"DEFAULT_settings\")\n\n self.freq_hour = \"01\"\n self.freq_minute = \"00\"\n self.freq_second = \"00\"\n\n self.start_hour = \"00\"\n self.star_minute = \"35\"\n self.start_second = \"00\"\n\n self.end_hour = \"23\"\n self.end_minute = \"59\"\n self.end_second = \"59\"\n\n self.remind_minute = \"01\"\n self.remind_second = \"00\"\n\n self.render_settings_windows()\n self.save()\n self.state_disable()\n\n def edit(self):\n print(\"EDIT_settings\")\n\n self.button_save.config(state=NORMAL)\n self.button_edit.config(state=DISABLED)\n\n self.state_normal()\n\n def save(self):\n\n print(\"SAVE_settings\")\n\n def find_errors(value, pos, err=None):\n\n hours_boxes = [1, 4, 7]\n minute_second_boxes = [2, 3, 5, 6, 8, 9, 11, 12]\n\n # pass_further = [0, None]\n\n if len(value) < 2 or len(value) > 2:\n err += 1\n\n # pass_further[0] += 1\n # pass_further[1] = 0\n\n if pos not in change_color:\n change_color.append(pos)\n else:\n try:\n int(value)\n\n if pos in hours_boxes and int(value) > 23:\n err += 1\n\n if pos not in change_color:\n change_color.append(pos)\n\n if pos in minute_second_boxes and int(value) > 59:\n err += 1\n\n if pos not in change_color:\n change_color.append(pos)\n except ValueError:\n err += 1\n\n if pos not in change_color:\n change_color.append(pos)\n\n return err\n\n def find_others_errors(err):\n\n pass_further = []\n error_name = 0\n\n # frequency cant be equal 0\n if self.freq_hour == \"00\" and self.freq_minute == \"00\" and self.freq_second == \"00\":\n\n if 1 not in change_color:\n change_color.append(1)\n if 2 not in change_color:\n change_color.append(2)\n if 3 not in change_color:\n change_color.append(3)\n\n err += 1\n error_name = 1\n # ending must be bigger than star\n elif self.end_hour + \":\" + self.end_minute + \":\" + self.end_second <= self.start_hour + \":\" + self.star_minute + \":\" + self.start_second:\n\n if 7 not in change_color:\n change_color.append(7)\n if 8 not in change_color:\n change_color.append(8)\n if 9 not in change_color:\n change_color.append(9)\n\n err += 1\n error_name = 2\n # remind before must be lower than frequency\n elif \"00\" + \":\" + self.remind_minute + \":\" + self.remind_second >= self.freq_hour + \":\" + self.freq_minute + \":\" + self.freq_second:\n\n if 11 not in change_color:\n change_color.append(11)\n if 12 not in change_color:\n change_color.append(12)\n\n err += 1\n error_name = 3\n\n pass_further.append(err)\n pass_further.append(error_name)\n\n return pass_further\n\n def mark_wrong_boxes(boxes_list):\n\n for num in boxes_list:\n\n if num == 1:\n self.text_freq_hour.config(bg=\"#ff7d66\")\n if num == 2:\n self.text_freq_minute.config(bg=\"#ff7d66\")\n if num == 3:\n self.text_freq_second.config(bg=\"#ff7d66\")\n if num == 4:\n self.text_start_hour.config(bg=\"#ff7d66\")\n if num == 5:\n self.text_start_minute.config(bg=\"#ff7d66\")\n if num == 6:\n self.text_start_second.config(bg=\"#ff7d66\")\n if num == 7:\n self.text_end_hour.config(bg=\"#ff7d66\")\n if num == 8:\n self.text_end_minute.config(bg=\"#ff7d66\")\n if num == 9:\n self.text_end_second.config(bg=\"#ff7d66\")\n if num == 11:\n self.text_remind_minute.config(bg=\"#ff7d66\")\n if num == 12:\n self.text_remind_second.config(bg=\"#ff7d66\")\n\n error = 0\n # error_type # 0-Value, 1-Frequency, 2-End time, 3-Frequency can't be equal remind before\n change_color = []\n\n # might be disable state\n\n self.freq_hour = self.text_freq_hour.get(1.0, END).strip()\n self.freq_minute = self.text_freq_minute.get(1.0, END).strip()\n self.freq_second = self.text_freq_second.get(1.0, END).strip()\n\n self.start_hour = self.text_start_hour.get(1.0, END).strip()\n self.star_minute = self.text_start_minute.get(1.0, END).strip()\n self.start_second = self.text_start_second.get(1.0, END).strip()\n\n self.end_hour = self.text_end_hour.get(1.0, END).strip()\n self.end_minute = self.text_end_minute.get(1.0, END).strip()\n self.end_second = self.text_end_second.get(1.0, END).strip()\n\n # remind_hour = text_remind_hour.get(1.0, END)\n self.remind_minute = self.text_remind_minute.get(1.0, END).strip()\n self.remind_second = self.text_remind_second.get(1.0, END).strip()\n\n error = find_errors(self.freq_hour, 1, error)\n #error_type.append(find_errors(freq_hour, 1, error)[1])\n\n error = find_errors(self.freq_minute, 2, error)\n error = find_errors(self.freq_second, 3, error)\n\n error = find_errors(self.start_hour, 4, error)\n error = find_errors(self.star_minute, 5, error)\n error = find_errors(self.start_second, 6, error)\n\n error = find_errors(self.end_hour, 7, error)\n error = find_errors(self.end_minute, 8, error)\n error = find_errors(self.end_second, 9, error)\n\n error = find_errors(self.remind_minute, 11, error)\n error = find_errors(self.remind_second, 12, error)\n\n if error == 0:\n error = find_others_errors(error)[0]\n error_type = find_others_errors(error)[1]\n else:\n error_type = 0\n\n # DO zmiany\n if error == 0:\n\n self.button_edit.config(state=NORMAL)\n self.button_save.config(state=DISABLED)\n\n user_config = {\n \"frequency\": {\n \"freq_hour\": None,\n \"freq_minute\": None,\n \"freq_second\": None,\n },\n \"start\": {\n \"start_hour\": None,\n \"start_minute\": None,\n \"start_second\": None,\n },\n \"end\": {\n \"end_hour\": None,\n \"end_minute\": None,\n \"end_second\": None\n },\n \"remind\": {\n \"remind_minute\": None,\n \"remind_second\": None\n }\n }\n\n user_config[\"frequency\"][\"freq_hour\"] = self.freq_hour\n user_config[\"frequency\"][\"freq_minute\"] = self.freq_minute\n user_config[\"frequency\"][\"freq_second\"] = self.freq_second\n\n user_config[\"start\"][\"start_hour\"] = self.start_hour\n user_config[\"start\"][\"start_minute\"] = self.star_minute\n user_config[\"start\"][\"start_second\"] = self.start_second\n\n user_config[\"end\"][\"end_hour\"] = self.end_hour\n user_config[\"end\"][\"end_minute\"] = self.end_minute\n user_config[\"end\"][\"end_second\"] = self.end_second\n\n user_config[\"remind\"][\"remind_minute\"] = self.remind_minute\n user_config[\"remind\"][\"remind_second\"] = self.remind_second\n\n #print(user_config)\n\n json_file = open(\"config.json\", \"w\")\n json_file.write(json.dumps(user_config, indent=4))\n json_file.close()\n\n self.white_texts_background()\n self.justify()\n self.state_disable()\n self.render_settings_windows()\n\n # TODO\n # nie wiem czy takie cos wystarczy czy trzeba zrobic cos lepszego\n self.make_auctions_list()\n self.find_auction_index()\n # self.update_main_window() - stara funkcja\n else:\n self.white_texts_background()\n mark_wrong_boxes(change_color)\n if error_type == 0:\n tkinter.messagebox.showerror(\"Auction Reminder Assistant\",\n \"Time_Clock_Value_Error\\n\\nYou have inputted too big values or they have wrong format!\\nPlease, \"\n \"correct these mistakes.\")\n elif error_type == 1:\n tkinter.messagebox.showerror(\"Auction Reminder Assistant\",\n \"Time_Clock_Value_Error\\n\\nFrequency can't be equal zero!\\nPlease, \"\n \"correct this mistake.\")\n elif error_type == 2:\n tkinter.messagebox.showerror(\"Auction Reminder Assistant\",\n \"Time_Clock_Value_Error\\n\\nEnding time must be greater than Starting \"\n \"time!\\nPlease, correct this mistake.\")\n elif error_type == 3:\n tkinter.messagebox.showerror(\"Auction Reminder Assistant\",\n \"Time_Clock_Value_Error\\n\\nRemind time must be lower than Frequency \"\n \"time!\\nPlease, correct this mistake.\")\n\n change_color.clear()\n\n def state_normal(self):\n\n self.text_freq_hour.config(state=NORMAL)\n self.text_freq_minute.config(state=NORMAL)\n self.text_freq_second.config(state=NORMAL)\n\n self.text_start_hour.config(state=NORMAL)\n self.text_start_minute.config(state=NORMAL)\n self.text_start_second.config(state=NORMAL)\n\n self.text_end_hour.config(state=NORMAL)\n self.text_end_minute.config(state=NORMAL)\n self.text_end_second.config(state=NORMAL)\n\n # text_remind_hour.config(state=NORMAL)\n self.text_remind_minute.config(state=NORMAL)\n self.text_remind_second.config(state=NORMAL)\n\n def state_disable(self):\n\n self.text_freq_hour.config(state=DISABLED)\n self.text_freq_minute.config(state=DISABLED)\n self.text_freq_second.config(state=DISABLED)\n\n self.text_start_hour.config(state=DISABLED)\n self.text_start_minute.config(state=DISABLED)\n self.text_start_second.config(state=DISABLED)\n\n self.text_end_hour.config(state=DISABLED)\n self.text_end_minute.config(state=DISABLED)\n self.text_end_second.config(state=DISABLED)\n\n # text_remind_hour.config(state=DISABLED)\n self.text_remind_minute.config(state=DISABLED)\n self.text_remind_second.config(state=DISABLED)\n\n def white_texts_background(self):\n\n self.text_freq_hour.config(bg=\"white\")\n self.text_freq_minute.config(bg=\"white\")\n self.text_freq_second.config(bg=\"white\")\n\n self.text_start_hour.config(bg=\"white\")\n self.text_start_minute.config(bg=\"white\")\n self.text_start_second.config(bg=\"white\")\n\n self.text_end_hour.config(bg=\"white\")\n self.text_end_minute.config(bg=\"white\")\n self.text_end_second.config(bg=\"white\")\n\n self.text_remind_minute.config(bg=\"white\")\n self.text_remind_second.config(bg=\"white\")\n\n def clear(self):\n\n self.text_freq_hour.delete(1.0, END)\n self.text_freq_minute.delete(1.0, END)\n self.text_freq_second.delete(1.0, END)\n\n self.text_start_hour.delete(1.0, END)\n self.text_start_minute.delete(1.0, END)\n self.text_start_second.delete(1.0, END)\n\n self.text_end_hour.delete(1.0, END)\n self.text_end_minute.delete(1.0, END)\n self.text_end_second.delete(1.0, END)\n\n # text_remind_hour.delete(1.0, END)\n self.text_remind_minute.delete(1.0, END)\n self.text_remind_second.delete(1.0, END)\n\n def justify(self):\n\n self.text_freq_hour.tag_configure(\"center\", justify='center')\n self.text_freq_minute.tag_configure(\"center\", justify='center')\n self.text_freq_second.tag_configure(\"center\", justify='center')\n\n self.text_start_hour.tag_configure(\"center\", justify='center')\n self.text_start_minute.tag_configure(\"center\", justify='center')\n self.text_start_second.tag_configure(\"center\", justify='center')\n\n self.text_end_hour.tag_configure(\"center\", justify='center')\n self.text_end_minute.tag_configure(\"center\", justify='center')\n self.text_end_second.tag_configure(\"center\", justify='center')\n\n # text_remind_hour.tag_configure(\"center\", justify='center')\n self.text_remind_minute.tag_configure(\"center\", justify='center')\n self.text_remind_second.tag_configure(\"center\", justify='center')\n\n self.text_freq_hour.tag_add(\"center\", \"1.0\", \"end\")\n self.text_freq_minute.tag_add(\"center\", \"1.0\", \"end\")\n self.text_freq_second.tag_add(\"center\", \"1.0\", \"end\")\n\n self.text_start_hour.tag_add(\"center\", \"1.0\", \"end\")\n self.text_start_minute.tag_add(\"center\", \"1.0\", \"end\")\n self.text_start_second.tag_add(\"center\", \"1.0\", \"end\")\n\n self.text_end_hour.tag_add(\"center\", \"1.0\", \"end\")\n self.text_end_minute.tag_add(\"center\", \"1.0\", \"end\")\n self.text_end_second.tag_add(\"center\", \"1.0\", \"end\")\n\n # text_remind_hour.tag_add(\"center\", \"1.0\", \"end\")\n self.text_remind_minute.tag_add(\"center\", \"1.0\", \"end\")\n self.text_remind_second.tag_add(\"center\", \"1.0\", \"end\")\n\n # config.json\n def whether_config_exist(self):\n print(\"WHETHER FILE EXIST\")\n # It looks like, your settings file has been deleted.\n # Please input your settings again.\n\n default_config = {\n \"frequency\": {\n \"freq_hour\": \"00\",\n \"freq_minute\": \"01\",\n \"freq_second\": \"00\"\n },\n \"start\": {\n \"start_hour\": \"00\",\n \"start_minute\": \"35\",\n \"start_second\": \"00\"\n },\n \"end\": {\n \"end_hour\": \"23\",\n \"end_minute\": \"59\",\n \"end_second\": \"59\"\n },\n \"remind\": {\n \"remind_minute\": \"01\",\n \"remind_second\": \"00\"\n }\n }\n\n try:\n json_file = open(\"config.json\")\n # whether_file_is_complete()\n json_file.close()\n except FileNotFoundError:\n tkinter.messagebox.showerror(\"Auction Reminder Assistant\",\n \"File_Not_Found_Error:\\n\\nIt looks like, your settings file has been deleted, \"\n \"has changed directory or has an inappropriate name.\\n\\nDefault settings will be recovered.\", )\n\n json_file = open(\"config.json\", \"w\")\n json_file.write(json.dumps(default_config, indent=4))\n # file.write(\"01:00:00\\n\" + \"00:35:00\\n\" + \"23:59:59\\n\" + \"00:01:00\")\n json_file.close()\n\n def load_config_json(self):\n print(\"LOAD_CONFIG_JSON\")\n\n json_file = open(\"config.json\", \"r\")\n user_config = json.load(json_file)\n json_file.close()\n\n self.freq_hour = user_config[\"frequency\"][\"freq_hour\"]\n self.freq_minute = user_config[\"frequency\"][\"freq_minute\"]\n self.freq_second = user_config[\"frequency\"][\"freq_second\"]\n\n self.start_hour = user_config[\"start\"][\"start_hour\"]\n self.star_minute = user_config[\"start\"][\"start_minute\"]\n self.start_second = user_config[\"start\"][\"start_second\"]\n\n self.remind_minute = user_config[\"remind\"][\"remind_minute\"]\n self.remind_second = user_config[\"remind\"][\"remind_second\"]\n\n\n ''' FUNCTIONS TO CHECKING '''\n def check_internet_connection(self):\n # INFORMACJA:\n # polaczenie z internetem sprawdzam przed kazda czynosci ktora tego wymaga\n\n try:\n # connect to the host -- tells us if the host is actually\n # reachable\n socket.create_connection((\"1.1.1.1\", 53))\n print(\"\\nInternet connection exist\")\n self.internet_connection = True\n\n except OSError:\n print(\"No Internet connection\")\n self.internet_connection = False\n self.info_label_4.config(text=\"No Internet connection\")\n\n self.info_label_4.after(900000, self.check_internet_connection)\n\n def read_user_auth_key(self):\n # if zero data, then verify is the only one options\n\n read_auth_key = \"none\"\n\n try:\n auth_key_file = open(\"auth_key_file.txt\", \"r\")\n read_auth_key = auth_key_file.readline()\n self.auth_key_origin = \"read\"\n self.user_auth_key = read_auth_key\n print(\"Auth key: \" + read_auth_key + \" read from local computer\")\n auth_key_file.close()\n\n # check_auth_key_in_database(read_auth_key)\n\n except FileNotFoundError:\n print(\"Auth_key_file doesn't exist\")\n self.user_auth_key = \"none\"\n # Jesli nie ma pliku, to sa wyswietlane ustawienia \"domyslne\" okna\n\n # print(\"read_auth_key: \" + read_auth_key)\n\n if self.internet_connection is True:\n if read_auth_key != \"none\" and len(read_auth_key) > 0:\n self.check_auth_key_in_database(read_auth_key)\n # self.check_auth_key_in_database(read_auth_key)\n else:\n self.render_licence_window(self.licence_status, read_auth_key, \"none\")\n # if len(read_auth_key) == 0:\n # self.render_licence_window(self.licence_status, \"none\", \"none\")\n # else:\n # self.render_licence_window(self.licence_status, read_auth_key, \"none\")\n\n def get_current_date_from_server(self):\n # HOW PYTHON WORKS WITH PHP\n # Czy to jest bezpieczne ?\n url = 'http://localhost/Auction%20Reminder/php_server/current_date.php'\n response = urllib.request.urlopen(url)\n string_from_url = response.read().decode(\"utf-8\")\n server_date = json.loads(string_from_url)\n\n # print(type(server_date))\n # print(server_date['fulldate'])\n\n return server_date\n\n def check_auth_key_in_database(self, auth_key):\n\n\n # Opis dzialania\n # 1 sprawdz auth key\n # a) jesli istnieje pobierze reszte danych\n # b) jesli nie zwroc blad\n\n try:\n db_conn = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"\",\n database=\"auction_reminder\",\n port=33060\n )\n except mysql.connector.Error as err:\n print(\"Database issue, validation impossible\\n\")\n #print(err)\n\n # licence_window()\n self.render_licence_window(None, auth_key, None, \"Database issue, validation impossible\")\n self.light_diode_up()\n return\n\n # POBIERAM DANE Z SERWERA\n db_request = db_conn.cursor()\n db_request.execute(\"SELECT username, auth_key, status FROM generated_auth_keys WHERE auth_key= %s\", (auth_key,))\n req_result = db_request.fetchall()\n\n if len(req_result) == 0:\n # Jesli pusta wartosc, znaczy ze nie ma takiego auth key\n print(\"Invalid auth key, doesn't exist in database\")\n\n # licence_status = \"invalid\"\n\n # jesli mniejsze od zera przy wczytaniu jest napis none\n\n self.render_licence_window(self.licence_status, auth_key, \"Invalid\")\n self.light_diode_up()\n\n return\n else:\n\n username = req_result[0][0]\n status = req_result[0][2]\n\n if status == \"used\":\n # oznaca to ze ten auth key ejst juz wykorzystany\n self.render_licence_window(None, None, None, \"This auth key is already used\")\n self.light_diode_up()\n return\n\n else:\n # Jesli auth key istnieje i jest poprawny, sprawdzamy waznosc licencji\n # do niego przypisanej i pobieramy dane po to aby przerwac dzialanie porgramu\n # jesli licencja straci waznosc\n\n db_request.execute(\"SELECT expiry_date FROM licence_informations WHERE username=%s\", (username,))\n req_result = db_request.fetchall()\n\n self.licence_expiry_date = req_result[0][0] # datetime object\n self.current_server_date = self.get_current_date_from_server() # dictionary (int)\n\n print(\"Current date: \" + self.current_server_date[\"fulldate\"])\n print(\"Expiry date: \" + str(self.licence_expiry_date))\n\n self.licence_status = self.compare_dates(self.current_server_date, self.licence_expiry_date)\n if self.licence_status == \"Valid\":\n print(\"Licence is valid\")\n\n # ZAPOBIEGA PRZED KILKUKROTNYM WYWOLANIEM ZEGARA\n if self.licence_status == \"Valid\" and self.cloak_status == \"Inactive\":\n self.make_auctions_list()\n self.find_auction_index()\n\n self.digital_clock()\n self.cloak_status = \"Active\"\n else:\n print(\"Prevent from multi using\")\n\n # Poniewaz caly program zaczynamy od wczytania licencji z pliku nalezy\n # ten plik w tym miejscu zaktualizowac, poniewz podano poprawny auth key\n\n # sprawdzam czy auth key byl wczytany z pliku, czy podany przez uzytkownika\n if self.auth_key_origin == \"input\":\n print(\"Auth key in local computer changed successful\")\n auth_key_file = open(\"auth_key_file.txt\", \"w\")\n auth_key_file.write(auth_key)\n auth_key_file.close()\n\n else:\n print(\"Licence is expired\")\n\n # Sorry, your licence expired\n # Go to our website buy new licence\n\n self.render_licence_window(self.licence_status, auth_key, \"Valid\")\n self.light_diode_up()\n\n\n\n\n db_conn.close()\n\n def compare_dates(self, current_date, expiry_date):\n\n # check YEAR\n if current_date['year'] > expiry_date.year:\n return \"Invalid\"\n elif current_date['year'] == expiry_date.year:\n\n # check MONTH\n if current_date['month'] > expiry_date.month:\n return \"Invalid\"\n elif current_date['month'] == expiry_date.month:\n\n # check DAY\n if current_date['day'] > expiry_date.day:\n return \"Invalid\"\n elif current_date['day'] == expiry_date.day:\n\n # check HOUR\n if current_date['hour'] > expiry_date.hour:\n return \"Invalid\"\n elif current_date['hour'] == expiry_date.hour:\n\n # check MINUTE\n if current_date['minute'] > expiry_date.minute:\n return \"Invalid\"\n elif current_date['minute'] == expiry_date.minute:\n\n # check SECOND\n if current_date['second'] > expiry_date.second:\n return \"Invalid\"\n else:\n return \"Valid\"\n\n else:\n return \"Valid\"\n else:\n return \"Valid\"\n else:\n return \"Valid\"\n else:\n return \"Valid\"\n else:\n return \"Valid\"\n\n ###########################################################\n\n def verify_licence(self):\n\n self.check_internet_connection()\n\n if self.internet_connection is True:\n\n inputted_auth_key = self.text_enter_licence.get(1.0, END).strip()\n self.auth_key_origin = \"input\"\n self.user_auth_key = inputted_auth_key\n print(\"Auth key: \" + inputted_auth_key + \" inputted by user\")\n self.check_auth_key_in_database(inputted_auth_key)\n\n else:\n # tutaj nie podaje zadnych argumentow do funkcji bo sprawdzanie stanu\n # polaczenia jest na pierwszym miejscu\n self.render_licence_window()\n\n # ZAPOBIEGA PRZED KILKUKROTNYM WYWOLANIEM ZEGARA\n # if self.licence_status == \"Valid\" and self.cloak_status == \"Inactive\":\n # self.digital_clock()\n # self.cloak_status = \"Active\"\n # else:\n # print(\"Prevent from multi using\")\n\n def render_licence_window(self, lic_stat=None, auth_key=None, input_stat=None, other=None):\n\n # cala ta funckje musze przebudowac\n # musze przewidziec mozliwie jak najwiecej bledow ktore moga wystapic podczas\n # uzytkowania programu, nazwac je i dla kazdej z nazw zrobic osobe renderowaine okna licencij\n\n #TODO:\n # Nowe nazwy bledow:\n # 1) Brak polaczenia z internetem: 'No internet connection'\n # 2) Bład bazy danych: 'Database issue, validation impossible'\n # 3) Prawidłowy auth_key z wazna licencja: 'Verification successful'\n # 4) Wpisany auth_key jest juz w uzyciu: 'This auth key is already used'\n # 5) Niepoprawny auth_key: 'Invalid auth key'\n # 6) Aktualny auth_key jest poprawny, nowy auth_key nie jest poprawny/wazny: 'Changes not applied, invalid auth key'\n # 7) Licencja wygasła: 'Licence expired'\n # 8) Plik z auth_key nie istnieje: 'Licence status=Invalid Auth key=none'\n # 9) Plik za auth_key istnieje, pokazuje jakis auth key jest w srodku(jak len=0 to none)\n\n # print(\"lic_stat: \" + str(lic_stat))\n # print(\"auth_key: \" + str(auth_key))\n # print(\"input_stat: \" + str(input_stat))\n # print(\"other: \" + str(other))\n # print(\"\\n\")\n\n if auth_key is not None and len(auth_key) == 0: auth_key = \"none\"\n\n if self.internet_connection is False:\n self.label_validation_info.config(text=\"Validation impossible, no Internet connection\")\n self.label_valid_invalid.config(text=\"Invalid\", fg=\"red\", )\n self.label_auth_key_value.config(text=auth_key, fg=\"red\", )\n elif other is not None:\n\n self.label_valid_invalid.config(text=\"Invalid\", fg=\"red\", )\n self.label_auth_key_value.config(text=auth_key, fg=\"red\", )\n self.label_validation_info.config(text=other)\n\n else:\n\n # stylizuje status licencji\n if lic_stat == \"Valid\" and input_stat == \"Valid\":\n self.label_valid_invalid.config(text=\"Valid\", fg=\"#33cc33\", )\n self.label_auth_key_value.config(text=auth_key, fg=\"#33cc33\", )\n\n if lic_stat == \"Invalid\" and input_stat == \"Valid\":\n self.label_valid_invalid.config(text=\"Invalid\", fg=\"red\", )\n self.label_auth_key_value.config(text=auth_key, fg=\"red\", )\n\n if lic_stat == \"Invalid\" and input_stat == \"Invalid\":\n self.label_valid_invalid.config(text=\"Invalid\", fg=\"red\", )\n self.label_auth_key_value.config(text=auth_key, fg=\"red\", )\n\n # przypadek gdy serwer usunie niaktywna licencje\n if lic_stat == \"Invalid\" and input_stat is None:\n self.label_valid_invalid.config(text=\"Invalid\", fg=\"red\", )\n self.label_auth_key_value.config(text=auth_key, fg=\"red\", )\n\n\n # stylizuje komunikaty o bledach\n if lic_stat == \"Valid\" and input_stat == \"Valid\":\n\n if self.auth_key_origin == \"input\":\n self.label_validation_info.config(text=\"Verification successful\")\n self.label_validation_info.config(fg=\"#33cc33\")\n\n if lic_stat == \"Valid\" and input_stat == \"Invalid\":\n self.label_validation_info.config(text=\"Changes not applied, invalid auth key\")\n self.label_validation_info.config(fg=\"red\")\n\n if lic_stat == \"Invalid\" and input_stat == \"Valid\":\n # nie wiem czy w poprawnie dzialjacy serwerze i bazie danych\n # taka sytuacja moze sie wydarzyc, chodzi tutaj o okresowe\n # usuwanie nieaktywnych licencji\n self.label_validation_info.config(text=\"Licence expired\")\n self.label_validation_info.config(fg=\"red\")\n\n if lic_stat == \"Invalid\" and input_stat == \"Invalid\":\n self.label_validation_info.config(text=\"Invalid auth key\")\n self.label_validation_info.config(fg=\"red\")\n\n if lic_stat == \"Invalid\" and input_stat is None:\n self.label_validation_info.config(text=\"Licence expired\")\n self.label_validation_info.config(fg=\"red\")\n\n\n ''' INFINITY CHECKING FUNCTIONS'''\n def check_licence_remaining_time(self):\n # ta funkcja co 15min bedzie sprawdzac status licencji na podstawie\n # wprowadzonego auth key\n\n self.current_server_date = self.get_current_date_from_server() # dictionary (int)\n\n if self.current_server_date is not None and self.licence_expiry_date is not None:\n\n if self.compare_dates(self.current_server_date, self.licence_expiry_date) == \"Valid\":\n\n print(\"Licence is still valid: \" + self.user_auth_key)\n self.label_validation_info.after(90000, self.check_licence_remaining_time)\n\n else:\n print(\"Licence has just expired: \" + self.user_auth_key)\n self.licence_status = \"Invalid\"\n # TODO: odpowiednie rendwrowanie okna Licence\n else:\n print(\"Good auth key hasn't been entered yet\")\n self.label_validation_info.after(90000, self.check_licence_remaining_time)\n\n\nroot = Tk()\n\napp = AuctionReminder(root)\n\napp.whether_config_exist()\napp.load_config_json()\napp.render_settings_windows()\n\napp.check_internet_connection()\napp.read_user_auth_key()\n\napp.check_licence_remaining_time()\n\nroot.mainloop()\n\n\n\n\n\n", "repo_name": "rafii2000/Auction-Reminder", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 57283, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "tkinter.ttk.Frame", "line_number": 71, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 71, "usage_type": "name"}, {"api_name": "tkinter.ttk.Frame", "line_number": 72, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 72, "usage_type": "name"}, {"api_name": "tkinter.ttk.Frame", "line_number": 73, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 73, "usage_type": "name"}, {"api_name": "tkinter.ttk.Frame", "line_number": 74, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 74, "usage_type": "name"}, {"api_name": "tkinter.ttk.Frame", "line_number": 83, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 83, "usage_type": "name"}, {"api_name": "tkinter.ttk.Button", "line_number": 104, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 104, "usage_type": "name"}, {"api_name": "tkinter.ttk.Button", "line_number": 108, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 108, "usage_type": "name"}, {"api_name": "tkinter.ttk.Button", "line_number": 112, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 112, "usage_type": "name"}, {"api_name": "tkinter.ttk.Button", "line_number": 116, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 116, "usage_type": "name"}, {"api_name": "tkinter.ttk.Button", "line_number": 250, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 250, "usage_type": "name"}, {"api_name": "tkinter.ttk.Button", "line_number": 251, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 251, "usage_type": "name"}, {"api_name": "tkinter.ttk.Button", "line_number": 252, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 252, "usage_type": "name"}, {"api_name": "time.strftime", "line_number": 436, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 436, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 457, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 457, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 462, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 462, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 477, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 477, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 623, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 623, "usage_type": "call"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 636, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 636, "usage_type": "attribute"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 639, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 639, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 909, "usage_type": "call"}, {"api_name": "tkinter.messagebox.showerror", "line_number": 926, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 926, "usage_type": "attribute"}, {"api_name": "tkinter.messagebox.showerror", "line_number": 930, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 930, "usage_type": "attribute"}, {"api_name": "tkinter.messagebox.showerror", "line_number": 934, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 934, "usage_type": "attribute"}, {"api_name": "tkinter.messagebox.showerror", "line_number": 938, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 938, "usage_type": "attribute"}, {"api_name": "tkinter.messagebox.showerror", "line_number": 1082, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 1082, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 1087, "usage_type": "call"}, {"api_name": "json.load", "line_number": 1095, "usage_type": "call"}, {"api_name": "socket.create_connection", "line_number": 1118, "usage_type": "call"}, {"api_name": "urllib.request.request.urlopen", "line_number": 1166, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 1166, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 1166, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 1168, "usage_type": "call"}, {"api_name": "mysql.connector.connector.connect", "line_number": 1184, "usage_type": "call"}, {"api_name": "mysql.connector.connector", "line_number": 1184, "usage_type": "attribute"}, {"api_name": "mysql.connector", "line_number": 1184, "usage_type": "name"}, {"api_name": "mysql.connector.connector", "line_number": 1191, "usage_type": "attribute"}, {"api_name": "mysql.connector", "line_number": 1191, "usage_type": "name"}]} +{"seq_id": "33151025310", "text": "import copy\nimport os\nfrom typing import Any, Dict, Optional\n\nimport cv2\nimport numpy as np\nfrom easydict import EasyDict\n\nfrom pvp_iclr_release.utils.carla.core.utils.others.config_helper import deep_merge_dicts\nfrom pvp_iclr_release.utils.carla.core.utils.others.image_helper import GifMaker, VideoMaker, show_image\n\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\n\n\ndef draw_texts(data_dict, canvas, color=BLACK, thick=2):\n def _write(text, i, j, fontsize=0.4, choose_color=color):\n rows = [x * (canvas.shape[0] // 30) for x in range(10 + 1)]\n cols = [x * (canvas.shape[1] // 15) for x in range(9 + 1)]\n cv2.putText(\n canvas, text, (cols[j], rows[i]), cv2.FONT_HERSHEY_SIMPLEX, fontsize, choose_color, thick, cv2.LINE_AA\n )\n\n if canvas.shape[0] > 600:\n fontsize = canvas.shape[0] * 0.0008\n else:\n fontsize = 0.4\n\n left_text_pos = 1\n left_text_horizontal_pos = 3\n if 'command' in data_dict:\n _command = {\n -1: 'VOID',\n 1: 'LEFT',\n 2: 'RIGHT',\n 3: 'STRAIGHT',\n 4: 'FOLLOW',\n 5: 'CHANGE LEFT',\n 6: 'CHANGE RIGHT',\n }.get(data_dict['command'], '???')\n _write('Command: ' + _command, left_text_pos, left_text_horizontal_pos, fontsize=fontsize)\n left_text_pos += 1\n if 'agent_state' in data_dict:\n _state = {\n -1: 'VOID',\n 1: 'NAVIGATING',\n 2: 'BLOCKED_BY_VEHICLE',\n 3: 'BLOCKED_BY_WALKER',\n 4: 'BLOCKED_RED_LIGHT',\n 5: 'BLOCKED_BY_BIKE',\n }.get(data_dict['agent_state'], '???')\n _write('Agent State: ' + _state, left_text_pos, left_text_horizontal_pos, fontsize=fontsize)\n left_text_pos += 1\n if 'speed' in data_dict:\n text = 'Speed: {:04.1f}'.format(data_dict['speed_kmh'])\n # if 'speed_limit' in data_dict:\n # text += '/{:.1f}'.format(data_dict['speed_limit'] * 3.6)\n text += \" km/h\"\n _write(text, left_text_pos, left_text_horizontal_pos, fontsize=fontsize)\n left_text_pos += 1\n if 'steer' in data_dict and 'throttle' in data_dict and 'brake' in data_dict:\n _write('Steer: {:.3f}'.format(data_dict['steer']), left_text_pos, left_text_horizontal_pos, fontsize=fontsize)\n _write('Throttle: {:.3f}'.format(data_dict['throttle']), left_text_pos + 1, left_text_horizontal_pos,\n fontsize=fontsize)\n _write('Brake: {:.3f}'.format(data_dict['brake']), left_text_pos + 2, left_text_horizontal_pos,\n fontsize=fontsize)\n left_text_pos += 3\n if data_dict.get('takeover', False):\n if color == BLACK:\n _write('Taking Over!', left_text_pos, left_text_horizontal_pos, fontsize=fontsize)\n else:\n _write('Taking Over!', left_text_pos, left_text_horizontal_pos, fontsize=fontsize, choose_color=(0, 255, 0))\n left_text_pos += 1\n\n right_text_pos = 1\n if 'total_step' in data_dict:\n _write('Total Step: {} ({:02d}:{:04.1f})'.format(\n data_dict[\"total_step\"], int(data_dict[\"total_time\"] // 60), data_dict[\"total_time\"] % 60\n ), right_text_pos, 9, fontsize=fontsize)\n right_text_pos += 1\n # if 'total_lights' in data_dict and 'total_lights_ran' in data_dict:\n # text = 'Lights Ran: %d/%d' % (data_dict['total_lights_ran'], data_dict['total_lights'])\n # _write(text, right_text_pos, 9, fontsize=fontsize)\n # right_text_pos += 1\n if 'takeover_rate' in data_dict:\n _write('Takeover Rate: {:04.1f} %'.format(100 * data_dict[\"takeover_rate\"]), right_text_pos, 9,\n fontsize=fontsize)\n right_text_pos += 1\n if 'distance_to_go' in data_dict:\n text = 'Distance to go: %.1f' % data_dict['distance_to_go']\n if 'distance_total' in data_dict:\n text += '/{:.1f} ({:04.1f} %)'.format(\n data_dict['distance_total'], 100 * (1 - data_dict['distance_to_go'] / data_dict['distance_total'])\n )\n _write(text, right_text_pos, 9, fontsize=fontsize)\n right_text_pos += 1\n if 'tick' in data_dict:\n text = 'Step: %d' % data_dict['tick']\n if 'end_timeout' in data_dict:\n text += '/%d' % data_dict['end_timeout']\n _write(text, right_text_pos, 9, fontsize=fontsize)\n right_text_pos += 1\n if 'reward' in data_dict:\n text = 'Reward: %.02f' % data_dict['reward']\n if 'episode_reward' in data_dict:\n text += '/%.02f' % data_dict['episode_reward']\n _write(text, right_text_pos, 9, fontsize=fontsize)\n right_text_pos += 1\n if 'FPS' in data_dict:\n _write('FPS: %04.1f' % data_dict['FPS'], right_text_pos, 9, fontsize=fontsize)\n right_text_pos += 1\n if data_dict.get('stuck', False):\n _write('Stuck!', right_text_pos, 9, fontsize=fontsize)\n right_text_pos += 1\n if data_dict.get('ran_light', False):\n _write('Ran light!', right_text_pos, 9, fontsize=fontsize)\n right_text_pos += 1\n if data_dict.get('off_road', False):\n _write('Off road!', right_text_pos, 9, fontsize=fontsize)\n right_text_pos += 1\n if data_dict.get('wrong_direction', False):\n if color == BLACK:\n _write('Wrong direction!', right_text_pos, 9, fontsize=fontsize)\n else:\n _write('Wrong direction!', right_text_pos, 9, fontsize=fontsize, choose_color=(255, 0, 0))\n right_text_pos += 1\n\n\nclass Visualizer(object):\n \"\"\"\n Visualizer is used to visualize sensor data and print info during running.\n It can be used to show a sensor image on screen, save a gif or video file.\n\n :Arguments:\n - cfg (Dict): Config dict.\n\n :Interfaces: init, paint, run_visualize, done\n \"\"\"\n _name = None\n _canvas = None\n _gif_maker = None\n _video_maker = None\n _already_show_window = False\n config = dict(\n show_text=True,\n outputs=list(),\n save_dir='',\n frame_skip=0,\n min_size=400,\n location=None,\n )\n\n def __init__(self, cfg: Dict) -> None:\n if 'cfg_type' not in cfg:\n self._cfg = self.__class__.default_config()\n self._cfg = deep_merge_dicts(self._cfg, cfg)\n else:\n self._cfg = cfg\n\n self._text = self._cfg.show_text\n self._outputs = self._cfg.outputs\n self._save_dir = self._cfg.save_dir\n\n self._count = 0\n self._frame_skip = self._cfg.frame_skip\n\n if self._save_dir != '':\n os.makedirs(self._save_dir, exist_ok=True)\n\n def init(self, name: str) -> None:\n \"\"\"\n Initlaize visualizer with provided name.\n\n :Arguments:\n - name (str): Name for window or file.\n \"\"\"\n self._name = \"CARLA Simulator 0.9.10.1\"\n # cv2.waitKey(1)\n if 'gif' in self._outputs:\n self._gif_maker = GifMaker()\n if 'video' in self._outputs:\n self._video_maker = VideoMaker()\n self._video_maker.init(self._save_dir, self._name)\n\n def paint(self, image: Any, data_dict: Optional[Dict] = None) -> None:\n \"\"\"\n Paint canvas with observation images and data.\n\n :Arguments:\n - image: Rendered image.\n - data_dict(Dict, optional): data dict containing information, state, action and so on\n \"\"\"\n if data_dict is None:\n data_dict = {}\n self._canvas = np.uint8(image.copy())\n\n h, w = self._canvas.shape[:2]\n if min(h, w) < self._cfg.min_size:\n rate = self._cfg.min_size / min(h, w)\n self._canvas = resize_birdview(self._canvas, rate)\n\n if not self._already_show_window:\n move_window(self._name, self._cfg[\"location\"], image_x=self._canvas.shape[1], image_y=self._canvas.shape[0])\n self._already_show_window = True\n\n if not self._text:\n return\n\n draw_texts(data_dict, self._canvas, BLACK, thick=5)\n draw_texts(data_dict, self._canvas, WHITE, thick=2)\n\n def run_visualize(self) -> None:\n \"\"\"\n Run one step visualizer. Update file handler or show screen.\n \"\"\"\n if self._canvas is None:\n return\n self._count += 1\n if self._count > self._frame_skip:\n if 'gif' in self._outputs:\n self._gif_maker.add(self._name, self._canvas)\n if 'video' in self._outputs:\n self._video_maker.add(self._canvas)\n self._count = 0\n if 'show' in self._outputs:\n show_image(self._canvas, name=self._name)\n\n def done(self) -> None:\n \"\"\"\n Save file or release file writter, destroy windows.\n \"\"\"\n if self._gif_maker is not None:\n self._gif_maker.save(self._name, self._save_dir, self._name + '.gif')\n self._gif_maker.clear(self._name)\n if self._video_maker is not None:\n self._video_maker.clear()\n # if 'show' in self._outputs:\n # cv2.destroyAllWindows()\n\n @property\n def canvas(self):\n return self._canvas\n\n @classmethod\n def default_config(cls: type) -> EasyDict:\n cfg = EasyDict(cls.config)\n cfg.cfg_type = cls.__name__ + 'Config'\n return copy.deepcopy(cfg)\n\n\ndef resize_birdview(img, rate):\n assert len(img.shape) == 3\n img_res_list = []\n for i in range(img.shape[2]):\n img_slice = img[..., i]\n img_slice_res = cv2.resize(img_slice, None, fx=rate, fy=rate, interpolation=cv2.INTER_NEAREST)\n img_res_list.append(img_slice_res)\n img_res = np.stack(img_res_list, axis=2)\n return img_res\n\n\ndef move_window(name, location, image_x, image_y, monitor_index=1):\n \"\"\"monitor_index starts by 0.\"\"\"\n from screeninfo import get_monitors\n monitors = get_monitors()\n assert monitor_index < len(monitors)\n current_monitor = list(get_monitors())[monitor_index]\n cv2.namedWindow(name)\n if location == \"upper left\":\n cv2.moveWindow(name, current_monitor.x, current_monitor.y)\n elif location == \"lower right\":\n cv2.moveWindow(\n name,\n current_monitor.x + current_monitor.width - image_x,\n current_monitor.y + current_monitor.height - image_y\n )\n elif (location is None) or (location == \"center\"):\n cv2.moveWindow(\n name,\n int(current_monitor.x + (current_monitor.width - image_x) / 2),\n int(current_monitor.y + (current_monitor.height - image_y) / 2)\n )\n else:\n raise ValueError(\"Unknown location: {}\".format(location))\n\n", "repo_name": "metadriverse/PVP", "sub_path": "pvp/utils/carla/core/utils/others/visualizer.py", "file_name": "visualizer.py", "file_ext": "py", "file_size_in_byte": 10604, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "cv2.putText", "line_number": 20, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 21, "usage_type": "attribute"}, {"api_name": "cv2.LINE_AA", "line_number": 21, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 153, "usage_type": "name"}, {"api_name": "pvp_iclr_release.utils.carla.core.utils.others.config_helper.deep_merge_dicts", "line_number": 156, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 168, "usage_type": "call"}, {"api_name": "pvp_iclr_release.utils.carla.core.utils.others.image_helper.GifMaker", "line_number": 180, "usage_type": "call"}, {"api_name": "pvp_iclr_release.utils.carla.core.utils.others.image_helper.VideoMaker", "line_number": 182, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 185, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 185, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 185, "usage_type": "name"}, {"api_name": "numpy.uint8", "line_number": 195, "usage_type": "call"}, {"api_name": "pvp_iclr_release.utils.carla.core.utils.others.image_helper.show_image", "line_number": 226, "usage_type": "call"}, {"api_name": "easydict.EasyDict", "line_number": 246, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 248, "usage_type": "call"}, {"api_name": "easydict.EasyDict", "line_number": 245, "usage_type": "name"}, {"api_name": "cv2.resize", "line_number": 256, "usage_type": "call"}, {"api_name": "cv2.INTER_NEAREST", "line_number": 256, "usage_type": "attribute"}, {"api_name": "numpy.stack", "line_number": 258, "usage_type": "call"}, {"api_name": "screeninfo.get_monitors", "line_number": 265, "usage_type": "call"}, {"api_name": "screeninfo.get_monitors", "line_number": 267, "usage_type": "call"}, {"api_name": "cv2.namedWindow", "line_number": 268, "usage_type": "call"}, {"api_name": "cv2.moveWindow", "line_number": 270, "usage_type": "call"}, {"api_name": "cv2.moveWindow", "line_number": 272, "usage_type": "call"}, {"api_name": "cv2.moveWindow", "line_number": 278, "usage_type": "call"}]} +{"seq_id": "73423462152", "text": "import datetime\nfrom typing import Any, Dict, List, Type, TypeVar, Union, cast\n\nimport attr\nfrom dateutil.parser import isoparse\n\nfrom ..models.keyfactor_api_models_orchestrators_agent_response_agent_platform import (\n KeyfactorApiModelsOrchestratorsAgentResponseAgentPlatform,\n)\nfrom ..models.keyfactor_api_models_orchestrators_agent_response_status import (\n KeyfactorApiModelsOrchestratorsAgentResponseStatus,\n)\nfrom ..types import UNSET, Unset\n\nT = TypeVar(\"T\", bound=\"KeyfactorApiModelsOrchestratorsAgentResponse\")\n\n\n@attr.s(auto_attribs=True)\nclass KeyfactorApiModelsOrchestratorsAgentResponse:\n \"\"\"\n Attributes:\n agent_id (Union[Unset, str]): Example: 00000000-0000-0000-0000-000000000000.\n client_machine (Union[Unset, str]):\n username (Union[Unset, str]):\n agent_platform (Union[Unset, KeyfactorApiModelsOrchestratorsAgentResponseAgentPlatform]):\n version (Union[Unset, str]):\n status (Union[Unset, KeyfactorApiModelsOrchestratorsAgentResponseStatus]):\n last_seen (Union[Unset, datetime.datetime]):\n capabilities (Union[Unset, List[str]]):\n blueprint (Union[Unset, str]):\n thumbprint (Union[Unset, str]):\n legacy_thumbprint (Union[Unset, str]):\n auth_certificate_reenrollment (Union[Unset, str]):\n last_thumbprint_used (Union[Unset, str]):\n last_error_code (Union[Unset, int]):\n last_error_message (Union[Unset, str]):\n \"\"\"\n\n agent_id: Union[Unset, str] = UNSET\n client_machine: Union[Unset, str] = UNSET\n username: Union[Unset, str] = UNSET\n agent_platform: Union[Unset, KeyfactorApiModelsOrchestratorsAgentResponseAgentPlatform] = UNSET\n version: Union[Unset, str] = UNSET\n status: Union[Unset, KeyfactorApiModelsOrchestratorsAgentResponseStatus] = UNSET\n last_seen: Union[Unset, datetime.datetime] = UNSET\n capabilities: Union[Unset, List[str]] = UNSET\n blueprint: Union[Unset, str] = UNSET\n thumbprint: Union[Unset, str] = UNSET\n legacy_thumbprint: Union[Unset, str] = UNSET\n auth_certificate_reenrollment: Union[Unset, str] = UNSET\n last_thumbprint_used: Union[Unset, str] = UNSET\n last_error_code: Union[Unset, int] = UNSET\n last_error_message: Union[Unset, str] = UNSET\n additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n agent_id = self.agent_id\n client_machine = self.client_machine\n username = self.username\n agent_platform: Union[Unset, int] = UNSET\n if not isinstance(self.agent_platform, Unset):\n agent_platform = self.agent_platform.value\n\n version = self.version\n status: Union[Unset, int] = UNSET\n if not isinstance(self.status, Unset):\n status = self.status.value\n\n last_seen: Union[Unset, str] = UNSET\n if not isinstance(self.last_seen, Unset):\n last_seen = self.last_seen.isoformat()[:-6]+'Z'\n\n capabilities: Union[Unset, List[str]] = UNSET\n if not isinstance(self.capabilities, Unset):\n capabilities = self.capabilities\n\n blueprint = self.blueprint\n thumbprint = self.thumbprint\n legacy_thumbprint = self.legacy_thumbprint\n auth_certificate_reenrollment = self.auth_certificate_reenrollment\n last_thumbprint_used = self.last_thumbprint_used\n last_error_code = self.last_error_code\n last_error_message = self.last_error_message\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update({})\n if agent_id is not UNSET:\n field_dict[\"AgentId\"] = agent_id\n if client_machine is not UNSET:\n field_dict[\"ClientMachine\"] = client_machine\n if username is not UNSET:\n field_dict[\"Username\"] = username\n if agent_platform is not UNSET:\n field_dict[\"AgentPlatform\"] = agent_platform\n if version is not UNSET:\n field_dict[\"Version\"] = version\n if status is not UNSET:\n field_dict[\"Status\"] = status\n if last_seen is not UNSET:\n field_dict[\"LastSeen\"] = last_seen\n if capabilities is not UNSET:\n field_dict[\"Capabilities\"] = capabilities\n if blueprint is not UNSET:\n field_dict[\"Blueprint\"] = blueprint\n if thumbprint is not UNSET:\n field_dict[\"Thumbprint\"] = thumbprint\n if legacy_thumbprint is not UNSET:\n field_dict[\"LegacyThumbprint\"] = legacy_thumbprint\n if auth_certificate_reenrollment is not UNSET:\n field_dict[\"AuthCertificateReenrollment\"] = auth_certificate_reenrollment\n if last_thumbprint_used is not UNSET:\n field_dict[\"LastThumbprintUsed\"] = last_thumbprint_used\n if last_error_code is not UNSET:\n field_dict[\"LastErrorCode\"] = last_error_code\n if last_error_message is not UNSET:\n field_dict[\"LastErrorMessage\"] = last_error_message\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n d = src_dict.copy()\n agent_id = d.pop(\"AgentId\", UNSET)\n\n client_machine = d.pop(\"ClientMachine\", UNSET)\n\n username = d.pop(\"Username\", UNSET)\n\n _agent_platform = d.pop(\"AgentPlatform\", UNSET)\n agent_platform: Union[Unset, KeyfactorApiModelsOrchestratorsAgentResponseAgentPlatform]\n if isinstance(_agent_platform, Unset):\n agent_platform = UNSET\n else:\n agent_platform = KeyfactorApiModelsOrchestratorsAgentResponseAgentPlatform(_agent_platform)\n\n version = d.pop(\"Version\", UNSET)\n\n _status = d.pop(\"Status\", UNSET)\n status: Union[Unset, KeyfactorApiModelsOrchestratorsAgentResponseStatus]\n if isinstance(_status, Unset):\n status = UNSET\n else:\n status = KeyfactorApiModelsOrchestratorsAgentResponseStatus(_status)\n\n _last_seen = d.pop(\"LastSeen\", UNSET)\n last_seen: Union[Unset, datetime.datetime]\n if isinstance(_last_seen, Unset):\n last_seen = UNSET\n else:\n last_seen = isoparse(_last_seen)\n\n capabilities = cast(List[str], d.pop(\"Capabilities\", UNSET))\n\n blueprint = d.pop(\"Blueprint\", UNSET)\n\n thumbprint = d.pop(\"Thumbprint\", UNSET)\n\n legacy_thumbprint = d.pop(\"LegacyThumbprint\", UNSET)\n\n auth_certificate_reenrollment = d.pop(\"AuthCertificateReenrollment\", UNSET)\n\n last_thumbprint_used = d.pop(\"LastThumbprintUsed\", UNSET)\n\n last_error_code = d.pop(\"LastErrorCode\", UNSET)\n\n last_error_message = d.pop(\"LastErrorMessage\", UNSET)\n\n keyfactor_api_models_orchestrators_agent_response = cls(\n agent_id=agent_id,\n client_machine=client_machine,\n username=username,\n agent_platform=agent_platform,\n version=version,\n status=status,\n last_seen=last_seen,\n capabilities=capabilities,\n blueprint=blueprint,\n thumbprint=thumbprint,\n legacy_thumbprint=legacy_thumbprint,\n auth_certificate_reenrollment=auth_certificate_reenrollment,\n last_thumbprint_used=last_thumbprint_used,\n last_error_code=last_error_code,\n last_error_message=last_error_message,\n )\n\n keyfactor_api_models_orchestrators_agent_response.additional_properties = d\n return keyfactor_api_models_orchestrators_agent_response\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n", "repo_name": "Keyfactor/keyfactor-python-client-sdk", "sub_path": "kfclient/keyfactor_v_1_client/models/keyfactor_api_models_orchestrators_agent_response.py", "file_name": "keyfactor_api_models_orchestrators_agent_response.py", "file_ext": "py", "file_size_in_byte": 8039, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "27", "api": [{"api_name": "typing.TypeVar", "line_number": 15, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 39, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 39, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 39, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 40, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 40, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 40, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 41, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 41, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 41, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 42, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 42, "usage_type": "name"}, {"api_name": "models.keyfactor_api_models_orchestrators_agent_response_agent_platform.KeyfactorApiModelsOrchestratorsAgentResponseAgentPlatform", "line_number": 42, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 42, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 43, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 43, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 43, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 44, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 44, "usage_type": "name"}, {"api_name": "models.keyfactor_api_models_orchestrators_agent_response_status.KeyfactorApiModelsOrchestratorsAgentResponseStatus", "line_number": 44, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 44, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 45, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 45, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 45, "usage_type": "attribute"}, {"api_name": "types.UNSET", "line_number": 45, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 46, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 46, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 46, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 46, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 47, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 47, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 47, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 48, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 48, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 48, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 49, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 49, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 49, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 50, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 50, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 50, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 51, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 51, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 51, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 52, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 52, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 52, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 53, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 53, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 53, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 54, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 54, "usage_type": "name"}, {"api_name": "attr.ib", "line_number": 54, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 60, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 60, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 60, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 61, "usage_type": "argument"}, {"api_name": "typing.Union", "line_number": 65, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 65, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 65, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 66, "usage_type": "argument"}, {"api_name": "typing.Union", "line_number": 69, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 69, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 69, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 70, "usage_type": "argument"}, {"api_name": "typing.Union", "line_number": 73, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 73, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 73, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 73, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 74, "usage_type": "argument"}, {"api_name": "typing.Dict", "line_number": 85, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 85, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 88, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 90, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 92, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 94, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 96, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 98, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 100, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 102, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 104, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 106, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 108, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 110, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 112, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 114, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 116, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 56, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 56, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 122, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 122, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 122, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 124, "usage_type": "argument"}, {"api_name": "types.UNSET", "line_number": 126, "usage_type": "argument"}, {"api_name": "types.UNSET", "line_number": 128, "usage_type": "argument"}, {"api_name": "types.UNSET", "line_number": 130, "usage_type": "argument"}, {"api_name": "typing.Union", "line_number": 131, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 131, "usage_type": "name"}, {"api_name": "models.keyfactor_api_models_orchestrators_agent_response_agent_platform.KeyfactorApiModelsOrchestratorsAgentResponseAgentPlatform", "line_number": 131, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 132, "usage_type": "argument"}, {"api_name": "types.UNSET", "line_number": 133, "usage_type": "name"}, {"api_name": "models.keyfactor_api_models_orchestrators_agent_response_agent_platform.KeyfactorApiModelsOrchestratorsAgentResponseAgentPlatform", "line_number": 135, "usage_type": "call"}, {"api_name": "types.UNSET", "line_number": 137, "usage_type": "argument"}, {"api_name": "types.UNSET", "line_number": 139, "usage_type": "argument"}, {"api_name": "typing.Union", "line_number": 140, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 140, "usage_type": "name"}, {"api_name": "models.keyfactor_api_models_orchestrators_agent_response_status.KeyfactorApiModelsOrchestratorsAgentResponseStatus", "line_number": 140, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 141, "usage_type": "argument"}, {"api_name": "types.UNSET", "line_number": 142, "usage_type": "name"}, {"api_name": "models.keyfactor_api_models_orchestrators_agent_response_status.KeyfactorApiModelsOrchestratorsAgentResponseStatus", "line_number": 144, "usage_type": "call"}, {"api_name": "types.UNSET", "line_number": 146, "usage_type": "argument"}, {"api_name": "typing.Union", "line_number": 147, "usage_type": "name"}, {"api_name": "types.Unset", "line_number": 147, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 147, "usage_type": "attribute"}, {"api_name": "types.Unset", "line_number": 148, "usage_type": "argument"}, {"api_name": "types.UNSET", "line_number": 149, "usage_type": "name"}, {"api_name": "dateutil.parser.isoparse", "line_number": 151, "usage_type": "call"}, {"api_name": "typing.cast", "line_number": 153, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 153, "usage_type": "name"}, {"api_name": "types.UNSET", "line_number": 153, "usage_type": "argument"}, {"api_name": "types.UNSET", "line_number": 155, "usage_type": "argument"}, {"api_name": "types.UNSET", "line_number": 157, "usage_type": "argument"}, {"api_name": "types.UNSET", "line_number": 159, "usage_type": "argument"}, {"api_name": "types.UNSET", "line_number": 161, "usage_type": "argument"}, {"api_name": "types.UNSET", "line_number": 163, "usage_type": "argument"}, {"api_name": "types.UNSET", "line_number": 165, "usage_type": "argument"}, {"api_name": "types.UNSET", "line_number": 167, "usage_type": "argument"}, {"api_name": "typing.List", "line_number": 191, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 194, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 197, "usage_type": "name"}, {"api_name": "attr.s", "line_number": 18, "usage_type": "call"}]} +{"seq_id": "17699450109", "text": "import argparse\nimport numpy as np\nimport pandas as pd\nfrom models import *\nfrom datasets import *\nimport datetime as dt\nimport sys\nimport os\nimport matplotlib.pyplot as plt\nimport imageio, cv2\n\nfrom tensorflow.keras.layers import Input, Concatenate\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.models import Model, load_model\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--epoch\", type=int, default=1, help=\"epoch to start training from\")\nparser.add_argument(\"--n_epochs\", type=int, default=200, help=\"number of epochs of training\")\nparser.add_argument(\"--dataset_name\", type=str, default=\"sample\", help=\"name of the dataset\")\nparser.add_argument(\"--batch_size\", type=int, default=1, help=\"size of the batches\")\nparser.add_argument(\"--lr\", type=float, default=0.0002, help=\"adam: learning rate\")\nparser.add_argument(\"--b1\", type=float, default=0.5, help=\"adam: decay of first order momentum of gradient\")\nparser.add_argument(\"--b2\", type=float, default=0.999, help=\"adam: decay of first order momentum of gradient\")\nparser.add_argument(\"--dropout_rate\", type=float, default=0.5, help=\"dropout rate in Generator (UNet)\")\nparser.add_argument(\"--sample_epoch_interval\", type=int, default=100, help=\"epoch interval between sampling of images from generators\")\nparser.add_argument(\"--checkpoint_interval\", type=int, default=100, help=\"interval between model checkpoints\")\nopt = parser.parse_args()\nprint(opt)\n\nif opt.batch_size != 1:\n print('Error: batch_size must be equal to 1')\n sys.exit()\n\nos.makedirs('images/%s' % opt.dataset_name, exist_ok=True)\nos.makedirs('saved_models/%s' % opt.dataset_name, exist_ok=True)\n\nfilenames = glob('data/{}/{}/{}/*.jpg'.format(opt.dataset_name, 'hig_reso', '00'))\nstr_len = len('data/{}/{}/{}/'.format(opt.dataset_name, 'hig_reso', '00'))\nimg_list = [filename[str_len:] for filename in filenames]\nimg_list = list(sorted(img_list))\nfilename = 'data/{}/{}/{}/{}'.format(opt.dataset_name, 'hig_reso', '00', img_list[0])\nimage = imageio.imread(filename, as_gray=False, pilmode='RGB').astype(np.float)\nheight, width, _ = image.shape\n\ndata_loader = DataLoader(dataset_name=opt.dataset_name, height=height, width=width)\nimg_list = data_loader.get_img_list()\nframes = len(img_list)\nheight, width, in_channels = data_loader.get_img_shape(img_list[0])\n\npatch_height = height // 2 ** 4\npatch_width = width // 2 ** 4\ndisc_patch = (patch_height, patch_width, 1)\n\nout_channels = 1\ndropout_rate = opt.dropout_rate\noptimizer = Adam(lr=opt.lr, beta_1=opt.b1, beta_2=opt.b2)\n\n# Discriminator\n# pix2pixのpytorch実装では、\n# MSELoss(patch毎の真贋判定なので、binary cross entropyではない)と\n# L1Loss(本物の画像と偽物の画像のピクセル毎の比較)の併用\n# Keras実装には下記サイトも参考にする(L1Lossのあたりとか)\n# https://github.com/tommyfms2/pix2pix-keras-byt/blob/master/pix2pix.py\n# pytorch実装の作者のKeras実装\n# https://github.com/eriklindernoren/Keras-GAN/blob/master/pix2pix/pix2pix.py\ndiscriminator = discriminator(name='discriminator')\ndiscriminator(Input((frames, height, width, out_channels * 2)))\n# Discriminatorへの入力は、生成された画像もしくは変換後の真の画像と変換前の画像を結合したもの\ndiscriminator.summary()\ndiscriminator.compile(loss='mse', optimizer=optimizer, metrics=['accuracy'])\n\n# Generator\ngenerator = generator(frames, out_channels, dropout_rate, name='generator')\ngenerator(Input((frames, height, width, in_channels)))\ngenerator.summary()\n\ninput_A = Input((frames, height, width, in_channels)) # Results of Low resolution\ninput_B = Input((frames, height, width, in_channels)) # Results of High resolution\n\nfake_B = generator(input_A)\n\n# For the combined model we will only train the generator\ndiscriminator.trainable = False\n\n# Discriminators determines validity of translated images / condition pairs\ncombined_imgs = Concatenate(axis=-1)([fake_B, input_A])\nvalidity = discriminator(combined_imgs)\n\ncombined_Model = Model(inputs=[input_A, input_B], outputs=[validity, fake_B])\ncombined_Model.summary()\ncombined_Model.compile(loss=['mse', 'mae'],\n loss_weights=[1, 100],\n optimizer=optimizer)\n\nif opt.epoch != 1:\n discriminator.load_weights('saved_models/%s/discriminator_%d.h5' % (opt.dataset_name, opt.epoch-1))\n combined_Model.load_weights('saved_models/%s/combined_Model_%d.h5' % (opt.dataset_name, opt.epoch-1))\n\ndef sample_images(dirs, epoch, type='horizontal', frame_interval=1):\n plot_list = []\n for i in range(0, frames, frame_interval):\n plot_list.append(i)\n\n for dir in dirs:\n imgs_A, imgs_B = data_loader.load_batch(dir, img_list)\n imgs_A = imgs_A.reshape(opt.batch_size, frames, height, width, in_channels)\n imgs_B = imgs_B.reshape(opt.batch_size, frames, height, width, in_channels)\n fake_B = generator.predict(imgs_A)\n\n titles = ['Low Resolution', 'Generated', 'High Resolution']\n\n imgs_A = imgs_A.reshape(frames, height, width, in_channels)\n imgs_B = imgs_B.reshape(frames, height, width, in_channels)\n fake_B = fake_B.reshape(frames, height, width, in_channels)\n\n if type == 'horizontal':\n fig, axs = plt.subplots(3, len(plot_list))\n for frame in range(len(plot_list)):\n # Low Resolution\n# img_tmp = 0.5 * imgs_A[plot_list[frame], :, :, :] + 0.5\n img_tmp = 255*(0.5 * imgs_A[plot_list[frame], :, :, :] + 0.5)\n print(img_tmp.max())\n print(img_tmp.min())\n img_tmp = np.array(img_tmp, np.uint8)\n img_tmp = cv2.cvtColor(img_tmp, cv2.COLOR_GRAY2RGB)\n# print(img_tmp.shape)\n# img_tmp = img_tmp.reshape(height, width)\n axs[0, frame].imshow(img_tmp)\n axs[0, frame].axis('off')\n if frame == len(plot_list) // 2:\n axs[0, frame].set_title(titles[0])\n # Generated\n# img_tmp = 0.5 * fake_B[plot_list[frame], :, :, :] + 0.5\n img_tmp = 255*(0.5 * fake_B[plot_list[frame], :, :, :] + 0.5)\n print(img_tmp.max())\n print(img_tmp.min())\n img_tmp = np.array(img_tmp, np.uint8)\n img_tmp = cv2.cvtColor(img_tmp, cv2.COLOR_GRAY2RGB)\n# print(img_tmp.shape)\n# img_tmp = img_tmp.reshape(height, width)\n axs[1, frame].imshow(img_tmp)\n axs[1, frame].axis('off')\n if frame == len(plot_list) // 2:\n axs[1, frame].set_title(titles[1])\n # High Resolution\n# img_tmp = 0.5 * imgs_B[plot_list[frame], :, :, :] + 0.5\n img_tmp = 255*(0.5 * imgs_B[plot_list[frame], :, :, :] + 0.5)\n print(img_tmp.max())\n print(img_tmp.min())\n img_tmp = np.array(img_tmp, np.uint8)\n img_tmp = cv2.cvtColor(img_tmp, cv2.COLOR_GRAY2RGB)\n# print(img_tmp.shape)\n# img_tmp = img_tmp.reshape(height, width)\n axs[2, frame].imshow(img_tmp)\n axs[2, frame].axis('off')\n if frame == len(plot_list) // 2:\n axs[2, frame].set_title(titles[2])\n elif type == 'vertical':\n fig, axs = plt.subplots(len(plot_list), 3)\n for frame in range(len(plot_list)):\n # Low Resolution\n# img_tmp = 0.5 * imgs_A[plot_list[frame], :, :, :] + 0.5\n img_tmp = 255*(0.5 * imgs_A[plot_list[frame], :, :, :] + 0.5)\n print(img_tmp.max())\n print(img_tmp.min())\n img_tmp = np.array(img_tmp, np.uint8)\n img_tmp = cv2.cvtColor(img_tmp, cv2.COLOR_GRAY2RGB)\n# print(img_tmp.shape)\n# img_tmp = img_tmp.reshape(height, width)\n axs[frame, 0].imshow(img_tmp)\n axs[frame, 0].axis('off')\n if frame == 0:\n axs[frame, 0].set_title(titles[0])\n # Generated\n# img_tmp = 0.5 * fake_B[plot_list[frame], :, :, :] + 0.5\n img_tmp = 255*(0.5 * fake_B[plot_list[frame], :, :, :] + 0.5)\n print(img_tmp.max())\n print(img_tmp.min())\n img_tmp = np.array(img_tmp, np.uint8)\n img_tmp = cv2.cvtColor(img_tmp, cv2.COLOR_GRAY2RGB)\n# print(img_tmp.shape)\n# img_tmp = img_tmp.reshape(height, width)\n axs[frame, 1].imshow(img_tmp)\n axs[frame, 1].axis('off')\n if frame == 0:\n axs[frame, 1].set_title(titles[1])\n # High Resolution\n# img_tmp = 0.5 * imgs_B[plot_list[frame], :, :, :] + 0.5\n img_tmp = 255*(0.5 * imgs_B[plot_list[frame], :, :, :] + 0.5)\n print(img_tmp.max())\n print(img_tmp.min())\n img_tmp = np.array(img_tmp, np.uint8)\n img_tmp = cv2.cvtColor(img_tmp, cv2.COLOR_GRAY2RGB)\n# print(img_tmp.shape)\n# img_tmp = img_tmp.reshape(height, width)\n axs[frame, 2].imshow(img_tmp)\n axs[frame, 2].axis('off')\n if frame == 0:\n axs[frame, 2].set_title(titles[2])\n fig.savefig('images/%s/%s_%d.png' % (opt.dataset_name, dir, epoch))\n plt.close()\n\nstart_time = dt.datetime.now()\n\n# Adversarial loss ground truths\nvalid = np.ones((opt.batch_size, frames, ) + disc_patch)\nfake = np.zeros((opt.batch_size, frames, ) + disc_patch)\n\nloss_Discriminator = []\nloss_Generator = []\naccuracy_Discriminator = []\n\ntrain_dirs, val_dirs = data_loader.make_train_val_set(train_size=0.8)\nprint('train_dirs= ', train_dirs)\nprint('val_dirs= ', val_dirs)\nfor epoch in range(opt.epoch, opt.n_epochs+1):\n# train_dirs, val_dirs = data_loader.make_train_val_set(train_size=0.8)\n for batch_i, dir in enumerate(train_dirs):\n imgs_A, imgs_B = data_loader.load_batch(dir, img_list)\n imgs_A = imgs_A.reshape(opt.batch_size, frames, height, width, in_channels)\n imgs_B = imgs_B.reshape(opt.batch_size, frames, height, width, in_channels)\n\n # ---------------------\n # Train Discriminator\n # ---------------------\n\n # Condition on A and generate a translated version\n fake_B = generator.predict(imgs_A)\n\n # Train the discriminators (original images = real / generated = Fake)\n# combined_imgs_valid = Concatenate(axis=-1)([imgs_B, imgs_A])\n# combined_imgs_fake = Concatenate(axis=-1)([fake_B, imgs_A])\n combined_imgs_valid = np.concatenate([imgs_B, imgs_A], axis=-1)\n combined_imgs_fake = np.concatenate([fake_B, imgs_A], axis=-1)\n d_loss_real = discriminator.train_on_batch(combined_imgs_valid, valid)\n d_loss_fake = discriminator.train_on_batch(combined_imgs_fake, fake)\n d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)\n\n # -----------------\n # Train Generator\n # -----------------\n\n # Train the generators\n g_loss = combined_Model.train_on_batch([imgs_A, imgs_B], [valid, imgs_B])\n\n elapsed_time = dt.datetime.now() - start_time\n # Plot the progress\n print (\"[Epoch %d/%d] [Batch %d/%d] [D loss: %f, acc: %3d%%] [G loss: %f] time: %s\" % (epoch, opt.n_epochs,\n batch_i+1, len(train_dirs),\n d_loss[0], 100*d_loss[1],\n g_loss[0],\n elapsed_time))\n\n if epoch % opt.checkpoint_interval == 0:\n discriminator.save_weights('saved_models/%s/discriminator_%d.h5' % (opt.dataset_name, epoch))\n combined_Model.save_weights('saved_models/%s/combined_Model_%d.h5' % (opt.dataset_name, epoch))\n\n if epoch % opt.sample_epoch_interval == 0:\n sample_images(val_dirs, epoch, type='horizontal', frame_interval=4)\n\n loss_Discriminator.append(d_loss[0])\n loss_Generator.append(g_loss[0])\n accuracy_Discriminator.append(d_loss[1])\n\ndf = pd.DataFrame(data=None, columns=['loss_D', 'loss_G', 'acc_D'])\ndf['loss_D'] = loss_Discriminator\ndf['loss_G'] = loss_Generator\ndf['acc_D'] = accuracy_Discriminator\ndf.to_csv('loss_history.csv')\n", "repo_name": "bright1998/pix2pix_LSTM", "sub_path": "pix2pix+LSTM/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 12575, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "27", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 16, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 32, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 34, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 35, "usage_type": "call"}, {"api_name": "imageio.imread", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.float", "line_number": 42, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.optimizers.Adam", "line_number": 56, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Input", "line_number": 67, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Input", "line_number": 74, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Input", "line_number": 77, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Input", "line_number": 78, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Concatenate", "line_number": 86, "usage_type": "call"}, {"api_name": "tensorflow.keras.models.Model", "line_number": 89, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 117, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 117, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 124, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 125, "usage_type": "call"}, {"api_name": "cv2.COLOR_GRAY2RGB", "line_number": 125, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 137, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 138, "usage_type": "call"}, {"api_name": "cv2.COLOR_GRAY2RGB", "line_number": 138, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 150, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 151, "usage_type": "call"}, {"api_name": "cv2.COLOR_GRAY2RGB", "line_number": 151, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 159, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 159, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 166, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 167, "usage_type": "call"}, {"api_name": "cv2.COLOR_GRAY2RGB", "line_number": 167, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 179, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 179, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 180, "usage_type": "call"}, {"api_name": "cv2.COLOR_GRAY2RGB", "line_number": 180, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 192, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 192, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 193, "usage_type": "call"}, {"api_name": "cv2.COLOR_GRAY2RGB", "line_number": 193, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.close", "line_number": 201, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 201, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 203, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 203, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 206, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 207, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 233, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 234, "usage_type": "call"}, {"api_name": "numpy.add", "line_number": 237, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 246, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 246, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 265, "usage_type": "call"}]} +{"seq_id": "36558776399", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport numpy as np\nimport torch.nn as nn\nimport torch\n\nclass TextGenerationModel(nn.Module):\n\n def __init__(self,config,vocabulary_size,device):\n\n super(TextGenerationModel, self).__init__()\n # Initialization here...\n self.batch_size = config.batch_size\n self.voc_size = vocabulary_size\n self.hidden_dim = config.lstm_num_hidden\n self.num_layers = config.lstm_num_layers\n self.device = device\n self.input_dim = config.lstm_num_hidden\n self.embed = nn.Embedding(self.voc_size,self.input_dim)\n self.lstm = nn.LSTM(self.input_dim,self.hidden_dim,self.num_layers,batch_first=False,dropout=config.dropout_keep_prob) \n self.fc = nn.Linear(self.hidden_dim,self.voc_size) # From hidden vector to output p_t\n self.lsm=nn.LogSoftmax(dim=2)\n self.temp=1 # used to enable softmax with temperature after training\n def forward(self, x, h, C): # h=hidden tensor, C=cell state tensor\n # Implementation here...\n if len(x.shape) == 0:\n x=x.unsqueeze(0).unsqueeze(0) # if sequence length ==1 and batch size ==1, add two dimensions to tensor\n if len(x.shape) == 1: # if sequence length >1 and batch size == 1, add batch dimension \n x=x.unsqueeze(1) # in dim 1, following the default nn.LSTM input, this makes x (seq_len,batch_size=1)\n seq_len = x.size(0)\n out = self.embed(x).to(self.device) # out (seq_len,batch_size,input_dim)\n out, (h,C) = self.lstm(out,(h,C))\n out = self.fc(out.reshape(-1,self.hidden_dim)) # linear layer acts on one character at a time\n \n out = out.reshape(seq_len,self.batch_size,-1) # shape back to output tensor (seq_len,batch_size,voc_size)\n out = self.lsm(out/self.temp) # apply the log softmax\n return out,h,C\n\n def init_cell(self, bsize):\n h = torch.zeros(self.num_layers,bsize,self.hidden_dim).to(self.device)\n C = torch.zeros(self.num_layers,bsize,self.hidden_dim).to(self.device)\n self.batch_size=bsize # overwrite in preparation of new data coming in\n return h,C\n\n def numTrainableParameters(self):\n #return sum(p.numel() for p in self.parameters() if p.requires_grad)\n \n total = 0\n for name, p in self.named_parameters():\n total += np.prod(p.shape)\n print(\"{:24s} {:12s} requires_grad={}\".format(name, str(list(p.shape)), p.requires_grad))\n print(\"\\nTotal number of parameters: {}\\n\".format(total))\n assert total == sum(p.numel() for p in self.parameters() if p.requires_grad)\n return total\n", "repo_name": "rvdweerd/DL2020_Lab2_p2", "sub_path": "model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 2750, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "torch.nn.Module", "line_number": 8, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 8, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.LSTM", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn.LogSoftmax", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.prod", "line_number": 51, "usage_type": "call"}]} +{"seq_id": "70546827272", "text": "# might need to install these, probably ...$ pip install xmltodict requests\nimport xmltodict\nimport requests\n\ndef getETA(stop, route):\n '''return a nice string with info about buses arriving at this stop'''\n # found this URL with a little poking around http://ridetransfort.com/bustracker\n url = 'http://clever-web.fcgov.com/bustime/map/getStopPredictions.jsp?stop={}&route={}'.format(stop, route)\n r = requests.get(url)\n xml = xmltodict.parse(r.content)\n ret = ''\n name = xml['stop']['nm']\n\n if name == None:\n ret = \"Stop {} doesn't exist.\".format(stop)\n elif 'pre' not in xml['stop']:\n ret = 'Route {} not arriving at stop {} ({}) anytime soon.'.format(route, stop, name)\n else:\n time = xml['stop']['pre']['pt'].split(' ')[0]\n bus = xml['stop']['pre']['v']\n ret = 'Route {} (bus {}) arriving at stop {} ({}) in {} minutes.'.format(route, bus, stop, name, time)\n\n return ret\n\n# Next, it would be cool to get geolocation info too\n# http://clever-web.fcgov.com/bustime/map/getBusesForRoute.jsp?route=2 is a good starting place\n\nif __name__ == '__main__':\n # examples\n print(getETA(237, 2))\n print(getETA(237, 3))\n", "repo_name": "M3tanym/python-fun", "sub_path": "transfort.py", "file_name": "transfort.py", "file_ext": "py", "file_size_in_byte": 1189, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "requests.get", "line_number": 9, "usage_type": "call"}, {"api_name": "xmltodict.parse", "line_number": 10, "usage_type": "call"}]} +{"seq_id": "40814205766", "text": "from django.urls import path\n\nfrom home import views\n\napp_name = 'home'\n\nurlpatterns = [\n path('login/', views.loginUser, name='login'),\n path('logout/', views.logoutUser, name='logout'),\n path('register/', views.registerUser, name='register'),\n path('', views.index, name='index'),\n]\n", "repo_name": "yannis971/Projet_P9", "sub_path": "lit_review/home/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 297, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "home.views.loginUser", "line_number": 8, "usage_type": "attribute"}, {"api_name": "home.views", "line_number": 8, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "home.views.logoutUser", "line_number": 9, "usage_type": "attribute"}, {"api_name": "home.views", "line_number": 9, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "home.views.registerUser", "line_number": 10, "usage_type": "attribute"}, {"api_name": "home.views", "line_number": 10, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "home.views.index", "line_number": 11, "usage_type": "attribute"}, {"api_name": "home.views", "line_number": 11, "usage_type": "name"}]} +{"seq_id": "5105599197", "text": "#!/bin/python3\nimport requests\nimport json\n\nurl = 'http://localhost:5000/uploader'\nfiles = {'file': open('x.jpg', 'rb')}\n\nr = requests.post(url, files=files)\nresult=json.loads(r.text)\n\nprint(f'Status: {result[\"status\"]}')\nprint(f'filename: {result[\"filename\"]}')\nprint(f'points: {result[\"points\"]}')", "repo_name": "sdcitychris/flaskUpload", "sub_path": "client/client.py", "file_name": "client.py", "file_ext": "py", "file_size_in_byte": 300, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "requests.post", "line_number": 8, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 9, "usage_type": "call"}]} +{"seq_id": "3605636265", "text": "import requests\nimport json\n\n#======================================百度api请求token通用块儿=======================================\n# 需要的库requests、json(import 进来就好了)\nbaidu_server = 'https://aip.baidubce.com/oauth/2.0/token?' #获取token的server\ngrant_type = 'client_credentials'\nclient_id = 'zlXShBegxps1THXdG8mfP6nM' #API KEY\nclient_secret = 'klBQOr4kX3ZcarI4zadWTRik26P226yc' #Secret KEY 这里可以自己去百度注册,这里是我的API KEY 和 Secret KEY\n\n#合成请求token的url\nurl = baidu_server+'grant_type='+grant_type+'&client_id='+client_id+'&client_secret='+client_secret\n\n#获取token\nres = requests.get(url).text\ndata = json.loads(res) #将json格式转换为字典格式\ntoken = data['access_token']\nprint(token)\n#=====================================================================================================\n", "repo_name": "shui0/QIingyu-translate", "sub_path": "获取api_token.py", "file_name": "获取api_token.py", "file_ext": "py", "file_size_in_byte": 875, "program_lang": "python", "lang": "fr", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "requests.get", "line_number": 15, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 16, "usage_type": "call"}]} +{"seq_id": "30922588952", "text": "from typing import Any, Dict, Optional, Tuple\nimport torch\nimport torch.nn.functional as F\nimport random\nimport glob\nimport os\nimport numpy as np\nfrom rich.progress import Progress\nfrom multiprocessing import Pool, Manager\nfrom itertools import repeat\nfrom pytorch_lightning import LightningDataModule\nfrom torch.utils.data import ConcatDataset, DataLoader, Dataset, random_split\nfrom miditok import MIDITokenizer\nfrom miditoolkit import MidiFile\nfrom src.data_preprocess.data_preprocess import (\n classic_guitar_preprocess,\n check_midi_validity,\n)\nfrom shutil import rmtree\nfrom src.datamodules.components import CustomDataset, CustomPadCollate\n\n\nclass ClassicGuitarDataModule(LightningDataModule):\n \"\"\"Custom datamodule for classic guitar dataset.\n\n Args:\n data_preprocess_cfg: config file object for data preprocessing\n tokenizer: MIDITokenizer class\n vocab_size: vocabulary size of tokenizer\n data_dir: base data directory\n train_ratio: ratio of training data from the whole dataset\n valid_ratio: ratio of validataion data from the whole dataset\n test_player_n: dummy argument. it should always be \"classic_guitar\"\n batch_size: batch size\n cache_dataset: whether to cache the whole dataset during first epoch\n might not work well with multiple dataloader workers\n num_workers: number of workers for parallel data preprocessing\n dataloader_workers: number of workers for dataloader\n pin_memory: whether to pin memory or not\n persistent_workers: whether to make the workers persistent\n preprocess_on_training_start: if set to False, it will bypass the preprocessing and use the existing preprocessed data\n \"\"\"\n\n def __init__(\n self,\n data_preprocess_cfg: any,\n tokenizer: MIDITokenizer,\n vocab_size: int,\n data_dir: str = \"data/\",\n train_ratio: float = 0.9,\n valid_ratio: float = 0.05,\n test_player_n=\"classic_guitar\",\n batch_size: int = 16,\n cache_dataset: bool = False,\n num_workers: int = 10,\n dataloader_workers: int = 5,\n pin_memory: bool = True,\n persistent_workers: bool = False,\n preprocess_on_training_start: bool = True,\n ):\n super().__init__()\n\n self.save_hyperparameters(logger=False)\n classclef_filename_list = glob.glob(\n os.path.join(\n data_preprocess_cfg.data_dir,\n \"classic_guitar_midi\",\n \"guitar_classclef\",\n \"*.mid\",\n )\n )\n midifiles_filename_list = glob.glob(\n os.path.join(\n data_preprocess_cfg.data_dir,\n \"classic_guitar_midi\",\n \"midifiles\",\n \"*.mid\",\n )\n )\n self.midi_filename_list = midifiles_filename_list + classclef_filename_list\n\n def prepare_data(self):\n \"\"\"Make dirs, preprocess and split the dataset\"\"\"\n output_dir = os.path.join(\n self.hparams.data_preprocess_cfg.output_dir, \"classic_guitar\"\n )\n wav_dir = os.path.join(output_dir, \"wav\")\n cqt_dir = os.path.join(output_dir, \"cqt\")\n midi_dir = os.path.join(output_dir, \"midi\")\n\n if self.hparams.preprocess_on_training_start:\n # make dirs for data preprocessing\n if os.path.exists(output_dir):\n rmtree(output_dir)\n os.makedirs(wav_dir)\n os.makedirs(cqt_dir)\n os.makedirs(midi_dir)\n else:\n os.makedirs(wav_dir)\n os.makedirs(cqt_dir)\n os.makedirs(midi_dir)\n\n self.valid_midi_filename_list = []\n self.total_dataset_time = 0\n\n # check validity of MIDI file\n pool = Pool(processes=self.hparams.num_workers)\n with Progress() as p:\n task = p.add_task(\n \"Checking validity...\", total=len(self.midi_filename_list)\n )\n for valid_midi_filename, validity, time in pool.imap_unordered(\n check_midi_validity,\n self.midi_filename_list,\n ):\n if validity:\n self.valid_midi_filename_list.append(valid_midi_filename)\n self.total_dataset_time += time\n p.update(task, advance=1)\n pool.close()\n print(\n f\"Using {len(self.valid_midi_filename_list)} valid MIDI files out of {len(self.midi_filename_list)} total MIDI files.\"\n )\n print(f\"{int(self.total_dataset_time)} mins in total.\")\n\n # preprocess the data using multiprocessing for parallel computation\n pool = Pool(processes=self.hparams.num_workers)\n with Progress() as p:\n task = p.add_task(\n \"Preprocessing...\", total=len(self.valid_midi_filename_list)\n )\n for _ in pool.imap_unordered(\n classic_guitar_preprocess,\n zip(\n self.valid_midi_filename_list,\n repeat(self.hparams.data_preprocess_cfg),\n ),\n ):\n p.update(task, advance=1)\n\n pool.close()\n\n # split the dataset to train/valid/test set\n split_trackname_list = glob.glob(os.path.join(cqt_dir, \"*.npy\"))\n glob_in = os.path.join(cqt_dir, \"*.npy\")\n split_trackname_list = [\n os.path.split(path)[1][:-4] for path in split_trackname_list\n ]\n random.shuffle(split_trackname_list)\n train_valid_test_ratio = [self.hparams.train_ratio, self.hparams.valid_ratio]\n cumsum_ratio = np.cumsum(train_valid_test_ratio)\n self.train_data_list = split_trackname_list[\n : int(round(len(split_trackname_list) * cumsum_ratio[0]))\n ]\n self.val_data_list = split_trackname_list[\n int(round(len(split_trackname_list) * cumsum_ratio[0])) : int(\n round(len(split_trackname_list) * cumsum_ratio[1])\n )\n ]\n self.test_data_list = split_trackname_list[\n int(round(len(split_trackname_list) * cumsum_ratio[1])) :\n ]\n\n def setup(self, stage=None):\n \"\"\"Initialize train, validation and test dataset\"\"\"\n self.data_train = CustomDataset(\n self.train_data_list,\n self.hparams.data_preprocess_cfg.output_dir + \"classic_guitar\",\n self.hparams.tokenizer,\n self.hparams.cache_dataset,\n )\n self.data_val = CustomDataset(\n self.val_data_list,\n self.hparams.data_preprocess_cfg.output_dir + \"classic_guitar\",\n self.hparams.tokenizer,\n self.hparams.cache_dataset,\n )\n self.data_test = CustomDataset(\n self.test_data_list,\n self.hparams.data_preprocess_cfg.output_dir + \"classic_guitar\",\n self.hparams.tokenizer,\n self.hparams.cache_dataset,\n )\n\n def train_dataloader(self):\n \"\"\"Initialize the train dataloader\"\"\"\n return DataLoader(\n dataset=self.data_train,\n batch_size=self.hparams.batch_size,\n collate_fn=CustomPadCollate(self.hparams.vocab_size),\n num_workers=self.hparams.dataloader_workers,\n pin_memory=self.hparams.pin_memory,\n shuffle=True,\n )\n\n def val_dataloader(self):\n \"\"\"Initialize the validataion dataloader\"\"\"\n return DataLoader(\n dataset=self.data_val,\n batch_size=self.hparams.batch_size,\n collate_fn=CustomPadCollate(self.hparams.vocab_size),\n num_workers=self.hparams.dataloader_workers,\n pin_memory=self.hparams.pin_memory,\n shuffle=False,\n )\n\n def test_dataloader(self):\n \"\"\"Initialize the test dataloader\"\"\"\n return DataLoader(\n dataset=self.data_test,\n batch_size=self.hparams.batch_size,\n collate_fn=CustomPadCollate(self.hparams.vocab_size),\n num_workers=self.hparams.dataloader_workers,\n pin_memory=self.hparams.pin_memory,\n shuffle=False,\n )\n\n def teardown(self, stage: Optional[str] = None):\n \"\"\"Clean up after fit or test\"\"\"\n pass\n\n def state_dict(self):\n \"\"\"Extra things to save to checkpoint\"\"\"\n return {}\n\n def load_state_dict(self, state_dict: Dict[str, Any]):\n \"\"\"Things to do when loading checkpoint\"\"\"\n pass\n\n\nif __name__ == \"__main__\":\n import hydra\n import omegaconf\n import pyrootutils\n\n root = pyrootutils.setup_root(__file__, pythonpath=True)\n cfg = omegaconf.OmegaConf.load(\n root / \"configs\" / \"datamodule\" / \"classic_guitar.yaml\"\n )\n cfg.data_dir = str(root / \"data\")\n _ = hydra.utils.instantiate(cfg)\n", "repo_name": "KimSehun725/seq2seqGuitarTranscription", "sub_path": "src/datamodules/classic_guitar.py", "file_name": "classic_guitar.py", "file_ext": "py", "file_size_in_byte": 8984, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "pytorch_lightning.LightningDataModule", "line_number": 23, "usage_type": "name"}, {"api_name": "miditok.MIDITokenizer", "line_number": 47, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path", "line_number": 73, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 84, "usage_type": "call"}, {"api_name": "os.path", "line_number": 84, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path", "line_number": 87, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 88, "usage_type": "call"}, {"api_name": "os.path", "line_number": 88, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 89, "usage_type": "call"}, {"api_name": "os.path", "line_number": 89, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 93, "usage_type": "call"}, {"api_name": "os.path", "line_number": 93, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 94, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 95, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 96, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 97, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 99, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 100, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 101, "usage_type": "call"}, {"api_name": "multiprocessing.Pool", "line_number": 107, "usage_type": "call"}, {"api_name": "rich.progress.Progress", "line_number": 108, "usage_type": "call"}, {"api_name": "src.data_preprocess.data_preprocess.check_midi_validity", "line_number": 113, "usage_type": "argument"}, {"api_name": "multiprocessing.Pool", "line_number": 127, "usage_type": "call"}, {"api_name": "rich.progress.Progress", "line_number": 128, "usage_type": "call"}, {"api_name": "src.data_preprocess.data_preprocess.classic_guitar_preprocess", "line_number": 133, "usage_type": "argument"}, {"api_name": "itertools.repeat", "line_number": 136, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 144, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 144, "usage_type": "call"}, {"api_name": "os.path", "line_number": 144, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 145, "usage_type": "call"}, {"api_name": "os.path", "line_number": 145, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 147, "usage_type": "call"}, {"api_name": "os.path", "line_number": 147, "usage_type": "attribute"}, {"api_name": "random.shuffle", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 151, "usage_type": "call"}, {"api_name": "src.datamodules.components.CustomDataset", "line_number": 166, "usage_type": "call"}, {"api_name": "src.datamodules.components.CustomDataset", "line_number": 172, "usage_type": "call"}, {"api_name": "src.datamodules.components.CustomDataset", "line_number": 178, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 187, "usage_type": "call"}, {"api_name": "src.datamodules.components.CustomPadCollate", "line_number": 190, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 198, "usage_type": "call"}, {"api_name": "src.datamodules.components.CustomPadCollate", "line_number": 201, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 209, "usage_type": "call"}, {"api_name": "src.datamodules.components.CustomPadCollate", "line_number": 212, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 218, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 226, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 226, "usage_type": "name"}, {"api_name": "pyrootutils.setup_root", "line_number": 236, "usage_type": "call"}, {"api_name": "omegaconf.OmegaConf.load", "line_number": 237, "usage_type": "call"}, {"api_name": "omegaconf.OmegaConf", "line_number": 237, "usage_type": "attribute"}, {"api_name": "hydra.utils.instantiate", "line_number": 241, "usage_type": "call"}, {"api_name": "hydra.utils", "line_number": 241, "usage_type": "attribute"}]} +{"seq_id": "19987050321", "text": "import requests\n\n\ndef call_api(ticket_id):\n api_url = \"http://localhost:58000/api/v1/host\"\n headers = {\"X-Auth-Token\": ticket_id}\n return requests.get(api_url, headers=headers, verify=False)\n\n\ndef get_hosts(ticket_id):\n resp = call_api(ticket_id)\n response_json = resp.json()\n hosts = response_json[\"response\"]\n formatted_hosts = []\n for host in hosts:\n if 'hostName' in host:\n formatted_host = format_dict_to_list(host)\n # print(formatted_host)\n formatted_hosts.append(formatted_host)\n else:\n continue\n return formatted_hosts\n\n\ndef format_dict_to_list(host):\n return [host[\"hostName\"], host[\"hostIp\"], host[\"hostMac\"], host[\"connectedInterfaceName\"]]\n\n\ndef get_hostcount(ticket_id):\n api_url = \"http://localhost:58000/api/v1/host/count\"\n\n headers = {\"X-Auth-Token\": \"NC-19-7661d50f182946278a7e-nbi\"}\n\n resp = requests.get(api_url, headers=headers, verify=False)\n\n response_json = resp.json()\n hostcount = response_json[\"response\"]\n print(\"Number of hosts: \", hostcount)\n\n\ndef get_host_by_ip(ticket_id, ip_address):\n api_url = \"http://localhost:58000/api/v1/host/ip-address/\" + ip_address\n\n headers = {\"X-Auth-Token\": \"NC-19-7661d50f182946278a7e-nbi\"}\n\n resp = requests.get(api_url, headers=headers, verify=False)\n\n response_json = resp.json()\n hostname = response_json[\"hostName\"]\n hostIp = response_json[\"hostIp\"]\n hostType = response_json[\"hostType\"]\n print(\"Hostname:\", hostname)\n print(\"Host-IP:\", hostIp)\n print(\"Host-Type:\", hostType)\n", "repo_name": "CptTripps-tech/LF09", "sub_path": "src/host_service.py", "file_name": "host_service.py", "file_ext": "py", "file_size_in_byte": 1578, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "requests.get", "line_number": 7, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 34, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 46, "usage_type": "call"}]} +{"seq_id": "30090975373", "text": "# !/usr/bin/python\n# -*- coding: -*-\n\nimport requests\nimport json\nimport time\nimport re\nimport pymysql\n\n\ndef save_to_mysql(data: dict, conn):\n cursor = conn.cursor()\n if '-' in data['city']:\n data['city'] = re.sub('-.*?$', ' ', data['city']).strip()\n print('start save', data['job_name'], data['kw'], data['city'])\n sql = '''\n insert into zhilian_job (kw, job_name, company, city, salary, exp, edu) values (%s,%s,%s,%s,%s,%s,%s)\n '''\n cursor.execute(sql, (\n data['kw'], data['job_name'], data['company'], data['city'], data['salary'], data['exp'], data['edu']))\n conn.commit()\n time.sleep(1)\n\n\ndef get_data(url: str, kw: str, conn):\n '''提取该条url中所有可以提取的数据'''\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'\n }\n content = requests.get(url, headers=headers).content.decode()\n try:\n data_list = json.loads(content)['data']['results']\n except:\n return\n for data in data_list:\n job_name = data['jobName']\n company = data['company']['name']\n city = data['city']['display']\n salary = data['salary']\n exp = data['workingExp']['name']\n edu = data['eduLevel']['name']\n\n data_dict = {\n 'kw': kw,\n 'job_name': job_name,\n 'company': company,\n 'city': city,\n 'salary': salary,\n 'exp': exp,\n 'edu': edu,\n }\n\n save_to_mysql(data_dict, conn)\n\n\ndef judge_result_data_exist(content: str):\n '''判断该页是否存在可以爬取的数据,存在返回True,否则返回false'''\n try:\n data_list = json.loads(content)['data']['results']\n except:\n return False\n if len(data_list) != 0:\n return True\n else:\n return False\n\n\ndef loop_spider(url: str, kw: str, conn):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'\n }\n page = 0\n while True:\n url = re.sub('start=\\d+&', 'start=' + str(page) + '&', url)\n print('start this', url)\n content = requests.get(url, headers=headers).content.decode()\n flag = judge_result_data_exist(content)\n if flag:\n get_data(url, kw, conn)\n continue\n page += 90\n else:\n break\n\n\ndef gen_url_list():\n base_url = '''https://fe-api.zhaopin.com/c/i/sou?start=0&pageSize=90&cityId=489&salary=0,0&workExperience=-1&education=-1&companyType=-1&employmentType=-1&jobWelfareTag=-1&kw={kw}&kt=3&=0&rt=cdebee05f68b46ad9b2826ad59465995&_v=0.67395132&x-zp-page-request-id=4e016822e03b42238ccdde80f80db89f-1554534268499-442740'''\n key_lan_word = ['python', 'java', 'c语言', 'c++', 'sql', 'go', 'php', 'c#', 'JavaScript', 'perl', '.net', 'objective-c',\n 'MATLAB', 'R', 'assembly', 'swift', 'Delphi']\n key_job_word = ['前端', '后端', '软件开发', 'Android',\n 'ios', '测试', '运维', 'DBA', '算法', '架构', '运营', '大数据', '数据分析', '机器学习', '游戏制作', '人工智���']\n key_list = key_lan_word + key_job_word\n result_list = []\n\n for kw in key_list:\n result_list.append((base_url.format(kw=kw), kw))\n\n return result_list\n\n\nif __name__ == '__main__':\n conn = pymysql.connect(\n host='localhost',\n user='root',\n password='xzx199110',\n database='bs',\n port=3306,\n )\n url_list = gen_url_list()\n\n for url, kw in url_list:\n loop_spider(url, kw, conn)\n\n conn.close()\n", "repo_name": "pipoted/bs", "sub_path": "spider/all_spider/zhilian_spider.py", "file_name": "zhilian_spider.py", "file_ext": "py", "file_size_in_byte": 3718, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "re.sub", "line_number": 14, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 22, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 30, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 32, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 59, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 74, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 76, "usage_type": "call"}, {"api_name": "pymysql.connect", "line_number": 102, "usage_type": "call"}]} +{"seq_id": "71565650608", "text": "\"\"\"Load templates for loaded plugins.\"\"\"\n\nfrom django.template.loaders.filesystem import Loader as FilesystemLoader\n\nfrom plugin import registry\n\n\nclass PluginTemplateLoader(FilesystemLoader):\n \"\"\"A custom template loader which allows loading of templates from installed plugins.\n\n Each plugin can register templates simply by providing a 'templates' directory in its root path.\n\n The convention is that each 'templates' directory contains a subdirectory with the same name as the plugin,\n e.g. templates/myplugin/my_template.html\n\n In this case, the template can then be loaded (from any plugin!) by loading \"myplugin/my_template.html\".\n\n The separate plugin-named directories help keep the templates separated and uniquely identifiable.\n \"\"\"\n\n def get_dirs(self):\n \"\"\"Returns all template dir paths in plugins.\"\"\"\n dirname = 'templates'\n template_dirs = []\n\n for plugin in registry.plugins.values():\n new_path = plugin.path().joinpath(dirname)\n if new_path.is_dir():\n template_dirs.append(new_path)\n\n return tuple(template_dirs)\n", "repo_name": "inventree/InvenTree", "sub_path": "InvenTree/plugin/template.py", "file_name": "template.py", "file_ext": "py", "file_size_in_byte": 1127, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3204, "dataset": "github-code", "pt": "2", "api": [{"api_name": "django.template.loaders.filesystem.Loader", "line_number": 8, "usage_type": "name"}, {"api_name": "plugin.registry.plugins.values", "line_number": 26, "usage_type": "call"}, {"api_name": "plugin.registry.plugins", "line_number": 26, "usage_type": "attribute"}, {"api_name": "plugin.registry", "line_number": 26, "usage_type": "name"}, {"api_name": "plugin.path", "line_number": 27, "usage_type": "call"}]} +{"seq_id": "15731300945", "text": "\"\"\"Sensor for fdmealplanner account status.\"\"\"\nfrom datetime import timedelta\nimport logging\nimport requests\nimport arrow\nimport xmltodict, json\nfrom xml.etree import ElementTree\nfrom itertools import islice\nimport urllib.parse\n\nfrom time import mktime\n\nimport voluptuous as vol\n\nfrom homeassistant.components.sensor import PLATFORM_SCHEMA\nfrom homeassistant.core import callback\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.helpers.entity import Entity\nfrom homeassistant.helpers.event import track_time_interval\nfrom homeassistant.util.dt import utc_from_timestamp\nfrom homeassistant.helpers.aiohttp_client import async_get_clientsession\n\n_LOGGER = logging.getLogger(__name__)\n\nCONF_ACCOUNTS = \"accounts\"\n\nICON = \"mdi:robot-outline\"\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(\n {\n vol.Required(CONF_ACCOUNTS, default=[]): vol.All(cv.ensure_list, [cv.string]),\n }\n)\n\n\nBASE_INTERVAL = timedelta(hours=6)\n\n\nasync def async_setup_platform(hass, config, async_add_entities, discovery_info=None):\n \"\"\"Set up the fdmealplanner platform.\"\"\"\n \n entities = [fdmealplannerSensor(hass, account) for account in config.get(CONF_ACCOUNTS)]\n if not entities:\n return\n async_add_entities(entities, True)\n\n # Only one sensor update once every 60 seconds to avoid\n entity_next = 0\n\n\n\nclass fdmealplannerSensor(Entity):\n \"\"\"A class for the mealviewer account.\"\"\"\n\n def __init__(self, hass, account):\n \"\"\"Initialize the sensor.\"\"\"\n \n self._account = account\n self._lunch0 = None\n self._lunch1 = None\n self._lunch2 = None\n self._lunch3 = None\n self._lunch4 = None\n self._state = None\n self._name = self._account\n self.hass = hass\n \n @property\n def name(self):\n \"\"\"Return the name of the sensor.\"\"\"\n return self._name\n\n @property\n def entity_id(self):\n \"\"\"Return the entity ID.\"\"\"\n #return f\"sensor.mealviewer_{self._name}\"\n return 'sensor.fdmealplanner_' + (self._account).replace(\"/\",\"_\")\n \n @property\n def state(self):\n \"\"\"Return the state of the sensor.\"\"\"\n return self._state\n \n @property\n def should_poll(self):\n \"\"\"Turn off polling, will do ourselves.\"\"\"\n return True\n \n async def async_update(self):\n \"\"\"Update device state.\"\"\"\n \n self._state = 'Not Updated'\n try:\n \n headers = {\n 'accept': 'application/json',\n 'pragma': 'no-cache',\n 'x-jsonresponsecase': 'camel',\n 'x-requested-with': 'XMLHttpRequest',\n 'user-agent': 'okhttp/4.9.1',\n }\n session = async_get_clientsession(self.hass)\n [accountId, locationId, mealPeriodId] = self._account.split('/')\n for day in range(5):\n tomorrow = arrow.utcnow().to('US/Eastern').shift(days=day)\n meal = ''\n if tomorrow.weekday() not in (5, 6):\n formatted_tomorrow = urllib.parse.quote(tomorrow.format('MM DD YYYY'))\n formatted_year = tomorrow.format('YYYY')\n formatted_month = tomorrow.format('M') \n \n url = 'https://apiservicelocators.fdmealplanner.com/api/v1/data-locator-webapi/3/meals?accountId=' + accountId + '&endDate=' + formatted_tomorrow + '&isActive=true&isStandalone&locationId='+ locationId +'&mealPeriodId=' + mealPeriodId + '&menuId=0&monthId=' +formatted_month+ '&selectedDate=' + formatted_tomorrow + '&startDate=' + formatted_tomorrow + '&tenantId=3&timeOffset=300&year=' + formatted_year\n \n resp = await session.get(url,headers=headers)\n datajson = await resp.json()\n \n if datajson['result'][0].get('xmlMenuRecipes') is None:\n meal = ''\n else: \n root = ElementTree.fromstring(datajson['result'][0].get('xmlMenuRecipes'))\n meal = tomorrow.format('dddd')\n counter = 0\n lastEntree = ''\n for child in root: #islice(root,15):\n if counter > 5:\n break\n entree = child.attrib.get('ComponentEnglishName').strip()\n if entree == lastEntree:\n continue\n lastEntree = entree \n counter = counter + 1\n if counter == 1:\n meal = meal + ': ' + entree\n else:\n meal = meal + ', ' + entree\n \n \n \n if day == 0:\n self._lunch0 = meal\n if day == 1:\n self._lunch1 = meal\n if day == 2:\n self._lunch2 = meal\n if day == 3:\n self._lunch3 = meal\n if day == 4:\n self._lunch4 = meal\n \n self._state = 'Updated' \n except: \n self._lunch0 = None\n self._lunch1 = None\n self._lunch2 = None\n self._lunch3 = None\n self._lunch4 = None\n \n @property\n def extra_state_attributes(self):\n \"\"\"Return the state attributes.\"\"\"\n attr = {}\n \n attr[\"lunch0\"] = self._lunch0\n attr[\"lunch1\"] = self._lunch1 \n attr[\"lunch2\"] = self._lunch2\n attr[\"lunch3\"] = self._lunch3\n attr[\"lunch4\"] = self._lunch4\n \n \n return attr\n\n \n @property\n def icon(self):\n \"\"\"Return the icon to use in the frontend.\"\"\"\n return ICON\n", "repo_name": "jdeath/fdmealplanner", "sub_path": "custom_components/mealviewer/sensor.py", "file_name": "sensor.py", "file_ext": "py", "file_size_in_byte": 6015, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "logging.getLogger", "line_number": 23, "usage_type": "call"}, {"api_name": "homeassistant.components.sensor.PLATFORM_SCHEMA", "line_number": 29, "usage_type": "name"}, {"api_name": "homeassistant.components.sensor.PLATFORM_SCHEMA.extend", "line_number": 29, "usage_type": "call"}, {"api_name": "voluptuous.Required", "line_number": 31, "usage_type": "call"}, {"api_name": "voluptuous.All", "line_number": 31, "usage_type": "call"}, {"api_name": "homeassistant.helpers.config_validation.ensure_list", "line_number": 31, "usage_type": "attribute"}, {"api_name": "homeassistant.helpers.config_validation", "line_number": 31, "usage_type": "name"}, {"api_name": "homeassistant.helpers.config_validation.string", "line_number": 31, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 36, "usage_type": "call"}, {"api_name": "homeassistant.helpers.entity.Entity", "line_number": 52, "usage_type": "name"}, {"api_name": "homeassistant.helpers.aiohttp_client.async_get_clientsession", "line_number": 102, "usage_type": "call"}, {"api_name": "arrow.utcnow", "line_number": 105, "usage_type": "call"}, {"api_name": "urllib.parse.parse.quote", "line_number": 108, "usage_type": "call"}, {"api_name": "urllib.parse.parse", "line_number": 108, "usage_type": "attribute"}, {"api_name": "urllib.parse", "line_number": 108, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.fromstring", "line_number": 120, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 120, "usage_type": "name"}]} +{"seq_id": "8434323457", "text": "# -*- coding: utf-8 -*-\nimport time\nimport types\nimport atexit\nimport pickle\nimport asyncio\nfrom functools import wraps\n\nimport aioredis as redis\n\n\nclass ArgsUnhashable(Exception):\n pass\n\nclass AioRedisLRU:\n def __init__(self,\n client: redis.StrictRedis,\n max_size=2 ** 20,\n default_ttl=15 * 60,\n key_prefix='RedisLRU',\n clear_on_exit=False):\n self.client = client\n self.max_size = max_size\n self.key_prefix = key_prefix\n self.default_ttl = default_ttl\n\n if clear_on_exit:\n atexit.register(self.clear_all_cache)\n\n def __call__(self, ttl=60 * 15, skiped_args=0):\n func = None\n\n async def inner(*args, **kwargs):\n try:\n key = self._decorator_key(func, *args[skiped_args:], **kwargs)\n except ArgsUnhashable:\n return await func(*args, **kwargs)\n else:\n try:\n # print('key', key)\n task = await self[key]\n # print('cache result:', task)\n return task\n except KeyError:\n result = await func(*args, **kwargs)\n await self.set(key, result, ttl)\n return result\n\n # decorator without arguments\n if callable(ttl):\n func = ttl\n ttl = 60 * 15\n skipped_args = 0\n return wraps(func)(inner)\n\n # decorator with arguments\n def wrapper(f):\n nonlocal func\n func = f\n return wraps(func)(inner)\n\n return wrapper\n\n def __setitem__(self, key, value):\n return self.set(key, value)\n\n\n async def __getitem__(self, key):\n r = await self.client.exists(key)\n if not r:\n raise KeyError()\n else:\n result = await self.client.get(key)\n if result is None:\n raise KeyError()\n return pickle.loads(result)\n\n async def set(self, key, value, ttl=None):\n ttl = ttl or self.default_ttl\n value = pickle.dumps(value)\n return await self.client.setex(key, ttl, value)\n\n async def get(self, key, default=None):\n \"\"\"\n Fetch a given key from the cache. If the key does not exist, return\n default, which itself defaults to None.\n \"\"\"\n\n try:\n return await self[key]\n except KeyError:\n return default\n\n async def clear_all_cache(self):\n def delete_keys(items):\n pipeline = self.client.pipeline()\n for item in items:\n pipeline.delete(item)\n return pipeline.execute()\n\n match = '{}*'.format(self.key_prefix)\n keys = []\n for key in await self.client.scan_iter(match, count=100):\n keys.append(key)\n if len(keys) >= 100:\n await delete_keys(keys)\n keys = []\n time.sleep(0.01)\n else:\n await delete_keys(keys)\n\n def _decorator_key(self, func: types.FunctionType, *args, **kwargs):\n try:\n for arg in args:\n hash(arg)\n for value in kwargs.values():\n hash(value)\n except TypeError:\n raise ArgsUnhashable()\n\n return '{}:{}:{}{!r}:{!r}'.format(self.key_prefix, func.__module__,\n func.__qualname__, args, kwargs)\n\n\n\n\n# from diskcache import Cache\n# client = redis.StrictRedis()\n#\n# cache = RedisLRU(client, 0)\n#\n# cache['x'] = 10\n#\n#\n# @cache(ttl=10)\n# def foo(x):\n# print('foo ', x)\n# return x + 1\n#\n#\n# @cache\n# def bar():\n# print('bar')\n# pass\n#\n#\n# print(foo(1))\n# print(bar())\n", "repo_name": "Pupation/GalaxyGallery", "sub_path": "utils/cache/aioredis.py", "file_name": "aioredis.py", "file_ext": "py", "file_size_in_byte": 3792, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "27", "api": [{"api_name": "aioredis.StrictRedis", "line_number": 17, "usage_type": "attribute"}, {"api_name": "atexit.register", "line_number": 28, "usage_type": "call"}, {"api_name": "functools.wraps", "line_number": 54, "usage_type": "call"}, {"api_name": "functools.wraps", "line_number": 60, "usage_type": "call"}, {"api_name": "pickle.loads", "line_number": 76, "usage_type": "call"}, {"api_name": "pickle.dumps", "line_number": 80, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 108, "usage_type": "call"}, {"api_name": "types.FunctionType", "line_number": 112, "usage_type": "attribute"}]} +{"seq_id": "31062345320", "text": "# -*- coding: utf-8 -*-\n\"\"\"WorkChian to easily and controlablly evaluate the energy of the configurations(Using QE plugins).\"\"\"\nfrom aiida import orm\nfrom aiida.engine import WorkChain, ToContext, if_\nfrom aiida.plugins import WorkflowFactory\nfrom aiida.common import AttributeDict\n\nfrom aiida_quantumespresso.utils.protocols.pw import ProtocolManager\nfrom aiida_quantumespresso.utils.pseudopotential import get_pseudos_from_dict\nfrom aiida_quantumespresso.utils.resources import get_default_options\nfrom aiida_quantumespresso.utils.mapping import prepare_process_inputs\n\nPwBaseWorkChain = WorkflowFactory('quantumespresso.pw.base')\nPwRelaxWorkChain = WorkflowFactory('quantumespresso.pw.relax')\n\ndef validate_protocol(protocol_dict):\n \"\"\"Check that the protocol is one for which we have a definition.\"\"\"\n try:\n protocol_name = protocol_dict['name']\n except KeyError as exception:\n return 'Missing key `name` in protocol dictionary'\n try:\n ProtocolManager(protocol_name)\n except ValueError as exception:\n return str(exception)\n\nclass DpEvaluateBaseWorkChain(WorkChain):\n \"\"\"WorkChian to easily and controlablly evaluate the energy of the configurations(Using QE plugins).\"\"\"\n\n @classmethod\n def define(cls, spec):\n \"\"\"Define the process specification\"\"\"\n # yapf: disable\n super(DpEvaluateBaseWorkChain, cls).define(spec)\n spec.input('code', valid_type=orm.Code,\n help='The `pw.x` code to use for the `PwCalculations`.')\n spec.input('structure', valid_type=orm.StructureData,\n help='The input structure.')\n spec.input('options', valid_type=orm.Dict, required=False,\n help='Optional `options` to use for the `PwCalculations`.')\n spec.input('protocol', valid_type=orm.Dict,\n default=orm.Dict(dict={'name': 'theos-ht-1.0', 'modifiers': {'parameters': 'default', 'pseudo': 'SSSP-efficiency-1.1'}}),\n help='The protocol to use for the workchain.', validator=validate_protocol)\n spec.input('do_relax', valid_type=orm.Bool, default=orm.Bool(True),\n help='If `True`, running the relax and then scf')\n spec.input('clean_workdir', valid_type=orm.Bool, default=orm.Bool(True),\n help='If `True`, work directories of all called calculation will be cleaned at the end of execution.')\n spec.outline(\n cls.setup_protocol,\n cls.setup_parameters,\n if_(cls.should_do_relax)(\n cls.run_relax,\n cls.inspect_relax,\n ),\n cls.run_scf,\n cls.inspect_scf,\n cls.results,\n )\n spec.exit_code(201, 'ERROR_INVALID_INPUT_UNRECOGNIZED_KIND',\n message='Input `StructureData` contains an unsupported kind.')\n spec.exit_code(401, 'ERROR_SUB_PROCESS_FAILED_RELAX',\n message='the PwRelaxWorkChain sub process failed')\n spec.exit_code(402, 'ERROR_SUB_PROCESS_FAILED_SCF',\n message='the scf PwBasexWorkChain sub process failed')\n spec.output('primitive_structure', valid_type=orm.StructureData,\n help='The normalized and primitivized structure for which the scf step are computed.')\n spec.output('scf_parameters', valid_type=orm.Dict,\n help='The output parameters of the SCF `PwBaseWorkChain`.')\n\n def _get_protocol(self):\n protocol_data = self.inputs.protocol.get_dict()\n protocol_name = protocol_data['name']\n protocol = ProtocolManager(protocol_name)\n\n protocol_modifiers = protocol_data.get('modifiers', {})\n\n return protocol, protocol_modifiers\n\n def setup_protocol(self):\n \"\"\"Set up context variables and inputs for the `CeEvaluateWorkChain`\n\n Based on the specified protocol, we define values for variables that affect the execution of the calculations.\n \"\"\"\n protocol, protocol_modifiers = self._get_protocol()\n self.report('running the workchain with the \"{}\" protocol'.format(protocol.name))\n self.ctx.protocol = protocol.get_protocol_data(modifiers=protocol_modifiers)\n\n def setup_parameters(self):\n \"\"\"Set up the default input parameters required for the `PwBandsWorkChain`.\"\"\"\n ecutwfc = []\n ecutrho = []\n\n for kind in self.inputs.structure.get_kind_names():\n try:\n dual = self.ctx.protocol['pseudo_data'][kind]['dual']\n cutoff = self.ctx.protocol['pseudo_data'][kind]['cutoff']\n cutrho = dual * cutoff\n ecutwfc.append(cutoff)\n ecutrho.append(cutrho)\n except KeyError:\n self.report('failed to retrieve the cutoff or dual factor for {}'.format(kind))\n return self.exit_codes.ERROR_INVALID_INPUT_UNRECOGNIZED_KIND\n\n self.ctx.parameters = orm.Dict(dict={\n 'CONTROL': {\n 'restart_mode': 'from_scratch',\n 'tstress': self.ctx.protocol['tstress'],\n 'tprnfor': self.ctx.protocol['tprnfor'],\n },\n 'SYSTEM': {\n 'ecutwfc': max(ecutwfc),\n 'ecutrho': max(ecutrho),\n 'smearing': self.ctx.protocol['smearing'],\n 'degauss': self.ctx.protocol['degauss'],\n 'occupations': self.ctx.protocol['occupations'],\n },\n 'ELECTRONS': {\n 'conv_thr': self.ctx.protocol['convergence_threshold_per_atom'] * len(self.inputs.structure.sites),\n }\n })\n\n def should_do_relax(self):\n \"\"\"If the 'relax' input namespace was specified, we relax the input structure.\"\"\"\n return self.inputs.do_relax.value\n\n def _get_common_inputs(self):\n \"\"\"Return the dictionary of inputs to be used as the basis for each `PwBaseWorkChain`.\"\"\"\n protocol, protocol_modifiers = self._get_protocol()\n checked_pseudos = protocol.check_pseudos(\n modifier_name=protocol_modifiers.get('pseudo', None),\n pseudo_data=protocol_modifiers.get('pseudo_data', None))\n known_pseudos = checked_pseudos['found']\n\n inputs = AttributeDict({\n 'pw': {\n 'code': self.inputs.code,\n 'pseudos': get_pseudos_from_dict(self.inputs.structure, known_pseudos),\n 'parameters': self.ctx.parameters,\n 'metadata': {},\n }\n })\n\n if 'options' in self.inputs:\n inputs.pw.metadata.options = self.inputs.options.get_dict()\n else:\n inputs.pw.metadata.options = get_default_options(with_mpi=True)\n\n return inputs\n\n def run_relax(self):\n \"\"\"Run the PwRelaxWorkChain to run a relax PwCalculation.\"\"\"\n inputs = AttributeDict({\n 'structure': self.inputs.structure,\n 'base': self._get_common_inputs(),\n 'relaxation_scheme': orm.Str('vc-relax'),\n 'meta_convergence': orm.Bool(self.ctx.protocol['meta_convergence']),\n 'volume_convergence': orm.Float(self.ctx.protocol['volume_convergence']),\n })\n inputs.base.kpoints_distance = orm.Float(self.ctx.protocol['kpoints_mesh_density'])\n\n running = self.submit(PwRelaxWorkChain, **inputs)\n\n self.report('launching PwRelaxWorkChain<{}>'.format(running.pk))\n\n return ToContext(workchain_relax=running)\n\n def inspect_relax(self):\n \"\"\"Verify that the PwRelaxWorkChain finished successfully.\"\"\"\n workchain = self.ctx.workchain_relax\n\n if not workchain.is_finished_ok:\n self.report('PwRelaxWorkChain failed with exit status {}'.format(workchain.exit_status))\n return self.exit_codes.ERROR_SUB_PROCESS_FAILED_RELAX\n\n self.ctx.current_structure = workchain.outputs.output_structure\n\n def run_scf(self):\n \"\"\"Run the PwBaseWorkChain in scf mode on the primitive cell of (optionally relaxed) input structure.\"\"\"\n inputs = self._get_common_inputs()\n if not self.should_do_relax():\n self.ctx.current_structure = self.inputs.structure\n inputs.pw.structure = self.ctx.current_structure\n inputs.pw.parameters = inputs.pw.parameters.get_dict()\n inputs.pw.parameters.setdefault('CONTROL', {})\n inputs.pw.parameters['CONTROL']['calculation'] = 'scf'\n\n inputs.kpoints_distance = orm.Float(self.ctx.protocol['kpoints_mesh_density'])\n\n inputs = prepare_process_inputs(PwBaseWorkChain, inputs)\n running = self.submit(PwBaseWorkChain, **inputs)\n\n self.report('launching PwBaseWorkChain<{}> in {} mode'.format(running.pk, 'scf'))\n\n return ToContext(workchain_scf=running)\n\n def inspect_scf(self):\n \"\"\"Verify that the PwBaseWorkChain for the scf run finished successfully.\"\"\"\n workchain = self.ctx.workchain_scf\n\n if not workchain.is_finished_ok:\n self.report('scf PwBaseWorkChain failed with exit status {}'.format(workchain.exit_status))\n return self.exit_codes.ERROR_SUB_PROCESS_FAILED_SCF\n\n self.ctx.current_folder = workchain.outputs.remote_folder\n\n def results(self):\n \"\"\"Attach the desired output nodes directly as outputs of the workchain.\"\"\"\n self.report('workchain succesfully completed')\n self.out('scf_parameters', self.ctx.workchain_scf.outputs.output_parameters)\n self.out('primitive_structure', self.ctx.current_structure)\n\n def on_terminated(self):\n \"\"\"Clean the working directories of all child calculations if `clean_workdir=True` in the inputs.\"\"\"\n super(CeEvaluateBaseWorkChain, self).on_terminated()\n\n if self.inputs.clean_workdir.value is False:\n self.report('remote folders will not be cleaned')\n return\n\n cleaned_calcs = []\n\n for called_descendant in self.node.called_descendants:\n if isinstance(called_descendant, orm.CalcJobNode):\n try:\n called_descendant.outputs.remote_folder._clean() # pylint: disable=protected-access\n cleaned_calcs.append(called_descendant.pk)\n except (IOError, OSError, KeyError):\n pass\n\n if cleaned_calcs:\n self.report('cleaned remote folders of calculations: {}'.format(' '.join(map(str, cleaned_calcs))))\n", "repo_name": "chenggroup/aiida-deepmd", "sub_path": "aiida_deepmd/workflows/evaluate_base.py", "file_name": "evaluate_base.py", "file_ext": "py", "file_size_in_byte": 10325, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "aiida.plugins.WorkflowFactory", "line_number": 13, "usage_type": "call"}, {"api_name": "aiida.plugins.WorkflowFactory", "line_number": 14, "usage_type": "call"}, {"api_name": "aiida_quantumespresso.utils.protocols.pw.ProtocolManager", "line_number": 23, "usage_type": "call"}, {"api_name": "aiida.engine.WorkChain", "line_number": 27, "usage_type": "name"}, {"api_name": "aiida.orm.Code", "line_number": 35, "usage_type": "attribute"}, {"api_name": "aiida.orm", "line_number": 35, "usage_type": "name"}, {"api_name": "aiida.orm.StructureData", "line_number": 37, "usage_type": "attribute"}, {"api_name": "aiida.orm", "line_number": 37, "usage_type": "name"}, {"api_name": "aiida.orm.Dict", "line_number": 39, "usage_type": "attribute"}, {"api_name": "aiida.orm", "line_number": 39, "usage_type": "name"}, {"api_name": "aiida.orm.Dict", "line_number": 41, "usage_type": "attribute"}, {"api_name": "aiida.orm", "line_number": 41, "usage_type": "name"}, {"api_name": "aiida.orm.Dict", "line_number": 42, "usage_type": "call"}, {"api_name": "aiida.orm", "line_number": 42, "usage_type": "name"}, {"api_name": "aiida.orm.Bool", "line_number": 44, "usage_type": "attribute"}, {"api_name": "aiida.orm", "line_number": 44, "usage_type": "name"}, {"api_name": "aiida.orm.Bool", "line_number": 46, "usage_type": "attribute"}, {"api_name": "aiida.orm", "line_number": 46, "usage_type": "name"}, {"api_name": "aiida.engine.if_", "line_number": 51, "usage_type": "call"}, {"api_name": "aiida.orm.StructureData", "line_number": 65, "usage_type": "attribute"}, {"api_name": "aiida.orm", "line_number": 65, "usage_type": "name"}, {"api_name": "aiida.orm.Dict", "line_number": 67, "usage_type": "attribute"}, {"api_name": "aiida.orm", "line_number": 67, "usage_type": "name"}, {"api_name": "aiida_quantumespresso.utils.protocols.pw.ProtocolManager", "line_number": 73, "usage_type": "call"}, {"api_name": "aiida.orm.Dict", "line_number": 104, "usage_type": "call"}, {"api_name": "aiida.orm", "line_number": 104, "usage_type": "name"}, {"api_name": "aiida.common.AttributeDict", "line_number": 134, "usage_type": "call"}, {"api_name": "aiida_quantumespresso.utils.pseudopotential.get_pseudos_from_dict", "line_number": 137, "usage_type": "call"}, {"api_name": "aiida_quantumespresso.utils.resources.get_default_options", "line_number": 146, "usage_type": "call"}, {"api_name": "aiida.common.AttributeDict", "line_number": 152, "usage_type": "call"}, {"api_name": "aiida.orm.Str", "line_number": 155, "usage_type": "call"}, {"api_name": "aiida.orm", "line_number": 155, "usage_type": "name"}, {"api_name": "aiida.orm.Bool", "line_number": 156, "usage_type": "call"}, {"api_name": "aiida.orm", "line_number": 156, "usage_type": "name"}, {"api_name": "aiida.orm.Float", "line_number": 157, "usage_type": "call"}, {"api_name": "aiida.orm", "line_number": 157, "usage_type": "name"}, {"api_name": "aiida.orm.Float", "line_number": 159, "usage_type": "call"}, {"api_name": "aiida.orm", "line_number": 159, "usage_type": "name"}, {"api_name": "aiida.engine.ToContext", "line_number": 165, "usage_type": "call"}, {"api_name": "aiida.orm.Float", "line_number": 187, "usage_type": "call"}, {"api_name": "aiida.orm", "line_number": 187, "usage_type": "name"}, {"api_name": "aiida_quantumespresso.utils.mapping.prepare_process_inputs", "line_number": 189, "usage_type": "call"}, {"api_name": "aiida.engine.ToContext", "line_number": 194, "usage_type": "call"}, {"api_name": "aiida.orm.CalcJobNode", "line_number": 223, "usage_type": "attribute"}, {"api_name": "aiida.orm", "line_number": 223, "usage_type": "name"}]} +{"seq_id": "38147767558", "text": "import unittest\nfrom pyramid import testing\n\n\nclass TestFrontPage(unittest.TestCase):\n\n def setUp(self):\n self.config = testing.setUp()\n\n def tearDown(self):\n testing.tearDown()\n\n def test_frontpage(self):\n from webidentity.views.pages import front_page\n\n self.config.add_route('openid_endpoint', '/openid')\n self.config.add_route('yadis_server', '/yadis')\n request = testing.DummyRequest()\n\n self.assertEquals(front_page(request), {\n 'xrds_location': 'http://example.com/yadis',\n 'openid_endpoint': 'http://example.com/openid',\n 'title': u'Nuorisovaalit 2011 - Tunnistautuminen'})\n", "repo_name": "verkkodemokratiaseura/verkkovaali", "sub_path": "WebIdentity/webidentity/tests/test_pages.py", "file_name": "test_pages.py", "file_ext": "py", "file_size_in_byte": 673, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "27", "api": [{"api_name": "unittest.TestCase", "line_number": 5, "usage_type": "attribute"}, {"api_name": "pyramid.testing.setUp", "line_number": 8, "usage_type": "call"}, {"api_name": "pyramid.testing", "line_number": 8, "usage_type": "name"}, {"api_name": "pyramid.testing.tearDown", "line_number": 11, "usage_type": "call"}, {"api_name": "pyramid.testing", "line_number": 11, "usage_type": "name"}, {"api_name": "pyramid.testing.DummyRequest", "line_number": 18, "usage_type": "call"}, {"api_name": "pyramid.testing", "line_number": 18, "usage_type": "name"}, {"api_name": "webidentity.views.pages.front_page", "line_number": 20, "usage_type": "call"}]} +{"seq_id": "21955312317", "text": "#!/usr/bin/env python\nfrom dipy.workflows.reconst import ReconstMAPMRIFlow\nimport json\nimport os.path\n\nwith open('config.json') as config_json:\n\tconfig = json.load(config_json)\n\n\t# Paths to data\n\tdata_file = str(config['dwi'])\n\tdata_bval = str(config['bvals'])\n\tdata_bvec = str(config['bvecs'])\n\tlap = bool(config['lap'])\n\tpos = bool(config['pos'])\n\tlap_weighting = float(config['laplacian_weighting'])\n\n\tpath = os.getcwd()\n\tmmri_flow = ReconstMAPMRIFlow()\n\tsave_metrics = ['rtop', 'msd', 'qiv', 'rtap', 'rtpp', 'ng', 'perng', 'parng']\n\tmmri_flow.run(data_file=data_file, data_bval=data_bval, data_bvec=data_bvec,\n\t\t out_dir=path, laplacian=lap, positivity=pos, save_metrics=save_metrics,\n\t\t lap_weighting=lap_weighting)\n\n", "repo_name": "brainlife/app-dipy-MAPMRI", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 724, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "json.load", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path.getcwd", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "name"}, {"api_name": "dipy.workflows.reconst.ReconstMAPMRIFlow", "line_number": 18, "usage_type": "call"}]} +{"seq_id": "6252240945", "text": "from django.urls import path\n\nfrom . import views\n\napp_name = 'cart'\n\nurlpatterns = [\n path('', views.view_cart, name='view_cart'),\n path('addcart/', views.add_cart, name='add_cart'),\n path('removecart/', views.remove_cart, name='remove_cart'),\n]\n", "repo_name": "Evert-R/milestone-four", "sub_path": "cart/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 264, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}]} +{"seq_id": "22178996818", "text": "import numpy as np\nimport cv2\nimport cvbase as cvb\nimport os\nimport pycocotools.mask as maskUtils\nfrom utils import *\nimport PIL.Image as pil\nfrom PIL import Image, ImageFile\nimport time\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\ndef savelabel(producedinstancelabel, figname, outputroot, cam):\n date = figname[0:10]\n seq = \"{}_sync\".format(figname[0:21])\n ind = figname.split('_')[-1].zfill(10)\n os.makedirs(os.path.join(outputroot, date, seq, cam), exist_ok=True)\n producedinstancelabel.save(os.path.join(outputroot, date, seq, cam, \"{}.png\".format(ind)))\n\ninstanceroot = '/home/shengjie/Documents/Data/organized_kins'\ndstroot = '/home/shengjie/Documents/Data/organized_kins/from_all'\nsplitroot = '/home/shengjie/Documents/Project_SemanticDepth/splits/eigen_full'\nsplitentry = ['test', 'train', 'val']\nlookuporder = ['from_semantics', 'from_kins', 'from_tracking', 'from_semankitti']\ndirmapping = {'l':'image_02', 'r':'image_03'}\n\ntotnum = 0\nfor split in splitentry:\n entries = readlines(os.path.join(splitroot, \"{}_files.txt\".format(split)))\n totnum = totnum + len(entries)\n\nst = time.time()\n\ncount = 0\nfor split in splitentry:\n entries = readlines(os.path.join(splitroot, \"{}_files.txt\".format(split)))\n for entry in entries:\n seq, index, direction = entry.split(' ')\n labelpath = os.path.join(seq, dirmapping[direction], \"{}.png\".format(index.zfill(10)))\n for source in lookuporder:\n curlabelpath = os.path.join(instanceroot, source, labelpath)\n if os.path.exists(curlabelpath):\n savelabel(pil.open(curlabelpath), \"{}_{}\".format(seq.split('/')[1], index), dstroot, dirmapping[direction])\n break\n count = count + 1\n dr = time.time() - st\n leftime = (totnum - count) * (dr / count) / 60 / 60\n print(\"Finished: %d, remains hours: %f\" % (count, leftime))\n\n\n", "repo_name": "TWJianNuo/DepIns", "sub_path": "Exp_PreSIL/develop/build_integratedInstanceDataset.py", "file_name": "build_integratedInstanceDataset.py", "file_ext": "py", "file_size_in_byte": 1882, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "PIL.ImageFile.LOAD_TRUNCATED_IMAGES", "line_number": 10, "usage_type": "attribute"}, {"api_name": "PIL.ImageFile", "line_number": 10, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path", "line_number": 38, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 42, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 42, "usage_type": "name"}, {"api_name": "time.time", "line_number": 45, "usage_type": "call"}]} +{"seq_id": "72739738953", "text": "import json\n\nfrom qwikidata.linked_data_interface import get_entity_dict_from_api\n\nfor i in range(1501, 1721):\n\n\twith open('../Data/FinalData/FinalData_15000_Final/Cool' + str(i) + '.json', 'r') as fin:\n\n\t\tfor line in fin:\n\n\t\t\ttemplate_data = json.loads(line)\n\n\tfor k, v in template_data.items():\n\n\t\ttry:\n\n\t\t\tif 'बच्चों की संख्या' in v.keys():\n\n\t\t\t\tprint(\"FINALLY\")\n\n\t\t\t\tx = get_entity_dict_from_api(v['QID'])\n\n\t\t\t\ty = x['claims']['P1971'][0]['mainsnak']['datavalue']['value']\n\n\t\t\t\tv.update({'बच्चों की संख्या' : y})\n\n\t\texcept:\n\n\t\t\tprint(i)\n\n\t\t\tprint(k, v)\n\n\twith open('../Data/FinalData/FinalData_15000_Final/Cool' + str(i) + '.json', 'w') as fout:\n\n\t\tjson.dump(template_data, fout)", "repo_name": "aditya3498/Automatic_Hindi_Wikipedia_Generation", "sub_path": "Source/Error_Resolve_Number_of_Children.py", "file_name": "Error_Resolve_Number_of_Children.py", "file_ext": "py", "file_size_in_byte": 739, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "json.loads", "line_number": 11, "usage_type": "call"}, {"api_name": "qwikidata.linked_data_interface.get_entity_dict_from_api", "line_number": 21, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 35, "usage_type": "call"}]} +{"seq_id": "8126781140", "text": "from django import forms\nimport re\n\nfrom .models import Customer\n\n\n# classe para criar campo de dada no form de inserção\nclass DateInput(forms.DateInput):\n input_type = \"date\"\n\n\nclass CustomerForm(forms.ModelForm):\n first_name = forms.CharField(\n label=\"Nome\",\n error_messages={\"max_length\": \"Nome não pode conter mais de 30 caracteres\"}\n )\n last_name = forms.CharField(\n label=\"Sobrenome\",\n error_messages={\"max_length\": \"Sobrenome não pode conter mais de 30 caracteres\"}\n )\n email = forms.EmailField(label=\"Email\")\n birth_date = forms.CharField(label=\"Data de nascimento\", widget=DateInput())\n area_code = forms.RegexField( # regex serve para criar máscaras para os campos\n label=\"DDD\",\n regex=r\"^\\d{2}$\", #r para iniciar o regex, ^\\inicio de significa numeros entre [0-9] {2} numero de digitos $fim do regex\n error_messages={\"invalid\": \"Número de DDD inválido!\"}\n )\n phone_number = forms.RegexField(\n label=\"Telefone\",\n regex=r\"^\\+?1?[0-9]{9,15}$\",#outra forma de fazer +?1? recebe 1 string caracteres entre 0 e 9 valor total entre 9 e 15 caracteres\n error_messages = {\"invalid\": \"Número de telefone inválido!\"}\n )\n country = forms.CharField(label=\"País\")\n state = forms.CharField(label=\"State\")\n city = forms.CharField(label=\"Cidade\")\n\n class Meta:\n model = Customer\n fields = (\n \"first_name\",\n \"last_name\",\n \"email\",\n \"birth_date\",\n \"area_code\",\n \"phone_number\",\n \"country\",\n \"state\",\n \"city\"\n )\n", "repo_name": "JianGoersch/crm", "sub_path": "customer/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 1641, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "django.forms.DateInput", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 8, "usage_type": "name"}, {"api_name": "django.forms.ModelForm", "line_number": 12, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 12, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 13, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 13, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 17, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 17, "usage_type": "name"}, {"api_name": "django.forms.EmailField", "line_number": 21, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 21, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 22, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 22, "usage_type": "name"}, {"api_name": "django.forms.RegexField", "line_number": 23, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 23, "usage_type": "name"}, {"api_name": "django.forms.RegexField", "line_number": 28, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 28, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 33, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 33, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 34, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 34, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 35, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 35, "usage_type": "name"}, {"api_name": "models.Customer", "line_number": 38, "usage_type": "name"}]} +{"seq_id": "37203096148", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 7 14:36:55 2022\n\n@author: ZR\n\"\"\"\nimport pandas as pd\nfrom tqdm import tqdm\n\n\ndef Get_Frame_Response(series,cell_tuning_dic,thres = 2,clip = 5,OD_thres = 0.5):\n '''\n This function will calculate OD,Orientation response in all series.\n\n Parameters\n ----------\n series : (pd Frame)\n Pre-processed series train, can be generated by Preprocessor\n cell_tuning_dic : (Dic)\n Cell Tuning Dic, also generated by caiman process.\n thres : (int), optional\n Thres hold to define spike. The default is 2.\n clip : (int), optional\n Clip up extrem high value. The default is 5.\n OD_thres : (float), optional\n Threshold to determine an OD response. The default is 5.\n \n\n Returns\n -------\n frame_response : (pd Frame)\n Pandas frame of Single-Frame response.\n\n '''\n # clip firing frame, get response here.\n firing_data = series[series>thres].fillna(0).clip(upper = clip)\n # get tuning\n actune = pd.DataFrame(columns = ['OD','Orien'])\n acn = firing_data.index\n for i,cc in enumerate(acn):\n tc = cell_tuning_dic[cc]\n if tc['Fitted_Orien'] != 'No_Tuning':\n actune.loc[cc] = [tc['OD']['Tuning_Index'],tc['Fitted_Orien']]\n actune['Orien_Group'] = (((actune['Orien']+22.5)%180)//45)*45 # Given Orien+-22.5\n all_frame_name = firing_data.columns\n all_cell_name_t = actune.index\n all_cell_Num = len(all_cell_name_t)\n LE_cell_Num = (actune['OD']>OD_thres).sum()\n RE_cell_Num = (actune['OD']<-OD_thres).sum()\n Orien0_cell_Num = (actune['Orien_Group']==0).sum()\n Orien45_cell_Num = (actune['Orien_Group']==45).sum()\n Orien90_cell_Num = (actune['Orien_Group']==90).sum()\n Orien135_cell_Num = (actune['Orien_Group']==135).sum()\n tuned_data = firing_data.loc[all_cell_name_t]\n # generate frame response\n spike_info_column = ['All_Num','All_spike','All_prop','LE_Num','LE_spike','LE_prop','RE_Num','RE_spike','RE_prop','Orien0_Num','Orien0_spike','Orien0_prop','Orien45_Num','Orien45_spike','Orien45_prop','Orien90_Num','Orien90_spike','Orien90_prop','Orien135_Num','Orien135_spike','Orien135_prop']\n frame_response = pd.DataFrame(0,columns = spike_info_column,index = all_frame_name)\n for c_frame_name in tqdm(all_frame_name):\n c_frame = tuned_data[c_frame_name]\n firing_cells = c_frame[c_frame>0]\n frame_response.loc[c_frame_name,'All_Num'] = len(firing_cells)\n frame_response.loc[c_frame_name,'All_spike'] = firing_cells.sum()\n fire_cell_names = list(firing_cells.index)\n # then cycle cells to count tuning response.\n for cc in fire_cell_names:\n c_tune = actune.loc[cc,:]\n if c_tune['OD']>OD_thres: # LE cell\n frame_response.loc[c_frame_name,'LE_Num'] +=1\n frame_response.loc[c_frame_name,'LE_spike'] += firing_cells[cc]\n elif c_tune['OD']<-OD_thres: # RE cell\n frame_response.loc[c_frame_name,'RE_Num'] +=1\n frame_response.loc[c_frame_name,'RE_spike'] += firing_cells[cc]\n # orien counter\n if c_tune['Orien_Group'] == 0 : # Orien 0 cell\n frame_response.loc[c_frame_name,'Orien0_Num'] +=1\n frame_response.loc[c_frame_name,'Orien0_spike'] += firing_cells[cc]\n elif c_tune['Orien_Group'] == 45 : # Orien 45 cell\n frame_response.loc[c_frame_name,'Orien45_Num'] +=1\n frame_response.loc[c_frame_name,'Orien45_spike'] += firing_cells[cc]\n elif c_tune['Orien_Group'] == 90 : # Orien 90 cell\n frame_response.loc[c_frame_name,'Orien90_Num'] +=1\n frame_response.loc[c_frame_name,'Orien90_spike'] += firing_cells[cc]\n elif c_tune['Orien_Group'] == 135 : # Orien 135 cell\n frame_response.loc[c_frame_name,'Orien135_Num'] +=1\n frame_response.loc[c_frame_name,'Orien135_spike'] += firing_cells[cc]\n # at last, calculate response propotion\n frame_response['All_prop'] = frame_response['All_spike']/all_cell_Num\n frame_response['LE_prop'] = frame_response['LE_spike']/LE_cell_Num\n frame_response['RE_prop'] = frame_response['RE_spike']/RE_cell_Num\n frame_response['Orien0_prop'] = frame_response['Orien0_spike']/Orien0_cell_Num\n frame_response['Orien45_prop'] = frame_response['Orien45_spike']/Orien45_cell_Num\n frame_response['Orien90_prop'] = frame_response['Orien90_spike']/Orien90_cell_Num\n frame_response['Orien135_prop'] = frame_response['Orien135_spike']/Orien135_cell_Num\n #define cell_num_dic\n cell_num_dic = {}\n cell_num_dic['LE'] = LE_cell_Num\n cell_num_dic['RE'] = RE_cell_Num\n cell_num_dic['Orien0'] = Orien0_cell_Num\n cell_num_dic['Orien45'] = Orien45_cell_Num\n cell_num_dic['Orien90'] = Orien90_cell_Num\n cell_num_dic['Orien135'] = Orien135_cell_Num\n \n \n return frame_response,cell_num_dic,actune", "repo_name": "adolescent/2P_Analysis", "sub_path": "My_Wheels/Series_Analyzer/Response_Info.py", "file_name": "Response_Info.py", "file_ext": "py", "file_size_in_byte": 5027, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "27", "api": [{"api_name": "pandas.DataFrame", "line_number": 38, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 57, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 58, "usage_type": "call"}]} +{"seq_id": "11035633835", "text": "#!/usr/bin/env python3\n\nfrom itertools import chain\nimport logging\nimport sys\nfrom architecture.scheduler import ACTIVE_NAME\nfrom architecture.tok_ring import HAS_TOK_NAME\nfrom interfaces.parser_expr import Signal, Bool, BinOp, UnaryOp, ForallExpr, Number, QuantifiedSignal\nfrom spec_optimizer.optimizations import _instantiate_expr2\nfrom parsing.helpers import Visitor\nfrom parsing.par_lexer_desc import PAR_GUARANTEES, PAR_ASSUMPTIONS\nfrom parsing.par_parser import parse_ltl\n\n\nclass ConverterToWringVisitor(Visitor):\n def visit_number(self, number:Number):\n return str(number)\n\n def visit_forall(self, node:ForallExpr):\n # assert 0\n return self.dispatch(node.arg2)\n\n def visit_unary_op(self, unary_op:UnaryOp):\n arg = self.dispatch(unary_op.arg)\n\n return '({op}({arg}))'.format(op=unary_op.name, arg=arg)\n\n def visit_binary_op(self, binary_op:BinOp):\n arg1, arg2 = self.dispatch(binary_op.arg1), self.dispatch(binary_op.arg2)\n\n if binary_op.name == '=':\n #don't add spaces around '=' -- Acacia cannot recognize this\n return '({arg1}{op}{arg2})'.format(arg1=arg1, arg2=arg2, op=binary_op.name)\n else:\n return '({arg1} {op} {arg2})'.format(arg1=arg1, arg2=arg2, op=binary_op.name)\n\n def visit_tuple(self, node:tuple):\n assert 0\n\n def visit_bool(self, bool_const:Bool):\n return str(bool_const).upper()\n\n def visit_signal(self, signal:Signal):\n # assert signal.name != ACTIVE_NAME, 'not supported:' + str(signal.name)\n # assert signal.name != HAS_TOK_NAME, 'not supported:' + str(signal.name)\n\n return str(signal)\n\n\ndef _instantiate(spec_text):\n section_by_name = parse_ltl(spec_text, logging.getLogger())\n input_signals = [QuantifiedSignal('r', i) for i in range(nof_processes)]\n output_signals = [QuantifiedSignal('g', i) for i in range(nof_processes)]\n\n assumptions = section_by_name[PAR_ASSUMPTIONS]\n guarantees = section_by_name[PAR_GUARANTEES]\n\n inst_assumptions = list(chain(*[_instantiate_expr2(a, nof_processes, False)\n for a in assumptions]))\n\n inst_guarantees = list(chain(*[_instantiate_expr2(g, nof_processes, False)\n for g in guarantees]))\n\n assumptions_as_strings = [ConverterToWringVisitor().dispatch(a) + ';\\n'\n for a in inst_assumptions]\n guarantees_as_strings = [ConverterToWringVisitor().dispatch(g) + ';\\n'\n for g in inst_guarantees]\n\n return input_signals, output_signals, assumptions_as_strings, guarantees_as_strings\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 4:\n print('Provide and ')\n exit(0)\n\n spec = open(sys.argv[1]).read()\n nof_processes = int(sys.argv[2])\n out_file_prefix = sys.argv[3]\n\n assert nof_processes > 1, 'should be at least two processes: ' + str(nof_processes)\n\n input_signals, output_signals, assumptions, guarantees = _instantiate(spec)\n\n with open(out_file_prefix + str(nof_processes) + '.ltl', 'w') as ltl_file:\n ltl_file.writelines(['assume ' + a for a in assumptions])\n ltl_file.writelines(guarantees)\n\n with open(out_file_prefix + str(nof_processes) + '.part', 'w') as part_file:\n part_file.writelines(['.inputs ' + ' '.join(map(str, input_signals)) + '\\n',\n '.outputs ' + ' '.join(map(str, output_signals)) + '\\n'])\n", "repo_name": "5nizza/Party", "sub_path": "src/helpers/parameterized2monolithic.py", "file_name": "parameterized2monolithic.py", "file_ext": "py", "file_size_in_byte": 3529, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "parsing.helpers.Visitor", "line_number": 15, "usage_type": "name"}, {"api_name": "interfaces.parser_expr.Number", "line_number": 16, "usage_type": "name"}, {"api_name": "interfaces.parser_expr.ForallExpr", "line_number": 19, "usage_type": "name"}, {"api_name": "interfaces.parser_expr.UnaryOp", "line_number": 23, "usage_type": "name"}, {"api_name": "interfaces.parser_expr.BinOp", "line_number": 28, "usage_type": "name"}, {"api_name": "interfaces.parser_expr.Bool", "line_number": 40, "usage_type": "name"}, {"api_name": "interfaces.parser_expr.Signal", "line_number": 43, "usage_type": "name"}, {"api_name": "parsing.par_parser.parse_ltl", "line_number": 51, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 51, "usage_type": "call"}, {"api_name": "interfaces.parser_expr.QuantifiedSignal", "line_number": 52, "usage_type": "call"}, {"api_name": "interfaces.parser_expr.QuantifiedSignal", "line_number": 53, "usage_type": "call"}, {"api_name": "parsing.par_lexer_desc.PAR_ASSUMPTIONS", "line_number": 55, "usage_type": "name"}, {"api_name": "parsing.par_lexer_desc.PAR_GUARANTEES", "line_number": 56, "usage_type": "name"}, {"api_name": "itertools.chain", "line_number": 58, "usage_type": "call"}, {"api_name": "spec_optimizer.optimizations._instantiate_expr2", "line_number": 58, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 61, "usage_type": "call"}, {"api_name": "spec_optimizer.optimizations._instantiate_expr2", "line_number": 61, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 73, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 77, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 78, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 79, "usage_type": "attribute"}]} +{"seq_id": "19169489296", "text": "#!/usr/bin/env python3\n\n'''\nThis script aims to create a text file with a line per gnina command that needs to be run.\n\nNOTE if an option(s) is selected, the script will write a command for that option while keeping the others as gnina's defaults!\n\nIE if you specify --exhaustiveness 1 2 3 AND --cnn_rotations 1 2 3 you will get 6 jobs (not 9)!\n\nInput:\n infile -- a space-delimited file containing: \n cnn -- defaults to gnina default. Must be in [crossdock_default2018, crossdock_default2018_<1-4>, \n default2017, dense, dense_<1-4>, \n general_default2018, general_default2018_<1-4>]. *if multiple args are given, it is an ensemble\n cnn_scoring -- defaults to rescore. Must be in [none, rescore, refinement, all].\n exhaustiveness -- number(s)\n rmsd_filter -- number(s)\n cnn_rotations -- number(s)\n num_modes -- number(s)\n autobox_add -- number(s)\n num_mc_saved -- number(s)\n cnn_empirical_weight -- number(s)\n --gpu : this will turn on gpu acceleration for the command.\n\nThe name of the output file for the gnina command will be the name of the outfile_prefix+\"option\"+.sdf\n\nOutput:\n a text file with a command per line.\n'''\n\nimport argparse, os, re\n\ndef make_out_name(cnns): # make sure names of output sdf is consistent for single models and ensembles\n # Ensembles will be named _\n ensemble_models = ['crossdock_default2018', 'dense', 'general_default2018', 'redock_default2018']\n cnn_string = '+'.join(cnns)\n out_strings = []\n for m in ensemble_models:\n search_string = f'(?<={m}_)(\\d)'\n matches = ''.join(sorted(re.findall(search_string, cnn_string)))\n first_ss = f'(?<={m})(\\+|$)'\n if len(re.findall(first_ss, cnn_string)):\n matches = '0' + matches\n if len(matches):\n out_strings.append(f'{m}_{matches}')\n if 'default2017' in cnn_string: \n out_strings.append('default2017')\n\n return f'{\"_\".join(out_strings)}'\n\nparser=argparse.ArgumentParser(description='Create a text file containing all the gnina commands you specify to run.')\nparser.add_argument('-i','--input',required=True,help='Space-delimited file containing: .')\nparser.add_argument('-o','--output',default='gnina_cmds.txt',help='Name of the output file containing the commands to run. Defaults to \"gnina_cmds.txt\"')\nparser.add_argument('--cnn',nargs='+',help=\"Specify built-in CNN model for gnina. Defaults to unspecified cnn, which uses the default cnn model of gnina. If multiple models are specified, an ensemble will be evaluated.(ensembles can also be specified through the same notation as Gnina, i.e. '_ensemble' to specify the ensemble of \")\nparser.add_argument('--cnn_scoring',default='rescore',help='Specify what method of CNN scoring. Must be [none, rescore,refinement,all]. Defaults to rescore')\nparser.add_argument('--exhaustiveness',default=None,nargs='+',help='exhaustiveness arguments for gnina. Accepts any number of arguments.')\nparser.add_argument('--min_rmsd_filter',default=None,nargs='+',help='Filters for min_rmsd_filter for gnina. Accepts any number of arguments.')\nparser.add_argument('--cnn_rotation',default=None,nargs='+',help='Options for cnn_rotation for gnina. Accepts any number of arguments. All must be [0,24].')\nparser.add_argument('--num_modes',default=None,nargs='+',help='Options for num_modes for gnina. Accepts any number of arguments.')\nparser.add_argument('--autobox_add',default=None,nargs='+',help='Options for autobox_add for gnina. Accepts any number of arguments.')\nparser.add_argument('--num_mc_saved',default=None,nargs='+',help='Options for num_mc_saved for gnina. Accepts any number of arguments.')\nparser.add_argument('--cnn_empirical_weight',default=None, nargs='+',help='Option for merging CNN with empirical forces and energies during docking. Accepts any number of arguments.')\nparser.add_argument('--nogpu',action='store_true',help='Flag to turn OFF gpu acceleration for gnina.')\nparser.add_argument('--seed',default=420,type=int,help='Seed for Gnina (default: %(default)d)')\nargs=parser.parse_args()\n\n#Checking that the input arguments make sense\nif args.cnn_rotation:\n for rot in args.cnn_rotation:\n assert (0<=int(rot) and int(rot)<=24),\"cnn_rotations need to be in [0,24]!\"\n\nassert (args.cnn_scoring in ['none', 'rescore', 'refinement', 'all']),\"cnn_scoring must be one of none,rescore,refinement,all!\"\npossible=[\n'crossdock_default2018', 'crossdock_default2018_1', 'crossdock_default2018_2',\n'crossdock_default2018_3', 'crossdock_default2018_4', 'default2017',\n'dense', 'dense_1', 'dense_2', 'dense_3', 'dense_4', 'general_default2018',\n'general_default2018_1', 'general_default2018_2', 'general_default2018_3',\n'general_default2018_4', 'redock_default2018', 'redock_default2018_1',\n'redock_default2018_2', 'redock_default2018_3', 'redock_default2018_4'\n]\nif args.cnn is not None:\n if '_ensemble' in '_'.join(args.cnn): # See if '_ensemble' in any of the arguments\n new_args_cnn = set() # Using set so don't have two of the same model in the ensemble\n for model in args.cnn:\n if 'ensemble' not in model:\n new_args_cnn.add(model)\n else:\n assert model[:-len('_ensemble')] in possible+[''], \"Must be ensemble of built in model(s)\" # can also be ensemble of all models which would be '_ensemble' so '' is a valid model\n base_cnn = model[:-len('_ensemble')]\n ensemble = [cnn_model for cnn_model in possible if base_cnn in cnn_model]\n new_args_cnn.update(ensemble)\n args.cnn = sorted(list(new_args_cnn))\n\n for cnn in args.cnn:\n assert(cnn in possible), \"Specified cnn not built into gnina!\"\n\n# Specifying arguments to skip over\nskip = set(['input', 'output', 'cnn', 'cnn_scoring', 'nogpu', 'seed'])\n\n# Gathering the receptor, ligand, and autobox_ligand arguments from input\ntodock = [] # list of tuples (recfile,ligfile,autobox_ligand,outf_prefix)\nwith open(args.input) as infile:\n for line in infile:\n rec, lig, box, outf_prefix = line.rstrip().split()\n todock.append((rec, lig, box, outf_prefix))\n\n# main part of the program\n# step1 -- check if we just want all defaults\nonly_defaults = True\nfor arg in vars(args):\n if arg not in skip:\n if getattr(args, arg):\n only_defaults = False\n\nwith open(args.output, 'w') as outfile:\n # TEMP WORKAROUND -- if only specified defaults E.G. passed no arguments into the script we still want to dock\n if only_defaults:\n print('default arguments')\n for r, l, box, out_prefix in todock:\n sent = f'gnina -r {r} -l {l} --autobox_ligand {box} --cnn_scoring {args.cnn_scoring} --cpu 1 --seed {args.seed}'\n if args.cnn is None:\n dock_out = out_prefix + 'default_ensemble_' + args.cnn_scoring+'_defaults.sdf.gz'\n elif len(args.cnn) == len(possible):\n dock_out = out_prefix+'all_ensemble_'+args.cnn_scoring+'_defaults.sdf.gz'\n else:\n cnn_out_string = make_out_name(args.cnn)\n dock_out = out_prefix+cnn_out_string+'_'+args.cnn_scoring+'_defaults.sdf.gz'\n if args.cnn is None:\n sent += f' --out {dock_out}'\n else:\n sent += f' --cnn {\" \".join(args.cnn)} --out {dock_out}'\n\n if args.nogpu:\n sent += ' --no_gpu'\n outfile.write(sent+'\\n')\n else:\n for arg in vars(args):\n if arg not in skip:\n print(arg)\n if getattr(args, arg):\n for val in getattr(args, arg):\n print(val)\n for r, l, box, out_prefix in todock:\n sent = f'gnina -r {r} -l {l} --autobox_ligand {box} --cnn_scoring {args.cnn_scoring} --cpu 1 --seed {args.seed}'\n if args.cnn is None:\n dock_out = out_prefix + 'default_ensemble_' + args.cnn_scoring + '_' + arg + val + '.sdf.gz'\n elif len(args.cnn) == len(possible):\n dock_out = out_prefix+'all_ensemble_'+args.cnn_scoring+'_'+ arg + val +'.sdf.gz'\n else:\n cnn_out_string = make_out_name(args.cnn)\n dock_out = out_prefix+cnn_out_string+'_'+args.cnn_scoring+ '_' + arg + val +'.sdf.gz'\n\n if args.cnn is None:\n sent += f' --out {dock_out}'\n else:\n sent += f' --cnn {\" \".join(args.cnn)} --out {dock_out}'\n\n # adding in the stuff for the specified argument\n sent += f' --{arg} {val}'\n\n #if the cnn_empirical_weight is selected, adding the other necessary gnina flags.\n if arg == 'cnn_empirical_weight':\n sent+=' --cnn_mix_emp_force --cnn_mix_emp_energy'\n\n if args.nogpu:\n sent += ' --no_gpu'\n outfile.write(sent+'\\n')\n", "repo_name": "dkoes/GNINA-1.0", "sub_path": "analysis_scripts/make_gnina_cmds.py", "file_name": "make_gnina_cmds.py", "file_ext": "py", "file_size_in_byte": 9680, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "27", "api": [{"api_name": "re.findall", "line_number": 40, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 42, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 51, "usage_type": "call"}]} +{"seq_id": "38730485964", "text": "from selenium import webdriver\nimport pickle\nfrom selenium.common.exceptions import NoSuchElementException\nimport os\nimport re\nfrom bs_table_extractor import Extractor\nfrom datetime import date\nimport bs4 as bs\nimport pandas as pd\nimport smtplib, ssl\nimport time\nfrom email_service import send_email\n\nma_download_dir = \"/Users/harsh/Desktop/coding/urap-scrape/ma_downloads/\"\n# Initialising the location for the chromedriver\nchrome_options = webdriver.ChromeOptions()\nprefs = {\"download.default_directory\": ma_download_dir}\nchrome_options.add_experimental_option(\"prefs\", prefs)\ndriver = webdriver.Chrome(executable_path='/Users/harsh/Downloads/chromedriver', chrome_options=chrome_options)\n\nglobal company_name, offer_detail, rate_detail, offer_type, green_offer_details, history_pricing\n\n\ndef get_zipcodes(state):\n zipcodes_list_dict = zipcodes.filter_by(state=state)\n return [int(x['zip_code']) for x in zipcodes_list_dict]\n\n\ndef today_date():\n \"\"\"\n Return the current date in the format Date (MM/DD/YY)\n :return:\n \"\"\"\n return date.today().strftime(\"%m/%d/%y\")\n\n\ndef sleep_one():\n \"\"\"\n Calls the time.sleep function for 1 second. The program run time pauses for 1 sec\n :return: None\n \"\"\"\n time.sleep(1)\n\n\ndef extract_table(inner_html):\n \"\"\"\n This function uses the bs_table_extractor library and uses that to extract the table from the pop up.\n :param inner_html: inner HTML code for the popup\n :return: table_extracted of type list of lists\n \"\"\"\n try:\n soup = bs.BeautifulSoup(inner_html, 'html.parser')\n table = soup.find('table')\n extractor = Extractor(table)\n table_extracted = extractor.parse().return_list()\n return table_extracted\n except Exception as e:\n pass\n\n\ndef scrape_website(source_url, zipcode):\n \"\"\"\n This is the main function, head for the scraping module that we will write for the New York\n website scrape\n :return:\n \"\"\"\n # Below part accepts the agreement popup using just the clicks\n global company_name, offer_detail, rate_detail, offer_type, history_pricing, green_offer_details\n driver.get(source_url)\n try:\n time.sleep(1)\n driver.find_element_by_xpath('//*[@id=\"acceptOverlay\"]').click()\n sleep_one()\n driver.find_element_by_xpath('//*[@id=\"scrollDown\"]').click()\n sleep_one()\n driver.find_element_by_xpath('//*[@id=\"acceptOverlay\"]').click()\n except NoSuchElementException:\n pass\n\n # Now we click the view electric popup, fuck these popups I swear\n sleep_one()\n driver.find_element_by_xpath(\n '/html/body/app-root/offer-search-component/div[2]/offer-summary-popup/div/div/div[2]/div[1]/button').click()\n\n # Main table data scrape now\n full_data = []\n for x in range(2, 1500):\n \"Here we can put this to an arbitrary large number just for the sake of the loop\"\n try:\n element_xpath = f\"/html/body/app-root/offer-search-component/div[2]/div[4]/main/div/div/div[{x}]\"\n element = driver.find_element_by_xpath(element_xpath)\n element_id = element\n divs = element.find_elements_by_tag_name('div')\n offer_id = element.get_attribute('id')\n\n for div in element.find_elements_by_tag_name('div'):\n # print(div.get_attribute('class'))\n div_class_name = div.get_attribute('class')\n if 'company-name-col' in div_class_name:\n company_name = div.text.strip().replace('\\n', '')\n elif 'offer-detail-col' in div_class_name:\n offer_detail = div.text\n try:\n min_term = re.search('Min Term:(.*)', offer_detail).group(1)\n min_term = min_term.strip('\\n')\n except Exception as e:\n min_term = offer_detail\n elif 'rateColumn' in div_class_name:\n rate_detail = div.text\n try:\n rate_per_kwh = re.search('\\\\n(.*)\\\\n', rate_detail).group(1)\n rate_per_kwh = float(rate_per_kwh.replace('$', '').replace('per kWh', '').strip())\n except Exception as e:\n rate_per_kwh = rate_detail\n try:\n rate_per_month = float(re.search('\\\\n(.*)per month', rate_detail).group(1).replace('$', '')\n .strip())\n units_per_month = rate_per_month / rate_per_kwh\n units_per_month = round(units_per_month, 2)\n except Exception as num_months_extraction_err:\n units_per_month = 700\n\n elif 'offer-type-col' in div_class_name:\n offer_type = div.text\n elif 'green-offer-col' in div_class_name:\n green_offer_details = div.text\n elif 'historic-pricing' in div_class_name:\n history_pricing = div.text\n\n print(offer_id)\n if offer_id != \"\":\n\n view_details_element = driver.find_element_by_xpath(f'//*[@id=\"{offer_id}\"]/div[4]/span[1]/a')\n view_details_element.click()\n # sleeping for 2 seconds to make sure the table opens\n time.sleep(0.7)\n # getting the element of the popup to be sent to the extract_table function\n popup = driver.find_element_by_xpath('//*[@id=\"detailContent\"]')\n # table_data is a list of list from the extracted table from the popup\n table_data = extract_table(inner_html=popup.get_attribute('innerHTML'))\n table_data_dict = {x[0]: str(x[1]).strip().replace('\\n', '') for x in table_data}\n # Extracting cancellation fee and the EDP Compliant\n cancellation_fee = table_data_dict['Cancellation Fee']\n guaranteed_savings = table_data_dict['Guaranteed Saving']\n edp_compliant = table_data_dict['EDP Compliant']\n\n # closing the popup, here we use offer-table\n popup.find_element_by_class_name('close-button').click()\n\n data_row = [company_name, min_term, rate_per_kwh, units_per_month, guaranteed_savings, offer_type,\n green_offer_details, history_pricing, today_date(), source_url, \"New York\", zipcode,\n \"Default Fixed Only NO\", cancellation_fee, edp_compliant]\n if rate_detail is not '':\n print(data_row)\n full_data.append(data_row)\n # This is to catch if there is no element present, so it breaks out of the loop and just exits\n except NoSuchElementException or Exception as e:\n print(\"ERROR\\n\", e)\n if '\"method\":\"xpath\",\"selector\":\"/html/body/app-root/offer-search' in str(e) and f'div[{x}]' in str(e):\n break\n pass\n\n # else:\n # # send_email(body=error_message)\n # break\n\n df = pd.DataFrame.from_records(full_data)\n df.to_csv('data.csv', index=False)\n\n\nif __name__ == '__main__':\n for zipcode in get_zipcodes('NY')[0:100]:\n source_url = f\"http://documents.dps.ny.gov/PTC/zipcode/{zipcode}\"\n scrape_website(source_url=source_url, zipcode=zipcode)\n", "repo_name": "theharshgupta/urap-scrape", "sub_path": "newyork/scrape.py", "file_name": "scrape.py", "file_ext": "py", "file_size_in_byte": 7427, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "2", "api": [{"api_name": "selenium.webdriver.ChromeOptions", "line_number": 16, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 16, "usage_type": "name"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 19, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 19, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 34, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 34, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 42, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 52, "usage_type": "call"}, {"api_name": "bs_table_extractor.Extractor", "line_number": 54, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 71, "usage_type": "call"}, {"api_name": "selenium.common.exceptions.NoSuchElementException", "line_number": 77, "usage_type": "name"}, {"api_name": "re.search", "line_number": 104, "usage_type": "call"}, {"api_name": "re.search", "line_number": 111, "usage_type": "call"}, {"api_name": "re.search", "line_number": 116, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 136, "usage_type": "call"}, {"api_name": "selenium.common.exceptions.NoSuchElementException", "line_number": 157, "usage_type": "name"}, {"api_name": "pandas.DataFrame.from_records", "line_number": 167, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 167, "usage_type": "attribute"}]} +{"seq_id": "19041254059", "text": "from datetime import date\nimport icalendar # $ pip install icalendar\n\nICS_PATH = \"files/\"\nwith open(ICS_PATH, 'r', encoding=('utf-8')) as f:\n\n today = date.today()\n calendar = icalendar.Calendar.from_ical(f.read())\n for event in calendar.walk('VEVENT'):\n if event.get('summary').startswith('EventSummaryName'):\n print(event.get('summary'))\n print(event.get('dtstart').dt)\n print(event.get('dtend').dt)\n print(event.get('dtend').dt-event.get('dtstart').dt)\n", "repo_name": "FAD95/ics_usage", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 516, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "datetime.date.today", "line_number": 7, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 7, "usage_type": "name"}, {"api_name": "icalendar.Calendar.from_ical", "line_number": 8, "usage_type": "call"}, {"api_name": "icalendar.Calendar", "line_number": 8, "usage_type": "attribute"}]} +{"seq_id": "24840918446", "text": "import praw\nimport datetime as dt\nimport random\nimport time\nfrom multiprocessing import Process\nimport datetime\nimport pickle\n\n## SET BACKEND\nimport matplotlib as mpl\nmpl.use('TkAgg')\n\nfrom matplotlib import pyplot as plt\nplt.style.use('seaborn-pastel')\nfrom collections import Counter\nimport seaborn as sns\n\n\ndef number_of_daily_comments():\n\n with open('obj/' + 'comment_info_dict' + '.pkl', 'rb') as f:\n comment_info_dict=pickle.load(f)\n dates=[]\n amt=[]\n upv=[]\n \n for k, v in comment_info_dict.items():\n dates.append(k)\n \n dates=sorted(dates)\n for date in dates:\n amt.append(comment_info_dict[date][\"no_of_comments\"])\n upv.append(comment_info_dict[date][\"upvotes\"])\n \n # import ipdb; ipdb.set_trace()\n\n dates=[date[5:] for date in dates]\n \n fig, ax1 = plt.subplots()\n ax1.plot(dates, amt, 'bo-', linewidth=2)\n ax1.set_xticklabels(dates, rotation = 45)\n ax1.tick_params(axis='y', labelcolor='b')\n ax1.set_ylabel('No. of Daily Comments', color='b')\n\n ax2 = ax1.twinx()\n\n ax2.plot(dates, upv, 'r^-.')\n ax2.set_ylabel('No. of Daily Upvotes', color='r')\n ax2.set_xticklabels(dates, rotation = 45)\n ax2.tick_params(axis='y', labelcolor='r')\n\n fig.tight_layout()\n # plt.annotate('Bot stopped without me knowing', xy=('01-28', 0), arrowprops=dict(facecolor='black', width=2, headlength=8, headwidth=8), xytext=(12, 50))\n # plt.annotate('Banned from: \\n r/Gaming, \\n r/LifeProTips, \\n r/KemonoFriends, \\n r/Rpdrcringe', xy=('01-21', comment_info_dict['2019-01-21'][\"upvotes\"]), arrowprops=dict(facecolor='black', width=2, headlength=8, headwidth=8), xytext=(0, 1500))\n plt.title('Breakdown by Comments')\n plt.show()\n\n\ndef main(reddit):\n \n dates=[]\n for comment in reddit.redditor('JustAnAlpacaBot').comments.top(limit=None):\n dates.append(datetime.datetime.utcfromtimestamp(comment.created_utc).strftime('%Y-%m-%d'))\n \n print(f\"Total Comments = {len(dates)}\")\n dates=list(set(dates))\n dates.extend(['2019-01-28', '2019-01-29', '2019-01-30', '2019-01-31'])\n dates=sorted(dates)\n print(f\"Total dates: {len(dates)}\")\n\n comment_info_dict={\n '2019-01-28':{\n \"no_of_comments\": 0,\n \"upvotes\": 0\n },\n '2019-01-29':{\n \"no_of_comments\": 0,\n \"upvotes\": 0\n },\n '2019-01-30':{\n \"no_of_comments\": 0,\n \"upvotes\": 0\n },\n '2019-01-31':{\n \"no_of_comments\": 0,\n \"upvotes\": 0\n }}\n\n subreddit=[]\n subreddit_upvotes={}\n upvote_sum=0\n for comment in reddit.redditor('JustAnAlpacaBot').comments.top(limit=None):\n date=datetime.datetime.utcfromtimestamp(comment.created_utc).strftime('%Y-%m-%d') \n \n if date in comment_info_dict:\n no_of_comments=comment_info_dict[date][\"no_of_comments\"]+1\n upvotes=comment_info_dict[date][\"upvotes\"]+comment.score\n subreddit_id=comment.subreddit.display_name\n subreddit.append(subreddit_id)\n\n comment_info_dict[date]={\n \"no_of_comments\": no_of_comments,\n \"upvotes\": upvotes\n }\n\n if subreddit_id in subreddit_upvotes:\n sr_upvotes=subreddit_upvotes[subreddit_id]+comment.score\n subreddit_upvotes[subreddit_id]=sr_upvotes\n upvote_sum=upvote_sum+comment.score\n else:\n subreddit_upvotes[subreddit_id]=comment.score\n upvote_sum=upvote_sum+comment.score\n\n else:\n no_of_comments=1\n upvotes=comment.score\n subreddit_id=comment.subreddit.display_name\n subreddit.append(subreddit_id)\n \n if subreddit_id in subreddit_upvotes:\n sr_upvotes=subreddit_upvotes[subreddit_id]+comment.score\n subreddit_upvotes[subreddit_id]=sr_upvotes\n else:\n subreddit_upvotes[subreddit_id]=comment.score\n upvote_sum=upvote_sum+comment.score\n\n comment_info_dict[date]={\n \"no_of_comments\": no_of_comments,\n \"upvotes\": upvotes\n }\n \n with open('obj/comment_info_dict.pkl', 'wb') as f:\n pickle.dump(comment_info_dict, f, pickle.HIGHEST_PROTOCOL)\n\n with open('obj/subreddit.pkl', 'wb') as f:\n pickle.dump(subreddit, f, pickle.HIGHEST_PROTOCOL)\n\n with open('obj/subreddit_upvotes.pkl', 'wb') as f:\n pickle.dump(subreddit_upvotes, f, pickle.HIGHEST_PROTOCOL)\n\n number_of_daily_comments(comment_info_dict)\n \n print(Counter(subreddit))\n print(comment_info_dict)\n print(subreddit_upvotes)\n print(f\"Sum = {upvote_sum}\")\n\ndef pie_upvotes():\n\n with open('obj/' + 'subreddit_upvotes' + '.pkl', 'rb') as f:\n subreddit_upvotes=pickle.load(f)\n \n import operator\n sorted_d = sorted(subreddit_upvotes.items(), key=operator.itemgetter(1), reverse=True)\n\n shown_sum=0\n total_sum=0\n\n labels=[]\n sizes=[]\n\n for i, val in enumerate(sorted_d):\n \n sr, up=val\n total_sum=total_sum+up\n if i<9:\n labels.append(f\"r/{sr}: {up} upvotes\")\n sizes.append(up)\n shown_sum=shown_sum+up\n \n labels.append(f'Others: {total_sum-shown_sum} upvotes')\n sizes.append(total_sum-shown_sum)\n\n fig1, ax1 = plt.subplots()\n ax1.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=45)\n #ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\n fig1.text(0.5, 0.05,f'Most Upvoted Subreddits \\n Total Upvotes: {total_sum}', ha='center')\n plt.title(f'Breakdown by Subreddits')\n plt.show()\n\ndef pie():\n\n with open('obj/' + 'subreddit' + '.pkl', 'rb') as f:\n subreddit=pickle.load(f)\n \n\n\n subreddit=dict(Counter(subreddit))\n import operator\n\n sorted_d = sorted(subreddit.items(), key=operator.itemgetter(1), reverse=True)\n\n shown_sum=0\n total_sum=0\n\n labels=[]\n sizes=[]\n\n for i, val in enumerate(sorted_d):\n \n sr, up=val\n total_sum=total_sum+up\n if i<9:\n labels.append(f\"r/{sr}: {up} comments\")\n sizes.append(up)\n shown_sum=shown_sum+up\n \n labels.append(f'Others: {total_sum-shown_sum} \\n comments')\n sizes.append(total_sum-shown_sum)\n\n fig1, ax1 = plt.subplots()\n ax1.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=120)\n #ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\n fig1.text(0.5, 0.05,f'Subreddits Most Commented on \\n Total Comments: {total_sum}', ha='center')\n # plt.title(f'Breakdown by Subreddits')\n plt.show()\n\nif __name__ == \"__main__\":\n reddit=praw.Reddit(client_id='my_client',\n client_secret='my_secret',\n user_agent='Alpaca stats by u/JustAnAlpacaBot',\n username='JustAnAlpacaBot',\n password='mypass')\n \n # number_of_daily_comments()\n pie()\n", "repo_name": "soham96/AlpacaBot", "sub_path": "alpaca_stats.py", "file_name": "alpaca_stats.py", "file_ext": "py", "file_size_in_byte": 7113, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 33, "dataset": "github-code", "pt": "2", "api": [{"api_name": "matplotlib.use", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style.use", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 14, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 14, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 56, "usage_type": "name"}, {"api_name": "datetime.datetime.utcfromtimestamp", "line_number": 63, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 63, "usage_type": "attribute"}, {"api_name": "datetime.datetime.utcfromtimestamp", "line_number": 93, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 93, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 133, "usage_type": "call"}, {"api_name": "pickle.HIGHEST_PROTOCOL", "line_number": 133, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 136, "usage_type": "call"}, {"api_name": "pickle.HIGHEST_PROTOCOL", "line_number": 136, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 139, "usage_type": "call"}, {"api_name": "pickle.HIGHEST_PROTOCOL", "line_number": 139, "usage_type": "attribute"}, {"api_name": "collections.Counter", "line_number": 143, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 151, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 154, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 174, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 174, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 178, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 178, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 179, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 179, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 184, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 188, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 191, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 211, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 211, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 216, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 216, "usage_type": "name"}, {"api_name": "praw.Reddit", "line_number": 219, "usage_type": "call"}]} +{"seq_id": "29400793941", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*- \n\"\"\"\n# File : test_sap_cn_blank_passwd.py\n# Time :2023/7/25 10:39\n# Author :chao.li\n# version :python 3.9\n# Description:\n\"\"\"\n\n\n\nimport logging\n\nimport pytest\n\nfrom ADB import concomitant_dut\n\n'''\n测试步骤\nSSID中文字符\n\n密码含有中文和空格\n\n1.设置SAP 密码为\"SAP_测试 123\"\n\n可以保存成功,并能正确显示\n'''\n\nssid = 'SAP_测试 123'\n\n@pytest.fixture(autouse=True)\ndef setup_teardown():\n # pytest.executer.change_keyboard_language()\n pytest.executer.open_hotspot()\n logging.info('setup done')\n yield\n pytest.executer.reset_keyboard_language()\n pytest.executer.close_hotspot()\n\n@pytest.mark.hot_spot\ndef test_hotspot_cn_char_ssid():\n pytest.executer.wait_and_tap('Hotspot name', 'text')\n pytest.executer.u().d2(resourceId=\"android:id/edit\").clear_text()\n pytest.executer.checkoutput(f'am broadcast -a ADB_INPUT_TEXT --es msg \"{ssid}\"')\n pytest.executer.wait_and_tap('GO','text')\n pytest.executer.keyevent(66)\n pytest.executer.wait_element('Hotspot name', 'text')\n assert ssid == pytest.executer.u().d2(resourceId=\"android:id/summary\").get_text(), \"ssid can't be set currently\"\n concomitant_dut.wait_ssid_cmd(ssid)\n", "repo_name": "zhaoxiaojia/wifi_test", "sub_path": "test/full/test_sap_cn_blank_passwd.py", "file_name": "test_sap_cn_blank_passwd.py", "file_ext": "py", "file_size_in_byte": 1260, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "pytest.executer.open_hotspot", "line_number": 35, "usage_type": "call"}, {"api_name": "pytest.executer", "line_number": 35, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 36, "usage_type": "call"}, {"api_name": "pytest.executer.reset_keyboard_language", "line_number": 38, "usage_type": "call"}, {"api_name": "pytest.executer", "line_number": 38, "usage_type": "attribute"}, {"api_name": "pytest.executer.close_hotspot", "line_number": 39, "usage_type": "call"}, {"api_name": "pytest.executer", "line_number": 39, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 32, "usage_type": "call"}, {"api_name": "pytest.executer.wait_and_tap", "line_number": 43, "usage_type": "call"}, {"api_name": "pytest.executer", "line_number": 43, "usage_type": "attribute"}, {"api_name": "pytest.executer.u", "line_number": 44, "usage_type": "call"}, {"api_name": "pytest.executer", "line_number": 44, "usage_type": "attribute"}, {"api_name": "pytest.executer.checkoutput", "line_number": 45, "usage_type": "call"}, {"api_name": "pytest.executer", "line_number": 45, "usage_type": "attribute"}, {"api_name": "pytest.executer.wait_and_tap", "line_number": 46, "usage_type": "call"}, {"api_name": "pytest.executer", "line_number": 46, "usage_type": "attribute"}, {"api_name": "pytest.executer.keyevent", "line_number": 47, "usage_type": "call"}, {"api_name": "pytest.executer", "line_number": 47, "usage_type": "attribute"}, {"api_name": "pytest.executer.wait_element", "line_number": 48, "usage_type": "call"}, {"api_name": "pytest.executer", "line_number": 48, "usage_type": "attribute"}, {"api_name": "pytest.executer.u", "line_number": 49, "usage_type": "call"}, {"api_name": "pytest.executer", "line_number": 49, "usage_type": "attribute"}, {"api_name": "ADB.concomitant_dut.wait_ssid_cmd", "line_number": 50, "usage_type": "call"}, {"api_name": "ADB.concomitant_dut", "line_number": 50, "usage_type": "name"}, {"api_name": "pytest.mark", "line_number": 41, "usage_type": "attribute"}]} +{"seq_id": "281605806", "text": "import pandas as pd\n\nimport nltk\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nfrom textblob import TextBlob\n\n#!pip install afinn\nfrom afinn import Afinn\n\nnltk.download(\"vader_lexicon\")\n\n# instantiate afinn\nafn = Afinn()\n\n# Initialize the VADER sentiment analyzer\nvader = SentimentIntensityAnalyzer()\n\n# Define the sentences to analyze\nsentences = [\n \"Awful experience. I would never buy this product again!\",\n \"Overall, I had a good time, even though I felt bad\",\n \"Not bad!!!\",\n \"Great service :-((((\",\n \"I'm so sorry for your loss\",\n]\n\nresults = []\nfor sentence in sentences:\n # AFINN\n afinn_polarity = afn.score(sentence)\n\n # VADER\n vader_scores = vader.polarity_scores(sentence)\n vader_polarity = vader_scores[\"compound\"]\n\n # TextBlob\n textblob_polarity = TextBlob(sentence).sentiment.polarity\n\n # Apend results\n results.append(\n {\n \"sentence\": sentence,\n \"AFINN\": afinn_polarity,\n \"VADER\": vader_polarity,\n \"TextBlob\": textblob_polarity,\n }\n )\n\ndf = pd.DataFrame(results)\nprint(df)\n", "repo_name": "jony89/candidata", "sub_path": "scripts/sentinment_analysis_lexicon.py", "file_name": "sentinment_analysis_lexicon.py", "file_ext": "py", "file_size_in_byte": 1105, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "nltk.download", "line_number": 10, "usage_type": "call"}, {"api_name": "afinn.Afinn", "line_number": 13, "usage_type": "call"}, {"api_name": "nltk.sentiment.vader.SentimentIntensityAnalyzer", "line_number": 16, "usage_type": "call"}, {"api_name": "textblob.TextBlob", "line_number": 37, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 49, "usage_type": "call"}]} +{"seq_id": "74248659565", "text": "from django.urls import include, path, re_path\n\nfrom . import views\n\napp_name = 'members'\n\nurlpatterns = [\n re_path(r'^signup/$', views.signup, name='signup'),\n path('activate///', views.activate, name='activate'),\n re_path('^', include('django.contrib.auth.urls')),\n path('info/', views.EditView.as_view(), name='info'),\n path('cert/', views.CertificateView.as_view(), name='certificate'),\n path('alumn/signup', views.alumni_signup , name='alumni-signup'),\n]\n", "repo_name": "Datateknologerna-vid-Abo-Akademi/date-website", "sub_path": "members/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 493, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "2", "api": [{"api_name": "django.urls.re_path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.re_path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}]} +{"seq_id": "43027440860", "text": "import numpy as np\nfrom torch.utils.data import Dataset\n\nfrom mmpose.datasets.builder import DATASETS, build_dataset\n\n\n@DATASETS.register_module()\nclass Body3DSemiSupervisionDataset(Dataset):\n \"\"\"Mix Dataset for semi-supervised training in 3D human pose estimation\n task.\n\n The dataset combines data from two datasets (a labeled one and an unlabeled\n one) and return a dict containing data from two datasets.\n\n Args:\n labeled_dataset (Dataset): Dataset with 3D keypoint annotations.\n unlabeled_dataset (Dataset): Dataset without 3D keypoint annotations.\n \"\"\"\n\n def __init__(self, labeled_dataset, unlabeled_dataset):\n super().__init__()\n self.labeled_dataset = build_dataset(labeled_dataset)\n self.unlabeled_dataset = build_dataset(unlabeled_dataset)\n self.length = len(self.unlabeled_dataset)\n\n def __len__(self):\n \"\"\"Get the size of the dataset.\"\"\"\n return self.length\n\n def __getitem__(self, i):\n \"\"\"Given index, get the data from unlabeled dataset and randomly sample\n an item from labeled dataset.\n\n Return a dict containing data from labeled and unlabeled dataset.\n \"\"\"\n data = self.unlabeled_dataset[i]\n rand_ind = np.random.randint(0, len(self.labeled_dataset))\n labeled_data = self.labeled_dataset[rand_ind]\n data.update(labeled_data)\n return data\n", "repo_name": "ViTAE-Transformer/ViTPose", "sub_path": "mmpose/datasets/datasets/body3d/body3d_semi_supervision_dataset.py", "file_name": "body3d_semi_supervision_dataset.py", "file_ext": "py", "file_size_in_byte": 1403, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 978, "dataset": "github-code", "pt": "2", "api": [{"api_name": "torch.utils.data.Dataset", "line_number": 8, "usage_type": "name"}, {"api_name": "mmpose.datasets.builder.build_dataset", "line_number": 22, "usage_type": "call"}, {"api_name": "mmpose.datasets.builder.build_dataset", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 37, "usage_type": "attribute"}, {"api_name": "mmpose.datasets.builder.DATASETS.register_module", "line_number": 7, "usage_type": "call"}, {"api_name": "mmpose.datasets.builder.DATASETS", "line_number": 7, "usage_type": "name"}]} +{"seq_id": "14532459063", "text": "#pomodoro timer\r\n\r\nimport time\r\nimport os\r\nimport sys\r\nimport streamlit as st\r\n\r\n\r\n\r\nst.title(\"Pomodoro Timer\")\r\nst.write(\"A simple timer for the Pomodoro Technique\")\r\nst.write(\"By Davi Rezende\")\r\nst.write(\"\")\r\n\r\n\r\ntempo_total = 25 * 60\r\ntempo_restante = tempo_total\r\n\r\n\r\n\r\nif st.button(\"Iniciar\"):\r\n while tempo_restante > 0:\r\n mins, secs = divmod(tempo_restante, 60)\r\n timer = '{:02d}:{:02d}'.format(mins, secs)\r\n st.write(timer)\r\n time.sleep(1)\r\n tempo_restante -= 1\r\nst.write(\"Fim do tempo!\")\r\n\r\n\r\ntime_refresher = st.empty()\r\nwhile True:\r\n time_refresher.text(time.strftime(\"%H:%M:%S\"))\r\n time.sleep(1)\r\n", "repo_name": "Daviqr1/Pomodoro_timer", "sub_path": "pomodoro.py", "file_name": "pomodoro.py", "file_ext": "py", "file_size_in_byte": 653, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "streamlit.title", "line_number": 10, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 11, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 12, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 13, "usage_type": "call"}, {"api_name": "streamlit.button", "line_number": 21, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 25, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 26, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 28, "usage_type": "call"}, {"api_name": "streamlit.empty", "line_number": 31, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 33, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 34, "usage_type": "call"}]} +{"seq_id": "32868494704", "text": "import os\nimport sys\nimport platform\nimport logging\nfrom types import SimpleNamespace\nimport tkinter.ttk as tk\nfrom tkinter import Tk\n# from tkinter import Toplevel\nfrom tkinter import filedialog\nimport tkinter.scrolledtext as ScrolledText\nfrom tkinter import Text, IntVar, StringVar, Listbox, Label, Toplevel, TclError\nfrom tkinter import N, S, E, W, X, Y # pylint: disable=unused-import\nfrom tkinter import TOP, BOTTOM, LEFT, RIGHT # pylint: disable=unused-import\nfrom tkinter import END, BOTH, VERTICAL, HORIZONTAL # pylint: disable=unused-import\nfrom tkinter import EXTENDED, RAISED, SOLID, DISABLED, NORMAL # pylint: disable=unused-import\nfrom tkinter import PhotoImage\nfrom tkinter.font import Font\n\nBLACK = \"#000000\"\nYELLOW = \"#f4e012\"\nWHITE = \"#ffffff\"\nRED = \"#ff0000\"\nTEAL = \"#78CBFD\"\nGREEN = \"#09f218\"\nBLUE = \"#090df2\"\nGREY = '#e8e8e8'\n\nabsdir = os.path.dirname(os.path.realpath(__file__))\n\n\nclass TextHandler(logging.Handler):\n # This class allows you to log to a Tkinter Text or ScrolledText widget\n # Adapted from Moshe Kaplan: https://gist.github.com/moshekaplan/c425f861de7bbf28ef06\n\n def __init__(self, text):\n # run the regular Handler __init__\n logging.Handler.__init__(self)\n # Store a reference to the Text it will log to\n self.text = text\n\n def emit(self, record):\n msg = self.format(record)\n\n def append():\n self.text.configure(state='normal')\n self.text.insert(END, msg + '\\n')\n self.text.configure(state='disabled')\n # Autoscroll to the bottom\n self.text.yview(END)\n # This is necessary because we can't modify the Text from other threads\n self.text.after(0, append)\n\n\nclass ToolTip(object):\n\n def __init__(self, widget):\n self.widget = widget\n self.tipwindow = None\n self.id = None\n self.x = self.y = 0\n self.text = str()\n\n def showtip(self, text):\n \"Display text in tooltip window\"\n self.text = text\n if self.tipwindow or not self.text:\n return\n x, y, cx, cy = self.widget.bbox(\"insert\")\n x = x + self.widget.winfo_rootx() + 27\n y = y + cy + self.widget.winfo_rooty() + 27\n self.tipwindow = tw = Toplevel(self.widget)\n tw.wm_overrideredirect(1)\n tw.wm_geometry(\"+%d+%d\" % (x, y))\n try:\n # For Mac OS\n tw.tk.call(\"::tk::unsupported::MacWindowStyle\",\n \"style\", tw._w,\n \"help\", \"noActivates\")\n except TclError:\n pass\n label = Label(tw, text=self.text, justify=LEFT,\n background=\"#ffffe0\", relief=SOLID, borderwidth=1,\n font=(\"tahoma\", \"8\", \"normal\"))\n label.pack(ipadx=1)\n\n def hidetip(self):\n tw = self.tipwindow\n self.tipwindow = None\n if tw:\n tw.destroy()\n\n\ndef createToolTip(widget, text):\n toolTip = ToolTip(widget)\n\n def enter(event):\n toolTip.showtip(text)\n\n def leave(event):\n toolTip.hidetip()\n widget.bind('', enter)\n widget.bind('', leave)\n\n\nclass ChooseFiles(tk.Frame):\n '''The main frame for adding/removing files, accessing setttings\n and parsing.'''\n\n from seebeck.parse import GUIParse\n\n opts = SimpleNamespace(in_files=[],\n out_dir=os.path.join(os.getcwd(), 'parsed'),\n out_file='',\n plot=True,\n write=True,\n truetemp=False,\n col_to_parse=1,\n dTn=[],\n cutoff_to_toss=100) # TODO: Make this a user option\n raw_data = {}\n gothreads = []\n plots = []\n outdir = ''\n boolmap = {1: True, 0: False}\n colmap = {1: 'Raw Voltage (uV)',\n 2: 'Corrected Voltage (uV)',\n 3: 'Top T',\n 4: 'Bottom T',\n 5: 'Delta-T (°C)',\n 6: 'Seebeck (uV/K)'}\n\n FileListBoxFrameLabelVar = None\n FileListBoxFrameLabel = None\n filelist = None\n FileListBox = None\n checks = []\n OutputFileName = None\n DeltaTn = None\n OptionsColString = None\n OptionCol = None\n\n def __init__(self, master=None):\n if master is None:\n master = Tk()\n super().__init__(master)\n bgimg = PhotoImage(file=os.path.join(absdir, 'gui', 'RCCLabFluidic.png'))\n limg = Label(self.master, i=bgimg, background=GREY)\n limg.pack(side=TOP)\n try:\n self.last_input_path = os.getcwd()\n except KeyError:\n self.last_input_path = os.path.expanduser('~')\n master.tk_setPalette(background=GREY, activeBackground=GREY)\n master.title(\"RCCLab Rick-9000 Parser\")\n master.geometry('800x850+250+250')\n self.pack(fill=BOTH)\n if len(sys.argv) > 1:\n self.opts.in_files = sys.argv[1:]\n self.__createWidgets()\n self.ToFront()\n\n def __createWidgets(self):\n\n self.ButtonFrame = tk.Frame(self)\n self.LoggingFrame = tk.Frame(self)\n self.RightOptionsFrame = tk.Frame(self)\n self.FileListBoxFrame = tk.Frame(self)\n\n # ScrolledText widget to display logging output\n stlogger = ScrolledText.ScrolledText(self.LoggingFrame, state='disabled')\n stlogger.configure(font='TkFixedFont')\n stlogger.pack(side=LEFT, fill=BOTH, expand=True)\n # Create textLogger\n text_handler = TextHandler(stlogger)\n\n # Logging configuration\n logging.basicConfig(filename='Rick-9000.log',\n level=logging.INFO,\n format='%(asctime)s - %(levelname)s - %(message)s')\n\n # Add the handler to logger\n logger = logging.getLogger(__package__)\n logger.addHandler(text_handler)\n\n self.__createButtons()\n self.__createFileListBox()\n self.__createOptions()\n\n self.ButtonFrame.pack(side=BOTTOM, fill=None)\n self.FileListBoxFrame.pack(side=TOP, fill=BOTH, expand=True)\n self.RightOptionsFrame.pack(side=RIGHT, fill=Y)\n self.LoggingFrame.pack(side=BOTTOM, fill=BOTH)\n\n # self.logger.setLevel(getattr(logging, self.opts.loglevel.upper()))\n self.updateFileListBox()\n self.checkOptions()\n logging.info('Select some files to get started.')\n\n def __createButtons(self):\n\n buttons = [{'name': 'Quit', 'text': 'QUIT', 'command': 'Quit', 'side': BOTTOM},\n {'name': 'SpawnInputDialog', 'text': 'Add Input Files', 'side': LEFT},\n {'name': 'RemoveFile', 'text': 'Remove Files', 'side': LEFT},\n {'name': 'SpawnOutputDialog', 'text': 'Choose Output Directory', 'side': LEFT},\n {'name': 'Parse', 'text': 'Parse!', 'side': LEFT}\n ]\n\n for b in buttons:\n button = tk.Button(self.ButtonFrame)\n button.config(text=b['text'], command=getattr(self, b['name']+'Click'))\n button.pack(side=b['side'])\n setattr(self, 'Button'+b['name'], button)\n\n def __createFileListBox(self):\n self.FileListBoxFrameLabelVar = StringVar()\n self.FileListBoxFrameLabel = tk.Label(self.FileListBoxFrame,\n textvariable=self.FileListBoxFrameLabelVar,\n font=Font(size=10, weight=\"bold\"))\n self.FileListBoxFrameLabel.pack(side=TOP, fill=X)\n\n yScroll = tk.Scrollbar(self.FileListBoxFrame, orient=VERTICAL)\n yScroll.pack(side=RIGHT, fill=Y)\n xScroll = tk.Scrollbar(self.FileListBoxFrame, orient=HORIZONTAL)\n xScroll.pack(side=BOTTOM, fill=X)\n self.filelist = StringVar()\n self.FileListBox = Listbox(self.FileListBoxFrame,\n listvariable=self.filelist, selectmode=EXTENDED,\n height=20, width=0, relief=RAISED, bd=1,\n bg=WHITE,\n # font=Font(size=10),\n xscrollcommand=xScroll.set,\n yscrollcommand=yScroll.set)\n xScroll['command'] = self.FileListBox.xview\n yScroll['command'] = self.FileListBox.yview\n self.FileListBox.pack(side=LEFT, fill=BOTH, expand=True)\n self.UpdateFileListBoxFrameLabel()\n\n def __createOptions(self):\n '''Create the widgets for options and use setattr to assign them to self.'''\n self.checks = [{'name': 'plot', 'text': 'Plot', 'row': 1,\n 'tooltip': \"Show summary plots after parsing.\"},\n {'name': 'write', 'text': 'Write', 'row': 2,\n 'tooltip': \"Write results to text files after parsing.\"},\n {'name': 'truetemp', 'text': 'Use Real T', 'row': 3,\n 'tooltip': \"Use the measured ΔT instead the ΔT field values.\"}\n ]\n\n for _c in self.checks:\n setattr(self, _c['name'], IntVar())\n check = tk.Checkbutton(self.RightOptionsFrame, text=_c['text'],\n variable=getattr(self, _c['name']),\n command=self.checkOptions)\n check.grid(column=0, row=_c['row'], sticky=W)\n createToolTip(check, _c['tooltip'])\n setattr(self, 'Check_'+_c['name'], check)\n if getattr(self.opts, _c['name']):\n getattr(self, _c['name']).set(1)\n\n rowidx = len(self.checks)+1\n\n tk.Label(self.RightOptionsFrame, text=\"Output file base name:\").grid(\n column=0, row=rowidx)\n self.OutputFileName = tk.Entry(self.RightOptionsFrame, width=20,\n font=Font(size=10, slant='italic'))\n for n in ('', '', ''):\n self.OutputFileName.bind(n, self.checkOutputFileName)\n self.OutputFileName.grid(column=0, row=rowidx+1)\n\n if self.opts.out_file:\n self.OutputFileName.insert(0, self.opts.out_file)\n\n tk.Label(self.RightOptionsFrame, text=\"ΔT values:\").grid(\n column=0, row=rowidx+2, sticky=W)\n self.DeltaTn = tk.Entry(self.RightOptionsFrame, width=20,\n font=Font(size=10))\n self.DeltaTn.insert(0, '4,8,12')\n for n in ('', '', ''):\n self.DeltaTn.bind(None, self.checkOptions)\n self.DeltaTn.grid(column=0, row=rowidx+3, sticky=W)\n\n tk.Label(self.RightOptionsFrame, text=\"Cutoff Limit: \").grid(\n column=0, row=rowidx+4, sticky=W)\n self.cutoffEntry = tk.Entry(self.RightOptionsFrame, width=8,\n font=Font(size=10))\n self.cutoffEntry.insert(0, str(self.opts.cutoff_to_toss))\n for n in ('', '', ''):\n self.cutoffEntry.bind(None, self.checkOptions)\n self.cutoffEntry.grid(column=0, row=rowidx+4, sticky=E)\n\n tk.Label(self.RightOptionsFrame, text=\"Column to plot:\").grid(\n column=0, row=rowidx+6, sticky=W)\n self.OptionsColString = StringVar()\n self.OptionsColString.set(self.opts.col_to_parse)\n self.OptionCol = tk.OptionMenu(self.RightOptionsFrame,\n self.OptionsColString,\n self.colmap[self.opts.col_to_parse],\n command=self.checkOptions,\n *list(self.colmap.values()))\n # __menu = self.nametowidget(self.OptionCol)\n # __menu.config(font=Font(size=10)) # Set the dropdown menu's font\n self.OptionCol.grid(column=0, row=rowidx+5, sticky=W)\n\n # tk.Label(self.RightOptionsFrame, text=\"ΔT values:\").grid(\n # column=0, row=rowidx+2, sticky=W)\n # self.OptionsdTnString = StringVar()\n # self.OptionsdTnString.set('.'.join(self.opts.dTn))\n # self.OptionPlots = tk.OptionMenu(self.RightOptionsFrame,\n # self.OptionsdTnString, self.opts.dTn, 'J', 'R',\n # command=self.checkOptions)\n # self.OptionPlots.grid(column=0, row=rowidx+3, sticky=W)\n\n def RemoveFileClick(self):\n self.checkOptions()\n selected = [self.FileListBox.get(x) for x in self.FileListBox.curselection()]\n todel = []\n filelist = []\n for i in range(0, len(self.opts.in_files)):\n for _s in selected:\n if self.opts.in_files[i].replace(\" \", \"_\") == _s:\n todel.append(i)\n\n for i in range(0, len(self.opts.in_files)):\n if i not in todel:\n filelist.append(self.opts.in_files[i])\n self.opts.in_files = filelist\n self.updateFileListBox()\n self.FileListBox.selection_clear(0, END)\n\n def SpawnInputDialogClick(self):\n # self.checkOptions()\n self.opts.in_files += filedialog.askopenfilename(\n title=\"Files to parse\",\n multiple=True,\n initialdir=self.last_input_path,\n filetypes=[('LabView Files', '*.lvm'), ('Data files', '*_data.txt'),\n ('Text files', '*.txt'), ('All files', '*')])\n if self.opts.in_files:\n self.last_input_path = os.path.split(self.opts.in_files[0])[0]\n if not self.outdir:\n self.opts.out_dir = os.path.join(self.last_input_path, 'parsed')\n self.updateFileListBox()\n if not self.opts.out_file:\n self.OutputFileName.delete(0, END)\n self.OutputFileName.insert(0, os.path.basename(\n self.opts.in_files[-1]).lower().replace('.lvm', ''))\n self.checkOutputFileName()\n self.updateFileListBox()\n\n def ParseClick(self):\n self.checkOptions()\n self.GUIParse()\n\n def checkOptions(self, m=None):\n for c in self.checks:\n setattr(self.opts, c['name'], self.boolmap[getattr(self, c['name']).get()])\n if self.opts.truetemp:\n self.DeltaTn['state'] = DISABLED\n else:\n self.DeltaTn['state'] = NORMAL\n self.opts.dTn = self.DeltaTn.get().split(',')\n\n for __key in self.colmap:\n if self.colmap[__key] == self.OptionsColString.get():\n self.opts.col_to_parse = __key\n _toss = self.cutoffEntry.get()\n try:\n self.opts.cutoff_to_toss = int(_toss)\n except ValueError:\n self.cutoffEntry.insert(0, str(self.opts.cutoff_to_toss))\n\n def updateFileListBox(self):\n self.filelist.set(\" \".join([x.replace(\" \", \"_\") for x in self.opts.in_files]))\n\n def SpawnOutputDialogClick(self):\n outdir = filedialog.askdirectory(title=\"Select Output File(s)\",\n initialdir=self.opts.out_dir)\n if not outdir:\n return\n if os.path.exists(outdir):\n self.opts.out_dir = outdir\n self.outdir = self.opts.out_dir # So we know the user set the output dir\n self.UpdateFileListBoxFrameLabel()\n\n def UpdateFileListBoxFrameLabel(self):\n self.FileListBoxFrameLabelVar.set(\n f\"Output to: {self.opts.out_dir}/{self.opts.out_file}_*.txt\")\n\n def checkOutputFileName(self, event=None):\n self.opts.out_file = self.OutputFileName.get()\n self.UpdateFileListBoxFrameLabel()\n\n def QuitClick(self):\n self.Quit()\n\n def Quit(self):\n self.master.quit()\n self.master.destroy()\n\n def ToFront(self):\n '''Try to bring the main window to the front on different platforms'''\n if platform.system() == \"Darwin\":\n os.system(\n '''/usr/bin/osascript -e 'tell app \"Finder\" to set frontmost of process \"Python\" to true' ''')\n else:\n self.master.attributes('-topmost', 1)\n self.master.attributes('-topmost', 0)\n self.master.lift()\n\n\nif __name__ == '__main__':\n print(\"Starting GUI\")\n root = Tk()\n gui = ChooseFiles(root)\n gui.mainloop()\n", "repo_name": "rchiechi/GaussFit", "sub_path": "Rick-9000.py", "file_name": "Rick-9000.py", "file_ext": "py", "file_size_in_byte": 16226, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "27", "api": [{"api_name": "os.path.dirname", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 28, "usage_type": "call"}, {"api_name": "logging.Handler", "line_number": 31, "usage_type": "attribute"}, {"api_name": "logging.Handler.__init__", "line_number": 37, "usage_type": "call"}, {"api_name": "logging.Handler", "line_number": 37, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 46, "usage_type": "argument"}, {"api_name": "tkinter.END", "line_number": 49, "usage_type": "argument"}, {"api_name": "tkinter.Toplevel", "line_number": 71, "usage_type": "call"}, {"api_name": "tkinter.TclError", "line_number": 79, "usage_type": "name"}, {"api_name": "tkinter.Label", "line_number": 81, "usage_type": "call"}, {"api_name": "tkinter.LEFT", "line_number": 81, "usage_type": "name"}, {"api_name": "tkinter.SOLID", "line_number": 82, "usage_type": "name"}, {"api_name": "tkinter.ttk.Frame", "line_number": 105, "usage_type": "attribute"}, {"api_name": "tkinter.ttk", "line_number": 105, "usage_type": "name"}, {"api_name": "types.SimpleNamespace", "line_number": 111, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 112, "usage_type": "call"}, {"api_name": "os.path", "line_number": 112, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 112, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 144, "usage_type": "call"}, {"api_name": "tkinter.PhotoImage", "line_number": 146, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 146, "usage_type": "call"}, {"api_name": "os.path", "line_number": 146, "usage_type": "attribute"}, {"api_name": "tkinter.Label", "line_number": 147, "usage_type": "call"}, {"api_name": "tkinter.TOP", "line_number": 148, "usage_type": "name"}, {"api_name": "os.getcwd", "line_number": 150, "usage_type": "call"}, {"api_name": "os.path.expanduser", "line_number": 152, "usage_type": "call"}, {"api_name": "os.path", "line_number": 152, "usage_type": "attribute"}, {"api_name": "tkinter.BOTH", "line_number": 156, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 157, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 158, "usage_type": "attribute"}, {"api_name": "tkinter.ttk.Frame", "line_number": 164, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 164, "usage_type": "name"}, {"api_name": "tkinter.ttk.Frame", "line_number": 165, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 165, "usage_type": "name"}, {"api_name": "tkinter.ttk.Frame", "line_number": 166, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 166, "usage_type": "name"}, {"api_name": "tkinter.ttk.Frame", "line_number": 167, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 167, "usage_type": "name"}, {"api_name": "tkinter.scrolledtext.ScrolledText", "line_number": 170, "usage_type": "call"}, {"api_name": "tkinter.scrolledtext", "line_number": 170, "usage_type": "name"}, {"api_name": "tkinter.LEFT", "line_number": 172, "usage_type": "name"}, {"api_name": "tkinter.BOTH", "line_number": 172, "usage_type": "name"}, {"api_name": "logging.basicConfig", "line_number": 177, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 178, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 182, "usage_type": "call"}, {"api_name": "tkinter.BOTTOM", "line_number": 189, "usage_type": "name"}, {"api_name": "tkinter.TOP", "line_number": 190, "usage_type": "name"}, {"api_name": "tkinter.BOTH", "line_number": 190, "usage_type": "name"}, {"api_name": "tkinter.RIGHT", "line_number": 191, "usage_type": "name"}, {"api_name": "tkinter.Y", "line_number": 191, "usage_type": "name"}, {"api_name": "tkinter.BOTTOM", "line_number": 192, "usage_type": "name"}, {"api_name": "tkinter.BOTH", "line_number": 192, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 197, "usage_type": "call"}, {"api_name": "tkinter.BOTTOM", "line_number": 201, "usage_type": "name"}, {"api_name": "tkinter.LEFT", "line_number": 202, "usage_type": "name"}, {"api_name": "tkinter.LEFT", "line_number": 203, "usage_type": "name"}, {"api_name": "tkinter.LEFT", "line_number": 204, "usage_type": "name"}, {"api_name": "tkinter.LEFT", "line_number": 205, "usage_type": "name"}, {"api_name": "tkinter.ttk.Button", "line_number": 209, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 209, "usage_type": "name"}, {"api_name": "tkinter.StringVar", "line_number": 215, "usage_type": "call"}, {"api_name": "tkinter.ttk.Label", "line_number": 216, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 216, "usage_type": "name"}, {"api_name": "tkinter.font.Font", "line_number": 218, "usage_type": "call"}, {"api_name": "tkinter.TOP", "line_number": 219, "usage_type": "name"}, {"api_name": "tkinter.X", "line_number": 219, "usage_type": "name"}, {"api_name": "tkinter.ttk.Scrollbar", "line_number": 221, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 221, "usage_type": "name"}, {"api_name": "tkinter.VERTICAL", "line_number": 221, "usage_type": "name"}, {"api_name": "tkinter.RIGHT", "line_number": 222, "usage_type": "name"}, {"api_name": "tkinter.Y", "line_number": 222, "usage_type": "name"}, {"api_name": "tkinter.ttk.Scrollbar", "line_number": 223, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 223, "usage_type": "name"}, {"api_name": "tkinter.HORIZONTAL", "line_number": 223, "usage_type": "name"}, {"api_name": "tkinter.BOTTOM", "line_number": 224, "usage_type": "name"}, {"api_name": "tkinter.X", "line_number": 224, "usage_type": "name"}, {"api_name": "tkinter.StringVar", "line_number": 225, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 226, "usage_type": "call"}, {"api_name": "tkinter.EXTENDED", "line_number": 227, "usage_type": "name"}, {"api_name": "tkinter.RAISED", "line_number": 228, "usage_type": "name"}, {"api_name": "tkinter.LEFT", "line_number": 235, "usage_type": "name"}, {"api_name": "tkinter.BOTH", "line_number": 235, "usage_type": "name"}, {"api_name": "tkinter.IntVar", "line_number": 249, "usage_type": "call"}, {"api_name": "tkinter.ttk.Checkbutton", "line_number": 250, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 250, "usage_type": "name"}, {"api_name": "tkinter.W", "line_number": 253, "usage_type": "name"}, {"api_name": "tkinter.ttk.Label", "line_number": 261, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 261, "usage_type": "name"}, {"api_name": "tkinter.ttk.Entry", "line_number": 263, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 263, "usage_type": "name"}, {"api_name": "tkinter.font.Font", "line_number": 264, "usage_type": "call"}, {"api_name": "tkinter.ttk.Label", "line_number": 272, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 272, "usage_type": "name"}, {"api_name": "tkinter.W", "line_number": 273, "usage_type": "name"}, {"api_name": "tkinter.ttk.Entry", "line_number": 274, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 274, "usage_type": "name"}, {"api_name": "tkinter.font.Font", "line_number": 275, "usage_type": "call"}, {"api_name": "tkinter.W", "line_number": 279, "usage_type": "name"}, {"api_name": "tkinter.ttk.Label", "line_number": 281, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 281, "usage_type": "name"}, {"api_name": "tkinter.W", "line_number": 282, "usage_type": "name"}, {"api_name": "tkinter.ttk.Entry", "line_number": 283, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 283, "usage_type": "name"}, {"api_name": "tkinter.font.Font", "line_number": 284, "usage_type": "call"}, {"api_name": "tkinter.E", "line_number": 288, "usage_type": "name"}, {"api_name": "tkinter.ttk.Label", "line_number": 290, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 290, "usage_type": "name"}, {"api_name": "tkinter.W", "line_number": 291, "usage_type": "name"}, {"api_name": "tkinter.StringVar", "line_number": 292, "usage_type": "call"}, {"api_name": "tkinter.ttk.OptionMenu", "line_number": 294, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 294, "usage_type": "name"}, {"api_name": "tkinter.W", "line_number": 301, "usage_type": "name"}, {"api_name": "tkinter.END", "line_number": 327, "usage_type": "argument"}, {"api_name": "tkinter.filedialog.askopenfilename", "line_number": 331, "usage_type": "call"}, {"api_name": "tkinter.filedialog", "line_number": 331, "usage_type": "name"}, {"api_name": "os.path.split", "line_number": 338, "usage_type": "call"}, {"api_name": "os.path", "line_number": 338, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 340, "usage_type": "call"}, {"api_name": "os.path", "line_number": 340, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 343, "usage_type": "argument"}, {"api_name": "os.path.basename", "line_number": 344, "usage_type": "call"}, {"api_name": "os.path", "line_number": 344, "usage_type": "attribute"}, {"api_name": "tkinter.DISABLED", "line_number": 357, "usage_type": "name"}, {"api_name": "tkinter.NORMAL", "line_number": 359, "usage_type": "name"}, {"api_name": "tkinter.filedialog.askdirectory", "line_number": 375, "usage_type": "call"}, {"api_name": "tkinter.filedialog", "line_number": 375, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 379, "usage_type": "call"}, {"api_name": "os.path", "line_number": 379, "usage_type": "attribute"}, {"api_name": "platform.system", "line_number": 401, "usage_type": "call"}, {"api_name": "os.system", "line_number": 402, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 412, "usage_type": "call"}, {"api_name": "{'GUIParse': 'seebeck.parse.GUIParse'}", "line_number": 413, "usage_type": "call"}]} +{"seq_id": "37363575741", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass MLP(nn.Module):\n \"\"\"\n Zero initialisation for final layer is useful for training very deep flow models https: // arxiv.org / pdf / 1807.03039.pdf\n as it gives the identity transformation\n \"\"\"\n def __init__(self, input_dim, output_dim, hidden_layer_width, n_hidden_layers=1,\n init_zeros=True):\n super(MLP, self).__init__()\n in_dim = input_dim\n self.hidden_layers = torch.nn.ModuleList()\n for _ in range(n_hidden_layers):\n self.hidden_layers.append(nn.Linear(in_dim, hidden_layer_width))\n in_dim = hidden_layer_width\n self.output_layer = nn.Linear(in_dim, output_dim)\n if init_zeros:\n nn.init.zeros_(self.output_layer.weight)\n nn.init.zeros_(self.output_layer.bias)\n\n def forward(self, x):\n for hidden_layer in self.hidden_layers:\n x = F.leaky_relu(hidden_layer(x))\n return self.output_layer(x)\n", "repo_name": "lollcat/FAB-2021", "sub_path": "NormalisingFlow/Nets/MLP.py", "file_name": "MLP.py", "file_ext": "py", "file_size_in_byte": 1012, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "2", "api": [{"api_name": "torch.nn.Module", "line_number": 5, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 5, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 14, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 14, "usage_type": "attribute"}, {"api_name": "torch.nn.Linear", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 16, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 18, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 18, "usage_type": "name"}, {"api_name": "torch.nn.init.zeros_", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 20, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.init.zeros_", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 21, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.nn.functional.leaky_relu", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 25, "usage_type": "name"}]} +{"seq_id": "38711298023", "text": "from psoc import Psoc\nimport struct\nfrom serial_emulator import HSMEmulator\nimport logging\nimport time\n\n\nclass HSM(Psoc):\n \"\"\"Interface for communicating with the HSM\n\n Args:\n port (str, optional): Serial port connected to HSM\n verbose (bool, optional): Whether to print debug messages\n\n Note:\n Calls to get_uuid and withdraw must be alternated to remain in sync\n with the HSM\n \"\"\"\n\n def __init__(self, port=None, verbose=False, dummy=False):\n self.port = port\n self.verbose = verbose\n self.dummy = dummy\n\n def initialize(self):\n super(HSM, self).__init__('HSM', self.port, self.verbose)\n self._vp('Please connect HSM to continue.')\n while not self.connected and not self.dummy:\n time.sleep(2)\n self._vp('Initialized')\n\n def _authenticate(self, uuid):\n \"\"\"Requests authentication from the HSM\n\n Args:\n uuid (str): Challenge UUID of HSM\n\n Returns:\n bool: True if HSM verified authentication, False otherwise\n \"\"\"\n self._vp('Sending UUID %s' % uuid)\n self._push_msg('%s\\00' % uuid)\n\n resp = self._pull_msg()\n self._vp('Received response %s from HSM' % resp)\n\n return resp == 'K'\n\n def get_uuid(self):\n \"\"\"Retrieves the UUID from the HSM\n\n Returns:\n str: UUID of HSM\n \"\"\"\n self._sync(False)\n uuid = self._pull_msg()\n\n if uuid == 'P':\n self._vp('Security module not yet provisioned!', logging.error)\n return None\n\n self._vp('Got UUID %s' % uuid)\n\n return uuid\n\n def withdraw(self, uuid, amount):\n \"\"\"Attempts to withdraw bills from the HSM\n\n Args:\n uuid (str): Challenge UUID of HSM\n amount (int): Number of bills to withdraw from HSM\n\n Returns:\n list of str: List of dispensed bills on success\n str: 'Insufficient funds' if the UUID was incorrect\n 'Not enough bills in ATM' if HSM doesn't have enough bills\n to complete request\n \"\"\"\n if not self._authenticate(uuid):\n return 'Insufficient funds'\n\n msg = struct.pack('B', amount)\n self._push_msg(msg)\n\n msg = self._pull_msg()\n self._vp('Secmod replied %s' % msg)\n if msg == 'BAD':\n return 'Not enough bills in ATM'\n\n bills = []\n for i in range(amount):\n bill = self._pull_msg()\n self._vp('Received bill %d/%d: \\'%s\\'' % (i + 1, amount, bill))\n\n bills.append(bill)\n\n return bills\n\n def provision(self, uuid, bills):\n \"\"\"Attempts to provision HSM\n\n Args:\n uuid (str): UUID for HSM\n bills (list of str): List of bills to store in HSM\n\n Returns:\n bool: True if HSM provisioned, False otherwise\n \"\"\"\n self._sync(True)\n\n msg = self._pull_msg()\n if msg != 'P':\n self._vp('HSM already provisioned!', logging.error)\n return False\n self._vp('HSM sent provisioning message')\n\n self._push_msg('%s\\00' % uuid)\n while self._pull_msg() != 'K':\n self._vp('HSM hasn\\'t accepted UUID \\'%s\\'' % uuid, logging.error)\n self._vp('HSM accepted UUID \\'%s\\'' % uuid)\n\n self._push_msg(struct.pack('B', len(bills)))\n while self._pull_msg() != 'K':\n self._vp('HSM hasn\\'t accepted number of bills', logging.error)\n self._vp('HSM accepted number of bills')\n\n for bill in bills:\n msg = bill.strip()\n self._vp('Sending bill \\'%s\\'' % msg.encode('hex'))\n self._push_msg(msg)\n\n while self._pull_msg() != 'K':\n self._vp('HSM hasn\\'t accepted bill', logging.error)\n self._vp('HSM accepted bill')\n\n self._vp('All bills sent! Provisioning complete!')\n\n return True\n\n\nclass DummyHSM(HSM):\n \"\"\"Emulated HSM for testing\n\n Arguments:\n verbose (bool, optional): Whether to print debug messages\n provision (bool, optional): Whether to start the HSM ready\n for provisioning\n \"\"\"\n def __init__(self, verbose=False, provision=False):\n ser = HSMEmulator(verbose=verbose, provision=provision)\n super(DummyHSM, self).__init__(port=ser, verbose=verbose, dummy=True)\n", "repo_name": "mitre-cyber-academy/2018-ectf-insecure-example", "sub_path": "atm_backend/atm_backend/interface/hsm.py", "file_name": "hsm.py", "file_ext": "py", "file_size_in_byte": 4396, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "2", "api": [{"api_name": "psoc.Psoc", "line_number": 8, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 29, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 59, "usage_type": "attribute"}, {"api_name": "struct.pack", "line_number": 82, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 113, "usage_type": "attribute"}, {"api_name": "logging.error", "line_number": 119, "usage_type": "attribute"}, {"api_name": "struct.pack", "line_number": 122, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 124, "usage_type": "attribute"}, {"api_name": "logging.error", "line_number": 133, "usage_type": "attribute"}, {"api_name": "serial_emulator.HSMEmulator", "line_number": 150, "usage_type": "call"}]} +{"seq_id": "10825181763", "text": "import math\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom typing import Tuple, List\r\nfrom tqdm import tqdm\r\n\r\ndef load_data(file_path: str, label: str)->Tuple[np.ndarray, np.ndarray]:\r\n '''\r\n This function loads and parses text file separated by a ',' character and\r\n returns a data set as two arrays, an array of features, and an array of labels.\r\n Parameters\r\n ----------\r\n file_path : str\r\n path to the file containing the data set\r\n label : str\r\n A label of whether to grab training or testing data\r\n Returns\r\n -------\r\n features : ndarray\r\n 2D array of shape (n,m) containing features for the data set\r\n labels : ndarray\r\n 1D array of shape (n,) containing labels for the data set\r\n '''\r\n D = np.genfromtxt(file_path, delimiter=\",\")\r\n if label == \"train\":\r\n features = D[0:800, :-3] # all columns but the last three\r\n labels = D[0:800, -3:] # the last 3 columns\r\n else:\r\n features = D[801:1000, :-3] # all columns but the last three\r\n labels = D[801:1000, -3:] # the last 3 columns\r\n \r\n return features, labels\r\n\r\ndef initialize_network(layer_sizes : list, scale : float):\r\n \"\"\"\r\n This function will inialize weights for an arbitrary neural network defined by\r\n the number of neurons in each layer, given by 'layer_sizes'\r\n Your weights should be initialized to be numpy arrays composed of random numbers\r\n taken from a gaussian distribution with mean=0 and std=1, then multiplied by scale\r\n Parameters\r\n ----------\r\n layer_sizes : np.ndarray\r\n An array of intergers that denote the number of neurons in each layer\r\n [100, 50, 20] would denote a network with 100 inputs, a hidden layer\r\n with 50 neurons and output of size 20 -- this would mean W_0 would have dimensions (100,50) for example\r\n scale : float\r\n The scale of our initial weights, our weights should mostly be in the range\r\n [-1,1] * scale\r\n\r\n Returns\r\n ---------\r\n init_params : dict\r\n A dictionary that maps labels for parameters to an array of those parameters'\r\n initial values\r\n You MUST have 'W0' map to the first weight matrix, 'W1' to the second, etc.\r\n Hint: \"W\" + str(1) is \"W1\"\r\n \"\"\"\r\n # Initialize the parameter dictionary with weight matrices with random values\r\n # You need to use np.random.randn() to do this -- you can look up the API\r\n # This will give a number sampled from a normal distribution (a bell curve)\r\n init_params = {}\r\n for index in range(len(layer_sizes)-1):\r\n init_params['W' + str(index)] = scale * np.random.randn(layer_sizes[index],layer_sizes[index+1])\r\n init_params['b' + str(index)] = scale * np.random.randn(layer_sizes[index+1])\r\n\r\n return init_params\r\n\r\n# Wieghts are matrices of size input , output\r\n# Biases : output size, 1\r\ndef sigma_forward(IN: np.ndarray):\r\n \"\"\"\r\n performs the nonlinear function (sigmoid) on the given input and returns the result\r\n this is 1/(1 + e^IN)\r\n\r\n Parameters\r\n ----------\r\n IN: np.ndarray \r\n The given input to some layer\r\n Returns\r\n ----------\r\n A: np.ndarray \r\n sigma(IN), this is the A value of some layer\r\n This will need to be added to the cache too\r\n \"\"\"\r\n\r\n ######################################\r\n\r\n # TODO Implement the sigma function \r\n \r\n ######################################\r\n A = 1/(1 + np.exp(-IN))\r\n return A\r\n\r\ndef forward(params: dict, X: np.ndarray):\r\n \"\"\"\r\n This function will perform the forward pass of your backprop algorithm\r\n It will calculate your networks prediction using your parameters and\r\n will keep a cache of all intermittent values (which you need for backprop)\r\n ** YOU MUST COMPLETE THE \"sigmoid_forward()\" method for this part **\r\n Parameters\r\n ----------\r\n params : dict\r\n A dictionary that maps the labels: 'W0', 'W1', etc to their respective\r\n weight matrices -- this is the current state of your params\r\n X : np.ndarray\r\n A 2D numpy array representing input where each row represents a feature vector\r\n \r\n Returns\r\n ---------\r\n prediction : np.ndarray\r\n A 1D numpy array holding the predictions of your network given input X\r\n cache : dict\r\n A dictionary that holds all of the intermittent values calculated during your\r\n forward pass of your network (the 'IN' and 'A' of each layer), you must have the\r\n keys of this dictionary be of the form \"AL\" and \"INL\" where \"AL\" representes the input\r\n to the L-th layer of weights and \"IN(L+1)\" is the output after multiplying by weights in Layer L . \r\n \r\n i.e \"IN0\" will be the key for exactly the input X and \"A0\" will be (as a special case) also X \r\n generally \"AL\" will be sigma(\"INL\")\r\n \"\"\"\r\n # implement the forward pass of your network\r\n cache = {}\r\n # IN : W.T * X + b\r\n # A : sigmoid(IN)\r\n layerNumber = 0\r\n cache[\"A0\"] = np.copy(X)\r\n cache[\"IN0\"] = np.copy(X)\r\n while layerNumber < len(params) // 2:\r\n cache[\"IN\" + str(layerNumber + 1)] = np.dot(cache[\"A\" + str(layerNumber)], params[\"W\" + str(layerNumber)]) + \\\r\n params[\"b\" + str(layerNumber)]\r\n if layerNumber < (len(params) // 2) - 1:\r\n cache[\"A\" + str(layerNumber + 1)] = sigma_forward(cache[\"IN\" + str(layerNumber + 1)])\r\n else:\r\n cache[\"A\" + str(layerNumber + 1)] = cache[\"IN\" + str(layerNumber + 1)]\r\n layerNumber += 1\r\n\r\n prediction = cache[\"A\" + str(layerNumber)]\r\n\r\n\r\n return prediction, cache\r\n\r\ndef sigma_backward(A: np.ndarray):\r\n \"\"\"\r\n calculates the derivative of your sigma function give the output of it\r\n Parameters\r\n ----------\r\n A: np.ndarray \r\n sigmoid(IN), this is the A value (output of the sigma) of \r\n some layer. This is all we need to find dsigma / dIN believe it or not\r\n Returns\r\n ----------\r\n dsigma: np.ndarray\r\n the derivative of sigma(IN) dIN -- this will use the A value\r\n it will also be very simple\r\n \"\"\"\r\n # A = 1 / ( 1+ e^-IN ) => A *(1+e^-IN) = 1 => A + A*e^-IN = 1 => (1-A)/A = e^-IN\r\n ######################################\r\n # Implement the derivative of sigma\r\n ######################################\r\n dsigma = (1 - A) * A\r\n return dsigma\r\n\r\n\r\ndef backprop_and_loss(params: dict, prediction: np.ndarray, cache: dict, Y : np.ndarray):\r\n \"\"\"\r\n This function will calculate the loss (LSE) of your predictions and the gradient\r\n of your network for a single iteration. To calculate the gradient you must\r\n use backpropogation through your network\r\n ** YOU MUST COMPLETE THE \"sigma_backward()\" method for this part **\r\n Parameters\r\n ----------\r\n params : dict\r\n A dictionary that maps the labels: 'W0', 'W1', etc to their respective\r\n weight as well as 'b0', 'b1', etc to the bias\r\n -- this is the current state of your params\r\n prediction : np.ndarray\r\n A 1D numpy array holding the predictions of your network given input X\r\n cache : dict\r\n A dictionary that holds all of the intermittent values calculated during your\r\n forward pass of your network (the 'IN' and 'A' of each layer), you must have the\r\n keys of this dictionary be of the form \"AL\" and \"INL\" where \"AL\" representes the input\r\n to the L-th layer of weights and \"IN(L+1)\" is the output after multiplying by weights in Layer L . \r\n \r\n i.e \"IN0\" will be the key for exactly the input X and \"A0\" will be (as a special case) also X \r\n generally \"AL\" will be sigma(\"INL\")\r\n Y : np.ndarray\r\n A 1D numpy array of the correct labels of our input X\r\n Returns\r\n ---------\r\n gradient : dict\r\n A dictionary that maps the labels: 'W0', 'W1', etc to the gradients of \r\n the respective parameters (eg 'W0' -> gradient of first weight matrix)\r\n loss : float\r\n The MEAN (use np.mean) Squared Error loss given our predictions and true labels 'Y'. \r\n \r\n \"\"\"\r\n\r\n dLossWRTdPrediction = 2*(prediction - Y)\r\n dOut = dLossWRTdPrediction\r\n # Current Derivaitive calculated so far\r\n loss = np.mean((prediction - Y)**2)\r\n gradient = {}\r\n num_layers = len(params) // 2\r\n for index in reversed(range(num_layers)):\r\n dLoss_dwi = np.dot((cache[\"A\"+str(index)]).T,dOut)\r\n gradient[\"W\"+str(index)] = dLoss_dwi\r\n gradient[\"b\" + str(index)] = np.mean(dOut)\r\n dLoss_dAi = dOut.dot(params[\"W\" + str(index)].T) * sigma_backward(cache[\"A\" + str(index)])\r\n dOut = dLoss_dAi\r\n # TODO calculate the gradients of each layer using backprop -- and calculate loss\r\n return gradient, loss\r\n\r\ndef gradient_descent(X : np.ndarray, Y : np.ndarray, initial_params : dict, lr : float, num_iterations : int)->Tuple[List[float], np.ndarray]:\r\n \"\"\"\r\n This function runs gradient descent for a fixed number of iterations on the\r\n mean squared loss for a linear model parameterized by the weight vector w.\r\n This function returns a list of the losses for each iteration of gradient\r\n descent along with the final weight vector.\r\n Parameters\r\n ----------\r\n X : np.ndarray\r\n A 2D numpy array representing input where each row represents a feature vector\r\n Y : np.ndarray\r\n A 1D numpy array where each element represents a label for MSE\r\n initial_params : dictionary\r\n A dictionary holding the initialization of all parameters of the model as np.ndarrays\r\n (e.g. key 'W0' maps to the first weight array of the neural net) \r\n lr : float\r\n The step-size parameter to use with gradient descent.\r\n num_iterations : int\r\n The number of iterations of gradient descent to run.\r\n Returns\r\n -------\r\n losses : list\r\n A list of floats representing the loss from each iteration and the\r\n loss of the final weight vector\r\n final_params : dictionary \r\n A dictionary holding all of the parameters after training as np.ndarrays\r\n (this should have the same mapping as initial_params, just with updated arrays) \r\n \"\"\"\r\n losses = []\r\n params = initial_params\r\n # Complete this function. It's the whole sh-bang (Gradient Descent)\r\n for n in tqdm(range(num_iterations)): #tqdm will create a loading bar for your loop\r\n prediction,cache = forward(params, X)\r\n DerivativeParams,loss = backprop_and_loss(params, prediction,cache, Y)\r\n for param in params:\r\n params[param] -= lr * DerivativeParams[param]\r\n losses.append(loss)\r\n final_params = params\r\n return losses, final_params\r\n\r\ndef learning_curve(losses: list, names : list):\r\n \"\"\"\r\n This function plots the learning curves for all gradient descent procedures in this homework.\r\n The plot is saved in the file learning_curve.png.\r\n Parameters\r\n ----------\r\n losses : list\r\n A list of arrays representing the losses for the gradient at each iteration for each run of gradient descent\r\n names : list\r\n A list of strings representing the names for each gradient descent method\r\n Returns\r\n -------\r\n nothing\r\n \"\"\"\r\n for loss in losses:\r\n plt.plot(loss)\r\n plt.xscale(\"log\")\r\n plt.ylim(0, 10000)\r\n plt.xlabel(\"Iterations\")\r\n plt.ylabel(\"Squared Loss\")\r\n plt.title(\"Gradient Descent\")\r\n plt.legend(names)\r\n plt.savefig(\"learning_curve.png\")\r\n plt.show()\r\n\r\ndef train_best_model(Train_X, Train_Y):\r\n \"\"\"\r\n This function will train the model with the hyper parameters\r\n and layers that you have found to be best -- this model must get below 3\r\n MSE loss on our test data (which is not the test data you are given)\r\n \"\"\"\r\n\r\n # TODO CHANGE THESE VALUES\r\n np.shape(Train_X)\r\n BEST_SCALE = 0.02 # You need\r\n BEST_LAYERS = [17,20, 3] # to change\r\n BEST_ALPHA = 1e-6 # these\r\n BEST_NUM_ITERATIONS = 10000 # !\r\n # LR : e^-5\r\n # 1000 iterations : 1312.9642425305262\r\n # 10,000 Iterations: 263.5532959159481\r\n # 100000 Iterations: 301.5523573996149\r\n # Choosing 10000 Iterations\r\n # LR : e^-5 , 329.82868289845527,\r\n # LR : e^- 8, 1604.5941552175068\r\n # LR : e^-4 , 344.76074531959193\r\n # LR : e^-6 , 308.67533089876355 , Scale : 0.1,\r\n # LR : e^-6 , 306.96660619146996 , Scale : 0.01\r\n best_params = initialize_network(BEST_LAYERS, BEST_SCALE)\r\n best_losses, best_final_params = gradient_descent(Train_X, Train_Y, best_params, lr=BEST_ALPHA, num_iterations=BEST_NUM_ITERATIONS)\r\n\r\n return best_losses, best_final_params \r\n\r\ndef hw1_data():\r\n D = np.genfromtxt('housing.csv', delimiter=\",\")\r\n features = D[:, :-1] # all columns but the last one\r\n labels = D[:, -1] # the last column\r\n lr = 0.001 # You can change this to test it out\r\n scale = 0.1 # ''\r\n n_iter = 100 # ''\r\n layers = [13,1] # the input size is 13 and output size is 1 so these must stay\r\n\r\n model = initialize_network(layers, scale=scale)\r\n losses, final_params = gradient_descent(features, labels, model, lr=lr, num_iterations=n_iter)\r\n learning_curve([losses], ['MLP on housing data']) \r\n\r\ndef main():\r\n Train_X, Train_Y = load_data(\"StudentsPerformance.csv\", \"train\") # load the data set\r\n\r\n N = 10000 # N needs to equal 10,000 for your final plot. You can lower it to tune hyperparameters.\r\n\r\n init_params0 = initialize_network([17,3], scale=0.1) # initializes a sigle layer network (perceptron)\r\n losses0, final_params0 = gradient_descent(Train_X, Train_Y, init_params0, lr=1e-6, num_iterations=N) \r\n\r\n init_params1 = initialize_network([17, 5, 3], scale=0.1) # initializes a two layer network\r\n losses1, final_params1 = gradient_descent(Train_X, Train_Y, init_params1, lr=1e-6, num_iterations=N) \r\n\r\n init_params2 = initialize_network([17, 7, 3, 3], scale=0.1) # initializes a many layer network\r\n losses2, final_params2 = gradient_descent(Train_X, Train_Y, init_params2, lr=1e-6, num_iterations=N) \r\n\r\n all_losses = [losses0, losses1, losses2]\r\n names = [\"single layer\", \"two layer\", \"many layer\"]\r\n print(\"final training loss values\")\r\n for name, losses in zip(names, all_losses):\r\n print(\"{0:.<21}{1:>8.1f}\".format(name, float(losses[-1])))\r\n\r\n learning_curve(all_losses, names)\r\n\r\n # TESTING \r\n\r\n Test_X, Test_Y = load_data(\"StudentsPerformance.csv\", \"test\")\r\n\r\n pred0, _ = forward(final_params0, Test_X)\r\n test_loss0 = np.mean(np.square(Test_Y[:, None] - pred0))\r\n print(\"test loss of model 1:\", test_loss0)\r\n\r\n pred1, _ = forward(final_params1, Test_X)\r\n test_loss1 = np.mean(np.square(Test_Y[:, None] - pred1))\r\n print(\"test loss of model 2:\", test_loss1)\r\n\r\n pred2, _ = forward(final_params2, Test_X)\r\n test_loss2 = np.mean(np.square(Test_Y[:, None] - pred2))\r\n print(\"test loss of model 3:\", test_loss2)\r\n\r\n # TODO choose the hyper parameters for your best model (change them in train_best_model() )\r\n print(Train_X.shape,\"x.shape\", Train_Y.shape,\"y.shape\")\r\n best_losses, best_params = train_best_model(Train_X, Train_Y) \r\n best_pred, _ = forward(best_params, Test_X)\r\n\r\n best_loss = np.mean(np.square(Test_Y[:, None] - best_pred))\r\n print(Test_Y.shape,\"Y dataset .shape\",Test_X.shape,\"X dataset.shape\")\r\n print(\"test loss of your \\\"best\\\" model:\", best_loss)\r\n plt.plot(best_losses)\r\n plt.xscale(\"log\")\r\n plt.ylim(0, 10000)\r\n plt.xlabel(\"Iterations\")\r\n plt.ylabel(\"Squared Loss\")\r\n plt.title(\"Gradient Descent, Best Trained Model\")\r\n plt.savefig(\"Best Model\")\r\n plt.show()\r\n\r\nif __name__ == \"__main__\":\r\n main()", "repo_name": "R-Sharma-coder/Backprop-from-scratch", "sub_path": "hw2.py", "file_name": "hw2.py", "file_ext": "py", "file_size_in_byte": 15775, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "numpy.genfromtxt", "line_number": 25, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 8, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 8, "usage_type": "attribute"}, {"api_name": "numpy.random.randn", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 64, "usage_type": "attribute"}, {"api_name": "numpy.random.randn", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 65, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 71, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 95, "usage_type": "attribute"}, {"api_name": "numpy.copy", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 143, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 165, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 206, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 208, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 214, "usage_type": "attribute"}, {"api_name": "tqdm.tqdm", "line_number": 245, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 214, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 214, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 269, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 269, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xscale", "line_number": 270, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 270, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 271, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 271, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 272, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 272, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 273, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 273, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 274, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 274, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 275, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 275, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 276, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 276, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 277, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 277, "usage_type": "name"}, {"api_name": "numpy.shape", "line_number": 287, "usage_type": "call"}, {"api_name": "numpy.genfromtxt", "line_number": 308, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 347, "usage_type": "call"}, {"api_name": "numpy.square", "line_number": 347, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 351, "usage_type": "call"}, {"api_name": "numpy.square", "line_number": 351, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 355, "usage_type": "call"}, {"api_name": "numpy.square", "line_number": 355, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 363, "usage_type": "call"}, {"api_name": "numpy.square", "line_number": 363, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 366, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 366, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xscale", "line_number": 367, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 367, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 368, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 368, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 369, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 369, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 370, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 370, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 371, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 371, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 372, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 372, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 373, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 373, "usage_type": "name"}]} +{"seq_id": "2158055723", "text": "import PyQt4\nfrom PyQt4.QtCore import Qt, QObject, SIGNAL, QUrl\nfrom PyQt4.QtGui import *\nfrom PyQt4 import Qsci\n\n\nfrom io import StringIO\nfrom urllib import parse as urlparse\nimport uuid\nimport re\nimport json\nimport os\n\nfrom actions import interface\nfrom utility import ScintillaHelpers\n\nfrom dialogs.RequestResponseDetailDialog import RequestResponseDetailDialog\n\nfrom core.database.constants import ResponsesTable\n\nfrom core.fuzzer.RequestRunner import RequestRunner\nfrom core.data import ResponsesDataModel\nfrom core.web.StandardPageFactory import StandardPageFactory\nfrom core.web.RenderingWebView import RenderingWebView\nfrom widgets.ResponsesContextMenuWidget import ResponsesContextMenuWidget\nfrom widgets.MiniResponseRenderWidget import MiniResponseRenderWidget\nfrom core.network.InMemoryCookieJar import InMemoryCookieJar\nfrom core.fuzzer import Payloads\nfrom dialogs import ConfirmDialog\n\nfrom core.fuzzer.TemplateDefinition import TemplateDefinition\nfrom core.fuzzer.TemplateItem import TemplateItem\n\nfrom utility.ScriptLoader import ScriptLoader\n\nclass WebFuzzerTab(QObject):\n def __init__(self, framework, mainWindow):\n QObject.__init__(self, mainWindow)\n self.framework = framework\n self.mainWindow = mainWindow\n \n self.mainWindow.wfStdPreChk.stateChanged.connect(self.handle_wfStdPreChk_stateChanged)\n self.mainWindow.wfStdPostChk.stateChanged.connect(self.handle_wfStdPostChk_stateChanged)\n self.mainWindow.wfTempSeqChk.stateChanged.connect(self.handle_wfTempSeqChk_stateChanged)\n \n # Handle the toggling of payload mappings in the config tab\n self.mainWindow.wfPay1FuzzRadio.toggled.connect(self.handle_payload_toggled)\n self.mainWindow.wfPay1StaticRadio.toggled.connect(self.handle_payload_toggled)\n self.mainWindow.wfPay1DynamicRadio.toggled.connect(self.handle_payload_toggled)\n self.mainWindow.wfPay2FuzzRadio.toggled.connect(self.handle_payload_toggled)\n self.mainWindow.wfPay2StaticRadio.toggled.connect(self.handle_payload_toggled)\n self.mainWindow.wfPay2DynamicRadio.toggled.connect(self.handle_payload_toggled)\n self.mainWindow.wfPay3FuzzRadio.toggled.connect(self.handle_payload_toggled)\n self.mainWindow.wfPay3StaticRadio.toggled.connect(self.handle_payload_toggled)\n self.mainWindow.wfPay3DynamicRadio.toggled.connect(self.handle_payload_toggled)\n self.mainWindow.wfPay4FuzzRadio.toggled.connect(self.handle_payload_toggled)\n self.mainWindow.wfPay4StaticRadio.toggled.connect(self.handle_payload_toggled)\n self.mainWindow.wfPay4DynamicRadio.toggled.connect(self.handle_payload_toggled)\n self.mainWindow.wfPay5FuzzRadio.toggled.connect(self.handle_payload_toggled)\n self.mainWindow.wfPay5StaticRadio.toggled.connect(self.handle_payload_toggled)\n self.mainWindow.wfPay5DynamicRadio.toggled.connect(self.handle_payload_toggled)\n\n self.mainWindow.fuzzerHistoryClearButton.clicked.connect(self.fuzzer_history_clear_button_clicked)\n \n # inserted to initially fill the sequences box.\n # ToDo: Need to do this better\n self.mainWindow.mainTabWidget.currentChanged.connect(self.handle_mainTabWidget_currentChanged)\n self.mainWindow.webFuzzTab.currentChanged.connect(self.handle_webFuzzTab_currentChanged)\n self.mainWindow.stdFuzzTab.currentChanged.connect(self.handle_stdFuzzTab_currentChanged)\n # self.mainWindow.webFuzzTab.currentChanged.connect(self.fill_payloads)\n self.mainWindow.wfStdAddButton.clicked.connect(self.insert_payload_marker)\n self.mainWindow.wfStdStartButton.clicked.connect(self.start_fuzzing_clicked)\n self.mainWindow.wfDataDictonaryAddButton.clicked.connect(self.handle_wfDataDictonaryAddButton_clicked)\n \n self.framework.subscribe_populate_webfuzzer_response_id(self.webfuzzer_populate_response_id)\n self.framework.subscribe_sequences_changed(self.fill_sequences)\n \n self.mainWindow.wfFunctionsComboBox.activated.connect(self.fill_function_edit)\n \n self.mainWindow.wfFunctionsSaveButton.clicked.connect(self.save_function_file)\n self.mainWindow.wfFunctionsDeleteButton.clicked.connect(self.del_function_file)\n \n self.miniResponseRenderWidget = MiniResponseRenderWidget(self.framework, self.mainWindow.stdFuzzResultsTabWidget, True, self)\n \n self.re_request = re.compile(r'^(\\S+)\\s+((?:https?://(?:\\S+\\.)+\\w+(?::\\d+)?)?/.*)\\s+HTTP/\\d+\\.\\d+\\s*$', re.I)\n self.re_request_cookie = re.compile(r'^Cookie:\\s*(\\S+)', re.I|re.M)\n self.re_replacement = re.compile(r'\\$\\{(\\w+)\\}')\n\n self.setup_fuzzer_tab()\n\n self.setup_functions_tab()\n \n self.functions_dir = os.path.join(self.framework.get_data_dir(), 'functions')\n \n self.Attacks = Payloads.Payloads(self.framework)\n self.Attacks.list_files()\n \n # Fill the payloads combo boxes on init\n self.fill_payloads()\n self.pending_fuzz_requests = None\n \n # Fill the functions combo box on init\n self.fill_function_combo_box()\n\n self.mainWindow.wfDataDictionaryDataTable.setColumnCount(2)\n self.mainWindow.wfDataDictionaryDataTable.setHorizontalHeaderLabels(['Replacement', 'Value'])\n\n self.Data = None\n self.cursor = None\n self.framework.subscribe_database_events(self.db_attach, self.db_detach)\n\n def db_attach(self):\n self.Data = self.framework.getDB()\n self.cursor = self.Data.allocate_thread_cursor()\n self.fill_fuzzers()\n self.fill_standard_edits()\n self.fill_config_edits()\n self.restore_data_dictionary()\n\n def db_detach(self):\n self.close_cursor()\n self.Data = None\n\n def close_cursor(self):\n if self.cursor and self.Data:\n self.cursor.close()\n self.Data.release_thread_cursor(self.cursor)\n self.cursor = None\n \n def setup_fuzzer_tab(self):\n\n self.fuzzerHistoryDataModel = ResponsesDataModel.ResponsesDataModel(self.framework, self)\n self.mainWindow.fuzzerHistoryTreeView.setModel(self.fuzzerHistoryDataModel)\n self.mainWindow.fuzzerHistoryTreeView.doubleClicked.connect(self.fuzzer_history_item_double_clicked)\n self.mainWindow.fuzzerHistoryTreeView.clicked.connect(self.handle_fuzzer_history_clicked)\n self.mainWindow.fuzzerHistoryTreeView.activated.connect(self.handle_fuzzer_history_clicked)\n self.responsesContextMenu = ResponsesContextMenuWidget(self.framework, self.fuzzerHistoryDataModel, self.mainWindow.fuzzerHistoryTreeView, self)\n self.responsesContextMenu.set_currentChanged_callback(self.fill_fuzzer_history)\n\n def setup_functions_tab(self):\n self.functionsLayout = self.mainWindow.wfFunctionsEditPlaceholder.layout()\n if not self.functionsLayout:\n self.functionsLayout = QVBoxLayout(self.mainWindow.wfFunctionsEditPlaceholder)\n self.functionsEditScintilla = Qsci.QsciScintilla(self.mainWindow.wfFunctionsEditPlaceholder)\n\n ScintillaHelpers.SetScintillaProperties(self.framework, self.functionsEditScintilla, 'python')\n self.functionsEditScintilla.setAutoIndent(True)\n self.functionsLayout.addWidget(self.functionsEditScintilla)\n self.framework.subscribe_zoom_in(self.edit_function_zoom_in)\n self.framework.subscribe_zoom_out(self.edit_function_zoom_out)\n\n def edit_function_zoom_in(self):\n self.functionsEditScintilla.zoomIn()\n\n def edit_function_zoom_out(self):\n self.functionsEditScintilla.zoomOut()\n\n def fill_fuzzers(self):\n history_items = []\n for row in self.Data.get_all_fuzzer_history(self.cursor):\n response_item = [m or '' for m in row]\n history_items.append(response_item)\n self.fuzzerHistoryDataModel.append_data(history_items)\n self.fill_sequences()\n\n def fill_standard_edits(self):\n self.mainWindow.wfStdUrlEdit.setText(self.framework.get_raft_config_value('WebFuzzer.Standard.RequestUrl'))\n self.mainWindow.wfStdEdit.document().setHtml(self.framework.get_raft_config_value('WebFuzzer.Standard.TemplateHtml'))\n index = self.mainWindow.stdFuzzerReqMethod.findText(self.framework.get_raft_config_value('WebFuzzer.Standard.Method'))\n if index != -1:\n self.mainWindow.stdFuzzerReqMethod.setCurrentIndex(index)\n\n self.mainWindow.wfStdPreChk.setChecked(self.framework.get_raft_config_value('WebFuzzer.Standard.PreSequenceEnabled', bool))\n index = self.mainWindow.wfStdPreBox.findText(self.framework.get_raft_config_value('WebFuzzer.Standard.PreSequenceId'))\n if index != -1:\n self.mainWindow.wfStdPreBox.setCurrentIndex(index)\n\n self.mainWindow.wfStdPostChk.setChecked(self.framework.get_raft_config_value('WebFuzzer.Standard.PostSequenceEnabled', bool))\n index = self.mainWindow.wfStdPostBox.findText(self.framework.get_raft_config_value('WebFuzzer.Standard.PostSequenceId'))\n if index != -1:\n self.mainWindow.wfStdPostBox.setCurrentIndex(index)\n\n def fill_config_edits(self):\n self.fill_config_edit_item('Payload1', self.mainWindow.wfPay1FuzzRadio, self.mainWindow.wfPay1PayloadBox, self.mainWindow.wfPay1StaticRadio, self.mainWindow.wfPay1DynamicRadio, self.mainWindow.wfPay1StaticEdit)\n self.fill_config_edit_item('Payload2', self.mainWindow.wfPay2FuzzRadio, self.mainWindow.wfPay2PayloadBox, self.mainWindow.wfPay2StaticRadio, self.mainWindow.wfPay2DynamicRadio, self.mainWindow.wfPay2StaticEdit)\n self.fill_config_edit_item('Payload3', self.mainWindow.wfPay3FuzzRadio, self.mainWindow.wfPay3PayloadBox, self.mainWindow.wfPay3StaticRadio, self.mainWindow.wfPay3DynamicRadio, self.mainWindow.wfPay3StaticEdit)\n self.fill_config_edit_item('Payload4', self.mainWindow.wfPay4FuzzRadio, self.mainWindow.wfPay4PayloadBox, self.mainWindow.wfPay4StaticRadio, self.mainWindow.wfPay4DynamicRadio, self.mainWindow.wfPay4StaticEdit)\n self.fill_config_edit_item('Payload5', self.mainWindow.wfPay5FuzzRadio, self.mainWindow.wfPay5PayloadBox, self.mainWindow.wfPay5StaticRadio, self.mainWindow.wfPay5DynamicRadio, self.mainWindow.wfPay5StaticEdit)\n \n def fill_config_edit_item(self, payload_item, fuzzRadio, payloadBox, staticRadio, dynamicRadio, staticEdit):\n fuzzRadio.setChecked(self.framework.get_raft_config_value('WebFuzzer.Config.{0}FuzzSelected'.format(payload_item), bool))\n index = payloadBox.findText(self.framework.get_raft_config_value('WebFuzzer.Config.{0}FuzzPayload'.format(payload_item)))\n if index != -1:\n payloadBox.setCurrentIndex(index)\n staticRadio.setChecked(self.framework.get_raft_config_value('WebFuzzer.Config.{0}StaticSelected'.format(payload_item), bool))\n dynamicRadio.setChecked(self.framework.get_raft_config_value('WebFuzzer.Config.{0}DynamicSelected'.format(payload_item), bool))\n staticEdit.setText(self.framework.get_raft_config_value('WebFuzzer.Config.{0}StaticEdit'.format(payload_item)))\n\n def fuzzer_history_item_double_clicked(self, index):\n Id = interface.index_to_id(self.fuzzerHistoryDataModel, index)\n if Id:\n dialog = RequestResponseDetailDialog(self.framework, Id, self.mainWindow)\n dialog.show()\n dialog.exec_()\n\n def handle_mainTabWidget_currentChanged(self):\n self.save_configuration_values()\n\n def handle_stdFuzzTab_currentChanged(self):\n self.save_standard_configuration()\n\n def handle_webFuzzTab_currentChanged(self):\n self.save_configuration_values()\n \n def fill_sequences(self):\n self.fill_sequences_combo_box(self.mainWindow.wfStdPreBox)\n self.fill_sequences_combo_box(self.mainWindow.wfStdPostBox)\n self.fill_sequences_combo_box(self.mainWindow.wfStdBox)\n \n def fill_sequences_combo_box(self, comboBox):\n selectedText = comboBox.currentText()\n\n comboBox.clear()\n for row in self.Data.get_all_sequences(self.cursor):\n sequenceItem = [m or '' for m in row]\n name = str(sequenceItem[1])\n Id = str(sequenceItem[0])\n item = comboBox.addItem(name, Id)\n\n if selectedText:\n index = comboBox.findText(selectedText)\n if index != -1:\n comboBox.setCurrentIndex(index)\n \n def fill_payloads(self):\n self.fill_payload_combo_box(self.mainWindow.wfPay1PayloadBox)\n self.fill_payload_combo_box(self.mainWindow.wfPay2PayloadBox)\n self.fill_payload_combo_box(self.mainWindow.wfPay3PayloadBox)\n self.fill_payload_combo_box(self.mainWindow.wfPay4PayloadBox)\n self.fill_payload_combo_box(self.mainWindow.wfPay5PayloadBox)\n \n def fill_payload_combo_box(self, comboBox):\n \n selectedText = comboBox.currentText()\n comboBox.clear()\n \n payloads = self.Attacks.list_files()\n for item in payloads:\n if item.startswith(\".\"):\n pass\n else:\n comboBox.addItem(item)\n \n def fill_payload_combo_box_function(self, comboBox):\n \n selectedText = comboBox.currentText()\n comboBox.clear()\n \n functions = self.Attacks.list_function_files()\n for item in functions:\n if item.startswith(\".\"):\n pass\n else:\n comboBox.addItem(item)\n \n \n def fill_function_combo_box(self):\n comboBox = self.mainWindow.wfFunctionsComboBox\n comboBox.clear()\n \n functions = self.Attacks.list_function_files()\n for item in functions:\n if item.startswith(\".\"):\n pass\n else:\n comboBox.addItem(item)\n \n def fill_function_edit(self):\n \n filename = self.mainWindow.wfFunctionsComboBox.currentText()\n \n func = self.Attacks.read_function(filename)\n \n # Clear the Scintilla widget\n self.functionsEditScintilla.clear()\n \n for line in func:\n self.functionsEditScintilla.append(line.decode(\"utf8\"))\n \n def save_function_file(self):\n \n function_file = self.mainWindow.wfFunctionsComboBox.currentText()\n content = self.functionsEditScintilla.text()\n \n self.Attacks.save_function(function_file, content)\n \n \n def del_function_file(self):\n \n # Gets the current name of the file selected in the combobox\n filename = self.mainWindow.wfFunctionsComboBox.currentText()\n path = self.functions_dir\n \n message = \"Are you sure you want to delete: {0}\".format(filename)\n \n response = ConfirmDialog.display_confirm_dialog(self.mainWindow, message)\n \n if response == True:\n os.remove(os.path.join(path,filename))\n \n self.fill_function_combo_box()\n \n # Clear the items from the scintilla widget\n #ToDo: This should be the default data for the function\n self.functionsEditScintilla.clear()\n \n \n def create_payload_map(self):\n # create payload map from configuration tab\n \n payload_mapping = {}\n\n payload_config_items = (\n (\"payload_1\", \n \"fuzz\", self.mainWindow.wfPay1FuzzRadio, self.mainWindow.wfPay1PayloadBox,\n \"static\", self.mainWindow.wfPay1StaticRadio, self.mainWindow.wfPay1StaticEdit,\n \"dynamic\", self.mainWindow.wfPay1DynamicRadio, self.mainWindow.wfPay1StaticEdit,\n ),\n (\"payload_2\", \n \"fuzz\", self.mainWindow.wfPay2FuzzRadio, self.mainWindow.wfPay2PayloadBox,\n \"static\", self.mainWindow.wfPay2StaticRadio, self.mainWindow.wfPay2StaticEdit,\n \"dynamic\", self.mainWindow.wfPay2DynamicRadio, self.mainWindow.wfPay2StaticEdit,\n ),\n (\"payload_3\", \n \"fuzz\", self.mainWindow.wfPay3FuzzRadio, self.mainWindow.wfPay3PayloadBox,\n \"static\", self.mainWindow.wfPay3StaticRadio, self.mainWindow.wfPay3StaticEdit,\n \"dynamic\", self.mainWindow.wfPay3DynamicRadio, self.mainWindow.wfPay3StaticEdit,\n ),\n (\"payload_4\", \n \"fuzz\", self.mainWindow.wfPay4FuzzRadio, self.mainWindow.wfPay4PayloadBox,\n \"static\", self.mainWindow.wfPay4StaticRadio, self.mainWindow.wfPay4StaticEdit,\n \"dynamic\", self.mainWindow.wfPay4DynamicRadio, self.mainWindow.wfPay4StaticEdit,\n ),\n (\"payload_5\", \n \"fuzz\", self.mainWindow.wfPay5FuzzRadio, self.mainWindow.wfPay5PayloadBox,\n \"static\", self.mainWindow.wfPay5StaticRadio, self.mainWindow.wfPay5StaticEdit,\n \"dynamic\", self.mainWindow.wfPay5DynamicRadio, self.mainWindow.wfPay5StaticEdit,\n ),\n )\n \n # Determine active payloads and map them\n for config_item in payload_config_items:\n payload_item = config_item[0]\n payload_mapping[payload_item] = ('none', '')\n for offset in (1, 4, 7):\n if config_item[offset+1].isChecked():\n payload_type = config_item[offset]\n# print((payload_type, offset))\n if payload_type == \"dynamic\":\n payload_mapping[payload_item] = (payload_type, str(config_item[offset+2].text()), config_item[3].currentText())\n elif payload_type == \"fuzz\":\n payload_mapping[payload_item] = (payload_type, str(config_item[offset+2].currentText()), '')\n else:\n payload_mapping[payload_item] = (payload_type, str(config_item[offset+2].text()), '')\n break\n\n return payload_mapping\n\n def create_functions(self):\n self.global_ns = self.local_ns = {} \n functions = [\n'''\nimport urllib.parse\nimport re\nimport random\n\ndef url_encode(input):\n return urllib.parse.quote(input)\n\nre_alert_mangler = re.compile(r'alert\\([^(]+\\)', re.I)\n\ndef randomize_alert_replace(m):\n return 'alert(%d.%d)' % (random.randint(0,99999), random.randint(0,99999))\n\ndef randomize_alert(input):\n return re_alert_mangler.sub(randomize_alert_replace, input)\n'''\n]\n for func_str in functions:\n compiled = compile(func_str, '', 'exec')\n exec(compiled, self.global_ns, self.local_ns)\n \n def set_combo_box_text(self, comboBox, selectedText):\n index = comboBox.findText(selectedText)\n if -1 != index:\n comboBox.setCurrentIndex(index)\n else:\n index = comboBox.addItem(selectedText)\n comboBox.setCurrentIndex(index)\n \n def handle_wfStdPreChk_stateChanged(self, state):\n self.mainWindow.wfStdPreBox.setEnabled(self.mainWindow.wfStdPreChk.isChecked())\n \n def handle_wfStdPostChk_stateChanged(self, state):\n self.mainWindow.wfStdPostBox.setEnabled(self.mainWindow.wfStdPostChk.isChecked())\n \n def handle_wfTempSeqChk_stateChanged(self, state):\n self.mainWindow.wfStdBox.setEnabled(self.mainWindow.wfTempSeqChk.isChecked())\n \n def handle_payload_toggled(self):\n self.mainWindow.wfPay1PayloadBox.setEnabled(self.mainWindow.wfPay1FuzzRadio.isChecked() or self.mainWindow.wfPay1DynamicRadio.isChecked())\n self.mainWindow.wfPay1StaticEdit.setEnabled(self.mainWindow.wfPay1StaticRadio.isChecked() or self.mainWindow.wfPay1DynamicRadio.isChecked())\n # self.mainWindow.wfPay1PayloadBox.setEnabled(self.mainWindow.wfPay1DynamicRadio.isChecked()) or self.fill_payload_combo_box_function(self.mainWindow.wfPay1PayloadBox)\n self.mainWindow.wfPay2PayloadBox.setEnabled(self.mainWindow.wfPay2FuzzRadio.isChecked() or self.mainWindow.wfPay2DynamicRadio.isChecked())\n self.mainWindow.wfPay2StaticEdit.setEnabled(self.mainWindow.wfPay2StaticRadio.isChecked() or self.mainWindow.wfPay2DynamicRadio.isChecked()) \n self.mainWindow.wfPay3PayloadBox.setEnabled(self.mainWindow.wfPay3FuzzRadio.isChecked() or self.mainWindow.wfPay3DynamicRadio.isChecked())\n self.mainWindow.wfPay3StaticEdit.setEnabled(self.mainWindow.wfPay3StaticRadio.isChecked() or self.mainWindow.wfPay3DynamicRadio.isChecked()) \n self.mainWindow.wfPay4PayloadBox.setEnabled(self.mainWindow.wfPay4FuzzRadio.isChecked() or self.mainWindow.wfPay4DynamicRadio.isChecked())\n self.mainWindow.wfPay4StaticEdit.setEnabled(self.mainWindow.wfPay4StaticRadio.isChecked() or self.mainWindow.wfPay4DynamicRadio.isChecked()) \n self.mainWindow.wfPay5PayloadBox.setEnabled(self.mainWindow.wfPay5FuzzRadio.isChecked() or self.mainWindow.wfPay5DynamicRadio.isChecked())\n self.mainWindow.wfPay5StaticEdit.setEnabled(self.mainWindow.wfPay5StaticRadio.isChecked() or self.mainWindow.wfPay5DynamicRadio.isChecked()) \n \n # Determine if fuzz or dynamic is selected and change combo box items\n if self.mainWindow.wfPay1FuzzRadio.isChecked():\n self.fill_payload_combo_box(self.mainWindow.wfPay1PayloadBox)\n if self.mainWindow.wfPay1DynamicRadio.isChecked():\n self.fill_payload_combo_box_function(self.mainWindow.wfPay1PayloadBox)\n if self.mainWindow.wfPay2FuzzRadio.isChecked():\n self.fill_payload_combo_box(self.mainWindow.wfPay2PayloadBox)\n if self.mainWindow.wfPay2DynamicRadio.isChecked():\n self.fill_payload_combo_box_function(self.mainWindow.wfPay2PayloadBox)\n if self.mainWindow.wfPay3FuzzRadio.isChecked():\n self.fill_payload_combo_box(self.mainWindow.wfPay3PayloadBox)\n if self.mainWindow.wfPay3DynamicRadio.isChecked():\n self.fill_payload_combo_box_function(self.mainWindow.wfPay3PayloadBox)\n if self.mainWindow.wfPay4FuzzRadio.isChecked():\n self.fill_payload_combo_box(self.mainWindow.wfPay4PayloadBox)\n if self.mainWindow.wfPay4DynamicRadio.isChecked():\n self.fill_payload_combo_box_function(self.mainWindow.wfPay4PayloadBox)\n if self.mainWindow.wfPay5FuzzRadio.isChecked():\n self.fill_payload_combo_box(self.mainWindow.wfPay5PayloadBox)\n if self.mainWindow.wfPay5DynamicRadio.isChecked():\n self.fill_payload_combo_box_function(self.mainWindow.wfPay5PayloadBox)\n \n\n def handle_fuzzer_history_clicked(self):\n index = self.mainWindow.fuzzerHistoryTreeView.currentIndex()\n self.fill_fuzzer_history(index)\n\n def fill_fuzzer_history(self, index):\n Id = interface.index_to_id(self.fuzzerHistoryDataModel, index)\n if Id:\n row = self.Data.read_responses_by_id(self.cursor, Id)\n if not row:\n return\n responseItems = interface.data_row_to_response_items(row)\n url = responseItems[ResponsesTable.URL]\n reqHeaders = responseItems[ResponsesTable.REQ_HEADERS]\n reqData = responseItems[ResponsesTable.REQ_DATA]\n resHeaders = responseItems[ResponsesTable.RES_HEADERS]\n resData = responseItems[ResponsesTable.RES_DATA]\n contentType = responseItems[ResponsesTable.RES_CONTENT_TYPE]\n self.miniResponseRenderWidget.populate_response_content(url, reqHeaders, reqData, resHeaders, resData, contentType)\n\n def webfuzzer_populate_response_id(self, Id):\n\n self.clear_data_dictionary()\n \n row = self.Data.read_responses_by_id(self.cursor, Id)\n if not row:\n return\n\n responseItems = interface.data_row_to_response_items(row)\n\n url = responseItems[ResponsesTable.URL]\n reqHeaders = responseItems[ResponsesTable.REQ_HEADERS].decode('utf-8', 'ignore')\n reqData = responseItems[ResponsesTable.REQ_DATA].decode('utf-8', 'ignore')\n method = responseItems[ResponsesTable.REQ_METHOD]\n splitted = urlparse.urlsplit(url)\n \n # Create a new parsed object removing the scheme and netloc\n base_url = urlparse.urlunsplit((splitted[0], splitted[1], splitted[2], '', ''))\n req_loc = (\"\", \"\", \"\", splitted.query, splitted.fragment)\n\n useragent = self.framework.useragent()\n has_cookie = False\n template = StringIO()\n template.write('${method} ${request_uri}%s HTTP/1.1\\n' % urlparse.urlunsplit(req_loc))\n first = True\n for line in reqHeaders.splitlines():\n if not line:\n break\n if first and self.re_request.match(line):\n first = False\n continue\n if ':' in line:\n name, value = [v.strip() for v in line.split(':', 1)]\n lname = name.lower()\n if 'host' == lname:\n if splitted.hostname and value == splitted.hostname:\n template.write('Host: ${host}\\n')\n continue\n elif 'user-agent' == lname:\n if useragent == value:\n template.write('User-Agent: ${user_agent}\\n')\n continue\n template.write(line)\n template.write('\\n')\n template.write('\\n')\n template.write(reqData)\n\n self.set_combo_box_text(self.mainWindow.stdFuzzerReqMethod, method.upper())\n self.mainWindow.wfStdUrlEdit.setText(base_url)\n self.mainWindow.wfStdEdit.setPlainText(template.getvalue())\n \n def insert_payload_marker(self):\n \"\"\" Inserts a payload marker at current cursor position \"\"\"\n \n index = self.mainWindow.stdFuzzPayloadBox.currentIndex()\n curPayload = str(self.mainWindow.stdFuzzPayloadBox.itemText(index))\n currentText = self.mainWindow.wfStdEdit.textCursor().selectedText()\n \n self.store_in_data_dictionary(curPayload, currentText)\n self.mainWindow.wfStdEdit.textCursor().insertHtml(\"${%s}\" % curPayload)\n self.save_configuration_values()\n\n def clear_data_dictionary(self):\n tableWidget = self.mainWindow.wfDataDictionaryDataTable\n while tableWidget.rowCount() > 0:\n tableWidget.removeRow(0)\n self.save_data_dictionary_to_config()\n\n def store_in_data_dictionary(self, replacement, value):\n # TODO: currently logic allows for duplicate values to appear\n tableWidget = self.mainWindow.wfDataDictionaryDataTable\n row = tableWidget.rowCount()\n tableWidget.insertRow(row)\n tableWidget.setItem(row, 0, QTableWidgetItem(replacement))\n tableWidget.setItem(row, 1, QTableWidgetItem(value))\n self.save_data_dictionary_to_config()\n\n def save_data_dictionary_to_config(self):\n ddict = self.get_values_from_data_dictionary()\n dd_data = json.dumps(ddict)\n self.framework.set_raft_config_value('WebFuzzer.Standard.DataDictionary', dd_data)\n\n def restore_data_dictionary(self):\n dd_data = self.framework.get_raft_config_value('WebFuzzer.Standard.DataDictionary', '')\n if dd_data:\n tableWidget = self.mainWindow.wfDataDictionaryDataTable\n obj = json.loads(dd_data)\n for name, value in obj.items():\n row = tableWidget.rowCount()\n tableWidget.insertRow(row)\n tableWidget.setItem(row, 0, QTableWidgetItem(name))\n tableWidget.setItem(row, 1, QTableWidgetItem(value))\n \n def get_values_from_data_dictionary(self):\n tableWidget = self.mainWindow.wfDataDictionaryDataTable\n ddict = {}\n for rindex in range(0, tableWidget.rowCount()):\n name = tableWidget.item(rindex, 0).text()\n value = tableWidget.item(rindex, 1).text()\n ddict[name] = value\n\n return ddict\n\n def handle_wfDataDictonaryAddButton_clicked(self):\n name = self.mainWindow.wfDataDictionaryDataName.text()\n value = self.mainWindow.wfDataDictionaryDataValue.text()\n self.store_in_data_dictionary(name, value)\n\n def save_configuration_values(self):\n self.save_standard_configuration()\n self.save_config_configuration()\n\n def save_standard_configuration(self):\n url = str(self.mainWindow.wfStdUrlEdit.text())\n templateHtml = str(self.mainWindow.wfStdEdit.document().toHtml())\n method = str(self.mainWindow.stdFuzzerReqMethod.currentText())\n\n self.framework.set_raft_config_value('WebFuzzer.Standard.RequestUrl', url)\n self.framework.set_raft_config_value('WebFuzzer.Standard.TemplateHtml', templateHtml)\n self.framework.set_raft_config_value('WebFuzzer.Standard.Method', method)\n\n self.framework.set_raft_config_value('WebFuzzer.Standard.PreSequenceEnabled', self.mainWindow.wfStdPreChk.isChecked())\n self.framework.set_raft_config_value('WebFuzzer.Standard.PreSequenceId', self.mainWindow.wfStdPreBox.itemData(self.mainWindow.wfStdPreBox.currentIndex()))\n\n self.framework.set_raft_config_value('WebFuzzer.Standard.PostSequenceEnabled', self.mainWindow.wfStdPostChk.isChecked())\n self.framework.set_raft_config_value('WebFuzzer.Standard.PostSequenceId', self.mainWindow.wfStdPostBox.itemData(self.mainWindow.wfStdPostBox.currentIndex()))\n\n def save_config_configuration(self):\n self.save_config_configuration_item('Payload1', self.mainWindow.wfPay1FuzzRadio, self.mainWindow.wfPay1PayloadBox, self.mainWindow.wfPay1StaticRadio, self.mainWindow.wfPay1DynamicRadio, self.mainWindow.wfPay1StaticEdit)\n self.save_config_configuration_item('Payload2', self.mainWindow.wfPay2FuzzRadio, self.mainWindow.wfPay2PayloadBox, self.mainWindow.wfPay2StaticRadio, self.mainWindow.wfPay2DynamicRadio, self.mainWindow.wfPay2StaticEdit)\n self.save_config_configuration_item('Payload3', self.mainWindow.wfPay3FuzzRadio, self.mainWindow.wfPay3PayloadBox, self.mainWindow.wfPay3StaticRadio, self.mainWindow.wfPay3DynamicRadio, self.mainWindow.wfPay3StaticEdit)\n self.save_config_configuration_item('Payload4', self.mainWindow.wfPay4FuzzRadio, self.mainWindow.wfPay4PayloadBox, self.mainWindow.wfPay4StaticRadio, self.mainWindow.wfPay4DynamicRadio, self.mainWindow.wfPay4StaticEdit)\n self.save_config_configuration_item('Payload5', self.mainWindow.wfPay5FuzzRadio, self.mainWindow.wfPay5PayloadBox, self.mainWindow.wfPay5StaticRadio, self.mainWindow.wfPay5DynamicRadio, self.mainWindow.wfPay5StaticEdit)\n\n def save_config_configuration_item(self, payload_item, fuzzRadio, payloadBox, staticRadio, dynamicRadio, staticEdit):\n self.framework.set_raft_config_value('WebFuzzer.Config.{0}FuzzSelected'.format(payload_item), fuzzRadio.isChecked())\n self.framework.set_raft_config_value('WebFuzzer.Config.{0}FuzzPayload'.format(payload_item), str(payloadBox.currentText()))\n self.framework.set_raft_config_value('WebFuzzer.Config.{0}StaticSelected'.format(payload_item), staticRadio.isChecked())\n self.framework.set_raft_config_value('WebFuzzer.Config.{0}DynamicSelected'.format(payload_item), dynamicRadio.isChecked())\n self.framework.set_raft_config_value('WebFuzzer.Config.{0}StaticEdit'.format(payload_item), staticEdit.text())\n \n def start_fuzzing_clicked(self):\n \"\"\" Start the fuzzing attack \"\"\"\n\n if 'Cancel' == self.mainWindow.wfStdStartButton.text() and self.pending_fuzz_requests is not None:\n self.cancel_fuzz_requests = True\n for context, pending_request in self.pending_fuzz_requests.items():\n pending_request.cancel()\n self.pending_fuzz_requests = None\n self.mainWindow.wfStdStartButton.setText('Start Attack')\n self.mainWindow.fuzzerStandardProgressBar.setValue(0)\n return\n \n self.pending_fuzz_requests = {}\n \n url = str(self.mainWindow.wfStdUrlEdit.text())\n templateText = str(self.mainWindow.wfStdEdit.toPlainText())\n method = str(self.mainWindow.stdFuzzerReqMethod.currentText())\n\n self.save_standard_configuration()\n \n replacements = self.build_replacements(method, url)\n\n sequenceId = None\n if self.mainWindow.wfStdPreChk.isChecked():\n sequenceId = self.mainWindow.wfStdPreBox.itemData(self.mainWindow.wfStdPreBox.currentIndex())\n\n postSequenceId = None\n if self.mainWindow.wfStdPostChk.isChecked():\n postSequenceId = self.mainWindow.wfStdPostBox.itemData(self.mainWindow.wfStdPostBox.currentIndex())\n \n # Fuzzing stuff\n payload_mapping = self.create_payload_map()\n# print(payload_mapping)\n self.create_functions()\n \n template_definition = TemplateDefinition(templateText)\n\n template_items = template_definition.template_items\n### print(template_items)\n parameter_names = template_definition.parameter_names\n\n self.global_ns = self.local_ns = {}\n scriptLoader = ScriptLoader()\n\n errors = []\n fuzz_payloads = {}\n for name, payload_info in payload_mapping.items():\n if name in parameter_names:\n payload_type, payload_value, payload_file = payload_info\n if 'fuzz' == payload_type:\n filename = payload_value\n values = self.Attacks.read_data(filename)\n fuzz_payloads[name] = values\n elif 'dynamic' == payload_type:\n target = payload_file\n # TODO: should this come from saved file or current Scintilla values (?)\n script_env = scriptLoader.load_from_file(os.path.join(self.functions_dir, target), self.global_ns, self.local_ns)\n expression = payload_value\n if not expression.endswith('()'):\n expression += '()'\n eval_result = eval(expression, self.global_ns, self.local_ns)\n fuzz_payloads[name] = [str(v) for v in eval_result]\n elif 'static' == payload_type:\n pass\n elif 'none' == payload_type:\n # unconfigured payload\n errors.append(name)\n \n test_slots = []\n counters = []\n tests_count = []\n total_tests = 1\n \n for name, payload_info in payload_mapping.items():\n if name in parameter_names:\n payload_type, payload_value, payload_file = payload_info\n if 'static' == payload_type:\n # static payload value\n payloads = [payload_value]\n elif 'fuzz' == payload_type:\n payloads = fuzz_payloads[name]\n elif 'dynamic' == payload_type:\n payloads = fuzz_payloads[name]\n\n total_tests *= len(payloads)\n test_slots.append((name, payloads))\n counters.append(0)\n tests_count.append(len(payloads))\n \n position_end = len(counters) - 1\n position = position_end\n\n self.miniResponseRenderWidget.clear_response_render()\n self.mainWindow.fuzzerStandardProgressBar.setValue(0)\n self.mainWindow.fuzzerStandardProgressBar.setMaximum(total_tests)\n \n finished = False\n first = True\n while not finished:\n data = {}\n for j in range(0, len(test_slots)):\n name, payloads = test_slots[j]\n data[name] = payloads[counters[j]]\n \n template_io = StringIO()\n self.apply_template_parameters(template_io, data, template_items)\n \n templateText = template_io.getvalue()\n context = uuid.uuid4().hex\n # print('%s%s%s' % ('-'*32, request, '-'*32))\n use_global_cookie_jar = self.mainWindow.webFuzzerUseGlobalCookieJar.isChecked()\n (method, url, headers, body) = self.process_template(url, templateText, replacements)\n \n if first:\n self.mainWindow.wfStdStartButton.setText('Cancel')\n if use_global_cookie_jar:\n self.fuzzRequesterCookieJar = self.framework.get_global_cookie_jar()\n else:\n self.fuzzRequesterCookieJar = InMemoryCookieJar(self.framework, self)\n self.requestRunner = RequestRunner(self.framework, self)\n self.requestRunner.setup(self.fuzzer_response_received, self.fuzzRequesterCookieJar, sequenceId, postSequenceId)\n first = False\n\n self.pending_fuzz_requests[context] = self.requestRunner.queue_request(method, url, headers, body, context)\n \n # increment to next test\n counters[position] = (counters[position] + 1) % (tests_count[position])\n while position >= 0 and counters[position] == 0:\n position -= 1\n counters[position] = (counters[position] + 1) % (tests_count[position])\n \n if position == -1:\n finished = True\n else:\n position = position_end \n\n def apply_template_parameters(self, template_io, data, template_items):\n\n for item in template_items:\n if item.is_text():\n template_io.write(item.item_value)\n elif item.is_builtin():\n template_io.write('${'+item.item_value+'}')\n elif item.is_payload():\n template_io.write(data[item.item_value])\n elif item.is_function():\n temp_io = StringIO()\n self.apply_template_parameters(temp_io, data, item.items)\n temp_result = temp_io.getvalue()\n temp_io = None\n result = eval('%s(%s)' % (item.item_value, repr(temp_result)), self.global_ns, self.local_ns)\n template_io.write(str(result))\n else:\n raise Exception('unsupported template parameters: ' + repr(item))\n \n def build_replacements(self, method, url):\n replacements = {}\n splitted = urlparse.urlsplit(url)\n replacements['method'] = method.upper()\n replacements['url'] = url\n replacements['scheme'] = splitted.scheme or ''\n replacements['netloc'] = splitted.netloc or ''\n replacements['host'] = splitted.hostname or ''\n replacements['path'] = splitted.path or ''\n replacements['query'] = splitted.query or ''\n replacements['fragment'] = splitted.fragment or ''\n replacements['request_uri'] = url\n replacements['user_agent'] = self.framework.useragent()\n return replacements\n\n def process_template(self, url, template, replacements):\n \n # Start of old\n method, uri = '' ,''\n headers, body = '', ''\n\n # TODO: this allows for missing entries -- is this good?\n func = lambda m: replacements.get(m.group(1))\n\n prev = 0\n while True:\n n = template.find('\\n', prev)\n if -1 == n:\n break\n if n > 0 and '\\r' == template[n-1]:\n line = template[prev:n-1]\n else:\n line = template[prev:n]\n\n if 0 == len(line):\n # end of headers\n headers = template[0:n+1]\n body = template[n+1:]\n break\n prev = n + 1\n\n if not headers:\n headers = template\n body = ''\n \n # TODO: could work from ordered dict to main order?\n headers_dict = {}\n first = True\n for line in headers.splitlines():\n# print(line)\n if not line:\n break\n if '$' in line:\n line = self.re_replacement.sub(func, line)\n if first:\n m = self.re_request.match(line)\n if not m:\n raise Exception('Invalid HTTP request: failed to match request line: %s' % (line))\n method = m.group(1)\n uri = m.group(2)\n first = False\n continue\n\n if ':' in line:\n name, value = [v.strip() for v in line.split(':', 1)]\n headers_dict[name] = value\n \n if '$' in body:\n body = self.re_replacement.sub(func, body)\n\n url = urlparse.urljoin(url, uri)\n\n return (method, url, headers_dict, body)\n \n def fuzzer_history_clear_button_clicked(self):\n self.Data.clear_fuzzer_history(self.cursor)\n self.fuzzerHistoryDataModel.clearModel()\n\n def fuzzer_response_received(self, response_id, context):\n self.mainWindow.fuzzerStandardProgressBar.setValue(self.mainWindow.fuzzerStandardProgressBar.value()+1)\n context = str(context)\n if self.pending_fuzz_requests is not None:\n try:\n self.pending_fuzz_requests.pop(context)\n except KeyError as e:\n pass\n if 0 != response_id:\n row = self.Data.read_responses_by_id(self.cursor, response_id)\n if row:\n response_item = [m or '' for m in row]\n self.Data.insert_fuzzer_history(self.cursor, response_id)\n self.fuzzerHistoryDataModel.append_data([response_item])\n\n finished = False\n if self.pending_fuzz_requests is None or len(self.pending_fuzz_requests) == 0:\n self.mainWindow.fuzzerStandardProgressBar.setValue(self.mainWindow.fuzzerStandardProgressBar.maximum())\n finished = True\n elif self.mainWindow.fuzzerStandardProgressBar.value() == self.mainWindow.fuzzerStandardProgressBar.maximum():\n finished = True\n if finished:\n self.mainWindow.wfStdStartButton.setText('Start Attack')\n \n", "repo_name": "Averroes/raft", "sub_path": "tabs/WebFuzzerTab.py", "file_name": "WebFuzzerTab.py", "file_ext": "py", "file_size_in_byte": 42026, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 24, "dataset": "github-code", "pt": "27", "api": [{"api_name": "PyQt4.QtCore.QObject", "line_number": 36, "usage_type": "name"}, {"api_name": "PyQt4.QtCore.QObject.__init__", "line_number": 38, "usage_type": "call"}, {"api_name": "PyQt4.QtCore.QObject", "line_number": 38, "usage_type": "name"}, {"api_name": "widgets.MiniResponseRenderWidget.MiniResponseRenderWidget", "line_number": 83, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 85, "usage_type": "call"}, {"api_name": "re.I", "line_number": 85, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 86, "usage_type": "call"}, {"api_name": "re.I", "line_number": 86, "usage_type": "attribute"}, {"api_name": "re.M", "line_number": 86, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 93, "usage_type": "call"}, {"api_name": "os.path", "line_number": 93, "usage_type": "attribute"}, {"api_name": "core.fuzzer.Payloads.Payloads", "line_number": 95, "usage_type": "call"}, {"api_name": "core.fuzzer.Payloads", "line_number": 95, "usage_type": "name"}, {"api_name": "core.data.ResponsesDataModel.ResponsesDataModel", "line_number": 132, "usage_type": "call"}, {"api_name": "core.data.ResponsesDataModel", "line_number": 132, "usage_type": "name"}, {"api_name": "widgets.ResponsesContextMenuWidget.ResponsesContextMenuWidget", "line_number": 137, "usage_type": "call"}, {"api_name": "PyQt4.Qsci.QsciScintilla", "line_number": 144, "usage_type": "call"}, {"api_name": "PyQt4.Qsci", "line_number": 144, "usage_type": "name"}, {"api_name": "utility.ScintillaHelpers.SetScintillaProperties", "line_number": 146, "usage_type": "call"}, {"api_name": "utility.ScintillaHelpers", "line_number": 146, "usage_type": "name"}, {"api_name": "actions.interface.index_to_id", "line_number": 200, "usage_type": "call"}, {"api_name": "actions.interface", "line_number": 200, "usage_type": "name"}, {"api_name": "dialogs.RequestResponseDetailDialog.RequestResponseDetailDialog", "line_number": 202, "usage_type": "call"}, {"api_name": "dialogs.ConfirmDialog.display_confirm_dialog", "line_number": 306, "usage_type": "call"}, {"api_name": "dialogs.ConfirmDialog", "line_number": 306, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 309, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 309, "usage_type": "call"}, {"api_name": "os.path", "line_number": 309, "usage_type": "attribute"}, {"api_name": "actions.interface.index_to_id", "line_number": 451, "usage_type": "call"}, {"api_name": "actions.interface", "line_number": 451, "usage_type": "name"}, {"api_name": "actions.interface.data_row_to_response_items", "line_number": 456, "usage_type": "call"}, {"api_name": "actions.interface", "line_number": 456, "usage_type": "name"}, {"api_name": "core.database.constants.ResponsesTable.URL", "line_number": 457, "usage_type": "attribute"}, {"api_name": "core.database.constants.ResponsesTable", "line_number": 457, "usage_type": "name"}, {"api_name": "core.database.constants.ResponsesTable.REQ_HEADERS", "line_number": 458, "usage_type": "attribute"}, {"api_name": "core.database.constants.ResponsesTable", "line_number": 458, "usage_type": "name"}, {"api_name": "core.database.constants.ResponsesTable.REQ_DATA", "line_number": 459, "usage_type": "attribute"}, {"api_name": "core.database.constants.ResponsesTable", "line_number": 459, "usage_type": "name"}, {"api_name": "core.database.constants.ResponsesTable.RES_HEADERS", "line_number": 460, "usage_type": "attribute"}, {"api_name": "core.database.constants.ResponsesTable", "line_number": 460, "usage_type": "name"}, {"api_name": "core.database.constants.ResponsesTable.RES_DATA", "line_number": 461, "usage_type": "attribute"}, {"api_name": "core.database.constants.ResponsesTable", "line_number": 461, "usage_type": "name"}, {"api_name": "core.database.constants.ResponsesTable.RES_CONTENT_TYPE", "line_number": 462, "usage_type": "attribute"}, {"api_name": "core.database.constants.ResponsesTable", "line_number": 462, "usage_type": "name"}, {"api_name": "actions.interface.data_row_to_response_items", "line_number": 473, "usage_type": "call"}, {"api_name": "actions.interface", "line_number": 473, "usage_type": "name"}, {"api_name": "core.database.constants.ResponsesTable.URL", "line_number": 475, "usage_type": "attribute"}, {"api_name": "core.database.constants.ResponsesTable", "line_number": 475, "usage_type": "name"}, {"api_name": "core.database.constants.ResponsesTable.REQ_HEADERS", "line_number": 476, "usage_type": "attribute"}, {"api_name": "core.database.constants.ResponsesTable", "line_number": 476, "usage_type": "name"}, {"api_name": "core.database.constants.ResponsesTable.REQ_DATA", "line_number": 477, "usage_type": "attribute"}, {"api_name": "core.database.constants.ResponsesTable", "line_number": 477, "usage_type": "name"}, {"api_name": "core.database.constants.ResponsesTable.REQ_METHOD", "line_number": 478, "usage_type": "attribute"}, {"api_name": "core.database.constants.ResponsesTable", "line_number": 478, "usage_type": "name"}, {"api_name": "urllib.parse.urlsplit", "line_number": 479, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 479, "usage_type": "name"}, {"api_name": "urllib.parse.urlunsplit", "line_number": 482, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 482, "usage_type": "name"}, {"api_name": "io.StringIO", "line_number": 487, "usage_type": "call"}, {"api_name": "urllib.parse.urlunsplit", "line_number": 488, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 488, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 544, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 551, "usage_type": "call"}, {"api_name": "core.fuzzer.TemplateDefinition.TemplateDefinition", "line_number": 641, "usage_type": "call"}, {"api_name": "utility.ScriptLoader.ScriptLoader", "line_number": 648, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 662, "usage_type": "call"}, {"api_name": "os.path", "line_number": 662, "usage_type": "attribute"}, {"api_name": "io.StringIO", "line_number": 710, "usage_type": "call"}, {"api_name": "uuid.uuid4", "line_number": 714, "usage_type": "call"}, {"api_name": "core.network.InMemoryCookieJar.InMemoryCookieJar", "line_number": 724, "usage_type": "call"}, {"api_name": "core.fuzzer.RequestRunner.RequestRunner", "line_number": 725, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 752, "usage_type": "call"}, {"api_name": "urllib.parse.urlsplit", "line_number": 763, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 763, "usage_type": "name"}, {"api_name": "urllib.parse.urljoin", "line_number": 831, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 831, "usage_type": "name"}]} +{"seq_id": "31934790075", "text": "# To change this template, choose Tools | Templates\n# and open the template in the editor.\n\n__author__=\"naved\"\n__date__ =\"$22 Jun, 2010 1:32:06 PM$\"\n\nfrom utils.callback import Callback\ncb = Callback()\n\ndef unique_list(l):\n ulist = []\n [ulist.append(x) for x in l if x not in ulist]\n return ulist\n\ndef get_callback(request):\n if request.GET:\n data_id = request.GET['data_id'].split('+')\n else:\n data_id = request.POST['data_id'].split('+')\n func = cb._registry[data_id[0]]\n return func(request)\n", "repo_name": "spicavigo/cineight", "sub_path": "utils/ajax.py", "file_name": "ajax.py", "file_ext": "py", "file_size_in_byte": 530, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "2", "api": [{"api_name": "utils.callback.Callback", "line_number": 8, "usage_type": "call"}]} +{"seq_id": "36936161820", "text": "#-*- coding=utf-8 -*-\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nif __name__ == '__main__':\n head = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36'\n }\n url = 'https://www.shicimingju.com/book/sanguoyanyi.html'\n page_text = requests.get(url=url,headers=head).text\n soup = BeautifulSoup(page_text,'lxml')\n li_list = soup.select('.book-mulu > ul >li')\n fp = open('三国演义.txt', 'w', encoding='utf-8')\n for li in li_list:\n name = li.a.string\n data_url = 'https://www.shicimingju.com' + li.a['href']\n data_page_text = requests.get(headers=head,url=data_url).text\n text_soup = BeautifulSoup(data_page_text,'lxml')\n div_tag = text_soup.find('div',class_=\"chapter_content\")\n content = div_tag.text\n content = content.replace(' ',' ')\n fp.write(name+':'+content)\n print(name+'爬取完成!')", "repo_name": "qarro/testgit", "sub_path": "解析器/bs4解析/Bs4解析的例子.py", "file_name": "Bs4解析的例子.py", "file_ext": "py", "file_size_in_byte": 984, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "requests.get", "line_number": 10, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 11, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 17, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 18, "usage_type": "call"}]} +{"seq_id": "6913007080", "text": "\"\"\"\nLeetCode\n1162. As Far from Land as Possible\nFebruary 2023 Challenge\njramaswami\n\"\"\"\n\n\nimport collections\nimport math\nfrom typing import *\n\n\nclass Solution:\n def maxDistance(self, grid: List[List[int]]) -> int:\n\n def inbounds(r, c):\n return r >= 0 and c >= 0 and r < len(grid) and c < len(grid[r])\n\n def neighbors(r, c):\n for dr, dc in ((0, 1), (0, -1), (1, 0), (-1, 0)):\n r0, c0 = r + dr, c + dc\n if inbounds(r0, c0):\n yield r0, c0\n\n dist = [[math.inf for _ in row] for row in grid]\n queue = collections.deque()\n soln = -1\n for r, row in enumerate(grid):\n for c, _ in enumerate(row):\n if grid[r][c] == 1:\n queue.append((r, c))\n dist[r][c] = 0\n\n while queue:\n r, c = queue.popleft()\n for r0, c0 in neighbors(r, c):\n if dist[r][c] + 1 < dist[r0][c0]:\n dist[r0][c0] = dist[r][c] + 1\n queue.append((r0, c0))\n\n soln = -1\n for r, row in enumerate(grid):\n for c, _ in enumerate(row):\n if grid[r][c] == 0:\n soln = max(soln, dist[r][c])\n return -1 if soln == math.inf else soln\n\n\ndef test_1():\n grid = [[1,0,1],[0,0,0],[1,0,1]]\n expected = 2\n assert Solution().maxDistance(grid) == expected\n\n\ndef test_2():\n grid = [[1,0,0],[0,0,0],[0,0,0]]\n expected = 4\n assert Solution().maxDistance(grid) == expected\n", "repo_name": "jramaswami/LeetCode_Python", "sub_path": "as_far_from_land_as_possible.py", "file_name": "as_far_from_land_as_possible.py", "file_ext": "py", "file_size_in_byte": 1544, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "math.inf", "line_number": 26, "usage_type": "attribute"}, {"api_name": "collections.deque", "line_number": 27, "usage_type": "call"}, {"api_name": "math.inf", "line_number": 47, "usage_type": "attribute"}]} +{"seq_id": "14953667426", "text": "import socket\nimport threading\nimport SocketServer\nimport time, sys\nimport curses\n\nkill_received = False\n\ndef init_curses():\n stdscr = curses.initscr()\n curses.noecho()\n curses.cbreak()\n stdscr.keypad(1)\n curses.start_color()\n curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLUE)\n curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK)\n stdscr.bkgd(curses.color_pair(1))\n stdscr.refresh()\n return stdscr\n\ndef showMenu(menuwin):\n menuwin.box()\n menuwin.bkgd(curses.color_pair(2))\n menuwin.addstr(1, 2, \"X:\", curses.A_UNDERLINE)\n menuwin.addstr(1, 6, \"Exit\")\n menuwin.refresh()\n\ndef showFooter(footerwin):\n footerwin.box()\n footerwin.addstr(1, 2, \"Pakketsnuiver client\", curses.A_UNDERLINE)\n footerwin.refresh()\n\ndef showLogWin(logwin):\n logwin.bkgd(curses.color_pair(2))\n logwin.box()\n # logwin.addstr(3, 3, \"HEY\", curses.A_UNDERLINE)\n logwin.refresh()\n\ndef logWinNewLine(newLine, logwin):\n logwin.clear()\n logwin.box()\n logwin.addstr(4, 4, newLine, curses.A_UNDERLINE)\n logwin.box()\n logwin.clear()\n logwin.refresh()\n\ndef client():\n ip = \"127.0.0.1\"\n port = 12753\n global kill_received\n global logwin\n # print \"client start\"\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((ip, port))\n\n stdscr = init_curses()\n stdscr.immedok(True)\n\n menuwin = curses.newwin(3, 100, 0, 0)\n logwin = curses.newwin(22, 76, 4, 0)\n footer = curses.newwin(4, 100, 26, 0)\n\n stdscr.clear()\n stdscr.refresh()\n\n # while True:\n # if not kill_received:\n # print \"hoi\"\n\n # # response = sock.recv(1024)\n # # print \"{}\".format(response)\n\n # # c = stdscr.getch()\n\n # # if c == ord('s'):\n # # showMenu(menuwin)\n\n # # logWinRefresh(\"TEST\")\n\n # else:\n # sock.close()\n # break\n\n while True:\n showMenu(menuwin)\n showFooter(footer)\n showLogWin(logwin)\n response = sock.recv(1024)\n logWinNewLine(\"hoi\", logwin)\n # logwin.addstr(6, 4, \"HEY\", curses.A_UNDERLINE)\n stdscr.clear()\n stdscr.refresh()\n\n\n curses.nocbreak()\n stdscr.keypad(0)\n curses.echo()\n curses.endwin()\n\nif __name__ == \"__main__\":\n\n client()", "repo_name": "olafeee/UXX-Network-Monitor", "sub_path": "src/server/client.py", "file_name": "client.py", "file_ext": "py", "file_size_in_byte": 2127, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "2", "api": [{"api_name": "curses.initscr", "line_number": 10, "usage_type": "call"}, {"api_name": "curses.noecho", "line_number": 11, "usage_type": "call"}, {"api_name": "curses.cbreak", "line_number": 12, "usage_type": "call"}, {"api_name": "curses.start_color", "line_number": 14, "usage_type": "call"}, {"api_name": "curses.init_pair", "line_number": 15, "usage_type": "call"}, {"api_name": "curses.COLOR_GREEN", "line_number": 15, "usage_type": "attribute"}, {"api_name": "curses.COLOR_BLUE", "line_number": 15, "usage_type": "attribute"}, {"api_name": "curses.init_pair", "line_number": 16, "usage_type": "call"}, {"api_name": "curses.COLOR_YELLOW", "line_number": 16, "usage_type": "attribute"}, {"api_name": "curses.COLOR_BLACK", "line_number": 16, "usage_type": "attribute"}, {"api_name": "curses.color_pair", "line_number": 17, "usage_type": "call"}, {"api_name": "curses.color_pair", "line_number": 23, "usage_type": "call"}, {"api_name": "curses.A_UNDERLINE", "line_number": 24, "usage_type": "attribute"}, {"api_name": "curses.A_UNDERLINE", "line_number": 30, "usage_type": "attribute"}, {"api_name": "curses.color_pair", "line_number": 34, "usage_type": "call"}, {"api_name": "curses.A_UNDERLINE", "line_number": 42, "usage_type": "attribute"}, {"api_name": "socket.socket", "line_number": 53, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 53, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 53, "usage_type": "attribute"}, {"api_name": "curses.newwin", "line_number": 59, "usage_type": "call"}, {"api_name": "curses.newwin", "line_number": 60, "usage_type": "call"}, {"api_name": "curses.newwin", "line_number": 61, "usage_type": "call"}, {"api_name": "curses.nocbreak", "line_number": 95, "usage_type": "call"}, {"api_name": "curses.echo", "line_number": 97, "usage_type": "call"}, {"api_name": "curses.endwin", "line_number": 98, "usage_type": "call"}]} +{"seq_id": "31687568141", "text": "from collections import deque\nimport copy\n\n\nclass VigenereCypher():\n\n def __init__(self, key):\n self.key = key.upper()\n self.header = deque([chr(unicode) for unicode in range(32, 91)])\n\n def encrypt(self, msg):\n msg = msg.upper()\n\n chave_completa = self._completa_chave(msg)\n\n encripted = []\n\n for col, lin in zip(msg, chave_completa):\n coluna = self.header.index(col)\n linha = self._shift_header(self.header.index(lin))\n encripted.append(linha[coluna])\n\n return ''.join(encripted)\n\n def decrypt(self, msg) :\n msg = msg.upper()\n\n chave_completa = self._completa_chave(msg)\n\n decripted = []\n\n for col, lin in zip(msg, chave_completa):\n coluna = self._shift_header(self.header.index(lin)).index(col)\n decripted.append(self.header[coluna])\n\n\n return ''.join(decripted)\n \n def _shift_header(self, n):\n header = copy.copy(self.header)\n i = 0\n while i < n:\n header.append(header.popleft())\n i += 1\n return list(header)\n\n def _completa_chave(self, msg):\n chave_completa = ''\n for i in range(len(msg)):\n chave_completa += self.key[i%len(self.key)]\n \n return chave_completa \n\n\n\nif __name__ == '__main__':\n frase = 'O video de demonstracao da cifra de vigenere pode ser encontrada no youtube atraves do link abaixo'\n vigenere_cypher = VigenereCypher(key='FTT Salvador Arena')\n\n print('Encripting {}'.format(frase))\n\n encripted_frase = vigenere_cypher.encrypt(frase)\n print('Encripted message: {}'.format(encripted_frase))\n\n decripted_frase = vigenere_cypher.decrypt(encripted_frase)\n print('Decripted message: {}'.format(decripted_frase))\n \n", "repo_name": "fePremazzi/encryption", "sub_path": "vigenere/vige.py", "file_name": "vige.py", "file_ext": "py", "file_size_in_byte": 1802, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "collections.deque", "line_number": 9, "usage_type": "call"}, {"api_name": "copy.copy", "line_number": 40, "usage_type": "call"}]} +{"seq_id": "40465853390", "text": "import pandas as pd\nimport numpy as np\n\nimport imageio\nimport os\nimport gc\n\nfrom tqdm import tqdm\nfrom sklearn.model_selection import train_test_split\n\nfrom skimage.transform import resize as imgresize\n\nclass DataSet:\n \"\"\"\n \"\"\"\n def __init__(self, init_path, img_shape=[224,224,3], dir_img='images_training_rev1/'):\n self.ipath = init_path\n self.img_shape = img_shape\n self.img_dir = dir_img\n self._csv_data = pd.read_csv(os.path.join(init_path,'training_solutions_rev1.csv'))\n\n\n def _get_img_path(self, filename):\n path = self.ipath+self.img_dir+str(filename)+'.jpg'\n return path\n\n def _load_img(self, filepath):\n return imageio.imread(filepath)\n\n def _load_dataset(self):\n filenames = self._csv_data.loc[:,'GalaxyID']\n self.img = []\n self.y = []\n for i, fname in tqdm(enumerate(self._csv_data['GalaxyID'].values), 'Read Img'):\n img = self._load_img(self._get_img_path(fname))\n self.img.append(imgresize(img, self.img_shape))\n self.y.append(self._csv_data.iloc[i, 1:])\n del self._csv_data; gc.collect()\n\n def _train_valid_split(self, random_state, train_size):\n X_train, X_valid, y_train, y_valid = train_test_split(self.img,\n self.y,\n random_state=random_state,\n train_size=train_size,\n shuffle=True)\n self.img_train = X_train\n self.img_valid = X_valid\n self.y_train = y_train\n self.y_valid = y_valid\n del self.img, self.y; gc.collect()\n\n def load_and_transform_data(self, random_state=133, train_size=0.75):\n self._load_dataset()\n self._train_valid_split(random_state=random_state, train_size=train_size)\n", "repo_name": "MIklgr500/GalaxyZoo", "sub_path": "dataset.py", "file_name": "dataset.py", "file_ext": "py", "file_size_in_byte": 1949, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "pandas.read_csv", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "imageio.imread", "line_number": 28, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 34, "usage_type": "call"}, {"api_name": "skimage.transform.resize", "line_number": 36, "usage_type": "call"}, {"api_name": "gc.collect", "line_number": 38, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 41, "usage_type": "call"}, {"api_name": "gc.collect", "line_number": 50, "usage_type": "call"}]} +{"seq_id": "13668326159", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n@author:XuMing(xuming624@qq.com)\n@description: \n\"\"\"\n\nfrom pyecharts import Map\nvalue = [155, 10, 66, 78]\nattr = [\"福建\", \"山东\", \"北京\", \"上海\"]\nmap = Map(\"全国地图示例\",height=720,width=800)\nmap.add(\"\", attr, value, maptype='china')\nmap.render(\"country_map.html\")\n\n", "repo_name": "Dis-count/Python_practice", "sub_path": "practice/python-tutorial-master/32echart/country_map_demo.py", "file_name": "country_map_demo.py", "file_ext": "py", "file_size_in_byte": 310, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "2", "api": [{"api_name": "pyecharts.Map", "line_number": 10, "usage_type": "call"}]} +{"seq_id": "71306686126", "text": "from sklearn.model_selection import (StratifiedKFold,\n ShuffleSplit,\n TimeSeriesSplit,\n GroupShuffleSplit,\n GroupKFold,\n RepeatedKFold,\n RepeatedStratifiedKFold)\n\n\ndef get_cv(cv_name, n_splits=5, test_size_ratio=0.2,\n n_repeats=10, random_state=42, shuffle=True):\n\n cv = None\n\n if type(cv_name) is str:\n if cv_name == 'ShuffleSplit':\n cv = ShuffleSplit(n_splits=n_splits,\n test_size=test_size_ratio,\n train_size=None,\n random_state=random_state)\n elif cv_name == 'TimeSeriesSplit':\n cv = TimeSeriesSplit(n_splits=n_splits, max_train_size=None)\n elif cv_name == 'GroupShuffleSplit':\n cv = GroupShuffleSplit(n_splits=n_splits,\n test_size=test_size_ratio,\n train_size=None,\n random_state=random_state)\n elif cv_name == 'GroupKFold':\n cv = GroupKFold(n_splits=n_splits)\n elif cv_name == 'RepeatedKFold':\n cv = RepeatedKFold(n_splits=n_splits,\n n_repeats=n_repeats,\n random_state=random_state)\n elif cv_name == 'RepeatedStratifiedKFold':\n cv = RepeatedStratifiedKFold(\n n_splits=n_splits,\n n_repeats=n_repeats,\n random_state=random_state)\n else:\n cv = StratifiedKFold(\n n_splits=n_splits, random_state=random_state, shuffle=shuffle)\n\n return cv\n", "repo_name": "v-crn/Titanic-Tutorial", "sub_path": "vmlkit/validator.py", "file_name": "validator.py", "file_ext": "py", "file_size_in_byte": 1810, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "sklearn.model_selection.ShuffleSplit", "line_number": 17, "usage_type": "call"}, {"api_name": "sklearn.model_selection.TimeSeriesSplit", "line_number": 22, "usage_type": "call"}, {"api_name": "sklearn.model_selection.GroupShuffleSplit", "line_number": 24, "usage_type": "call"}, {"api_name": "sklearn.model_selection.GroupKFold", "line_number": 29, "usage_type": "call"}, {"api_name": "sklearn.model_selection.RepeatedKFold", "line_number": 31, "usage_type": "call"}, {"api_name": "sklearn.model_selection.RepeatedStratifiedKFold", "line_number": 35, "usage_type": "call"}, {"api_name": "sklearn.model_selection.StratifiedKFold", "line_number": 40, "usage_type": "call"}]} +{"seq_id": "11281887367", "text": "# ABC143b\nimport itertools\nimport sys\n\ninput = sys.stdin.readline\nsys.setrecursionlimit(10 ** 6)\n\nn = int(input())\nd = list(map(int, input().split()))\n\nans = 0\n\nfor i, j in itertools.combinations(d, 2):\n ans += i * j\n\nprint(ans)\n", "repo_name": "yuto-moriizumi/AtCoder", "sub_path": "ABC143/ABC143b.py", "file_name": "ABC143b.py", "file_ext": "py", "file_size_in_byte": 232, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "sys.stdin", "line_number": 5, "usage_type": "attribute"}, {"api_name": "sys.setrecursionlimit", "line_number": 6, "usage_type": "call"}, {"api_name": "itertools.combinations", "line_number": 13, "usage_type": "call"}]} +{"seq_id": "26941208567", "text": "from chalice import Chalice, Response\nfrom funcao_sql import busca_cliente_bd, insere_cliente_bd,\\\n busca_clientes_bd, modifica_cliente, deleta_cliente\n\n\napp = Chalice(app_name='projeto_crud')\n\n\n@app.route('/cliente', methods=['POST'])\ndef cadastra_cliente():\n request_dados: dict = {}\n request_dados = app.current_request.json_body\n insere_cliente_bd(request_dados)\n return Response(\n body={\"message\": \"cliente inserido com sucesso\"},\n status_code=201\n )\n\n\n@app.route('/cliente', methods=['GET'])\ndef retorna_cliente():\n request_codigo: dict = {}\n request_codigo = app.current_request.query_params['codigo']\n resposta_body = busca_cliente_bd(parametro_query=request_codigo)\n return Response(\n body=resposta_body,\n status_code=200\n )\n\n\n@app.route('/clientes', methods=['GET'])\ndef retorna_clientes():\n resposta_body = busca_clientes_bd()\n return Response(\n body=resposta_body,\n status_code=200\n )\n\n\n@app.route('/cliente', methods=['PATCH'])\ndef atualiza_cliente():\n requisicao_dados: dict = {}\n codigo_cliente: str = app.current_request.query_params['codigo']\n requisicao_dados[\"codigo\"] = codigo_cliente\n requisicao_dados[\"dados\"] = app.current_request.json_body\n modifica_cliente(corpo_requisicao=requisicao_dados)\n resposta_body = busca_cliente_bd(parametro_query=codigo_cliente)\n return Response(\n body=resposta_body,\n status_code=200\n )\n\n\n@app.route('/cliente', methods=['DELETE'])\ndef remove_cliente():\n codigo_cliente: str = app.current_request.query_params['codigo']\n deleta_cliente(codigo_cliente=codigo_cliente)\n resposta_corpo_requisicao: dict = {\"message\": \"Cliente deletado.\"}\n return Response(\n body=resposta_corpo_requisicao,\n status_code=200\n )\n", "repo_name": "wesleykalb/crud_", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1812, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "chalice.Chalice", "line_number": 6, "usage_type": "call"}, {"api_name": "funcao_sql.insere_cliente_bd", "line_number": 13, "usage_type": "call"}, {"api_name": "chalice.Response", "line_number": 14, "usage_type": "call"}, {"api_name": "funcao_sql.busca_cliente_bd", "line_number": 24, "usage_type": "call"}, {"api_name": "chalice.Response", "line_number": 25, "usage_type": "call"}, {"api_name": "funcao_sql.busca_clientes_bd", "line_number": 33, "usage_type": "call"}, {"api_name": "chalice.Response", "line_number": 34, "usage_type": "call"}, {"api_name": "funcao_sql.modifica_cliente", "line_number": 46, "usage_type": "call"}, {"api_name": "funcao_sql.busca_cliente_bd", "line_number": 47, "usage_type": "call"}, {"api_name": "chalice.Response", "line_number": 48, "usage_type": "call"}, {"api_name": "funcao_sql.deleta_cliente", "line_number": 57, "usage_type": "call"}, {"api_name": "chalice.Response", "line_number": 59, "usage_type": "call"}]} +{"seq_id": "71828757486", "text": "import logging\nimport os\nimport re\nimport shutil\nimport tempfile\nimport time\nfrom collections import defaultdict\nfrom operator import itemgetter\n\nimport pandas\nimport visdom\nfrom tqdm import tqdm\n\nimport src.utils.external_resources as external\n\nlogger = logging.getLogger(__name__)\n\ndef get_env_url(visdom_client, replace=('devfair054', 'localhost')):\n if isinstance(visdom_client, dict):\n res = '{}:{}/env/{}'.format(visdom_client['server'],\n visdom_client['port'],\n visdom_client['env'])\n else:\n res = '{}:{}/env/{}'.format(visdom_client.server,\n visdom_client.port,\n visdom_client.env)\n if not res.startswith('http://'):\n res = 'http://' + res\n if replace:\n res = res.replace(*replace)\n return res\n\n\ndef rename_class(cls, new_name):\n cls.__name__ = new_name\n qualname = cls.__qualname__.split('.')\n qualname[-1] = new_name\n cls.__qualname__ = '.'.join(qualname)\n return cls\n\n\ndef fill_matrix(matrix, val=float('nan')):\n assert isinstance(matrix, list)\n max_len = max(map(len, matrix))\n matrix = [pad_seq(seq, max_len, val) for seq in matrix]\n return matrix\n\n\ndef pad_seq(seq, length, val):\n new_elems = [val] * (length - len(seq))\n return seq + new_elems\n\n\ndef paretize_exp(data, x_name, crit_name, keep_keys):\n # Data needs to be sorted following x axis\n\n # for x1, x2 in zip(data[x_name], data[x_name][1:]):\n # assert x1 <= x2\n if isinstance(data, pandas.DataFrame):\n data = data.to_dict('list')\n\n keep_keys = set(keep_keys + [x_name, crit_name])\n\n res = defaultdict(list)\n cur_best_crit = None\n cur_best_x = None\n keys = list(data.keys())\n data = [dict(zip(keys, vals)) for vals in zip(*data.values())]\n for d in sorted(data, key=itemgetter(x_name)):\n cur_crit = d[crit_name]\n if len(res) == 0 or cur_crit > cur_best_crit:\n if d[x_name] == cur_best_x:\n for k in keep_keys:\n res[k][-1] = d[k]\n else:\n for k in keep_keys:\n res[k].append(d[k])\n cur_best_crit = cur_crit\n cur_best_x = d[x_name]\n return res\n\ndef get_runs(sacred_ids=None, slurm_ids=None, mongo_conf_path=None):\n if sacred_ids:\n assert not slurm_ids, 'Can\\'t specify both sacred and slurm ids'\n ids = sacred_ids\n req = {'_id': {\"$in\": ids}}\n elif slurm_ids:\n ids = [str(id) for id in slurm_ids]\n req = {'host.ENV.SLURM_JOB_ID': {\"$in\": ids}}\n else:\n raise ValueError('Should specify one of --sacred-ids or --slurm-ids.')\n\n mongo_collection = external.get_mongo_collection(mongo_path=mongo_conf_path)\n runs = mongo_collection.find(req, no_cursor_timeout=True)\n n_res = mongo_collection.count_documents(req)\n if n_res < len(ids):\n retrieved = set(r['_id'] if sacred_ids else\n r['host']['ENV']['SLURM_JOB_ID'] for r in runs)\n missing = set(ids) - retrieved\n raise ValueError('Missing runs, expected {} but got {} (missing {}).'\n .format(len(ids), runs.count(), missing))\n if n_res > len(ids):\n raise ValueError('Big problem: More results that ids (runs coming from '\n 'different Slurm clusters ?)')\n return runs\n\n\ndef replay_run(run, viz, args, mongo_path, logger):\n if not run['artifacts']:\n logger.warning(\n 'Run {} doesn\\'t have any stored file'.format(run['_id']))\n return None, 0, 0\n\n selected_artifact = None\n for artifact in reversed(run['artifacts']):\n if artifact['name'].endswith(args.name_end):\n selected_artifact = artifact\n break\n\n if selected_artifact is None:\n available = [a['name'] for a in run['artifacts']]\n raise ValueError('No artifact ending with \\'{}\\' in run {}. Available'\n ' artifacts are {}'.format(args.name_end, args.id,\n available))\n start_time = time.time()\n gridfs = external.get_gridfs(mongo_path=mongo_path)\n object = gridfs.get(selected_artifact['file_id'])\n\n # with tempfile.TemporaryDirectory() as dir:\n with tempfile.TemporaryDirectory(dir='/local/veniat') as dir:\n file_path = os.path.join(dir, selected_artifact['name'])\n with open(file_path, 'wb') as file:\n file.write(object.read())\n\n n_replayed, main_env = replay_from_path(file_path, viz, run['_id'],\n args.all_envs)\n tot_time = time.time() - start_time\n logger.info('Replayed {} envs in {:.3f} seconds.'.format(n_replayed,\n tot_time))\n if main_env is None:\n logger.warning('No main env file found.')\n else:\n logger.info('Main env is {}.'.format(main_env))\n viz.env = main_env\n logger.info(get_env_url(viz))\n return get_env_url(viz), n_replayed, tot_time\n\ndef replay_from_path(archive_path, viz, run_id, all_envs=False):\n target = archive_path[:-4]\n # print(archive_path)\n # print(os.path.getsize(archive_path))\n # shutil.copy(file_path, selected_artifact['name'])\n shutil.unpack_archive(archive_path, target)\n env_files = os.listdir(target)\n logger.info('Replaying envs for {}'.format(run_id))\n n_replayed = 0\n main_env = None\n for file in tqdm(env_files):\n if 'main' in file:\n main_env = file\n if all_envs or 'Trial' not in file or 'PSSN-search-6-bw' in file:\n # or 'main' in file or 'tasks' in file:\n # print(file)\n viz.delete_env(file)\n env_path = os.path.join(target, file)\n try:\n viz.replay_log(env_path)\n except ValueError as r:\n logger.warning('Can\\' replay {}: {}'.format(env_path, r))\n except IsADirectoryError as r:\n logger.warning('Can\\' replay dir {}: {}'.format(env_path, r))\n n_replayed += 1\n\n return n_replayed, main_env\n\n\ndef get_training_vis_conf(vis_p, trial_dir):\n vis_p = vis_p.copy()\n # if trial_dir.endswith('/'):\n # trial_dir = trial_dir[:-1]\n #\n # # 19 chars for the date + 8 chars for mktmp directory + 1 sep\n # tag = os.path.basename(trial_dir)[:-28]\n\n split = re.split('_\\d{4}-\\d{2}-\\d{2}_\\d{2}-\\d{2}', trial_dir)\n assert len(split) == 2\n tag = os.path.basename(split[0])\n\n env = vis_p['env'].split('_')\n assert len(env) == 3, '{} is too long'.format(env) # exp_model_task\n env[1] = tag\n env.insert(1, 'Trial')\n vis_p['env'] = '_'.join(env)\n\n vis_logdir = os.path.dirname(vis_p['log_to_filename'])\n vis_p['log_to_filename'] = os.path.join(vis_logdir, vis_p['env'])\n\n return vis_p\n\n\ndef count_params(model):\n n_params = 0\n n_trainable_params = 0\n for p in model.parameters():\n n_params += p.numel()\n if p.requires_grad:\n n_trainable_params += p.numel()\n\n return {'total': n_params, 'trainable': n_trainable_params}\n\n\nif __name__ == '__main__':\n vis = visdom.Visdom()\n path = '/home/tom/Downloads/new_archive.zip'\n\n print(replay_from_path(path, vis, 1888, False))", "repo_name": "TomVeniat/MNTDP", "sub_path": "src/utils/misc.py", "file_name": "misc.py", "file_ext": "py", "file_size_in_byte": 7343, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 17, "dataset": "github-code", "pt": "2", "api": [{"api_name": "logging.getLogger", "line_number": 16, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 59, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 64, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 69, "usage_type": "call"}, {"api_name": "src.utils.external_resources.get_mongo_collection", "line_number": 93, "usage_type": "call"}, {"api_name": "src.utils.external_resources", "line_number": 93, "usage_type": "name"}, {"api_name": "time.time", "line_number": 125, "usage_type": "call"}, {"api_name": "src.utils.external_resources.get_gridfs", "line_number": 126, "usage_type": "call"}, {"api_name": "src.utils.external_resources", "line_number": 126, "usage_type": "name"}, {"api_name": "tempfile.TemporaryDirectory", "line_number": 130, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 131, "usage_type": "call"}, {"api_name": "os.path", "line_number": 131, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 137, "usage_type": "call"}, {"api_name": "shutil.unpack_archive", "line_number": 153, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 154, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 158, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 165, "usage_type": "call"}, {"api_name": "os.path", "line_number": 165, "usage_type": "attribute"}, {"api_name": "re.split", "line_number": 185, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 187, "usage_type": "call"}, {"api_name": "os.path", "line_number": 187, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 195, "usage_type": "call"}, {"api_name": "os.path", "line_number": 195, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 196, "usage_type": "call"}, {"api_name": "os.path", "line_number": 196, "usage_type": "attribute"}, {"api_name": "visdom.Visdom", "line_number": 213, "usage_type": "call"}]} +{"seq_id": "25884767395", "text": "# -*- coding:utf-8 -*-\n\"\"\"\n@Time: 2022/02/11 12:12\n@Author: KI\n@File: fedavg-tff.py\n@Motto: Hungry And Humble\n\"\"\"\nimport os\n#os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nos.environ['CUDA_VISIBLE_DEVICES']='0' #cpu版本\nimport sys\nsys.path.append('../')\nfrom algorithms.bp_nn import load_data\nimport tensorflow as tf\nimport tensorflow_federated as tff\nimport nest_asyncio\nfrom args import args_parser\nargs = args_parser()\n\nnest_asyncio.apply()\ntf.compat.v1.enable_v2_behavior()\n\nclients_wind = ['Task1_W_Zone' + str(i) for i in range(1, 11)]\n\n\n# Data processing 客户数据处理\n# 对于函数client_data(n, B, train_flag),如果train_flag=True,返回客户端n的batch_size=B的训练集,否则返回测试集。\ndef client_data_wind(n, B, train_flag):\n print('data processing...')\n c = clients_wind\n data = load_data(c[n])\n if train_flag:\n data = data[0:int(len(data) * 0.9)]\n else:\n data = data[int(len(data) * 0.9):len(data)]\n\n label = data[data.columns[2]].values.tolist()\n data = data.values.tolist()\n X, Y = [], []\n for i in range(len(data) - 30):\n train_seq = []\n # train_label = []\n for j in range(i, i + 24):\n train_seq.append(label[j])\n for c in range(3, 7): #添加温度、湿度、气压等信息\n train_seq.append(data[i + 24][c])\n Y.append(label[i + 24])\n X.append(train_seq)\n\n X = tf.reshape(X, [len(X), -1])\n Y = tf.reshape(Y, [len(Y), -1])\n X = tf.data.Dataset.from_tensor_slices(X)\n Y = tf.data.Dataset.from_tensor_slices(Y)\n\n seq = tf.data.Dataset.zip((X, Y))\n seq = seq.batch(B, drop_remainder=True).shuffle(100).prefetch(B)\n # print(list(seq.as_numpy_iterator())[0]),batch_size=20\n\n return seq\n\n\n# Wrap a Keras model for use with TFF.\n# 构造ttf的keras模型\n'''\nkeras_model:为联邦学习封装的Keras模型,该模型不能compile。\nloss:损失函数。如果只提供一个损失函数,则所有模型都使用该损失函数;如果提供一个损失函数列表,则与各个客户端模型相互对应。这里选择MSE。\ninput_sec:指定模型的输入数据类型。input_spec必须是两个元素的复合结构,即x和y。如果作为列表提供,则必须按 [x, y]的顺序,如果作为字典提供,则键必须明确命名为“x”和“y”。本文是按照列表进行提供的。\nloss_weights:可选项。如果loss为一个列表,那么就可以为每一个客户端的loss指定一个权重,最后求加权和。\nmetrics:可选项。这里选择了MAPE。\n'''\ndef model_fn(): #最终返回的是一个tff.learning.Model,该模型将用于联邦学习\n metrics = [tf.keras.metrics.MeanAbsoluteError()]\n input_dim = args.input_dim\n\n model = tf.keras.models.Sequential([ #采用TensorFlow的keras模块来搭建了一个简单的神经网络\n tf.keras.layers.Dense(20, tf.nn.sigmoid, input_shape=(input_dim,),\n kernel_initializer='zeros'),\n tf.keras.layers.Dense(20, tf.nn.sigmoid),\n tf.keras.layers.Dense(20, tf.nn.sigmoid),\n tf.keras.layers.Dense(1, tf.sigmoid)\n ])\n return tff.learning.from_keras_model(\n model,\n input_spec=train_data[0].element_spec,\n loss=tf.keras.losses.MeanSquaredError(),\n metrics=metrics)\n\n\ndef FedAvg():\n # Simulate a few rounds of training with the selected client devices.\n trainer = tff.learning.build_federated_averaging_process(\n model_fn,\n client_optimizer_fn=lambda: tf.keras.optimizers.Adam(0.08),\n # server_optimizer_fn=lambda: tf.keras.optimizers.SGD(1.0),\n # use_experimental_simulation_loop=True\n )\n state = trainer.initialize()\n for r in range(args.r):\n state, metrics = trainer.next(state, train_data)\n print('round', r + 1, 'loss:', metrics['train']['loss'])\n evaluation = tff.learning.build_federated_evaluation(model_fn)\n for i in range(args.K):\n test_data = [client_data_wind(n, 20, train_flag=False) for n in range(i, i + 1)]\n # print('test:')\n test_metrics = evaluation(state.model, test_data)\n m = 'mean_absolute_error'\n print(str(test_metrics[m] / len(test_data[0])))\n\n\nif __name__ == '__main__':\n train_data = [client_data_wind(n, 20, train_flag=True) for n in range(args.K)]\n FedAvg()\n", "repo_name": "C-Wwb/GraduationProject", "sub_path": "FedAvg-numpy-pytorch-tff-main/algorithms/fedavg-tff.py", "file_name": "fedavg-tff.py", "file_ext": "py", "file_size_in_byte": 4350, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "2", "api": [{"api_name": "os.environ", "line_number": 10, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 12, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "args.args_parser", "line_number": 18, "usage_type": "call"}, {"api_name": "nest_asyncio.apply", "line_number": 20, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1.enable_v2_behavior", "line_number": 21, "usage_type": "call"}, {"api_name": "tensorflow.compat", "line_number": 21, "usage_type": "attribute"}, {"api_name": "algorithms.bp_nn.load_data", "line_number": 31, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 50, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 51, "usage_type": "call"}, {"api_name": "tensorflow.data.Dataset.from_tensor_slices", "line_number": 52, "usage_type": "call"}, {"api_name": "tensorflow.data", "line_number": 52, "usage_type": "attribute"}, {"api_name": "tensorflow.data.Dataset.from_tensor_slices", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.data", "line_number": 53, "usage_type": "attribute"}, {"api_name": "tensorflow.data.Dataset.zip", "line_number": 55, "usage_type": "call"}, {"api_name": "tensorflow.data", "line_number": 55, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.metrics.MeanAbsoluteError", "line_number": 72, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 72, "usage_type": "attribute"}, {"api_name": "args.input_dim", "line_number": 73, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.models.Sequential", "line_number": 75, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 75, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 76, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 76, "usage_type": "attribute"}, {"api_name": "tensorflow.nn", "line_number": 76, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 78, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 78, "usage_type": "attribute"}, {"api_name": "tensorflow.nn", "line_number": 78, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 79, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 79, "usage_type": "attribute"}, {"api_name": "tensorflow.nn", "line_number": 79, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 80, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 80, "usage_type": "attribute"}, {"api_name": "tensorflow.sigmoid", "line_number": 80, "usage_type": "attribute"}, {"api_name": "tensorflow_federated.learning.from_keras_model", "line_number": 82, "usage_type": "call"}, {"api_name": "tensorflow_federated.learning", "line_number": 82, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.losses.MeanSquaredError", "line_number": 85, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 85, "usage_type": "attribute"}, {"api_name": "tensorflow_federated.learning.build_federated_averaging_process", "line_number": 91, "usage_type": "call"}, {"api_name": "tensorflow_federated.learning", "line_number": 91, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.optimizers.Adam", "line_number": 93, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 93, "usage_type": "attribute"}, {"api_name": "args.r", "line_number": 98, "usage_type": "attribute"}, {"api_name": "tensorflow_federated.learning.build_federated_evaluation", "line_number": 101, "usage_type": "call"}, {"api_name": "tensorflow_federated.learning", "line_number": 101, "usage_type": "attribute"}, {"api_name": "args.K", "line_number": 102, "usage_type": "attribute"}, {"api_name": "args.K", "line_number": 111, "usage_type": "attribute"}]} +{"seq_id": "29052064925", "text": "import os\n\nimport numpy as np\nimport pandas as pd\nfrom keras.models import load_model\nfrom numpy import array\nfrom sklearn.preprocessing import OneHotEncoder\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n# ---- 数据导入 ----\ndata = pd.read_excel('H:\\Code\\PyCharm\\GraduationDesign\\cnn\\\\test.xlsx', header=None)\norigin_data_x = data.iloc[:, 1:].values\norigin_data_y = data.iloc[:, 0].values # 提取所有行,第1列,即label列\n\nprint(type(origin_data_x))\nprint(origin_data_x)\n\n\n# ---- 参数定义----\ninput_size = 140 # 长度\ntime_step = 1 # 步长\nlabels = 10 # 分类数,共10类\n\n\n# 对labels进行one-hot编码\ndef label2hot(labels):\n values = array(labels)\n onehot_encoder = OneHotEncoder(sparse=False)\n integer_encoded = values.reshape(len(values), 1)\n onehot_encoded = onehot_encoder.fit_transform(integer_encoded)\n return onehot_encoded\n\n\nhot_data_y = label2hot(origin_data_y[:])\n\n\n# 标准化,工具函数\ndef normal(datas):\n hang = datas.shape[0]\n list1 = []\n for i in range(hang):\n n = 0\n meihang = datas[i]\n # print(meihang)\n list2 = []\n for j in range(5):\n zhen = meihang[n:n + 28]\n # print(zhen)\n jishu = zhen[::2] # 取奇数位,即x\n x_max = max(jishu)\n x_min = min(jishu)\n x_err = x_max - x_min\n if x_err == 0:\n x_err = 0.001\n oushu = zhen[1::2] # 取偶数位,即y\n y_max = max(oushu)\n y_min = min(oushu)\n y_err = y_max - y_min\n if y_err == 0:\n y_err = 0.001\n for k in range(14):\n x_n = (jishu[k] - x_min) / x_err\n y_n = (oushu[k] - y_min) / y_err\n x_n = str(x_n)\n y_n = str(y_n)\n list2.append(x_n)\n list2.append(y_n)\n n += 28\n list1.append(list2)\n normal_data = np.array(list1)\n return normal_data\n\n\n# 测试数据\ntest_x = origin_data_x\ntest_x = normal(test_x)\ntest_x = test_x.reshape([-1, input_size, time_step])\n\n# 调用训练好的模型\nmodel = load_model('H:\\Code\\PyCharm\\GraduationDesign\\cnn\\models\\cnn_model_label.h5') # 选取自己的.h模型名称\n\n# 预测\npredict = model.predict_classes(test_x)\nprint(predict)\n\n\ndef execute():\n return predict\n", "repo_name": "marklee0315/XAUAT-GraduationDesign", "sub_path": "cnn/predictionModule.py", "file_name": "predictionModule.py", "file_ext": "py", "file_size_in_byte": 2348, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.environ", "line_number": 9, "usage_type": "attribute"}, {"api_name": "pandas.read_excel", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 28, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.OneHotEncoder", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 71, "usage_type": "call"}, {"api_name": "keras.models.load_model", "line_number": 81, "usage_type": "call"}]} +{"seq_id": "23398015887", "text": "from django.conf.urls import patterns, include, url\nfrom mysite.views import hello, current_datetime, hours_ahead, display_meta\nfrom django.contrib import admin\nfrom contact import views\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^hello/$', hello),\n url(r'^time/$', current_datetime),\n url(r'^time/plus/(\\d{1,2})/$', hours_ahead),\n url(r'^meta/$', display_meta),\n# url(r'^search/$', views.search),\n url(r'^contact/$', views.contact),\n \n # Uncomment the admin/doc line below to enable admin documentation:\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n)\n", "repo_name": "kevinlondon/djangobook-examples", "sub_path": "mysite/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 730, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.contrib.admin.autodiscover", "line_number": 6, "usage_type": "call"}, {"api_name": "django.contrib.admin", "line_number": 6, "usage_type": "name"}, {"api_name": "django.conf.urls.patterns", "line_number": 8, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 10, "usage_type": "call"}, {"api_name": "mysite.views.hello", "line_number": 10, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 11, "usage_type": "call"}, {"api_name": "mysite.views.current_datetime", "line_number": 11, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 12, "usage_type": "call"}, {"api_name": "mysite.views.hours_ahead", "line_number": 12, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 13, "usage_type": "call"}, {"api_name": "mysite.views.display_meta", "line_number": 13, "usage_type": "argument"}, {"api_name": "django.conf.urls.url", "line_number": 15, "usage_type": "call"}, {"api_name": "contact.views.contact", "line_number": 15, "usage_type": "attribute"}, {"api_name": "contact.views", "line_number": 15, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 18, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 18, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 21, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 21, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 21, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 21, "usage_type": "name"}]} +{"seq_id": "74514327742", "text": "#!/usr/bin/env python\n\nimport sys\nimport inspect\n\n\ndef called_from_main():\n stack = inspect.stack()\n if len(stack) < 3:\n return False\n\n callerframe = stack[2][0]\n callerhash = dict(inspect.getmembers(callerframe))\n caller_globals = callerhash.get('f_globals', False)\n if caller_globals:\n return caller_globals.get('__name__', None) == '__main__'\n\n\nfrom optparse import OptionParser\nfrom itertools import chain\n\ntry:\n from StringIO import StringIO\nexcept ImportError:\n from io import StringIO\n\n\ncasts = {\"int\": int,\n \"float\": float,\n \"bool\": bool,\n \"str\": str} # other??\n\n\ndef is_option(t):\n return t and t.startswith(\"-\") and len(t) > 1\n\n\ndef is_posarg(t):\n return t and not is_option(t)\n\n\ndef is_cast(t):\n return t and t.startswith(\"(\") and t.endswith(\")\")\n\n\ndef is_choice(t):\n return t and \"|\" in t\n\n\ndef is_assignment(t):\n return t and (t.find(\"->\") >= 0)\n\n\ndef handle_option(parser, optdef):\n opt, help = (\":\" in optdef) and optdef.split(\":\", 1) or (optdef, \"\")\n optstrings = []\n optatts = {\"help\": help.strip(), \"nargs\": 0}\n\n for term in opt.split():\n if is_option(term):\n optstrings.append(term)\n elif is_cast(term):\n optatts[\"type\"] = term[1:-1]\n elif is_assignment(term):\n const, dest = term.split(\"->\")\n optatts[\"dest\"] = dest\n optatts[\"const\"] = const\n elif is_choice(term):\n optatts[\"choices\"] = term.split(\"|\")\n else:\n optatts[\"dest\"] = term\n optatts[\"nargs\"] = 1\n\n # Set default type\n\n if \"type\" not in optatts:\n if not optatts[\"nargs\"]:\n optatts[\"type\"] = \"int\"\n\n # Eval const\n\n if \"type\" in optatts and \"const\" in optatts:\n optatts[\"const\"] = eval(\"%(type)s(%(const)s)\" % optatts)\n\n # Set action\n\n if optatts[\"nargs\"]:\n optatts[\"action\"] = \"store\"\n else:\n optatts[\"action\"] = \"store_const\"\n if not \"dest\" in optatts:\n optatts[\"const\"] = True\n del optatts[\"type\"]\n del optatts[\"nargs\"]\n\n # Finally\n\n parser.add_option(*(optstrings), **(optatts))\n\n\ndef handle_posarg(pargdef):\n parg, help = (\":\" in pargdef) and pargdef.split(\":\", 1) or (pargdef, \"\")\n cast = \"str\"\n name = \"\"\n for term in parg.split():\n if is_cast(term):\n cast = term[1:-1]\n else:\n name = term\n\n return (name, cast, help.strip())\n\n\ndef pargs_n_opts(optdefs):\n\n pargs = [handle_posarg(optdef) for optdef in optdefs if is_posarg(optdef)]\n\n # based on pargs, build usage string\n\n usage = \"%prog [options]\"\n\n if len(pargs) > 0:\n usage += \" \"\n usage += \" \".join([parg[0] for parg in pargs])\n\n # add explanation for pargs if any of them has helptext\n\n hpargs = filter(lambda parg: str.strip(parg[2]), pargs)\n\n if hpargs:\n usage += \" \\n\\narguments:\"\n\n for (name, type, help) in pargs:\n usage += \"\\n %s %s\" % (name.ljust(12), help)\n\n # then parse option definitions\n\n parser = OptionParser(usage=usage)\n\n for optdef in filter(is_option, optdefs):\n handle_option(parser, optdef)\n\n return pargs, parser\n\n\ndef che(func, optdefs, sysargs=None):\n\n if not called_from_main():\n return\n\n # to allow semicolons with syntax \\;\n\n optdefs = optdefs.replace(\"\\;\", \"@@@@semicolon@@@@\")\n optdefs = optdefs.replace(\";\", \"\\n\")\n optdefs = optdefs.replace(\"@@@@semicolon@@@@\", \";\")\n optdefs = optdefs.replace(\"\\r\", \"\\n\")\n\n lines = [l.strip() for l in optdefs.split(\"\\n\")]\n pargs, parser = pargs_n_opts(lines)\n\n if sysargs == None:\n sysargs = sys.argv[1:]\n\n opts, cargs = parser.parse_args(sysargs)\n\n if len(cargs) != len(pargs):\n parser.print_help()\n if cargs:\n sys.exit(\"\\nERROR: wrong number of arguments %s vs. %s\"\n % (cargs, pargs))\n else:\n sys.exit()\n\n # Now we go through command line args and set up the list of args\n\n arglist = []\n\n for carg, (name, cast, help) in zip(cargs, pargs):\n try:\n arglist.append(casts[cast](carg))\n except ValueError:\n parser.print_help()\n sys.exit('\\nERROR: invalid type for \"%s\". \"%s\" is not %s'\n % (name, carg, cast))\n\n # move opts to dictionary kws\n\n kws = {}\n\n optdests = [o.dest\n for o in chain(parser._short_opt.values(),\n parser._long_opt.values())\n if o.dest]\n\n for d in optdests:\n val = getattr(opts, d)\n if val != None:\n kws[d.replace(\"-\", \"_\")] = val\n\n return func(*arglist, **kws)\n\n\ndef teller(*args, **kws): # For debugging purposes\n print(\"args =\", args)\n print(\"kws =\", kws)\n\n\nif __name__ == \"__main__\":\n che(teller, open(sys.argv.pop(1)).read())\n", "repo_name": "tomisilander/coliche", "sub_path": "coliche.py", "file_name": "coliche.py", "file_ext": "py", "file_size_in_byte": 4914, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "inspect.stack", "line_number": 8, "usage_type": "call"}, {"api_name": "inspect.getmembers", "line_number": 13, "usage_type": "call"}, {"api_name": "optparse.OptionParser", "line_number": 138, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 162, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 169, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 172, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 183, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 191, "usage_type": "call"}, {"api_name": "sys.argv.pop", "line_number": 209, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 209, "usage_type": "attribute"}]} +{"seq_id": "1558685822", "text": "from flask import Flask, render_template, request\nimport datetime, json, time, requests, yaml\nimport array, fcntl, time, signal, sys, random, re\napp = Flask(__name__)\n\nspi = file(\"/dev/spidev0.0\", \"wb\")\nfcntl.ioctl(spi, 0x40046b04, array.array('L', [400000]))\n\n# Message Class\nclass Message:\n def getSettings(self):\n stream = open(\".settings.strings\", 'r')\n x = yaml.load(stream)\n stream = open(\".settings\", 'r')\n y = yaml.load(stream)\n self.settings = dict(x.items() + y.items())\n\n def __init__(self, direction, sender, points):\n self.getSettings()\n self.message = '
    ' + self.senderAvatar(sender) + '' + self.getRandomText(direction) % {'author': self.senderName(sender), 'number': points} + '
    '\n self.send()\n\n def getRandomText(self, direction):\n if direction == 'plus':\n self.color = 'green'\n return random.choice(self.settings[direction])\n elif direction == 'minus':\n self.color = 'red'\n return random.choice(self.settings[direction])\n else:\n return 'Unknown text'\n\n def senderName(self, sender):\n return '' + sender['login'] + ''\n\n def senderAvatar(self, sender):\n return ''\n\n def send(self):\n host = 'https://api.hipchat.com'\n path = '/v1/rooms/message'\n headers = { 'Content-type': 'application/x-www-form-urlencoded', 'User-Agent': 'RaspberryPi' }\n data = { 'room_id': self.settings['room_id'], 'from': self.settings['author'], 'message': self.message, 'message_format': 'html', 'color': self.color, 'format': 'json', 'auth_token': self.settings['hipchat_secret'] }\n r = requests.post(host + path, data=data, headers=headers)\n\n# Christmas Tree class\nclass ChristmasTree:\n value = 0;\n settings = [];\n\n def __init__(self):\n self.getSettings()\n self.value = self.settings['initial_value']\n\n def getSettings(self):\n stream = open(\".settings\", 'r')\n self.settings = yaml.load(stream)\n\n def getValue(self):\n return self.value\n\n def plus(self, number):\n self.value += number\n if self.value >= 50:\n self.value = 49\n self.set()\n\n def minus(self, number):\n self.value -= number\n if self.value < 0:\n self.value = 0\n self.set()\n\n def set(self):\n self.getSettings()\n # Get random colored lights\n rand = []\n rand.append(random.randint(0,8))\n rand.append(random.randint(9,16))\n rand.append(random.randint(17,24))\n rand.append(random.randint(25,32))\n rand.append(random.randint(33,40))\n rand.append(random.randint(41,48))\n\n for i in range(0, self.settings['num_leds']):\n if i < self.value and i in rand:\n self.writeLed(\n {\n 'r': random.randint(0,255),\n 'g': random.randint(0,10),\n 'b': random.randint(0,10)\n }\n )\n elif i == 49 and self.value == 49:\n self.writeLed({'r': 255, 'g': 150, 'b': 0})\n elif i < self.value:\n self.writeLed({'r': 0, 'g': 200, 'b': 0})\n else:\n self.writeLed({'r': 0, 'g': 0, 'b': 0})\n\n spi.flush()\n\n def writeLed(self, color):\n rgb = bytearray(3)\n rgb[0] = color['r']\n rgb[1] = color['g']\n rgb[2] = color['b']\n spi.write(rgb)\n\n\ndef push(response):\n branch = response['ref']\n if branch.startswith('refs/heads/'):\n branch = re.sub('refs/heads/', '', branch);\n master_branch = response['repository']['master_branch']\n sender = response['sender']\n points = len(response['commits'])\n is_merged = response['head_commit']['message'].startswith('Merge pull request')\n\n # do something\n if branch == master_branch and not is_merged:\n GITree.minus(points)\n Message('minus', sender, points)\n elif branch == master_branch and is_merged:\n GITree.plus(3)\n Message('plus', sender, 3)\n else:\n GITree.plus(points)\n Message('plus', sender, points)\n\ndef create(sender):\n GITree.plus(2)\n Message('plus', sender, 2)\n\ndef pull_request(sender):\n GITree.plus(2)\n Message('plus', sender, 2)\n\ndef issue_comment(sender):\n GITree.plus(1)\n Message('plus', sender, 1)\n\n\n# define new Christmas tree object\nGITree = ChristmasTree()\n\n@app.route(\"/\", methods=['GET'])\ndef index():\n return render_template('index.html')\n\n@app.route(\"/endpoint\", methods=['GET', 'POST'])\ndef endpoint():\n if request.headers.get('X-GitHub-Event') is None:\n return \"X-Github-Event header required\", 400;\n\n event = request.headers.get('X-GitHub-Event')\n\n # Get JSON from input.\n response = request.get_json()\n if event == \"push\":\n push(response)\n elif event == \"create\":\n create(response['sender'])\n elif event == \"pull_request\":\n pull_request(response['sender'])\n elif event == \"issue_comment\":\n issue_comment(response['sender'])\n else:\n return 'This event is not yet supported', 200\n\n return 'ok', 200\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=80, debug=True)\n", "repo_name": "eiriksm/christmas-tree", "sub_path": "webserver.py", "file_name": "webserver.py", "file_ext": "py", "file_size_in_byte": 4982, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "2", "api": [{"api_name": "flask.Flask", "line_number": 4, "usage_type": "call"}, {"api_name": "fcntl.ioctl", "line_number": 7, "usage_type": "call"}, {"api_name": "array.array", "line_number": 7, "usage_type": "call"}, {"api_name": "yaml.load", "line_number": 13, "usage_type": "call"}, {"api_name": "yaml.load", "line_number": 15, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 26, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 29, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 44, "usage_type": "call"}, {"api_name": "yaml.load", "line_number": 57, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 78, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 79, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 80, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 81, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 82, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 83, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 89, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 90, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 91, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 114, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 149, "usage_type": "call"}, {"api_name": "flask.request.headers.get", "line_number": 153, "usage_type": "call"}, {"api_name": "flask.request.headers", "line_number": 153, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 153, "usage_type": "name"}, {"api_name": "flask.request.headers.get", "line_number": 156, "usage_type": "call"}, {"api_name": "flask.request.headers", "line_number": 156, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 156, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 159, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 159, "usage_type": "name"}]} +{"seq_id": "72866901507", "text": "import math\nfrom datetime import date\n\ntoday = date.today()\n\nprint('Hello, today is ' + str(today))\n\nbs = int(input('Blood Sugar: '))\nbst = int(input('Blood Sugar Target: '))\nlist = []\nn = int(input('Enter how many times you take insulin in a day: '))\n\nfor i in range(0,n):\n dosage = float(input('Enter insulin dosage: '))\n list.append(dosage)\n\nttd = sum(list)\nprint(\"Total insulin dosage per day:\",ttd)\n\ninsulintype = str(input('Name of Bolus Insulin being used: '))\n\nI1 = ['Humolog','Novolog','Apidra']\n\nif insulintype in I1:\n crcf=1500/ttd\n print(\"correction factor is:\",crcf)\nelse:\n crcf=1800/ttd\n print(\"correction factor is:\",crcf)\n\ninsamt = float((bs - bst) / (crcf))\ncarbs = int(input('Carbohydrates: '))\ncarb_ratio = int(input('Insulin to carbohydrate ratio is 1: '))\ncarb_crct = float((carbs / carb_ratio))\n\ni = round((insamt + carb_crct),2)\nj=math.floor(i)\nif(j<= i < j+0.3):\n insulin= j\nelif(j+0.3 <= i < j+0.7):\n insulin = j+0.5\nelif(j+0.7 <= i None:\n if \"global\" in self.themeData:\n editWidget.setColor(QColor(self.themeData[\"global\"].get(\"textColor\", \"#000000\")))\n editWidget.setPaper(QColor(self.themeData[\"global\"].get(\"backgroundColor\", \"#FFFFFF\")))\n editWidget.setSelectionForegroundColor(QColor(self.themeData[\"global\"].get(\"selectionForegroundColor\", \"#FFFFFF\")))\n editWidget.setSelectionBackgroundColor(QColor(self.themeData[\"global\"].get(\"selectionBackgroundColor\", \"#308CC6\")))\n editWidget.setMarginsBackgroundColor(QColor(self.themeData[\"global\"].get(\"marginsBackgroundColor\", \"#cccccc\")))\n editWidget.setMarginsForegroundColor(QColor(self.themeData[\"global\"].get(\"marginsForegroundColor\", \"#000000\")))\n editWidget.setCaretLineBackgroundColor(QColor(self.themeData[\"global\"].get(\"caretColor\", \"#ffff00\")))\n if not lexer:\n return\n if \"global\" in self.themeData:\n lexer.setPaper(QColor(self.themeData[\"global\"].get(\"backgroundColor\", \"#FFFFFF\")))\n lexer.setColor(QColor(self.themeData[\"global\"].get(\"textColor\", \"#000000\")))\n lexer.setDefaultPaper(QColor(self.themeData[\"global\"].get(\"backgroundColor\", \"#FFFFFF\")))\n lexer.setDefaultColor(QColor(self.themeData[\"global\"].get(\"textColor\", \"#000000\")))\n lexerLanguage = lexer.language()\n if lexerLanguage not in self.themeData[\"lexer\"]:\n return\n for key, value in getLexerStyles(lexer).items():\n if key in self.themeData[\"lexer\"][lexerLanguage]:\n lexer.setColor(QColor(self.themeData[\"lexer\"][lexerLanguage][key]), value)\n\n def getName(self) -> str:\n return self.themeData[\"name\"]\n\n def getID(self) -> str:\n return self.themeData[\"id\"]\n", "repo_name": "JakobDev/jdTextEdit", "sub_path": "jdTextEdit/core/FileTheme.py", "file_name": "FileTheme.py", "file_ext": "py", "file_size_in_byte": 2667, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "25", "api": [{"api_name": "jdTextEdit.api.ThemeBase.ThemeBase", "line_number": 9, "usage_type": "name"}, {"api_name": "jdTextEdit.Functions.readJsonFile", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 20, "usage_type": "attribute"}, {"api_name": "PyQt6.QtGui.QColor", "line_number": 31, "usage_type": "call"}, {"api_name": "PyQt6.QtGui.QColor", "line_number": 32, "usage_type": "call"}, {"api_name": "PyQt6.QtGui.QColor", "line_number": 33, "usage_type": "call"}, {"api_name": "PyQt6.QtGui.QColor", "line_number": 34, "usage_type": "call"}, {"api_name": "PyQt6.QtGui.QColor", "line_number": 35, "usage_type": "call"}, {"api_name": "PyQt6.QtGui.QColor", "line_number": 36, "usage_type": "call"}, {"api_name": "PyQt6.QtGui.QColor", "line_number": 37, "usage_type": "call"}, {"api_name": "PyQt6.QtGui.QColor", "line_number": 41, "usage_type": "call"}, {"api_name": "PyQt6.QtGui.QColor", "line_number": 42, "usage_type": "call"}, {"api_name": "PyQt6.QtGui.QColor", "line_number": 43, "usage_type": "call"}, {"api_name": "PyQt6.QtGui.QColor", "line_number": 44, "usage_type": "call"}, {"api_name": "jdTextEdit.Functions.getLexerStyles", "line_number": 48, "usage_type": "call"}, {"api_name": "PyQt6.QtGui.QColor", "line_number": 50, "usage_type": "call"}]} +{"seq_id": "37389757586", "text": "import os\nfrom django.conf import settings\nimport datetime\n\ndef blog_directory_path(instance, filename):\n \n date_fields = str(datetime.date.today()).split('-')\n year = date_fields[0]\n month = date_fields[1]\n day = date_fields[2]\n\n # file will be uploaded to MEDIA_ROOT/blog/YEAR/MONTH/DAY//__\n blog_sub_path = 'produits/{0}/{1}/{2}/blog/{3}/image_{4}'.format(year, month, day,instance.id, filename)\n blog_full_path = os.path.join(settings.MEDIA_ROOT, blog_sub_path)\n if os.path.exists(blog_full_path):\n os.remove(blog_full_path)\n return blog_sub_path\n", "repo_name": "miyou995/octosite", "sub_path": "backend/posts/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 610, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "datetime.date.today", "line_number": 7, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "django.conf.settings.MEDIA_ROOT", "line_number": 14, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 14, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 16, "usage_type": "call"}]} +{"seq_id": "8700762484", "text": "import cv2\nfrom cv2 import VideoCapture\nfrom cv2 import dnn_DetectionModel\nimport numpy as np\nimport matplotlib as plt\n\n# opencv DNN\nnet = cv2.dnn.readNet('./dnn_model/yolov4-tiny.weights', './dnn_model/yolov4-tiny.cfg')\nmodel = cv2.dnn_DetectionModel(net)\n# 調整 DNN 與 opencv 的基本參數\nmodel.setInputParams(size = (416,416), scale = 1/255)\n\n# 模型偵測 txt\nclasses = []\nwith open(\"./dnn_model/classes.txt\", 'r') as file_object:\n for class_name in file_object.readlines():\n classname = class_name.strip()\n classes.append(class_name)\n \n# 相機刷新\ncap = cv2.VideoCapture(\"./utils/Alisa Stewart Honor Walk.mp4\")\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)\n\n\nwhile cap.isOpened():\n # 解讀相機拍到的圖片\n ret, frame = cap.read()\n if not ret:\n print(\"找不到影像輸入\")\n break\n \n # 物件偵測 (引用訓練好的模型) \n (class_ids, scores, bboxes) = model.detect(frame)\n for class_id, score, bbox in zip(class_ids, scores, bboxes):\n (x, y, w, h)= bbox\n class_name = classes[class_id]\n # print(bbox)\n # 繪製框框與偵測到的物件資訊\n cv2.putText(frame, class_name, (x, y-7), cv2.FONT_HERSHEY_SIMPLEX, 1.3, (139,61,72),2)\n cv2.rectangle(frame, (x,y), (x+w,y+h), (255,102,178), 3)\n # print('class_ids', class_ids)\n # print('score', scores)\n # print('bboxes', bboxes)\n # 展示圖片與停頓(構成影片)\n cv2.imshow('test', frame)\n if cv2.waitKey(1) == ord('q'):\n break\n", "repo_name": "weifish0/YOLOV4-easy-Object-Detection", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1570, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "cv2.dnn.readNet", "line_number": 8, "usage_type": "call"}, {"api_name": "cv2.dnn", "line_number": 8, "usage_type": "attribute"}, {"api_name": "cv2.dnn_DetectionModel", "line_number": 9, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 21, "usage_type": "call"}, {"api_name": "cv2.CAP_PROP_FRAME_WIDTH", "line_number": 22, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FRAME_HEIGHT", "line_number": 23, "usage_type": "attribute"}, {"api_name": "cv2.putText", "line_number": 40, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 40, "usage_type": "attribute"}, {"api_name": "cv2.rectangle", "line_number": 41, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 46, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 47, "usage_type": "call"}]} +{"seq_id": "36827458908", "text": "from typing import Any\n\nfrom grizzly_main.deploy.spark.pyspark_examples.pyspark_example_dict import pyspark_example_dict\nfrom grizzly_main.deploy.spark.utils.spark_context import get_spark_context\n\n\ndef run_pyspark_example(example_name: str, example_kwargs: dict[str, Any], run_mode: str) -> None:\n \"\"\"\n Run pyspark example\n :param example_name: Pyspark example name\n :param example_kwargs: Pyspark example kwargs\n :param run_mode: Run mode\n :return: None\n \"\"\"\n spark = get_spark_context(app_name=example_name, run_mode=run_mode)\n pyspark_example_dict[example_name](spark=spark, **example_kwargs) # type: ignore\n spark.stop()\n\n\nif __name__ == \"__main__\":\n # Inputs\n is_run_on_cluster = True\n example_name_ = \"pyspark_example_1\"\n # example_name_ = \"pyspark_example_2\"\n example_kwargs_: dict[str, Any] = {}\n\n # Example trigger\n if is_run_on_cluster:\n run_mode_ = \"local_cluster\"\n else:\n run_mode_ = \"local_single_worker\"\n run_pyspark_example(example_name=example_name_, example_kwargs=example_kwargs_, run_mode=run_mode_)\n", "repo_name": "madconsulting/grizzly", "sub_path": "grizzly_main/deploy/spark/local/run_pyspark_example.py", "file_name": "run_pyspark_example.py", "file_ext": "py", "file_size_in_byte": 1092, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.Any", "line_number": 7, "usage_type": "name"}, {"api_name": "grizzly_main.deploy.spark.utils.spark_context.get_spark_context", "line_number": 15, "usage_type": "call"}, {"api_name": "grizzly_main.deploy.spark.pyspark_examples.pyspark_example_dict.pyspark_example_dict", "line_number": 16, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 25, "usage_type": "name"}]} +{"seq_id": "1899205089", "text": "\n# my creations\nfrom fancy_distributions import Multimodal_MultivariateNormal, Multimodal_Normal, stack\nfrom fitting_tools import Fitting_nnModule, MLP_res_net, get_nuy_and_auto_norm, Norm\nfrom static_distribution_modeling import Dependent_dist\nimport random\n\nfrom time import time\nimport numpy as np\nimport torch\nfrom torch import nn\n\n#todo: \n# nf='sim'\n# giving measures for the multi-step-ahead for the validation (given to Multi_step_result?)\n# Inherets from Meta_SS_model creates an additional \n# This becomes a multiple inherentece problem?\n\nclass Meta_SS_model(Fitting_nnModule):\n def __init__(self, nu, ny, norm: Norm = Norm(), nz=5, n_weights=10, \\\n meta_state_advance_net = MLP_res_net, meta_state_advance_kwargs = {},\n meta_state_to_output_dist_net = Dependent_dist, meta_state_to_output_dist_kwargs=dict(n_weights=10)):\n super(Meta_SS_model, self).__init__()\n self.nz = nz\n self.ny = ny\n self.nu = nu\n self.ny_val = 1 if self.ny is None else self.ny\n self.nu_val = 1 if self.nu is None else self.nu\n self.norm = norm\n self.meta_state_advance = meta_state_advance_net(n_in=nz + self.nu_val, n_out=nz, \\\n **meta_state_advance_kwargs)\n self.meta_state_to_output_dist = meta_state_to_output_dist_net(nz=nz, ny=ny, norm=Norm(), \\\n **meta_state_to_output_dist_kwargs) #no norm here?\n\n def make_training_data(self, uy, nf=50, parameter_init=True, **kwargs):\n u,y = uy\n u = self.norm.input_transform(u)\n y = self.norm.output_transform(y)\n U, Y = [], []\n for i in range(nf,len(u)+1):\n U.append(u[i-nf:i])\n Y.append(y[i-nf:i])\n self.init_z = nn.Parameter(torch.randn((len(U), self.nz))) if parameter_init else torch.zeros((len(U), self.nz))\n ufuture = torch.as_tensor(np.array(U), dtype=torch.float32)\n yfuture = torch.as_tensor(np.array(Y), dtype=torch.float32)\n return ufuture, yfuture, self.init_z\n \n def simulate(self, ufuture, yfuture, init_z, return_z=False):\n zt = init_z\n ydist_preds = []\n ufuture = ufuture[:,:,None] if self.nu is None else ufuture\n zvecs = [] #(Ntime, Nb, nz)\n for ut, yt in zip(torch.transpose(ufuture,0,1),torch.transpose(yfuture,0,1)):\n ydist_pred = self.meta_state_to_output_dist.get_dist_normed(zt)\n ydist_preds.append(ydist_pred)\n zvecs.append(zt) \n zu = torch.cat([zt, ut], dim=1)\n zt = self.meta_state_advance(zu)\n ydist_preds = stack(ydist_preds,dim=1) #size is (Nbatch, )\n return (ydist_preds, torch.stack(zvecs,dim=1)) if return_z else ydist_preds\n\n def loss(self, u, y, init_z, burn_time=0, **kwargs):\n ydist_preds = self.simulate(u, y, init_z)\n return torch.mean(-ydist_preds[:,burn_time:].log_prob(y[:,burn_time:]))/self.ny_val + - 1.4189385332046727417803297364056176\n\n def multi_step(self, uydata, nf=100):\n nf = len(uydata[0]) if nf=='sim' else nf\n ufuture, yfuture, init_z = self.make_training_data(uydata, nf=nf)\n with torch.no_grad():\n y_dists, zfuture = self.simulate(ufuture, yfuture, init_z, return_z=True)\n I = self.norm.input_inverse_transform\n O = self.norm.output_inverse_transform\n test_norm = Norm(uydata[0], uydata[1])\n return Multi_step_result(O(yfuture), O(y_dists), test_norm, data=uydata, ufuture=I(ufuture), zfuture=zfuture)\n\nclass Meta_SS_model_encoder(Meta_SS_model):\n def __init__(self, nu: int, ny: int, norm: Norm = Norm(), nz: int=5, na: int=6, nb: int=6,\\\n meta_state_advance_net = MLP_res_net, meta_state_advance_kwargs = {},\\\n meta_state_to_output_dist_net = Dependent_dist, meta_state_to_output_dist_kwargs=dict(n_weights=10),\\\n past_to_meta_state_net = MLP_res_net, past_to_meta_state_kwargs={}):\n super(Meta_SS_model_encoder, self).__init__(nu, ny, norm, nz, meta_state_advance_net=meta_state_advance_net,\\\n meta_state_advance_kwargs=meta_state_advance_kwargs, meta_state_to_output_dist_net=meta_state_to_output_dist_net,\\\n meta_state_to_output_dist_kwargs=meta_state_to_output_dist_kwargs)\n self.na = na\n self.nb = nb\n self.past_to_meta_state = past_to_meta_state_net(self.nu_val*nb+self.ny_val*na, nz, **past_to_meta_state_kwargs)\n def make_training_data(self, uy, nf=50, **kwargs):\n u,y = uy\n u = self.norm.input_transform(u)\n y = self.norm.output_transform(y)\n ufuture, yfuture, upast, ypast = [], [], [], []\n for i in range(nf+max(self.na, self.nb),len(u)+1):\n ufuture.append(u[i-nf:i])\n yfuture.append(y[i-nf:i])\n upast.append(u[i-nf-self.nb:i-nf])\n ypast.append(y[i-nf-self.na:i-nf]) #here was the error u -> y\n as_tensor = lambda x: [torch.as_tensor(np.array(xi), dtype=torch.float32) for xi in x]\n return as_tensor([upast, ypast, ufuture, yfuture])\n def simulate(self, upast, ypast, ufuture, yfuture, return_z=False):\n Nb = upast.shape[0]\n init_z = self.past_to_meta_state(torch.cat([upast.view(Nb,-1), ypast.view(Nb,-1)],dim=1))\n return super().simulate(ufuture, yfuture, init_z, return_z=return_z)\n def loss(self, upast, ypast, ufuture, yfuture, **kwargs):\n ydist_preds = self.simulate(upast, ypast, ufuture, yfuture)\n return torch.mean(-ydist_preds.log_prob(yfuture))/self.ny_val + - 1.4189385332046727417803297364056176\n def multi_step(self, uydata, nf=100):\n nf = len(uydata[0])-max(self.na, self.nb) if nf=='sim' else nf\n upast, ypast, ufuture, yfuture = self.make_training_data(uydata, nf=nf)\n with torch.no_grad():\n y_dists, zfuture = self.simulate(upast, ypast, ufuture, yfuture, return_z=True)\n I = self.norm.input_inverse_transform\n O = self.norm.output_inverse_transform\n test_norm = Norm(uydata[0], uydata[1])\n return Multi_step_result(O(yfuture), O(y_dists), test_norm, \\\n data=uydata, ufuture=I(ufuture), upast=I(upast), ypast=O(ypast), zfuture=zfuture)\n\nclass Meta_SS_model_measure_encoder(Meta_SS_model_encoder): #always includes an encoder\n '''\n z_t+1^t = f^t(z_t^m, u_t)\n z_t+1^m = f^m(z_t+1^t, y_t+1)\n p(y_t| z_t^t) is the output (if z_t^m than it model could be a identity and be oke)\n '''\n def __init__(self, nu: int, ny: int, norm: Norm = Norm(), nz: int=5, na: int=6, nb: int=6,\\\n meta_state_advance_net = MLP_res_net, meta_state_advance_kwargs = {},\\\n meta_state_to_output_dist_net = Dependent_dist, meta_state_to_output_dist_kwargs=dict(n_weights=10),\\\n past_to_meta_state_net = MLP_res_net, past_to_meta_state_kwargs={}, \n measure_update_net = MLP_res_net, measure_update_kwargs={}):\n super(Meta_SS_model_measure_encoder, self).__init__(nu, ny, norm, nz, na, nb, meta_state_advance_net=meta_state_advance_net,\\\n meta_state_advance_kwargs=meta_state_advance_kwargs, meta_state_to_output_dist_net=meta_state_to_output_dist_net,\\\n meta_state_to_output_dist_kwargs=meta_state_to_output_dist_kwargs, past_to_meta_state_net=past_to_meta_state_net,\\\n past_to_meta_state_kwargs=past_to_meta_state_kwargs)\n ny_val = 1 if ny is None else ny\n self.measure_update = measure_update_net(n_in=ny_val+nz, n_out=nz, **measure_update_kwargs)\n def loss(self, upast, ypast, ufuture, yfuture, filter_p = 1, **kwargs):\n ydist_preds = self.filter(upast, ypast, ufuture, yfuture, filter_p=filter_p)\n return torch.mean(-ydist_preds.log_prob(yfuture))/self.ny_val + - 1.4189385332046727417803297364056176\n def filter(self, upast, ypast, ufuture, yfuture, filter_p = 1, return_z=False, sample_filter_p = 0): #a bit of duplicate code but it's fine. \n Nb = upast.shape[0]\n zt = self.past_to_meta_state(torch.cat([upast.view(Nb,-1), ypast.view(Nb,-1)],dim=1))\n ydist_preds = []\n ufuture = ufuture[:,:,None] if self.nu is None else ufuture\n yfuture = yfuture[:,:,None] if self.ny is None else yfuture\n zvecs = [] #(Ntime, Nb, nz)\n for ut, yt in zip(torch.transpose(ufuture,0,1),torch.transpose(yfuture,0,1)):\n ydist_pred = self.meta_state_to_output_dist.get_dist_normed(zt)\n ydist_preds.append(ydist_pred)\n zvecs.append(zt)\n if random.random() ',dev)\n while select not in all_dev:\n select = input(' Sheet : ') \n\n dev = all_dev[select]\n self.struc = self.struc[dev]\n self.ws = xlrd.open_workbook(input_testplan).sheet_by_name(dev)\n \n self.coordinate = self.die_info()\n if len(self.coordinate) == 0:\n print(' none golden die...');exit()\n else:\n fig=plt.figure()\n self.ax = fig.add_subplot(111,aspect='equal')\n self.draw()\n time0 = time.strftime(\"%Y%m%d\", time.localtime()) \n fig.savefig(path + '/output/' + 'golden_die_map_%s.png'%time0)\n print(' golden_die_map_%s 已生成完毕...'%time0)\n \n def title_col_data(self,title):\n first_row = self.ws.row_values(0)\n index = first_row.index(title)\n return self.ws.col_values(index)[1:]\n\n def die_info(self):\n dies = self.title_col_data('Golden_Die') \n dies_ = []\n for die in dies:\n x_y = re.findall('-?\\d',die)\n if x_y == [] : pass\n else : dies_.append((eval(x_y[0]),eval(x_y[1]))) \n return dies_\n\n def non_repeat(self):\n dies_ = self.coordinate\n return len(set(dies_))\n \n def radius(self):\n # max value of coordinates\n s = str(self.coordinate).lstrip('[').rstrip(']').replace('(','').replace(')','')\n maxXY = max([abs(eval(x)) for x in s.split(',') if x.strip()])\n return maxXY + 1 \n \n def draw(self):\n maxDie = self.radius()\n # draw a circle\n self.addCircle(0,0,maxDie,'none','black')\n # draw squares\n for die in [(x,y) for x in range(-maxDie+1,maxDie) for y in range(-maxDie+1,maxDie)]:\n x,y = die[0],die[1]\n if die in self.coordinate:\n self.addRectangle(x,y,'blue','white')\n else:\n if (abs(x)+0.5)**2 + (abs(y)+0.5)**2 <= maxDie**2:\n self.addRectangle(x,y,'grey','white') \n self.style()\n\n def style(self):\n maxDie = self.radius()\n try:\n self.ax.set_xticks(range(-maxDie,maxDie+1))\n self.ax.set_yticks(range(-maxDie,maxDie+1))\n self.ax.set_xlim(-maxDie,maxDie)\n self.ax.set_ylim(-maxDie,maxDie)\n except:\n pass\n self.ax.invert_yaxis() \n plt.title('Total : %s'%self.non_repeat())\n\n def addCircle(self,x,y,radius,faceColor,edgeColor):\n self.ax.add_patch(patches.Circle(\n (x,y), # center\n radius, # radius\n facecolor = faceColor,\n edgecolor = edgeColor)\n )\n\n def addRectangle(self,x,y,faceColor,edgeColor):\n self.ax.add_patch(patches.Rectangle(\n (x-0.5,y-0.5), # left,bottom\n 1, # width\n 1, # height\n facecolor = faceColor,\n edgecolor = edgeColor)\n )\nif __name__=='__main__':\n Main() ", "repo_name": "whyeemcc/Klayout-Pad-Extraction", "sub_path": "coordinate_&_testplan/script/Golden_Die_Wafer_Map.py", "file_name": "Golden_Die_Wafer_Map.py", "file_ext": "py", "file_size_in_byte": 3897, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sys.path", "line_number": 16, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 21, "usage_type": "call"}, {"api_name": "xlrd.open_workbook", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "time.strftime", "line_number": 41, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 41, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 93, "usage_type": "name"}, {"api_name": "matplotlib.patches.Circle", "line_number": 96, "usage_type": "call"}, {"api_name": "matplotlib.patches", "line_number": 96, "usage_type": "name"}, {"api_name": "matplotlib.patches.Rectangle", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.patches", "line_number": 104, "usage_type": "name"}]} +{"seq_id": "19887353212", "text": "#!/usr/bin/env python\n\n\nfrom random import randint\nimport rospy\nfrom time import sleep\nfrom std_msgs.msg import UInt32\nimport tf\nfrom tf.transformations import quaternion_from_euler\nimport math as m\n\n\nservo_msg = UInt32()\n\n\ndef servoCallback(msg):\n global servo_msg\n servo_msg = msg\n\n\nif __name__ == \"__main__\":\n rospy.init_node(\"servo_joint\")\n\n tf_pub = tf.TransformBroadcaster()\n\n rospy.Subscriber(\"servo\", UInt32, callback=servoCallback)\n\n r = rospy.Rate(10)\n while not rospy.is_shutdown():\n\n quat = quaternion_from_euler(0., m.radians(servo_msg.data - 40), 0.)\n\n tf_pub.sendTransform(\n translation=[0., 3., 5.],\n rotation=quat,\n time=rospy.Time.now(),\n child=\"servo_arm\",\n parent=\"servo_support\"\n )\n\n r.sleep()\n", "repo_name": "7cmdehdrb/1-DOF-PID-Control", "sub_path": "src/servo_joint.py", "file_name": "servo_joint.py", "file_ext": "py", "file_size_in_byte": 819, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "std_msgs.msg.UInt32", "line_number": 13, "usage_type": "call"}, {"api_name": "rospy.init_node", "line_number": 22, "usage_type": "call"}, {"api_name": "tf.TransformBroadcaster", "line_number": 24, "usage_type": "call"}, {"api_name": "rospy.Subscriber", "line_number": 26, "usage_type": "call"}, {"api_name": "std_msgs.msg.UInt32", "line_number": 26, "usage_type": "argument"}, {"api_name": "rospy.Rate", "line_number": 28, "usage_type": "call"}, {"api_name": "rospy.is_shutdown", "line_number": 29, "usage_type": "call"}, {"api_name": "tf.transformations.quaternion_from_euler", "line_number": 31, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 31, "usage_type": "call"}, {"api_name": "rospy.Time.now", "line_number": 36, "usage_type": "call"}, {"api_name": "rospy.Time", "line_number": 36, "usage_type": "attribute"}]} +{"seq_id": "30799362495", "text": "import dpkt\nimport logging\n\nlogging.getLogger(\"scapy.runtime\").setLevel(logging.ERROR)\nfrom scapy.all import *\nfrom scapy.layers.dot11 import Dot11Beacon\n\nintfmon = \"wlan0\"\n\n\ndef PacketHandler(pkt):\n rawdata = pkt.build()\n tap = dpkt.radiotap.Radiotap(rawdata)\n signal = tap.ant_sig.db\n bssid = pkt.addr3\n essid = pkt.info\n print(f\"BSSID:{bssid} ESSID:{essid} \\t ({signal} dBm)\")\n\n\nsniff(iface=intfmon, prn=PacketHandler, lfilter=lambda p: Dot11Beacon in p)\n", "repo_name": "drmteba/wifi_example", "sub_path": "example_004.py", "file_name": "example_004.py", "file_ext": "py", "file_size_in_byte": 476, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "logging.getLogger", "line_number": 4, "usage_type": "call"}, {"api_name": "logging.ERROR", "line_number": 4, "usage_type": "attribute"}, {"api_name": "dpkt.radiotap.Radiotap", "line_number": 13, "usage_type": "call"}, {"api_name": "dpkt.radiotap", "line_number": 13, "usage_type": "attribute"}, {"api_name": "scapy.layers.dot11.Dot11Beacon", "line_number": 20, "usage_type": "name"}]} +{"seq_id": "9451904637", "text": "\nfrom pyspark.sql import SparkSession\nspark = SparkSession.builder.master(\"local[*]\").getOrCreate()\n\nfrom pyspark.sql import DataFrameWriter\n\n#\"jdbc:oracle:thin:username/password@//hostname:portnumber/SID\"\n\n#myrdd1 = spark.read.format(\"jdbc\").options(url=\"jdbc:oracle:thin:user2/user2@//192.168.1.151:1521/xe \",driver=\"oracle.jdbc.OracleDriver\",dbtable=\"DEPT\").load().take(10)\n\nmyrdd1 = spark.read\\\n .format(\"jdbc\")\\\n .option(\"url\", \"jdbc:sqlite:/home/sammy/snap/dbeaver-ce/94/.local/share/DBeaverData/workspace6/.metadata/sample-database-sqlite-1/Chinook.db\")\\\n .option(\"dbtable\", \"Album\")\\\n .option(\"driver\", \"org.sqlite.JDBC\").load()\n\n#my_writer = DataFrameWriter(myrdd1)\n\nmyrdd2 = spark.read\\\n .format(\"jdbc\")\\\n .option(\"url\", \"jdbc:sqlite:/home/sammy/Learning_pyspark/SQLITE/STG.db\")\\\n .option(\"dbtable\", \"STG_FireIncidents\")\\\n .option(\"driver\", \"org.sqlite.JDBC\").load()\n\n#myrdd3 = my_writer.jdbc\n\n\nif __name__ == '__main__':\n print('This is main')\n# print(my_writer)\n myrdd2.printSchema()\n myrdd1.write.csv(path=\"/home/sammy/Learning_pyspark/OutDir/album_out/fil.csv\", mode=\"append\",header=\"True\")\n myrdd1.write.jdbc(url =\"jdbc:sqlite:/home/sammy/Learning_pyspark/SQLITE/STG.db\",table=\"STG_Album\",mode=\"append\")\n\n myrdd2.show(2)\n\n myrdd1.show(5)\n myrdd1.describe()\n# myrdd1.collect()\n# myrdd1.count()\n\n print(\"Connected SQLLite\")\n print(myrdd1)\n\n print(myrdd1.count())\n\n", "repo_name": "samarthk/Learning_pyspark_101", "sub_path": "DE_101/src/DB_Write_SQLLite.py", "file_name": "DB_Write_SQLLite.py", "file_ext": "py", "file_size_in_byte": 1440, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pyspark.sql.SparkSession.builder.master", "line_number": 3, "usage_type": "call"}, {"api_name": "pyspark.sql.SparkSession.builder", "line_number": 3, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession", "line_number": 3, "usage_type": "name"}]} +{"seq_id": "22838998928", "text": "#!/usr/bin/env python3\n# -*- coding=utf-8 -*- \nimport pyvo\nimport warnings\nimport sys\n\ndef main():\n # Keep the output of this example \"sane\".\n if not sys.warnoptions:\n warnings.simplefilter(\"ignore\")\n\n # Query the registry to find tap service with data in the radio\n # band\n\n services=pyvo.registry.search(\n # Obscore services are special TAP Services\n servicetype=\"tap\",\n\n # We add the waveband argument\n waveband=\"radio\", \n\n # And the tricky part: obscore is a datamodel on a tap service\n datamodel=\"obscore\")\n\n print (services)\n\n\nif __name__==\"__main__\":\n main()\n", "repo_name": "hendhd/taenaris", "sub_path": "pysrc/example1/exercise_radio.py", "file_name": "exercise_radio.py", "file_ext": "py", "file_size_in_byte": 636, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "2", "api": [{"api_name": "sys.warnoptions", "line_number": 9, "usage_type": "attribute"}, {"api_name": "warnings.simplefilter", "line_number": 10, "usage_type": "call"}, {"api_name": "pyvo.registry.search", "line_number": 15, "usage_type": "call"}, {"api_name": "pyvo.registry", "line_number": 15, "usage_type": "attribute"}]} +{"seq_id": "29568276026", "text": "import glob\nimport os\n\nimport IPython\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport scipy\nfrom scipy import io\nfrom scipy.signal import medfilt\nfrom scipy.optimize import minimize\n\nfrom lib.math import *\nfrom lib import util\nfrom lib import vision\n\ndef compare(config):\n '''\n vicon data is required!\n execute 'read_bag' first\n '''\n\n task_name = config['data_name']\n nb_object = config['object']['nb_object']\n supervision = config['pose']['supervision']\n fps = config['animation']['fps']\n \n data_dir = './data/'+task_name\n pose_dir = './output/read_pose/'+task_name\n vicon_dir = './output/vicon/'+task_name\n output_dir = './output/compare_traj/'+task_name\n \n util.create_dir(output_dir, clear = True)\n \n\n demo_list = os.listdir('./data/'+task_name)\n for demo in demo_list:\n data_demo_dir = data_dir+'/'+demo\n vicon_demo_dir = vicon_dir + '/' + demo\n cam_pos0 = np.load(data_demo_dir+'/camera_position0.npy', allow_pickle = True)\n cam_pos1 = np.load(data_demo_dir+'/camera_position1.npy', allow_pickle = True)\n robot_pos0 = np.load(data_demo_dir+'/pioneer_position0.npy', allow_pickle = True)\n robot_pos1 = np.load(data_demo_dir+'/pioneer_position1.npy', allow_pickle = True)\n cut_point = np.loadtxt(data_demo_dir+'/cut.txt')\n\n util.create_dir(output_dir+'/'+demo+'/plot', clear = True)\n util.create_dir(output_dir+'/'+demo+'/pickle', clear = True)\n ## open vicon trajectory\n vision_traj_list = np.load(pose_dir+'/'+demo+'/pose_traj.npy')\n obj_files = sorted(glob.glob(vicon_demo_dir+'/*_pose.npy'))\n assert len(obj_files) == 1\n vicon_traj_list = []\n for obj_file in obj_files:\n vicon_traj_loaded = np.load(obj_file, allow_pickle = True)\n #for i in range(1,7):\n # vicon_traj_loaded[:,i] = medfilt(vicon_traj_loaded[:,i],11)\n \n vicon_traj_list.append(vicon_traj_loaded)\n\n ## open cam time\n cam_start_time = cam_pos0[0] \n cam_finish_time = cam_pos1[0]\n ## cut point\n total_img = cut_point[0]\n beginning_cut = cut_point[1]\n endding_cut = cut_point[2]\n ## modify cam start time\n play_time = cam_finish_time-cam_start_time\n cam_start_time = cam_start_time+play_time*(beginning_cut/(total_img-1))\n cam_finish_time = cam_finish_time - play_time*(endding_cut/(total_img-1))\n\n for i in range(nb_object):\n vicon_traj = vicon_traj_list[i]\n vision_traj = vision_traj_list[:,i,:]\n vicon_time = vicon_traj[:,0]\n\n vicon_start_idx = 0\n vicon_finish_idx = len(vicon_time)\n \n for i in range(len(vicon_time)):\n if vicon_time[i] < cam_start_time:\n vicon_start_idx = i\n if vicon_time[i] < cam_finish_time:\n vicon_finish_idx = i\n vicon_start_idx += 1\n\n clipped_vicon_time = vicon_time[vicon_start_idx:vicon_finish_idx]\n clipped_vicon = vicon_traj[vicon_start_idx:vicon_finish_idx, 1:7]\n \n ### align time \n len_vision = len(vision_traj)\n vision_time = np.arange(clipped_vicon_time[0], clipped_vicon_time[-1], (clipped_vicon_time[-1]-clipped_vicon_time[0])/len_vision)\n \n fig = plt.figure()\n ax = fig.add_subplot(111, projection = '3d')\n vicon_plot = np.zeros((0,3))\n vicon_se3 = np.zeros((0,6))\n vision_plot = np.zeros((0,3))\n vision_se3 = np.zeros((0,6))\n\n obj_vicon = vision.SE3object(np.zeros(6), angle_type = 'axis')\n obj_vision = vision.SE3object(np.zeros(6), angle_type = 'axis')\n v_t = 1\n\n for t in range(len(vision_traj)): # ah\n for tt in range(v_t-1, len(clipped_vicon_time)):\n if clipped_vicon_time[tt] > vision_time[t]:\n break\n v_t = tt\n #print('vision_time:%04.04f'%vision_time[t])\n #print('vicon_time:%04.04f'%clipped_vicon_time[v_t])\n #print('\\n')\n \n ## time\n vicon_T = se3_to_SE3(clipped_vicon[v_t,:])\n vision_T = se3_to_SE3(vision_traj[t,:])\n vicon_plot = np.concatenate([vicon_plot, np.expand_dims(vicon_T[0:3,3],0) ], 0)\n vision_plot = np.concatenate([vision_plot, np.expand_dims(vision_T[0:3,3],0)], 0)\n\n vicon_se3_element = SE3_to_se3(se3_to_SE3(clipped_vicon[v_t,:]))\n vicon_se3 = np.concatenate([vicon_se3, np.expand_dims(vicon_se3_element,0) ], 0)\n vision_se3 = np.concatenate([vision_se3, np.expand_dims( SE3_to_se3(vision_T),0)], 0)\n \n plt.close('all')\n ## align translation\n x0 = np.random.rand(12)\n optimize_len = int(len(vision_plot))\n ########################## for task3 (occlusion)\n #if task_name == 'task3':\n # optimize_len = 100\n def objective_fn(x0):\n SE30 = se3_to_SE3(x0[0:6])\n SE31 = se3_to_SE3(x0[6:12])\n loss = 0\n for t in range(optimize_len):\n transformed = np.matmul(np.matmul(SE30, se3_to_SE3(vision_se3[t,:])),SE31)\n transformed_se3 = SE3_to_se3(transformed)\n loss += np.sum(np.square(transformed_se3[:]-vicon_se3[t,:]))\n \n #transformed = un_homo( np.matmul(np.matmul(SE30, to_homo(vision_plot[t,:])),SE31))\n #loss += np.sum(np.square(transformed-vicon_plot[t,:]))\n return loss\n print(demo)\n print('initial_loss:'+str(objective_fn(x0)))\n if False:\n result = np.load(output_dir+'/'+demo+'/optimization.npy').item() \n else:\n #'''\n result = minimize(objective_fn, \n x0, \n method='BFGS', \n tol=1e-7,\n options={'gtol': 1e-6, 'disp': True})\n \n #'''\n '''\n result = minimize(objective_fn, \n x0, \n method='Nelder-Mead',\n options={'maxiter':1})\n '''\n np.save(output_dir+'/'+demo+'/optimization.npy',result)\n print('optimized_loss:'+str(objective_fn(result.x))) \n print(result.x)\n \n SE30 = se3_to_SE3(result.x[0:6]) \n SE31 = se3_to_SE3(result.x[6:12]) \n ### align orientation\n #'''\n \n vision_SE30 = np.matmul(np.matmul(SE30, se3_to_SE3(vision_se3[0,:])),SE31)\n vicon_SE30 = se3_to_SE3(vicon_se3[0,:])\n R_target = vicon_SE30[0:3,0:3]\n R_ori = vision_SE30[0:3,0:3] \n T_ori = vision_SE30[0:3,3]\n \n SO3_align = np.matmul(R_target, np.transpose(R_ori)) \n \n #####################################################\n fig = plt.figure()\n ax = fig.add_subplot(111, projection = '3d')\n transformed_vision_se3 = np.zeros((0,6))\n transformed_vision_SE3 = np.zeros((0,4,4))\n transformed_vision_plot = np.zeros((0,3))\n \n loss = 0\n position_error = []\n rotation_error = []\n total_position = []\n total_rotation = []\n for t in range(len(vicon_se3)):\n ## time\n vicon_se3_t = vicon_se3[t,:]\n vision_se3_t = vision_se3[t,:]\n vicon_T_t = se3_to_SE3(vicon_se3[t,:])\n vision_T_t = se3_to_SE3(vision_se3[t,:])\n ############################### not alignment!!!!!!!!!\n \n #if supervision == 'never': \n # se3_rc = np.asarray([0.333653152, -0.19545771, -0.41434446, -0.16426212, 0.4854613, -0.28981152],dtype = np.float32)\n # g_rc = se3_to_SE3(se3_rc)\n # _, g_vr = util.load_vicon(data_demo_dir+'/camera_position0.npy')\n # SE3 = np.matmul(g_vr, g_rc)\n \n vision_T_t = np.matmul(np.matmul(SE30, vision_T_t),SE31)\n #vision_T_t[0:3,0:3] = np.matmul(SO3_align, vision_T_t[0:3,0:3])\n vision_se3_t = SE3_to_se3(vision_T_t)\n #IPython.embed()\n\n transformed_vision_se3 = np.concatenate([transformed_vision_se3, np.expand_dims(SE3_to_se3(vision_T_t),0)], 0)\n transformed_vision_plot = np.concatenate([transformed_vision_plot, np.expand_dims(vision_T_t[0:3,3],0)], 0)\n transformed_vision_SE3 = np.concatenate([transformed_vision_SE3, np.expand_dims(vision_T_t,0)],0)\n\n loss += np.sqrt(np.sum(np.square(SE3_to_se3(vicon_T_t)-SE3_to_se3(vision_T_t))))\n position_error.append( np.expand_dims( np.sqrt(np.sum(np.square(vicon_T_t[0:3,3]-vision_T_t[0:3,3]))),0))\n rotation_error.append( np.expand_dims( np.sqrt(np.sum(np.square(vicon_se3_t[3:6]-vision_se3_t[3:6]))),0))\n total_position.append(np.expand_dims(vicon_T_t[0:3,3],0))\n total_rotation.append(np.expand_dims(vicon_se3_t[3:6],0))\n\n ax.clear()\n obj_vicon.apply_pose(vicon_se3_t)\n obj_vision.apply_pose(vision_se3_t)\n obj_vicon.plot(ax, scale = 0.015, linewidth = 3)\n obj_vision.plot(ax, scale = 0.015, linewidth = 3)\n ##\n ax.plot(vicon_plot[:t,0], vicon_plot[:t,1], vicon_plot[:t,2], '--', color = 'r', alpha = 0.5, linewidth = 4)\n ax.plot(transformed_vision_plot[:,0], transformed_vision_plot[:,1], transformed_vision_plot[:,2], color = 'g', alpha = 0.5, linewidth = 3)\n ###\n util.set_axes_equal(ax)\n ax.set_xlabel('x(m)')\n ax.set_ylabel('y(m)')\n ax.set_zlabel('z(m)')\n fig.savefig(output_dir+'/'+demo+'/%05d.png'%t)\n plt.close() \n\n loss = loss/len(vision_traj)\n position_error = np.sum(position_error)/len(vision_traj) #np.concatenate(position_error,0)\n rotation_error = np.sum(rotation_error)/len(vision_traj) #np.concatenate(rotation_error,0)\n \n total_position = np.concatenate(total_position,0)\n total_rotation = np.concatenate(total_rotation,0)\n \n np.savetxt(output_dir+'/'+demo+'/loss.txt',[loss])\n np.savetxt(output_dir+'/'+demo+'/position_error.txt',[position_error])\n np.savetxt(output_dir+'/'+demo+'/rotation_error.txt',[rotation_error])\n np.savetxt(output_dir+'/'+demo+'/total_position.txt',total_position)\n np.savetxt(output_dir+'/'+demo+'/total_rotation.txt',total_rotation)\n\n #################### save data for jigang\n pickle_dict = {'time': np.transpose(vision_time), 'se3': transformed_vision_se3, 'SE3': transformed_vision_SE3}\n io.savemat(output_dir+'/'+demo+'/pickle/trajectories.mat', pickle_dict)\n\n #####################################################\n if len(vision_time) > len(transformed_vision_se3):\n vision_time = vision_time[:len(transformed_vision_se3)]\n\n fig = plt.figure()\n ax1 = fig.add_subplot(311)\n ax1.plot(clipped_vicon_time, clipped_vicon[:,0],'--')\n ax1.plot(vision_time, transformed_vision_se3[:,0])\n ax1.set_title('se3[0:3]')\n\n ax2 = fig.add_subplot(312)\n ax2.plot(clipped_vicon_time, clipped_vicon[:,1],'--')\n ax2.plot(vision_time, transformed_vision_se3[:,1])\n\n ax3 = fig.add_subplot(313)\n ax3.plot(clipped_vicon_time, clipped_vicon[:,2],'--')\n ax3.plot(vision_time, transformed_vision_se3[:,2])\n fig.savefig(output_dir+'/'+demo+'/plot/xyz.png')\n #####################################################\n fig = plt.figure()\n ax1 = fig.add_subplot(311)\n ax1.plot(clipped_vicon_time, clipped_vicon[:,3],'--')\n ax1.plot(vision_time, transformed_vision_se3[:,3])\n ax1.set_title('se3[3:6]')\n\n ax2 = fig.add_subplot(312)\n ax2.plot(clipped_vicon_time, clipped_vicon[:,4],'--')\n ax2.plot(vision_time, transformed_vision_se3[:,4])\n\n ax3 = fig.add_subplot(313)\n ax3.plot(clipped_vicon_time, clipped_vicon[:,5],'--')\n ax3.plot(vision_time, transformed_vision_se3[:,5])\n fig.savefig(output_dir+'/'+demo+'/plot/wxwywz.png')\n plt.close()\n #####################################################\n diff_vicon = (clipped_vicon[1:,:]-clipped_vicon[:-1,:])/np.expand_dims(clipped_vicon_time[1:]-clipped_vicon_time[:-1], 1)\n diff_vision = (transformed_vision_se3[1:,:] - transformed_vision_se3[:-1,:])/np.expand_dims(vision_time[1:]-vision_time[:-1],1)\n\n fig = plt.figure()\n ax1 = fig.add_subplot(311)\n ax1.plot(clipped_vicon_time[:-1], diff_vicon[:,0],'--')\n ax1.plot(vision_time[:-1], diff_vision[:,0])\n ax1.set_title('diff_se3[0:3]')\n ax1.set_ylim([-0.5,0.5])\n\n ax2 = fig.add_subplot(312)\n ax2.plot(clipped_vicon_time[:-1], diff_vicon[:,1],'--')\n ax2.plot(vision_time[:-1], diff_vision[:,1])\n ax2.set_ylim([-0.5,0.5])\n \n ax3 = fig.add_subplot(313)\n ax3.plot(clipped_vicon_time[:-1], diff_vicon[:,2],'--')\n ax3.plot(vision_time[:-1], diff_vision[:,2])\n ax3.set_ylim([-0.5,0.5])\n \n fig.savefig(output_dir+'/'+demo+'/plot/diff_xyz.png')\n plt.close()\n #####################################################\n fig = plt.figure()\n ax1 = fig.add_subplot(311)\n ax1.plot(clipped_vicon_time[:-1], diff_vicon[:,3],'--')\n ax1.plot(vision_time[:-1], diff_vision[:,3])\n ax1.set_title('diff_se3[0:3]')\n ax1.set_ylim([-0.5,0.5])\n\n ax2 = fig.add_subplot(312)\n ax2.plot(clipped_vicon_time[:-1], diff_vicon[:,4],'--')\n ax2.plot(vision_time[:-1], diff_vision[:,4])\n ax2.set_ylim([-0.5,0.5])\n\n ax3 = fig.add_subplot(313)\n ax3.plot(clipped_vicon_time[:-1], diff_vicon[:,5],'--')\n ax3.plot(vision_time[:-1], diff_vision[:,5])\n ax3.set_ylim([-0.5,0.5])\n \n fig.savefig(output_dir+'/'+demo+'/plot/diff_wxwywz.png')\n plt.close()\n #####################################################\n\n video_path = output_dir+'/'+demo+'/se3_compare.avi'\n util.frame_to_video(output_dir+'/'+demo, video_path, 'png', fps=fps)()\n\n\n \n \n\n'''\ndef apply_transform(pose, transform):\n # pose : [N,K,6]\n # transform : ([3,], [4,])\n T = transform[0]\n quaternion = transform[1]\n R = quaternion_to_R(quaternion)\n G = RT_to_SE3(R,T)\n\n vicon_to_cam_R = np.asarray([[0, 0.5, 0.8660254],\n [1, 0, 0],\n [0, 0.8660254, -0.5]])\n vicon_to_cam_T = np.asarray([0,0,0.5])\n vicon_to_cam_G = RT_to_SE3(vicon_to_cam_R, vicon_to_cam_T)\n G = np.matmul(G,vicon_to_cam_G)\n\n traj = []\n for t in range(pose.shape[0]):\n traj_k = []\n for k in range(pose.shape[1]):\n obj_SE3 = se3_to_SE3(pose[t,k,:])\n transformed_SE3 = np.matmul(G,obj_SE3)\n \n transformed_se3 = SE3_to_se3(transformed_SE3)\n traj_k.append(np.expand_dims(transformed_se3,0))\n traj_k = np.concatenate(traj_k, 0)\n traj.append(np.expand_dims(traj_k,0))\n traj = np.concatenate(traj, 0)\n return traj\n\ndef read_traj(config):\n data_name = config['data_name']\n nb_object = config['object']['nb_object']\n demo_list = os.listdir('./data/'+data_name)\n\n pose_dir = './output/read_pose/'+data_name\n transform_dir = './data/'+data_name\n output_dir = './output/read_traj/'+data_name\n util.create_dir(output_dir, clear = True)\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection = '3d')\n color = ['g', 'r']\n robot = vision.SE3object(np.zeros(6), angle_type = 'axis')\n cam = vision.SE3object(np.zeros(6), angle_type = 'axis')\n vicon_to_cam_R = np.asarray([[0, 0.5, 0.8660254],\n [1, 0, 0],\n [0, 0.8660254, -0.5]])\n vicon_to_cam_T = np.asarray([0,0,0.3])\n vicon_to_cam_G = RT_to_SE3(vicon_to_cam_R, vicon_to_cam_T)\n \n\n for demo_name in demo_list:\n pose_path = pose_dir+'/'+demo_name+'/pose_traj.npy'\n output_path = output_dir+'/'+demo_name\n transform_path = transform_dir+'/'+demo_name+'/position.npy'\n\n pose = np.load(pose_path)\n transform = np.load(transform_path)\n\n traj = apply_transform(pose, transform)\n \n robot_T = transform[0]\n robot_quaternion = transform[1]\n robot_R = quaternion_to_R(robot_quaternion)\n robot_G = RT_to_SE3(robot_R,robot_T)\n robot_se3 = SE3_to_se3(robot_G)\n robot.apply_pose(robot_se3)\n robot.plot(ax, scale = 0.3, linewidth = 3)\n\n cam_SE3 = np.matmul(robot_G, vicon_to_cam_G)\n cam_se3 = SE3_to_se3(cam_SE3)\n cam.apply_pose(cam_se3)\n cam.plot(ax, scale = 0.2, linewidth = 3)\n ax.scatter(cam_se3[0], cam_se3[1], cam_se3[2], alpha = 0.5, s = 200)\n\n for obj in range(traj.shape[1]):\n #ax.plot(traj[:,obj,0], traj[:,obj,1], traj[:,obj,2], \n # color[obj], alpha = 0.5, linewidth = 4)\n ax.plot(traj[:,obj,0], traj[:,obj,1], traj[:,obj,2], alpha = 0.5, linewidth = 4)\n \n\n ax.set_xlabel('x(m)')\n ax.set_ylabel('y(m)')\n ax.set_zlabel('z(m)')\n util.set_axes_equal(ax)\n #ax.set_zlim([0,1.2])\n #ax.axis('equal')\n #ax.set_aspect('equal')\n ax.view_init(elev = -60, azim = -90)\n fig.savefig(output_dir+'/traj_'+demo_name+'.png')\n\n plt.show()\n fig.savefig(output_dir+'/traj.png') \n #IPython.embed()\n\n\n\n'''", "repo_name": "babymind-project/babymind19", "sub_path": "algorithm/compare_traj_2.py", "file_name": "compare_traj_2.py", "file_ext": "py", "file_size_in_byte": 18681, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "2", "api": [{"api_name": "lib.util.create_dir", "line_number": 33, "usage_type": "call"}, {"api_name": "lib.util", "line_number": 33, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 44, "usage_type": "call"}, {"api_name": "lib.util.create_dir", "line_number": 46, "usage_type": "call"}, {"api_name": "lib.util", "line_number": 46, "usage_type": "name"}, {"api_name": "lib.util.create_dir", "line_number": 47, "usage_type": "call"}, {"api_name": "lib.util", "line_number": 47, "usage_type": "name"}, {"api_name": "numpy.load", "line_number": 49, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 92, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 94, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 94, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 99, "usage_type": "call"}, {"api_name": "lib.vision.SE3object", "line_number": 101, "usage_type": "call"}, {"api_name": "lib.vision", "line_number": 101, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 101, "usage_type": "call"}, {"api_name": "lib.vision.SE3object", "line_number": 102, "usage_type": "call"}, {"api_name": "lib.vision", "line_number": 102, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 122, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.close", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 124, "usage_type": "name"}, {"api_name": "numpy.random.rand", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 126, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.square", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 146, "usage_type": "call"}, {"api_name": "scipy.optimize.minimize", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 171, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 177, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 180, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 180, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 182, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 183, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 184, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 205, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 210, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 210, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 212, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 212, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 214, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 214, "usage_type": "call"}, {"api_name": "numpy.square", "line_number": 214, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.square", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 216, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 216, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 216, "usage_type": "call"}, {"api_name": "numpy.square", "line_number": 216, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 217, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 218, "usage_type": "call"}, {"api_name": "lib.util.set_axes_equal", "line_number": 229, "usage_type": "call"}, {"api_name": "lib.util", "line_number": 229, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 234, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 234, "usage_type": "name"}, {"api_name": "numpy.sum", "line_number": 237, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 238, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 240, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 241, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 243, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 244, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 245, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 246, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 247, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 250, "usage_type": "call"}, {"api_name": "scipy.io.savemat", "line_number": 251, "usage_type": "call"}, {"api_name": "scipy.io", "line_number": 251, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 257, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 257, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 272, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 272, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 286, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 286, "usage_type": "name"}, {"api_name": "numpy.expand_dims", "line_number": 288, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 289, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 291, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 291, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 309, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 309, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 311, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 311, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 329, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 329, "usage_type": "name"}, {"api_name": "lib.util.frame_to_video", "line_number": 333, "usage_type": "call"}, {"api_name": "lib.util", "line_number": 333, "usage_type": "name"}]} +{"seq_id": "6720161061", "text": "\"\"\"This module contain any actions for Flask server.py\"\"\"\n\nfrom fpdf import FPDF\nfrom wh_app.web.servers_parts.support_part import *\nfrom wh_app.web.any_section import main_web_menu, faq_page, statistics_page,\\\n system_status_page, viev_changelog\nfrom wh_app.supporting.pdf_operations.pdf import equips_in_point, works_from_equip,\\\n works_from_performer, weekly_charts_pdf, move_equip, point_tech_information, find_work_without_date, find_equip,\\\n find_point, find_work_with_date, works_from_performer_with_date\n\n\n@app.route(\"/\")\ndef main_page() -> Response:\n \"\"\"Return main web-page\"\"\"\n return goto_or_redirect(lambda: main_web_menu(stylesheet_number()))\n\n\n@app.route(\"/FAQ\", methods=['GET'])\ndef faq() -> Response:\n \"\"\"Return FAQ-page\"\"\"\n return goto_or_redirect(lambda: faq_page(request.args.get('page',\n default=config.full_address(),\n type=str),\n stylesheet_number()))\n\n\n@app.route('/statistics', methods=['GET'])\ndef statistics() -> Response:\n \"\"\"Return STATISTIC-page\"\"\"\n return goto_or_redirect(lambda: statistics_page(request.args.get('page',\n default=config.full_address(),\n type=str),\n stylesheet_number()))\n\n\n@app.route('/system-status', methods=['GET'])\ndef system_status() -> Response:\n \"\"\"Return page, contain status all system components\"\"\"\n return goto_or_redirect(lambda: system_status_page(request.args.get('page',\n default=config.full_address(),\n type=str),\n stylesheet_number()))\n\n\n@app.route('/changelog-page')\ndef changelog_page() -> Response:\n \"\"\"Return ALL CHANGELOG page\"\"\"\n return goto_or_redirect(lambda: viev_changelog(stylesheet_number()))\n\n\n@app.route(\"/table-to-pdf/\")\ndef html_table_to_pdf(data:str) -> Response:\n \"\"\"Redirect to method generate pdf-version current main-table\n correct adr /table-to-pdf/
    = or /table-to-pdf/
    ==\"\"\"\n\n command_table = {\"point\": equips_in_point,\n \"equip\": works_from_equip,\n \"performer\": works_from_performer,\n \"performer-with-date\": works_from_performer_with_date,\n \"weekly\": weekly_charts_pdf,\n \"move-equip-pdf\": move_equip,\n \"point-tech\": point_tech_information,\n \"find-work-not-date\": find_work_without_date,\n \"find-equip\": find_equip,\n \"point\": find_point,\n \"find-work-with-date\": find_work_with_date}\n lst_data = data.split('=')\n if len(lst_data) == 2:\n section, value = lst_data\n elif len(lst_data) == 3:\n section, value, page_num = lst_data\n elif len(lst_data) == 5:\n section, value, date1, date2, page_num = lst_data\n else:\n print(\"Команда {} для формирования PDF не опознана\".format(data))\n try:\n if len(lst_data) == 2:\n pdf = command_table[section](value)\n elif len(lst_data) == 5:\n pdf = command_table[section](value, date1, date2, page_num)\n else:\n pdf = command_table[section](value, page_num)\n except Exception as err:\n print(err)\n pdf: FPDF = FPDF()\n\n pdf.output(config.path_to_pdf())\n return send_file(config.path_to_pdf()) \\\n if section == \"weekly\" \\\n else goto_or_redirect(lambda : send_file(config.path_to_pdf()))\n\n\n", "repo_name": "saibogo/work_history", "sub_path": "wh_app/web/servers_parts/any_part.py", "file_name": "any_part.py", "file_ext": "py", "file_size_in_byte": 3911, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "wh_app.web.any_section.main_web_menu", "line_number": 15, "usage_type": "call"}, {"api_name": "wh_app.web.any_section.faq_page", "line_number": 21, "usage_type": "call"}, {"api_name": "wh_app.web.any_section.statistics_page", "line_number": 30, "usage_type": "call"}, {"api_name": "wh_app.web.any_section.system_status_page", "line_number": 39, "usage_type": "call"}, {"api_name": "wh_app.web.any_section.viev_changelog", "line_number": 48, "usage_type": "call"}, {"api_name": "wh_app.supporting.pdf_operations.pdf.equips_in_point", "line_number": 56, "usage_type": "name"}, {"api_name": "wh_app.supporting.pdf_operations.pdf.works_from_equip", "line_number": 57, "usage_type": "name"}, {"api_name": "wh_app.supporting.pdf_operations.pdf.works_from_performer", "line_number": 58, "usage_type": "name"}, {"api_name": "wh_app.supporting.pdf_operations.pdf.works_from_performer_with_date", "line_number": 59, "usage_type": "name"}, {"api_name": "wh_app.supporting.pdf_operations.pdf.weekly_charts_pdf", "line_number": 60, "usage_type": "name"}, {"api_name": "wh_app.supporting.pdf_operations.pdf.move_equip", "line_number": 61, "usage_type": "name"}, {"api_name": "wh_app.supporting.pdf_operations.pdf.point_tech_information", "line_number": 62, "usage_type": "name"}, {"api_name": "wh_app.supporting.pdf_operations.pdf.find_work_without_date", "line_number": 63, "usage_type": "name"}, {"api_name": "wh_app.supporting.pdf_operations.pdf.find_equip", "line_number": 64, "usage_type": "name"}, {"api_name": "wh_app.supporting.pdf_operations.pdf.find_point", "line_number": 65, "usage_type": "name"}, {"api_name": "wh_app.supporting.pdf_operations.pdf.find_work_with_date", "line_number": 66, "usage_type": "name"}, {"api_name": "fpdf.FPDF", "line_number": 85, "usage_type": "name"}]} +{"seq_id": "40310129253", "text": "import argparse\nimport cv2\nimport numpy as np \nfrom matplotlib import pyplot as plt \n\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--images\", help = \"the image that you wanna load\")\nargs = vars(ap.parse_args())\nimage = cv2.imread(args[\"images\"])\ncv2.imshow(\"original\",image)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\nchans = cv2.split(image)\ncolors = (\"b\", \"g\", \"r\")\nplt.figure()\nplt.title(\"’Flattened’ Color Histogram\")\nplt.xlabel(\"Bins\")\nplt.ylabel(\"# of Pixels\")\nfor (chan, color) in zip(chans, colors):\n hist = cv2.calcHist([chan], [0], None, [256], [0, 256])\n plt.plot(hist, color = color)\n plt.xlim([0, 256])\n\nplt.show()\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n \n\n\n\n\n\n", "repo_name": "nayantarachauhan/image_processing_openCV", "sub_path": "color_histogram.py", "file_name": "color_histogram.py", "file_ext": "py", "file_size_in_byte": 697, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 6, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 9, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 10, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 11, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 12, "usage_type": "call"}, {"api_name": "cv2.split", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "cv2.calcHist", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "cv2.waitKey", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 28, "usage_type": "call"}]} +{"seq_id": "422139378", "text": "import tkinter as tk\r\nfrom tkinter import Entry, ttk\r\nimport openpyxl\r\nfrom openpyxl import load_workbook, Workbook\r\nfrom tkinter import *\r\nimport tkinter.ttk as ttk\r\n\r\n#i figured out the search option babeee\r\n\r\n\r\n# Load the xlsx file, then store the value of each column in the \"elements\" list\r\nwb = load_workbook(filename=r\"C:\\Users\\Chinnu\\Downloads\\exampleapp\\testdata.xlsx\")\r\nws = wb['Sheet1']\r\nwBook = load_workbook('storingfile.xlsx')\r\nsheet = wBook.active\r\n\r\nm_row = ws.max_row\r\nm_col= ws.max_column\r\nprint(\"total rows of the excel: \",m_row)\r\nMaterialDescription = ws['A2':'A10']\r\nelements = [] \r\ncodeval = '' \r\n\r\n#to get the list of column values\r\nfor cell in MaterialDescription:\r\n for x in cell:\r\n y = x.value\r\n elements.append(y)\r\n print(y)\r\n\r\n\r\n#search function\r\ndef check_input(event):\r\n value2 = event.widget.get()\r\n\r\n if value2 == '':\r\n combodata['values'] = elements\r\n else:\r\n data = []\r\n for item in elements:\r\n if value2.lower() in item.lower():\r\n data.append(item)\r\n\r\n combodata['values'] = data\r\n\r\n print(\"selected value=\", combodata.get(), \"index=\",combodata.current())\r\n\r\n main_sheet = wb.active\r\n for row in range(2, main_sheet.max_row + 1):\r\n material = main_sheet.cell(row=row, column=1).value\r\n if material == combodata.get():\r\n codeval = main_sheet.cell(row=row, column=2).value\r\n print(main_sheet.cell(row=row, column=2).value)\r\n code.insert(\"end-1c\", codeval)\r\n break \r\n \r\n\r\n data1 = [combodata.get()]\r\n sheet.append(data1)\r\n wBook.save('storingfile.xlsx')\r\n\r\n\r\n# Tkinter stuff\r\nwin = Tk()\r\nclicked = StringVar()\r\n\r\n#label and combobox, binding\r\nttk.Label(text=\"Material Description:\").grid(row=1, column=0, padx=10, pady=10)\r\ncombodata = ttk.Combobox(win, values=elements)\r\ncombodata.grid(row=1, column=1, padx=10, pady=10)\r\ncombodata['values'] = elements\r\ncombodata.bind('', check_input)\r\nwBook.save('storingfile.xlsx')\r\n\r\nttk.Label(text=\"Material Code:\").grid(row=2, column=0, padx=10, pady=10)\r\ncode = Text(height=1, width=18)\r\ncode.grid(row=2, column=1, padx=10, pady=10)\r\n\r\nwin.mainloop()\r\n", "repo_name": "SriHarshitha25/excelapp", "sub_path": "savingtoex.py", "file_name": "savingtoex.py", "file_ext": "py", "file_size_in_byte": 2269, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "openpyxl.load_workbook", "line_number": 12, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 14, "usage_type": "call"}, {"api_name": "tkinter.ttk.Label", "line_number": 68, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 68, "usage_type": "name"}, {"api_name": "tkinter.ttk.Combobox", "line_number": 69, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 69, "usage_type": "name"}, {"api_name": "tkinter.ttk.Label", "line_number": 75, "usage_type": "call"}, {"api_name": "tkinter.ttk", "line_number": 75, "usage_type": "name"}]} +{"seq_id": "37495315874", "text": "import numpy as np\nimport cv2\n\n\n\ndef main():\n cam = cv2.VideoCapture(1)\n if cam.read()[0] == False:\n cam = cv2.VideoCapture(0)\n\n _, first_frame = cam.read()\n first_frame = cv2.flip(first_frame, 1)\n\n #cam = cv2.VideoCapture('vtest.avi')\n first_gray = cv2.cvtColor(first_frame, cv2.COLOR_BGR2GRAY)\n first_gray = cv2.GaussianBlur(first_gray, (5, 5), 0)\n\n fgbg = cv2.createBackgroundSubtractorMOG2()\n\n while True:\n frame = cam.read()[1]\n frame = cv2.flip(frame, 1)\n\n gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray_frame = cv2.GaussianBlur(gray_frame, (5, 5), 0)\n difference = cv2.absdiff(first_gray, gray_frame)\n _, difference = cv2.threshold(difference, 25, 255, cv2.THRESH_BINARY)\n #difference=difference[80:350,350:600]\n cv2.rectangle(frame, (350, 80), (600, 350), (0, 255, 0), 2)\n\n cv2.imshow(\"First frame\", first_frame)\n cv2.imshow(\"Frame\", frame)\n cv2.rectangle(difference, (350, 80), (600, 350), (0, 255, 0), 2)\n\n cv2.imshow(\"difference\", difference)\n k = cv2.waitKey(30) & 0xff\n if k == 27:\n break\n\n\n\n cam.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n main()\n", "repo_name": "ntomazin/Croatian-Sign-Language-Alphabet-Recognition", "sub_path": "background_substraction.py", "file_name": "background_substraction.py", "file_ext": "py", "file_size_in_byte": 1246, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "cv2.VideoCapture", "line_number": 7, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 9, "usage_type": "call"}, {"api_name": "cv2.flip", "line_number": 12, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 15, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 15, "usage_type": "attribute"}, {"api_name": "cv2.GaussianBlur", "line_number": 16, "usage_type": "call"}, {"api_name": "cv2.createBackgroundSubtractorMOG2", "line_number": 18, "usage_type": "call"}, {"api_name": "cv2.flip", "line_number": 22, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 24, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 24, "usage_type": "attribute"}, {"api_name": "cv2.GaussianBlur", "line_number": 25, "usage_type": "call"}, {"api_name": "cv2.absdiff", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.threshold", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 27, "usage_type": "attribute"}, {"api_name": "cv2.rectangle", "line_number": 29, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 31, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 32, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 35, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 36, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 43, "usage_type": "call"}]} +{"seq_id": "27126713732", "text": "import copy\nimport inspect\nimport os\nimport sys\nimport warnings\n\nimport numpy as np\n\nfrom ...datbase import DataType\nfrom ...utils.datautil import DatumUtil, MultiList\nfrom ..data.mfstructure import DatumType\nfrom ..mfbase import ExtFileAction, MFDataException, VerbosityLevel\nfrom ..utils.mfenums import DiscretizationType\nfrom .mfdata import MFMultiDimVar, MFTransient\nfrom .mfdatastorage import DataStorage, DataStorageType, DataStructureType\nfrom .mffileaccess import MFFileAccessArray\n\n\nclass MFArray(MFMultiDimVar):\n \"\"\"\n Provides an interface for the user to access and update MODFLOW array data.\n MFArray objects are not designed to be directly constructed by the end\n user. When a FloPy for MODFLOW 6 package object is constructed, the\n appropriate MFArray objects are automatically built.\n\n Parameters\n ----------\n sim_data : MFSimulationData\n data contained in the simulation\n structure : MFDataStructure\n describes the structure of the data\n data : list or ndarray\n actual data\n enable : bool\n enable/disable the array\n path : tuple\n path in the data dictionary to this MFArray\n dimensions : MFDataDimensions\n dimension information related to the model, package, and array\n\n \"\"\"\n\n def __init__(\n self,\n sim_data,\n model_or_sim,\n structure,\n data=None,\n enable=True,\n path=None,\n dimensions=None,\n block=None,\n ):\n super().__init__(\n sim_data, model_or_sim, structure, enable, path, dimensions\n )\n self._block = block\n if self.structure.layered:\n try:\n self._layer_shape = self.layer_shape()\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"resolving layer dimensions\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n else:\n self._layer_shape = (1,)\n if self._layer_shape[0] is None:\n self._layer_shape = (1,)\n self._data_type = structure.data_item_structures[0].type\n try:\n shp_ml = MultiList(shape=self._layer_shape)\n self._data_storage = self._new_storage(\n shp_ml.get_total_size() != 1\n )\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n structure.get_model(),\n structure.get_package(),\n path,\n \"creating storage\",\n structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n sim_data.debug,\n ex,\n )\n self._last_line_info = []\n if self.structure.type == DatumType.integer:\n multiplier = [1]\n else:\n multiplier = [1.0]\n if data is not None:\n try:\n self._get_storage_obj().set_data(\n data, key=self._current_key, multiplier=multiplier\n )\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"setting data\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n\n def __setattr__(self, name, value):\n if name == \"__setstate__\":\n raise AttributeError(name)\n elif name == \"fname\":\n self._get_storage_obj().layer_storage.first_item().fname = value\n elif name == \"factor\":\n self._get_storage_obj().layer_storage.first_item().factor = value\n elif name == \"iprn\":\n self._get_storage_obj().layer_storage.first_item().iprn = value\n elif name == \"binary\":\n self._get_storage_obj().layer_storage.first_item().binary = value\n else:\n super().__setattr__(name, value)\n\n def __getitem__(self, k):\n if isinstance(k, int):\n k = (k,)\n storage = self._get_storage_obj()\n if storage.layered and (isinstance(k, tuple) or isinstance(k, list)):\n if not storage.layer_storage.in_shape(k):\n comment = (\n 'Could not retrieve layer {} of \"{}\". There'\n \"are only {} layers available\"\n \".\".format(\n k, self.structure.name, len(storage.layer_storage)\n )\n )\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"getting data\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n comment,\n self._simulation_data.debug,\n )\n # for layered data treat k as layer number(s)\n return storage.layer_storage[k]\n else:\n # for non-layered data treat k as an array/list index of the data\n if isinstance(k, int):\n try:\n if len(self._get_data(apply_mult=True).shape) == 1:\n return self._get_data(apply_mult=True)[k]\n elif self._get_data(apply_mult=True).shape[0] == 1:\n return self._get_data(apply_mult=True)[0, k]\n elif self._get_data(apply_mult=True).shape[1] == 1:\n return self._get_data(apply_mult=True)[k, 0]\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"setting data\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n\n comment = (\n f'Unable to resolve index \"{k}\" for multidimensional data.'\n )\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"getting data\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n comment,\n self._simulation_data.debug,\n )\n else:\n try:\n if isinstance(k, tuple):\n if len(k) == 3:\n return self._get_data(apply_mult=True)[\n k[0], k[1], k[2]\n ]\n elif len(k) == 2:\n return self._get_data(apply_mult=True)[k[0], k[1]]\n if len(k) == 1:\n return self._get_data(apply_mult=True)[k]\n else:\n return self._get_data(apply_mult=True)[(k,)]\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"setting data\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n\n def __setitem__(self, k, value):\n storage = self._get_storage_obj()\n self._resync()\n if storage.layered:\n if isinstance(k, int):\n k = (k,)\n # for layered data treat k as a layer number\n try:\n storage.layer_storage[k]._set_data(value)\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"setting data\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n\n else:\n try:\n # for non-layered data treat k as an array/list index of the data\n a = self._get_data()\n a[k] = value\n a = a.astype(self._get_data().dtype)\n layer_storage = storage.layer_storage.first_item()\n self._get_storage_obj().set_data(\n a, key=self._current_key, multiplier=layer_storage.factor\n )\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"setting data\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n\n @property\n def data_type(self):\n \"\"\"Type of data (DataType) stored in the array\"\"\"\n if self.structure.layered:\n return DataType.array3d\n else:\n return DataType.array2d\n\n @property\n def dtype(self):\n \"\"\"Type of data (numpy.dtype) stored in the array\"\"\"\n return self._get_data().dtype.type\n\n @property\n def plottable(self):\n \"\"\"If the array is plottable\"\"\"\n if self.model is None:\n return False\n else:\n return True\n\n @property\n def data(self):\n \"\"\"Returns array data. Calls get_data with default parameters.\"\"\"\n return self._get_data()\n\n def new_simulation(self, sim_data):\n \"\"\"Initialize MFArray object for a new simulation\n\n Parameters\n ----------\n sim_data : MFSimulationData\n Data dictionary containing simulation data.\n\n\n \"\"\"\n super().new_simulation(sim_data)\n self._data_storage = self._new_storage(False)\n self._layer_shape = (1,)\n\n def supports_layered(self):\n \"\"\"Returns whether this MFArray supports layered data\n\n Returns\n -------\n layered data supported: bool\n Whether or not this data object supports layered data\n\n \"\"\"\n\n try:\n model_grid = self._data_dimensions.get_model_grid()\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"getting model grid\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n return (\n self.structure.layered\n and model_grid.grid_type() != DiscretizationType.DISU\n )\n\n def set_layered_data(self, layered_data):\n \"\"\"Sets whether this MFArray supports layered data\n\n Parameters\n ----------\n layered_data : bool\n Whether data is layered or not.\n\n \"\"\"\n if layered_data is True and self.structure.layered is False:\n if (\n self._data_dimensions.get_model_grid().grid_type()\n == DiscretizationType.DISU\n ):\n comment = f\"Layered option not available for unstructured grid. {self._path}\"\n else:\n comment = (\n 'Data \"{}\" does not support layered option. '\n \"{}\".format(self._data_name, self._path)\n )\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"setting layered data\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n comment,\n self._simulation_data.debug,\n )\n self._get_storage_obj().layered = layered_data\n\n def make_layered(self):\n \"\"\"Changes the data to be stored by layer instead of as a single array.\"\"\"\n\n if self.supports_layered():\n try:\n self._get_storage_obj().make_layered()\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"making data layered\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n else:\n if (\n self._data_dimensions.get_model_grid().grid_type()\n == DiscretizationType.DISU\n ):\n comment = f\"Layered option not available for unstructured grid. {self._path}\"\n else:\n comment = (\n 'Data \"{}\" does not support layered option. '\n \"{}\".format(self._data_name, self._path)\n )\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"converting data to layered\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n comment,\n self._simulation_data.debug,\n )\n\n def store_as_external_file(\n self,\n external_file_path,\n layer=None,\n binary=False,\n replace_existing_external=True,\n check_data=True,\n ):\n \"\"\"Stores data from layer `layer` to an external file at\n `external_file_path`. For unlayered data do not pass in `layer`.\n If layer is not specified all layers will be stored with each layer\n as a separate file. If replace_existing_external is set to False,\n this method will not do anything if the data is already in an\n external file.\n\n Parameters\n ----------\n external_file_path : str\n Path to external file\n layer : int\n Which layer to store in external file, `None` value stores all\n layers.\n binary : bool\n Store data in a binary file\n replace_existing_external : bool\n Whether to replace an existing external file.\n check_data : bool\n Verify data prior to storing\n \"\"\"\n storage = self._get_storage_obj()\n if storage is None:\n self._set_storage_obj(self._new_storage(False, True))\n storage = self._get_storage_obj()\n # build list of layers\n if layer is None:\n layer_list = []\n for index in range(0, storage.layer_storage.get_total_size()):\n if (\n replace_existing_external\n or storage.layer_storage[index].data_storage_type\n == DataStorageType.internal_array\n or storage.layer_storage[index].data_storage_type\n == DataStorageType.internal_constant\n ):\n layer_list.append(index)\n else:\n if (\n replace_existing_external\n or storage.layer_storage[layer].data_storage_type\n == DataStorageType.internal_array\n or storage.layer_storage[layer].data_storage_type\n == DataStorageType.internal_constant\n ):\n layer_list = [layer]\n else:\n layer_list = []\n\n # store data from each layer in a separate file\n for current_layer in layer_list:\n # determine external file name for layer\n if len(layer_list) > 0:\n fname, ext = os.path.splitext(external_file_path)\n if len(layer_list) == 1:\n file_path = f\"{fname}{ext}\"\n else:\n file_path = f\"{fname}_layer{current_layer + 1}{ext}\"\n else:\n file_path = external_file_path\n if isinstance(current_layer, int):\n current_layer = (current_layer,)\n # get the layer's data\n data = self._get_data(current_layer, True)\n\n if data is None:\n # do not write empty data to an external file\n continue\n if isinstance(data, str) and self._tas_info(data)[0] is not None:\n # data must not be time array series information\n continue\n if storage.get_data_dimensions(current_layer)[0] == -9999:\n # data must have well defined dimensions to make external\n continue\n try:\n # store layer's data in external file\n if (\n self._simulation_data.verbosity_level.value\n >= VerbosityLevel.verbose.value\n ):\n print(\n \"Storing {} layer {} to external file {}..\"\n \".\".format(\n self.structure.name,\n current_layer[0] + 1,\n file_path,\n )\n )\n factor = storage.layer_storage[current_layer].factor\n external_data = {\n \"filename\": file_path,\n \"data\": self._get_data(current_layer, True),\n \"factor\": factor,\n \"binary\": binary,\n }\n self._set_data(\n external_data, layer=current_layer, check_data=False\n )\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n f\"storing data in external file {external_file_path}\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n\n def store_internal(\n self,\n layer=None,\n check_data=True,\n ):\n \"\"\"Stores data from layer `layer` internally. For unlayered data do\n not pass in `layer`. If layer is not specified all layers will be\n stored internally\n\n Parameters\n ----------\n layer : int\n Which layer to store in external file, `None` value stores all\n layers.\n check_data : bool\n Verify data prior to storing\n \"\"\"\n storage = self._get_storage_obj()\n if storage is None:\n self._set_storage_obj(self._new_storage(False, True))\n storage = self._get_storage_obj()\n # build list of layers\n if layer is None:\n layer_list = []\n for index in range(0, storage.layer_storage.get_total_size()):\n if (\n storage.layer_storage[index].data_storage_type\n == DataStorageType.external_file\n ):\n layer_list.append(index)\n else:\n if (\n storage.layer_storage[layer].data_storage_type\n == DataStorageType.external_file\n ):\n layer_list = [layer]\n else:\n layer_list = []\n\n # store data from each layer\n for current_layer in layer_list:\n if isinstance(current_layer, int):\n current_layer = (current_layer,)\n # get the layer's data\n data = self._get_data(current_layer, False)\n\n if data is None:\n # do not write empty data to an internal file\n continue\n try:\n # store layer's data internally\n if (\n self._simulation_data.verbosity_level.value\n >= VerbosityLevel.verbose.value\n ):\n print(\n \"Storing {} layer {} internally..\"\n \".\".format(\n self.structure.name,\n current_layer[0] + 1,\n )\n )\n factor = storage.layer_storage[current_layer].factor\n internal_data = {\n current_layer[0]: {\n \"data\": self._get_data(current_layer, False),\n \"factor\": factor,\n }\n }\n self._set_record(internal_data)\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n f\"storing data {self.structure.name} internally\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n\n def has_data(self, layer=None):\n \"\"\"Returns whether layer \"layer_num\" has any data associated with it.\n\n Parameters\n ----------\n layer_num : int\n Layer number to check for data. For unlayered data do not\n pass anything in\n\n Returns\n -------\n has data: bool\n Returns if there is data.\n\n \"\"\"\n storage = self._get_storage_obj()\n if storage is None:\n return False\n if isinstance(layer, int):\n layer = (layer,)\n try:\n return storage.has_data(layer)\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"checking for data\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n\n def get_data(self, layer=None, apply_mult=False, **kwargs):\n \"\"\"Returns the data associated with layer \"layer\". If \"layer\"\n is None, returns all data.\n\n Parameters\n ----------\n layer : int\n\n Returns\n -------\n data : ndarray\n Array data in an ndarray\n\n \"\"\"\n return self._get_data(layer, apply_mult, **kwargs)\n\n def _get_data(self, layer=None, apply_mult=False, **kwargs):\n if self._get_storage_obj() is None:\n self._data_storage = self._new_storage(False)\n if isinstance(layer, int):\n layer = (layer,)\n storage = self._get_storage_obj()\n if storage is not None:\n try:\n data = storage.get_data(layer, apply_mult)\n if (\n \"array\" in kwargs\n and kwargs[\"array\"]\n and isinstance(self, MFTransientArray)\n and data is not []\n ):\n data = np.expand_dims(data, 0)\n return data\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"getting data\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n return None\n\n def get_record(self, layer=None):\n \"\"\"Returns the data record associated with layer \"layer\". If \"layer\"\n is None, returns all data.\n\n Parameters\n ----------\n layer : int\n\n Returns\n -------\n data_record : dict\n Dictionary containing data record for specified layer or\n dictionary containing layer numbers (keys) and data record\n for that layer (values).\n\n \"\"\"\n if self._get_storage_obj() is None:\n self._data_storage = self._new_storage(False)\n if isinstance(layer, int):\n layer = (layer,)\n storage = self._get_storage_obj()\n if storage is not None:\n try:\n return storage.get_record(layer)\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"getting record\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n return None\n\n def set_record(self, data_record):\n \"\"\"Sets the contents of the data and metadata to the contents of\n 'data_record`. For unlayered data do not pass in `layer`. For\n unlayered data 'data_record' is a dictionary with either of the\n following key/value pairs:\n 1) {'filename':filename, 'factor':fct, 'iprn':print, 'data':data} -\n dictionary defining external file information\n 2) {'data':data, 'factor':fct, 'iprn':print)}- dictionary defining\n internal information. Data that is layered can also be set by defining\n For layered data data_record must be a dictionary of dictionaries\n with zero-based layer numbers for the outer dictionary keys and the\n inner dictionary as described above:\n {0: {'data':data_lay_0, 'factor':fct_lay_0, 'iprn':prn_lay_0)},\n 1: {'data':data_lay_1, 'factor':fct_lay_1, 'iprn':prn_lay_1)},\n 2: {'data':data_lay_2, 'factor':fct_lay_2, 'iprn':prn_lay_2)}}\n\n Parameters\n ----------\n data_record : dict\n An dictionary of data record information or a dictionary of\n layers (keys) with a dictionary of data record information for each\n layer (values).\n \"\"\"\n self._set_record(data_record)\n\n def _set_record(self, data_record):\n \"\"\"Sets the contents of the data and metadata to the contents of\n 'data_record`. For unlayered data do not pass in `layer`. For\n unlayered data 'data_record' is a dictionary with either of the\n following key/value pairs:\n 1) {'filename':filename, 'factor':fct, 'iprn':print, 'data':data} -\n dictionary defining external file information\n 2) {'data':data, 'factor':fct, 'iprn':print)}- dictionary defining\n internal information. Data that is layered can also be set by defining\n For layered data data_record must be a list of dictionaries or a\n dictionary of dictionaries with zero-based layer numbers for the outer\n dictionary keys and the inner dictionary as described above:\n {0: {'data':data_lay_0, 'factor':fct_lay_0, 'iprn':prn_lay_0)},\n 1: {'data':data_lay_1, 'factor':fct_lay_1, 'iprn':prn_lay_1)},\n 2: {'data':data_lay_2, 'factor':fct_lay_2, 'iprn':prn_lay_2)}}\n\n Parameters\n ----------\n data_record : dict\n An dictionary of data record information or a dictionary of\n layers (keys) with a dictionary of data record information for each\n layer (values).\n \"\"\"\n if isinstance(data_record, dict):\n first_key = list(data_record.keys())[0]\n if isinstance(first_key, int):\n for layer, record in data_record.items():\n self._set_data(record, layer=layer, preserve_record=False)\n else:\n self._set_data(data_record, preserve_record=False)\n elif type(data_record) == list:\n for layer, record in enumerate(data_record):\n self._set_data(record, layer=layer, preserve_record=False)\n else:\n message = (\n \"Unable to set record. The contents of data_record must be\"\n \"a dictionary or a list.\"\n )\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self._data_dimensions.structure.get_model(),\n self._data_dimensions.structure.get_package(),\n self._data_dimensions.structure.path,\n \"setting record\",\n self._data_dimensions.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n message,\n self._simulation_data.debug,\n )\n\n def set_data(self, data, multiplier=None, layer=None):\n \"\"\"Sets the contents of the data at layer `layer` to `data` with\n multiplier `multiplier`. For unlayered data do not pass in\n `layer`. Data can have the following formats:\n 1) ndarray - numpy ndarray containing all of the data\n 2) [data] - python list containing all of the data\n 3) val - a single constant value to be used for all of the data\n\n Parameters\n ----------\n data : ndarray/list\n An ndarray or nested lists containing the data to set.\n multiplier : float\n Multiplier to apply to data\n layer : int\n Data layer that is being set\n\n \"\"\"\n self._set_data(data, multiplier, layer)\n\n def _set_data(\n self,\n data,\n multiplier=None,\n layer=None,\n check_data=True,\n preserve_record=True,\n ):\n self._resync()\n if self._get_storage_obj() is None:\n self._data_storage = self._new_storage(False)\n if isinstance(layer, int):\n layer = (layer,)\n if isinstance(data, str):\n # check to see if this is a time series array\n tas_name, tas_label = self._tas_info(data)\n if tas_name is not None:\n # verify and save as time series array\n self._get_storage_obj().set_tas(\n tas_name, tas_label, self._current_key, check_data\n )\n return\n\n storage = self._get_storage_obj()\n if self.structure.name == \"aux\" and layer is None:\n if isinstance(data, dict):\n aux_data = copy.deepcopy(data[\"data\"])\n else:\n aux_data = data\n # make a list out of a single item\n if (\n isinstance(aux_data, int)\n or isinstance(aux_data, float)\n or isinstance(aux_data, str)\n ):\n aux_data = [[aux_data]]\n # handle special case of aux variables in an array\n self.layered = True\n aux_var_names = (\n self._data_dimensions.package_dim.get_aux_variables()\n )\n if len(aux_data) == len(aux_var_names[0]) - 1:\n for layer, aux_var_data in enumerate(aux_data):\n if (\n layer > 0\n and layer >= storage.layer_storage.get_total_size()\n ):\n storage.add_layer()\n if isinstance(data, dict):\n # put layer data back in dictionary\n layer_data = data\n layer_data[\"data\"] = aux_var_data\n else:\n layer_data = aux_var_data\n try:\n storage.set_data(\n layer_data,\n [layer],\n multiplier,\n self._current_key,\n preserve_record=preserve_record,\n )\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"setting data\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n else:\n message = (\n \"Unable to set data for aux variable. \"\n \"Expected {} aux variables but got \"\n \"{}.\".format(len(aux_var_names[0]), len(data))\n )\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self._data_dimensions.structure.get_model(),\n self._data_dimensions.structure.get_package(),\n self._data_dimensions.structure.path,\n \"setting aux variables\",\n self._data_dimensions.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n message,\n self._simulation_data.debug,\n )\n else:\n try:\n storage.set_data(\n data,\n layer,\n multiplier,\n key=self._current_key,\n preserve_record=preserve_record,\n )\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"setting data\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n self._layer_shape = storage.layer_storage.list_shape\n\n def load(\n self,\n first_line,\n file_handle,\n block_header,\n pre_data_comments=None,\n external_file_info=None,\n ):\n \"\"\"Loads data from first_line (the first line of data) and open file\n file_handle which is pointing to the second line of data. Returns a\n tuple with the first item indicating whether all data was read and\n the second item being the last line of text read from the file. This\n method is for internal flopy use and is not intended for the end user.\n\n Parameters\n ----------\n first_line : str\n A string containing the first line of data in this array.\n file_handle : file descriptor\n A file handle for the data file which points to the second\n line of data for this array\n block_header : MFBlockHeader\n Block header object that contains block header information\n for the block containing this data\n pre_data_comments : MFComment\n Comments immediately prior to the data\n external_file_info : list\n Contains information about storing files externally\n\n Returns\n -------\n more data : bool,\n next data line : str\n\n \"\"\"\n super().load(\n first_line,\n file_handle,\n block_header,\n pre_data_comments=None,\n external_file_info=None,\n )\n self._resync()\n if self.structure.layered:\n try:\n model_grid = self._data_dimensions.get_model_grid()\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"getting model grid\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n if self._layer_shape[-1] != model_grid.num_layers():\n if model_grid.grid_type() == DiscretizationType.DISU:\n self._layer_shape = (1,)\n else:\n self._layer_shape = (model_grid.num_layers(),)\n if self._layer_shape[-1] is None:\n self._layer_shape = (1,)\n shape_ml = MultiList(shape=self._layer_shape)\n self._set_storage_obj(\n self._new_storage(shape_ml.get_total_size() != 1, True)\n )\n storage = self._get_storage_obj()\n if external_file_info is not None:\n storage.point_to_existing_external_file(\n external_file_info, storage.layer_storage.get_total_size() - 1\n )\n return_val = [False, None]\n else:\n file_access = MFFileAccessArray(\n self.structure,\n self._data_dimensions,\n self._simulation_data,\n self._path,\n self._current_key,\n )\n self._layer_shape, return_val = file_access.load_from_package(\n first_line,\n file_handle,\n self._layer_shape,\n storage,\n self._keyword,\n pre_data_comments=None,\n )\n\n return return_val\n\n def _is_layered_aux(self):\n # determine if this is the special aux variable case\n if (\n self.structure.name.lower() == \"aux\"\n and self._get_storage_obj().layered\n ):\n return True\n else:\n return False\n\n def get_file_entry(\n self, layer=None, ext_file_action=ExtFileAction.copy_relative_paths\n ):\n \"\"\"Returns a string containing the data in layer \"layer\" formatted for\n a MODFLOW 6 file. For unlayered data do not pass in \"layer\".\n\n Parameters\n ----------\n layer : int\n The layer to return file entry for.\n ext_file_action : ExtFileAction\n How to handle external paths.\n\n Returns\n -------\n file entry : str\n\n \"\"\"\n return self._get_file_entry(layer, ext_file_action)\n\n def _get_file_entry(\n self, layer=None, ext_file_action=ExtFileAction.copy_relative_paths\n ):\n if isinstance(layer, int):\n layer = (layer,)\n data_storage = self._get_storage_obj()\n if (\n data_storage is None\n or data_storage.layer_storage.get_total_size() == 0\n or not data_storage.has_data()\n ):\n return \"\"\n\n layered_aux = self._is_layered_aux()\n\n # prepare indent\n indent = self._simulation_data.indent_string\n shape_ml = MultiList(shape=self._layer_shape)\n if shape_ml.get_total_size() == 1:\n data_indent = indent\n else:\n data_indent = f\"{indent}{self._simulation_data.indent_string}\"\n\n file_entry_array = []\n if data_storage.data_structure_type == DataStructureType.scalar:\n # scalar data, like in the case of a time array series gets written\n # on a single line\n try:\n data = data_storage.get_data()\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"getting data\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n if (\n self.structure.data_item_structures[0].numeric_index\n or self.structure.data_item_structures[0].is_cellid\n ):\n # for cellid and numeric indices convert from 0 base to 1 based\n data = abs(data) + 1\n file_entry_array.append(\n f\"{indent}{self.structure.name}{indent}{data}\\n\"\n )\n elif data_storage.layered:\n if not layered_aux:\n if not self.structure.data_item_structures[0].just_data:\n name = self.structure.name\n file_entry_array.append(f\"{indent}{name}{indent}LAYERED\\n\")\n else:\n file_entry_array.append(f\"{indent}LAYERED\\n\")\n\n if layer is None:\n layer_min = shape_ml.first_index()\n layer_max = copy.deepcopy(self._layer_shape)\n else:\n # set layer range\n if not shape_ml.in_shape(layer):\n comment = (\n 'Layer {} for variable \"{}\" does not exist'\n \".\".format(layer, self._data_name)\n )\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"getting file entry\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n comment,\n self._simulation_data.debug,\n )\n\n layer_min = layer\n layer_max = shape_ml.inc_shape_idx(layer)\n for layer in shape_ml.indexes(layer_min, layer_max):\n file_entry_array.append(\n self._get_file_entry_layer(\n layer,\n data_indent,\n data_storage.layer_storage[layer].data_storage_type,\n ext_file_action,\n layered_aux,\n )\n )\n else:\n # data is not layered\n if not self.structure.data_item_structures[0].just_data:\n if self._data_name == \"aux\":\n file_entry_array.append(\n f\"{indent}{self._get_aux_var_name([0])}\\n\"\n )\n else:\n file_entry_array.append(f\"{indent}{self.structure.name}\\n\")\n\n data_storage_type = data_storage.layer_storage[0].data_storage_type\n file_entry_array.append(\n self._get_file_entry_layer(\n None, data_indent, data_storage_type, ext_file_action\n )\n )\n\n return \"\".join(file_entry_array)\n\n def _new_storage(\n self, set_layers=True, base_storage=False, stress_period=0\n ):\n if set_layers:\n return DataStorage(\n self._simulation_data,\n self._model_or_sim,\n self._data_dimensions,\n self._get_file_entry,\n DataStorageType.internal_array,\n DataStructureType.ndarray,\n self._layer_shape,\n stress_period=stress_period,\n data_path=self._path,\n )\n else:\n return DataStorage(\n self._simulation_data,\n self._model_or_sim,\n self._data_dimensions,\n self._get_file_entry,\n DataStorageType.internal_array,\n DataStructureType.ndarray,\n stress_period=stress_period,\n data_path=self._path,\n )\n\n def _get_storage_obj(self):\n return self._data_storage\n\n def _set_storage_obj(self, storage):\n self._data_storage = storage\n\n def _get_file_entry_layer(\n self,\n layer,\n data_indent,\n storage_type,\n ext_file_action,\n layered_aux=False,\n ):\n if (\n not self.structure.data_item_structures[0].just_data\n and not layered_aux\n ):\n indent_string = \"{}{}\".format(\n self._simulation_data.indent_string,\n self._simulation_data.indent_string,\n )\n else:\n indent_string = self._simulation_data.indent_string\n\n file_entry = \"\"\n if layered_aux:\n try:\n # display aux name\n file_entry = (\n f\"{indent_string}{self._get_aux_var_name(layer)}\\n\"\n )\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"getting aux variables\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n indent_string = (\n f\"{indent_string}{self._simulation_data.indent_string}\"\n )\n\n data_storage = self._get_storage_obj()\n if storage_type == DataStorageType.internal_array:\n # internal data header + data\n format_str = self._get_internal_formatting_string(layer).upper()\n lay_str = self._get_data_layer_string(layer, data_indent).upper()\n file_entry = f\"{file_entry}{indent_string}{format_str}\\n{lay_str}\"\n elif storage_type == DataStorageType.internal_constant:\n # constant data\n try:\n const_val = data_storage.get_const_val(layer)\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"getting constant value\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n None,\n self._simulation_data.debug,\n ex,\n )\n const_str = self._get_constant_formatting_string(\n const_val, layer, self._data_type\n ).upper()\n file_entry = f\"{file_entry}{indent_string}{const_str}\"\n else:\n # external data\n ext_str = self._get_external_formatting_string(\n layer, ext_file_action\n )\n file_entry = f\"{file_entry}{indent_string}{ext_str}\"\n # add to active list of external files\n try:\n file_path = data_storage.get_external_file_path(layer)\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n comment = (\n f'Could not get external file path for layer \"{layer}\"',\n )\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"getting external file path\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n comment,\n self._simulation_data.debug,\n ex,\n )\n package_dim = self._data_dimensions.package_dim\n model_name = package_dim.model_dim[0].model_name\n self._simulation_data.mfpath.add_ext_file(file_path, model_name)\n return file_entry\n\n def _get_data_layer_string(self, layer, data_indent):\n # iterate through data layer\n try:\n data = self._get_storage_obj().get_data(layer, False)\n except Exception as ex:\n type_, value_, traceback_ = sys.exc_info()\n comment = f'Could not get data for layer \"{layer}\"'\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"getting data\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n comment,\n self._simulation_data.debug,\n ex,\n )\n file_access = MFFileAccessArray(\n self.structure,\n self._data_dimensions,\n self._simulation_data,\n self._path,\n self._current_key,\n )\n return file_access.get_data_string(data, self._data_type, data_indent)\n\n def _resolve_layer_index(self, layer, allow_multiple_layers=False):\n # handle layered vs non-layered data\n storage = self._get_storage_obj()\n if storage.layered:\n if layer is None:\n if storage.layer_storage.get_total_size() == 1:\n layer_index = [0]\n elif allow_multiple_layers:\n layer_index = storage.get_active_layer_indices()\n else:\n comment = (\n 'Data \"{}\" is layered but no '\n \"layer_num was specified\"\n \".\".format(self._data_name)\n )\n type_, value_, traceback_ = sys.exc_info()\n raise MFDataException(\n self.structure.get_model(),\n self.structure.get_package(),\n self._path,\n \"resolving layer index\",\n self.structure.name,\n inspect.stack()[0][3],\n type_,\n value_,\n traceback_,\n comment,\n self._simulation_data.debug,\n )\n\n else:\n layer_index = [layer]\n else:\n layer_index = [[0]]\n return layer_index\n\n def _verify_data(self, data_iter, layer_num):\n # TODO: Implement\n return True\n\n def plot(\n self,\n filename_base=None,\n file_extension=None,\n mflay=None,\n fignum=None,\n title=None,\n **kwargs,\n ):\n \"\"\"\n Plot 3-D model input data\n\n Parameters\n ----------\n filename_base : str\n Base file name that will be used to automatically generate file\n names for output image files. Plots will be exported as image\n files if file_name_base is not None. (default is None)\n file_extension : str\n Valid matplotlib.pyplot file extension for savefig(). Only used\n if filename_base is not None. (default is 'png')\n mflay : int\n MODFLOW zero-based layer number to return. If None, then all\n all layers will be included. (default is None)\n **kwargs : dict\n axes : list of matplotlib.pyplot.axis\n List of matplotlib.pyplot.axis that will be used to plot\n data for each layer. If axes=None axes will be generated.\n (default is None)\n pcolor : bool\n Boolean used to determine if matplotlib.pyplot.pcolormesh\n plot will be plotted. (default is True)\n colorbar : bool\n Boolean used to determine if a color bar will be added to\n the matplotlib.pyplot.pcolormesh. Only used if pcolor=True.\n (default is False)\n inactive : bool\n Boolean used to determine if a black overlay in inactive\n cells in a layer will be displayed. (default is True)\n contour : bool\n Boolean used to determine if matplotlib.pyplot.contour\n plot will be plotted. (default is False)\n clabel : bool\n Boolean used to determine if matplotlib.pyplot.clabel\n will be plotted. Only used if contour=True. (default is False)\n grid : bool\n Boolean used to determine if the model grid will be plotted\n on the figure. (default is False)\n masked_values : list\n List of unique values to be excluded from the plot.\n\n Returns\n ----------\n out : list\n Empty list is returned if filename_base is not None. Otherwise\n a list of matplotlib.pyplot.axis is returned.\n \"\"\"\n from ...plot import PlotUtilities\n\n if not self.plottable:\n raise TypeError(\n \"This MFArray is not plottable likely because modelgrid is \"\n \"not available.\"\n )\n\n modelgrid = self._get_model_grid()\n a = self.array\n num_plottable_layers = modelgrid.get_number_plottable_layers(a)\n\n if num_plottable_layers == 1:\n axes = PlotUtilities._plot_util2d_helper(\n self,\n title=title,\n filename_base=filename_base,\n file_extension=file_extension,\n fignum=fignum,\n **kwargs,\n )\n elif num_plottable_layers > 1:\n axes = PlotUtilities._plot_util3d_helper(\n self,\n filename_base=filename_base,\n file_extension=file_extension,\n mflay=mflay,\n fignum=fignum,\n **kwargs,\n )\n else:\n axes = None\n\n return axes\n\n\nclass MFTransientArray(MFArray, MFTransient):\n \"\"\"\n Provides an interface for the user to access and update MODFLOW transient\n array data. MFTransientArray objects are not designed to be directly\n constructed by the end user. When a FloPy for MODFLOW 6 package object is\n constructed, the appropriate MFArray objects are automatically built.\n\n Parameters\n ----------\n sim_data : MFSimulationData\n data contained in the simulation\n structure : MFDataStructure\n describes the structure of the data\n data : list or ndarray\n actual data\n enable : bool\n enable/disable the array\n path : tuple\n path in the data dictionary to this MFArray\n dimensions : MFDataDimensions\n dimension information related to the model, package, and array\n\n Examples\n --------\n\n \"\"\"\n\n def __init__(\n self,\n sim_data,\n model_or_sim,\n structure,\n enable=True,\n path=None,\n dimensions=None,\n block=None,\n ):\n MFTransient.__init__(self)\n MFArray.__init__(\n self,\n sim_data=sim_data,\n model_or_sim=model_or_sim,\n structure=structure,\n data=None,\n enable=enable,\n path=path,\n dimensions=dimensions,\n block=block,\n )\n self.repeating = True\n\n @property\n def data_type(self):\n \"\"\"Type of data (DataType) stored in the array\"\"\"\n return DataType.transient2d\n\n def remove_transient_key(self, transient_key):\n \"\"\"Removes a new transient time `transient_key` and any data stored\n at that time. This method is intended for internal library usage only.\n\n Parameters\n ----------\n transient_key : int\n Zero-based stress period\n\n \"\"\"\n if transient_key in self._data_storage:\n del self._data_storage[transient_key]\n\n def add_transient_key(self, transient_key):\n \"\"\"Adds a new transient time allowing data for that time to be stored\n and retrieved using the key `transient_key`. This method is intended\n for internal library usage only.\n\n Parameters\n ----------\n transient_key : int\n Zero-based stress period\n\n \"\"\"\n super().add_transient_key(transient_key)\n self._data_storage[transient_key] = super()._new_storage(\n stress_period=transient_key\n )\n\n def store_as_external_file(\n self,\n external_file_path,\n layer=None,\n binary=False,\n replace_existing_external=True,\n check_data=True,\n ):\n \"\"\"Stores data from layer `layer` to an external file at\n `external_file_path`. For unlayered data do not pass in `layer`.\n If layer is not specified all layers will be stored with each layer\n as a separate file. If replace_existing_external is set to False,\n this method will not do anything if the data is already in an\n external file.\n\n Parameters\n ----------\n external_file_path : str\n Path to external file\n layer : int\n Which layer to store in external file, `None` value stores all\n layers.\n binary : bool\n Store data in a binary file\n replace_existing_external : bool\n Whether to replace an existing external file.\n check_data : bool\n Verify data prior to storing\n \"\"\"\n # store each stress period in separate file(s)\n for sp in self._data_storage.keys():\n self._current_key = sp\n layer_storage = self._get_storage_obj().layer_storage\n if (\n layer_storage.get_total_size() > 0\n and self._get_storage_obj().layer_storage[0].data_storage_type\n != DataStorageType.external_file\n ):\n fname, ext = os.path.splitext(external_file_path)\n if DatumUtil.is_int(sp):\n full_name = f\"{fname}_{sp + 1}{ext}\"\n else:\n full_name = f\"{fname}_{sp}{ext}\"\n super().store_as_external_file(\n full_name,\n layer,\n binary,\n replace_existing_external,\n check_data,\n )\n\n def store_internal(\n self,\n layer=None,\n check_data=True,\n ):\n \"\"\"Stores data from layer `layer` internally. For unlayered data do\n not pass in `layer`. If layer is not specified all layers will be\n stored internally.\n\n Parameters\n ----------\n layer : int\n Which layer to store internally file, `None` value stores all\n layers.\n check_data : bool\n Verify data prior to storing\n \"\"\"\n for sp in self._data_storage.keys():\n self._current_key = sp\n layer_storage = self._get_storage_obj().layer_storage\n if (\n layer_storage.get_total_size() > 0\n and self._get_storage_obj().layer_storage[0].data_storage_type\n == DataStorageType.external_file\n ):\n super().store_internal(\n layer,\n check_data,\n )\n\n def _get_array(self, num_sp, apply_mult, **kwargs):\n \"\"\"Returns all data up to stress period num_sp in a single array.\n If `layer` is None, returns all data for time `layer`.\n\n Parameters\n ----------\n num_sp : int\n Zero-based stress period of data to return all data up to\n apply_mult : bool\n Whether to apply multiplier to data prior to returning it\n\n \"\"\"\n data = None\n output = None\n for sp in range(0, num_sp):\n if sp in self._data_storage:\n self.get_data_prep(sp)\n data = super().get_data(apply_mult=apply_mult, **kwargs)\n data = np.expand_dims(data, 0)\n else:\n # if there is no previous data provide array of\n # zeros, otherwise provide last array of data found\n if data is None:\n # get any data\n data_dimensions = None\n for key in self._data_storage.keys():\n self.get_data_prep(key)\n data = super().get_data(\n apply_mult=apply_mult, **kwargs\n )\n break\n if data is not None:\n if self.structure.type == DatumType.integer:\n data = np.full_like(data, 1)\n else:\n data = np.full_like(data, 0.0)\n data = np.expand_dims(data, 0)\n if output is None or data is None:\n output = data\n else:\n output = np.concatenate((output, data))\n return output\n\n def has_data(self, layer=None):\n if layer is None:\n for sto_key in self._data_storage.keys():\n self.get_data_prep(sto_key)\n if super().has_data():\n return True\n return False\n else:\n self.get_data_prep(layer)\n return super().has_data()\n\n def get_record(self, key=None):\n \"\"\"Returns the data record (data and metadata) associated with stress\n period key `layer`. If `layer` is None, returns all data for\n time `layer`.\n\n Parameters\n ----------\n key : int\n Zero-based stress period of data to return\n\n \"\"\"\n if self._data_storage is not None and len(self._data_storage) > 0:\n if key is None:\n sim_time = self._data_dimensions.package_dim.model_dim[\n 0\n ].simulation_time\n num_sp = sim_time.get_num_stress_periods()\n return self._build_period_data(num_sp, get_record=True)\n else:\n self.get_data_prep(key)\n return super().get_record()\n\n def get_data(self, key=None, apply_mult=True, **kwargs):\n \"\"\"Returns the data associated with stress period key `key`.\n\n Parameters\n ----------\n key : int\n Zero-based stress period of data to return\n apply_mult : bool\n Whether to apply multiplier to data prior to returning it\n\n \"\"\"\n if self._data_storage is not None and len(self._data_storage) > 0:\n if key is None:\n sim_time = self._data_dimensions.package_dim.model_dim[\n 0\n ].simulation_time\n num_sp = sim_time.get_num_stress_periods()\n if \"array\" in kwargs:\n return self._get_array(num_sp, apply_mult, **kwargs)\n else:\n return self._build_period_data(\n num_sp, apply_mult, **kwargs\n )\n else:\n self.get_data_prep(key)\n return super().get_data(apply_mult=apply_mult)\n else:\n return None\n\n def _build_period_data(\n self, num_sp, apply_mult=False, get_record=False, **kwargs\n ):\n output = None\n for sp in range(0, num_sp):\n data = None\n if sp in self._data_storage:\n self.get_data_prep(sp)\n if get_record:\n data = super().get_record()\n else:\n data = super().get_data(apply_mult=apply_mult, **kwargs)\n if output is None:\n if \"array\" in kwargs:\n output = [data]\n else:\n output = {sp: data}\n else:\n if \"array\" in kwargs:\n output.append(data)\n else:\n output[sp] = data\n return output\n\n def set_record(self, data_record):\n \"\"\"Sets data and metadata at layer `layer` and time `key` to\n `data_record`. For unlayered data do not pass in `layer`.\n\n Parameters\n ----------\n data_record : dict\n Data record being set. Data must be a dictionary with keys as\n zero-based stress periods and values as a dictionary of data\n and metadata (factor, iprn, filename, binary, data) for a given\n stress period. How to define the dictionary of data and\n metadata is described in the MFData class's set_record method.\n \"\"\"\n self._set_data_record(data_record, is_record=True)\n\n def set_data(self, data, multiplier=None, layer=None, key=None):\n \"\"\"Sets the contents of the data at layer `layer` and time `key` to\n `data` with multiplier `multiplier`. For unlayered data do not pass\n in `layer`.\n\n Parameters\n ----------\n data : dict, ndarray, list\n Data being set. Data can be a dictionary with keys as\n zero-based stress periods and values as the data. If data is\n an ndarray or list of lists, it will be assigned to the the\n stress period specified in `key`. If any is set to None, that\n stress period of data will be removed.\n multiplier : int\n multiplier to apply to data\n layer : int\n Layer of data being set. Keep default of None of data is not\n layered.\n key : int\n Zero based stress period to assign data too. Does not apply\n if `data` is a dictionary.\n \"\"\"\n self._set_data_record(data, multiplier, layer, key)\n\n def _set_data_record(\n self, data, multiplier=None, layer=None, key=None, is_record=False\n ):\n if isinstance(data, dict):\n # each item in the dictionary is a list for one stress period\n # the dictionary key is the stress period the list is for\n del_keys = []\n for key, list_item in data.items():\n if list_item is None:\n self.remove_transient_key(key)\n del_keys.append(key)\n else:\n self._set_data_prep(list_item, key)\n if is_record:\n super().set_record(list_item)\n else:\n super().set_data(list_item, multiplier, layer)\n for key in del_keys:\n del data[key]\n else:\n if key is None:\n # search for a key\n new_key_index = self.structure.first_non_keyword_index()\n if (\n new_key_index is not None\n and hasattr(data, \"__len__\")\n and len(data) > new_key_index\n ):\n key = data[new_key_index]\n else:\n key = 0\n if data is None:\n self.remove_transient_key(key)\n else:\n self._set_data_prep(data, key)\n super().set_data(data, multiplier, layer)\n\n def get_file_entry(\n self, key=0, ext_file_action=ExtFileAction.copy_relative_paths\n ):\n \"\"\"Returns a string containing the data in stress period \"key\".\n\n Parameters\n ----------\n key : int\n The stress period to return file entry for.\n ext_file_action : ExtFileAction\n How to handle external paths.\n\n Returns\n -------\n file entry : str\n\n \"\"\"\n\n self._get_file_entry_prep(key)\n return super().get_file_entry(ext_file_action=ext_file_action)\n\n def load(\n self,\n first_line,\n file_handle,\n block_header,\n pre_data_comments=None,\n external_file_info=None,\n ):\n \"\"\"Loads data from first_line (the first line of data) and open file\n handle which is pointing to the second line of data. Returns a\n tuple with the first item indicating whether all data was read\n and the second item being the last line of text read from the file.\n This method is for internal flopy use and is not intended to be called\n by the end user.\n\n Parameters\n ----------\n first_line : str\n A string containing the first line of data in this array.\n file_handle : file descriptor\n A file handle for the data file which points to the second\n line of data for this array\n block_header : MFBlockHeader\n Block header object that contains block header information\n for the block containing this data\n pre_data_comments : MFComment\n Comments immediately prior to the data\n external_file_info : list\n Contains information about storing files externally\n\n Returns\n -------\n more data : bool,\n next data line : str\n\n \"\"\"\n self._load_prep(block_header)\n return super().load(\n first_line, file_handle, pre_data_comments, external_file_info\n )\n\n def _new_storage(\n self, set_layers=True, base_storage=False, stress_period=0\n ):\n if base_storage:\n if not isinstance(stress_period, int):\n stress_period = 1\n return super()._new_storage(\n set_layers, base_storage, stress_period\n )\n else:\n return {}\n\n def _set_storage_obj(self, storage):\n self._data_storage[self._current_key] = storage\n\n def _get_storage_obj(self):\n if (\n self._current_key is None\n or self._current_key not in self._data_storage\n ):\n return None\n return self._data_storage[self._current_key]\n\n def plot(\n self,\n kper=None,\n filename_base=None,\n file_extension=None,\n mflay=None,\n fignum=None,\n **kwargs,\n ):\n \"\"\"\n Plot transient array model input data\n\n Parameters\n ----------\n transient2d : flopy.utils.util_array.Transient2D object\n filename_base : str\n Base file name that will be used to automatically generate file\n names for output image files. Plots will be exported as image\n files if file_name_base is not None. (default is None)\n file_extension : str\n Valid matplotlib.pyplot file extension for savefig(). Only used\n if filename_base is not None. (default is 'png')\n **kwargs : dict\n axes : list of matplotlib.pyplot.axis\n List of matplotlib.pyplot.axis that will be used to plot\n data for each layer. If axes=None axes will be generated.\n (default is None)\n pcolor : bool\n Boolean used to determine if matplotlib.pyplot.pcolormesh\n plot will be plotted. (default is True)\n colorbar : bool\n Boolean used to determine if a color bar will be added to\n the matplotlib.pyplot.pcolormesh. Only used if pcolor=True.\n (default is False)\n inactive : bool\n Boolean used to determine if a black overlay in inactive\n cells in a layer will be displayed. (default is True)\n contour : bool\n Boolean used to determine if matplotlib.pyplot.contour\n plot will be plotted. (default is False)\n clabel : bool\n Boolean used to determine if matplotlib.pyplot.clabel\n will be plotted. Only used if contour=True. (default is False)\n grid : bool\n Boolean used to determine if the model grid will be plotted\n on the figure. (default is False)\n masked_values : list\n List of unique values to be excluded from the plot.\n kper : str\n MODFLOW zero-based stress period number to return. If\n kper='all' then data for all stress period will be\n extracted. (default is zero).\n\n Returns\n ----------\n axes : list\n Empty list is returned if filename_base is not None. Otherwise\n a list of matplotlib.pyplot.axis is returned.\n \"\"\"\n from ...plot.plotutil import PlotUtilities\n\n if not self.plottable:\n raise TypeError(\"Simulation level packages are not plottable\")\n\n axes = PlotUtilities._plot_transient2d_helper(\n self,\n filename_base=filename_base,\n file_extension=file_extension,\n kper=kper,\n fignum=fignum,\n **kwargs,\n )\n return axes\n", "repo_name": "modflowpy/flopy", "sub_path": "flopy/mf6/data/mfdataarray.py", "file_name": "mfdataarray.py", "file_ext": "py", "file_size_in_byte": 77273, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 449, "dataset": "github-code", "pt": "27", "api": [{"api_name": "mfdata.MFMultiDimVar", "line_number": 19, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 62, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 63, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 69, "usage_type": "call"}, {"api_name": "utils.datautil.MultiList", "line_number": 83, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 88, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 89, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 95, "usage_type": "call"}, {"api_name": "data.mfstructure.DatumType.integer", "line_number": 104, "usage_type": "attribute"}, {"api_name": "data.mfstructure.DatumType", "line_number": 104, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 108, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 111, "usage_type": "argument"}, {"api_name": "sys.exc_info", "line_number": 114, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 115, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 121, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 157, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 158, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 164, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 184, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 185, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 191, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 203, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 204, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 210, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 231, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 232, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 238, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 257, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 258, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 264, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 284, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 285, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 291, "usage_type": "call"}, {"api_name": "datbase.DataType.array3d", "line_number": 304, "usage_type": "attribute"}, {"api_name": "datbase.DataType", "line_number": 304, "usage_type": "name"}, {"api_name": "datbase.DataType.array2d", "line_number": 306, "usage_type": "attribute"}, {"api_name": "datbase.DataType", "line_number": 306, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 353, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 354, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 360, "usage_type": "call"}, {"api_name": "utils.mfenums.DiscretizationType.DISU", "line_number": 370, "usage_type": "attribute"}, {"api_name": "utils.mfenums.DiscretizationType", "line_number": 370, "usage_type": "name"}, {"api_name": "utils.mfenums.DiscretizationType.DISU", "line_number": 385, "usage_type": "attribute"}, {"api_name": "utils.mfenums.DiscretizationType", "line_number": 385, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 393, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 394, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 400, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 416, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 417, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 423, "usage_type": "call"}, {"api_name": "utils.mfenums.DiscretizationType.DISU", "line_number": 434, "usage_type": "attribute"}, {"api_name": "utils.mfenums.DiscretizationType", "line_number": 434, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 442, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 443, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 449, "usage_type": "call"}, {"api_name": "mfdatastorage.DataStorageType.internal_array", "line_number": 497, "usage_type": "attribute"}, {"api_name": "mfdatastorage.DataStorageType", "line_number": 497, "usage_type": "name"}, {"api_name": "mfdatastorage.DataStorageType.internal_constant", "line_number": 499, "usage_type": "attribute"}, {"api_name": "mfdatastorage.DataStorageType", "line_number": 499, "usage_type": "name"}, {"api_name": "mfdatastorage.DataStorageType.internal_array", "line_number": 506, "usage_type": "attribute"}, {"api_name": "mfdatastorage.DataStorageType", "line_number": 506, "usage_type": "name"}, {"api_name": "mfdatastorage.DataStorageType.internal_constant", "line_number": 508, "usage_type": "attribute"}, {"api_name": "mfdatastorage.DataStorageType", "line_number": 508, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 518, "usage_type": "call"}, {"api_name": "os.path", "line_number": 518, "usage_type": "attribute"}, {"api_name": "data.mfstructure", "line_number": 528, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 530, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 533, "usage_type": "argument"}, {"api_name": "mfbase.VerbosityLevel.verbose", "line_number": 543, "usage_type": "attribute"}, {"api_name": "mfbase.VerbosityLevel", "line_number": 543, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 564, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 565, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 571, "usage_type": "call"}, {"api_name": "mfdatastorage.DataStorageType.external_file", "line_number": 607, "usage_type": "attribute"}, {"api_name": "mfdatastorage.DataStorageType", "line_number": 607, "usage_type": "name"}, {"api_name": "mfdatastorage.DataStorageType.external_file", "line_number": 613, "usage_type": "attribute"}, {"api_name": "mfdatastorage.DataStorageType", "line_number": 613, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 624, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 626, "usage_type": "name"}, {"api_name": "mfbase.VerbosityLevel.verbose", "line_number": 633, "usage_type": "attribute"}, {"api_name": "mfbase.VerbosityLevel", "line_number": 633, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 651, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 652, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 658, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 690, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 691, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 697, "usage_type": "call"}, {"api_name": "data.mfstructure", "line_number": 730, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 735, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 737, "usage_type": "name"}, {"api_name": "numpy.expand_dims", "line_number": 737, "usage_type": "call"}, {"api_name": "data.mfstructure", "line_number": 738, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 740, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 741, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 747, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 782, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 783, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 789, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 862, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 863, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 869, "usage_type": "call"}, {"api_name": "data.mfstructure", "line_number": 895, "usage_type": "argument"}, {"api_name": "data.mfstructure", "line_number": 910, "usage_type": "argument"}, {"api_name": "data.mfstructure", "line_number": 912, "usage_type": "argument"}, {"api_name": "data.mfstructure", "line_number": 922, "usage_type": "argument"}, {"api_name": "copy.deepcopy", "line_number": 923, "usage_type": "call"}, {"api_name": "data.mfstructure", "line_number": 923, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 925, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 945, "usage_type": "argument"}, {"api_name": "data.mfstructure", "line_number": 947, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 960, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 961, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 967, "usage_type": "call"}, {"api_name": "data.mfstructure", "line_number": 979, "usage_type": "argument"}, {"api_name": "sys.exc_info", "line_number": 981, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 982, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 988, "usage_type": "call"}, {"api_name": "data.mfstructure", "line_number": 998, "usage_type": "argument"}, {"api_name": "sys.exc_info", "line_number": 1005, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 1006, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 1012, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 1069, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 1070, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 1076, "usage_type": "call"}, {"api_name": "utils.mfenums.DiscretizationType.DISU", "line_number": 1085, "usage_type": "attribute"}, {"api_name": "utils.mfenums.DiscretizationType", "line_number": 1085, "usage_type": "name"}, {"api_name": "utils.datautil.MultiList", "line_number": 1091, "usage_type": "call"}, {"api_name": "mffileaccess.MFFileAccessArray", "line_number": 1102, "usage_type": "call"}, {"api_name": "mfbase.ExtFileAction.copy_relative_paths", "line_number": 1131, "usage_type": "attribute"}, {"api_name": "mfbase.ExtFileAction", "line_number": 1131, "usage_type": "name"}, {"api_name": "mfbase.ExtFileAction.copy_relative_paths", "line_number": 1151, "usage_type": "attribute"}, {"api_name": "mfbase.ExtFileAction", "line_number": 1151, "usage_type": "name"}, {"api_name": "utils.datautil.MultiList", "line_number": 1167, "usage_type": "call"}, {"api_name": "mfdatastorage.DataStructureType.scalar", "line_number": 1174, "usage_type": "attribute"}, {"api_name": "mfdatastorage.DataStructureType", "line_number": 1174, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1178, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 1180, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 1181, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 1187, "usage_type": "call"}, {"api_name": "data.mfstructure", "line_number": 1200, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1202, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 1214, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 1222, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 1223, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 1229, "usage_type": "call"}, {"api_name": "mfdatastorage.DataStorage", "line_number": 1272, "usage_type": "call"}, {"api_name": "mfdatastorage.DataStorageType.internal_array", "line_number": 1277, "usage_type": "attribute"}, {"api_name": "mfdatastorage.DataStorageType", "line_number": 1277, "usage_type": "name"}, {"api_name": "mfdatastorage.DataStructureType.ndarray", "line_number": 1278, "usage_type": "attribute"}, {"api_name": "mfdatastorage.DataStructureType", "line_number": 1278, "usage_type": "name"}, {"api_name": "mfdatastorage.DataStorage", "line_number": 1284, "usage_type": "call"}, {"api_name": "mfdatastorage.DataStorageType.internal_array", "line_number": 1289, "usage_type": "attribute"}, {"api_name": "mfdatastorage.DataStorageType", "line_number": 1289, "usage_type": "name"}, {"api_name": "mfdatastorage.DataStructureType.ndarray", "line_number": 1290, "usage_type": "attribute"}, {"api_name": "mfdatastorage.DataStructureType", "line_number": 1290, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 1328, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 1329, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 1335, "usage_type": "call"}, {"api_name": "mfdatastorage.DataStorageType.internal_array", "line_number": 1348, "usage_type": "attribute"}, {"api_name": "mfdatastorage.DataStorageType", "line_number": 1348, "usage_type": "name"}, {"api_name": "mfdatastorage.DataStorageType.internal_constant", "line_number": 1353, "usage_type": "attribute"}, {"api_name": "mfdatastorage.DataStorageType", "line_number": 1353, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 1358, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 1359, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 1365, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 1387, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 1391, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 1397, "usage_type": "call"}, {"api_name": "data.mfstructure", "line_number": 1413, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 1415, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 1417, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 1423, "usage_type": "call"}, {"api_name": "mffileaccess.MFFileAccessArray", "line_number": 1431, "usage_type": "call"}, {"api_name": "data.mfstructure", "line_number": 1438, "usage_type": "argument"}, {"api_name": "sys.exc_info", "line_number": 1455, "usage_type": "call"}, {"api_name": "mfbase.MFDataException", "line_number": 1456, "usage_type": "call"}, {"api_name": "inspect.stack", "line_number": 1462, "usage_type": "call"}, {"api_name": "plot.PlotUtilities._plot_util2d_helper", "line_number": 1550, "usage_type": "call"}, {"api_name": "plot.PlotUtilities", "line_number": 1550, "usage_type": "name"}, {"api_name": "plot.PlotUtilities._plot_util3d_helper", "line_number": 1559, "usage_type": "call"}, {"api_name": "plot.PlotUtilities", "line_number": 1559, "usage_type": "name"}, {"api_name": "mfdata.MFTransient", "line_number": 1573, "usage_type": "name"}, {"api_name": "mfdata.MFTransient.__init__", "line_number": 1610, "usage_type": "call"}, {"api_name": "mfdata.MFTransient", "line_number": 1610, "usage_type": "name"}, {"api_name": "{'PlotUtilities': 'plot.PlotUtilities'}.__init__", "line_number": 1611, "usage_type": "call"}, {"api_name": "datbase.DataType.transient2d", "line_number": 1627, "usage_type": "attribute"}, {"api_name": "datbase.DataType", "line_number": 1627, "usage_type": "name"}, {"api_name": "mfdatastorage.DataStorageType.external_file", "line_number": 1694, "usage_type": "attribute"}, {"api_name": "mfdatastorage.DataStorageType", "line_number": 1694, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 1696, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1696, "usage_type": "attribute"}, {"api_name": "utils.datautil.DatumUtil.is_int", "line_number": 1697, "usage_type": "call"}, {"api_name": "utils.datautil.DatumUtil", "line_number": 1697, "usage_type": "name"}, {"api_name": "mfdatastorage.DataStorageType.external_file", "line_number": 1732, "usage_type": "attribute"}, {"api_name": "mfdatastorage.DataStorageType", "line_number": 1732, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1751, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1756, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1757, "usage_type": "name"}, {"api_name": "numpy.expand_dims", "line_number": 1757, "usage_type": "call"}, {"api_name": "data.mfstructure", "line_number": 1761, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1766, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1770, "usage_type": "name"}, {"api_name": "data.mfstructure.DatumType.integer", "line_number": 1771, "usage_type": "attribute"}, {"api_name": "data.mfstructure.DatumType", "line_number": 1771, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1772, "usage_type": "name"}, {"api_name": "numpy.full_like", "line_number": 1772, "usage_type": "call"}, {"api_name": "data.mfstructure", "line_number": 1774, "usage_type": "name"}, {"api_name": "numpy.full_like", "line_number": 1774, "usage_type": "call"}, {"api_name": "data.mfstructure", "line_number": 1775, "usage_type": "name"}, {"api_name": "numpy.expand_dims", "line_number": 1775, "usage_type": "call"}, {"api_name": "data.mfstructure", "line_number": 1776, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1777, "usage_type": "name"}, {"api_name": "numpy.concatenate", "line_number": 1779, "usage_type": "call"}, {"api_name": "data.mfstructure", "line_number": 1779, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1849, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1853, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1855, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1858, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1860, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1863, "usage_type": "argument"}, {"api_name": "data.mfstructure", "line_number": 1865, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1905, "usage_type": "argument"}, {"api_name": "data.mfstructure", "line_number": 1910, "usage_type": "argument"}, {"api_name": "data.mfstructure.items", "line_number": 1914, "usage_type": "call"}, {"api_name": "data.mfstructure", "line_number": 1914, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1925, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1932, "usage_type": "argument"}, {"api_name": "data.mfstructure", "line_number": 1933, "usage_type": "argument"}, {"api_name": "data.mfstructure", "line_number": 1935, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1938, "usage_type": "name"}, {"api_name": "data.mfstructure", "line_number": 1941, "usage_type": "argument"}, {"api_name": "data.mfstructure", "line_number": 1942, "usage_type": "argument"}, {"api_name": "mfbase.ExtFileAction.copy_relative_paths", "line_number": 1945, "usage_type": "attribute"}, {"api_name": "mfbase.ExtFileAction", "line_number": 1945, "usage_type": "name"}, {"api_name": "plot.plotutil.PlotUtilities._plot_transient2d_helper", "line_number": 2093, "usage_type": "call"}, {"api_name": "plot.plotutil.PlotUtilities", "line_number": 2093, "usage_type": "name"}]} +{"seq_id": "17809513993", "text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# cell_metadata_filter: -all\n# formats: notebooks//ipynb,py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.13.7\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# # Dissolution of calcite in an acidic HCl-solution\n#\n# This tutorial demonstrates how Reaktoro can be used for modeling the dissolution of calcite in an acidic\n# HCl-solution at temperature 30 °C and pressure 1 bar using chemical kinetics. A partial equilibrium\n# assumption is considered here so that aqueous species react using a chemical equilibrium model, while calcite\n# reacts with the aqueous solution using a chemical kinetics model.\n#\n# We start with again import the reaktoro Python package so that we can use its classes and methods for performing the\n# chemical reaction calculations.\n\nfrom reaktoro import *\n\n# The class [ChemicalEditor](https://reaktoro.org/cpp/classReaktoro_1_1ChemicalEditor.html) is used to conveniently\n# create instances of classes [ChemicalSystem](https://reaktoro.org/cpp/classReaktoro_1_1ChemicalSystem.html) and\n# [ReactionSystem](https://reaktoro.org/cpp/classReaktoro_1_1ReactionSystem.html). In particular, we specify aqueous\n# and mineral phases that should be considered in the chemical system. The aqueous phase is defined by the mixing of\n# H2O, HCl, and CaCO3 (effectively, collecting all aqueous species in the database that contains elements H,\n# O, C, Cl,\n# and Ca, which are the elements in this list of compounds). There is only one pure mineral phase: the calcite phase.\n\neditor = ChemicalEditor()\neditor.addAqueousPhaseWithElementsOf(\"H2O HCl CaCO3\")\neditor.addMineralPhase(\"Calcite\")\n\n# We set the reaction equation using\n# [setEquation](https://reaktoro.org/cpp/classReaktoro_1_1ChemicalEditor.html#af3c6212c6edb42c0e6f110b493ece45c)\n# method of the class [MineralReaction](https://reaktoro.org/cpp/classReaktoro_1_1MineralReaction.html).\n# Then, we add two mineral kinetic mechanisms for the reaction: neutral and acidic. This is done with the\n# [addMechanism](https://reaktoro.org/cpp/classReaktoro_1_1MineralReaction.html#a1bdeff51e51f42e4635208241cd54027)\n# method, where we set, for example, `logk`, the kinetic rate constant of the reaction in log scale, and `Ea`, the\n# Arrhenius activation energy. The values shown for `logk` and `Ea` were collected from:\n#\n# *Palandri, J.L., Kharaka, Y.K. (2004). A compilation of rate parameters of water-mineral interaction kinetics for\n# application to geochemical modeling. U.S. Geological Survey Open File Report (Vol. 2004–1068). Menlo Park,\n# California.*\n#\n# Finally, we provide the specific surface area of the mineral using method\n# [setSpecificSurfaceArea](https://reaktoro.org/cpp/classReaktoro_1_1MineralReaction.html#a9ea2feb68af0beddc856d6a60b863181)\n# of class [MineralReaction](https://reaktoro.org/cpp/classReaktoro_1_1MineralReaction.html), which can be specified\n# in units of m2/g or m2/m3. Compatible units are allowed, such as cm2/mg or\n# m2/dm3, and combinations.\n\neditor.addMineralReaction(\"Calcite\") \\\n .setEquation(\"Calcite = Ca++ + CO3--\") \\\n .addMechanism(\"logk = -5.81 mol/(m2*s); Ea = 23.5 kJ/mol\") \\\n .addMechanism(\"logk = -0.30 mol/(m2*s); Ea = 14.4 kJ/mol; a[H+] = 1.0\") \\\n .setSpecificSurfaceArea(10, \"cm2/g\")\n\n# Create instances of [ChemicalSystem](https://reaktoro.org/cpp/classReaktoro_1_1ChemicalSystem.html) and\n# [ReactionSystem](https://reaktoro.org/cpp/classReaktoro_1_1ReactionSystem.html).\n# [ChemicalSystem](https://reaktoro.org/cpp/classReaktoro_1_1ChemicalSystem.html) is a class that represents a\n# system and its attributes and properties, such as phases (in our case aqueous and mineral ones), species,\n# elements (5 in total, i.e., H, O, Ca, C, Cl), formula matrix, as well as chemical and thermodynamical model. Class\n# [ReactionSystem](https://reaktoro.org/cpp/classReaktoro_1_1ReactionSystem.html) serves as a system of the chemical\n# reaction by a collection of [Reaction](https://reaktoro.org/cpp/classReaktoro_1_1Reaction.html) class instances.\n# It provides convenient methods that calculate the equilibrium constants, reaction quotients, and rates of the\n# reactions.\n\nsystem = ChemicalSystem(editor)\nreactions = ReactionSystem(editor)\n\n# ### Specifying the equilibrium and kinetic species\n#\n# For the partition of a chemical system into equilibrium and kinetic species, we use the class\n# [Partition](https://reaktoro.org/cpp/classReaktoro_1_1Partition.html). We only\n# need to specify which species are kinetic species, and all others will be equilibrium species by default.\n# We set species Calcite (the only species in the mineral phase also called Calcite!) to be the only kinetic species.\n# This will allow us to model the dissolution of calcite using chemical kinetics, while all other species (the\n# aqueous species) are modeled using chemical equilibrium (i.e., their amounts are updated over time using chemical\n# equilibrium calculations).\n\npartition = Partition(system)\npartition.setKineticSpecies([\"Calcite\"])\n\n\n# ### Defining the initial state of the equilibrium species\n#\n# After constructing the chemical system and specifying the partitioning of the species, we proceed to a chemical\n# equilibrium calculation to set the initial state of the equilibrium species. For this, we use class\n# [EquilibriumProblem](https://reaktoro.org/cpp/classReaktoro_1_1EquilibriumProblem.html), as shown below:\n\nproblem = EquilibriumProblem(system)\nproblem.setPartition(partition)\nproblem.setTemperature(30, \"celsius\")\nproblem.setPressure(1, \"bar\")\nproblem.add(\"H2O\", 1, \"kg\")\nproblem.add(\"HCl\", 1, \"mmol\")\n\n# We specify the equilibrium/kinetic partitioning of the chemical system using the method\n# [setPartition](https://reaktoro.org/cpp/classReaktoro_1_1EquilibriumProblem.html#a53a9496c9d4ffc72a85903146b390e44)\n# of class [EquilibriumProblem](https://reaktoro.org/cpp/classReaktoro_1_1EquilibriumProblem.html). We then prescribe\n# what should be the initial state of the equilibrium species (the aqueous species in this case), before we start the\n# chemical kinetics calculation that will simulate the dissolution of calcite in this aqueous fluid.\n#\n# By mixing 1 kg of H2O and 1 mmol of HCl at 30 °C and 1 bar, we should produce a\n# chemical equilibrium state that corresponds to an acidic aqueous fluid. The species in this fluid will be in\n# disequilibrium with Calcite (our single kinetic species in this setup) since only equilibrium species\n# (i.e., the aqueous species) are considered during the next chemical equilibrium calculation.\n#\n# ### Calculating the initial chemical equilibrium state of the fluid\n#\n# We now use the function equilibrate to calculate the chemical equilibrium state of the equilibrium partition,\n# not the entire chemical system.\n\nstate0 = equilibrate(problem)\n\n# For this calculation, Reaktoro uses an efficient Gibbs energy minimization algorithm to determine the amounts of\n# the equilibrium species that correspond to a state of minimum Gibbs energy in the equilibrium partition only,\n# at given conditions of temperature, pressure, and element amounts in the equilibrium partition. The result is\n# stored in the object state0 of class [ChemicalState](https://reaktoro.org/cpp/classReaktoro_1_1ChemicalState.html),\n# a computational representation of the state of a multiphase\n# chemical system defined by its temperature (*T*), pressure (*P*), and vector of species amounts (*n*).\n#\n# To simulate the kinetic dissolution of calcite in the aqueous fluid we defined before, we need to specify its\n# initial amount. Below, we set the initial mass of species Calcite to 100 g.\n\nstate0.setSpeciesMass(\"Calcite\", 100, \"g\")\n\n# ### Performing the kinetic path calculation\n#\n# To be able to simulate the chemical kinetic path, we use class\n# [KineticPath](https://reaktoro.org/cpp/classReaktoro_1_1KineticPath.html). Note that here again, we need to\n# specify the partitioning of the chemical system into equilibrium, kinetic, and inert species.\n\npath = KineticPath(reactions)\npath.setPartition(partition)\n\n# To analyse the result of kinetic simulations, we save the evolution of different properties of the chemical system\n# into file `result.txt`:\n\noutput = path.output()\noutput.filename(\"results.txt\")\noutput.add(\"time(units=minute)\")\noutput.add(\"elementMolality(Ca units=mmolal)\", \"Ca [mmolal]\")\noutput.add(\"phaseMass(Calcite units=g)\", \"Calcite [units=g]\")\noutput.add(\"speciesMolality(Ca++ units=mmolal)\", \"Ca++ [mmol]\")\noutput.add(\"speciesMolality(HCO3- units=mmolal)\", \"HCO3- [mmol]\")\noutput.add(\"pH\")\n\n# > **Note**: A list of all possible quantities that can be plotted is shown in the class\n# > [ChemicalQuantity](https://reaktoro.org/cpp/classReaktoro_1_1ChemicalQuantity.html),\n# > which provides an interface for convenient ways of their retrieval.\n#\n# ### Solving the chemical kinetics problem\n#\n# Finally, we solve the kinetic path problem.\n# This step executes the method solve of class\n# [KineticPath](https://reaktoro.org/cpp/classReaktoro_1_1KineticPath.html), which requires the initial state of the\n# system (100 g of calcite in disequilibrium with a 1 mmolal HCl aqueous solution at 30 °C and 1 bar,\n# represented with the object state0), the initial and final time of the kinetic path calculation (`t0` and `t1`,\n# respectively), and the time unit of the specified time parameters (e.g., s, minute, day, year, etc.).\n\nt0, t1 = 0.0, 5.0\npath.solve(state0, t0, t1, \"minute\")\n\n# ### Plotting the results of equilibrium path calculation\n#\n# To load results from the outputfile, we use [loadtxt](https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html)\n# function provided by the *numpy* package:\n\nfilearray = numpy.loadtxt(\"results.txt\", skiprows=1) # load data from the file skipping the one row\ndata = filearray.T # transpose the matrix with data\n[time_indx, ca_elem_indx, calcite_indx, ca_species_indx, hco3_indx, ph_indx] = numpy.arange(0, 6) # assign indices of the corresponding data\n\n# To visually analyze the obtained reaction path, we export\n# [bokeh](https://docs.bokeh.org/en/latest/docs/gallery.html#standalone-examples) python plotting package.\n\nfrom bokeh.plotting import figure, show\nfrom bokeh.io import output_notebook\noutput_notebook()\n\n# Below, we define a custom function that would generate figure of certain size (in this case, 600 by 300) with label\n# `time` on the x-axis:\n\ndef custom_figure(title, y_axis_label):\n return figure(plot_width=600, plot_height=300,\n title=title,\n x_axis_label='time',\n y_axis_label=y_axis_label)\n\n# The plots below depict different chemical properties (x-axis) with respect to the time interval of the kinetic\n# simulation (y-axis). We start from the behavior of the amount of element Ca with respect to time:\n\ntime = data[time_indx, :] # fetch time from the data matrix\nfig1 = custom_figure(title=\"Amount of Ca w.r.t. time\", y_axis_label='Amount of Ca [mmolal]')\nfig1.line(time, data[ca_elem_indx], line_width=4, color=\"coral\", legend_label=\"Ca\")\nshow(fig1)\n\n# The increase of the amount of Ca element is happening along the dissolution of calcite on the\n# plot below:\n\nfig2 = custom_figure(title=\"Mass of Calcite w.r.t. time\", y_axis_label='Mass [g]')\nfig2.line(time, data[calcite_indx], line_width=4, color=\"blue\", legend_label=\"Calcite\")\nshow(fig2)\n\n# As calcite dissolves, the molallities of species Ca2+ and HCO3- are growing too:\n\nfig3 = custom_figure(title=\"Species molality w.r.t. time\", y_axis_label='Molality [mmolal]')\nfig3.line(time, data[ca_species_indx], line_width=4, legend_label=\"Ca++\", color=\"orange\")\nfig3.line(time, data[hco3_indx], line_width=4, legend_label=\"HCO3-\", color=\"green\")\nshow(fig3)\n\n# Finally, the pH of the overall chemical system is increasing as well:\n\nfig4 = custom_figure(title=\"pH w.r.t. time\", y_axis_label='pH [-]')\nfig4.line(time, data[ph_indx], line_width=4, color=\"darkviolet\")\nshow(fig4)\n\n", "repo_name": "reaktoro/reaktoro-jupyter", "sub_path": "scripts/kin.calcite-hcl.py", "file_name": "kin.calcite-hcl.py", "file_ext": "py", "file_size_in_byte": 12173, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "25", "api": [{"api_name": "bokeh.io.output_notebook", "line_number": 187, "usage_type": "call"}, {"api_name": "bokeh.plotting.figure", "line_number": 193, "usage_type": "call"}, {"api_name": "bokeh.plotting.show", "line_number": 204, "usage_type": "call"}, {"api_name": "bokeh.plotting.show", "line_number": 211, "usage_type": "call"}, {"api_name": "bokeh.plotting.show", "line_number": 218, "usage_type": "call"}, {"api_name": "bokeh.plotting.show", "line_number": 224, "usage_type": "call"}]} +{"seq_id": "27994400118", "text": "import sys\nimport argparse\n\nfrom misc import clean_sequences, subsequences, k_mers, read_fasta_file\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"\"\"Construction of corpus\"\"\")\n parser.add_argument(\"--file\", help=\"Path of the file that contains gene sequences\")\n # parser.add_argument(\"--type\", help=\"Type of the genes, i.e positive or negative \")\n parser.add_argument(\"--subregion\", default=None, help=\"Starting and finishing positions of the selected subregion of a gene\")\n parser.add_argument(\"--k\", help=\"k value for k-mers\")\n parser.add_argument(\"--overlapping\", default='non-overlapping', choices=['overlapping', 'non-overlapping'], help=\"overlapping k-mers\")\n\n args = parser.parse_args()\n \n file = args.file\n # typegenes = args.type\n subregion = args.subregion\n\n start_point = 60\n end_point = 120\n\n if args.subregion != None:\n subregion = args.subregion.split(\",\")\n\n if len(subregion) < 2 or subregion[1] == '':\n sys.exit('The given arguments for the flag --subregion are incorrect')\n else:\n start_point = int(subregion[0])\n end_point = int(subregion[1])\n\n\n k = args.k\n k = int(k)\n\n overlapping = args.overlapping\n\n if file == None:\n sys.exit('Please give the path of the file that contains the genes sequences')\n\n # if typegenes == None:\n # sys.exit('Please specify the type of the file (positive or negative)')\n\n genes = read_fasta_file(file)\n\n subseqs, window_size = subsequences(genes, [start_point, end_point], overlapping, k)\n\n\n subseqs = clean_sequences(subseqs, window_size)\n\n file = 'corpus_text.txt'\n\n f = open(file,'w')\n\n for subseq in subseqs.T:\n\n kmers = k_mers(subseq, k, overlapping)\n\n for kmer in kmers:\n f.write(kmer)\n f.write(' ')\n\n f.write('\\n')\n\n f.close()\n\n\nif __name__ == '__main__':\n\tmain()", "repo_name": "qwenikos/tis2023", "sub_path": "program8/source_code/create_corpus.py", "file_name": "create_corpus.py", "file_ext": "py", "file_size_in_byte": 1918, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 8, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 28, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 40, "usage_type": "call"}, {"api_name": "misc.read_fasta_file", "line_number": 45, "usage_type": "call"}, {"api_name": "misc.subsequences", "line_number": 47, "usage_type": "call"}, {"api_name": "misc.clean_sequences", "line_number": 50, "usage_type": "call"}, {"api_name": "misc.k_mers", "line_number": 58, "usage_type": "call"}]} +{"seq_id": "8689354035", "text": "import numpy as np\nimport math\nimport os\nfrom typing import Tuple, List, Dict\nimport torch\nimport sys\n\nimport time\n\nimport torch.nn as nn\nimport torch.nn.init as init\n\n\ndef add_path(path):\n if path not in sys.path:\n print('Adding {}'.format(path))\n sys.path.append(path)\n\n\ndef torch_accuracy(output, target, topk=(1,)) -> List[torch.Tensor]:\n '''\n param output, target: should be torch Variable\n '''\n # assert isinstance(output, torch.cuda.Tensor), 'expecting Torch Tensor'\n # assert isinstance(target, torch.Tensor), 'expecting Torch Tensor'\n # print(type(output))\n\n topn = max(topk)\n batch_size = output.size(0)\n\n _, pred = output.topk(topn, 1, True, True)\n pred = pred.t()\n\n is_correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n ans = []\n for i in topk:\n is_correct_i = is_correct[:i].view(-1).float().sum(0, keepdim=True)\n ans.append(is_correct_i.mul_(100.0 / batch_size))\n\n return ans\n\n\ndef mkdir(path):\n if not os.path.exists(path):\n print('creating dir {}'.format(path))\n os.mkdir(path)\n else:\n print('{} already exists.'.format(path))\n\n\ndef pretty_print(*values, col_width=13):\n # col_width = 13\n\n def format_val(v):\n if not isinstance(v, str):\n v = np.array2string(v, precision=5, floatmode='fixed')\n return v.ljust(col_width)\n\n str_values = [format_val(v) for v in values]\n print(\" \".join(str_values))\n\n\nclass AvgMeter(object):\n '''\n Computing mean\n '''\n name = 'No name'\n\n def __init__(self, name='No name'):\n self.name = name\n self.reset()\n\n def reset(self):\n self.sum = 0\n self.mean = 0\n self.num = 0\n self.now = 0\n\n def update(self, mean_var, count=1):\n if math.isnan(mean_var):\n mean_var = 1e6\n print('Avgmeter getting Nan!')\n self.now = mean_var\n self.num += count\n\n self.sum += mean_var * count\n self.mean = float(self.sum) / self.num\n\n\ndef make_symlink(source, link_name):\n '''\n Note: overwriting enabled!\n '''\n if os.path.exists(link_name):\n print(\"Link name already exist! Removing '{}' and overwriting\".format(link_name))\n os.remove(link_name)\n if os.path.exists(source):\n os.symlink(source, link_name)\n return\n else:\n print('Source path not exists')\n\n\ndef to_onehot(inp, num_dim=10):\n # inp: (bs,) int\n # ret: (bs, num_dim) float\n # assert inp.dtype == torch.long\n\n batch_size = inp.shape[0]\n y_onehot = torch.FloatTensor(batch_size, num_dim).to(inp.device)\n y_onehot.zero_()\n y_onehot.scatter_(1, inp.reshape(batch_size, 1), 1)\n\n return y_onehot", "repo_name": "ahujak/IB-IRM", "sub_path": "AC-CMNIST/utils/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 2709, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 24, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sys.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 17, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 20, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.array2string", "line_number": 57, "usage_type": "call"}, {"api_name": "math.isnan", "line_number": 81, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 95, "usage_type": "call"}, {"api_name": "os.path", "line_number": 95, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 97, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 98, "usage_type": "call"}, {"api_name": "os.path", "line_number": 98, "usage_type": "attribute"}, {"api_name": "os.symlink", "line_number": 99, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 111, "usage_type": "call"}]} +{"seq_id": "4029421369", "text": "from rest_framework.routers import DefaultRouter\nfrom api.views import *\n\nrouter = DefaultRouter()\nrouter.register('users', UserViewSet, basename='users')\nrouter.register('artistes', ArtisteViewSet, basename='artistes')\nrouter.register('songs', SongViewSet, basename='songs')\nrouter.register('lyrics', LyricViewSet, basename='lyrics')\n\nurlpatterns = router.urls\n", "repo_name": "Mwebesatrevor/songcrud", "sub_path": "api/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 362, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "rest_framework.routers.DefaultRouter", "line_number": 4, "usage_type": "call"}]} +{"seq_id": "6103080452", "text": "# room\nimport pygame\nimport random\nimport blocks\nimport inputmanager\nimport display\nimport game\n\nclass AbstractRoom(object):\n\n def __init__(self, row, col, name):\n\n self.directions = {\n \"N\": [-1, 0],\n \"S\": [1, 0],\n \"E\": [0, 1],\n \"W\": [0, -1]\n }\n\n self.name = name\n\n self.location = [row, col]\n\n self.player = None\n self.room_cleared = True\n self.created_floorplan = False\n\n self.all_sprites = pygame.sprite.Group()\n self.portals = pygame.sprite.Group()\n\n self.room_no_row = 7\n self.room_no_col = 13\n\n # create floorplan\n self.floorplan = [0] * self.room_no_row\n for i in range(self.room_no_row):\n self.floorplan[i] = [0] * self.room_no_col\n\n # allot walls in floorplan\n for i in range(self.room_no_row):\n for j in range(self.room_no_col):\n if i == 0 or j == 0 or i == self.room_no_row - 1 or j == self.room_no_col - 1:\n self.floorplan[i][j] = 1\n\n self.room_width = 13 * 45\n self.room_height = 7 * 45\n\n self.cell_width = self.room_width / self.room_no_col\n self.cell_height = self.room_height / self.room_no_row\n\n\n def assign_portals_floorplan(self):\n # make floorplan\n\n # allot portals\n if isinstance(self.directions.get(\"N\"), blocks.Portal):\n self.floorplan[0][int(self.room_no_col / 2)] = \"N\"\n if isinstance(self.directions.get(\"S\"), blocks.Portal):\n self.floorplan[self.room_no_row - 1][int(self.room_no_col / 2)] = \"S\"\n if isinstance(self.directions.get(\"W\"), blocks.Portal):\n self.floorplan[int(self.room_no_row / 2)][0] = \"W\"\n if isinstance(self.directions.get(\"E\"), blocks.Portal):\n self.floorplan[int(self.room_no_row / 2)][self.room_no_col - 1] = \"E\"\n\n\n # def print_floorplan(self):\n # for i in range(self.room_no_row):\n # print()\n # for j in range(self.room_no_col):\n # print(str(self.floorplan[i][j]), end=\" \")\n #\n # print()\n # print()\n # print()\n\n\n def create_floorplan(self):\n self.create_walls_and_portals()\n self.assign_room_specific_elements()\n self.create_room_specific_elements()\n\n\n def create_walls_and_portals(self):\n # actually create floorplan elements\n\n self.created_floorplan = True\n\n for i in range(self.room_no_row):\n for j in range(self.room_no_col):\n cell = self.floorplan[i][j]\n if cell == 1:\n wall = blocks.Wall(j * self.cell_width, i * self.cell_height)\n self.all_sprites.add(wall)\n if cell == \"N\" or cell == \"S\" or cell == \"W\" or cell == \"E\":\n portal = self.directions.get(cell)\n portal.set_portal(j * self.cell_width, i * self.cell_height)\n self.all_sprites.add(portal)\n self.portals.add(portal)\n\n def assign_room_specific_elements(self):\n pass\n\n def create_room_specific_elements(self):\n pass\n\n\n def start(self):\n if not self.created_floorplan:\n self.create_floorplan() # TODO\n self.player = blocks.Player()\n self.player.rect.x = 100\n self.player.rect.y = 100\n self.all_sprites.add(self.player)\n self.play()\n\n def play(self):\n inputmanager.InputManager.handle_events()\n self.room_logic()\n display.Display.render(self.all_sprites)\n\n # open doors and initialize new avalible rooms\n # game.goto other room\n\n\n def room_logic(self):\n pass\n\n def space_action(self):\n pass\n\n\n @classmethod\n def turn(cls, character, list, do_kill = False):\n\n character.set_dx()\n character.move_x()\n\n hit_list = pygame.sprite.spritecollide(character, list, do_kill)\n\n character.action_lr(hit_list)\n\n character.set_dy()\n character.move_y()\n\n hit_list = pygame.sprite.spritecollide(character, list, do_kill)\n\n character.action_tb(hit_list)\n\n\nclass MonsterRoom(AbstractRoom):\n \"\"\"\n Manages logic of this specific room\n \"\"\"\n\n def __init__(self, row, col, name):\n\n super().__init__(row, col, name)\n\n self.bullets = pygame.sprite.Group()\n\n self.monsters = pygame.sprite.Group()\n self.num_monsters = random.randint(3, 7)\n self.num_crates = random.randint(5, 20)\n self.num_tiles = random.randint(5, 20)\n\n self.room_cleared = False\n\n def space_action(self):\n dir_x, dir_y = pygame.mouse.get_pos()\n self.new_player_attack(dir_x, dir_y)\n\n def new_player_attack(self, aim_x, aim_y):\n bullet = blocks.Bullet(self.player, aim_x, aim_y)\n self.all_sprites.add(bullet)\n self.bullets.add(bullet)\n\n def new_monster_attack(self, monster):\n bullet = blocks.Bullet(monster, self.player.rect.x, self.player.rect.y)\n self.all_sprites.add(bullet)\n self.bullets.add(bullet)\n\n def assign_room_specific_elements(self):\n\n # deactivate portals\n for portal in self.portals:\n portal.is_active = False\n\n # create crates\n for i in range(self.num_crates):\n successful = False\n while not successful:\n coor_x = random.randint(0, self.room_no_row - 1)\n coor_y = random.randint(0, self.room_no_col - 1)\n if self.floorplan[coor_x][coor_y] == 0:\n self.floorplan[coor_x][coor_y] = 3\n crate = blocks.Crate(coor_y * self.cell_width, coor_x * self.cell_height)\n self.all_sprites.add(crate)\n successful = True\n\n # create tiles\n for i in range(self.num_tiles):\n successful = False\n while not successful:\n coor_x = random.randint(0, self.room_no_row - 1)\n coor_y = random.randint(0, self.room_no_col - 1)\n if self.floorplan[coor_x][coor_y] == 0:\n self.floorplan[coor_x][coor_y] = 4\n tile = blocks.Tile(coor_y * self.cell_width, coor_x * self.cell_height)\n self.all_sprites.add(tile)\n successful = True\n\n # create monsters\n for i in range(self.num_monsters):\n successful = False\n while not successful:\n coor_x = random.randint(0, self.room_no_row - 1)\n coor_y = random.randint(0, self.room_no_col - 1)\n if self.floorplan[coor_x][coor_y] == 0:\n self.floorplan[coor_x][coor_y] = 5\n monster = blocks.Monster(coor_y * self.cell_width, coor_x * self.cell_height)\n self.all_sprites.add(monster)\n self.monsters.add(monster)\n successful = True\n\n for i in range(self.room_no_row):\n print()\n for j in range(self.room_no_col):\n print(self.floorplan[i][j], end=\"\")\n\n print()\n print()\n print()\n\n\n\n def room_logic(self):\n\n self.turn(self.player, self.all_sprites)\n\n if len(self.monsters) == 0:\n self.room_cleared = True\n for portal in self.portals:\n portal.is_active = True\n\n else:\n for monster in self.monsters:\n self.turn(monster, self.all_sprites)\n monster.current_count += 1\n if monster.current_count % monster.attack_counter == 0:\n self.new_monster_attack(monster)\n\n for bullet in self.bullets:\n self.turn(bullet, self.all_sprites)\n #\n # print(self.player.hp)\n #\n # if self.player.hp <= 0:\n # game.Game.end_game()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass EndRoom(AbstractRoom):\n \"\"\"\n Manages logic of this specific room\n \"\"\"\n\n def __init__(self, row, col):\n super().__init__(row, col, \"E\")\n\n\n def room_logic(self):\n self.turn(self.player, self.all_sprites)\n\n\nclass HomeRoom(AbstractRoom):\n \"\"\"\n Manages logic of this specific room\n \"\"\"\n\n def __init__(self, row, col):\n super().__init__(row, col, \"H\")\n\n\n def room_logic(self):\n self.turn(self.player, self.all_sprites)", "repo_name": "GatiAher/dungeoncrawler", "sub_path": "rooms.py", "file_name": "rooms.py", "file_ext": "py", "file_size_in_byte": 8387, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pygame.sprite.Group", "line_number": 28, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 28, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Group", "line_number": 29, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 29, "usage_type": "attribute"}, {"api_name": "blocks.Portal", "line_number": 56, "usage_type": "attribute"}, {"api_name": "blocks.Portal", "line_number": 58, "usage_type": "attribute"}, {"api_name": "blocks.Portal", "line_number": 60, "usage_type": "attribute"}, {"api_name": "blocks.Portal", "line_number": 62, "usage_type": "attribute"}, {"api_name": "blocks.Wall", "line_number": 92, "usage_type": "call"}, {"api_name": "blocks.Player", "line_number": 110, "usage_type": "call"}, {"api_name": "inputmanager.InputManager.handle_events", "line_number": 117, "usage_type": "call"}, {"api_name": "inputmanager.InputManager", "line_number": 117, "usage_type": "attribute"}, {"api_name": "display.Display.render", "line_number": 119, "usage_type": "call"}, {"api_name": "display.Display", "line_number": 119, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollide", "line_number": 138, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 138, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollide", "line_number": 145, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 145, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Group", "line_number": 159, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 159, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Group", "line_number": 161, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 161, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 162, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 163, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 164, "usage_type": "call"}, {"api_name": "pygame.mouse.get_pos", "line_number": 169, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 169, "usage_type": "attribute"}, {"api_name": "blocks.Bullet", "line_number": 173, "usage_type": "call"}, {"api_name": "blocks.Bullet", "line_number": 178, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 192, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 193, "usage_type": "call"}, {"api_name": "blocks.Crate", "line_number": 196, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 204, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 205, "usage_type": "call"}, {"api_name": "blocks.Tile", "line_number": 208, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 216, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 217, "usage_type": "call"}, {"api_name": "blocks.Monster", "line_number": 220, "usage_type": "call"}]} +{"seq_id": "6204009333", "text": "from cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import serialization\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.hazmat.primitives.asymmetric import padding\nfrom cryptography.hazmat.primitives import hashes\nfrom pydrive.auth import GoogleAuth\nimport quickstart\nimport hashlib\n\ndef authenticate():\n gauth = GoogleAuth()\n gauth.LocalWebserverAuth()\n drive = GoogleDrive(gauth)\n\n file1 = drive.CreateFile({'title': 'Hello.txt'}) # Create GoogleDriveFile instance with title 'Hello.txt'.\n file1.SetContentString('Hello World!') # Set content of the file from given string.\n file1.Upload()\n\n\ndef store_privKey(private_key):\n pem = private_key.private_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PrivateFormat.PKCS8,\n encryption_algorithm=serialization.NoEncryption()\n )\n with open('private_key.pem', 'wb+') as f:\n f.write(pem)\n\ndef store_pubKey(public_key):\n pem = public_key.public_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PublicFormat.SubjectPublicKeyInfo\n)\n pem1 = pem.decode()\n return pem1\n\n\ndef readKey():\n with open(\"public_keys.txt\") as f: #in read mode, not in write mode, careful\n rd=f.readlines()\n return rd\n\ndef keyToBytes(public_key):\n pem = public_key.public_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PublicFormat.SubjectPublicKeyInfo\n)\n return pem\n\ndef genRSAKey():\n private_key = rsa.generate_private_key(\n public_exponent = 65537,\n key_size = 2048,\n backend= default_backend()\n )\n return private_key\n\ndef encryptRSA(byteKey, public_key):\n #Encrypt RSA\n encryptedKey = public_key.encrypt(\n byteKey,\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return encryptedKey\n#decrypt RSA\ndef decryptRSA(encryptedAESKey, private_key):\n original_message = private_key.decrypt(\n encryptedAESKey,\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return original_message\n\ndef findKey(file, identifier):\n y = 0\n count = len(file)\n start = 400\n pkLength = 434\n while (y != count):\n pKey = file[y]\n toCompare = ''\n for x in range (start, pkLength):\n toCompare += pKey[x]\n y = y + 1\n start = start + 464\n pkLength = pkLength + 464\ndef AESKey():\n iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))\n key = hashlib.sha256(iv).digest()\n return key\n \ndef encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):\n \"\"\" Encrypts a file using AES (CBC mode) with the\n given key.\n\n key:\n The encryption key - a string that must be\n either 16, 24 or 32 bytes long. Longer keys\n are more secure.\n\n in_filename:\n Name of the input file\n\n out_filename:\n If None, '.enc' will be used.\n\n chunksize:\n Sets the size of the chunk which the function\n uses to read and encrypt the file. Larger chunk\n sizes can be faster for some files and machines.\n chunksize must be divisible by 16.\n \"\"\"\n if not out_filename:\n out_filename = in_filename + '.enc'\n\n iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))\n encryptor = AES.new(key, AES.MODE_CBC, iv)\n filesize = os.path.getsize(in_filename)\n\n with open(in_filename, 'rb') as infile:\n with open(out_filename, 'wb') as outfile:\n outfile.write(struct.pack(' list:\n selected_rows = self.get_selected_rows(get_cells=False, get_cells_as_rows=True)\n for row in selected_rows:\n pattern_name = self.get_cell_data(row, 0)\n if pattern_name not in pattern_filter_list:\n pattern_filter_list.append(pattern_name)\n return pattern_filter_list\n \n def enable_filter_in_menue(self, filter_type: str, func: callable):\n self.popup_menu_add_command(filter_type, func, index_menu = False, header_menu = False)\n\n def delete_pattern(self, filter_list: list) -> list:\n selected_rows = self.get_selected_rows(get_cells=False, get_cells_as_rows=True)\n selected_rows_data = [self.get_row_data(row, return_copy = True) for row in selected_rows]\n \n for row_with_data in selected_rows_data:\n table_total_rows = self.get_total_rows()\n for row in range(0,table_total_rows):\n if row_with_data == self.get_row_data(row, return_copy=True):\n self.delete_row(row, deselect_all = True)\n break\n \n for list in filter_list:\n for pattern in list:\n if row_with_data[0] == pattern:\n list.remove(row_with_data[0])\n\n return filter_list\n \n def update_design(self, main_color: str, second_color: str, third_color: str, text_color:str):\n self.set_options(table_bg=main_color, \n top_left_bg=main_color,\n frame_bg=main_color, \n popup_menu_bg=main_color, \n header_bg=third_color, \n index_bg=third_color,\n table_fg=text_color,\n header_fg=second_color,\n popup_menu_highlight_bg=second_color,\n table_selected_cells_border_fg=second_color,\n table_selected_rows_border_fg=second_color,\n table_selected_columns_border_fg=second_color)\n \nclass CustomMessagebox(customtkinter.CTkToplevel):\n def __init__(self, title: str=\"\", label: str=\"\", text: str=\"\", geometry: str=\"400x500\", *args: any, **kwargs: any):\n super().__init__(*args, **kwargs)\n self.wm_iconbitmap(app_icon)\n\n self.title(title)\n self.geometry(geometry)\n self.grid_columnconfigure((0), weight=1)\n self.grid_rowconfigure((0,1), weight=2)\n self.resizable(False,False)\n message_text_row=0\n if len(label) > 0:\n message_label = customtkinter.CTkLabel(self, \n text=label, \n font=small_font)\n message_label.grid(row=0, column=0, padx=50, pady=(20,10),sticky=\"nsew\")\n message_text_row=1\n if text:\n message_text = customtkinter.CTkTextbox(self,\n font=small_font)\n message_text.grid(row=message_text_row, column=0, padx=10, pady=(0,10), sticky=\"nsew\")\n message_text.insert(\"0.0\", text)\n message_text.configure(state=\"disabled\")\n ok_button = customtkinter.CTkButton(self, \n text=\"OK\", \n command=self.destroy, \n width=40, \n font=medium_font)\n ok_button.grid(row=message_text_row+1, column=0, padx=10, pady=(0,10), sticky=\"s\")\n \n self.attributes(\"-topmost\", True)\n\nclass RegexHelpMessagebox(customtkinter.CTkToplevel):\n def __init__(self, mode: str=\"\", theme: str=\"\", first_color: str=\"\", second_color: str=\"\", third_color: str=\"\", text_color:str=\"\", geometry: str=\"\", *args: any, **kwargs: any):\n super().__init__(*args, **kwargs)\n self.wm_iconbitmap(app_icon)\n self.title(regex_help_window_title)\n self.geometry(\"%dx%d\" % (regex_window_width, regex_window_height))\n self.grid_columnconfigure((0), weight=1)\n self.grid_rowconfigure((0,1), weight=2)\n self.resizable(False,False)\n self.regex_help_sheet = CustomSheet(self,\n height=420,\n theme=mode+\" \"+theme,\n show_x_scrollbar = True,\n show_y_scrollbar = False,\n empty_horizontal = False,\n empty_vertical = False,\n show_top_left = False,\n show_row_index = True,\n auto_resize_default_row_index=True,\n headers=regex_help_headers,\n data=regex_help_data)\n self.regex_help_sheet.grid(row = 0, column = 0, columnspan=2, sticky = \"nswe\")\n self.regex_help_sheet.column_width(column=0, width=115) \n self.regex_help_sheet.column_width(column=1, width=70) \n self.regex_help_sheet.column_width(column=2, width=850) \n self.regex_help_sheet.enable_bindings(\"double_click_column_resize\")\n\n ok_button = customtkinter.CTkButton(self, \n text=\"OK\", \n command=self.destroy, \n width=80, \n font=medium_font)\n ok_button.grid(row=1, column=0, padx=10, pady=(0,10), sticky=\"s\")\n self.attributes(\"-topmost\", True)\n self.regex_help_sheet.update_design(first_color,\n second_color, \n third_color,\n text_color)\n \nclass CustomTextBox(customtkinter.CTkTextbox):\n def __init__(self, *args: any, **kwargs: any):\n super().__init__(*args, **kwargs)\n self.tag_config(\"match\", foreground=highlight_fg_color, background=\"\")\n\n def highlight(self, tag: str, start: str, end: str):\n self.tag_add(tag, start, end)\n\n def highlight_all(self, pattern: str, tag: str):\n for match in self.search_re(pattern):\n self.highlight(tag, match[0], match[1])\n\n def clean_highlights(self, tag: str):\n self.tag_remove(tag, \"1.0\", \"end\")\n\n def search_re(self, pattern: str) -> list:\n matches = []\n text = self.get(\"1.0\", customtkinter.END).splitlines()\n for i, line in enumerate(text):\n for match in re.finditer(pattern, line):\n matches.append((f\"{i + 1}.{match.start()}\", f\"{i + 1}.{match.end()}\"))\n return matches\n\n def highlight_pattern(self, pattern: str, tag: str=\"match\"):\n self.clean_highlights(tag)\n if valid_regex(pattern):\n self.highlight_all(pattern, tag)\n", "repo_name": "H4NM/Groppy", "sub_path": "custom_widgets.py", "file_name": "custom_widgets.py", "file_ext": "py", "file_size_in_byte": 7866, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "25", "api": [{"api_name": "customtkinter.CTkTabview", "line_number": 6, "usage_type": "attribute"}, {"api_name": "tksheet.Sheet", "line_number": 12, "usage_type": "name"}, {"api_name": "customtkinter.CTkToplevel", "line_number": 72, "usage_type": "attribute"}, {"api_name": "customtkinter.CTkLabel", "line_number": 84, "usage_type": "call"}, {"api_name": "customtkinter.CTkTextbox", "line_number": 90, "usage_type": "call"}, {"api_name": "customtkinter.CTkButton", "line_number": 95, "usage_type": "call"}, {"api_name": "customtkinter.CTkToplevel", "line_number": 104, "usage_type": "attribute"}, {"api_name": "customtkinter.CTkButton", "line_number": 131, "usage_type": "call"}, {"api_name": "customtkinter.CTkTextbox", "line_number": 143, "usage_type": "attribute"}, {"api_name": "customtkinter.END", "line_number": 160, "usage_type": "attribute"}, {"api_name": "re.finditer", "line_number": 162, "usage_type": "call"}, {"api_name": "other_funcs.valid_regex", "line_number": 168, "usage_type": "call"}]} +{"seq_id": "22594932506", "text": "from selenium import webdriver\nimport random\n\nwhile True:\n\n\tdriver = webdriver.Firefox()\n\tdriver.get('http://www.porngifs.xyz/')\n\n\telements = driver.find_elements_by_tag_name('iframe')\n\n\tfor element in elements:\n\t\tif \"jads\" in element.get_attribute(\"src\"):\n\t\t\telement.click()\n\n\thandle=driver.window_handles\n\t\n\tfor tab in driver.window_handles:\n\t\tdriver.switch_to.window(tab)\n\t\tdriver.close()\n\t\n\t", "repo_name": "erichadley8/selenium-random", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 395, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "selenium.webdriver.Firefox", "line_number": 6, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 6, "usage_type": "name"}]} +{"seq_id": "73823682302", "text": "from django.urls import path\nfrom . import views\n\napp_name = \"events\"\n\nurlpatterns = [\n path(\"\", views.index, name = \"home\"),\n path(\"createevent/\", views.createEvent, name = \"createEvent\"),\n path(\"update//\", views.updateEvent, name = \"updateDelete\"),\n path(\"delete//\", views.deleteEvent, name = \"deleteEvent\"),\n\n]", "repo_name": "clifford-silindana/GSR-website", "sub_path": "root/events/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 353, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}]} +{"seq_id": "8374417068", "text": "import os\nimport sys\nfrom sqlalchemy import Column, ForeignKey, Integer, String, DateTime\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy import create_engine\nfrom eralchemy import render_er\nfrom datetime import datetime\n\nBase = declarative_base()\n\nclass User(Base):\n __tablename__='users'\n id = Column(Integer, primary_key=True)\n username=Column(String(20), nullable=False, unique=True)\n firstname=Column(String(20), nullable=False)\n lastname=Column(String(20), nullable=False)\n email=Column(String(50), nullable=False, unique=True)\n password=Column(String(10), nullable=False)\n created_at=Column(DateTime(), default=datetime.now())\n follower=relationship('Follower',backref='User')\n post=relationship('Post',backref='User')\n comment=relationship('Comment',backref='User')\n \nclass Follower(Base):\n __tablename__='followers'\n id = Column(Integer, primary_key=True)\n user_from_id=Column(Integer, ForeignKey('users.id'), nullable=False)\n user_to_id=Column(Integer, ForeignKey('users.id'), nullable=False)\n\nclass Post(Base):\n __tablename__ = 'posts'\n id = Column(Integer, primary_key=True)\n user_id= Column(Integer, ForeignKey('users.id'), nullable=False)\n media=relationship('Media',backref='Post', uselist=False)\n comment=relationship('Comment',backref='Post', uselist=False)\n\nclass Media(Base):\n __tablename__ = 'media'\n id = Column(Integer, primary_key=True)\n type=Column(String(50), nullable=False)\n url=Column(String(50), nullable=False)\n post_id= Column(Integer, ForeignKey('posts.id'), nullable=False)\n \nclass Comment(Base):\n __tablename__ = 'comment'\n id = Column(Integer, primary_key=True)\n comment_text=Column(String(120), nullable=False)\n author_id=Column(Integer, ForeignKey('users.id'), nullable=False)\n post_id=Column(Integer, ForeignKey('posts.id'), nullable=False)\n\n\n## Draw from SQLAlchemy base\nrender_er(Base, 'diagram.png')", "repo_name": "Covaar/Instagram_Database_Model", "sub_path": "src/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 2000, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sqlalchemy.ext.declarative.declarative_base", "line_number": 10, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 14, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 14, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 15, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 15, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 16, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 16, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 17, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 17, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 18, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 18, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 19, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 19, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 20, "usage_type": "call"}, {"api_name": "sqlalchemy.DateTime", "line_number": 20, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 20, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 20, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.relationship", "line_number": 21, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.relationship", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.relationship", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 27, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 27, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 28, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 28, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 28, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 29, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 29, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 29, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 33, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 33, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 34, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 34, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 34, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.relationship", "line_number": 35, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.relationship", "line_number": 36, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 40, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 40, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 41, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 41, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 42, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 42, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 43, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 43, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 43, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 47, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 47, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 48, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 48, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 49, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 49, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 49, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 50, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 50, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 50, "usage_type": "call"}, {"api_name": "eralchemy.render_er", "line_number": 54, "usage_type": "call"}]} +{"seq_id": "35936813237", "text": "import xarray as xr\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\nclass VisualStimData:\n \"\"\"\n Data and methods for the visual stimulus ePhys experiment.\n The data table itself is held in self.data, an `xarray` object.\n Inputs:\n data: xr.DataArray or xr.Dataset\n Methods:\n ...\n \"\"\"\n def __init__(self, data: xr.Dataset, ):\n assert isinstance(data, xr.Dataset)\n self.data = data\n\n\n def plot_electrode(self, rep_number: int, rat_id: int, elec_number: tuple=(0,)):\n \"\"\"\n Plots the voltage of the electrodes in \"elec_number\" for the rat \"rat_id\" in the repetition\n \"rep_number\". Shows a single figure with two subplots, for male and female rats.\n \"\"\"\n fig, axes = plt.subplots(len(elec_number), 1)\n axes = np.array([axes]) if isinstance(axes, plt.Axes) else axes\n time = self.data['time']\n for ax, elec in zip(axes, elec_number):\n to_plot = self.data.sel(rep=rep_number, rat_id=rat_id, elec=elec)['volt'].values\n ax.plot(time, to_plot)\n ax.set_xlabel('Time [s]')\n ax.set_ylabel('Voltage [V]')\n ax.set_title(f'Electrode {elec}')\n\n fig.tight_layout()\n\n def experimenter_bias(self):\n \"\"\" Shows the statistics of the average recording across all experimenters \"\"\"\n names = np.unique(self.data.coords['exp_name'].values)\n means = []\n stds = []\n medians = []\n for experimenter in names:\n data = self.data.sel(exp_name=experimenter)['volt'].values\n means.append(np.abs(data.mean()))\n stds.append(np.abs(data.std()))\n medians.append(np.abs(np.median(data)))\n\n # Plotting\n fig, ax = plt.subplots()\n x_locs = np.arange(len(names))\n width = 0.3\n rect0 = ax.bar(x_locs, means, width, color='C0')\n rect1 = ax.bar(x_locs + width, stds, width, color='C1')\n rect2 = ax.bar(x_locs - width, medians, width, color='C2')\n\n ax.set_xticks(x_locs)\n ax.set_xticklabels(names)\n ax.legend((rect0[0], rect1[0], rect2[0]), ('Mean', 'STD', 'Median'))\n ax.set_title('Experimenter Bias (absolute values)')\n ax.set_ylabel('Volts [V]')\n\ndef mock_stim_data() -> VisualStimData:\n \"\"\" Creates a new VisualStimData instance with mock data \"\"\"\n num_of_animals = 20\n num_of_reps = 4\n reps = np.arange(num_of_reps, dtype=np.uint8)\n total_num_of_exp = num_of_animals * num_of_reps\n exp_number = np.arange(total_num_of_exp, dtype=np.uint32)\n \n rat_id_ints, rat_id = _generate_rat_data(num_of_animals)\n room_temp, room_humid = _generate_temp_hum_values(total_num_of_exp)\n experimenters = _generate_experimenter_names(num_of_animals, num_of_reps)\n rat_sex = _generate_rat_gender(num_of_animals, num_of_reps)\n stim, electrode_array, time, volt = _generate_voltage_stim(num_of_animals, num_of_reps)\n\n # Construct the Dataset - this could be done with a pd.MultiIndex as well\n ds = xr.Dataset({'temp': (['num'], room_temp),\n 'humid': (['num'], room_humid),\n 'volt': (['elec', 'time', 'rat_id', 'rep'], volt),\n 'stim': (['time'], stim)},\n coords={'elec': electrode_array,\n 'time': time,\n 'rat_id': rat_id,\n 'rep': reps,\n 'exp_name': experimenters,\n 'sex': rat_sex,\n 'num': exp_number,\n })\n\n ds.attrs['exp_date'] = pd.to_datetime('today')\n ds.attrs['rat_strain'] = 'Sprague Dawley'\n\n return VisualStimData(ds)\n \ndef _generate_rat_data(num_of_animals):\n rat_id_ints = np.random.choice(np.arange(100, 900), size=300, replace=False)\n rat_id = np.random.choice(rat_id_ints, size=num_of_animals, replace=False)\n return rat_id_ints, rat_id\n\n\ndef _generate_temp_hum_values(total_num_of_exp):\n room_temp = np.random.random(total_num_of_exp) * 3 + 23 # between 23 and 26 C\n room_humid = np.random.randint(30, 70, size=total_num_of_exp)\n return room_temp, room_humid\n\ndef _generate_experimenter_names(num_of_animals, num_of_reps):\n names = ['Dana', 'Motti', 'Sam', 'Daria']\n experimenters = np.random.choice(names, size=num_of_animals, replace=True)\n experimenters = np.tile(experimenters, num_of_reps)\n return experimenters\n\ndef _generate_rat_gender(num_of_animals, num_of_reps):\n sex = ['F', 'M']\n rat_sex = np.random.choice(sex, size=num_of_animals, replace=True)\n rat_sex = np.tile(rat_sex, num_of_reps)\n return rat_sex\n\n\ndef _generate_voltage_stim(num_of_animals, num_of_reps):\n pre_stim = 1 # seconds\n stim_time = 0.1 # seconds\n post_stim = 0.9 # seconds\n sampling_rate = 5000 # Hz\n freq = 1 / sampling_rate\n experiment_length = int(pre_stim + stim_time + post_stim)\n electrodes = 10\n samples = sampling_rate * experiment_length\n\n # Random voltage values from N(0.068, 0.0004)\n volt = 0.02 * np.random.randn(electrodes, samples, num_of_animals,\n num_of_reps).astype(np.float32) - 0.068 # in volts, not millivolts\n volt[volt > -0.02] = 0.04 # \"spikes\"\n time = pd.date_range(start=pd.to_datetime('today'), periods=experiment_length * sampling_rate,\n freq=f'{freq}S')\n electrode_array = np.arange(electrodes, dtype=np.uint16)\n\n # Stim index - -1 is pre, 0 is stim, 1 is post\n stim = np.zeros(int(samples), dtype=np.int8)\n stim[:int(pre_stim*sampling_rate)] = -1\n stim[int((pre_stim + stim_time)*sampling_rate):] += 1\n return stim, electrode_array, time, volt\n\n\n# Run the solution\nstim_data = mock_stim_data()\nids = stim_data.data['rat_id']\narr = stim_data.plot_electrode(rep_number=2, rat_id=ids[0], elec_number=(1, 6))\nstim_data.experimenter_bias()", "repo_name": "guywine/Python_course", "sub_path": "Exercises/08_xarray_ex.py", "file_name": "08_xarray_ex.py", "file_ext": "py", "file_size_in_byte": 5940, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "xarray.Dataset", "line_number": 16, "usage_type": "attribute"}, {"api_name": "xarray.Dataset", "line_number": 17, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.Axes", "line_number": 27, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.median", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 68, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.uint32", "line_number": 70, "usage_type": "attribute"}, {"api_name": "xarray.Dataset", "line_number": 79, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 98, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 99, "usage_type": "attribute"}, {"api_name": "numpy.random.random", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 104, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 105, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 110, "usage_type": "attribute"}, {"api_name": "numpy.tile", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 116, "usage_type": "attribute"}, {"api_name": "numpy.tile", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 132, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 133, "usage_type": "attribute"}, {"api_name": "pandas.date_range", "line_number": 135, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.uint16", "line_number": 137, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 140, "usage_type": "call"}, {"api_name": "numpy.int8", "line_number": 140, "usage_type": "attribute"}]} +{"seq_id": "3183575034", "text": "import tabulate\n\nimport technic.solder.cli.command\n\nclass ModCommand(technic.solder.cli.command.Command):\n\tname = 'mod'\n\tcommand_help = 'Get information about mods'\n\n\tdef setup(self, parser):\n\t\tsubparsers = parser.add_subparsers()\n\n\t\tself.add_subcommand(subparsers, ListModsCommand())\n\t\tself.add_subcommand(subparsers, GetModCommand())\n\n\tdef run(self, client, arguments):\n\t\tpass # This is a wrapper command so it will never actually be called\n\n\tdef skip_handling(self):\n\t\treturn True\n\nclass ListModsCommand(technic.solder.cli.command.Command):\n\tname = 'list'\n\tcommand_help = 'List all available mods'\n\n\tdef setup(self, parser):\n\t\tpass\n\n\tdef run(self, client, arguments):\n\t\tself.output(\n\t\t\t'',\n\t\t\ttabulate.tabulate(\n\t\t\t\t[\n\t\t\t\t\t[slug, name]\n\t\t\t\t\tfor slug, name in client.mods.iteritems()\n\t\t\t\t],\n\t\t\t\theaders = ['Slug', 'Name'],\n\t\t\t)\n\t\t)\n\nclass GetModCommand(technic.solder.cli.command.Command):\n\tname = 'get'\n\tcommand_help = 'Get information about a specific mod'\n\n\tdef setup(self, parser):\n\t\tparser.add_argument(\n\t\t\t'mod_slug',\n\t\t\ttype = str,\n\t\t\thelp = 'The mod slug',\n\t\t)\n\n\tdef run(self, client, arguments):\n\t\tmod = client.get_mod_info(arguments.mod_slug)\n\n\t\tself.success(mod['pretty_name'])\n\n\t\tself.output(\n\t\t\t'',\n\t\t\ttabulate.tabulate(\n\t\t\t\t[\n\t\t\t\t\t['Slug', mod['name']],\n\t\t\t\t\t['Author', mod['author']],\n\t\t\t\t\t['Description', mod['description']],\n\t\t\t\t\t['Website', mod['link']],\n\t\t\t\t\t['Donate URL', mod['donate']],\n\t\t\t\t\t['Versions', ', '.join(mod['versions'][:10])],\n\t\t\t\t]\n\t\t\t)\n\t\t)\n\n", "repo_name": "cadyyan/technic-solder-client", "sub_path": "technic/solder/cli/commands/mods.py", "file_name": "mods.py", "file_ext": "py", "file_size_in_byte": 1523, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "technic.solder.cli.command.solder", "line_number": 5, "usage_type": "attribute"}, {"api_name": "technic.solder.cli.command", "line_number": 5, "usage_type": "name"}, {"api_name": "technic.solder.cli.command.solder", "line_number": 21, "usage_type": "attribute"}, {"api_name": "technic.solder.cli.command", "line_number": 21, "usage_type": "name"}, {"api_name": "tabulate.tabulate", "line_number": 31, "usage_type": "call"}, {"api_name": "technic.solder.cli.command.solder", "line_number": 40, "usage_type": "attribute"}, {"api_name": "technic.solder.cli.command", "line_number": 40, "usage_type": "name"}, {"api_name": "tabulate.tabulate", "line_number": 58, "usage_type": "call"}]} +{"seq_id": "43266815755", "text": "import os\nimport sys\nimport re\nimport pprint\nimport json, copy\nimport pandas as pd\n\ndef update_excel_pd(xls_path, statlist: dict, *, crop_codes=[1]):\n \"\"\"\n pandas version of excel update\n \"\"\"\n \n # =============================================\n d = pd.read_excel(xls_path, sheetname=0)\n\n d1 = pd.DataFrame(statlist)\n d1 = d1.T\n \n d[\"OBJECTID_1\"] = pd.to_numeric(d[\"OBJECTID_1\"], errors=\"coerce\")\n d1[\"OBJECTID_1\"] = pd.to_numeric(d1[\"OBJECTID_1\"], errors=\"coerce\")\n d2 = pd.merge(d, d1, on=\"OBJECTID_1\", how='left')\n d.head()\n\n out_path = xls_path.replace(\".xls\", \".stat0627.xls\")\n writer = pd.ExcelWriter(out_path)\n d2.to_excel(writer, \"Sheet1\")\n writer.save()\n\nif __name__ == \"__main__\":\n json_path = '/home/tq/data2/citrus/tree_age/samples-0625/adm-40w.bm.1-2465.all_ly.ndvi-bp.tree_age_summary.json'\n with open(json_path) as ff: # load the json file\n result = json.load(ff)\n for k, v in result.items():\n result[k]['OBJECTID_1'] = int(k)\n update_excel_pd('/home/tq/data_pool/diva-gis/全国乡镇边界/test/attribute-xls/hunan.xls', result)\n print('fin')\n", "repo_name": "yilu2019sys/test", "sub_path": "json2csv.py", "file_name": "json2csv.py", "file_ext": "py", "file_size_in_byte": 1136, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pandas.read_excel", "line_number": 14, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 16, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 19, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 20, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 21, "usage_type": "call"}, {"api_name": "pandas.ExcelWriter", "line_number": 25, "usage_type": "call"}, {"api_name": "json.load", "line_number": 32, "usage_type": "call"}]} +{"seq_id": "12377739442", "text": "from guider.tasks import crawl\nfrom tuangou.guider.models import Website, City, ReDeal\nfrom django.core.management.base import NoArgsCommand\n\nDISTRICT_SITE = ['manzuo', 'ftuan', 'wowotuan', 'didatuan', 'haotehui', 'lashouwang']\nclass Command(NoArgsCommand):\n def handle_noargs(self, **options):\n try:\n publisher = crawl.get_publisher()\n fields = ('pk', 'deal_url')\n for city in City.actives.all():\n if city.districts.values_list('pk').filter(level=0, is_active=True):\n for name in DISTRICT_SITE:\n site = Website.objects.get(slug=name)\n deals = ReDeal.news.values_list(*fields).filter(website=site, division=city)\n for pk, url in deals:\n crawl.apply_async(args=(name, pk, city.slug, url), publisher=publisher)\n finally:\n publisher.close()\n publisher.connection.close()\n", "repo_name": "pymmrd/tuangou", "sub_path": "guider/management/commands/spider_dist.py", "file_name": "spider_dist.py", "file_ext": "py", "file_size_in_byte": 970, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.core.management.base.NoArgsCommand", "line_number": 6, "usage_type": "name"}, {"api_name": "guider.tasks.crawl.get_publisher", "line_number": 9, "usage_type": "call"}, {"api_name": "guider.tasks.crawl", "line_number": 9, "usage_type": "name"}, {"api_name": "tuangou.guider.models.City.actives.all", "line_number": 11, "usage_type": "call"}, {"api_name": "tuangou.guider.models.City.actives", "line_number": 11, "usage_type": "attribute"}, {"api_name": "tuangou.guider.models.City", "line_number": 11, "usage_type": "name"}, {"api_name": "tuangou.guider.models.Website.objects.get", "line_number": 14, "usage_type": "call"}, {"api_name": "tuangou.guider.models.Website.objects", "line_number": 14, "usage_type": "attribute"}, {"api_name": "tuangou.guider.models.Website", "line_number": 14, "usage_type": "name"}, {"api_name": "tuangou.guider.models.ReDeal.news.values_list", "line_number": 15, "usage_type": "call"}, {"api_name": "tuangou.guider.models.ReDeal.news", "line_number": 15, "usage_type": "attribute"}, {"api_name": "tuangou.guider.models.ReDeal", "line_number": 15, "usage_type": "name"}, {"api_name": "guider.tasks.crawl.apply_async", "line_number": 17, "usage_type": "call"}, {"api_name": "guider.tasks.crawl", "line_number": 17, "usage_type": "name"}]} +{"seq_id": "4202528344", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n## preprocessing\n\nwith open('auto-mpg.data') as datafile:\n dataset = [[value for value in line.split()] for line in datafile]\n \ncarnames = [[]]\nY_list = [[]]\nX_list = [[]]\nbucketlist = [[]]\nfeat_names = ['mpg', 'cylinders', 'displacement','horsepower', \n 'weight', 'acceleration', 'model year', 'origin']\n\nfrom random import shuffle\nshuffle(dataset)\n\nfor row in dataset:\n for col in range (0,8):\n row[col] = float(row[col])\n carnames.append(row[8:])\n del row[8:]\n Y_list.append(row[0])\n bucketlist.append(row[0])\n X_list.append(row[1:])\n \ncarnames.pop(0)\nY_list.pop(0)\nX_list.pop(0)\nbucketlist.pop(0)\nbucketlist.sort()\nbuckets = [bucketlist[130],bucketlist[260]]\n\n\n\"\"\"classify low mpg as 1, mid as 2, high as 3, for better graphical \nrepresentation of data\"\"\"\n\nfor row in dataset:\n if row[0] <= buckets[0]:\n row[0] = 1\n elif row[0] <= buckets[1]:\n row[0] = 2\n else:\n row[0] = 3\n\n## problem 2 in another file\n\n## train / test split ##\nX_list_train = X_list[0:200]\nX_list_test = X_list[200:]\n\nY_list_train = Y_list[0:200]\nY_list_test = Y_list[200:]\n\nX_train = np.array(X_list_train)\nX_test = np.array(X_list_test)\n\nY_train = np.array(Y_list_train)\nY_test = np.array(Y_list_test)\n\nX = np.array(X_list)\nY = np.array(Y_list)\n## feature scaling ##\n\n#colmeans = []\n#colstd = []\n#for i in range(0,7):\n# colmeans.append(X[:,i].mean())\n# colstd.append(X[:,i].std())\n# X[:,i] = X[:,i] - colmeans[i]\n# X[:,i] = X[:,i] / colstd[i]\n# X_test[:,i] = X_test[:,i] - colmeans[i]\n# X_test[:,i] = X_test[:,i] / colstd[i] \n# X_train[:,i] = X_train[:,i] - colmeans[i]\n# X_train[:,i] = X_train[:,i] / colstd[i]\n# \n#Y_mean = Y.mean()\n#Y_std = Y.std()\n#Y = Y - Y_mean\n#Y = Y / Y_std\n#Y_test = Y_test - Y_mean\n#Y_test = Y_test / Y_std\n#Y_train = Y_train - Y_mean\n#Y_train = Y_train / Y_std\n\n## solver ##\n\n## helper function to compute values for polynomial calculations\n\ndef polyhelper(value, order):\n table = [1]\n x = value\n for i in range(1,order+1):\n table.append(x)\n x = x*value\n return table\n\ndef modifiedpolyhelper(valuematrix,order):\n table = [1]\n for value in valuematrix:\n x = value\n for i in range(1,order+1):\n table.append(x)\n x = x*value\n return table\n\ndef polytable(polymat, matrix, polyval, listrep = False):\n output= matrix\n if (listrep== True):\n for row in polymat:\n matrix.append(modifiedpolyhelper(row,polyval))\n else:\n for value in polymat:\n matrix.append(polyhelper(value,polyval))\n matrix.pop(0)\n return output\n\ndef weighthelper(X,Y):\n xTx = np.matmul(X.T,X)\n xTx_inv = np.linalg.pinv(xTx)\n xTy = np.matmul(X.T,Y)\n W = np.matmul(xTx_inv, xTy)\n return W\n\ndef error_calc(X,Y,W, size):\n error= 0\n for i in range(0,size):\n iterable = 0\n for j in range(0, len(W)):\n iterable += X[i][j]*W[j]\n error += (Y[i] - iterable)**2\n error = error/ size\n return error\n\nclass solver:\n def __init__(self,X,Y):\n self.X = X\n self.Y = Y\n \n ## single variable polynomial calculator \n def single_var_poly(self, polyVal, index):\n self.index = index\n self.polyVal = polyVal\n ## generate X table of values given a certain order to go to\n x_poly_matrix = [[]] \n x_col = self.X[:,index].tolist()\n x_poly_matrix = polytable(x_col,x_poly_matrix, polyVal) \n newX = np.array(x_poly_matrix)\n self.XpolyTable = newX\n self.W = weighthelper(newX,self.Y)\n \n ## train error squared given M samples\n def train_error_calc(self, multi = False):\n self.trainerror = 0\n if (multi == False):\n self.trainerror = error_calc(self.XpolyTable,self.Y,self.W,200)\n else:\n self.trainerror = error_calc(self.Xmulti_polyTable, self.Y,\n self.W,200)\n ## test error squared calculation given M samples\n def test_error_calc(self, xtest, ytest,multi= False):\n self.xtest = xtest\n self.ytest = ytest\n x_test_poly_matrix = [[]]\n if (multi == False):\n x_col = xtest[:,self.index].tolist()\n x_test_poly_matrix = polytable(x_col,x_test_poly_matrix,\n self.polyVal)\n newX = np.array(x_test_poly_matrix)\n self.xtest_polytable = newX\n self.testerror = error_calc(self.xtest_polytable,self.ytest,\n self.W,192)\n else:\n x_test_poly_matrix = polytable(self.xtest,x_test_poly_matrix,\n self.multi_polyVal, True)\n newX = np.array(x_test_poly_matrix)\n self.xtest_polytable = newX\n self.testerror = error_calc(self.xtest_polytable,self.ytest,\n self.W,192)\n\n ## modified for multivariable, with new modified polyhelper func\n def multivarpoly(self, poly):\n self.multi_polyVal = poly\n ## generate X table of values given a certain order to go to\n x_poly_matrix = [[]]\n x_poly_matrix = polytable(self.X,x_poly_matrix, poly, True)\n newX = np.array(x_poly_matrix)\n self.Xmulti_polyTable = newX\n self.W = weighthelper(newX, self.Y)\n \n\n###################end of solver object####################################### \n\n\nweightset = [[solver(X_train, Y_train) for i in range(0,4)] for j in range (0,7)]\n\n\ntest = [[]]\ntrain = [[]]\nweightlist = [[]]\nfunctions = []\nrangesplot = []\nrangesminplot = []\nfor i in range(0,7):\n rangesplot.append(np.amax(X[:,i]))\n rangesminplot.append(np.amin(X[:,i]))\n temp1 = []\n temp2 = []\n for j in range(0,4):\n weightset[i][j].single_var_poly(j,i)\n weightset[i][j].train_error_calc()\n weightset[i][j].test_error_calc(X_test,Y_test)\n weightlist.append(weightset[i][j].W)\n temp1.append(weightset[i][j].trainerror)\n temp2.append(weightset[i][j].testerror)\n \n train.append(temp1)\n test.append(temp2)\n \nweightlist.pop(0)\ntrain.pop(0)\ntest.pop(0)\n\ntrain_error_4 = pd.DataFrame(train, index = ['cylinders', 'displacement','horsepower',\n 'weight', 'acceleration', 'model year',\n 'origin'], columns = ['0th order',\n '1st order', '2nd order',\n '3rd order'] )\ntest_error_4 = pd.DataFrame(test, index = ['cylinders', 'displacement','horsepower',\n 'weight', 'acceleration', 'model year',\n 'origin'], columns = ['0th order',\n '1st order', '2nd order',\n '3rd order'] )\n\n\n## graphing the specific coefficients applied to polynomial values\n## scatter plot the test values versus the coefficints providing the lines\n## through training\n\n\n\nscatterval = 0\nplotval = 0\nfor i in range(0,28,4):\n x = np.linspace(rangesminplot[plotval],rangesplot[plotval],1000)\n\n plt.scatter(X_test[:,scatterval],Y_test)\n #plt.scatter(X_train[:,scatterval],Y_train)\n plt.plot(x, weightlist[i][0]*(x**0), label = 'intercept')\n plt.plot(x, weightlist[i+1][0]*(x**0) + weightlist[i+1][1]*(x**1), label = 'linear')\n plt.plot(x, weightlist[i+2][0]*(x**0) + weightlist[i+2][1]*(x**1) +\n weightlist[i+2][2]*(x**2), label = 'quadratic')\n plt.plot(x, weightlist[i+3][0]*(x**0) + weightlist[i+3][1]*(x**1) +\n weightlist[i+3][2]*(x**2) +\n weightlist[i+3][3]*(x**3) , label = 'cubic')\n plt.xlabel('Values for feature %s' %feat_names[scatterval+1])\n plt.ylabel('MPG')\n plotval= plotval + 1\n scatterval = scatterval + 1\n plt.show()\n\nmulti_feature_poly = solver(X_train,Y_train)\nmulti_feature_poly.multivarpoly(0)\nmulti_feature_poly.test_error_calc(X_test,Y_test,True)\nmulti_feature_poly.train_error_calc(True)\nmfp_error = [[multi_feature_poly.trainerror],[multi_feature_poly.testerror]]\n\nmulti_feature_poly.multivarpoly(1)\nmulti_feature_poly.test_error_calc(X_test,Y_test,True)\nmulti_feature_poly.train_error_calc(True)\nmfp_error[0].append(multi_feature_poly.trainerror)\nmfp_error[1].append(multi_feature_poly.testerror)\n\nmulti_feature_poly.multivarpoly(2)\nmulti_feature_poly.test_error_calc(X_test,Y_test,True)\nmulti_feature_poly.train_error_calc(True)\nmfp_error[0].append(multi_feature_poly.trainerror)\nmfp_error[1].append(multi_feature_poly.testerror)\n\nmfp_error_table = pd.DataFrame(mfp_error, index = ['Training MSE','Testing MSE'],\n columns = ['0th Order','1st Order', '2nd Order'])\n\n## number 6, logistic regression using sklearn and precision using sklearn\n\ntemp = np.array(dataset[0:200])\ntemp2 = np.array(dataset[200:])\nY_classify= temp [:,0]\nY_true = temp2[:,0]\nfrom sklearn.linear_model import LogisticRegression\nclassifier = LogisticRegression(random_state = 0)\nclassifier.fit(X_train, Y_classify)\n\n\nY_pred = classifier.predict(X_test)\nY_pred_train = classifier.predict(X_train)\nfrom sklearn.metrics import precision_score\nprec_score_test = precision_score(Y_true,Y_pred,average= 'macro')\nprec_score_train = precision_score(Y_classify, Y_pred_train, average = 'macro')\n\n## number 7, using the models to predict new values ##\n\norigin_1 =[6,350,180,3700,9,80,1]\nregressor = solver(X_train,Y_train)\nregressor.multivarpoly(2)\norigin_poly = modifiedpolyhelper(origin_1,2)\nmpg_pred = np.matmul(regressor.W,origin_poly)\n\npredvar = [origin_1]\nmpg_class_pred= classifier.predict(predvar)\n", "repo_name": "alev30/Linear_Regression", "sub_path": "all_other_problems.py", "file_name": "all_other_problems.py", "file_ext": "py", "file_size_in_byte": 9829, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "random.shuffle", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.linalg.pinv", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 122, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 171, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 178, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 189, "usage_type": "call"}, {"api_name": "numpy.amax", "line_number": 207, "usage_type": "call"}, {"api_name": "numpy.amin", "line_number": 208, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 226, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 231, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 247, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 249, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 249, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 251, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 251, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 252, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 252, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 253, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 253, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 255, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 255, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 258, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 258, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 259, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 259, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 262, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 262, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 282, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 287, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 288, "usage_type": "call"}, {"api_name": "sklearn.linear_model.LogisticRegression", "line_number": 292, "usage_type": "call"}, {"api_name": "sklearn.metrics.precision_score", "line_number": 299, "usage_type": "call"}, {"api_name": "sklearn.metrics.precision_score", "line_number": 300, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 308, "usage_type": "call"}]} +{"seq_id": "14701439630", "text": "import discord\r\nfrom discord.ext import commands\r\nfrom discord.utils import get\r\nimport random\r\n\r\nadvertising_channel = 000000000000000000\r\ntarget_channel = 000000000000000000\r\n\r\nstream_ping_role = 000000000000000000\r\n\r\nmod_role = 000000000000000000\r\nop_role = 000000000000000000\r\nadmin_role = 000000000000000000\r\n\r\niel_role = 000000000000000000\r\ntl_role = 000000000000000000\r\n\r\npermitted_roles = [mod_role, op_role, admin_role, iel_role, tl_role, test_role_ID]\r\n\r\n\r\nclass Stream(commands.Cog, name=\"Stream Commands\"):\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n @commands.command(name=\"twitch\", aliases=[\"Twitch\", \"IEL\", \"iel\", \"TL\", \"tl\"])\r\n async def twitch(self, ctx):\r\n\r\n stream_perm = False\r\n\r\n for role in ctx.author.roles:\r\n if role.id in permitted_roles:\r\n stream_perm = True\r\n break\r\n\r\n if stream_perm == False:\r\n await ctx.channel.send(f\"{ctx.author.mention} you do not have the perms to use this command.\") \r\n\r\n elif ctx.channel.id == advertising_channel and stream_perm:\r\n target = get(ctx.guild.channels, id=target_channel)\r\n role_ping = ctx.guild.get_role(stream_ping_role)\r\n await target.send(f\"{role_ping.mention}\")\r\n else:\r\n await ctx.channel.send(f\"{ctx.author.mention} you cannot use this command in this channel.\")\r\n \r\n\r\n await ctx.message.delete()\r\n\r\n\r\ndef setup(bot):\r\n print(\"setup\")\r\n bot.add_cog(Stream(bot))\r\n bot.remove_command(\"help\")\r\n", "repo_name": "conorkostick/RLI-Helper", "sub_path": "stream_cog.py", "file_name": "stream_cog.py", "file_ext": "py", "file_size_in_byte": 1544, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "discord.ext.commands.Cog", "line_number": 21, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 21, "usage_type": "name"}, {"api_name": "discord.utils.get", "line_number": 39, "usage_type": "call"}, {"api_name": "discord.ext.commands.command", "line_number": 25, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 25, "usage_type": "name"}]} +{"seq_id": "24675292445", "text": "import csv\nimport os\nimport glob\nimport random\nimport numpy as np\nimport cv2\nfrom PIL import Image\nfrom keras.utils import to_categorical\nfrom keras.applications.resnet50 import preprocess_input\n\n\ndef get_data(csv_file):\n \"\"\"Load our data from file.\"\"\"\n with open(csv_file, 'r') as fin:\n reader = csv.reader(fin)\n data = list(reader)\n return data\n\ndef split_train_test(data):\n train, test = [], []\n for item in data:\n if item[0] == 'train' or item[0] == 'TRAIN':\n train.append(item)\n else:\n test.append(item)\n return train, test\n\ndef get_classes(data):\n \"\"\"Extract the classes from our data. If we want to limit them,\n only return the classes we need.\"\"\"\n classes = []\n for item in data:\n if item[1] not in classes:\n classes.append(item[1])\n # Sort them.\n classes = sorted(classes)\n return classes\n\ndef clean_data(data, CLIPS_LENGTH, classes, MAX_FRAMES=3000):\n \"\"\"Limit samples to greater than the sequence length and fewer\n than N frames. Also limit it to classes we want to use.\"\"\"\n data_clean = []\n for item in data:\n if int(item[3]) >= CLIPS_LENGTH and int(item[3]) <= MAX_FRAMES and item[1] in classes:\n data_clean.append(item)\n return data_clean\n\ndef get_class_one_hot(class_str, classes):\n label_encoded = classes.index(class_str)\n # Now one-hot it.\n label_hot = to_categorical(label_encoded, len(classes))\n assert len(label_hot) == len(classes)\n return label_hot\n\ndef get_frames_for_sample(sample):\n \"\"\"Given a sample row from the data file, get all the corresponding frame\n filenames.\"\"\"\n path = os.path.join(sample[0], sample[1])\n folder_name = sample[2]\n images = sorted(glob.glob(os.path.join(path, folder_name + '/*jpg')))\n num_frames = sample[3]\n return images, int(num_frames)\n\n\ndef read_images(frames, start_idx, num_frames_per_clip):\n img_data = []\n for i in range(start_idx, start_idx + num_frames_per_clip):\n img = Image.open(frames[i])\n img = np.asarray(img)\n img_data.append(img)\n return img_data\n\ndef read_images_1(frames, num_frames, num_frames_per_clip):\n img_data = []\n for i in range(0, num_frames):\n img = Image.open(frames[i])\n img = np.asarray(img)\n img_data.append(img)\n for i in range(num_frames_per_clip-num_frames):\n img = Image.open(frames[num_frames-1])\n img = np.asarray(img)\n img_data.append(img)\n return img_data\n\ndef data_process(tmp_data, crop_size, is_train):\n img_datas = []\n mean = np.asarray([0.485, 0.456, 0.406])\n std = np.asarray([0.229, 0.224, 0.225])\n crop_x = 0\n crop_y = 0\n\n if crop_size==224:\n resize_value=256\n else:\n resize_value=129\n\n if is_train == True and random.random() > 0.5:\n cvt_color = True\n else:\n cvt_color = False\n\n if is_train == True and random.random() > 0.5:\n flip = True\n else:\n flip = False\n\n for j in range(len(tmp_data)):\n img = Image.fromarray(tmp_data[j].astype(np.uint8))\n if img.width > img.height:\n scale = float(resize_value) / float(img.height)\n img = np.array(cv2.resize(np.array(img), (int(img.width * scale + 1), resize_value))).astype(np.float32)\n else:\n scale = float(resize_value) / float(img.width)\n img = np.array(cv2.resize(np.array(img), (resize_value, int(img.height * scale + 1)))).astype(np.float32)\n if j == 0:\n if is_train:\n crop_x = random.randint(0, int(img.shape[0] - crop_size))\n crop_y = random.randint(0, int(img.shape[1] - crop_size))\n else:\n crop_x = int((img.shape[0] - crop_size) / 2)\n crop_y = int((img.shape[1] - crop_size) / 2)\n img = img[crop_x:crop_x + crop_size, crop_y:crop_y + crop_size, :]\n img = np.asarray(img) / 127.5\n img -= 1\n\n\n if cvt_color:\n img = -img\n if flip:\n img = np.flip(img, axis=1)\n\n img_datas.append(img)\n return img_datas\n\ndef frame_generator(batch_size, data, num_frames_per_clip, crop_size, classes, is_train=True):\n while True:\n X, y = [], []\n random.shuffle(data)\n for i in range(len(data)):\n row = data[i]\n frames, num_frames = get_frames_for_sample(row)\n if num_frames >= num_frames_per_clip:\n start_idx = random.randint(0, num_frames - num_frames_per_clip)\n rgb_img_data = read_images(frames, start_idx, num_frames_per_clip)\n else:\n rgb_img_data = read_images_1(frames, num_frames, num_frames_per_clip)\n rgb_img_data = data_process(rgb_img_data, crop_size, is_train)\n rgb_img_data = np.asarray(rgb_img_data)\n X.append(rgb_img_data)\n label = get_class_one_hot(row[1], classes=classes)\n y.append(label)\n if len(y)== batch_size:\n yield np.asarray(X), np.asarray(y)\n X, y =[], []\n\n#----------------------------------------------------------------------------------------------------------------------------\n#------------------------------------------GENERATOR FOR IMAGE---------------------------------------------------------------\n#----------------------------------------------------------------------------------------------------------------------------\n\ndef img_process(rgb_img, crop_size, is_train=True):\n if is_train == True and random.random() > 0.5:\n cvt_color = True\n else:\n cvt_color = False\n\n if crop_size == 224:\n resize_value = 256\n else:\n resize_value = 129\n\n if is_train == True and random.random() > 0.5:\n flip = True\n else:\n flip = False\n\n\n img = Image.fromarray(rgb_img.astype(np.uint8))\n if img.width > img.height:\n scale = float(resize_value) / float(img.height)\n img = np.array(cv2.resize(np.array(img), (int(img.width * scale + 1), resize_value))).astype(np.float32)\n else:\n scale = float(resize_value) / float(img.width)\n img = np.array(cv2.resize(np.array(img), (resize_value, int(img.height * scale + 1)))).astype(np.float32)\n\n if is_train:\n crop_x = random.randint(0, int(img.shape[0] - crop_size))\n crop_y = random.randint(0, int(img.shape[1] - crop_size))\n else:\n crop_x = int((img.shape[0] - crop_size) / 2)\n crop_y = int((img.shape[1] - crop_size) / 2)\n\n img = img[crop_x:crop_x + crop_size, crop_y:crop_y + crop_size, :]\n img = np.asarray(img) / 127.5\n img -= 1.0\n\n if cvt_color:\n img = -img\n if flip:\n img = np.flip(img, axis=1)\n\n return np.asarray(img)\n\ndef img_generator(batch_size, data, crop_size, classes, is_train=True):\n while True:\n X, y = [], []\n random.shuffle(data)\n for i in range(len(data)):\n row = data[i]\n frames, num_frames = get_frames_for_sample(row)\n idx = random.randint(0, num_frames-1)\n rgb_img = Image.open(frames[idx])\n # rgb_img = rgb_img.resize((crop_size,crop_size))\n # rgb_img = np.asarray(rgb_img)\n # rgb_img = preprocess_input(rgb_img)\n rgb_img = np.asarray(rgb_img)\n rgb_img = img_process(rgb_img, crop_size,is_train)\n X.append(rgb_img)\n label = get_class_one_hot(row[1], classes=classes)\n y.append(label)\n if len(y)== batch_size:\n yield np.asarray(X), np.asarray(y)\n X, y =[], []\n\n#----------------------------------------------------------------------------------------------------------------------------\n#------------------------------------------GENERATOR FOR TEACHER STUDENT---------------------------------------------------------------\n#----------------------------------------------------------------------------------------------------------------------------\n\ndef generator_teacher_student(batch_size, data, num_frames_per_clip, crop_size, is_train=True):\n while True:\n X_img, X_frames, y = [], [], []\n random.shuffle(data)\n for i in range(len(data)):\n row = data[i]\n frames, num_frames = get_frames_for_sample(row)\n if num_frames >= num_frames_per_clip:\n start_idx = random.randint(0, num_frames - num_frames_per_clip)\n rgb_img_data = read_images(frames, start_idx, num_frames_per_clip)\n else:\n rgb_img_data = read_images_1(frames, num_frames, num_frames_per_clip)\n rgb_img_data = data_process(rgb_img_data, crop_size, is_train)\n idx = random.randint(0, len(rgb_img_data)-1)\n rgb_img = rgb_img_data[idx]\n rgb_img = np.asarray(rgb_img)\n rgb_img_data = np.asarray(rgb_img_data)\n X_img.append(rgb_img)\n X_frames.append(rgb_img_data)\n\n label = 1\n y.append(label)\n if len(y) == batch_size:\n yield [np.asarray(X_img), np.asarray(X_frames), np.asarray(X_frames)], np.asarray(y)\n X_img, X_frames, y = [], [], []\n\n#----------------------------------------------------------------------------------------------------------------------------\n#------------------------------------------GENERATOR FOR ENCODER PREDICT-----------------------------------------------------\n#----------------------------------------------------------------------------------------------------------------------------\ndef generator_encoder_predict(batch_size, data, num_frames_per_clip, crop_size, classes, is_train=True):\n while True:\n X, y = [], []\n random.shuffle(data)\n for i in range(len(data)):\n row = data[i]\n frames, num_frames = get_frames_for_sample(row)\n if num_frames > num_frames_per_clip:\n start_idx = random.randint(0, num_frames - num_frames_per_clip)\n end_idx = start_idx + num_frames_per_clip - 1\n else:\n start_idx = 0\n end_idx = num_frames - 1\n rgb_start = Image.open(frames[start_idx])\n rgb_start = np.asarray(rgb_start)\n rgb_end = Image.open(frames[end_idx])\n rgb_end = np.asarray(rgb_end)\n rgb_start = img_process(rgb_start, crop_size, is_train)\n rgb_end = img_process(rgb_end, crop_size, is_train)\n\n temp = []\n for k in range(num_frames_per_clip//2):\n temp.append(rgb_start)\n for k in range(num_frames_per_clip//2):\n temp.append(rgb_end)\n temp = np.asarray(temp)\n X.append(temp)\n label = get_class_one_hot(row[1], classes=classes)\n y.append(label)\n if len(y) == batch_size:\n yield np.asarray(X), np.asarray(y)\n X, y = [], []\n\n\n#----------------------------------------------------------------------------------------------------------------------------\n#------------------------------------------GENERATOR FOR ENCODER DECODER-----------------------------------------------------\n#----------------------------------------------------------------------------------------------------------------------------\ndef generator_encoder_decoder(batch_size, data, num_frames_per_clip, crop_size, is_train=True):\n while True:\n X, y = [], []\n random.shuffle(data)\n for i in range(len(data)):\n row = data[i]\n frames, num_frames = get_frames_for_sample(row)\n start_idx = random.randint(0, num_frames - num_frames_per_clip)\n rgb_img_data = read_images(frames, start_idx, num_frames_per_clip)\n rgb_img_data = data_process(rgb_img_data, crop_size, is_train)\n\n temp = []\n zero_img = np.zeros((crop_size, crop_size,3))\n temp.append(rgb_img_data[0])\n for j in range(num_frames_per_clip-2):\n temp.append(zero_img)\n temp.append(rgb_img_data[-1])\n rgb_img_data = np.asarray(rgb_img_data)\n temp = np.asarray(temp)\n y.append(rgb_img_data)\n X.append(temp)\n if len(y)== batch_size:\n yield np.asarray(X), np.asarray(y)\n X, y =[], []\n\n#----------------------------------------------------------------------------------------------------------------------------\n#------------------------------------------GENERATOR FOR PREDICT NOISE VIDEOS------------------------------------------------\n#----------------------------------------------------------------------------------------------------------------------------\ndef pre_process(tmp_data, crop_size, is_train):\n img_datas = []\n crop_x = 0\n crop_y = 0\n\n if crop_size==224:\n resize_value=256\n else:\n resize_value=129\n\n for j in range(len(tmp_data)):\n img = Image.fromarray(tmp_data[j].astype(np.uint8))\n if img.width > img.height:\n scale = float(resize_value) / float(img.height)\n img = np.array(cv2.resize(np.array(img), (int(img.width * scale + 1), resize_value))).astype(np.float32)\n else:\n scale = float(resize_value) / float(img.width)\n img = np.array(cv2.resize(np.array(img), (resize_value, int(img.height * scale + 1)))).astype(np.float32)\n if j == 0:\n if is_train:\n crop_x = random.randint(0, int(img.shape[0] - crop_size))\n crop_y = random.randint(0, int(img.shape[1] - crop_size))\n else:\n crop_x = int((img.shape[0] - crop_size) / 2)\n crop_y = int((img.shape[1] - crop_size) / 2)\n img = img[crop_x:crop_x + crop_size, crop_y:crop_y + crop_size, :]\n img = np.asarray(img) / 127.5\n img -= 1\n\n img_datas.append(img)\n return img_datas\n\ndef rotation_video(tmp_data, rot=90):\n new_data = []\n for img in tmp_data:\n if rot==90:\n new_img = np.rot90(img)\n elif rot==180:\n new_img = np.rot90(img, 2)\n else:\n new_img = np.rot90(img,3)\n new_data.append(new_img)\n return new_data\n\ndef shufle_frames(tmp_data):\n new_data = tmp_data.copy()\n random.shuffle(new_data)\n return new_data\n\ndef flip_frames(tmp_data):\n new_data = []\n for frame in tmp_data:\n new_data.append(np.flip(frame, axis=1))\n return new_data\n\ndef switch_channel(tmp_data):\n a = [0, 1, 2]\n new_data = []\n while a == [0, 1, 2]:\n random.shuffle(a)\n for frame in tmp_data:\n red = frame[:, :, 0].copy()\n green = frame[:, :, 1].copy()\n blue = frame[:, :, 2].copy()\n frame[:, :, a[0]] = red\n frame[:, :, a[1]] = green\n frame[:, :, a[2]] = blue\n new_data.append(frame)\n return new_data\n\ndef inverse_frame(tmp_data):\n new_data = []\n for i in range(len(tmp_data),0,-1):\n new_data.append(tmp_data[i-1])\n return new_data\n\ndef replace_frame(tmp_data, crop_size):\n new_data = tmp_data.copy()\n idx = random.randint(1, len(new_data)-1)\n fake_img = np.random.uniform(-1, 1, (crop_size, crop_size, 3))\n new_data[idx] = fake_img\n return new_data\n\ndef add_noise_to_frame(tmp_data, crop_size=224):\n new_data = []\n for j in range(len(tmp_data)):\n img = tmp_data[j]\n noise = random.random() + 0.2\n noise_frame = np.random.uniform(-noise, noise, crop_size*crop_size*3)\n noise_frame = np.reshape(noise_frame, newshape=(224, 224, 3))\n img = img + noise_frame\n new_data.append(img)\n return new_data\n\ndef split_and_join(tmp_data, crop_size=224, is_train=True):\n new_data = tmp_data.copy()\n num_frames_per_clip = len(new_data)\n train_data = get_data('train.csv')\n other_video = random.choice(train_data)\n frames, num_frames = get_frames_for_sample(other_video)\n start_idx = random.randint(0, num_frames - num_frames)\n other_clip = read_images(frames, start_idx, num_frames_per_clip)\n other_clip = pre_process(other_clip, crop_size, is_train)\n start_idx = random.uniform(0, num_frames_per_clip//2)\n for i in range(start_idx, start_idx + num_frames_per_clip//2):\n new_data[i] = other_clip[i]\n return new_data\n\n\ndef modify_video(tmp_data, class_value, crop_size=224, is_train=True):\n if class_value==1:\n rot = random.choice([90, 180, 270])\n new_video = rotation_video(tmp_data, rot)\n elif class_value==2:\n new_video = switch_channel(tmp_data)\n elif class_value==3:\n new_video = add_noise_to_frame(tmp_data, crop_size)\n elif class_value == 4:\n new_video = replace_frame(tmp_data, crop_size)\n elif class_value == 5:\n new_video = inverse_frame(tmp_data)\n elif class_value == 6:\n new_video = split_and_join(tmp_data, crop_size, is_train)\n else:\n new_video = shufle_frames(tmp_data)\n return new_video\n\ndef generator_predict_noise_video(batch_size, data, num_frames_per_clip, crop_size, nb_classes, is_train=True):\n while True:\n X, y = [], []\n random.shuffle(data)\n for i in range(len(data)):\n row = data[i]\n frames, num_frames = get_frames_for_sample(row)\n if num_frames > num_frames_per_clip:\n start_idx = random.randint(0, num_frames - num_frames_per_clip)\n rgb_img_data = read_images(frames, start_idx, num_frames_per_clip)\n else:\n rgb_img_data = read_images_1(frames, num_frames, num_frames_per_clip)\n rgb_img_data = pre_process(rgb_img_data, crop_size, is_train)\n\n probability = random.random()\n encoder_label = np.zeros((8))\n if probability < 0.2:\n encoder_label[0]=1\n else:\n spatial = 0\n temporal = 0\n while spatial==0 and temporal==0:\n probability = random.random()\n if probability > 0.5:\n transformation_idx = random.randint(1,4)\n spatial = 1\n encoder_label[transformation_idx] = 1\n rgb_img_data = modify_video(rgb_img_data, transformation_idx, crop_size=crop_size, is_train=is_train)\n probability = random.random()\n if probability > 0.5:\n transformation_idx = random.randint(5, 7)\n temporal=1\n encoder_label[transformation_idx]=1\n rgb_img_data = modify_video(rgb_img_data, transformation_idx, crop_size=crop_size,is_train=is_train)\n\n noise_video = np.asarray(rgb_img_data)\n X.append(noise_video)\n y.append(encoder_label)\n if len(y)== batch_size:\n yield np.asarray(X), np.asarray(y)\n X, y =[], []", "repo_name": "vdquang1991/action_recognition", "sub_path": "C_data_generator.py", "file_name": "C_data_generator.py", "file_ext": "py", "file_size_in_byte": 18953, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "csv.reader", "line_number": 15, "usage_type": "call"}, {"api_name": "keras.utils.to_categorical", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path", "line_number": 58, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path", "line_number": 60, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 68, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 68, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 69, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 76, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 76, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 77, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 80, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 80, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 88, "usage_type": "call"}, {"api_name": "random.random", "line_number": 97, "usage_type": "call"}, {"api_name": "random.random", "line_number": 102, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 108, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 108, "usage_type": "name"}, {"api_name": "numpy.uint8", "line_number": 108, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 111, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 111, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 114, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 114, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 117, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.flip", "line_number": 130, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 138, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 153, "usage_type": "call"}, {"api_name": "random.random", "line_number": 161, "usage_type": "call"}, {"api_name": "random.random", "line_number": 171, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 177, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 177, "usage_type": "name"}, {"api_name": "numpy.uint8", "line_number": 177, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 180, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 180, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 180, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 183, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 183, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 183, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 186, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 187, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 193, "usage_type": "call"}, {"api_name": "numpy.flip", "line_number": 199, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 201, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 206, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 210, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 211, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 211, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 221, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 231, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 236, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 241, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 243, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 244, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 251, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 260, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 265, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 270, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 270, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 271, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 272, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 272, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 273, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 282, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 287, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 297, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 301, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 306, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 311, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 312, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 316, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 333, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 333, "usage_type": "name"}, {"api_name": "numpy.uint8", "line_number": 333, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 336, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 336, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 336, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 339, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 339, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 339, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 342, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 343, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 348, "usage_type": "call"}, {"api_name": "numpy.rot90", "line_number": 358, "usage_type": "call"}, {"api_name": "numpy.rot90", "line_number": 360, "usage_type": "call"}, {"api_name": "numpy.rot90", "line_number": 362, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 368, "usage_type": "call"}, {"api_name": "numpy.flip", "line_number": 374, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 381, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 400, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 401, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 401, "usage_type": "attribute"}, {"api_name": "random.random", "line_number": 409, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 410, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 410, "usage_type": "attribute"}, {"api_name": "numpy.reshape", "line_number": 411, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 420, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 422, "usage_type": "call"}, {"api_name": "random.uniform", "line_number": 425, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 433, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 452, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 457, "usage_type": "call"}, {"api_name": "random.random", "line_number": 463, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 464, "usage_type": "call"}, {"api_name": "random.random", "line_number": 471, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 473, "usage_type": "call"}, {"api_name": "random.random", "line_number": 477, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 479, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 484, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 488, "usage_type": "call"}]} +{"seq_id": "22241358903", "text": "import collections\n\n\n__all__ = [\n 'get_innermost',\n 'get_nested_objs',\n 'get_outermost',\n 'has_nested',\n 'replace_innermost',\n 'replace_outermost',\n 'UnnestingWrapper',\n]\n\n\ndef get_nested_objs(obj,\n nested_key='__nested_attrs__',\n fallback_attrs=(\n 'inner_results',\n 'accepted_results',\n '_inner_kernel', # used by TransformedTransitionKernel\n 'inner_kernel',\n )):\n \"\"\"Finds the list of nested objects inside an object's attributes.\n\n `get_nested_objs` proceeds as follow:\n\n 1. If `hasattr(obj, nested_key)`, then set\n `nested_attrs = getattr(obj, nested_key)`.\n 2. Otherwise set `nested_attrs = fallback_attrs`.\n 3. In either case, `nested_attrs` should now be a string or collection of\n strings. Return the list `[(attr, getattr(obj, attr)) for attr in\n nested_attrs]` omitting missing attributes.\n\n `nested_key` is for class- or object-level customization, and `fallback_attrs`\n for invocation-level customization.\n\n Example:\n\n ```\n class Nest:\n __nested_attrs__ = ('inner1', 'inner2')\n\n def __init__(self, inner1, inner2, inner3):\n self.inner1 = inner1\n self.inner2 = inner2\n self.inner3 = inner3\n\n nest = Nest('x', 'y', 'z')\n\n # Search stops if `nested_key` is found.\n get_nested_objs(\n nest,\n nested_key='__nested_attrs__',\n fallback_attrs=('inner1', 'inner2', 'inner3')) == [\n ('inner1', 'x'), ('inner2', 'y')] # True\n\n # If `nested_key` is not found, search in all of `fallback_attrs`.\n get_nested_objs(\n nest,\n nested_key='does_not_exist',\n fallback_attrs=('inner1', 'inner2', 'inner3')) == [\n ('inner1', 'x'), ('inner2', 'y'), ('inner3', 'z')] # True\n\n # If nothing is found, empty list is returned.\n get_nested_objs(\n nest,\n nested_key='does_not_exist',\n fallback_attrs=('does_not_exist')) == [] # True\n\n # `getattr(obj, nested_key)` and `fallback_attrs` can be either strings or\n # collections of strings.\n nest2 = Nest('x', 'y', 'z')\n nest2.__nested_attrs__ = 'inner3'\n get_nested_objs(\n nest2,\n nested_key='__nested_attrs__',\n fallback_attrs=('inner1', 'inner2')) == [('inner3', 'z')] # True\n get_nested_objs(\n nest2,\n nested_key='does_not_exist',\n fallback_attrs='inner2') == [('inner2', 'y')] # True\n ```\n\n Args:\n obj: The object to find nested objects in.\n nested_key: A string that names an attribute on `obj` which contains the\n names of attributes to search for nested objects in. See function\n documentation for details. Default is `__nested_attrs__`.\n fallback_attrs: A string or collection of strings that name attributes to\n search for nested objects in, when `nested_key` is not present. See\n function documentation for details. Default is the tuple\n `('inner_results', 'accepted_results', 'inner_kernel')`, which works well\n for MCMC kernels and kernel results.\n\n Returns:\n pairs: Returns a (possibly empty) list of (field name, nested results).\n \"\"\"\n if hasattr(obj, nested_key):\n attrs = getattr(obj, nested_key)\n else:\n attrs = fallback_attrs\n if isinstance(attrs, str):\n attrs = [attrs]\n return [(attr, getattr(obj, attr)) for attr in attrs\n if hasattr(obj, attr)]\n\n\ndef has_nested(obj, attr, nested_lookup_fn=get_nested_objs):\n \"\"\"Check if the object has a (nested) attribute.\n\n Args:\n obj: The object to find (nested) attributes in.\n attr: A `string` attribute name to search for.\n nested_lookup_fn: A single-argument callable that returns a list of\n (attribute name, nested object) pairs. Defaults to `get_nested_objs`.\n\n Returns:\n has_nested: Boolean if the attribute was found or not.\n \"\"\"\n if hasattr(obj, attr):\n return True\n for _, nested in nested_lookup_fn(obj):\n if has_nested(nested, attr, nested_lookup_fn=nested_lookup_fn):\n return True\n return False\n\n\nSENTINEL = object()\n\n\ndef get_innermost(obj, attr, default=SENTINEL,\n nested_lookup_fn=get_nested_objs):\n \"\"\"Return a (nested) attribute value.\n\n The first attribute found is returned. Nested objects are traversed\n depth-first in post-order, with level-wise order determined by the list\n ordering returned from `nested_lookup_fn`.\n\n Args:\n obj: The object to find (nested) attributes in.\n attr: A `string` attribute name to search for.\n default: If `attr` does not exist in `obj` or nested objects, and `default`\n is set, return `default`.\n nested_lookup_fn: A single-argument callable that returns a list of\n (attribute name, nested object) pairs. Defaults to `get_nested_objs`.\n\n Returns:\n value: The (nested) attribute value, or `default` if it does not exist and\n `default` is set.\n\n Raises:\n AttributeError: if `attr` is not found and `default` is not specified.\n \"\"\"\n for _, nested in nested_lookup_fn(obj):\n try:\n return get_innermost(nested, attr, nested_lookup_fn=nested_lookup_fn)\n except AttributeError:\n pass\n try:\n return getattr(obj, attr)\n except AttributeError:\n if default is not SENTINEL:\n return default\n raise AttributeError('No attribute `' + attr + '` in nested results of '\n + str(obj.__class__))\n\n\ndef get_outermost(obj, attr, default=SENTINEL,\n nested_lookup_fn=get_nested_objs):\n \"\"\"Return a (nested) attribute value.\n\n The first attribute found is returned. Nested objects are traversed\n breadth-first, with level-wise order determined by the list ordering returned\n from `nested_lookup_fn`.\n\n Args:\n obj: The object to find (nested) attributes in.\n attr: A `string` attribute name to search for.\n default: If `attr` does not exist in `obj` or nested objects, and `default`\n is set, return `default`.\n nested_lookup_fn: A single-argument callable that returns a list of\n (attribute name, nested object) pairs. Defaults to `get_nested_objs`.\n\n Returns:\n value: The (nested) attribute value, or `default` if it does not exist and\n `default` is set.\n\n Raises:\n AttributeError: if `attr` is not found and `default` is not specified.\n \"\"\"\n to_visit = collections.deque([obj])\n while to_visit:\n nested = to_visit.popleft()\n to_visit.extend((nested for _, nested in nested_lookup_fn(nested)))\n try:\n return getattr(nested, attr)\n except AttributeError:\n pass\n if default is not SENTINEL:\n return default\n raise AttributeError('No attribute `' + attr + '` in nested results of '\n + str(obj.__class__))\n\n\ndef replace_innermost(ntuple, return_unused=False,\n nested_lookup_fn=get_nested_objs, **kw):\n \"\"\"Replace (nested) fields in a `namedtuple`.\n\n For each attribute-value update specified, this function only replaces the\n first matching attribute found. Nested objects are traversed depth-first in\n post-order, with level-wise order determined by the list ordering returned\n from `nested_lookup_fn`.\n\n Args:\n ntuple: A `namedtuple` to replace (nested) fields in.\n return_unused: If `True`, return the `dict` of attribute-value pairs in\n `**kw` that were not found and updated in `ntuple`.\n nested_lookup_fn: A single-argument callable that returns a list of\n (attribute name, nested object) pairs. Defaults to `get_nested_objs`.\n **kw: The attribute-value pairs to update.\n\n Returns:\n updated: A copy of `ntuple` with (nested) fields updated.\n unused: If `return_unused` is `True`, the dictionary of attribute-value\n pairs in `**kw` that were not found and updated in `ntuple`.\n\n Raises:\n ValueError: if `returne_unused=False` and attributes in `**kw` are not found\n in `ntuple`.\n \"\"\"\n nested_updates = {}\n for fieldname, nested in nested_lookup_fn(ntuple):\n updated, kw = replace_innermost(\n nested, return_unused=True, nested_lookup_fn=nested_lookup_fn, **kw)\n nested_updates[fieldname] = updated\n kw.update(nested_updates)\n if not return_unused:\n return ntuple._replace(**kw)\n outer_updates = {attr: kw[attr] for attr in ntuple._fields\n if attr in kw}\n extra = {attr: val for attr, val in kw.items()\n if attr not in outer_updates}\n return ntuple._replace(**outer_updates), extra\n\n\ndef replace_outermost(ntuple, return_unused=False,\n nested_lookup_fn=get_nested_objs, **kw):\n \"\"\"Replace (nested) fields in a `namedtuple`.\n\n For each attribute-value update specified, this function only replaces the\n first matching attribute found. Nested objects are traversed breadth-first,\n with level-wise order determined by the list ordering returned from\n `nested_lookup_fn`.\n\n Args:\n ntuple: A `namedtuple` to replace (nested) fields in.\n return_unused: If `True`, return the `dict` of attribute-value pairs in\n `**kw` that were not found and updated in `ntuple`.\n nested_lookup_fn: A single-argument callable that returns a list of\n (attribute name, nested object) pairs. Defaults to `get_nested_objs`.\n **kw: The attribute-value pairs to update.\n\n Returns:\n updated: A copy of `ntuple` with (nested) fields updated.\n unused: If `return_unused` is `True`, the dictionary of attribute-value\n pairs in `**kw` that were not found and updated in `ntuple`.\n\n Raises:\n ValueError: if `returne_unused=False` and attributes in `**kw` are not found\n in `ntuple`.\n \"\"\"\n root = ntuple\n root_update = {k: kw[k] for k in root._fields if k in kw}\n kw = {k: v for k, v in kw.items() if k not in root_update}\n # Collect the updates to apply later by traversing breadth-first, but with\n # backlinks to parent updates.\n to_visit = collections.deque(\n [(root_update, field, child)\n for field, child in nested_lookup_fn(root)])\n inner_updates = []\n while to_visit and kw:\n parent_update, field, child = to_visit.popleft()\n child_update = {k: kw[k] for k in child._fields if k in kw}\n if child_update:\n kw = {k: v for k, v in kw.items() if k not in child_update}\n inner_updates.append((parent_update, field, child, child_update))\n to_visit.extend(\n [(child_update, child_field, child_child)\n for child_field, child_child in nested_lookup_fn(child)])\n # Now apply updates in reverse order, propogating up to root.\n for parent_update, field, child, child_update in reversed(inner_updates):\n parent_update[field] = child._replace(**child_update)\n root = root._replace(**root_update)\n if not return_unused:\n if kw:\n raise ValueError(\n 'Got unexpected (nested) field names: {}'.format(list(kw)))\n return root\n return root, kw\n\n\nclass UnnestingWrapper:\n \"\"\"For when you want to get (nested) fields by usual attribute access.\n\n Example usage:\n\n ```\n results = ...\n wrapped = UnnestingWrapper(results)\n wrapped.my_attr # equivalent to `get_innermost(results, 'my_attr')\n\n # Use `_object` to get at the wrapped object.\n new_results = replace_innermost(wrapped._object, ...)\n ```\n \"\"\"\n\n def __init__(self, obj, innermost=True):\n \"\"\"Wraps objects so attribute access searches nested objects.\n\n Args:\n obj: The object to find nested objects in.\n innermost: Boolean. When `True`, attribute access uses `get_innermost`;\n otherwise uses `get_outermost`. Defaults to `True`.\n \"\"\"\n self._object = obj\n self._innermost = innermost\n\n def __getattr__(self, attr):\n if self._innermost:\n return get_innermost(self._object, attr)\n else:\n return get_outermost(self._object, attr)\n\n def __repr__(self):\n return 'UnnestingWrapper(innermost={}):\\n{}'.format(\n self._innermost,\n repr(self._object))\n", "repo_name": "tensorflow/probability", "sub_path": "tensorflow_probability/python/internal/unnest.py", "file_name": "unnest.py", "file_ext": "py", "file_size_in_byte": 11766, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3997, "dataset": "github-code", "pt": "24", "api": [{"api_name": "collections.deque", "line_number": 191, "usage_type": "call"}, {"api_name": "collections.deque", "line_number": 277, "usage_type": "call"}]} +{"seq_id": "6832559989", "text": "import collections\nfrom .position_data import PositionData\nfrom .dataset_detail import DatasetDetail\nfrom .full_dataset import FullDataset\n\nclass SequenceData:\n def __init__(self, sequence, patterns):\n self.positions = []\n self.dataset_names = []\n self.full_datasets = collections.OrderedDict()\n\n for i, base in enumerate(sequence):\n self.positions.append(PositionData(base, i+1))\n\n for pattern in patterns:\n for pos in pattern.finditer(sequence):\n self.positions[pos].add_pattern_match(pattern)\n\n # Position on sequence starts from 1\n def position(self, pos):\n return self.positions[pos-1]\n\n def full_dataset(self, name):\n return self.full_datasets[name]\n\n def any_datasets(self):\n return len(self.dataset_names) > 0\n\n def ensure_dataset(self, name, check_dataset=False):\n if name in self.dataset_names:\n return\n\n for positions in self.positions:\n positions.datasets[name] = DatasetDetail(check_dataset)\n\n self.full_datasets[name] = FullDataset(name, self)\n self.dataset_names.append(name)\n\n def calculate(self):\n for position in self.positions:\n position.calculate()\n\n for _, dataset in self.full_datasets.items():\n dataset.calculate()\n", "repo_name": "bioinfocz/rnamod", "sub_path": "rnamod/sequence_data.py", "file_name": "sequence_data.py", "file_ext": "py", "file_size_in_byte": 1281, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "collections.OrderedDict", "line_number": 10, "usage_type": "call"}, {"api_name": "position_data.PositionData", "line_number": 13, "usage_type": "call"}, {"api_name": "dataset_detail.DatasetDetail", "line_number": 34, "usage_type": "call"}, {"api_name": "full_dataset.FullDataset", "line_number": 36, "usage_type": "call"}]} +{"seq_id": "37599195575", "text": "import pygame \nimport sys\nimport random\n\nFPS = 120\nsize = [1080,900]\npygame.init()\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption('Game')\n\ndef updateColor(color,index):\n return round((color+random.random()*3 +index*random.random()*3)%255,2)\n\ndef bgRender():\n bg.fill(bgColor)\n a.fill([((x*2)%255) for x in bgColor])\n pygame.draw.circle(bg, [230,40,40],(bgColor[2]*5,400), bgColor[0], 0)\n screen.blit(bg,(0,0))\n screen.blit(a,(bgColor[0]*2.2,400))\n\n\nbgColor = [10,30,30]\nbg = pygame.Surface(screen.get_size())\nbg = bg.convert()\n\na = pygame.Surface([x/2 for x in size])\n\nrunning = True\nwhile running:\n for e in pygame.event.get():\n if(e.type == pygame.QUIT):\n running = False\n for index,i in enumerate(bgColor):\n bgColor[index] = updateColor(i,index)\n\n bgRender()\n pygame.display.update()\n pygame.time.Clock().tick(FPS)\n\npygame.quit()\nsys.exit()\n\n\n", "repo_name": "JiaLong0209/coding365", "sub_path": "AI_python/base/0714_pygame/pg.py", "file_name": "pg.py", "file_ext": "py", "file_size_in_byte": 923, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pygame.init", "line_number": 7, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 8, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 9, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 9, "usage_type": "attribute"}, {"api_name": "random.random", "line_number": 12, "usage_type": "call"}, {"api_name": "pygame.draw.circle", "line_number": 17, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 17, "usage_type": "attribute"}, {"api_name": "pygame.Surface", "line_number": 23, "usage_type": "call"}, {"api_name": "pygame.Surface", "line_number": 26, "usage_type": "call"}, {"api_name": "pygame.event.get", "line_number": 30, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 30, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 31, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 37, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 37, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 38, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 38, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 40, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 41, "usage_type": "call"}]} +{"seq_id": "18438758762", "text": "import json\r\nimport matplotlib.pyplot as plt\r\n\r\nfilename = 'chapter_16_files\\cpi.json'\r\n\r\nwith open(filename) as f_obj:\r\n cpi_dictlist = json.load(f_obj)\r\n \r\nyears = []\r\ncpis = []\r\n \r\nfor dict in cpi_dictlist:\r\n if dict['Country Name'] == 'Afghanistan':\r\n year = dict['Year']\r\n cpi = float(dict[\"CPI\"])\r\n years.append(year)\r\n cpis.append(cpi)\r\n\r\ncpi_percentages = []\r\nprevious_i = 0\r\n\r\nfor i in cpis:\r\n try:\r\n value = (i/previous_i) - 1\r\n except ZeroDivisionError:\r\n previous_i = i\r\n else:\r\n cpi_percentages.append(value)\r\n previous_i = i\r\ncpi_percentages.insert(0,0)\r\n \r\nfig = plt.figure(dpi=128, figsize=(10, 6))\r\ncolorlist = ['red', 'green', 'blue', 'orange', 'yellow', 'white']\r\ncolor_index = int(0)\r\n\r\nplt.plot(years, cpi_percentages, c='green', alpha=0.5, label='Afghanistan')\r\n\r\nfig.autofmt_xdate()\r\nlegend = plt.legend(loc=2)\r\nplt.title(\"CPI - Afghanistan\", fontsize=20)\r\nplt.xlabel('Year', fontsize=16)\r\nplt.ylabel(\"CPI\", fontsize=16)\r\nplt.tick_params(axis='both', which='major', labelsize=16)\r\n#Run plot.\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n", "repo_name": "wbroach/python_work", "sub_path": "cpi.py", "file_name": "cpi.py", "file_ext": "py", "file_size_in_byte": 1122, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "json.load", "line_number": 7, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tick_params", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}]} +{"seq_id": "12889302214", "text": "import logging\n\nimport pytest\n\nfrom pystac import Asset, Catalog, Collection, Item, Link\nfrom pystac.errors import ExtensionNotImplemented\nfrom pystac.extensions.ext import (\n EXTENSION_NAME_MAPPING,\n EXTENSION_NAMES,\n AssetExt,\n CatalogExt,\n CollectionExt,\n ItemExt,\n LinkExt,\n)\nfrom tests.conftest import get_data_file\n\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger()\n\n\n@pytest.fixture\ndef eo_ext_item() -> Item:\n ext_item_uri = get_data_file(\"eo/eo-landsat-example.json\")\n return Item.from_file(ext_item_uri)\n\n\ndef test_ext_syntax_has(eo_ext_item: Item) -> None:\n assert eo_ext_item.ext.has(\"eo\") is True\n assert eo_ext_item.ext.has(\"proj\") is False\n\n assert eo_ext_item.assets[\"B1\"].ext.has(\"eo\") is True\n assert eo_ext_item.assets[\"B1\"].ext.has(\"proj\") is False\n\n\ndef test_ext_syntax_raises_if_ext_not_on_obj(eo_ext_item: Item) -> None:\n with pytest.raises(ExtensionNotImplemented):\n eo_ext_item.ext.proj.epsg\n\n\ndef test_ext_syntax_ext_can_be_added(eo_ext_item: Item) -> None:\n eo_ext_item.ext.add(\"proj\")\n assert eo_ext_item.ext.proj.epsg is None\n\n\ndef test_ext_syntax_trying_to_add_invalid_ext_raises(item: Item) -> None:\n with pytest.raises(KeyError, match=\"Extension 'foo' is not a valid extension\"):\n item.ext.add(\"foo\") # type: ignore\n\n\ndef test_ext_syntax_ext_can_be_removed(eo_ext_item: Item) -> None:\n original_n = len(eo_ext_item.stac_extensions)\n eo_ext_item.ext.remove(\"eo\")\n with pytest.raises(\n ExtensionNotImplemented, match=\"Extension 'eo' is not implemented\"\n ):\n eo_ext_item.ext.eo\n assert len(eo_ext_item.stac_extensions) == original_n - 1\n\n\nall_link_ext_props = {a for a in dir(LinkExt) if not a.startswith(\"_\")} - {\n \"has\",\n \"add\",\n \"remove\",\n}\nall_asset_ext_props = {a for a in dir(AssetExt) if not a.startswith(\"_\")} - {\n \"has\",\n \"add\",\n \"remove\",\n}\nall_item_ext_props = {a for a in dir(ItemExt) if not a.startswith(\"_\")} - {\n \"has\",\n \"add\",\n \"remove\",\n}\nall_collection_ext_props = {a for a in dir(CollectionExt) if not a.startswith(\"_\")} - {\n \"has\",\n \"add\",\n \"remove\",\n}\nall_catalog_ext_props = {a for a in dir(CatalogExt) if not a.startswith(\"_\")} - {\n \"has\",\n \"add\",\n \"remove\",\n}\n\n\n@pytest.mark.parametrize(\"name\", all_link_ext_props)\ndef test_ext_syntax_every_prop_can_be_added_to_link(\n link: Link, name: EXTENSION_NAMES\n) -> None:\n assert link.ext.has(name) is False\n link.ext.add(name)\n assert link.ext.has(name) is True\n link.ext.remove(name)\n with pytest.raises(\n ExtensionNotImplemented, match=f\"Extension '{name}' is not implemented\"\n ):\n getattr(link.ext, name)\n\n\n@pytest.mark.parametrize(\"name\", all_asset_ext_props)\ndef test_ext_syntax_every_prop_can_be_added_to_asset(\n asset: Asset, name: EXTENSION_NAMES\n) -> None:\n assert asset.ext.has(name) is False\n asset.ext.add(name)\n assert asset.ext.has(name) is True\n asset.ext.remove(name)\n with pytest.raises(\n ExtensionNotImplemented, match=f\"Extension '{name}' is not implemented\"\n ):\n getattr(asset.ext, name)\n\n\n@pytest.mark.parametrize(\"name\", all_item_ext_props)\ndef test_ext_syntax_every_prop_can_be_added_to_item(\n item: Item, name: EXTENSION_NAMES\n) -> None:\n assert item.ext.has(name) is False\n item.ext.add(name)\n assert item.ext.has(name) is True\n item.ext.remove(name)\n with pytest.raises(\n ExtensionNotImplemented, match=f\"Extension '{name}' is not implemented\"\n ):\n getattr(item.ext, name)\n\n\n@pytest.mark.parametrize(\"name\", all_collection_ext_props)\ndef test_ext_syntax_every_prop_can_be_added_to_collection(\n collection: Collection, name: EXTENSION_NAMES\n) -> None:\n assert collection.ext.has(name) is False\n collection.ext.add(name)\n assert collection.ext.has(name) is True\n collection.ext.remove(name)\n with pytest.raises(\n ExtensionNotImplemented, match=f\"Extension '{name}' is not implemented\"\n ):\n getattr(collection.ext, name)\n\n\n@pytest.mark.parametrize(\"name\", all_catalog_ext_props)\ndef test_ext_syntax_every_prop_can_be_added_to_catalog(\n catalog: Catalog, name: EXTENSION_NAMES\n) -> None:\n assert catalog.ext.has(name) is False\n catalog.ext.add(name)\n assert catalog.ext.has(name) is True\n catalog.ext.remove(name)\n with pytest.raises(\n ExtensionNotImplemented, match=f\"Extension '{name}' is not implemented\"\n ):\n getattr(catalog.ext, name)\n\n\ndef test_ext_syntax_every_name_has_a_prop() -> None:\n assert {\n *all_asset_ext_props,\n *all_item_ext_props,\n *all_collection_ext_props,\n } == set(EXTENSION_NAME_MAPPING.keys())\n", "repo_name": "stac-utils/pystac", "sub_path": "tests/extensions/test_ext.py", "file_name": "test_ext.py", "file_ext": "py", "file_size_in_byte": 4699, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 285, "dataset": "github-code", "pt": "24", "api": [{"api_name": "logging.basicConfig", "line_number": 18, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 18, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 19, "usage_type": "call"}, {"api_name": "tests.conftest.get_data_file", "line_number": 24, "usage_type": "call"}, {"api_name": "pystac.Item.from_file", "line_number": 25, "usage_type": "call"}, {"api_name": "pystac.Item", "line_number": 25, "usage_type": "name"}, {"api_name": "pytest.fixture", "line_number": 22, "usage_type": "attribute"}, {"api_name": "pystac.Item", "line_number": 23, "usage_type": "name"}, {"api_name": "pystac.Item", "line_number": 28, "usage_type": "name"}, {"api_name": "pystac.Item", "line_number": 36, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 37, "usage_type": "call"}, {"api_name": "pystac.errors.ExtensionNotImplemented", "line_number": 37, "usage_type": "argument"}, {"api_name": "pystac.Item", "line_number": 41, "usage_type": "name"}, {"api_name": "pystac.Item", "line_number": 46, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 47, "usage_type": "call"}, {"api_name": "pystac.Item", "line_number": 51, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 54, "usage_type": "call"}, {"api_name": "pystac.errors.ExtensionNotImplemented", "line_number": 55, "usage_type": "argument"}, {"api_name": "pystac.extensions.ext.LinkExt", "line_number": 61, "usage_type": "argument"}, {"api_name": "pystac.extensions.ext.AssetExt", "line_number": 66, "usage_type": "argument"}, {"api_name": "pystac.extensions.ext.ItemExt", "line_number": 71, "usage_type": "argument"}, {"api_name": "pystac.extensions.ext.CollectionExt", "line_number": 76, "usage_type": "argument"}, {"api_name": "pystac.extensions.ext.CatalogExt", "line_number": 81, "usage_type": "argument"}, {"api_name": "pystac.Link", "line_number": 90, "usage_type": "name"}, {"api_name": "pystac.extensions.ext.EXTENSION_NAMES", "line_number": 90, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 96, "usage_type": "call"}, {"api_name": "pystac.errors.ExtensionNotImplemented", "line_number": 97, "usage_type": "argument"}, {"api_name": "pytest.mark.parametrize", "line_number": 88, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 88, "usage_type": "attribute"}, {"api_name": "pystac.Asset", "line_number": 104, "usage_type": "name"}, {"api_name": "pystac.extensions.ext.EXTENSION_NAMES", "line_number": 104, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 110, "usage_type": "call"}, {"api_name": "pystac.errors.ExtensionNotImplemented", "line_number": 111, "usage_type": "argument"}, {"api_name": "pytest.mark.parametrize", "line_number": 102, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 102, "usage_type": "attribute"}, {"api_name": "pystac.Item", "line_number": 118, "usage_type": "name"}, {"api_name": "pystac.extensions.ext.EXTENSION_NAMES", "line_number": 118, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 124, "usage_type": "call"}, {"api_name": "pystac.errors.ExtensionNotImplemented", "line_number": 125, "usage_type": "argument"}, {"api_name": "pytest.mark.parametrize", "line_number": 116, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 116, "usage_type": "attribute"}, {"api_name": "pystac.Collection", "line_number": 132, "usage_type": "name"}, {"api_name": "pystac.extensions.ext.EXTENSION_NAMES", "line_number": 132, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 138, "usage_type": "call"}, {"api_name": "pystac.errors.ExtensionNotImplemented", "line_number": 139, "usage_type": "argument"}, {"api_name": "pytest.mark.parametrize", "line_number": 130, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 130, "usage_type": "attribute"}, {"api_name": "pystac.Catalog", "line_number": 146, "usage_type": "name"}, {"api_name": "pystac.extensions.ext.EXTENSION_NAMES", "line_number": 146, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 152, "usage_type": "call"}, {"api_name": "pystac.errors.ExtensionNotImplemented", "line_number": 153, "usage_type": "argument"}, {"api_name": "pytest.mark.parametrize", "line_number": 144, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 144, "usage_type": "attribute"}, {"api_name": "pystac.extensions.ext.EXTENSION_NAME_MAPPING.keys", "line_number": 163, "usage_type": "call"}, {"api_name": "pystac.extensions.ext.EXTENSION_NAME_MAPPING", "line_number": 163, "usage_type": "name"}]} +{"seq_id": "23697644158", "text": "import numpy as np\nimport random\nimport torch\nimport torch.nn as nn\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch import optim\nfrom torch.utils.data import TensorDataset\nfrom torch.utils.data import DataLoader\nfrom torch import linalg as LA\nimport torch\nfrom torch.nn import functional as F, Parameter\nfrom torch.autograd import Variable\nfrom collections import Counter\nfrom torch.nn.init import xavier_normal_, xavier_uniform_\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\nimport random\nimport timeit\nimport shutil\nimport subprocess\nimport matplotlib.pyplot as plt\nimport math\nimport pathlib\nimport os\nfrom distutils.dir_util import copy_tree\n\n\ndef read_dataset(dataset):\n train = open('data/' + dataset+ '/train2id.txt').readlines()[1:]\n train = [i.split() for i in train]\n test = open('data/' + dataset+ '/test2id.txt').readlines()[1:]\n test = [i.split() for i in test]\n valid = open('data/' + dataset+ '/valid2id.txt').readlines()[1:]\n valid = [i.split() for i in valid]\n train = [[int(i),int(k),int(j)] for i,j,k in train]\n test = [[int(i),int(k),int(j)] for i,j,k in test ]\n valid = [[int(i),int(k),int(j)] for i,j,k in valid]\n WholeGraph = train+valid+test\n return train,valid,test,WholeGraph\n \n# def dataset_creator(train,test,valid,name = 'dataset'): \n# pathlib.Path('/content/dataset').mkdir(parents=True, exist_ok=True) \n# # create dataset in a format that suitable for openke\n# shutil.copy('/content/OpenKE/benchmarks/FB13/n-n.py', '/content/'+name)\n\n# graph = train + test + valid\n# entities = [i[0] for i in graph] + [i[2] for i in graph] \n# relations= [i[1] for i in graph]\n# entities = list(set(entities))\n# relations = list(set(relations))\n# ent_dict = {}\n# for i in range(len(entities)):\n# ent_dict[entities[i]] = i\n# rel_dict = {}\n# for i in range(len(relations)):\n# rel_dict[relations[i]] = i \n \n# f1 = open('/content/'+name+'/entity2id.txt','w')\n# f1.write(str(len(ent_dict))+'\\n')\n# for k,v in ent_dict.items():\n# f1.write(str(k)+'\\t'+str(v)+ '\\n')\n# f1.close()\n\n# f1 = open('/content/'+name+'/relation2id.txt','w')\n# f1.write(str(len(rel_dict))+'\\n')\n# for k,v in rel_dict.items():\n# f1.write(str(k)+'\\t'+str(v)+ '\\n')\n# f1.close()\n\n\n# f1 = open('/content/'+name+'/train2id.txt','w')\n# f1.write(str(len(train))+'\\n')\n# for row in train:\n# f1.write(str(ent_dict[row[0]])+' '+str(ent_dict[row[2]])+' '+str(rel_dict[row[1]])+'\\n')\n\n# f1.close()\n\n# f1 = open('/content/'+name+'/test2id.txt','w')\n# f1.write(str(len(test))+'\\n')\n# for row in test:\n# f1.write(str(ent_dict[row[0]])+' '+str(ent_dict[row[2]])+' '+str(rel_dict[row[1]])+'\\n')\n# f1.close() \n\n# f1 = open('/content/'+name+'/valid2id.txt','w')\n# f1.write(str(len(valid))+'\\n')\n# for row in valid:\n# f1.write(str(ent_dict[row[0]])+' '+str(ent_dict[row[2]])+' '+str(rel_dict[row[1]])+'\\n')\n# f1.close() \n\n# subprocess.call(\"/content/\"+name+\"/n-n.py.py\", shell=True)\n\ndef dataset_creator(train,test,valid,Whole_graph = [],name = 'dataset'): \n pathlib.Path('/content/dataset').mkdir(parents=True, exist_ok=True) \n # create dataset in a format that suitable for openke\n shutil.copy('/content/OpenKE/benchmarks/FB13/n-n.py', '/content/'+name)\n\n graph = train + test + valid + Whole_graph\n entities = [i[0] for i in graph] + [i[2] for i in graph] \n relations= [i[1] for i in graph]\n entities = list(set(entities))\n relations = list(set(relations))\n ent_dict = {}\n for i in range(len(entities)):\n ent_dict[entities[i]] = i\n rel_dict = {}\n for i in range(len(relations)):\n rel_dict[relations[i]] = i \n \n f1 = open('/content/'+name+'/entity2id.txt','w')\n f1.write(str(len(ent_dict))+'\\n')\n for k,v in ent_dict.items():\n f1.write(str(k)+'\\t'+str(v)+ '\\n')\n f1.close()\n\n f1 = open('/content/'+name+'/relation2id.txt','w')\n f1.write(str(len(rel_dict))+'\\n')\n for k,v in rel_dict.items():\n f1.write(str(k)+'\\t'+str(v)+ '\\n')\n f1.close()\n\n\n f1 = open('/content/'+name+'/train2id.txt','w')\n f1.write(str(len(train))+'\\n')\n for row in train:\n f1.write(str(ent_dict[row[0]])+' '+str(ent_dict[row[2]])+' '+str(rel_dict[row[1]])+'\\n')\n\n f1.close()\n\n f1 = open('/content/'+name+'/test2id.txt','w')\n f1.write(str(len(test))+'\\n')\n for row in test:\n f1.write(str(ent_dict[row[0]])+' '+str(ent_dict[row[2]])+' '+str(rel_dict[row[1]])+'\\n')\n f1.close() \n\n f1 = open('/content/'+name+'/valid2id.txt','w')\n f1.write(str(len(valid))+'\\n')\n for row in valid:\n f1.write(str(ent_dict[row[0]])+' '+str(ent_dict[row[2]])+' '+str(rel_dict[row[1]])+'\\n')\n f1.close() \n\n subprocess.call(\"/content/\"+name+\"/n-n.py.py\", shell=True)\n\ndef n2n_py():\n lef = {}\n rig = {}\n rellef = {}\n relrig = {}\n\n triple = open(\"train2id.txt\", \"r\")\n valid = open(\"valid2id.txt\", \"r\")\n test = open(\"test2id.txt\", \"r\")\n\n tot = (int)(triple.readline())\n for i in range(tot):\n content = triple.readline()\n h,t,r = content.strip().split()\n if not (h,r) in lef:\n lef[(h,r)] = []\n if not (r,t) in rig:\n rig[(r,t)] = []\n lef[(h,r)].append(t)\n rig[(r,t)].append(h)\n if not r in rellef:\n rellef[r] = {}\n if not r in relrig:\n relrig[r] = {}\n rellef[r][h] = 1\n relrig[r][t] = 1\n\n tot = (int)(valid.readline())\n for i in range(tot):\n content = valid.readline()\n h,t,r = content.strip().split()\n if not (h,r) in lef:\n lef[(h,r)] = []\n if not (r,t) in rig:\n rig[(r,t)] = []\n lef[(h,r)].append(t)\n rig[(r,t)].append(h)\n if not r in rellef:\n rellef[r] = {}\n if not r in relrig:\n relrig[r] = {}\n rellef[r][h] = 1\n relrig[r][t] = 1\n\n tot = (int)(test.readline())\n for i in range(tot):\n content = test.readline()\n h,t,r = content.strip().split()\n if not (h,r) in lef:\n lef[(h,r)] = []\n if not (r,t) in rig:\n rig[(r,t)] = []\n lef[(h,r)].append(t)\n rig[(r,t)].append(h)\n if not r in rellef:\n rellef[r] = {}\n if not r in relrig:\n relrig[r] = {}\n rellef[r][h] = 1\n relrig[r][t] = 1\n\n test.close()\n valid.close()\n triple.close()\n\n f = open(\"type_constrain.txt\", \"w\")\n f.write(\"%d\\n\"%(len(rellef)))\n for i in rellef:\n f.write(\"%s\\t%d\"%(i,len(rellef[i])))\n for j in rellef[i]:\n f.write(\"\\t%s\"%(j))\n f.write(\"\\n\")\n f.write(\"%s\\t%d\"%(i,len(relrig[i])))\n for j in relrig[i]:\n f.write(\"\\t%s\"%(j))\n f.write(\"\\n\")\n f.close()\n\n rellef = {}\n totlef = {}\n relrig = {}\n totrig = {}\n # lef: (h, r)\n # rig: (r, t)\n for i in lef:\n if not i[1] in rellef:\n rellef[i[1]] = 0\n totlef[i[1]] = 0\n rellef[i[1]] += len(lef[i])\n totlef[i[1]] += 1.0\n\n for i in rig:\n if not i[0] in relrig:\n relrig[i[0]] = 0\n totrig[i[0]] = 0\n relrig[i[0]] += len(rig[i])\n totrig[i[0]] += 1.0\n\n s11=0\n s1n=0\n sn1=0\n snn=0\n f = open(\"test2id.txt\", \"r\")\n tot = (int)(f.readline())\n for i in range(tot):\n content = f.readline()\n h,t,r = content.strip().split()\n rign = rellef[r] / totlef[r]\n lefn = relrig[r] / totrig[r]\n if (rign < 1.5 and lefn < 1.5):\n s11+=1\n if (rign >= 1.5 and lefn < 1.5):\n s1n+=1\n if (rign < 1.5 and lefn >= 1.5):\n sn1+=1\n if (rign >= 1.5 and lefn >= 1.5):\n snn+=1\n f.close()\n\n\n f = open(\"test2id.txt\", \"r\")\n f11 = open(\"1-1.txt\", \"w\")\n f1n = open(\"1-n.txt\", \"w\")\n fn1 = open(\"n-1.txt\", \"w\")\n fnn = open(\"n-n.txt\", \"w\")\n fall = open(\"test2id_all.txt\", \"w\")\n tot = (int)(f.readline())\n fall.write(\"%d\\n\"%(tot))\n f11.write(\"%d\\n\"%(s11))\n f1n.write(\"%d\\n\"%(s1n))\n fn1.write(\"%d\\n\"%(sn1))\n fnn.write(\"%d\\n\"%(snn))\n for i in range(tot):\n content = f.readline()\n h,t,r = content.strip().split()\n rign = rellef[r] / totlef[r]\n lefn = relrig[r] / totrig[r]\n if (rign < 1.5 and lefn < 1.5):\n f11.write(content)\n fall.write(\"0\"+\"\\t\"+content)\n if (rign >= 1.5 and lefn < 1.5):\n f1n.write(content)\n fall.write(\"1\"+\"\\t\"+content)\n if (rign < 1.5 and lefn >= 1.5):\n fn1.write(content)\n fall.write(\"2\"+\"\\t\"+content)\n if (rign >= 1.5 and lefn >= 1.5):\n fnn.write(content)\n fall.write(\"3\"+\"\\t\"+content)\n fall.close()\n f.close()\n f11.close()\n f1n.close()\n fn1.close()\n fnn.close()\n \ndef Cut_graph(dataset):\n population_size = 100\n generations = 10\n temp = 4000 # init temprature\n good_ppl_rate = 0.6 #0.65\n train,valid,test,Graph = read_dataset(dataset)\n WholeGraph = Graph\n Entities = {}\n for i,j,k in WholeGraph:\n if i not in Entities:\n Entities[i] = 1\n if k not in Entities:\n Entities[k] = 1 \n def my_sigmoid(x):\n t = 1 / (1 + math.exp(-(x/3)))\n return 2*(1 -( t ))\n Entity_count = len(Entities.keys())\n matrix = {}\n for i in range(len(Graph)):\n head = Graph[i][0]\n tail = Graph[i][2]\n if head not in matrix:\n matrix[head] = []\n matrix[head].append(tail)\n elif tail not in matrix[head]:\n matrix[head].append(tail)\n for i in range(len(Graph)):\n tail = Graph[i][0]\n head = Graph[i][2]\n # tail, head = head, tail\n if head not in matrix:\n matrix[head] = []\n matrix[head].append(tail)\n elif tail not in matrix[head]:\n matrix[head].append(tail)\n Components = []\n graph_bfs = []\n for k,v in matrix.items():\n graph_bfs.append([k]+v)\n Entities = {}\n for i,j,k in WholeGraph:\n if i not in Entities:\n Entities[i] = 1\n if k not in Entities:\n Entities[k] = 1 \n def get_vertices(WholeGraph):\n return list(range(Entity_count))\n def random_split(V,sample_size = 200, matrix = matrix): # mutation\n V1,V2 = V[:int(len(V)/2)],V[int(len(V)/2):]\n S1 = random.sample(range(1, len(V1)), sample_size)\n S2 = random.sample(range(1, len(V2)), sample_size)\n t1 = [V1[i] for i in S1] # changes (remove from set 1)\n t2 = [V2[i] for i in S2]\n t1 = {i:1 for i in t1}\n t2 = {i:1 for i in t2}\n V1_new = [i for i in V1 if i not in t1]\n V2_new = [i for i in V2 if i not in t2]\n V1_new += list(t2.keys())\n V2_new += list(t1.keys())\n V1_new = {i:1 for i in V1_new}\n V2_new = {i:1 for i in V2_new}\n v_cuts = 0\n for k,v in V1_new.items():\n if k in matrix:\n for i in matrix[k]:\n if i in V2_new:\n v_cuts += 1\n return list(V1_new.keys()), list(V2_new.keys()),v_cuts\n city = []\n V = get_vertices(WholeGraph)\n for i in range(population_size):\n temp = int(temp*my_sigmoid(j))\n v1,v2,cut = random_split(V,temp)\n city.append([v1,v2,cut])\n for j in range(generations):\n city = sorted(city,key=lambda l:l[-1])\n city = city[:population_size]\n temp = int(temp*my_sigmoid(j))\n print([sorted([int(i[-1]) for i in city])[:10],sum([i[-1] for i in city])])\n death_cut = sorted([i[-1] for i in city])[int(len(city)*good_ppl_rate)-1]\n city = [i for i in city if i[-1] <= death_cut]\n new_ppl = []\n for i in range(len(city)):\n V1,V2 = city[i][0],city[i][1]\n v1,v2,cut = random_split(V1+V2,temp)\n new_ppl.append([v1,v2,cut])\n city += new_ppl\n immigs = []\n # for i in range(population_size-len(city)):\n for i in range(40):\n V11 = list(V)\n random.shuffle(V11)\n v1,v2,cut = random_split(V11,temp)\n immigs.append([v1,v2,cut])\n city += immigs\n return city[0]\n# V1,V2,cut = Cut_graph(dataset)\n\n\n\ndef remove_coonections_of_graphs(v1,v2,train,test,valid,rate = 0.01):\n train_exp1 = [] # for two disjoint graph\n valid_exp1 = [] # test set\n test_exp1 = [] # for 2 disjoint graphs in test\n AliSalim_Test = [] # for connections in between\n V1 = {}\n for item in v1:\n V1[item] = 1\n V2 = {}\n for item in v2:\n V2[item] = 1 \n removed = []\n for row in train:\n h,r,t = row\n if h in V1 and t in V2:\n removed.append(row)\n continue\n if h in V2 and t in V1:\n removed.append(row)\n continue\n train_exp1.append(row)\n random.shuffle(removed)\n train_exp1 = train_exp1 + removed[:int(len(removed) * rate)]\n for row in test:\n h,r,t = row\n if h in V1 and t in V2:\n continue\n if h in V2 and t in V1:\n continue\n test_exp1.append(row)\n\n# for row in test:\n# h,r,t = row\n# if h in V1 and t in V2:\n# AliSalim_Test.append(row)\n# if h in V2 and t in V1:\n# AliSalim_Test.append(row)\n\n for row in test:\n valid_exp1.append(row)\n \n \n AliSalim_Test = [i for i in valid_exp1 if i not in test_exp1]\n return train_exp1,valid_exp1, test_exp1,AliSalim_Test \n\n\ndef prepare_dataset4exprement(dataset):\n train,valid,test,WholeGraph = read_dataset(dataset)\n dataset_creator(train,test,valid)\n os.chdir('/content/dataset')\n n2n_py()\n os.chdir('/content')\n\n\ndef Prepare_data_into_files_for_exprement(train_exp1,valid_exp1, test_exp1,test3,WholeGraph):\n try: \n shutil.rmtree('/content/OpenKE/benchmarks/dataset_test1')\n except:\n pass\n try: \n shutil.rmtree('/content/OpenKE/benchmarks/dataset_test2')\n except:\n pass\n\n try: \n shutil.rmtree('/content/OpenKE/benchmarks/dataset_test3')\n except:\n pass\n \n# _,_,_,WholeGraph = read_dataset(dataset)\n #this is the last stage, takes files and create 2-3 datasets for running exprements\n pathlib.Path('dataset_test3').mkdir(parents=True, exist_ok=True) \n dataset_creator(train_exp1,test3,test3,WholeGraph,'dataset_test3')\n os.chdir('dataset_test3')\n n2n_py()\n os.chdir('..')\n\n #test2\n pathlib.Path('dataset_test2').mkdir(parents=True, exist_ok=True) \n dataset_creator(train_exp1,test_exp1,valid_exp1,WholeGraph,'dataset_test2')\n os.chdir('dataset_test2')\n n2n_py()\n os.chdir('..')\n\n\n # test1\n pathlib.Path('dataset_test1').mkdir(parents=True, exist_ok=True) \n dataset_creator(train_exp1,valid_exp1,test_exp1,WholeGraph,'dataset_test1')\n os.chdir('dataset_test1')\n n2n_py()\n os.chdir('..')\n \n \n shutil.copytree('/content/dataset_test1', '/content/OpenKE/benchmarks/dataset_test1') \n shutil.copytree('/content/dataset_test2', '/content/OpenKE/benchmarks/dataset_test2') \n shutil.copytree('/content/dataset_test3', '/content/OpenKE/benchmarks/dataset_test3') \n \n try: \n shutil.rmtree('/content/dataset_test1')\n except:\n pass\n try: \n shutil.rmtree('/content/dataset_test2')\n except:\n pass\n\n try: \n shutil.rmtree('/content/dataset_test3')\n except:\n pass\n\n", "repo_name": "saeedizade/LinkPrediction_Interpretability", "sub_path": "Utils.py", "file_name": "Utils.py", "file_ext": "py", "file_size_in_byte": 14277, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pathlib.Path", "line_number": 93, "usage_type": "call"}, {"api_name": "shutil.copy", "line_number": 95, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 141, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 313, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 348, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 349, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 390, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 420, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 448, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 450, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 455, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 459, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 464, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 470, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 472, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 474, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 477, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 479, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 481, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 485, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 487, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 489, "usage_type": "call"}, {"api_name": "shutil.copytree", "line_number": 492, "usage_type": "call"}, {"api_name": "shutil.copytree", "line_number": 493, "usage_type": "call"}, {"api_name": "shutil.copytree", "line_number": 494, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 497, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 501, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 506, "usage_type": "call"}]} +{"seq_id": "22243365644", "text": "#######################################################################################################################\r\n#######################################################################################################################\r\n# # NOTES #\r\n#\r\n# Date: 05.11.2019\r\n# Creator: Florian Schneider\r\n#\r\n# Important: To download packages exit the Internal EY Network (e.g.\r\n# use your Mobile to create a HotSpot\r\n#\r\n#######################################################################################################################\r\n#######################################################################################################################\r\n\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nimport seaborn as sns\r\n\r\ndf_tweets = pd.read_csv(\"DT_Tweets_0516_0219 - SMALL.csv\")\r\ndf_tweets.tail()\r\ndf_tweets.head()\r\n\r\n# Combining two datasets\r\n# df_combined = pd.merge(dataset1, dataset2, left_index=True, right_index=True)\r\n\r\n\r\ndf_tweets['Month'] = pd.to_datetime(df_tweets['created_at']).dt.month\r\ndf_tweets['Weekday'] = pd.to_datetime(df_tweets['created_at']).dt.weekday\r\ndf_tweets['Hour'] = pd.to_datetime(df_tweets['created_at']).dt.hour\r\ndf_tweets.head()\r\n\r\n# Sentiment Analysis\r\n\r\n## Step 1: Identification of the most favourite tweet\r\nfav_tweets = np.max(df_tweets['favorite_count'])\r\nprint(fav_tweets)\r\n\r\nfav = df_tweets[df_tweets.favorite_count == fav_tweets].index[0]\r\n#print(fav)\r\nprint(\"The tweet with most likes/favourite counts is: \\n{}\".format(df_tweets['text'][fav]))\r\n\r\n# Identification of the top 3 tweets (according to the number of likes)\r\nfav3_tweets = df_tweets['favorite_count'].nlargest(3)\r\n#print(fav3_tweets)\r\nprint('The three most likes tweets of Trump are: \\n{}'.format(df_tweets['text'][fav3_tweets]))\r\n\r\n## Step 2: Identification of the most retweeted tweet\r\nrt_max = np.max(df_tweets['retweet_count'])\r\nprint(rt_max)\r\n\r\nID_rt_max = df_tweets[df_tweets.retweet_count == rt_max].index[0]\r\nprint(\"The tweet with the most retweets is: \\n{}\".format(df_tweets['text'][ID_rt_max]))\r\n\r\n## Step 3: Sentiment Analysis with the Natural Language Toolkit (NLTK)\r\nimport nltk\r\nfrom nltk.sentiment import SentimentIntensityAnalyzer\r\nnltk.download('vader_lexicon')\r\n\r\n# For analyzing A SINGLE STRING the following code can be used:\r\nnltk.sentiment.util.demo_vader_instance('''RT @cvpayne: While the media is fixated on tweets and fear mongering here's'\r\n 'are some employment stats for Black American in July''')\r\nnltk.sentiment.util.demo_vader_instance('It was great being with Luther Strange last night in Alabama. What great '\r\n 'people what a crowd! Vote Luther on Tuesday.')\r\n\r\n# For analyzing A WHOLE ARRAY the following code can be used:\r\n# Yet first the Dataframe must be transformed into an Array\r\nfrom nltk.corpus import twitter_samples\r\n\r\n#text_array = df_tweets[['text']].as_matrix()\r\n#print(len(text_array))\r\n\r\n#strings = str(text_array)\r\n#print(strings)\r\n#print(len(strings))\r\n#nltk.sentiment.util.demo_vader_instance(strings)\r\n\r\n# Performing the sentiment analysis for all of the rows in the twitter post dataframe\r\nimport nltk\r\nnltk.download('stopwords')\r\nnltk.download('opinion_lexicon')\r\nfrom nltk.corpus import stopwords\r\nstop = set(stopwords.words('english'))\r\nfrom nltk import sentiment\r\n############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n## !!! The execution of the following line take app. 1.5 hours for the full dataset\r\n\r\n# Schleife aufbauen, welche über die tweets geht pro position und es ins entsprechende Feld schreibt+++++++++++++++++++++++++++++++++ SPACY auch testen ANSTELLE VON NLTK!!! BeautifulSoup (Victoria sendet einen link)\r\n\r\ndf_tweets['SentimentsAnalyzed'] = (df_tweets['text'].apply(nltk.sentiment.util.demo_liu_hu_lexicon))\r\ndf_tweets['SentimentsAnalyzed'].to_csv('DT_Tweets_0516_0219_SA_Done.csv')\r\n\r\nSA = pd.read_csv('DT_Tweets_0516_0219_SA_Done.csv')\r\n\r\ndf_tweets.head()\r\n\r\n############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n\r\ninput_file = 'DT_Tweets_0516_0219 - SMALL.csv'\r\nSA = pd.read_csv(input_file)\r\nSA.head()\r\n\r\n\r\n\r\n# Combining the tweet dataframe with the sentiment dataframe\r\ntweets_SA = pd.merge(df_tweets, SA, left_index=True, right_index=True)\r\ntweets_SA.head()\r\n\r\n\r\n\r\n# Definition of custom colour palettes for charts in future\r\nplt.rcdefaults()\r\nown_palette_1= [\"g\", \"#FFD700\", \"#FF6347\", \"#1E90FF\"]\r\nsns.set_palette(own_palette_1)\r\nsns.palplot(sns.color_palette())\r\nown_palette_2= [ \"#FFD700\", \"#FF6347\", \"g\", \"#1E90FF\"]\r\nsns.set_palette(own_palette_2)\r\nsns.palplot(sns.color_palette())\r\nown_palette_3= [ \"#FF6347\", \"#FFD700\", \"g\", \"#1E90FF\"]\r\nsns.set_palette(own_palette_3)\r\nsns.palplot(sns.color_palette())\r\nplt.show()\r\n\r\n\r\n# How many tweets have been neutral, positive oder negative?\r\ntweets_SA.Sentiment.value_counts()\r\n\r\n\r\npd.Series(tweets_SA[\"Sentiment\"]).value_counts().plot(kind = \"bar\", width=0.7,\r\n figsize=(16,4),fontsize=15, color='#1E90FF', title = \"Sentiments in Donald Trump's tweets: May 2016 - May2018\" )\r\n#plt.xlabel('Sentiment', fontsize=10)\r\nplt.ylabel('Nr. of tweets', fontsize=15);\r\nplt.show()\r\n\r\n\r\n# Plot the percentage of the sentiments into a pie chart\r\npd.Series(tweets_SA[\"Sentiment\"]).value_counts().plot(kind=\"pie\", colors=sns.color_palette(own_palette_1, 10),\r\n labels=[\"Positive\", \"Neutral\", \"Negative\", \"Positive\"],\r\n shadow=True,autopct='%.1f%%', fontsize=15,figsize=(6, 6))\r\nplt.title(\"Percentage of tweets of each sentiment\", fontsize=20);\r\nplt.show()\r\n\r\n\r\n# Hour of day vs sentiment - Plotted as Crosstable\r\nhour_of_day =pd.crosstab(tweets_SA.Hour, tweets_SA.Sentiment)\r\nhour_of_day\r\n# Hour of day vs sentiment - Plotted as Bar chart\r\npd.crosstab(index = tweets_SA[\"Hour\"],columns = tweets_SA[\"Sentiment\"]).plot(kind='bar',fontsize=15, color=sns.color_palette(own_palette_3, 10),\r\n figsize=(16, 6),alpha=0.5,rot=0,width=0.7, stacked=True,title=\"Tweets per hour of the day\")\r\nplt.title(\"Tweets per hour of the day\", fontsize=20)\r\nplt.xlabel('Hour', fontsize=15)\r\nplt.ylabel('Nr of tweets', fontsize=15)\r\nplt.legend(fontsize=15);\r\nplt.show()\r\n\r\n# todo Tokenization\r\n# todo Lemmatization\r\n# todo Map the sentiments to the top 10 european DAX shares (Condition: economically involved in the USA) [Maybe Automotive OEMs, Pharmaceutical Companies]\r\n", "repo_name": "FSchneider91/Twitter-Streaming-Sentiment-Analysis", "sub_path": "DT_SA_Twitter.py", "file_name": "DT_SA_Twitter.py", "file_ext": "py", "file_size_in_byte": 7154, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pandas.read_csv", "line_number": 20, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 28, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 29, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 49, "usage_type": "call"}, {"api_name": "nltk.download", "line_number": 58, "usage_type": "call"}, {"api_name": "nltk.sentiment.util.demo_vader_instance", "line_number": 61, "usage_type": "call"}, {"api_name": "nltk.sentiment", "line_number": 61, "usage_type": "attribute"}, {"api_name": "nltk.sentiment.util.demo_vader_instance", "line_number": 63, "usage_type": "call"}, {"api_name": "nltk.sentiment", "line_number": 63, "usage_type": "attribute"}, {"api_name": "nltk.download", "line_number": 80, "usage_type": "call"}, {"api_name": "nltk.download", "line_number": 81, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 83, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 83, "usage_type": "name"}, {"api_name": "nltk.sentiment", "line_number": 92, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 95, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 104, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.rcdefaults", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}, {"api_name": "seaborn.set_palette", "line_number": 118, "usage_type": "call"}, {"api_name": "seaborn.palplot", "line_number": 119, "usage_type": "call"}, {"api_name": "seaborn.color_palette", "line_number": 119, "usage_type": "call"}, {"api_name": "seaborn.set_palette", "line_number": 121, "usage_type": "call"}, {"api_name": "seaborn.palplot", "line_number": 122, "usage_type": "call"}, {"api_name": "seaborn.color_palette", "line_number": 122, "usage_type": "call"}, {"api_name": "seaborn.set_palette", "line_number": 124, "usage_type": "call"}, {"api_name": "seaborn.palplot", "line_number": 125, "usage_type": "call"}, {"api_name": "seaborn.color_palette", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 126, "usage_type": "name"}, {"api_name": "pandas.Series", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 136, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 136, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 137, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 137, "usage_type": "name"}, {"api_name": "pandas.Series", "line_number": 141, "usage_type": "call"}, {"api_name": "seaborn.color_palette", "line_number": 141, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 144, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 144, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 145, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 145, "usage_type": "name"}, {"api_name": "pandas.crosstab", "line_number": 149, "usage_type": "call"}, {"api_name": "pandas.crosstab", "line_number": 152, "usage_type": "call"}, {"api_name": "seaborn.color_palette", "line_number": 152, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 154, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 154, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 155, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 155, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 156, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 156, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 157, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 157, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 158, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 158, "usage_type": "name"}]} +{"seq_id": "9057144307", "text": "import pytest\nfrom copy import deepcopy\nfrom pprint import pprint\nimport pandas as pd\n\nimport projection\n\n@pytest.fixture\ndef base_eras():\n in_list = [\n {\n 'start': pd.Period('1-2000'),\n 'freq': 3,\n 'repeats': 4,\n 'last': pd.Period('10-2000'),\n 'end': pd.Period('12-2000'),\n },\n\n {\n 'start': pd.Period('1-2001'),\n 'freq': 2,\n 'repeats': 6,\n 'last': pd.Period('11-2001'),\n 'end': pd.Period('12-2001'),\n },\n\n {\n 'start': pd.Period('1-2002'),\n 'freq': 6,\n 'repeats': 2,\n 'last': pd.Period('7-2002'),\n 'end': pd.Period('12-2002'),\n }\n ]\n\n return in_list\n\n \ndef test_in_era(base_eras):\n\n for i, row in enumerate(base_eras):\n print(f'in row {i}')\n for test_var in row:\n t = deepcopy(base_eras)\n print(f'\\n---> setting {test_var} to None')\n t[i][test_var] = None\n\n out = projection.make_eras(t)\n compare(base_eras, out, test_var)\n\n\ndef test_inner(base_eras):\n\n for only_key in ['freq', 'repeats']:\n print(f'trying with only {only_key} in row 1, ', end='')\n only_val = base_eras[1][only_key]\n print(f'value is {only_val}')\n t = deepcopy(base_eras)\n t[1] = {only_key: only_val}\n print(f'new row 1 is {t[1]}')\n\n out = projection.make_eras(t)\n for var in out[1]:\n compare(base_eras, out, t[0].keys())\n\n\ndef compare(base_eras, test_eras, vars_to_print):\n if isinstance(vars_to_print, str):\n vars_to_print = [vars_to_print]\n for i, row in enumerate(base_eras):\n for var in row:\n if var in vars_to_print:\n print(f'row[{(str(i)+\"] \"+var).ljust(12)}{test_eras[i][var]}'\n f': {base_eras[i][var]}')\n assert test_eras[i][var] == base_eras[i][var]\n\n\n", "repo_name": "opi9a/myfin", "sub_path": "projection/test_proj.py", "file_name": "test_proj.py", "file_ext": "py", "file_size_in_byte": 1973, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pandas.Period", "line_number": 12, "usage_type": "call"}, {"api_name": "pandas.Period", "line_number": 15, "usage_type": "call"}, {"api_name": "pandas.Period", "line_number": 16, "usage_type": "call"}, {"api_name": "pandas.Period", "line_number": 20, "usage_type": "call"}, {"api_name": "pandas.Period", "line_number": 23, "usage_type": "call"}, {"api_name": "pandas.Period", "line_number": 24, "usage_type": "call"}, {"api_name": "pandas.Period", "line_number": 28, "usage_type": "call"}, {"api_name": "pandas.Period", "line_number": 31, "usage_type": "call"}, {"api_name": "pandas.Period", "line_number": 32, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 8, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 44, "usage_type": "call"}, {"api_name": "projection.make_eras", "line_number": 48, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 58, "usage_type": "call"}, {"api_name": "projection.make_eras", "line_number": 62, "usage_type": "call"}]} +{"seq_id": "20668227976", "text": "#coding=utf-8\n\nimport matplotlib.pyplot as plot\nimport numpy as np\nimport pandas as pd\nimport sys, getopt, os\n\nN = len(sys.argv)\nprint(\"load %d files of solver time recorder.\" %(N-1))\n\nfiilenames = sys.argv[1:]\nx_labels = list()\n\n\n\n# 读取文件\nsolver_time = list() # 每帧求解时间\nhessian_time = list() # hessian时间\ni=1\nfor file in fiilenames:\n tmp_time = np.loadtxt(file, dtype=np.float32)\n solver_time.append(tmp_time[...,0])\n hessian_time.append(tmp_time[...,1])\n # 获取文件名\n filepath, tmpfilename = os.path.split(sys.argv[i])\n shotname, extention = os.path.splitext(tmpfilename)\n x_labels.append(shotname)\n i = i + 1\n# 使用pandas分析数据\ndf_solver = pd.DataFrame(solver_time)\ndf_hessian = pd.DataFrame(hessian_time)\nprint(df_solver.mean(1))\nprint(df_hessian.mean(1))\n# 绘制求解器耗时统计图\n#solver_time = np.loadtxt(\"../build/solver_cost.txt\", dtype=np.float32)\nfig, axes = plot.subplots(nrows = 2, ncols = 1, figsize=(10,8)) # 两行一列\n\n\naxes[0].violinplot(solver_time, showmeans=False, showmedians=True)\naxes[0].yaxis.grid(True)\naxes[0].set_xlabel(\"solve frame\")\naxes[0].set_ylabel(\"cost(ms)\")\n\naxes[1].violinplot(hessian_time, showmeans=False, showmedians=True)\naxes[1].yaxis.grid(True)\naxes[1].set_xlabel(\"make hessian\")\naxes[1].set_ylabel(\"cost(ms)\")\n# x轴依次画标签三个坐标\nplot.setp(axes, xticks=[y + 1for y in range(len(solver_time))],\n xticklabels=x_labels,);\n\nplot.show();", "repo_name": "yuntianli91/vio_course", "sub_path": "Ch8/tools/time_compare.py", "file_name": "time_compare.py", "file_ext": "py", "file_size_in_byte": 1461, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sys.argv", "line_number": 8, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 11, "usage_type": "attribute"}, {"api_name": "numpy.loadtxt", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 30, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.setp", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}]} +{"seq_id": "795385010", "text": "import torch\nimport math\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\ndef D_classify_loss(output, target):\n e = 1e-8\n # loss=target*torch.log(output)+(1-target)*torch.log(1-output)\n output = torch.exp(output)\n total = torch.sum(output, 1).view(output.size()[0], 1)\n output = torch.log(output/total+e)\n # print(target)\n # print(output)\n output = torch.sum(-target*output, 1)\n return output.mean()\n\n\ndef G_classify_loss(output):\n e = 1e-8\n output = torch.exp(output)\n total = torch.sum(output, 1).view(output.size()[0], 1)\n output = torch.log(output/total+e)\n output = torch.mean(-output, 1)\n return output.mean()\n\n# loss function\n\n\ndef l1_loss(x1, x2):\n loss = torch.abs(x1-x2).mean()\n return loss\n\n\ndef D_real_loss(output, loss_func='lsgan'):\n if(loss_func == 'lsgan'):\n distance = (output-1.0)*(output-1.0)\n loss = distance.mean()\n return loss\n\n if(loss_func == 'wgan'):\n return (-output).mean()\n\n if(loss_func == 'hinge'):\n real_loss = torch.functional.F.relu(1.0 - output).mean()\n return real_loss\n\n\ndef D_fake_loss(output, loss_func='lsgan'):\n if(loss_func == 'lsgan'):\n distance = output*output\n loss = distance.mean()\n return loss\n\n if(loss_func == 'wgan'):\n return output.mean()\n\n if(loss_func == 'hinge'):\n real_loss = torch.functional.F.relu(1.0 + output).mean()\n return real_loss\n\n\ndef G_fake_loss(output, loss_func='lsgan'):\n if(loss_func == 'lsgan'):\n distance = (output-1)*(output-1)\n loss = distance.mean()\n return loss\n\n if(loss_func == 'wgan'):\n return (-output).mean()\n\n if(loss_func == 'hinge'):\n return (-output).mean()\n\n\ndef gradient_penalty(y, x):\n \"\"\"Compute gradient penalty: (L2_norm(dy/dx) - 1)**2.\"\"\"\n weight = torch.ones(y.size()).cuda()\n dydx = torch.autograd.grad(outputs=y,\n inputs=x,\n grad_outputs=weight,\n retain_graph=True,\n create_graph=True,\n only_inputs=True)[0]\n\n dydx = dydx.view(dydx.size(0), -1)\n dydx_l2norm = torch.sqrt(torch.sum(dydx**2, dim=1))\n return torch.mean((dydx_l2norm-1)**2)\n", "repo_name": "ZizhouJia/PDANet", "sub_path": "model_utils/loss_function.py", "file_name": "loss_function.py", "file_ext": "py", "file_size_in_byte": 2304, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 35, "dataset": "github-code", "pt": "24", "api": [{"api_name": "torch.exp", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 11, "usage_type": "call"}, {"api_name": "torch.log", "line_number": 12, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 15, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.log", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.mean", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.abs", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.functional.F.relu", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.functional", "line_number": 45, "usage_type": "attribute"}, {"api_name": "torch.functional.F.relu", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.functional", "line_number": 59, "usage_type": "attribute"}, {"api_name": "torch.ones", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.autograd.grad", "line_number": 79, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 79, "usage_type": "attribute"}, {"api_name": "torch.sqrt", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.mean", "line_number": 88, "usage_type": "call"}]} +{"seq_id": "41079267459", "text": "import json\nimport sys\n\nfrom openpyxl import load_workbook\n\ndef main(xls_filename, model_filename):\n \"\"\"\n Finds controls cost in an Excel file\n and update them in a JSON model file.\n \"\"\"\n\n wb = load_workbook(filename=xls_filename, data_only=True)\n ws = wb.active\n\n with open(model_filename, \"r\") as file:\n model = json.load(file)\n\n all_found = True\n for i in range(14, 32):\n name = ws[\"A\"][i].value\n cost = ws[\"H\"][i].value\n ind_cost = ws[\"I\"][i].value\n\n found = False\n for control in model[\"controls\"]:\n try:\n index = model[\"controls\"][control][\"level_name\"].index(name)\n found = True\n\n model[\"controls\"][control][\"cost\"][index] = cost\n model[\"controls\"][control][\"ind_cost\"][index] = ind_cost\n except ValueError:\n pass\n\n if not found:\n all_found = False\n print(f\"{name} not found\")\n \n if all_found:\n with open(model_filename, \"w\") as file:\n json.dump(model, file, indent=2)\n\nif __name__ == \"__main__\":\n main(xls_filename=sys.argv[1], model_filename=sys.argv[2])\n\n", "repo_name": "przemub/cysectool", "sub_path": "doc/update_control_cost.py", "file_name": "update_control_cost.py", "file_ext": "py", "file_size_in_byte": 1187, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "20", "api": [{"api_name": "openpyxl.load_workbook", "line_number": 12, "usage_type": "call"}, {"api_name": "json.load", "line_number": 16, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 41, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 44, "usage_type": "attribute"}]} +{"seq_id": "5937285082", "text": "\n# coding: utf-8\n\n# In[1]:\n\nfrom keras.utils import np_utils\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\nfrom keras.layers.convolutional import Convolution2D, MaxPooling2D\nfrom keras.optimizers import SGD\n\nimport pandas as pd\nimport numpy as np\n\n\n# In[4]:\n\ndata = pd.read_csv('E:/data_files/train.csv',skiprows=[0],header=None)\n\n\n# In[257]:\n\ndata.head()\n\n\n# In[3]:\n\nfrom sklearn.model_selection import train_test_split\n\n\n# In[272]:\n\ntrain,test=train_test_split(data, test_size=0.2, random_state=42)\n\n\n# In[273]:\n\nlabels = train.ix[:,0].values.astype('int32')\nX_train = (train.ix[:,1:].values).astype('float32')\nX_test = (test.ix[:,1:].values).astype('float32')\ntest_labels = test.ix[:,0].values.astype('int32')\ntest_labels = np_utils.to_categorical(test_labels, 10)\n\n\n\n# In[274]:\n\ny_train = np_utils.to_categorical(labels) \n\n\n# In[275]:\n\n# pre-processing: divide by max and substract mean\nscale = np.max(X_train)\nX_train /= scale\nX_test /= scale\n\nmean = np.std(X_train)\nX_train -= mean\nX_test -= mean\n\ninput_dim = X_train.shape[1]\nnb_classes = y_train.shape[1]\n\n\n# In[276]:\n\n#for tensorflow as backend use the below code\nX_train1 = X_train.reshape(X_train.shape[0], 28, 28, 1)\nX_test1 = X_test.reshape(X_test.shape[0], 28, 28, 1)\n\n\n# In[286]:\n\nmodel = Sequential()\n\n\n# In[117]:\n\n#input == the output whatever the stride is set when the valid_mode = same\n\n\n# In[287]:\n\nmodel.add(Convolution2D(32,5,5,activation='relu', input_shape=(28,28,1)))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\n\n\n\n# In[288]:\n\n#2ND ADDITION\nmodel.add(Convolution2D(32,5,5,activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\n\n# In[289]:\n\n#dense_layer_addition\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu',input_shape=(28,28,1)))\n\nmodel.add(Dense(10, activation='softmax'))\n\n\n# In[ ]:\n\n\n\n\n# In[290]:\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n\n# In[291]:\n\n\nmodel.fit(X_train1, y_train, \n batch_size=32, epochs=1, verbose=1) \n\n\n# In[292]:\n\nscore = model.evaluate(X_test1, test_labels, verbose=0)\n\n\n# In[293]:\n\nscore\n\n\n# In[256]:\n\nmodel.summary()\n\n\n# In[1]:\n\n\n\n\n# In[4]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n", "repo_name": "pawa034/Convolution-Neural-Network", "sub_path": "keras_digit_classification.py", "file_name": "keras_digit_classification.py", "file_ext": "py", "file_size_in_byte": 2236, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pandas.read_csv", "line_number": 18, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 33, "usage_type": "call"}, {"api_name": "keras.utils.np_utils.to_categorical", "line_number": 42, "usage_type": "call"}, {"api_name": "keras.utils.np_utils", "line_number": 42, "usage_type": "name"}, {"api_name": "keras.utils.np_utils.to_categorical", "line_number": 48, "usage_type": "call"}, {"api_name": "keras.utils.np_utils", "line_number": 48, "usage_type": "name"}, {"api_name": "numpy.max", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 58, "usage_type": "call"}, {"api_name": "keras.models.Sequential", "line_number": 75, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Convolution2D", "line_number": 85, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.MaxPooling2D", "line_number": 86, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Convolution2D", "line_number": 94, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.MaxPooling2D", "line_number": 95, "usage_type": "call"}, {"api_name": "keras.layers.core.Flatten", "line_number": 101, "usage_type": "call"}, {"api_name": "keras.layers.core.Dense", "line_number": 102, "usage_type": "call"}, {"api_name": "keras.layers.core.Dense", "line_number": 104, "usage_type": "call"}]} +{"seq_id": "71566647422", "text": "# -*- coding: utf-8 -*-\nimport pickle\nimport random\nimport re\nimport sys\nimport time\nimport math\nfrom statistics import mean\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.tensorboard import SummaryWriter\n\nsys.path.append(\"data\")\nfrom dataloader import *\nfrom embeddings import *\n\nsys.path.append(\"models\")\nfrom autoencoder import *\n\nsys.path.append(\"experiments\")\nfrom run_utils import *\nfrom procedures import Procedure\nfrom mean_metrics import *\n\nsys.path.append(\"configs\")\nimport config\n\nimport argparse\nimport logging\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s:%(message)s')\nlogger = logging.getLogger(__name__)\n\nparser = argparse.ArgumentParser(description=\"Update summarization using unsupervised autoencodder\")\n\n################ data ################\n# ENELVER GLOVE PATH AT THE END - GS\nparser.add_argument(\"--glove\", default=config.data[\"glove\"], help=\"glove embeddings file path\")\nparser.add_argument(\"--train\", default=config.data[\"train\"], help=\"data path for training\")\nparser.add_argument(\"--valid\", default=config.data[\"valid\"], help=\"data path for validation\")\nparser.add_argument(\"--test\", default=config.data[\"test\"], help=\"data path for testing\")\nparser.add_argument(\"--min_freq\", default=config.data[\"min_freq\"], type=int, help=\"minimum frequency needed to include a token in the vocabulary\")\nparser.add_argument(\"--vocab_size\", default=config.data[\"vocab_size\"], type=int, help=\"maximum size of the vocabulary\")\nparser.add_argument(\"--remove_stopwords\", default=config.data[\"remove_stopwords\"], type=bool, help=\"remove stopwords within preprocessing steps\")\nparser.add_argument(\"--remove_punctuation\", default=config.data[\"remove_punctuation\"], type=bool, help=\"remove punctuation within preprocessing steps\")\n\n################ Summarization parameters ################\nparser.add_argument(\"--length_ratio_train\", default=config.sum_param[\"length_ratio_train\"], type=float, help=\"Comrpession ratio when training\")\nparser.add_argument(\"--length_ratio_test\", default=config.sum_param[\"length_ratio_test\"], type=float, help=\"Comrpession ratio when generating final\")\nparser.add_argument(\"--lambda_\", default=config.sum_param[\"lambda_\"], type=float, help=\"Update summary's parameters (positive for coherence and negative value for novelty)\")\n\n################ training parameters ################\nparser.add_argument(\"--save_tfidf_path\", default=config.trainer[\"save_tfidf_path\"], help=\"data for pretrained TFIDF Model\")\nparser.add_argument(\"--save_model_path\", default=config.trainer[\"save_model_path\"], help=\"data for pretrained TFIDF Model\")\nparser.add_argument(\"--save_vocab_path\", default=config.trainer[\"save_vocab_path\"], help=\"data for pretrained TFIDF Model\")\nparser.add_argument(\"--min_seq_len\", default=config.trainer[\"min_seq_len\"], type=int, help=\"Minimum length of sentence for training\")\nparser.add_argument(\"--max_seq_len\", default=config.trainer[\"max_seq_len\"], type=int, help=\"Maximum length of sentence for training\")\nparser.add_argument(\"--max_numel_per_batch\", default=config.trainer[\"max_numel_per_batch\"], type=int, help=\"Number of updates by documents considered\")\nparser.add_argument(\"--accumulation_steps\", default=config.trainer[\"accumulation_steps\"], type=int, help=\"mini batch size when training\")\nparser.add_argument(\"--vocab_save\", default=config.trainer[\"vocab_save\"], type=bool, help=\"generate summary results with rouge scores\")\nparser.add_argument(\"--model_save\", default=config.trainer[\"model_save\"], type=bool, help=\"generate summary results with rouge scores\")\nparser.add_argument(\"--train_tfidf\", default=config.trainer[\"train_tfidf\"], type=bool, help=\"Training TFIDF model on training dataset\")\nparser.add_argument(\"--model_file\", default=config.trainer[\"model_file\"], help=\"relative path locating the model saved\")\nparser.add_argument(\"--vocab_file\", default=config.trainer[\"vocab_file\"], help=\"relative path locating the vocabulary saved\")\nparser.add_argument(\"--tfidf_file\", default=config.trainer[\"tfidf_file\"], help=\"relative path locating the tfidf model saved\")\n\n################ model parameters ################\nparser.add_argument(\"--emb_dim\", default=config.model_parameters[\"emb_dim\"], type=int, help=\"dimension number of glove pre-trained word vectors\")\nparser.add_argument(\"--enc_hid_dim\", default=config.model_parameters[\"enc_hid_dim\"], type=int, help=\"hidden state dimension of the encoder\")\nparser.add_argument(\"--dec_hid_dim\", default=config.model_parameters[\"dec_hid_dim\"], type=int, help=\"hidden state dimension of the decoder\")\nparser.add_argument(\"--enc_dropout\", default=config.model_parameters[\"enc_dropout\"], type=float, help=\"probability a neuron being deactivated in the encoder\")\nparser.add_argument(\"--dec_dropout\", default=config.model_parameters[\"dec_dropout\"], type=float, help=\"probability a neuron being deactivated in the decoder\")\nparser.add_argument(\"--use_pretrained\", default=config.model_parameters[\"use_pretrained\"], type=bool, help=\"use glove pre-trained word vectors\")\nparser.add_argument(\"--fxed_len_updates\", default=config.model_parameters[\"fxed_len_updates\"], type=bool, help=\"use fixed summary length or incrementally increase summary size with updates\")\nparser.add_argument(\"--weights_init\", default=config.model_parameters[\"weights_init\"], help=\"weight initialization: xavier/orthogonal/normal\")\n\n################ model hyperparameters ################\nparser.add_argument(\"--optimizer\", default=config.model_hyperparameters[\"optimizer\"], help=\"optimization algorithm that will update model's parameters\")\nparser.add_argument(\"--learning_rate\", default=config.model_hyperparameters[\"learning_rate\"], type=float, help=\"optimization algorithm that will update model's parameters\")\nparser.add_argument(\"--weight_decay\", default=config.model_hyperparameters[\"weight_decay\"], type=float, help=\"optimization algorithm that will update model's parameters\")\nparser.add_argument(\"--clip\", default=config.model_hyperparameters[\"clip\"], type=int, help=\"optimization algorithm that will update model's parameters\")\nparser.add_argument(\"--include_prev\", default=config.model_hyperparameters[\"include_prev\"], type=bool, help=\"optimization algorithm that will update model's parameters\")\nparser.add_argument(\"--include_prev_epoch\", default=config.model_hyperparameters[\"include_prev_epoch\"], type=int, help=\"optimization algorithm that will update model's parameters\")\n\n################ beam ################\nparser.add_argument(\"--size\", default=config.beam[\"size\"], type=int, help=\"Beam size\")\nparser.add_argument(\"--min_steps\", default=config.beam[\"min_steps\"], type=int, help=\"Minimum of words to be generated\")\nparser.add_argument(\"--num_return_seq\", default=config.beam[\"num_return_seq\"], type=int, help=\"Number of sequence returned by beam\")\nparser.add_argument(\"--num_return_sum\", default=config.beam[\"num_return_sum\"], type=int, help=\"Number of summaries generated by the model for each text\")\nparser.add_argument(\"--n_gram_block\", default=config.beam[\"n_gram_block\"], type=int, help=\"Windows size for non repetitive words\")\n\n################ Runs experiment ################\nparser.add_argument(\"--writer\", default=config.runs[\"writer\"], type=bool, help=\"Tracking loss on Tensorboard\")\nparser.add_argument(\"--run_name\", default=config.runs[\"run_name\"], help=\"Naming files for this run\")\nparser.add_argument(\"--path_results\", default=config.runs[\"path_results\"], help=\"Folder for saving results\")\nparser.add_argument(\"--track_all_loss\", default=config.runs[\"track_all_loss\"], type=bool, help=\"Tracking all sub losses\")\nparser.add_argument(\"--n_epochs\", default=config.runs[\"n_epochs\"], type=int, help=\"Number of training epochs\")\nparser.add_argument(\"--train_model\", default=config.runs[\"train_model\"], type=bool, help=\"training the model\")\nparser.add_argument(\"--generate\", default=config.runs[\"generate\"], type=bool, help=\"Generating results\")\nparser.add_argument(\"--output_metrics\", default=config.runs[\"output_metrics\"], type=bool, help=\"Output ROUGE score and other metrics\")\n\n\nargs = parser.parse_args() \nprint(args)\n\nSEED = 42\nrandom.seed(SEED)\nnp.random.seed(SEED)\ntorch.manual_seed(SEED)\ntorch.cuda.manual_seed(SEED)\ntorch.backends.cudnn.deterministic = True\n\n# enable gpu if available \ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nlogger.info(f\"The device you are using is {device}\")\n\n#######################################\n######## load glove embeddings ########\nglove_model = loadGloveModel(args.glove)\nvocab = None\n\n###############################################\n######## Loading iterator for training ########\nif args.train_model:\n logger.info(f\"Loading dataloader for train\")\n train_iterator, vocab = get_loader(file=args.train, \n min_freq=args.min_freq, \n vocab_size=args.vocab_size,\n remove_stopwords=args.remove_stopwords, \n remove_punctuation=args.remove_punctuation,\n tfidf_file=args.save_tfidf_path,\n vectorizer_train=args.train_tfidf)\n \n logger.info(f\"Loading dataloader for valid\")\n valid_iterator = get_loader(file=args.valid, \n vocabulary=vocab, \n min_freq=args.min_freq, \n vocab_size=args.vocab_size,\n remove_stopwords=args.remove_stopwords, \n remove_punctuation=args.remove_punctuation, \n tfidf_file = args.tfidf_file)\n\n if args.vocab_save:\n torch.save(vocab, args.save_vocab_path)\n\n#################################################\n######## Iterator for generating summary ########\nif args.generate:\n #Using pretrained model and only generating results\n if vocab is None:\n vocab = torch.load(args.vocab_file)\n \n logger.info(f\"Loading dataloader for test\")\n test_iterator = get_loader(file=args.test, \n vocabulary=vocab, \n min_freq=args.min_freq, \n vocab_size=args.vocab_size,\n remove_stopwords=args.remove_stopwords, \n remove_punctuation=args.remove_punctuation, \n tfidf_file = args.tfidf_file)\n\n\ntry:\n train_iterator\nexcept :\n try:\n test_iterator\n except NameError :\n print('Please, set at least set variable train_model or generate to True to provide model at least one valid iterator')\n\n##############################################\n######## Intializing model parameters ########\nweights_matrix = weights_matrix_embedding(glove_model, vocab.itos.values(), len(vocab), 100)\ninput_dim = len(vocab)\noutput_dim = len(vocab)\n\n################################\n######## Defining model ########\nmodel = AE(vocab=vocab, \n weights_matrix=weights_matrix, \n input_dim=input_dim, \n output_dim=output_dim, \n enc_hid_dim=args.enc_hid_dim, \n dec_hid_dim=args.dec_hid_dim, \n emb_dim=args.emb_dim, \n enc_dropout=args.enc_dropout, \n dec_dropout=args.dec_dropout, \n device=device, \n use_pretrained=args.use_pretrained,\n beam_size=args.size, \n min_dec_steps=args.min_steps, \n num_return_seq=args.num_return_seq, \n num_return_sum=args.num_return_sum,\n n_gram_block=args.n_gram_block).to(device)\n\nmodel.apply(args.weights_init)\nlogger.info(f'The model has {count_parameters(model):,} trainable parameters')\n\n###########################################\n######## Keep track on tensorboard ########\nif args.writer:\n writer = SummaryWriter(comment=args.run_name)\nelse:\n writer = None\n\nprocedure = Procedure(model=model, \n vocab=vocab,\n optimizer=args.optimizer,\n learning_rate=args.learning_rate, \n weight_decay=args.weight_decay, \n clip=args.clip,\n lambda_=args.lambda_, \n device=device,\n writer=writer,\n include_prev=args.include_prev,\n include_prev_epoch=args.include_prev_epoch,\n min_seq_len=args.min_seq_len,\n max_seq_len=args.max_seq_len,\n max_numel_per_batch=args.max_numel_per_batch,\n track_all_loss=args.track_all_loss,\n fixed_len=args.fxed_len_updates)\n\n################################\n######## training model ########\nif args.train_model:\n \n N_EPOCHS = args.n_epochs\n \n logger.info(f\"The model will be trained for {N_EPOCHS} epochs\")\n best_valid_loss = float('inf')\n\n for epoch in range(N_EPOCHS):\n\n start_time = time.time()\n train_loss = procedure.train(train_iterator, args.length_ratio_train, epoch, args.accumulation_steps)\n valid_loss = procedure.evaluate(valid_iterator, args.length_ratio_train, epoch)\n end_time = time.time()\n epoch_mins, epoch_secs = epoch_time(start_time, end_time)\n\n #If model account for novelty/coherency we start saving model when we trained with the inclusion of previous iteration\n if args.model_save:\n if args.include_prev:\n if epoch > args.include_prev_epoch:\n if valid_loss < best_valid_loss:\n best_valid_loss = valid_loss\n torch.save(model.state_dict(), args.save_model_path)\n else:\n if valid_loss < best_valid_loss:\n best_valid_loss = valid_loss\n torch.save(model.state_dict(), args.save_model_path)\n\n print(f'Epoch: {epoch+1:02} | Time: {epoch_mins}m {epoch_secs}s')\n print(f'\\t Train Loss: {train_loss:.3f}')\n print(f'\\t Val. Loss: {valid_loss:.3f}')\n\n\n###################################################\n######## Generating Summary for test model ########\nif args.generate: \n if not args.train_model:\n procedure.model.load_state_dict(torch.load(args.model_file))\n \n logger.info(f\"The model is generating summaries\")\n \n #Getting all results\n results = procedure.summary_generation(test_iterator, args.length_ratio_test)\n src_list = results.src.to_list()\n update_ids = results.update_id.to_list()\n t_results = treat_results(results)\n \n #Creating columns name for storing final results\n col_names = []\n for i in range(len(t_results[0])):\n col_names.append('gensum_{}'.format(i))\n\n # Creating dataframe for storing text results\n df_textsum = pd.DataFrame(t_results, columns=col_names)\n df_textsum['source_text'] = src_list\n cols = df_textsum.columns.tolist()\n cols = cols[-1:] + cols[:-1]\n df_textsum = df_textsum[cols]\n df_textsum.to_csv('{}{}.csv'.format(args.path_results, args.run_name))\n \n #Getting metrics for the batch\n if args.output_metrics:\n logger.info(f\"The model is generating ROUGE scores and other metrics\")\n #Getting ROUGE Score\n R_mean_results = rouge_means(results)\n cols_name = df_textsum.columns.tolist()[1:]\n \n #Getting mesuring novelty / coherency ratios\n reuse_means = []\n new_means = []\n for col in cols_name:\n reuse_means.append(pct_reuse(src_list, update_ids, df_textsum[col]))\n new_means.append(pct_new(src_list, update_ids, df_textsum[col]))\n pct_reuse_m = mean(reuse_means)\n pct_new_m = mean(new_means)\n \n #Saving metrics into csv file\n metrics_results = R_mean_results + [pct_reuse_m] + [pct_new_m]\n cols_temp = results.columns.tolist()\n rouge_name = list(filter(lambda x: x.startswith('rouge'), cols_temp))\n metrics_name = rouge_name + ['reuse_ratio'] + ['new_ratio']\n df_metrics = pd.DataFrame(metrics_results, metrics_name, columns=['value'])\n df_metrics.to_csv('{}metrics_{}.csv'.format(args.path_results, args.run_name))", "repo_name": "florentfettu/update-summarization-production", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 16245, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sys.path.append", "line_number": 16, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 16, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 20, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 23, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "sys.path.append", "line_number": 28, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "logging.basicConfig", "line_number": 34, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 34, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 35, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 37, "usage_type": "call"}, {"api_name": "config.data", "line_number": 41, "usage_type": "attribute"}, {"api_name": "config.data", "line_number": 42, "usage_type": "attribute"}, {"api_name": "config.data", "line_number": 43, "usage_type": "attribute"}, {"api_name": "config.data", "line_number": 44, "usage_type": "attribute"}, {"api_name": "config.data", "line_number": 45, "usage_type": "attribute"}, {"api_name": "config.data", "line_number": 46, "usage_type": "attribute"}, {"api_name": "config.data", "line_number": 47, "usage_type": "attribute"}, {"api_name": "config.data", "line_number": 48, "usage_type": "attribute"}, {"api_name": "config.sum_param", "line_number": 51, "usage_type": "attribute"}, {"api_name": "config.sum_param", "line_number": 52, "usage_type": "attribute"}, {"api_name": "config.sum_param", "line_number": 53, "usage_type": "attribute"}, {"api_name": "config.trainer", "line_number": 56, "usage_type": "attribute"}, {"api_name": "config.trainer", "line_number": 57, "usage_type": "attribute"}, {"api_name": "config.trainer", "line_number": 58, "usage_type": "attribute"}, {"api_name": "config.trainer", "line_number": 59, "usage_type": "attribute"}, {"api_name": "config.trainer", "line_number": 60, "usage_type": "attribute"}, {"api_name": "config.trainer", "line_number": 61, "usage_type": "attribute"}, {"api_name": "config.trainer", "line_number": 62, "usage_type": "attribute"}, {"api_name": "config.trainer", "line_number": 63, "usage_type": "attribute"}, {"api_name": "config.trainer", "line_number": 64, "usage_type": "attribute"}, {"api_name": "config.trainer", "line_number": 65, "usage_type": "attribute"}, {"api_name": "config.trainer", "line_number": 66, "usage_type": "attribute"}, {"api_name": "config.trainer", "line_number": 67, "usage_type": "attribute"}, {"api_name": "config.trainer", "line_number": 68, "usage_type": "attribute"}, {"api_name": "config.model_parameters", "line_number": 71, "usage_type": "attribute"}, {"api_name": "config.model_parameters", "line_number": 72, "usage_type": "attribute"}, {"api_name": "config.model_parameters", "line_number": 73, "usage_type": "attribute"}, {"api_name": "config.model_parameters", "line_number": 74, "usage_type": "attribute"}, {"api_name": "config.model_parameters", "line_number": 75, "usage_type": "attribute"}, {"api_name": "config.model_parameters", "line_number": 76, "usage_type": "attribute"}, {"api_name": "config.model_parameters", "line_number": 77, "usage_type": "attribute"}, {"api_name": "config.model_parameters", "line_number": 78, "usage_type": "attribute"}, {"api_name": "config.model_hyperparameters", "line_number": 81, "usage_type": "attribute"}, {"api_name": "config.model_hyperparameters", "line_number": 82, "usage_type": "attribute"}, {"api_name": "config.model_hyperparameters", "line_number": 83, "usage_type": "attribute"}, {"api_name": "config.model_hyperparameters", "line_number": 84, "usage_type": "attribute"}, {"api_name": "config.model_hyperparameters", "line_number": 85, "usage_type": "attribute"}, {"api_name": "config.model_hyperparameters", "line_number": 86, "usage_type": "attribute"}, {"api_name": "config.beam", "line_number": 89, "usage_type": "attribute"}, {"api_name": "config.beam", "line_number": 90, "usage_type": "attribute"}, {"api_name": "config.beam", "line_number": 91, "usage_type": "attribute"}, {"api_name": "config.beam", "line_number": 92, "usage_type": "attribute"}, {"api_name": "config.beam", "line_number": 93, "usage_type": "attribute"}, {"api_name": "config.runs", "line_number": 96, "usage_type": "attribute"}, {"api_name": "config.runs", "line_number": 97, "usage_type": "attribute"}, {"api_name": "config.runs", "line_number": 98, "usage_type": "attribute"}, {"api_name": "config.runs", "line_number": 99, "usage_type": "attribute"}, {"api_name": "config.runs", "line_number": 100, "usage_type": "attribute"}, {"api_name": "config.runs", "line_number": 101, "usage_type": "attribute"}, {"api_name": "config.runs", "line_number": 102, "usage_type": "attribute"}, {"api_name": "config.runs", "line_number": 103, "usage_type": "attribute"}, {"api_name": "random.seed", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 111, "usage_type": "attribute"}, {"api_name": "torch.manual_seed", "line_number": 112, "usage_type": "call"}, {"api_name": "torch.cuda.manual_seed", "line_number": 113, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 113, "usage_type": "attribute"}, {"api_name": "torch.backends", "line_number": 114, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 117, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 117, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 117, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 154, "usage_type": "call"}, {"api_name": "torch.utils.tensorboard.SummaryWriter", "line_number": 205, "usage_type": "call"}, {"api_name": "procedures.Procedure", "line_number": 209, "usage_type": "call"}, {"api_name": "time.time", "line_number": 237, "usage_type": "call"}, {"api_name": "time.time", "line_number": 240, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 249, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 253, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 264, "usage_type": "call"}, {"api_name": "statistics.mean", "line_number": 300, "usage_type": "call"}, {"api_name": "statistics.mean", "line_number": 301, "usage_type": "call"}]} +{"seq_id": "21427991713", "text": "from rest_framework import serializers\r\nfrom django.contrib.auth import authenticate\r\nfrom rest_framework import exceptions\r\nfrom pizza_app.models import Pizza\r\nfrom django.http import HttpResponse\r\n\r\nclass ModelSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model=Pizza\r\n fields=(\r\n 'id',\r\n 'pizza_type',\r\n 'pizza_size',\r\n 'toppings'\r\n ) \r\n \r\nclass PostSerialzer(serializers.ModelSerializer):\r\n def save(self):\r\n try:\r\n pizza=Pizza(\r\n pizza_size=self.validated_data['pizza_size'],\r\n pizza_type=self.validated_data['pizza_type'],\r\n toppings=self.validated_data['toppings'],\r\n )\r\n pizza_size=self.validated_data['pizza_size']\r\n pizza_type=self.validated_data['pizza_type']\r\n toppings=self.validated_data['toppings']\r\n pizza.save()\r\n return pizza\r\n except KeyError as ke:\r\n print('Key must be', ke) \r\n \r\n class Meta:\r\n model=Pizza\r\n fields='__all__' \r\n", "repo_name": "nidhiverma-prog/Pizza_API", "sub_path": "pizza_app/serializers.py", "file_name": "serializers.py", "file_ext": "py", "file_size_in_byte": 1190, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 7, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 7, "usage_type": "name"}, {"api_name": "pizza_app.models.Pizza", "line_number": 9, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 17, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 17, "usage_type": "name"}, {"api_name": "pizza_app.models.Pizza", "line_number": 20, "usage_type": "call"}, {"api_name": "pizza_app.models.Pizza", "line_number": 34, "usage_type": "name"}]} +{"seq_id": "34242366239", "text": "#coding=utf-8\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect\nfrom django.template import RequestContext\nfrom kovin.models import Object, Place, BattleLog\nimport extsea\nimport rpgdb\n\ndef list(request):\n\tif ('user' in request.session):\n\t\tuser = request.session['user']\n\t\tcharacter = user.to_extsea()\n\t\tbattles = BattleLog.objects.filter(owner=user)\n\t\tcontext = {\n\t\t\t\t 'character' : character,\n\t\t\t\t 'user' : user, \n\t\t\t\t 'battles' : battles\n\t\t\t\t }\n\t\treturn render_to_response('battles.html', context, context_instance=RequestContext(request))\n\telse:\n\t\treturn HttpResponseRedirect('/login/')\n\ndef view(request, id):\n\tif ('user' in request.session):\n\t\tuser = request.session['user']\n\t\tcharacter = user.to_extsea()\n\t\tbattle = BattleLog.objects.get(id=id)\n\t\tlines = battle.log.split('\\n')\n\t\tlog = []\n\t\tfor line in lines:\n\t\t\tdata = line.split(' ')\n\t\t\tif data[0] == 'use':\n\t\t\t\tattribute = rpgdb.create(data[1])\n\t\t\t\tdata[1] = attribute.title\n\t\t\tlog.append(data)\n\t\tcontext = {\n\t\t\t\t 'character' : character,\n\t\t\t\t 'user' : user, \n\t\t\t\t 'log' : log\n\t\t\t\t }\n\t\treturn render_to_response('battle.html', context, context_instance=RequestContext(request))\n\telse:\n\t\treturn HttpResponseRedirect('/login/')\n", "repo_name": "szatkus/kovin", "sub_path": "views/battle.py", "file_name": "battle.py", "file_ext": "py", "file_size_in_byte": 1244, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "kovin.models.BattleLog.objects.filter", "line_number": 13, "usage_type": "call"}, {"api_name": "kovin.models.BattleLog.objects", "line_number": 13, "usage_type": "attribute"}, {"api_name": "kovin.models.BattleLog", "line_number": 13, "usage_type": "name"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 19, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 19, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 21, "usage_type": "call"}, {"api_name": "kovin.models.BattleLog.objects.get", "line_number": 27, "usage_type": "call"}, {"api_name": "kovin.models.BattleLog.objects", "line_number": 27, "usage_type": "attribute"}, {"api_name": "kovin.models.BattleLog", "line_number": 27, "usage_type": "name"}, {"api_name": "rpgdb.create", "line_number": 33, "usage_type": "call"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 41, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 41, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 43, "usage_type": "call"}]} +{"seq_id": "291679909", "text": "from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n # ex: /leaderboards/\n path('leaderboards/', views.index, name='index'),\n path('', views.lookup, name='lookup'),\n path('lookup/', views.lookup, name='lookup'),\n path('lookup//', views.lookup, name='lookup'),\n path('player//', views.stat, name='stat'),\n path('leaderboards//', views.index, name='index'),\n path('leaderboards///', views.index, name='index'),\n # ex: /leaderboards/5/\n \n # ex: /leaderboards/5/name/\n path('/div/', views.division, name='div'),\n # ex: /leaderboards/5/team/\n # path('/team/', views.team, name='team'),\n]", "repo_name": "kepalr/rglSTATS", "sub_path": "leaderboards/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 725, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 17, "usage_type": "call"}]} +{"seq_id": "5724349975", "text": "import logging\nimport os.path\nfrom os import path\n\nimport sys\n#from pathlib import Path\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.model_selection import train_test_split\n\nimport fonctions as f\n\n\nlogger = logging.getLogger(__name__)\n\n# ===================================================================================================\n\n\ndef prepare_data(config):\n\n # Constantes depuis le fichier de config\n path = config[\"DATA\"][\"FILE_PATH\"]\n \n train_data = config[\"DATA\"][\"TRAIN_DATA\"]\n \n test_data = config[\"DATA\"][\"TEST_DATA\"]\n \n test_size = config[\"MODELE\"][\"TEST_SIZE\"]\n \n seuil = config[\"MODELE\"][\"SEUIL\"]\n \n max_depth = config[\"MODELE\"][\"DEPH\"]\n \n n_trees = config[\"MODELE\"][\"TREES\"]\n \n min_samples_split= config[\"MODELE\"][\"MIN_SPLIT\"]\n \n modele = config[\"MODELE\"][\"MODELE\"]\n\n predictions = config[\"OUTPUT\"][\"PREDICTIONS\"]\n \n matrice = config[\"OUTPUT\"][\"MATRICE\"]\n \n \n logger.info(f'Chargement des données')\n \n try:\n\n train= pd.read_csv(train_data)\n test= pd.read_csv(test_data)\n\n\n except:\n \n df= pd.read_csv(path, sep=\";\")\n\n logger.info(f'Exploration des données')\n\n #print(df.info())\n #print(df.isna().sum())\n\n df.drop(df.tail(2).index,inplace = True)\n\n logger.info(f'Nettoyage des données')\n\n df= df.drop(columns=[\"id_client\"])\n\n df[\"annual_flux\"].fillna('0', inplace = True)\n df[\"job_category\"].fillna('inconnu', inplace = True) \n df[\"risk_of_credit\"].fillna('inconnu', inplace = True) \n df['annual_flux']= df['annual_flux'].str.replace(',', '.', regex=True)\n\n #get all categorical columns\n cat_columns = ['job_category','service_channel','risk_of_credit','credit_flux']\n\n #convert all categorical columns to numeric\n df[cat_columns] = df[cat_columns].apply(lambda x: pd.factorize(x)[0])\n\n df = df.astype(float, errors = 'raise')\n\n train, test = train_test_split(df, test_size=test_size, random_state=42)\n\n train.to_csv(train_data)\n test.to_csv(test_data)\n \n \n X= train.drop(['target'],axis=1)\n Y= train[\"target\"]\n \n X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=test_size, random_state=42)\n \n \n x_test= test.drop(['target'],axis=1)\n y= test[\"target\"]\n \n '''\n \n logger.info(f'Choix des meilleurs paramètres pour le modèle')\n \n max_depth, n_trees= f.best_parameters(X_train, y_train)\n \n print('\\n')\n print(\"max_depth:\", max_depth)\n print('\\n')\n print(\"n_trees:\", n_trees)\n '''\n \n return max_depth, n_trees, min_samples_split, X_train, X_test, y_train, y_test, x_test, y, seuil, modele, predictions, matrice\n\n\n \n \n \n \n \n \n \n \n \n ", "repo_name": "SebastiaSerena/Test", "sub_path": "code/pretraitement.py", "file_name": "pretraitement.py", "file_ext": "py", "file_size_in_byte": 2879, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "logging.getLogger", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 51, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 52, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path", "line_number": 57, "usage_type": "argument"}, {"api_name": "pandas.factorize", "line_number": 79, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 83, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 92, "usage_type": "call"}]} +{"seq_id": "39070394415", "text": "import jax\nimport jax.numpy as jnp\n\nfrom functools import partial\nfrom planners.utils import adam_with_projection\nfrom planners.disprod import Disprod\n\nclass DiscreteDisprod(Disprod):\n def __init__(self, env, cfg):\n\n super(DiscreteDisprod, self).__init__(env, cfg)\n\n self.ac_lb = 0\n self.ac_ub = env.action_space.n - 1\n \n # self.nA = cfg[\"nA\"]\n # self.nS = cfg[\"nS\"]\n self.depth = cfg.get(\"depth\")\n\n self.n_res = cfg[\"disprod\"][\"n_restarts\"]\n self.max_grad_steps = cfg[\"disprod\"][\"max_grad_steps\"]\n self.step_size = cfg[\"disprod\"][\"step_size\"]\n self.step_size_var = cfg[\"disprod\"][\"step_size_var\"]\n self.conv_thresh = cfg[\"disprod\"][\"convergance_threshold\"] \n \n self.log_file = cfg[\"log_file\"]\n\n # Multiplicative factor used to transform free_action variables to the legal range.\n self.scale_fac = self.ac_ub - self.ac_lb\n self.converged_jit = jax.jit(lambda x, thresh: jnp.max(jnp.abs(x)) < thresh)\n \n self.n_bin_var = cfg.get(\"n_bin_var\", 0)\n self.n_real_var = self.nS - self.n_bin_var\n \n # Partial function to initialize action distribution\n self.ac_dist_init_fn = init_ac_dist(self.n_res, self.depth, self.nA, low_ac=0, high_ac=1) \n \n norm_mu, norm_var = 0, 1\n \n noise_dist = (jnp.array([norm_mu]), jnp.array([norm_var]))\n\n projection = projection_fn(self.nA)\n self.batch_projection = jax.vmap(projection, in_axes=(0), out_axes=(0))\n \n \n # Dynamics distribution function\n if cfg[\"disprod\"][\"taylor_expansion_mode\"] == \"complete\":\n fop_fn = fop_analytic(self.ns_fn, env)\n sop_fn = sop_analytic(self.ns_fn, env)\n self.dynamics_dist_fn = dynamics_comp(self.ns_fn, env, fop_fn, sop_fn, noise_dist, self.n_real_var, self.n_bin_var)\n elif cfg[\"disprod\"][\"taylor_expansion_mode\"] == \"no_var\":\n self.dynamics_dist_fn = dynamics_nv(self.ns_fn, env, noise_dist, self.n_real_var, self.n_bin_var)\n else:\n raise Exception(\n f\"Unknown value for config taylor_expansion_mode. Got {cfg['taylor_expansion_mode']}\")\n \n # Reward distribution function\n if cfg['disprod']['reward_fn_using_taylor']:\n self.reward_dist_fn = reward_comp(self.reward_fn, self.env)\n else:\n self.reward_dist_fn = reward_mean(self.reward_fn, self.env)\n\n # Action selector\n if cfg[\"disprod\"][\"choose_action_mean\"]:\n self.ac_selector = lambda m,v,key: m\n else:\n self.ac_selector = lambda m,v,key: m + jnp.sqrt(v) * jax.random.normal(key, shape=(self.nA,)) \n \n self.rollout_fn = rollout_graph(self.dynamics_dist_fn, self.reward_dist_fn)\n self.q_fn = q(noise_dist, self.depth, self.rollout_fn)\n self.batch_q_fn = jax.vmap(self.q_fn, in_axes=(0, 0), out_axes=(0))\n \n self.batch_grad_q_fn = jax.vmap(grad_q(self.q_fn), in_axes=(0, 0), out_axes=(0))\n\n\n def reset(self, key):\n key_1, key_2 = jax.random.split(key)\n ac_seq = jax.random.uniform(key_1, shape=(self.depth, self.nA))\n return ac_seq, key_2\n\n @partial(jax.jit, static_argnums=(0,))\n def choose_action(self, obs, prev_ac_seq, key):\n ac_seq = prev_ac_seq\n\n # Create a vector of obs corresponding to n_restarts\n state = jnp.tile(obs, (self.n_res, 1)).astype('float32')\n\n # key: returned\n # subkey1: for action distribution initialization\n key, subkey1 = jax.random.split(key, 2)\n\n # Initialize the action distribution\n ac = self.ac_dist_init_fn(subkey1, ac_seq)\n\n opt_init_mean, opt_update_mean, get_params_mean = adam_with_projection(self.step_size, proj_fn=self.batch_projection)\n opt_state_mean = opt_init_mean(ac)\n\n\n n_grad_steps = 0\n has_converged = False\n\n def _update_ac(val):\n \"\"\"\n Update loop for all the restarts.\n \"\"\"\n ac_init, n_grad_steps, has_converged, state, opt_state_mean, tmp = val\n\n # Compute Q-value function for all restarts\n reward = self.batch_q_fn(state, ac_init)\n\n # Compute gradients with respect to action marginals.\n grads = self.batch_grad_q_fn(state, ac_init)\n\n # Update action distribution based on gradients\n opt_state_mean = opt_update_mean(n_grad_steps, -grads, opt_state_mean)\n ac_mu_upd = get_params_mean(opt_state_mean)\n\n # Compute updated reward\n updated_reward = self.batch_q_fn(state, ac_mu_upd)\n\n # Reset the restarts in which updates led to a poor reward\n restarts_to_reset = jnp.where(updated_reward < reward, jnp.ones(self.n_res, dtype=jnp.int32), jnp.zeros(self.n_res, dtype=jnp.int32))\n mask = jnp.tile(restarts_to_reset, (self.depth, self.nA, 1)).transpose(2, 0, 1)\n ac_mu = ac_init * mask + ac_mu_upd * (1-mask)\n\n # Compute action mean and variance epsilon\n ac_mu_eps = ac_mu - ac_init\n\n # Check for convergence\n has_converged = jnp.max(jnp.abs(ac_mu_eps)) < self.conv_thresh\n\n return ac_mu, n_grad_steps + 1, has_converged, state, opt_state_mean, tmp.at[n_grad_steps].set(jnp.sum(restarts_to_reset))\n\n def _check_conv(val):\n _, n_grad_steps, has_converged, _, _, _ = val\n return jnp.logical_and(n_grad_steps < self.max_grad_steps, jnp.logical_not(has_converged))\n\n # Iterate until max_grad_steps reached or both means and variance has not converged\n\n init_val = (ac, n_grad_steps, has_converged, state, opt_state_mean, jnp.zeros((self.max_grad_steps,))) \n ac, n_grad_steps, _, _, _, tmp = jax.lax.while_loop(_check_conv, _update_ac, init_val)\n\n\n # if self.debug:\n # print(f\"Gradients steps taken: {n_grad_steps}. Resets per step: {tmp}\")\n\n q_value = self.batch_q_fn(state, ac)\n\n # TODO: Figure out a JAX version of random_argmax\n # best_restart = random_argmax(subkey2, q_value)\n best_restart = jnp.nanargmax(q_value)\n ac_seq = ac[best_restart]\n\n ac = jnp.argmax(ac_seq[0])\n \n return ac, ac_seq, key\n\n\n# def random_argmax(key, x, pref_idx=0):\n# options = jnp.where(x == jnp.nanmax(x))[0]\n# val = 0 if 0 in options else jax_random.choice(key, options)\n# return val\n\n\n#########\n# Action Distribution initialization and transformation\n#########\n\ndef init_ac_dist(n_res, depth, nA, low_ac, high_ac):\n def _init_ac_dist(key, ac_seq):\n key1, key2 = jax.random.split(key)\n # Layer 1 actions are concrete\n ac_l1 = jax.random.randint(key1, shape=(n_res, 1, nA), minval=0, maxval=1)\n # Rest actions are marginals\n ac_l2 = jax.random.dirichlet(key2, jnp.ones(nA), (n_res, depth-1))\n\n ac_l1 = ac_l1.at[0, 0, :].set(jnp.round(ac_seq[1]))\n ac_l2 = ac_l2.at[0, : depth-2, :].set(ac_seq[2:])\n ac = jnp.concatenate([ac_l1, ac_l2], axis=1)\n return ac\n return _init_ac_dist\n\n# https://arxiv.org/pdf/1309.1541.pdf\ndef projection_fn(nA):\n def _projection_fn(ac):\n ac_sort = jnp.sort(ac)[::-1]\n ac_sort_cumsum = jnp.cumsum(ac_sort)\n rho_candidates = ac_sort + (1 - ac_sort_cumsum)/jnp.arange(1, nA+1)\n mask = jnp.where(rho_candidates > 0, jnp.arange(nA, dtype=jnp.int32), -jnp.ones(nA, dtype=jnp.int32))\n rho = jnp.max(mask)\n contrib = (1 - ac_sort_cumsum[rho])/(rho + 1)\n return jax.nn.relu(ac + contrib)\n return jax.vmap(_projection_fn, in_axes=0, out_axes=0)\n\n#####################################\n# Q-function computation graph\n#################################\n\ndef rollout_graph(dynamics_dist_fn, reward_dist_fn):\n def _rollout_graph(d, params):\n agg_reward, s_mu, s_var, a_mu = params\n reward = reward_dist_fn(s_mu, s_var, a_mu[d, :])\n ns_mu, ns_var = dynamics_dist_fn(s_mu, s_var, a_mu[d, :]) \n return agg_reward+reward, ns_mu, ns_var, a_mu\n return _rollout_graph\n\ndef q(noise_dist, depth, rollout_fn):\n def _q(s, a_mu):\n \"\"\"\n Compute the Q-function for a single restart\n \"\"\"\n noise_mean, noise_var = noise_dist\n # augment state by adding variable for noise \n s_mu = jnp.concatenate([s, noise_mean], axis=0)\n s_var = jnp.concatenate([s*0, noise_var], axis=0)\n\n init_rew = jnp.array([0.0])\n init_params = (init_rew, s_mu, s_var, a_mu)\n agg_rew, _, _, _ = jax.lax.fori_loop( 0, depth, rollout_fn, init_params)\n return agg_rew.sum()\n return _q\n \ndef grad_q(q): \n def _grad_q(s, ac_mu):\n \"\"\"\n Compute the gradient of Q-function for a single restart with actions\n \"\"\"\n return jax.grad(q, argnums=(1), allow_int=True)(s, ac_mu)\n return _grad_q\n\n#####################################\n# Dynamics Distribution Fn\n#####################################\n\n# No variance mode\ndef dynamics_nv(ns_fn, env, noise_dist, n_real_var, n_bin_var):\n def _dynamics_nv(s_mu, s_var, a_mu):\n ns = ns_fn(s_mu, a_mu, env)\n \n noise_mean, noise_var = noise_dist\n ns_mu = jnp.concatenate([ns, noise_mean], axis=0)\n ns_var = jnp.concatenate([jnp.zeros_like(ns), noise_var], axis=0)\n\n return ns_mu, ns_var\n return _dynamics_nv\n\n# Complete Mode\ndef dynamics_comp(ns_fn, env, fop_fn, sop_fn, noise_dist, n_real_var, n_bin_var):\n def _dynamics_comp(s_mu, s_var, a_mu):\n ns = ns_fn(s_mu, a_mu, env)\n \n fop_wrt_s, fop_wrt_ac = fop_fn(s_mu, a_mu)\n sop_wrt_s, sop_wrt_ac = sop_fn(s_mu, a_mu)\n\n # Taylor's expansion\n ns_mu = ns + 0.5*(jnp.multiply(sop_wrt_s, s_var).sum(axis=1))\n ns_var = jnp.multiply(jnp.square(fop_wrt_s), s_var).sum(axis=1)\n\n noise_mean, noise_var = noise_dist\n ns_mu = jnp.concatenate([ns_mu, noise_mean], axis=0)\n ns_var = jnp.concatenate([ns_var, noise_var], axis=0)\n\n return ns_mu, ns_var\n return _dynamics_comp\n\n#####################################\n# Reward distribution fn\n#####################################\n\ndef reward_mean(reward_fn, env):\n def _reward_mean(s_mu, s_var, ac_mu):\n return reward_fn(s_mu, ac_mu, env)\n return _reward_mean\n\ndef reward_comp(reward_fn, env):\n def _reward_comp(s_mu, s_var, ac_mu):\n reward_mu = reward_fn(s_mu, ac_mu, env)\n def _diag_hessian(wrt):\n hess = jax.hessian(reward_fn, wrt)(s_mu, ac_mu, env)\n return jax.numpy.diagonal(hess, axis1=0, axis2=1)\n sop_wrt_s = _diag_hessian(0)\n sop_wrt_ac = _diag_hessian(1)\n\n return reward_mu + 0.5*(jnp.multiply(sop_wrt_s, s_var).sum(axis=0))\n return _reward_comp\n\n#########################################\n# Functions for computing partials - Analytic\n###########################################\n\ndef fop_analytic(ns_fn, env):\n def _fop_analytic(s_mu, ac_mu):\n return jax.jacfwd(ns_fn, argnums=(0, 1))(s_mu, ac_mu, env)\n return _fop_analytic\n\ndef sop_analytic(ns_fn, env):\n def _sop_analytic(s_mu, ac_mu):\n def _diag_hessian(wrt):\n hess = jax.hessian(ns_fn, wrt)(s_mu, ac_mu, env)\n return jax.numpy.diagonal(hess, axis1=1, axis2=2)\n # TODO: Compute in one call\n sop_wrt_s = _diag_hessian(0)\n sop_wrt_ac = _diag_hessian(1)\n return sop_wrt_s, sop_wrt_ac\n return _sop_analytic", "repo_name": "pecey/DiSProD", "sub_path": "planners/discrete_disprod.py", "file_name": "discrete_disprod.py", "file_ext": "py", "file_size_in_byte": 11532, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "24", "api": [{"api_name": "planners.disprod.Disprod", "line_number": 8, "usage_type": "name"}, {"api_name": "jax.jit", "line_number": 30, "usage_type": "call"}, {"api_name": "jax.numpy.max", "line_number": 30, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 30, "usage_type": "name"}, {"api_name": "jax.numpy.abs", "line_number": 30, "usage_type": "call"}, {"api_name": "jax.numpy.array", "line_number": 40, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 40, "usage_type": "name"}, {"api_name": "jax.vmap", "line_number": 43, "usage_type": "call"}, {"api_name": "jax.numpy.sqrt", "line_number": 67, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 67, "usage_type": "name"}, {"api_name": "jax.random.normal", "line_number": 67, "usage_type": "call"}, {"api_name": "jax.random", "line_number": 67, "usage_type": "attribute"}, {"api_name": "jax.vmap", "line_number": 71, "usage_type": "call"}, {"api_name": "jax.vmap", "line_number": 73, "usage_type": "call"}, {"api_name": "jax.random.split", "line_number": 77, "usage_type": "call"}, {"api_name": "jax.random", "line_number": 77, "usage_type": "attribute"}, {"api_name": "jax.random.uniform", "line_number": 78, "usage_type": "call"}, {"api_name": "jax.random", "line_number": 78, "usage_type": "attribute"}, {"api_name": "jax.numpy.tile", "line_number": 86, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 86, "usage_type": "name"}, {"api_name": "jax.random.split", "line_number": 90, "usage_type": "call"}, {"api_name": "jax.random", "line_number": 90, "usage_type": "attribute"}, {"api_name": "planners.utils.adam_with_projection", "line_number": 95, "usage_type": "call"}, {"api_name": "jax.numpy.where", "line_number": 122, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 122, "usage_type": "name"}, {"api_name": "jax.numpy.ones", "line_number": 122, "usage_type": "call"}, {"api_name": "jax.numpy.int32", "line_number": 122, "usage_type": "attribute"}, {"api_name": "jax.numpy.zeros", "line_number": 122, "usage_type": "call"}, {"api_name": "jax.numpy.tile", "line_number": 123, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 123, "usage_type": "name"}, {"api_name": "jax.numpy.max", "line_number": 130, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 130, "usage_type": "name"}, {"api_name": "jax.numpy.abs", "line_number": 130, "usage_type": "call"}, {"api_name": "jax.numpy.sum", "line_number": 132, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 132, "usage_type": "name"}, {"api_name": "jax.numpy.logical_and", "line_number": 136, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 136, "usage_type": "name"}, {"api_name": "jax.numpy.logical_not", "line_number": 136, "usage_type": "call"}, {"api_name": "jax.numpy.zeros", "line_number": 140, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 140, "usage_type": "name"}, {"api_name": "jax.lax.while_loop", "line_number": 141, "usage_type": "call"}, {"api_name": "jax.lax", "line_number": 141, "usage_type": "attribute"}, {"api_name": "jax.numpy.nanargmax", "line_number": 151, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 151, "usage_type": "name"}, {"api_name": "jax.numpy.argmax", "line_number": 154, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 154, "usage_type": "name"}, {"api_name": "functools.partial", "line_number": 81, "usage_type": "call"}, {"api_name": "jax.jit", "line_number": 81, "usage_type": "attribute"}, {"api_name": "jax.random.split", "line_number": 171, "usage_type": "call"}, {"api_name": "jax.random", "line_number": 171, "usage_type": "attribute"}, {"api_name": "jax.random.randint", "line_number": 173, "usage_type": "call"}, {"api_name": "jax.random", "line_number": 173, "usage_type": "attribute"}, {"api_name": "jax.random.dirichlet", "line_number": 175, "usage_type": "call"}, {"api_name": "jax.random", "line_number": 175, "usage_type": "attribute"}, {"api_name": "jax.numpy.ones", "line_number": 175, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 175, "usage_type": "name"}, {"api_name": "jax.numpy.round", "line_number": 177, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 177, "usage_type": "name"}, {"api_name": "jax.numpy.concatenate", "line_number": 179, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 179, "usage_type": "name"}, {"api_name": "jax.numpy.sort", "line_number": 186, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 186, "usage_type": "name"}, {"api_name": "jax.numpy.cumsum", "line_number": 187, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 187, "usage_type": "name"}, {"api_name": "jax.numpy.arange", "line_number": 188, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 188, "usage_type": "name"}, {"api_name": "jax.numpy.where", "line_number": 189, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 189, "usage_type": "name"}, {"api_name": "jax.numpy.arange", "line_number": 189, "usage_type": "call"}, {"api_name": "jax.numpy.int32", "line_number": 189, "usage_type": "attribute"}, {"api_name": "jax.numpy.ones", "line_number": 189, "usage_type": "call"}, {"api_name": "jax.numpy.max", "line_number": 190, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 190, "usage_type": "name"}, {"api_name": "jax.nn.relu", "line_number": 192, "usage_type": "call"}, {"api_name": "jax.nn", "line_number": 192, "usage_type": "attribute"}, {"api_name": "jax.vmap", "line_number": 193, "usage_type": "call"}, {"api_name": "jax.numpy.concatenate", "line_number": 214, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 214, "usage_type": "name"}, {"api_name": "jax.numpy.concatenate", "line_number": 215, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 215, "usage_type": "name"}, {"api_name": "jax.numpy.array", "line_number": 217, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 217, "usage_type": "name"}, {"api_name": "jax.lax.fori_loop", "line_number": 219, "usage_type": "call"}, {"api_name": "jax.lax", "line_number": 219, "usage_type": "attribute"}, {"api_name": "jax.grad", "line_number": 228, "usage_type": "call"}, {"api_name": "jax.numpy.concatenate", "line_number": 241, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 241, "usage_type": "name"}, {"api_name": "jax.numpy.concatenate", "line_number": 242, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 242, "usage_type": "name"}, {"api_name": "jax.numpy.zeros_like", "line_number": 242, "usage_type": "call"}, {"api_name": "jax.numpy.multiply", "line_number": 256, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 256, "usage_type": "name"}, {"api_name": "jax.numpy.multiply", "line_number": 257, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 257, "usage_type": "name"}, {"api_name": "jax.numpy.square", "line_number": 257, "usage_type": "call"}, {"api_name": "jax.numpy.concatenate", "line_number": 260, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 260, "usage_type": "name"}, {"api_name": "jax.numpy.concatenate", "line_number": 261, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 261, "usage_type": "name"}, {"api_name": "jax.hessian", "line_number": 279, "usage_type": "call"}, {"api_name": "jax.numpy.diagonal", "line_number": 280, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 280, "usage_type": "attribute"}, {"api_name": "jax.numpy.multiply", "line_number": 284, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 284, "usage_type": "name"}, {"api_name": "jax.jacfwd", "line_number": 293, "usage_type": "call"}, {"api_name": "jax.hessian", "line_number": 299, "usage_type": "call"}, {"api_name": "jax.numpy.diagonal", "line_number": 300, "usage_type": "call"}, {"api_name": "jax.numpy", "line_number": 300, "usage_type": "attribute"}]} +{"seq_id": "30181111836", "text": "__author__ = 'schlitzer'\n\nimport logging\n\nfrom bottle import request\n\nfrom el_aap_api.errors import *\n\n\nclass AuthenticationAuthorization(object):\n def __init__(self, users, sessions):\n self.users = users\n self.sessions = sessions\n self.log = logging.getLogger('el_aap')\n\n @method_wrapper\n def _get_session_from_header(self):\n request_id = request.environ.get('REQUEST_ID', None)\n self.log.debug('{0} trying to get session from header'.format(request_id))\n result = {}\n _id = request.get_header('X-SID', False)\n token = request.get_header('X-TOKEN', False)\n if _id and token:\n result['_id'] = _id\n result['token'] = token\n self.log.debug('{0} success trying to get session from header'.format(request_id))\n return result\n self.log.debug('{0} failed trying to get session from header'.format(request_id))\n\n @method_wrapper\n def _get_session_from_cookie(self):\n request_id = request.environ.get('REQUEST_ID', None)\n self.log.debug('{0} trying to get session from cookie'.format(request_id))\n result = {}\n _id = request.get_cookie('sid', False)\n token = request.get_cookie('token', False)\n if _id and token:\n result['_id'] = _id\n result['token'] = token\n self.log.debug('{0} success trying to get session from cookie'.format(request_id))\n return result\n self.log.debug('{0} failed trying to get session from cookie'.format(request_id))\n\n @method_wrapper\n def _get_session(self):\n request_id = request.environ.get('REQUEST_ID', None)\n self.log.debug('{0} trying to get session'.format(request_id))\n session = self._get_session_from_header()\n if not session:\n session = self._get_session_from_cookie()\n if not session:\n self.log.warning('{0} failed trying to get session'.format(request_id))\n raise SessionError\n self.log.debug('{0} success trying to get session'.format(request_id))\n return session\n\n @method_wrapper\n def get_session(self):\n session = self._get_session()\n self.sessions.check_session(session)\n return session\n\n @method_wrapper\n def get_user(self):\n return self.sessions.check_session(self._get_session())\n\n @method_wrapper\n def require_admin(self):\n self.users.require_admin(self.get_user())\n", "repo_name": "schlitzered/el_aap", "sub_path": "el_aap_api/models/aa.py", "file_name": "aa.py", "file_ext": "py", "file_size_in_byte": 2468, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "logging.getLogger", "line_number": 14, "usage_type": "call"}, {"api_name": "bottle.request.environ.get", "line_number": 18, "usage_type": "call"}, {"api_name": "bottle.request.environ", "line_number": 18, "usage_type": "attribute"}, {"api_name": "bottle.request", "line_number": 18, "usage_type": "name"}, {"api_name": "bottle.request.get_header", "line_number": 21, "usage_type": "call"}, {"api_name": "bottle.request", "line_number": 21, "usage_type": "name"}, {"api_name": "bottle.request.get_header", "line_number": 22, "usage_type": "call"}, {"api_name": "bottle.request", "line_number": 22, "usage_type": "name"}, {"api_name": "bottle.request.environ.get", "line_number": 32, "usage_type": "call"}, {"api_name": "bottle.request.environ", "line_number": 32, "usage_type": "attribute"}, {"api_name": "bottle.request", "line_number": 32, "usage_type": "name"}, {"api_name": "bottle.request.get_cookie", "line_number": 35, "usage_type": "call"}, {"api_name": "bottle.request", "line_number": 35, "usage_type": "name"}, {"api_name": "bottle.request.get_cookie", "line_number": 36, "usage_type": "call"}, {"api_name": "bottle.request", "line_number": 36, "usage_type": "name"}, {"api_name": "bottle.request.environ.get", "line_number": 46, "usage_type": "call"}, {"api_name": "bottle.request.environ", "line_number": 46, "usage_type": "attribute"}, {"api_name": "bottle.request", "line_number": 46, "usage_type": "name"}]} +{"seq_id": "601928288", "text": "#!/usr/bin python\n# -*- encoding: utf-8 -*-\n'''\n@File : smart_api.py\n@Time : 2021/01/15 11:50:47\n'''\nimport json\nimport requests\nimport logging\nfrom utils.jkaes import jkAes\nfrom django.conf import settings\n\n\nlogger = logging.getLogger('console')\n\nclass SmartApi():\n def __init__(self, args):\n self.url = 'http://{}:{}'.format(\n settings.SMART_AGENT_SERVER['host'],\n str(settings.SMART_AGENT_SERVER['port'])\n )\n self.args = args\n if self.args == '':\n self.workdir = ''\n elif self.args.split('.')[-1] == 'sh':\n self.workdir = settings.SMART_AGENT_SCRIPT_PATH_LINUX\n elif self.args.split('.')[-1] == 'bat':\n self.workdir = settings.SMART_AGENT_SCRIPT_PATH_WINDOWS\n elif self.args.split('.')[-1] == 'ps1':\n self.workdir = settings.SMART_AGENT_SCRIPT_PATH_WINDOWS\n else:\n self.workdir = ''\n\n\n def hosts_list(self):\n hosts_url = '{}/host/list'.format(self.url)\n data = json.loads(requests.get(hosts_url).text)\n # logger.debug(data)\n return data\n\n def sys_info(self, hid):\n info_url = '{}/hm/static?id={}'.format(self.url, hid)\n data = json.loads(requests.get(info_url).text)\n logger.debug(data)\n return data\n\n def process_info(self, hid):\n process_url = '{}/hm/dynamic/process?id={}'.format(self.url, hid)\n data = json.loads(requests.get(process_url).text)\n logger.debug(data)\n return data\n\n def connection_info(self, hid):\n conn_url = '{}/hm/dynamic/connections?id={}'.format(self.url, hid)\n data = json.loads(requests.get(conn_url).text)\n logger.debug(data)\n return data\n\n def cmd_status(self, hid, pid):\n status_url = '{}/cmd/status?id={}&pid={}'.format(self.url, hid, pid)\n data = requests.get(status_url)\n # logger.debug(data)\n return data\n\n def cmd_run(self, hid, args, option_args, time_out, become):\n if become:\n cmd_url = '{}/cmd/run?workdir={}&id={}&cmd={}&args={}&timeout={}&auth={}&user={}&pass={}'.format(\n self.url, self.workdir, hid, args, option_args, time_out,\n become.get('method'),\n become.get('username'),\n jkAes().decrypt(become.get('password')))\n else:\n cmd_url = '{}/cmd/run?workdir={}&id={}&cmd={}&args={}&timeout={}'.format(\n self.url, self.workdir, hid, args, option_args, time_out)\n data = json.loads(requests.get(cmd_url).text)\n # logger.debug(data)\n return data\n\n def cmd_pty(self, agent_id, channel_id):\n pty_url = '{}/cmd/pty?id={}&pid={}'.format(self.url, agent_id, channel_id)\n data = requests.get(pty_url).text\n try:\n data = json.loads(data.replace('\\n', '').replace('\\r', ''))\n except:\n data = data.replace('\\n', '').replace('\\r', '')\n # logger.debug(data)\n return data\n\n def file_upload(self, payload, files):\n upload_url = '{}/file/upload'.format(self.url)\n data = requests.post(upload_url, data=payload, files=files)\n # logger.debug(data)\n return data\n\n def file_download(self, payload, files):\n download_url = '{}/file/download'.format(self.url)\n data = requests.post(download_url, data=payload, files=files)\n # logger.debug(data)\n return data", "repo_name": "llllllizili/exec-svc", "sub_path": "apps/jkexec/exectools/smartagentApi/smart_api.py", "file_name": "smart_api.py", "file_ext": "py", "file_size_in_byte": 3446, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "logging.getLogger", "line_number": 14, "usage_type": "call"}, {"api_name": "django.conf.settings.SMART_AGENT_SERVER", "line_number": 19, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 19, "usage_type": "name"}, {"api_name": "django.conf.settings.SMART_AGENT_SERVER", "line_number": 20, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 20, "usage_type": "name"}, {"api_name": "django.conf.settings.SMART_AGENT_SCRIPT_PATH_LINUX", "line_number": 26, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 26, "usage_type": "name"}, {"api_name": "django.conf.settings.SMART_AGENT_SCRIPT_PATH_WINDOWS", "line_number": 28, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 28, "usage_type": "name"}, {"api_name": "django.conf.settings.SMART_AGENT_SCRIPT_PATH_WINDOWS", "line_number": 30, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 30, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 37, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 37, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 43, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 43, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 49, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 49, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 55, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 55, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 61, "usage_type": "call"}, {"api_name": "utils.jkaes.jkAes", "line_number": 71, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 75, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 75, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 81, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 83, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 91, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 97, "usage_type": "call"}]} +{"seq_id": "29796097428", "text": "from csv import reader\nfrom bs4 import BeautifulSoup\nfrom bs4.element import ResultSet\nfrom selenium import webdriver\nimport json\nfrom database import DataBase\n\n\ndef get_url(asin):\n \"\"\"genera url\"\"\"\n #template = 'https://www.buscalibre.com.ar/amazon?url=https%3A%2F%2Fwww.amazon.com%2Fdp%2F{}&t=tetraemosv4'\n template = 'https://www.buscalibre.com.ar/boton-prueba-gp?t=tetraemosv4&envio-avion=1&codigo={}-com&sitio=amazon&version=2&condition=new'\n url = template.format(asin) \n\n return url\n\ndef get_item(soup,url,price_amz,img,asin):\n product_name = soup.find('div','product-name')\n\n # nombre\n try:\n name = product_name.h1.text\n except AttributeError:\n return\n\n # stock y peso\n description = soup.find('div','short-description')\n stock = description.find('span', {'id':'stock_producto_ajax'}).text.strip()\n weight = description.find('span', {'id':'weight_producto_ajax'}).text\n weight = weight.replace('.',',')\n\n # precio\n price_parent = soup.find('div','product-price-box-wrap')\n price = price_parent.find('span', {'id':'allfinalpricecountry_ar_producto_ajax'}).text\n \n \n # imagenes\n images_parent = soup.find('div','tumbSlider')\n images = []\n for image in images_parent.find_all('a',{'id':'mainthumb_link_producto_ajax'}):\n images.append(image.get('href'))\n \n images =json.dumps(images)\n\n result = (name, asin, price_amz, img, stock, weight, url,price, images)\n\n return result\n\ndef main(): \n # conexion a base\n database = DataBase()\n\n records = database.amazon_get_items() \n if(len(records) != 0):\n\n # iniciar webdriver\n driver = webdriver.Chrome()\n \n #cambio codificacion de caracteres\n (driver.page_source).encode('utf-8')\n \n \n for record in records: \n id = record[0]\n asin = record[1]\n\n url = get_url(asin)\n \n driver.get(url) \n\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n price_parent = soup.find('div','precio-transporte')\n if price_parent:\n price_bl = price_parent.find('span', 'price').text\n database.amazon_update_item(True,price_bl,id)\n else:\n database.amazon_update_item(False,'',id)\n \n database.close()\n driver.close() \n else:\n print(\"NO SE ENCONTRARON PRODUCTOS PARA VERIFICAR\")\n\n\nmain()\n", "repo_name": "maurojcordoba/amazon-scrap", "sub_path": "buscalibre-scrap.py", "file_name": "buscalibre-scrap.py", "file_ext": "py", "file_size_in_byte": 2476, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "json.dumps", "line_number": 43, "usage_type": "call"}, {"api_name": "database.DataBase", "line_number": 51, "usage_type": "call"}, {"api_name": "database.amazon_get_items", "line_number": 53, "usage_type": "call"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 57, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 57, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 71, "usage_type": "call"}, {"api_name": "database.amazon_update_item", "line_number": 75, "usage_type": "call"}, {"api_name": "database.amazon_update_item", "line_number": 77, "usage_type": "call"}, {"api_name": "database.close", "line_number": 79, "usage_type": "call"}]} +{"seq_id": "6610046018", "text": "from pyomo.environ import value\nfrom mpisppy import haveMPI, global_toc, MPI\n\nfrom mpisppy.utils.sputils import (\n first_stage_nonant_writer,\n scenario_tree_solution_writer,\n )\n\nclass WheelSpinner:\n\n def __init__(self, hub_dict, list_of_spoke_dict):\n \"\"\" top level for the hub and spoke system\n Args:\n hub_dict(dict): controls hub creation\n list_of_spoke_dict(list dict): controls creation of spokes\n \n Returns:\n spcomm (Hub or Spoke object): the object that did the work (windowless)\n opt_dict (dict): the dictionary that controlled creation for this rank\n \n NOTE: the return is after termination; the objects are provided for query.\n \n \"\"\"\n if not haveMPI:\n raise RuntimeError(\"spin_the_wheel called, but cannot import mpi4py\")\n self.hub_dict = hub_dict\n self.list_of_spoke_dict = list_of_spoke_dict\n\n self._ran = False\n\n def spin(self, comm_world=None):\n return self.run(comm_world=comm_world)\n\n def run(self, comm_world=None):\n \"\"\" top level for the hub and spoke system\n Args:\n comm_world (MPI comm): the world for this hub-spoke system\n \"\"\"\n if self._ran:\n raise RuntimeError(\"WheelSpinner can only be run once\")\n\n hub_dict = self.hub_dict\n list_of_spoke_dict = self.list_of_spoke_dict\n\n # Confirm that the provided dictionaries specifying\n # the hubs and spokes contain the appropriate keys\n if \"hub_class\" not in hub_dict:\n raise RuntimeError(\n \"The hub_dict must contain a 'hub_class' key specifying \"\n \"the hub class to use\"\n )\n if \"opt_class\" not in hub_dict:\n raise RuntimeError(\n \"The hub_dict must contain an 'opt_class' key specifying \"\n \"the SPBase class to use (e.g. PHBase, etc.)\"\n )\n if \"hub_kwargs\" not in hub_dict:\n hub_dict[\"hub_kwargs\"] = dict()\n if \"opt_kwargs\" not in hub_dict:\n hub_dict[\"opt_kwargs\"] = dict()\n for spoke_dict in list_of_spoke_dict:\n if \"spoke_class\" not in spoke_dict:\n raise RuntimeError(\n \"Each spoke_dict must contain a 'spoke_class' key \"\n \"specifying the spoke class to use\"\n )\n if \"opt_class\" not in spoke_dict:\n raise RuntimeError(\n \"Each spoke_dict must contain an 'opt_class' key \"\n \"specifying the SPBase class to use (e.g. PHBase, etc.)\"\n )\n if \"spoke_kwargs\" not in spoke_dict:\n spoke_dict[\"spoke_kwargs\"] = dict()\n if \"opt_kwargs\" not in spoke_dict:\n spoke_dict[\"opt_kwargs\"] = dict()\n \n if comm_world is None:\n comm_world = MPI.COMM_WORLD\n n_spokes = len(list_of_spoke_dict)\n \n # Create the necessary communicators\n fullcomm = comm_world\n strata_comm, cylinder_comm = _make_comms(n_spokes, fullcomm=fullcomm)\n strata_rank = strata_comm.Get_rank()\n cylinder_rank = cylinder_comm.Get_rank()\n global_rank = fullcomm.Get_rank()\n \n # Assign hub/spokes to individual ranks\n if strata_rank == 0: # This rank is a hub\n sp_class = hub_dict[\"hub_class\"]\n sp_kwargs = hub_dict[\"hub_kwargs\"]\n opt_class = hub_dict[\"opt_class\"]\n opt_kwargs = hub_dict[\"opt_kwargs\"]\n opt_dict = hub_dict\n else: # This rank is a spoke\n spoke_dict = list_of_spoke_dict[strata_rank - 1]\n sp_class = spoke_dict[\"spoke_class\"]\n sp_kwargs = spoke_dict[\"spoke_kwargs\"]\n opt_class = spoke_dict[\"opt_class\"]\n opt_kwargs = spoke_dict[\"opt_kwargs\"]\n opt_dict = spoke_dict\n\n # Create the appropriate opt object locally\n opt_kwargs[\"mpicomm\"] = cylinder_comm\n opt = opt_class(**opt_kwargs)\n \n # Create the SPCommunicator object (hub/spoke) with\n # the appropriate SPBase object attached\n if strata_rank == 0: # Hub\n spcomm = sp_class(opt, fullcomm, strata_comm, cylinder_comm,\n list_of_spoke_dict, **sp_kwargs) \n else: # Spokes\n spcomm = sp_class(opt, fullcomm, strata_comm, cylinder_comm, **sp_kwargs) \n \n # Create the windows, run main(), destroy the windows\n spcomm.make_windows()\n if strata_rank == 0:\n spcomm.setup_hub()\n\n global_toc(\"Starting spcomm.main()\")\n spcomm.main()\n if strata_rank == 0: # If this is the hub\n spcomm.send_terminate()\n \n # Anything that's left to do\n spcomm.finalize()\n \n # to ensure the messages below are True\n cylinder_comm.Barrier()\n global_toc(f\"Hub algorithm {opt_class.__name__} complete, waiting for spoke finalization\")\n global_toc(f\"Spoke {sp_class.__name__} finalized\", (cylinder_rank == 0 and strata_rank != 0))\n \n fullcomm.Barrier()\n \n ## give the hub the chance to catch new values\n spcomm.hub_finalize()\n \n fullcomm.Barrier()\n\n spcomm.free_windows()\n global_toc(\"Windows freed\")\n\n self.spcomm = spcomm\n self.opt_dict = opt_dict\n self.global_rank = global_rank\n self.strata_rank = strata_rank\n self.cylinder_rank = cylinder_rank\n\n if self.strata_rank == 0:\n self.BestInnerBound = spcomm.BestInnerBound\n self.BestOuterBound = spcomm.BestOuterBound\n else: # the cylinder ranks don't track the inner / outer bounds\n self.BestInnerBound = None\n self.BestOuterBound = None\n\n self._ran = True\n\n def on_hub(self):\n if not self._ran:\n raise RuntimeError(\"Need to call WheelSpinner.run() before finding out.\")\n return (\"hub_class\" in self.opt_dict)\n\n def write_first_stage_solution(self, solution_file_name,\n first_stage_solution_writer=first_stage_nonant_writer):\n \"\"\" Write a solution file, if a solution is available, to the solution_file_name provided\n Args:\n solution_file_name : filename to write the solution to\n first_stage_solution_writer (optional) : custom first stage solution writer function\n \"\"\"\n if not self._ran:\n raise RuntimeError(\"Need to call WheelSpinner.run() before querying solutions.\")\n winner = self._determine_innerbound_winner()\n if winner:\n self.spcomm.opt.write_first_stage_solution(solution_file_name,first_stage_solution_writer)\n \n def write_tree_solution(self, solution_directory_name,\n scenario_tree_solution_writer=scenario_tree_solution_writer):\n \"\"\" Write a tree solution directory, if available, to the solution_directory_name provided\n Args:\n solution_file_name : filename to write the solution to\n scenario_tree_solution_writer (optional) : custom scenario solution writer function\n \"\"\"\n if not self._ran:\n raise RuntimeError(\"Need to call WheelSpinner.run() before querying solutions.\")\n winner = self._determine_innerbound_winner()\n if winner:\n self.spcomm.opt.write_tree_solution(solution_directory_name,scenario_tree_solution_writer)\n\n def local_nonant_cache(self):\n \"\"\" Returns a dict with non-anticipative values at each local node\n We assume that the optimization has been done before calling this\n \"\"\"\n if not self._ran:\n raise RuntimeError(\"Need to call WheelSpinner.run() before querying solutions.\")\n local_xhats = dict()\n for k,s in self.spcomm.opt.local_scenarios.items():\n for node in s._mpisppy_node_list:\n if node.name not in local_xhats:\n local_xhats[node.name] = [\n value(var) for var in node.nonant_vardata_list]\n return local_xhats\n\n def _determine_innerbound_winner(self):\n if self.spcomm.global_rank == 0:\n if self.spcomm.last_ib_idx is None:\n best_strata_rank = -1\n global_toc(\"No incumbent solution available to write!\")\n else:\n best_strata_rank = self.spcomm.last_ib_idx\n else:\n best_strata_rank = None\n \n best_strata_rank = self.spcomm.fullcomm.bcast(best_strata_rank, root=0)\n return (self.spcomm.strata_rank == best_strata_rank)\n\ndef _make_comms(n_spokes, fullcomm=None):\n \"\"\" Create the strata_comm and cylinder_comm for hub/spoke style runs\n \"\"\"\n if not haveMPI:\n raise RuntimeError(\"make_comms called, but cannot import mpi4py\")\n # Ensure that the proper number of processes have been invoked\n nsp1 = n_spokes + 1 # Add 1 for the hub\n if fullcomm is None:\n fullcomm = MPI.COMM_WORLD\n n_proc = fullcomm.Get_size() \n if n_proc % nsp1 != 0:\n raise RuntimeError(f\"Need a multiple of {nsp1} processes (got {n_proc})\")\n\n # Create the strata_comm and cylinder_comm\n # Cryptic comment: intra is vertical, inter is around the hub\n global_rank = fullcomm.Get_rank()\n strata_comm = fullcomm.Split(key=global_rank, color=global_rank // nsp1)\n cylinder_comm = fullcomm.Split(key=global_rank, color=global_rank % nsp1)\n return strata_comm, cylinder_comm\n", "repo_name": "Pyomo/mpi-sppy", "sub_path": "mpisppy/spin_the_wheel.py", "file_name": "spin_the_wheel.py", "file_ext": "py", "file_size_in_byte": 9500, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 47, "dataset": "github-code", "pt": "20", "api": [{"api_name": "mpisppy.haveMPI", "line_number": 24, "usage_type": "name"}, {"api_name": "mpisppy.MPI.COMM_WORLD", "line_number": 78, "usage_type": "attribute"}, {"api_name": "mpisppy.MPI", "line_number": 78, "usage_type": "name"}, {"api_name": "mpisppy.global_toc", "line_number": 120, "usage_type": "call"}, {"api_name": "mpisppy.global_toc", "line_number": 130, "usage_type": "call"}, {"api_name": "mpisppy.global_toc", "line_number": 131, "usage_type": "call"}, {"api_name": "mpisppy.global_toc", "line_number": 141, "usage_type": "call"}, {"api_name": "mpisppy.utils.sputils.first_stage_nonant_writer", "line_number": 164, "usage_type": "name"}, {"api_name": "mpisppy.utils.sputils.scenario_tree_solution_writer", "line_number": 177, "usage_type": "name"}, {"api_name": "mpisppy.utils.sputils.scenario_tree_solution_writer", "line_number": 187, "usage_type": "argument"}, {"api_name": "pyomo.environ.value", "line_number": 200, "usage_type": "call"}, {"api_name": "mpisppy.global_toc", "line_number": 207, "usage_type": "call"}, {"api_name": "mpisppy.haveMPI", "line_number": 219, "usage_type": "name"}, {"api_name": "mpisppy.MPI.COMM_WORLD", "line_number": 224, "usage_type": "attribute"}, {"api_name": "mpisppy.MPI", "line_number": 224, "usage_type": "name"}]} +{"seq_id": "3875636718", "text": "import multiprocessing as mp\nimport time\n\ndef job(x):\n print(x * x)\n\nif __name__ =='__name__':\n \n t1 = time.time()\n pool = mp.Pool()\n res = pool.map(job,range(1000))\n print(res)\n t2 = time.time()\n print(t2-t1)\n\n res = pool.apply_async(job,(2))\n print(res.get())\n \n #p1 = mp.Process(target=job,args=(1,2))\n #p1.start()\n #p1.join()", "repo_name": "a765357592/firstgithub", "sub_path": "2019/aaa/trd.py", "file_name": "trd.py", "file_ext": "py", "file_size_in_byte": 371, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "time.time", "line_number": 9, "usage_type": "call"}, {"api_name": "multiprocessing.Pool", "line_number": 10, "usage_type": "call"}, {"api_name": "time.time", "line_number": 13, "usage_type": "call"}]} +{"seq_id": "25214328160", "text": "import numpy as np\nimport time\nimport pandas as pd\n\nIN_COLAB = False\nimport sys\nif IN_COLAB:\n \n scripts_dir = '/drive/My Drive/Colab Notebooks/scripts/'\n sys.path.insert(1, scripts_dir)\n# from opfunu.cec_basic.cec2014_nobias import *\n# from mealpy.swarm_based.PSO import BasePSO\n\n# insert at 1, 0 is the script path (or '' in REPL)\nelse:\n sys.path.insert(1, 'scripts')\n\nfrom geneticalgorithm import geneticalgorithm as ga\nfrom geneticalgorithm1 import geneticalgorithm1 as ga1\nfrom geneticalgorithmOptd import geneticalgorithmOptd as gaOptd\n\nfrom PSO import BasePSO\nfrom BBO import BaseBBO\n\nimport pandas as pd\n\n# import benchmark_func as bf\n\nimport importlib\nbf = importlib.import_module(\"benchmark_func\")\n\n# class_ = getattr(bf, \"Ackley\")\n# instance = class_(2)\n\ndimension = 2\npopulation_size = 15\nmax_iter = 10\nnum_runs = 5\nseeds = np.random.randint(0, 1000, num_runs)\nvarbound=np.array([[-100, 100]]*dimension)\n\ntimestr = time.strftime(\"%Y%m%d-%H%M%S\")\nfilename = f'results/low_pop/Run_Results-{timestr}'\n\none_args = getattr(bf, \"__oneArgument__\")\ntwo_args = getattr(bf, \"__twoArgument__\")\n\nresult = {}\nresult[\"function\"] = None\nresult[\"run\"] = None\nresult[\"seed\"] = None\nresult[\"algo\"] = None\nresult[\"pop_size\"] = None\nresult[\"g_opt_val\"] = None\nresult[\"func_val\"] = None\n\nresult[\"max_iter\"] = None\nresult[\"best_iter\"] = None\n\nresults = []\n\ndef createPop(dimension=2, population_size=15):\n var=np.zeros(dimension) \n\n pop=np.array([np.zeros(dimension)]*population_size)\n for p in range(0, population_size):\n for i in range(0, dimension):\n var[i]=np.random.randint(varbound[i][0],\\\n varbound[i][1]+1) \n pop[p] = var\n data = {}\n data['pop'] = pop.copy()\n\n # print(\"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\")\n # print(data['pop'])\n\n return data\n# result = instance.get_func_val(np.array([0.0, 5.0]))\n\n# print(getattr(bf, \"__oneArgument__\"))\n\nresults_df = pd.DataFrame(results)\n\ndef normGa(obj_func, pop_data=None, seed = 777):\n algorithm_param = {'max_num_iteration': max_iter,\\\n 'population_size':population_size,\\\n 'mutation_probability':0.2,\\\n 'elit_ratio': 0.1,\\\n 'crossover_probability': .7,\\\n 'parents_portion': 0.3,\\\n 'crossover_type':'uniform',\\\n 'max_iteration_without_improv':None}\n model=ga(function=obj_func,dimension=dimension,variable_type='real',variable_boundaries=varbound, random_seed=seed, algorithm_parameters=algorithm_param)\n model.run('GA_data.dat', data=pop_data)\n\n data = {}\n data['best_sol'] = model.best_variable\n data['best_fit'] = model.best_function\n data['best_iter'] = model.iterate\n data['max_iter'] = model.iterate\n return data\n\ndef imprvGa(obj_func, pop_data=None, seed = 777):\n algorithm_param = {'max_num_iteration': max_iter,\\\n 'population_size':population_size,\\\n 'mutation_probability':0.4,\\\n 'elit_ratio': 0.1,\\\n 'crossover_probability': .7,\\\n 'parents_portion': 0.3,\\\n 'crossover_type':'uniform',\\\n 'max_iteration_without_improv':None}\n model=gaOptd(function=obj_func,dimension=dimension,variable_type='real',variable_boundaries=varbound, random_seed=seed, algorithm_parameters=algorithm_param)\n model.run('GA_data.dat', data=pop_data)\n\n data = {}\n data['best_sol'] = model.best_variable\n data['best_fit'] = model.best_function\n data['best_iter'] = model.iterate\n data['max_iter'] = model.iterate\n # data['best_sol'] = best_pos1\n # data['best_sol'] = best_pos1\n return data\n\ndef pso(obj_func, pop_data=None, seed = 777):\n lb = varbound[:, 0].tolist()\n ub = varbound[:, 1].tolist()\n\n verbose = False\n \n model = BasePSO(obj_func, lb, ub, verbose, max_iter, population_size, random_seed=seed) # Remember the keyword \"problem_size\"\n best_sol, best_fit, list_loss1 = model.train('pso_data.dat', data=pop_data)\n data = {}\n data['best_sol'] = best_sol\n data['best_fit'] = best_fit\n data['best_iter'] = max_iter\n data['max_iter'] = max_iter\n # data['best_sol'] = best_pos1\n # data['best_sol'] = best_pos1\n return data\n\ndef bbo(obj_func, pop_data=None, seed = 777):\n lb = varbound[:, 0].tolist()\n ub = varbound[:, 1].tolist()\n\n verbose = False\n\n model = BaseBBO(obj_func, lb, ub, verbose, max_iter, population_size, random_seed=seed) # Remember the keyword \"problem_size\"\n best_sol, best_fit, list_loss1 = model.train('bbo_data.dat', data=pop_data)\n data = {}\n data['best_sol'] = best_sol\n data['best_fit'] = best_fit\n data['best_iter'] = max_iter\n data['max_iter'] = max_iter\n # data['best_sol'] = best_pos1\n # data['best_sol'] = best_pos1\n return data\n\nfor func in two_args:\n class_ = getattr(bf, func)\n instance = class_(dimension)\n count = 1\n for seed in seeds:\n np.random.seed(seed)\n obj_func = instance.get_func_val\n pop_data = createPop(dimension, population_size)\n\n print(\"NormGA\")\n res = normGa(obj_func, pop_data)\n\n result = {}\n result[\"function\"] = func\n result[\"run\"] = count\n result[\"seed\"] = seed\n result[\"algo\"] = \"NormGA\"\n result[\"func_val\"] = res[\"best_fit\"]\n result[\"pop_size\"] = population_size\n result[\"max_iter\"] = max_iter\n result[\"best_iter\"] = max_iter\n\n results.append(result)\n\n print(\"imprvGA\")\n res = imprvGa(obj_func, pop_data)\n\n result = {}\n result[\"function\"] = func\n result[\"run\"] = count\n result[\"seed\"] = seed\n result[\"algo\"] = \"imprvGA\"\n result[\"func_val\"] = res[\"best_fit\"]\n result[\"pop_size\"] = population_size\n result[\"max_iter\"] = max_iter\n result[\"best_iter\"] = max_iter\n\n results.append(result)\n\n print(\"PSO\")\n res = pso(obj_func, pop_data)\n\n result = {}\n result[\"function\"] = func\n result[\"run\"] = count\n result[\"seed\"] = seed\n result[\"algo\"] = \"PSO\"\n result[\"func_val\"] = res[\"best_fit\"]\n result[\"pop_size\"] = population_size\n result[\"max_iter\"] = max_iter\n result[\"best_iter\"] = max_iter\n\n results.append(result)\n\n print(\"BBO\")\n res = bbo(obj_func, pop_data)\n\n result = {}\n result[\"function\"] = func\n result[\"run\"] = count\n result[\"seed\"] = seed\n result[\"algo\"] = \"BBO\"\n result[\"func_val\"] = res[\"best_fit\"]\n result[\"pop_size\"] = population_size\n result[\"max_iter\"] = max_iter\n result[\"best_iter\"] = max_iter\n\n results.append(result)\n\n\n \n\n count += 1\n\npd.DataFrame.from_dict(results, orient='columns').to_csv(f'{filename}.csv')\n\n\n", "repo_name": "funaquarius24/Simple-Deterministic-Selection-Based-Genetic-Algorithm", "sub_path": "BenchmarkExperiments/TestCompareLowPop.py", "file_name": "TestCompareLowPop.py", "file_ext": "py", "file_size_in_byte": 6516, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sys.path.insert", "line_number": 10, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "sys.path.insert", "line_number": 16, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 16, "usage_type": "attribute"}, {"api_name": "importlib.import_module", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 39, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 40, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 68, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 82, "usage_type": "call"}, {"api_name": "geneticalgorithm.geneticalgorithm", "line_number": 93, "usage_type": "call"}, {"api_name": "geneticalgorithmOptd.geneticalgorithmOptd", "line_number": 112, "usage_type": "call"}, {"api_name": "PSO.BasePSO", "line_number": 130, "usage_type": "call"}, {"api_name": "BBO.BaseBBO", "line_number": 147, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 163, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame.from_dict", "line_number": 232, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 232, "usage_type": "attribute"}]} +{"seq_id": "70559238464", "text": "# -*- coding: utf-8 -*-\nimport scrapy\nimport pymysql\nfrom qunaerone.items import QunaeroneItem\n\n\nclass MeishiSpider(scrapy.Spider):\n name = 'meishi'\n\n headers = {\n 'authority': \"travel.qunar.com\",\n 'cache-control': \"max-age=0,no-cache\",\n 'upgrade-insecure-requests': \"1\",\n 'user-agent': \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3876.0 Safari/537.36\",\n 'sec-fetch-mode': \"navigate\",\n 'sec-fetch-user': \"?1\",\n 'accept': \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n 'sec-fetch-site': \"same-origin\",\n 'referer': \"https://travel.qunar.com/p-cs300195-hangzhou-meishi\",\n 'accept-encoding': \"gzip, deflate, br\",\n 'accept-language': \"zh-CN,zh;q=0.9\"\n }\n\n # 初始化,从数据库获取详情链接\n def __init__(self):\n try:\n self.conn = pymysql.Connect(host='localhost', user='root', password='13567651173', database='python',\n charset='utf8')\n cur = self.conn.cursor()\n sql = 'select detail_link,area from qnems_detail_url where is_download = 0 limit 1'\n cur.execute(sql)\n self.urls = list(cur.fetchall())\n except Exception as e:\n print(\"连接数据库出错,错误原因%s\" % e)\n\n # 直接爬取详情页\n def start_requests(self):\n for url in self.urls:\n print(\"爬取链接::::::::\" + url[0])\n item = QunaeroneItem()\n item['url'] = url[0]\n item['area'] = url[1]\n yield scrapy.Request(url=url[0], callback=self.step_one, headers=self.headers, meta={'item': item})\n\n # 详情页部分内容\n def step_one(self, response):\n item = response.meta['item']\n name = response.xpath('//*[@id=\"js_mainleft\"]/div[@class=\"b_title clrfix\"]/h1/text()').extract_first()\n total_score = response.xpath(\n '//*[@id=\"js_mainleft\"]/div[4]/div/div[2]/div[1]/div[1]/span[1]/text()').extract_first()\n average_cost = response.xpath(\n '//*[@id=\"js_mainleft\"]/div[4]/div/div[2]/div[1]/div[2]/div[2]/text()').extract_first()\n overview = response.xpath('//*[@id=\"gs\"]/div[1]/p/text()').extract_first()\n address = response.xpath('//*[@id=\"gs\"]/div[2]/div[1]/table/tr/td[1]/dl[1]/dd/span/text()').extract_first()\n phone_number = response.xpath('//*[@id=\"gs\"]/div[2]/div[1]/table/tr/td[1]/dl[2]/dd/span/text()').extract_first()\n open_time = response.xpath('//*[@id=\"gs\"]/div[2]/div[1]/table/tr/td[2]/dl[1]/dd/span/p/text()').extract_first()\n images = response.xpath('//*[@id=\"idNum\"]/li/div[@class=\"imgbox\"]/img/@src').extract()\n traffic = response.xpath('//*[@id=\"jtzn\"]/div[2]/p/text()').extract_first()\n nearby_scenic = response.xpath('//*[@id=\"idContBox\"]/ul[1]/li/a/@href').extract()\n nearby_food = response.xpath('//*[@id=\"idContBox\"]/ul[2]/li/a/@href').extract()\n nearby_hotel = response.xpath('//*[@id=\"idContBox\"]/ul[3]/li/a/@href').extract()\n nearby_shopping = response.xpath('//*[@id=\"idContBox\"]/ul[4]/li/a/@href').extract()\n\n if name is not None:\n item['name'] = name\n if total_score is not None:\n item['total_score'] = total_score\n if average_cost is not None:\n item['average_cost'] = average_cost\n if overview is not None:\n item['overview'] = overview\n if address is not None:\n item['address'] = address\n if phone_number is not None:\n item['phone_number'] = phone_number\n if open_time is not None:\n item['open_time'] = open_time\n if images is not None:\n item['images'] = images\n if traffic is not None:\n item['traffic'] = traffic\n if nearby_scenic is not None:\n item['nearby_scenic'] = nearby_scenic\n if nearby_food is not None:\n item['nearby_food'] = nearby_food\n if nearby_hotel is not None:\n item['nearby_hotel'] = nearby_hotel\n if nearby_shopping is not None:\n item['nearby_shopping'] = nearby_shopping\n\n # 是否有翻页的评论需要爬取\n coments = []\n # 先爬取当前页\n for index in range(11):\n if index == 0:\n pass\n else:\n current = {}\n star = response.xpath(\n '//*[@id=\"js_replace_box\"]/div[2]/ul/li[$index]/div[1]/div[1]/div[2]/span/span/@class',\n index=index).extract_first()\n content = \"\".join(\n response.xpath('//*[@id=\"js_replace_box\"]/div[2]/ul/li[$index]/div[1]/div[1]/div[3]/p/text()',\n index=index).extract())\n images = \",\".join(response.xpath(\n '//*[@id=\"js_replace_box\"]/div[2]/ul/li[$index]/div[1]/div[1]/div[4]/div[1]/ul/li/a/@href',\n index=index).extract())\n date = response.xpath(\n '//*[@id=\"js_replace_box\"]/div[2]/ul/li[$index]/div[1]/div[1]/div[5]/ul/li[1]/text()',\n index=index).extract_first()\n reldate = response.xpath(\n '//*[@id=\"js_replace_box\"]/div[2]/ul/li[$index]/div[1]/div[1]/div[4]/ul/li[1]/text()',\n index=index).extract_first()\n if star is not None:\n current['star'] = star[-1:]\n else:\n break\n if content is not None:\n current['content'] = content.replace(\"\\r\", \"\").replace(\" \", \"\").replace(\"\\n\", \"\")\n if images is not None:\n current['images'] = images\n if date is not None:\n current['date'] = date\n else:\n if reldate is not None:\n current['date'] = reldate\n coments.append(current)\n item['comments'] = coments\n next_page = response.xpath('//*[@id=\"js_replace_box\"]/div[2]/div/a[@class=\"page next\"]/@href').extract_first()\n if next_page is not None:\n yield scrapy.Request(url=next_page, callback=self.step_two, headers=self.headers, meta={'item': item})\n\n # 下一页的评论\n def step_two(self, response):\n item = response.meta['item']\n coments = item['comments']\n # 先爬取当前页\n for index in range(11):\n if index == 0:\n pass\n else:\n current = {}\n star = response.xpath(\n '//*[@id=\"js_replace_box\"]/div[2]/ul/li[$index]/div[1]/div[1]/div[2]/span/span/@class',\n index=index).extract_first()\n content = \"\".join(\n response.xpath('//*[@id=\"js_replace_box\"]/div[2]/ul/li[$index]/div[1]/div[1]/div[3]/p/text()',\n index=index).extract())\n images = \",\".join(response.xpath(\n '//*[@id=\"js_replace_box\"]/div[2]/ul/li[$index]/div[1]/div[1]/div[4]/div[1]/ul/li/a/@href',\n index=index).extract())\n date = response.xpath(\n '//*[@id=\"js_replace_box\"]/div[2]/ul/li[$index]/div[1]/div[1]/div[5]/ul/li[1]/text()',\n index=index).extract_first()\n reldate = response.xpath(\n '//*[@id=\"js_replace_box\"]/div[2]/ul/li[$index]/div[1]/div[1]/div[4]/ul/li[1]/text()',\n index=index).extract_first()\n if star is not None:\n current['star'] = star[-1:]\n else:\n break\n if content is not None:\n current['content'] = content.replace(\"\\r\", \"\").replace(\" \", \"\").replace(\"\\n\", \"\")\n if images is not None:\n current['images'] = images\n if date is not None:\n current['date'] = date\n else:\n if reldate is not None:\n current['date'] = reldate\n coments.append(current)\n item['comments'] = coments\n next_page = response.xpath('//*[@id=\"js_replace_box\"]/div[2]/div/a[@class=\"page next\"]/@href').extract_first()\n if next_page is not None:\n yield scrapy.Request(url=next_page, callback=self.step_two, headers=self.headers, meta={'item': item})\n else:\n yield item\n", "repo_name": "haoYuanZheng/PythonScrapy", "sub_path": "qunaerone/qunaerone/spiders/meishi.py", "file_name": "meishi.py", "file_ext": "py", "file_size_in_byte": 8622, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "scrapy.Spider", "line_number": 7, "usage_type": "attribute"}, {"api_name": "pymysql.Connect", "line_number": 27, "usage_type": "call"}, {"api_name": "qunaerone.items.QunaeroneItem", "line_number": 40, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 43, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 131, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 175, "usage_type": "call"}]} +{"seq_id": "42970065761", "text": "from turtle import forward\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport math\n\nclass LRR(nn.Module):\n def __init__(self, dim_input, dim_hidden):\n super(LRR, self).__init__()\n self.dim_input = dim_input\n self.dim_hidden = dim_hidden\n self.B = nn.Linear(dim_input, dim_hidden, bias=False)\n self.w = nn.Linear(dim_hidden, 1, bias=False)\n nn.init.normal_(self.B.weight, mean=0, \n std=1 / math.sqrt(self.dim_hidden * self.dim_input))\n nn.init.normal_(self.w.weight, mean=0, \n std=1 / math.sqrt(self.dim_hidden))\n\n def forward(self, x):\n h = self.B(x)\n y = self.w(h)\n return y\n\n\nclass MLP(nn.Module):\n def __init__(self, dim_input, dim_hidden):\n super(MLP, self).__init__()\n self.dim_input = dim_input\n self.dim_hidden = dim_hidden\n self.activated = None\n self.down = nn.Linear(dim_input, dim_hidden, bias=True)\n self.up = nn.Linear(dim_hidden, 1, bias=True)\n nn.init.normal_(self.down.weight, mean=0, \n std=4 / math.sqrt(self.dim_hidden * self.dim_input))\n nn.init.normal_(self.down.bias, mean=0, \n std=4 / math.sqrt(self.dim_hidden))\n nn.init.normal_(self.up.weight, mean=0, \n std=4 / math.sqrt(self.dim_hidden))\n nn.init.normal_(self.up.bias, mean=0, \n std=4 / math.sqrt(self.dim_input))\n\n def forward(self, x):\n h = self.down(x)\n h = F.relu(h)\n self.activated = h.clone().detach()\n y = self.up(h)\n return y\n\n\n\n", "repo_name": "qiaosenwang/ActivationSparsity", "sub_path": "toy_model.py", "file_name": "toy_model.py", "file_ext": "py", "file_size_in_byte": 1608, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "torch.nn.Module", "line_number": 8, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 8, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 13, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 13, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 14, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 14, "usage_type": "name"}, {"api_name": "torch.nn.init.normal_", "line_number": 15, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 15, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 15, "usage_type": "name"}, {"api_name": "math.sqrt", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.nn.init.normal_", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 17, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 17, "usage_type": "name"}, {"api_name": "math.sqrt", "line_number": 18, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 26, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 26, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 33, "usage_type": "name"}, {"api_name": "torch.nn.init.normal_", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 34, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 34, "usage_type": "name"}, {"api_name": "math.sqrt", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.nn.init.normal_", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 36, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "name"}, {"api_name": "math.sqrt", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.nn.init.normal_", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 38, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 38, "usage_type": "name"}, {"api_name": "math.sqrt", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.nn.init.normal_", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 40, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 40, "usage_type": "name"}, {"api_name": "math.sqrt", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 45, "usage_type": "name"}]} +{"seq_id": "26416282028", "text": "import os\nfrom setuptools import setup, find_packages\n\n# single source of truth for package version\nversion_ns = {}\nwith open(os.path.join('gladier_hedm', 'version.py')) as f:\n exec(f.read(), version_ns)\nversion = version_ns['__version__']\n\ninstall_requires = []\nwith open('requirements.txt') as reqs:\n for line in reqs.readlines():\n req = line.strip()\n if not req or req.startswith('#'):\n continue\n install_requires.append(req)\n\nsetup(\n name='gladier_hedm',\n description='The HEDM Gladier Client',\n url='https://github.com/globus-gladier/gladier-hedm',\n maintainer='Hemant Sharma',\n maintainer_email='hsharma@anl.gov',\n version=version_ns['__version__'],\n packages=find_packages(),\n install_requires=install_requires,\n dependency_links=[],\n license='Apache 2.0',\n classifiers=[]\n)\n", "repo_name": "globus-gladier/gladier-hedm", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 853, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "os.path.join", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "setuptools.setup", "line_number": 18, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "29775311714", "text": "# Fichier Class Jeu, gère toute ce qui est autres que l'affichage et minimax du projet 177 lignes (avec beaucoup de saut de ligne) pour 3700 caractères\r\n# Ce fichier reprend en grande partie le de corrigé du projet Morpion\r\n\r\nimport pygame\r\nfrom pygame.locals import *\r\nimport sys\r\nfrom random import randint\r\n\r\n\r\nclass Jeu:\r\n \r\n def __init__(self):\r\n '''Créer un Objet Jeu avec un attribut score'''\r\n\r\n self.score = [0,0,0] # Score de la partie : [nombre de Victoire (J1), nombre de match nul, nombre de Défaite (J1)]\r\n\r\n \r\n \r\n def coup_jouer(self,info_jeu):\r\n \"\"\"Cette fonction prend en paramètre\r\n - info_jeu : Un Object de la class Grille\r\n Cette fonction renvoie le numéro de la case séléctionner par le Joueur, tel que représenté sur ce schéma\r\n \r\n _|_|O 0|1|2\r\n _|X|_ --> 3|4|5\r\n _|_|_ 6|7|8\r\n \"\"\"\r\n \r\n Jouer= False\r\n \r\n while Jouer == False:\r\n \r\n # Recuperer tout les inputs\r\n for event in pygame.event.get():\r\n \r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n \r\n num_case = -1\r\n \r\n if event.type == MOUSEBUTTONDOWN and event.button == 1:\r\n \r\n num_case = 0\r\n \r\n pos = pygame.mouse.get_pos()\r\n \r\n if 200 < pos[0] < 400:\r\n num_case +=1\r\n \r\n elif pos[0] > 400:\r\n num_case +=2\r\n\r\n if 250 < pos[1] < 450:\r\n num_case +=3\r\n elif pos[1] > 450:\r\n num_case +=6\r\n \r\n \r\n if event.type == pygame.KEYDOWN: # Si une touche du clavier est appuyer\r\n \r\n # Renvoie la touche correspondante au pavé numérique\r\n if event.key == pygame.K_KP1:\r\n num_case = 6\r\n if event.key == pygame.K_KP2:\r\n num_case = 7\r\n if event.key == pygame.K_KP3:\r\n num_case = 8\r\n if event.key == pygame.K_KP4:\r\n num_case = 3\r\n if event.key == pygame.K_KP5:\r\n num_case = 4\r\n if event.key == pygame.K_KP6:\r\n num_case = 5\r\n if event.key == pygame.K_KP7:\r\n num_case = 0\r\n if event.key == pygame.K_KP8:\r\n num_case = 1\r\n if event.key == pygame.K_KP9:\r\n num_case = 2\r\n \r\n if num_case != -1:\r\n if info_jeu.cases[num_case] == 0:\r\n \r\n return (num_case)\r\n \r\n \r\n \r\n\r\n def horiz(self,Liste_cases):\r\n \"\"\"Cette fonction prend en paramètre\r\n - Liste_cases qui contient les informations de chaques cases du jeu\r\n \r\n Cette fonction détermine si un des deux joueurs à 3 croix ou rond alignés en horizontal. \r\n \r\n Elle retroune un tuple de type (boolean, numéro du Joueur qui gagne int(1 ou 2), numéro de case1 int (0 à 9), numéro de case 2 int (0 à 9)).\"\"\"\r\n\r\n for i in range(0,3):\r\n if Liste_cases[i*3] == Liste_cases[i*3+1] == Liste_cases[i*3+2] != 0:\r\n return (True,Liste_cases[i*3],i*3,i*3+2)\r\n return (False,None,None,None)\r\n\r\n def vertic(self,Liste_cases):\r\n \"\"\"Cette fonction prend en paramètre\r\n - Liste_cases qui contient les informations de chaques cases du jeu\r\n \r\n Cette fonction détermine si un des deux joueurs à 3 croix ou rond alignés en vertical. \r\n \r\n Elle retroune un tuple de type (boolean, numéro du Joueur qui gagne int(1 ou 2), numéro de case1 int (0 à 9), numéro de case 2 int (0 à 9))\"\"\"\r\n\r\n for i in range(0,3):\r\n if Liste_cases[i] == Liste_cases[i+3] == Liste_cases[i+6] != 0:\r\n return (True,Liste_cases[i],i,i+6)\r\n return (False,None,None,None)\r\n\r\n\r\n def diag(self,Liste_cases):\r\n \"\"\"Cette fonction prend en paramètre\r\n - Liste_cases qui contient les informations de chaques cases du jeu\r\n \r\n Cette fonction détermine si un des deux joueurs à 3 croix ou rond alignés en diagonal. \r\n \r\n Elle retroune un tuple de type (boolean, numéro du Joueur qui gagne int(1 ou 2), numéro de case1 int (0 à 9), numéro de case 2 int (0 à 9))\r\n \r\n \r\n \"\"\"\r\n\r\n if Liste_cases[0] == Liste_cases[4] == Liste_cases[8] != 0:\r\n return (True,Liste_cases[0],0,8)\r\n \r\n if Liste_cases[2] == Liste_cases[4] == Liste_cases[6] != 0:\r\n return (True,Liste_cases[2],2,6)\r\n \r\n return (False,None,None,None)\r\n\r\n\r\n def info_victoire(self,Liste_cases):\r\n \"\"\" Cette fonction prend en paramètre\r\n - Liste_cases qui contient les informations de chaques cases du jeu\r\n \r\n Cette fonction utilise les fonction diag, horiz, et vertic et détermine si un des deux joueurs à fini la partie. \r\n \r\n Elle retroune un tuple de type (boolean, numéro du Joueur qui gagne int(1 ou 2), numéro de case1 int (0 à 9), numéro de case 2 int (0 à 9))\"\"\"\r\n \r\n horizontal = self.horiz(Liste_cases)\r\n vertical = self.vertic(Liste_cases)\r\n diagonal = self.diag(Liste_cases)\r\n \r\n if horizontal[0] == True:\r\n return horizontal\r\n \r\n if vertical[0] == True:\r\n return vertical\r\n \r\n if diagonal[0] == True:\r\n return diagonal\r\n \r\n return (False,None,None,None)\r\n\r\n\r\n def partie_nulle(self,Liste_cases,victoire):\r\n \"\"\"Cette fonction prend en paramètre\r\n - Liste_cases qui contient les informations de chaques cases du jeu\r\n - victoire : Boolean particulié de type False ou (True,numéro du Joueur qui gagne int(1 ou 2), numéro de case1 int (0 à 9), numéro de case 2 int (0 à 9))\r\n \r\n Cette fonction détermine si la partie est nulle c'est à dire qu'elle est terminé et qu'aucun des joueurs ne gagne. Elle retroune un booléen correspondant \"\"\"\r\n\r\n if victoire[0] == False:\r\n \r\n for valeur in Liste_cases:\r\n if valeur == 0:\r\n return False\r\n return True\r\n return False\r\n \r\n # Pas de case vide + Pas de victoire : Match nulle", "repo_name": "MatteoBertauld/Morpion_Graphique", "sub_path": "Fichier python/Class_jeu.py", "file_name": "Class_jeu.py", "file_ext": "py", "file_size_in_byte": 6890, "program_lang": "python", "lang": "fr", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pygame.event.get", "line_number": 34, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 34, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 36, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 37, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 38, "usage_type": "call"}, {"api_name": "pygame.mouse.get_pos", "line_number": 46, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 46, "usage_type": "attribute"}, {"api_name": "pygame.KEYDOWN", "line_number": 60, "usage_type": "attribute"}, {"api_name": "pygame.K_KP1", "line_number": 63, "usage_type": "attribute"}, {"api_name": "pygame.K_KP2", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pygame.K_KP3", "line_number": 67, "usage_type": "attribute"}, {"api_name": "pygame.K_KP4", "line_number": 69, "usage_type": "attribute"}, {"api_name": "pygame.K_KP5", "line_number": 71, "usage_type": "attribute"}, {"api_name": "pygame.K_KP6", "line_number": 73, "usage_type": "attribute"}, {"api_name": "pygame.K_KP7", "line_number": 75, "usage_type": "attribute"}, {"api_name": "pygame.K_KP8", "line_number": 77, "usage_type": "attribute"}, {"api_name": "pygame.K_KP9", "line_number": 79, "usage_type": "attribute"}]} +{"seq_id": "44018240539", "text": "import httplib\nimport urllib\nimport json\nimport logging\nimport pandas\n\ndef scrapeGame(wpID):\n gameConnection = httplib.HTTPSConnection('public-api.wordpress.com')\n gameConnection.request('GET', '/rest/v1/sites/%d/posts/' % wpID)\n postsConn = gameConnection.getresponse()\n #postsJSON = postsConn.read()\n postsJSON = json.loads(postsConn.read())\n postIDs = []\n posts = {}\n for post in postsJSON['posts']:\n postIDs.append(post['ID'])\n posts[post['ID']] = post['title']\n logging.info(\"Got posts %s\" % postIDs)\n comments = []\n for postID in postIDs:\n gameConnection.request(\n 'GET', \n '/rest/v1/sites/%d/posts/%d/replies?number=100' % (wpID, postID))\n logging.info(\"Getting replies to post %d:%s\" % (postID, posts[postID]))\n commentsConn = gameConnection.getresponse()\n commentsJSON = json.loads(commentsConn.read())\n totalComments = commentsJSON['found']\n commentsRead = 100\n while totalComments > 0:\n newComments = map(lambda c: \n (c['ID'], c['author']['name'], c['content']), \n commentsJSON['comments'])\n comments.extend(newComments)\n\n gameConnection.request(\n 'GET', \n '/rest/v1/sites/%d/posts/%d/replies?offset=%d&number=100' % (wpID, postID, commentsRead))\n logging.info(\"Getting replies to post %d with offset %d\" % \n (postID, commentsRead))\n commentsConn = gameConnection.getresponse()\n commentsJSON = json.loads(commentsConn.read())\n totalComments -= len(newComments)\n commentsRead += len(newComments)\n ids = []\n posts = []\n contents = []\n authors = []\n for comment in comments:\n ids.append(comment[0])\n authors.append(comment[1])\n contents.append(comment[2])\n posts.append(postID)\n return pandas.DataFrame({\n 'id':ids, \n 'post':posts,\n 'content':contents,\n 'author':authors})\n", "repo_name": "ririw/lawyered", "sub_path": "lawyered/wpScraper.py", "file_name": "wpScraper.py", "file_ext": "py", "file_size_in_byte": 1962, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "httplib.HTTPSConnection", "line_number": 8, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 12, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 18, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 24, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 26, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 38, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 41, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 53, "usage_type": "call"}]} +{"seq_id": "40133562896", "text": "#!/usr/bin/env python3\n# coding: utf-8\n\nimport sys, os, glob, logging\nimport itertools, functools\nfrom pathlib import Path\n\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\n\ncurr = Path('.').resolve()\nfor path in Path('.').resolve().parents:\n print(\"path:\",path, (path / 'scilab').exists())\n if (path / 'scilab').exists():\n scibase = path\n\nprint(\"scibase:\",scibase)\nsys.path.insert(0,str(scibase))\n\nfrom scilab.tools.project import *\nfrom scilab.tools.instroncsv import *\n\nimport scilab.tools.project as Project\nimport scilab.tools.excel as Excel\nimport scilab.tools.graphing as Graphing\nimport scilab.tools.scriptrunner as ScriptRunner\nimport scilab.tools.jsonutils as Json\n\nfrom scilab.tools.tables import mdBlock, mdHeader, ImageTable, MarkdownTable\nfrom scilab.expers.mechanical.fatigue.helpers import *\nfrom scilab.expers.configuration import FileStructure, TestInfo, TestData, TestDetails\n\nimport scilab.expers.mechanical.fatigue.cycles as fatigue_cycles\nimport scilab.expers.mechanical.fatigue.uts as fatigue_uts\n\n\nPlotData = namedtuple('PlotData', 'array label units max')\n \ndef process_uts_tests(testinfo, testfolder, handlers, reportfile):\n args = DataTree()\n args.experReportGraphs = testfolder.graphs\n args.experJson = testfolder.jsoncalc\n args.experJsonCalc = testfolder.jsoncalc\n args.only_first = False\n args.report = reportfile \n args.step = 2\n args.begin = 80.3\n args.end = 4.8\n \n data = DataTree()\n data.tests = DataTree()\n \n trackingtest = testfolder.raws.csv_step04_uts.tracking\n trackingdata = csvread(trackingtest.as_posix())\n data.tracking = trackingdata\n \n data.tests.uts = DataTree(tracking=trackingdata)\n # debug(testfolder.raws.csv_step02_precond.tracking)\n data.tests.preconds = DataTree(tracking = csvread( testfolder.raws.csv_step02_precond.tracking )) \n data.datasheet = testfolder.datasheet\n \n data.details = Json.load_json_from(testfolder.details)\n \n return [ handler(testinfo=testinfo, testfolder=testfolder, testdata=data, args=args)\n for handler in handlers ]\n\n measurements = run_image_measure.process_test(testinfo, testfolder)\n \n \n\ndef process_cycle_tests(testinfo, testfolder, reportfile, doLoad, handlers,):\n args = DataTree()\n args.experReportGraphs = testfolder.graphs\n args.experJson = testfolder.jsoncalc\n args.experJsonCalc = testfolder.jsoncalc\n args.only_first = False\n args.report = reportfile\n args.doLoad = doLoad\n \n testdata = TestData(tests=TestData())\n \n # debug(testfolder.raws.preconds_csv.tracking)\n testdata.tests.preconds = DataTree(tracking = csvread( testfolder.raws.preconds_csv.tracking )) \n\n cycles_test = 'cycles_{}_csv'.format(testinfo.orientation)\n debug(cycles_test, testfolder.raws[cycles_test].tracking)\n testdata.tests.cycles = TestData()\n if doLoad.tracking:\n csvdata_tracking = csvread(testfolder.raws[cycles_test].tracking.as_posix())\n testdata.tests.cycles.tracking = csvdata_tracking\n if doLoad.trends:\n csvdata_trends = csvread(testfolder.raws[cycles_test].trends.as_posix())\n testdata.tests.cycles.trends = csvdata_trends\n\n testdata.details = Json.load_json_from(testfolder.details)\n \n results = []\n for handler in handlers:\n results.append( handler(testinfo=testinfo, testfolder=testfolder, testdata=testdata, args=args) )\n \n return results \n\ndef process_test(testinfo, testfolder, reportfile):\n\n debug(testinfo, testinfo)\n\n import scilab.utilities.make_data_json as make_data_json\n import scilab.utilities.merge_calculated_jsons as merge_calculated_jsons\n import scilab.expers.mechanical.fatigue.run_image_measure as run_image_measure\n import scilab.graphs.instron_uts as graphs_instron_uts\n import scilab.graphs.instron_all as graphs_instron_all\n import scilab.graphs.graph_all as graphs_graph_all\n import scilab.graphs.precondition_fitting as precondition_fitting\n import scilab.graphs.cycle_trends as cycle_trends\n \n doLoadTracking = DataTree(tracking=True, trends=False)\n doLoadTrends = DataTree(tracking=False, trends=True)\n doLoadPost = DataTree(tracking=False, trends=False)\n \n try:\n process_cycle_tests(testinfo, testfolder, reportfile, doLoadTracking,\n handlers=[make_data_json.graphs2_handler, merge_calculated_jsons.graphs2_handler], )\n #\n # process_cycle_tests(testinfo, testfolder, reportfile, doLoadTracking,\n # handlers=[ graphs_graph_all.graphs2_handler,merge_calculated_jsons.graphs2_handler,], )\n #\n # process_cycle_tests(testinfo, testfolder, reportfile, doLoadTrends,\n # handlers=[cycle_trends.graphs2_handler], )\n\n process_cycle_tests(testinfo, testfolder, reportfile, doLoadPost,\n handlers=[merge_calculated_jsons.graphs2_handler], )\n \n # return process_uts_tests(testinfo, testfolder, uts_handlers, reportfile)\n except Exception as err:\n # logging.warn(\"Error occurred: \"+str(err),exc_info=err)\n raise err\n\n# from multiprocessing import Pool\n\ndef main():\n \n fs = fatigue_cycles.FileStructure('fatigue failure (cycles, expr1)', 'cycles-expr2')\n # fs = fatigue_uts.FileStructure('fatigue failure (uts, expr1)', 'fatigue-test-2')\n # Test test images for now\n test_dir = fs.test_parent.resolve()\n \n \n testitemsd = fs.testitemsd()\n\n import seaborn as sns\n sns.set_style(\"whitegrid\")\n # sns.set_style(\"ticks\")\n # sns.set_style(\"dark\")\n \n testitems = list(testitemsd.items())\n debug('\\n'.join([l.name for l in testitemsd ]))\n \n tempreports = fs.results_dir/'Temp Reports'\n if not tempreports.is_dir():\n tempreports.mkdir()\n \n with (tempreports/'Excel Data Sheet Results.md').open('w') as report:\n \n for testinfo, testfile in testitems[ : ]:\n # for testinfo, testfile in testitems[ :2 ]:\n # for testinfo, testfile in testitems[ : len(testitems)//2 ]:\n # for testinfo, testfile in testitems[ len(testitems)//2-1 : ]:\n\n # if testinfo.orientation == 'lg':\n # if testinfo.orientation == 'tr':\n # continue\n # if testinfo.name != 'nov28(gf10.1-llm)-wa-tr-l4-x2':\n # continue\n \n testfolder = fs.testfolder(testinfo=testinfo, ensure_folders_exists=False)\n \n print(mdHeader(3, testinfo))\n \n # if any( testfolder.jsoncalc.glob('*.summaries.calculated.json') ):\n # logging.info(\"SKIPPING: \"+str(testinfo))\n # continue\n \n try:\n res = process_test(testinfo, testfolder, reportfile=report)\n print(res)\n \n except Exception as err:\n logging.warn(\"Error processing tests %s: %s\", testinfo, err)\n raise err\n \n\nif __name__ == '__main__':\n\n main()\n\n", "repo_name": "elcritch/scilab", "sub_path": "scilab/graphs/graph_runner2.py", "file_name": "graph_runner2.py", "file_ext": "py", "file_size_in_byte": 7085, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "matplotlib.use", "line_number": 9, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 12, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 13, "usage_type": "call"}, {"api_name": "sys.path.insert", "line_number": 19, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "scilab.tools.jsonutils.load_json_from", "line_number": 63, "usage_type": "call"}, {"api_name": "scilab.tools.jsonutils", "line_number": 63, "usage_type": "name"}, {"api_name": "scilab.expers.configuration.TestData", "line_number": 81, "usage_type": "call"}, {"api_name": "scilab.expers.configuration.TestData", "line_number": 88, "usage_type": "call"}, {"api_name": "scilab.tools.jsonutils.load_json_from", "line_number": 96, "usage_type": "call"}, {"api_name": "scilab.tools.jsonutils", "line_number": 96, "usage_type": "name"}, {"api_name": "scilab.utilities.make_data_json.graphs2_handler", "line_number": 123, "usage_type": "attribute"}, {"api_name": "scilab.utilities.make_data_json", "line_number": 123, "usage_type": "name"}, {"api_name": "scilab.utilities.merge_calculated_jsons.graphs2_handler", "line_number": 123, "usage_type": "attribute"}, {"api_name": "scilab.utilities.merge_calculated_jsons", "line_number": 123, "usage_type": "name"}, {"api_name": "scilab.utilities.merge_calculated_jsons.graphs2_handler", "line_number": 132, "usage_type": "attribute"}, {"api_name": "scilab.utilities.merge_calculated_jsons", "line_number": 132, "usage_type": "name"}, {"api_name": "scilab.expers.mechanical.fatigue.cycles.FileStructure", "line_number": 143, "usage_type": "call"}, {"api_name": "scilab.expers.mechanical.fatigue.cycles", "line_number": 143, "usage_type": "name"}, {"api_name": "seaborn.set_style", "line_number": 152, "usage_type": "call"}, {"api_name": "scilab.tools.tables.mdHeader", "line_number": 178, "usage_type": "call"}, {"api_name": "logging.warn", "line_number": 189, "usage_type": "call"}]} +{"seq_id": "43050397323", "text": "import zmq\r\nimport time\r\nimport json\r\nimport os\r\nfrom model import constants\r\nfrom model.code_snippet import Code_Snippet\r\nfrom model.code_snippet import Code_Snippet_Encoder\r\n\r\n'''\r\nServer for the Snippopotamus Rex application\r\n@author: David Jarrett\r\n'''\r\nclass Server:\r\n \r\n '''\r\n Initialize the server.\r\n \r\n @param ip_port The ip and port that the server should run on\r\n @param users_file The location of the file containing valid usernames\r\n @param snippets_file The location of the file containing stored code snippet data\r\n '''\r\n def __init__(self, ip_port='tcp://127.0.0.1:5555', users_file='../server/users.txt', snippets_file='../server/snippets.txt'):\r\n self._users = set()\r\n self._code_snippets = {}\r\n self._context = zmq.Context()\r\n self._socket = self._context.socket(zmq.REP)\r\n self._socket.bind(ip_port)\r\n \r\n self._user_file = users_file\r\n self._snippet_file = snippets_file\r\n \r\n self.load_users()\r\n self.load_all_snippets()\r\n\r\n def load_users(self):\r\n try:\r\n with open(self._user_file) as inputFile:\r\n for user in inputFile:\r\n self._users.add(user.strip())\r\n except FileNotFoundError:\r\n with open(self._user_file, 'w') as outputFile:\r\n outputFile.write(constants.USR_ADMIN + '\\n')\r\n self.load_users()\r\n\r\n def load_all_snippets(self):\r\n try:\r\n with open(self._snippet_file) as inputFile:\r\n for line in inputFile:\r\n loaded_snippet = self.load_snippet(line)\r\n snippet_handle = loaded_snippet.get_user_name() + loaded_snippet.get_name()\r\n self._code_snippets[snippet_handle] = loaded_snippet\r\n except FileNotFoundError:\r\n #use empty _users dictionary\r\n pass\r\n except IndexError:\r\n return\r\n \r\n def load_snippet(self, field_string):\r\n fields = field_string.strip().split(',')\r\n build_message = {constants.MSG_USER_NAME: fields[0],\r\n constants.MSG_NAME: fields[1],\r\n constants.MSG_DESC: fields[2],\r\n constants.MSG_CODE: fields[3],\r\n constants.MSG_TAGS: []}\r\n for i in range(4, len(fields)):\r\n build_message[constants.MSG_TAGS].append(fields[i])\r\n return Code_Snippet(build_message, needs_approval=False)\r\n \r\n def store_snippet(self, code_snippet):\r\n user_name = code_snippet.get_user_name()\r\n snippet_name = code_snippet.get_name()\r\n desc = code_snippet.get_description()\r\n code = code_snippet.get_code()\r\n tags = code_snippet.get_tags()\r\n \r\n output_line = '%s,%s,%s,%s,' % (user_name, snippet_name, desc, code)\r\n for tag in tags:\r\n output_line += tag + ','\r\n output_line = output_line.rstrip(',')\r\n \r\n with open(self._snippet_file, 'a') as outputFile:\r\n outputFile.write(output_line + '\\n')\r\n \r\n def store_all_snippets(self):\r\n os.remove(self._snippet_file)\r\n for k, v in self._code_snippets.items():\r\n self.store_snippet(v)\r\n \r\n '''\r\n Starts the main processing loop of the server. Waits for incoming commands and processes them, in turn.\r\n Can only be terminated by sending the TERMINATE command to the server.\r\n \r\n @preconditions: None\r\n @postconditions: Any changes due to processing commands will be reflected.\r\n ''' \r\n def main_loop(self):\r\n result = ''\r\n while result != constants.COMMAND_TERMINATE:\r\n # Wait for next request from client\r\n print(\"waiting for message...\")\r\n json_message = self._socket.recv_string()\r\n #print('********' + json_message + '*********')\r\n message = json.loads(json_message)\r\n try:\r\n print(\"Received request: %s\" % message[constants.MSG_ID])\r\n print(\"From: %s\" % message[constants.MSG_USER_NAME])\r\n \r\n if not self.validate_user(message) and message[constants.MSG_ID] != constants.COMMAND_NEW_USER:\r\n self.send_response(constants.INVALID_USER)\r\n else:\r\n result = self.process_message(message)\r\n except KeyError as e:\r\n self.send_response(constants.MISSING_KEY + ': ' + str(e))\r\n \r\n def process_message(self, message):\r\n try:\r\n response = self.dispatch_message(message)\r\n json_message = json.dumps(response)\r\n if response != None:\r\n self._socket.send_string(json_message)\r\n return response\r\n except KeyError as e:\r\n self.send_response(str(e))\r\n return response\r\n\r\n def dispatch_message(self, message):\r\n try:\r\n if message[constants.MSG_ID] == constants.COMMAND_DUMP:\r\n return self.dump_all_snippets(message)\r\n if message[constants.MSG_ID] == constants.COMMAND_ADD:\r\n return self.add_snippet(message)\r\n if message[constants.MSG_ID] == constants.COMMAND_DELETE:\r\n return self.delete_snippet(message)\r\n if message[constants.MSG_ID] == constants.COMMAND_DELETE_ALL:\r\n return self.delete_all_snippets()\r\n if message[constants.MSG_ID] == constants.COMMAND_DELETE_USER:\r\n return self.delete_user(message)\r\n if message[constants.MSG_ID] == constants.COMMAND_NEW_USER:\r\n return self.add_user(message)\r\n if message[constants.MSG_ID] == constants.COMMAND_UPDATE:\r\n return self.update_snippet(message)\r\n if message[constants.MSG_ID] == constants.COMMAND_TERMINATE:\r\n return constants.COMMAND_TERMINATE\r\n return self.send_response(constants.UNKNOWN_ID + ': ' + message[constants.MSG_ID])\r\n except KeyError as e:\r\n return self.send_response(constants.MISSING_KEY + ': ' + str(e))\r\n except Exception as e:\r\n return self.send_response(str(e))\r\n\r\n def add_snippet(self, message):\r\n new_snippet = Code_Snippet(message)\r\n snippet_handle = new_snippet.get_user_name() + new_snippet.get_name() \r\n if (snippet_handle) in self._code_snippets.keys():\r\n return {constants.RESPONSE: constants.SNIPPET_EXISTS}\r\n self._code_snippets[snippet_handle] = new_snippet\r\n self.store_snippet(new_snippet)\r\n return {constants.RESPONSE: constants.SUCCESS}\r\n\r\n def add_user(self, message):\r\n if message[constants.MSG_USER_NAME] in self._users:\r\n return {constants.RESPONSE: constants.USER_EXISTS}\r\n self._users.add(message[constants.MSG_USER_NAME])\r\n with open(self._user_file, 'a') as output_file:\r\n output_file.write(message[constants.MSG_USER_NAME] + '\\n')\r\n return {constants.RESPONSE: constants.SUCCESS}\r\n \r\n def delete_user(self, message):\r\n if message[constants.MSG_USER_NAME] not in self._users:\r\n return {constants.RESPONSE: constants.INVALID_USER}\r\n self._users.remove(message[constants.MSG_USER_NAME])\r\n with open(self._user_file, 'w') as output_file:\r\n for user in self._users:\r\n output_file.write(user + '\\n')\r\n return {constants.RESPONSE: constants.SUCCESS}\r\n\r\n def update_snippet(self, message):\r\n new_snippet = Code_Snippet(message, False)\r\n snippet_handle = new_snippet.get_user_name() + new_snippet.get_name() \r\n if (snippet_handle) not in self._code_snippets.keys():\r\n return {constants.RESPONSE: constants.SNIPPET_DOESNT_EXIT}\r\n self._code_snippets[snippet_handle] = new_snippet\r\n self.store_all_snippets()\r\n return {constants.RESPONSE: constants.SUCCESS}\r\n \r\n def delete_snippet(self, message):\r\n new_snippet = Code_Snippet(message, False)\r\n snippet_handle = new_snippet.get_user_name() + new_snippet.get_name() \r\n if (snippet_handle) not in self._code_snippets.keys():\r\n return {constants.RESPONSE: constants.SNIPPET_DOESNT_EXIT}\r\n del self._code_snippets[snippet_handle]\r\n self.store_all_snippets()\r\n return {constants.RESPONSE: constants.SUCCESS}\r\n \r\n def delete_all_snippets(self):\r\n open('snippets.txt', 'w').close()\r\n self._code_snippets = {}\r\n return {constants.RESPONSE: constants.SUCCESS}\r\n \r\n def send_response(self, text):\r\n response = json.dumps( {constants.RESPONSE: text} )\r\n self._socket.send_string(response)\r\n\r\n def validate_user(self, message):\r\n if message[constants.MSG_USER_NAME] in self._users:\r\n return True\r\n return False\r\n \r\n def dump_all_snippets(self, message):\r\n file_string = ''\r\n with open('snippets.txt', 'r') as snippet_file:\r\n for line in snippet_file:\r\n message[constants.MSG_USER_NAME]\r\n if message[constants.MSG_USER_NAME] != constants.USR_ADMIN and 'needs_approval' not in line:\r\n file_string += line\r\n elif message[constants.MSG_USER_NAME] == constants.USR_ADMIN:\r\n file_string += line\r\n \r\n return {constants.RESPONSE: file_string}\r\n \r\n# result = {}\r\n# count = 0\r\n# for k, v in self._code_snippets.items():\r\n# result[count] = v\r\n# count = count + 1\r\n# all_snippets = json.dumps(result, cls=Code_Snippet_Encoder)\r\n# return {constants.RESPONSE: all_snippets}\r\n\r\n'''\r\nStarts the server on the main thread.\r\n@preconditions: None\r\n@postconditions: Server will be running on main thread.\r\n'''\r\ndef runServer():\r\n server = Server()\r\n server.main_loop()\r\n\r\nif(__name__ == \"__main__\"):\r\n runServer()\r\n", "repo_name": "djarret1/SnippopotamusServer", "sub_path": "server/server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 10008, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "zmq.Context", "line_number": 25, "usage_type": "call"}, {"api_name": "zmq.REP", "line_number": 26, "usage_type": "attribute"}, {"api_name": "model.constants.USR_ADMIN", "line_number": 42, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 42, "usage_type": "name"}, {"api_name": "model.constants.MSG_USER_NAME", "line_number": 60, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 60, "usage_type": "name"}, {"api_name": "model.constants.MSG_NAME", "line_number": 61, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 61, "usage_type": "name"}, {"api_name": "model.constants.MSG_DESC", "line_number": 62, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 62, "usage_type": "name"}, {"api_name": "model.constants.MSG_CODE", "line_number": 63, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 63, "usage_type": "name"}, {"api_name": "model.constants.MSG_TAGS", "line_number": 64, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 64, "usage_type": "name"}, {"api_name": "model.constants.MSG_TAGS", "line_number": 66, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 66, "usage_type": "name"}, {"api_name": "model.code_snippet.Code_Snippet", "line_number": 67, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 85, "usage_type": "call"}, {"api_name": "model.constants.COMMAND_TERMINATE", "line_number": 98, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 98, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 103, "usage_type": "call"}, {"api_name": "model.constants.MSG_ID", "line_number": 105, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 105, "usage_type": "name"}, {"api_name": "model.constants.MSG_USER_NAME", "line_number": 106, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 106, "usage_type": "name"}, {"api_name": "model.constants.MSG_ID", "line_number": 108, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 108, "usage_type": "name"}, {"api_name": "model.constants.COMMAND_NEW_USER", "line_number": 108, "usage_type": "attribute"}, {"api_name": "model.constants.INVALID_USER", "line_number": 109, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 109, "usage_type": "name"}, {"api_name": "model.constants.MISSING_KEY", "line_number": 113, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 113, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 118, "usage_type": "call"}, {"api_name": "model.constants.MSG_ID", "line_number": 128, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 128, "usage_type": "name"}, {"api_name": "model.constants.COMMAND_DUMP", "line_number": 128, "usage_type": "attribute"}, {"api_name": "model.constants.MSG_ID", "line_number": 130, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 130, "usage_type": "name"}, {"api_name": "model.constants.COMMAND_ADD", "line_number": 130, "usage_type": "attribute"}, {"api_name": "model.constants.MSG_ID", "line_number": 132, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 132, "usage_type": "name"}, {"api_name": "model.constants.COMMAND_DELETE", "line_number": 132, "usage_type": "attribute"}, {"api_name": "model.constants.MSG_ID", "line_number": 134, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 134, "usage_type": "name"}, {"api_name": "model.constants.COMMAND_DELETE_ALL", "line_number": 134, "usage_type": "attribute"}, {"api_name": "model.constants.MSG_ID", "line_number": 136, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 136, "usage_type": "name"}, {"api_name": "model.constants.COMMAND_DELETE_USER", "line_number": 136, "usage_type": "attribute"}, {"api_name": "model.constants.MSG_ID", "line_number": 138, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 138, "usage_type": "name"}, {"api_name": "model.constants.COMMAND_NEW_USER", "line_number": 138, "usage_type": "attribute"}, {"api_name": "model.constants.MSG_ID", "line_number": 140, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 140, "usage_type": "name"}, {"api_name": "model.constants.COMMAND_UPDATE", "line_number": 140, "usage_type": "attribute"}, {"api_name": "model.constants.MSG_ID", "line_number": 142, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 142, "usage_type": "name"}, {"api_name": "model.constants.COMMAND_TERMINATE", "line_number": 142, "usage_type": "attribute"}, {"api_name": "model.constants.COMMAND_TERMINATE", "line_number": 143, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 143, "usage_type": "name"}, {"api_name": "model.constants.UNKNOWN_ID", "line_number": 144, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 144, "usage_type": "name"}, {"api_name": "model.constants.MSG_ID", "line_number": 144, "usage_type": "attribute"}, {"api_name": "model.constants.MISSING_KEY", "line_number": 146, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 146, "usage_type": "name"}, {"api_name": "model.code_snippet.Code_Snippet", "line_number": 151, "usage_type": "call"}, {"api_name": "model.constants.RESPONSE", "line_number": 154, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 154, "usage_type": "name"}, {"api_name": "model.constants.SNIPPET_EXISTS", "line_number": 154, "usage_type": "attribute"}, {"api_name": "model.constants.RESPONSE", "line_number": 157, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 157, "usage_type": "name"}, {"api_name": "model.constants.SUCCESS", "line_number": 157, "usage_type": "attribute"}, {"api_name": "model.constants.MSG_USER_NAME", "line_number": 160, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 160, "usage_type": "name"}, {"api_name": "model.constants.RESPONSE", "line_number": 161, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 161, "usage_type": "name"}, {"api_name": "model.constants.USER_EXISTS", "line_number": 161, "usage_type": "attribute"}, {"api_name": "model.constants.MSG_USER_NAME", "line_number": 162, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 162, "usage_type": "name"}, {"api_name": "model.constants.MSG_USER_NAME", "line_number": 164, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 164, "usage_type": "name"}, {"api_name": "model.constants.RESPONSE", "line_number": 165, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 165, "usage_type": "name"}, {"api_name": "model.constants.SUCCESS", "line_number": 165, "usage_type": "attribute"}, {"api_name": "model.constants.MSG_USER_NAME", "line_number": 168, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 168, "usage_type": "name"}, {"api_name": "model.constants.RESPONSE", "line_number": 169, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 169, "usage_type": "name"}, {"api_name": "model.constants.INVALID_USER", "line_number": 169, "usage_type": "attribute"}, {"api_name": "model.constants.MSG_USER_NAME", "line_number": 170, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 170, "usage_type": "name"}, {"api_name": "model.constants.RESPONSE", "line_number": 174, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 174, "usage_type": "name"}, {"api_name": "model.constants.SUCCESS", "line_number": 174, "usage_type": "attribute"}, {"api_name": "model.code_snippet.Code_Snippet", "line_number": 177, "usage_type": "call"}, {"api_name": "model.constants.RESPONSE", "line_number": 180, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 180, "usage_type": "name"}, {"api_name": "model.constants.SNIPPET_DOESNT_EXIT", "line_number": 180, "usage_type": "attribute"}, {"api_name": "model.constants.RESPONSE", "line_number": 183, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 183, "usage_type": "name"}, {"api_name": "model.constants.SUCCESS", "line_number": 183, "usage_type": "attribute"}, {"api_name": "model.code_snippet.Code_Snippet", "line_number": 186, "usage_type": "call"}, {"api_name": "model.constants.RESPONSE", "line_number": 189, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 189, "usage_type": "name"}, {"api_name": "model.constants.SNIPPET_DOESNT_EXIT", "line_number": 189, "usage_type": "attribute"}, {"api_name": "model.constants.RESPONSE", "line_number": 192, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 192, "usage_type": "name"}, {"api_name": "model.constants.SUCCESS", "line_number": 192, "usage_type": "attribute"}, {"api_name": "model.constants.RESPONSE", "line_number": 197, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 197, "usage_type": "name"}, {"api_name": "model.constants.SUCCESS", "line_number": 197, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 200, "usage_type": "call"}, {"api_name": "model.constants.RESPONSE", "line_number": 200, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 200, "usage_type": "name"}, {"api_name": "model.constants.MSG_USER_NAME", "line_number": 204, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 204, "usage_type": "name"}, {"api_name": "model.constants.MSG_USER_NAME", "line_number": 212, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 212, "usage_type": "name"}, {"api_name": "model.constants.MSG_USER_NAME", "line_number": 213, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 213, "usage_type": "name"}, {"api_name": "model.constants.USR_ADMIN", "line_number": 213, "usage_type": "attribute"}, {"api_name": "model.constants.MSG_USER_NAME", "line_number": 215, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 215, "usage_type": "name"}, {"api_name": "model.constants.USR_ADMIN", "line_number": 215, "usage_type": "attribute"}, {"api_name": "model.constants.RESPONSE", "line_number": 218, "usage_type": "attribute"}, {"api_name": "model.constants", "line_number": 218, "usage_type": "name"}]} +{"seq_id": "9766569884", "text": "import sys\r\nfrom PyQt5 import QtWidgets, QtGui, QtCore\r\n\r\n\r\ndef window():\r\n \"\"\"\r\n 初次打开软件的欢迎界面\r\n :return:\r\n \"\"\"\r\n app = QtWidgets.QApplication(sys.argv)\r\n w = QtWidgets.QWidget()\r\n w.setWindowIcon(QtGui.QIcon(\"images\\\\logo.ico\"))\r\n\r\n btn_min = QtWidgets.QPushButton(w)\r\n btn_min.setStyleSheet('background-color:#00ff00;border-radius:5px;')\r\n btn_min.setGeometry(0, 0, 23, 23)\r\n btn_min.setText(\"\")\r\n btn_min.move(1160, 60)\r\n\r\n btn_close = QtWidgets.QPushButton(w)\r\n btn_close.setStyleSheet('background-color:#ff0000;border-radius:5px;')\r\n btn_close.setGeometry(0, 0, 23, 23)\r\n btn_close.setText(\"\")\r\n btn_close.move(1200, 60)\r\n\r\n logo = QtWidgets.QLabel(w)\r\n logo.setPixmap(QtGui.QPixmap(\"images\\Sangeetic(1).png\"))\r\n logo.move(0, 50)\r\n\r\n wel = QtWidgets.QLabel(w)\r\n wel.setText(\"欢 迎\")\r\n wel.setStyleSheet(\"color:#02e494;font-size:45px;font-family:微软雅黑;\")\r\n wel.move(200, 400)\r\n\r\n before = QtWidgets.QLabel(w)\r\n before.setText(\"使用须知\")\r\n before.setStyleSheet(\"color:#02e494;font-size:33px;font-family:微软雅黑;\")\r\n before.move(500, 200)\r\n\r\n noti = QtWidgets.QLabel(w)\r\n noti.setText(\"本软件基于深度学习进行分类,由于音乐种类众多并且通\\n\"\r\n \"常一首歌中包含多种音乐风格无法涵盖所有的情况。分类\\n\"\r\n \"结果仅供参考,感谢您的使用。\")\r\n noti.setStyleSheet(\"color:#fff;font-size:28px;font-family:微软雅黑;\")\r\n noti.move(500, 300)\r\n\r\n next = QtWidgets.QPushButton(w)\r\n next.setText(\"进入软件\")\r\n next.setGeometry(1050, 600, 150, 50)\r\n next.setStyleSheet(\"color:#fff;background-color:rgb(28, 37, 41);font-size:28px;font-family:微软雅黑;\")\r\n next.clicked.connect(w.close)\r\n btn_min.clicked.connect(w.showMinimized)\r\n btn_close.clicked.connect(w.close)\r\n\r\n w.setStyleSheet(\"background-color:rgb(28, 37, 41);\")\r\n w.setWindowTitle(\"欢迎\")\r\n w.setGeometry(5, 10, 1280, 720)\r\n w.setWindowFlag(QtCore.Qt.FramelessWindowHint)\r\n pre_move = w.frameGeometry()\r\n mov = QtWidgets.QDesktopWidget().availableGeometry().center()\r\n pre_move.moveCenter(mov)\r\n w.move(pre_move.topLeft())\r\n w.show()\r\n app.exec()\r\n\r\n\r\nif __name__ == '__main__':\r\n window()\r\n", "repo_name": "jerryzlz/Music-Classification-Player", "sub_path": "fct/welcome.py", "file_name": "welcome.py", "file_ext": "py", "file_size_in_byte": 2334, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 10, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 10, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 10, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 11, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 11, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 12, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 12, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 14, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 14, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 20, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 20, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 26, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 26, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 27, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 27, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 30, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 30, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 35, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 35, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 40, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 40, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 47, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 47, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 58, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 58, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QDesktopWidget", "line_number": 60, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 60, "usage_type": "name"}]} +{"seq_id": "43780753666", "text": "import random\nimport os\nimport spritesheet\nimport pygame\n#import Main\npygame.init()\n\ntile_height = 64\ntile_width = 64\n\n# creating 'Ground' classes\nclass Ground(object):\n def __init__(self, worldx, worldy):\n self.x = 0\n self.y = worldy - tile_height\n self.surface = self.y + 14\n self.img = None\n self.width = worldx\n self.height = tile_height\n self.label = 'ground'\n self.right_edge = self.x + self.width\n self.bottom_edge = self.y + self.height\n self.dimensions = [self.x, self.right_edge, self.surface, self.bottom_edge]\n\n def draw(self, world):\n world.blit(self.img, (self.x, self.y))\n\n# 'solid_ground' is the basic, one piece ground tile for beginning levels\nclass solid_ground(Ground):\n def __init__(self, worldx, worldy):\n Ground.__init__(self, worldx, worldy)\n self.img = pygame.image.load(os.path.join('images', 'full_ground1920x64.png'))\n\n# creating 'Platform' classes, each type of platform will be a different classe for ease of use\nclass Platform(object):\n def __init__(self, x, y, label):\n self.x = x\n self.y = y\n self.surface = y + 14\n self.img = None\n self.width = 0\n self.height = 0\n self.coin = 0\n self.chest = False\n self.label = label\n self.right_edge = self.x + self.width\n self.bottom_edge = self.y + self.height\n self.dimensions = [self.x, self.right_edge, self.surface, self.bottom_edge]\n\n\n def draw(self, world):\n world.blit(self.img, (self.x, self.y))\n\n# one tile, small platform, no coins, no chest, base class for more tiles later\nclass one_tile(Platform):\n def __init__(self, x, y, label):\n Platform.__init__(self, x, y, label)\n self.x = x\n self.y = y\n self.surface = y + 14\n self.img = pygame.image.load(os.path.join('images', '1TilePlatform64x64.png'))\n self.width = tile_width\n self.height = tile_height\n self.coin = 0\n self.chest = False\n self.label = label\n self.right_edge = self.x + self.width\n self.bottom_edge = self.y + self.height\n self.dimensions = [self.x, self.right_edge, self.surface, self.bottom_edge]\n\n# one tile platform, with one coin\nclass one_tile_coin(one_tile):\n def __init__(self, x, y, label):\n one_tile.__init__(self, x, y, label)\n self.coin = 1\n\n# one tile platform, with chest on it\nclass one_tile_chest(one_tile):\n def __init__(self, x, y, label):\n one_tile.__init__(self, x, y, label)\n self.chest = True\n\n# two tile platform, base class for other two tile platforms\nclass two_tile(Platform):\n def __init__(self, x, y, label):\n Platform.__init__(self, x, y, label)\n self.x = x\n self.y = y\n self.surface = y + 14\n self.img = pygame.image.load(os.path.join('images', '2TilePlatform128x64.png'))\n self.width = tile_width * 2\n self.height = tile_height\n self.coin = 0\n self.chest = False\n self.label = label\n self.right_edge = self.x + self.width\n self.bottom_edge = self.y + self.height\n self.dimensions = [self.x, self.right_edge, self.surface, self.bottom_edge]\n\n# two tile platform, with two coins on it\nclass two_tile_coin(two_tile):\n def __init__(self, x, y, label):\n two_tile.__init__(self, x, y, label)\n self.coin = 2\n\n# base method for creating platforms in the world, just calls other methods to create different kinds of platforms\ndef create_platforms(worldx, worldy, jump_width, jump_height):\n return_platforms = []\n coin_list = []\n chest_list = []\n platforms = pyramid_pattern(worldx, worldy, jump_width, jump_height)\n\n return_platforms.append(create_ground(worldx, worldy))\n for plat in platforms:\n return_platforms.append(plat)\n if plat.coin > 0:\n coin_list.append([plat.x + (tile_width // 2) - 20, plat.y - 20])\n if plat.coin > 1:\n coin_list.append([plat.x + (tile_width * 1.5) - 20, plat.y - 20])\n if plat.chest == True:\n chest_list.append([plat.x + (tile_width // 2) - 20, plat.y - 40])\n\n return return_platforms, coin_list, chest_list\n\n\n\n\n\n# creates the ground, starting with just \"solid_ground\" but different grounds will be added later\ndef create_ground(worldx, worldy):\n return solid_ground(worldx, worldy)\n\ndef pyramid_pattern(worldx, worldy, jump_width, jump_height):\n temp_list = [one_tile_chest(worldx // 2, 150, 'chest')]\n y_level = 150 + jump_height - 10\n x_left = worldx // 2\n x_i_left = (worldx // 2) - tile_width\n x_i_right = (worldx // 2) + tile_width\n x_right = worldx // 2 + tile_width\n level_count = 2\n tile_count = 0\n while y_level < worldy - tile_height:\n while tile_count <= level_count:\n left_plat_type = platform_types[random.randrange(0, len(platform_types)-1)]\n right_plat_type = platform_types[random.randrange(0, len(platform_types)-1)]\n x_left -= jump_width + tile_width * level_count\n x_i_left -= 12\n x_right += jump_width + tile_width * level_count\n x_i_right += 12\n if x_left > 0:\n temp_list.append(left_plat_type(x_left, y_level, str(tile_count)))\n if tile_count < 2:\n temp_list.append(left_plat_type(x_i_left, y_level-5, str(tile_count)))\n temp_list.append(right_plat_type(x_i_right, y_level -5, str(tile_count)))\n if x_right + tile_width < worldx:\n temp_list.append(right_plat_type(x_right, y_level, str(tile_count)))\n tile_count += level_count\n y_level += jump_height - 10\n tile_count = 0\n level_count += 1\n x_left = worldx // 2\n x_right = worldx //2 + tile_width\n\n\n\n\n\n return temp_list\n\"\"\"\n# create the chest(goal) in middle third and top third of screen, random location\n# this is for the first 'pyramid_pattern', more patterns to come later\ndef pyramid_pattern(worldx, worldy, jump_width, jump_height):\n platform_list = []\n label_count = 0\n chest_plat_x = random.randrange(worldx // 3, (worldx // 3) * 2)\n chest_plat_y = random.randrange(100, worldy // 3)\n chest = one_tile_chest(chest_plat_x, chest_plat_y, 'chest')\n platform_list.append(chest)\n generated_platforms_l = recurse_pyramid_l(chest.x, chest.x + chest.width, chest.surface, jump_width, jump_height, worldy)\n generated_platforms_r = recurse_pyramid_r(chest.x + chest.width, chest.surface, jump_width, jump_height, worldy)\n\n for plat in generated_platforms_l:\n label_count += 1\n plat.label = label_count\n if plat.x > 0 and plat.x + plat.width < worldx:\n platform_list.append(plat)\n\n for plat in generated_platforms_r:\n label_count += 1\n plat.label = label_count\n #platform_list.append(plat)\n if plat.x > 0 and plat.x + plat.width < worldx:\n platform_list.append(plat)\n\n\n print(label_count)\n return platform_list\n\n\ndef recurse_pyramid_r(current_right_x, current_surface, jump_width, jump_height, worldy):\n right_pyramid_list = []\n right_list = []\n # create right platform\n right_plat_type = platform_types[random.randrange(0, len(platform_types) - 1)]\n temp = right_plat_type(0, 0, '0')\n temp_x = random.randrange(current_right_x, current_right_x + jump_width)\n temp_y = current_surface + jump_height - tile_height #random.randrange(current_surface, current_surface + jump_height)\n right_plat = right_plat_type(temp_x, temp_y, 'temp')\n if right_plat.surface < worldy - jump_height - tile_height:\n right_list = recurse_pyramid_r(right_plat.x + right_plat.width, right_plat.surface, jump_width, jump_height, worldy)\n\n right_pyramid_list.append(right_plat)\n\n if right_list != []:\n for plat in right_list:\n right_pyramid_list.append(plat)\n\n return right_pyramid_list\n\n\n\n# populates the rest of the\ndef recurse_pyramid_l(current_left_x, current_right_x, current_surface, jump_width, jump_height, worldy):\n pyramid_list = []\n left_list = []\n right_list = []\n # choose left platform\n left_plat_type = platform_types[random.randrange(0, len(platform_types))]\n temp = left_plat_type(0, 0, '0')\n temp_x = random.randrange(current_left_x - temp.width - jump_width, current_left_x - temp.width)\n temp_y = current_surface + jump_height - tile_height #random.randrange(current_surface, current_surface + jump_height)\n left_plat = left_plat_type(temp_x, temp_y, 'temp')\n\n # create right platform\n right_plat_type = platform_types[random.randrange(0, len(platform_types))]\n right_plat = right_plat_type(0, 0, '0')\n right_plat.x = random.randrange(current_right_x, current_right_x + jump_width)\n right_plat.y = current_surface + jump_height - tile_height #random.randrange(current_surface, current_surface + jump_height)\n right_plat.surface = right_plat.y + 14\n\n if left_plat.surface < worldy - jump_height:\n left_list = recurse_pyramid_l(left_plat.x, left_plat.x + left_plat.width, left_plat.surface, jump_width, jump_height, worldy)\n\n if right_plat.surface < worldy - jump_height - 50:\n right_list = recurse_pyramid_r(right_plat.x + right_plat.width, right_plat.surface, jump_width, jump_height, worldy)\n\n pyramid_list.append(left_plat)\n #pyramid_list.append(right_plat)\n\n if left_list != []:\n for plat in left_list:\n pyramid_list.append(plat)\n\n if right_list != []:\n for plat in right_list:\n pyramid_list.append(plat)\n\n return pyramid_list\n\"\"\"\n\n#types of platforms\nplatform_types = [one_tile_coin, two_tile_coin]\n\n# base class for level creation\n# starts by creating the platforms\n# then adds coins\n# then adds chests\n# then adds enemies\n# finally adds player\n# returns list of lists\n\ndef level_creator(worldx, worldy, jump_width, jump_height):\n level_platforms = []\n level_coins = []\n level_chests = []\n level_enemies = []\n level_player = []\n\n level_platforms, level_coins, level_chests = create_platforms(worldx, worldy, jump_width, jump_height)\n level_enemies = [[0, 0]]#, [worldx - 50, 0]]\n\n return [level_platforms, level_coins, level_chests, level_enemies, level_player]\n\n\n\n\n", "repo_name": "Protopaco/Game_Prototype", "sub_path": "Level_Creator.py", "file_name": "Level_Creator.py", "file_ext": "py", "file_size_in_byte": 10305, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pygame.init", "line_number": 6, "usage_type": "call"}, {"api_name": "pygame.image.load", "line_number": 32, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 32, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path", "line_number": 32, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 61, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 61, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path", "line_number": 61, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 90, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 90, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 90, "usage_type": "call"}, {"api_name": "os.path", "line_number": 90, "usage_type": "attribute"}, {"api_name": "random.randrange", "line_number": 144, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 145, "usage_type": "call"}]} +{"seq_id": "30307498657", "text": "from argparse import ArgumentTypeError\nfrom datetime import date\nfrom datetime import datetime as dt\nfrom hashlib import md5\nfrom operator import truediv\nfrom os import makedirs, scandir\nfrom os.path import abspath, exists, expanduser, join\nfrom typing import Union\nfrom urllib import error, request\nfrom rapidjson import loads\nfrom sxtools.logging import get_basic_logger\nlogger = get_basic_logger() # sXtools.log\nfrom sxtools import __author__ as owner, __repository__ as repo, __version__\n\n\ndef apt_path_exists(path: str) -> str:\n '''\n Check if passed to Argsprser Directory exists\n :return: Path or ArgumentTypeError\n '''\n if exists(path):\n return abspath(path)\n else:\n raise ArgumentTypeError('No such file or directory')\n\ndef fview(s: str, sep: str='.') -> str: return ' '.join(s.split()).replace(sep, ' ').title() # s.replace(sep, ' ').title()\ndef bview(s: str, sep: str='.') -> str: return ' '.join(s.split()).replace(' ', sep).lower() # return s.strip().replace(' ', sep).lower()\n\ndef unify(s: Union[str, None]) -> str:\n '''\n '''\n return s and ''.join(x for x in s if x.isalnum()).lower()\n\ndef strtdate(s: str) -> date:\n '''\n Convert a string to DATETIME and return its date part\n :return: DATE as \"datetime.date\" class\n '''\n formats = set([\n '%Y-%m-%d',\n '%y.%m.%d',\n '%d-%m-%Y',\n '%m.%d.%y',\n '%Y.%m.%d',\n '%y-%m-%d',\n '%d.%m.%Y',\n '%m-%d-%y'])\n for fmt in formats:\n try:\n return dt.strptime(s, fmt).date()\n except ValueError:\n pass\n return None\n raise ValueError(f'No valid date format found in {s}')\n\ndef sortmap(d: dict) -> None:\n '''\n Sort a JSONfied dictionary by value\n '''\n for v in d.values():\n if type(v) == list:\n v.sort()\n elif type(v) == dict: sortmap(v)\n\ndef cache(object: str = None, init: bool = False) -> Union[str, bool]:\n '''\n Return the app's cache directory or path to a object in the cache\n '''\n d = expanduser('~/.config/sxtools/cache')\n if not exists(d): # check if cache exists\n makedirs(d, exist_ok=True)\n if not object:\n return d # return cache directory\n path = join(\n d, md5(object.encode('utf-8')).hexdigest() + '.jpg')\n return path if exists(path) or init else False # Union[path | False]\n\ndef cache_size() -> int:\n '''\n Calculate the size of cache directory\n '''\n total = 0\n with scandir(cache()) as it:\n for entry in it:\n if entry.is_file():\n total += entry.stat().st_size\n elif entry.is_dir():\n total += cache_size(entry.path)\n return total\n\ndef check_updates() -> str:\n '''\n Check for Updates @ using GitHub API\n '''\n GITHUB_API_URL = 'https://api.github.com/repos/%s/%s/releases/latest'\n try:\n response = request.urlopen(\n GITHUB_API_URL % (owner, repo))\n version = loads(response.read()).get('tag_name').strip('v.')\n except error.HTTPError as e:\n logger.warning(f'{e} (check failed)')\n return 'no information, try later again'\n return 'latest' if version == __version__ else 'development' if version < __version__ else 'outdated'\n\ndef table_readable(value: int) -> str:\n '''\n convert \"value\" in human readable format\n :return: \"value\" in next possible unit, e.g. 'KiB'\n '''\n try:\n if type(value) != int:\n value = int(value)\n except ValueError as e:\n logger.error(f'Couldn\\'t convert \"{value}\" to an Integer')\n value = 0 # reset\n return f'{truediv(value, 1024 * 1024):0.1f} MiB'\n\ndef human_readable(value: int) -> str:\n '''\n convert \"value\" in human readable format\n :return: \"value\" in next possible unit, e.g. 'KiB'\n '''\n try:\n if type(value) != int:\n value = int(value)\n except ValueError as e:\n logger.error(f'Couldn\\'t convert \"{value}\" to an Integer')\n value = 0 # reset\n for unit in ('B', 'KiB', 'MiB', 'GiB', 'TiB'):\n if value < 1024:\n return f'{value:0.2f} {unit}'\n value = truediv(value, 1024)\n return f'{value:0.1f} PiB' # pebibyte 1024^5 = 1,125,899,906,842,624 bytes\n", "repo_name": "nschepsen/sxtools-manager", "sub_path": "src/sxtools/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 4266, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sxtools.logging.get_basic_logger", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 22, "usage_type": "call"}, {"api_name": "argparse.ArgumentTypeError", "line_number": 24, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 29, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 50, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 50, "usage_type": "name"}, {"api_name": "datetime.date", "line_number": 34, "usage_type": "name"}, {"api_name": "os.path.expanduser", "line_number": 69, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 70, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 71, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 74, "usage_type": "call"}, {"api_name": "hashlib.md5", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 76, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 65, "usage_type": "name"}, {"api_name": "os.scandir", "line_number": 83, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 97, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 97, "usage_type": "name"}, {"api_name": "sxtools.__author__", "line_number": 98, "usage_type": "name"}, {"api_name": "sxtools.__repository__", "line_number": 98, "usage_type": "name"}, {"api_name": "rapidjson.loads", "line_number": 99, "usage_type": "call"}, {"api_name": "urllib.error.HTTPError", "line_number": 100, "usage_type": "attribute"}, {"api_name": "urllib.error", "line_number": 100, "usage_type": "name"}, {"api_name": "sxtools.__version__", "line_number": 103, "usage_type": "name"}, {"api_name": "operator.truediv", "line_number": 116, "usage_type": "call"}, {"api_name": "operator.truediv", "line_number": 132, "usage_type": "call"}]} +{"seq_id": "40531411427", "text": "from flask import current_app, render_template, request, redirect, flash, jsonify, send_from_directory, url_for, Blueprint\nfrom werkzeug.utils import secure_filename\nfrom werkzeug.datastructures import CombinedMultiDict\nfrom flask_login import login_required\nfrom datetime import datetime\nfrom functions import *\nimport uuid\n\nfrom .forms import DocumentForm\n\ndocument_bp = Blueprint(\"document\", __name__, template_folder=\"templates\")\n\n@document_bp.route('/download/')\n@login_required\ndef download(id):\n UPLOAD_FOLDER = current_app.config['UPLOAD_FOLDER']\n file = Document.query.filter(Document.id==id).first()\n return send_from_directory(f\"{UPLOAD_FOLDER}/documents\", file.filename)\n\n@document_bp.route('/add//', methods=['POST','GET'])\n@login_required\ndef add(target, id):\n UPLOAD_FOLDER = current_app.config['UPLOAD_FOLDER']\n\n form = DocumentForm(CombinedMultiDict((request.files, request.form)))\n\n if form.validate_on_submit():\n form_file = form.filename.data\n name = form.name.data\n if target == 'animal':\n animal_id = id\n terrarium_id = 'NULL'\n elif target == 'terrarium':\n terrarium_id = id\n animal_id = 'NULL'\n\n print(f\"animal: {animal_id}\")\n print(f\"terrarium: {terrarium_id}\")\n\n # Check if an image was uploaded\n if form_file.filename != '':\n # Save the image to a folder\n if form_file and allowed_file(form_file.filename):\n filename = f\"{uuid.uuid4().hex[:8]}_{secure_filename(form_file.filename)}\"\n form_file.save(os.path.join(f\"{UPLOAD_FOLDER}/documents\", filename))\n else:\n flash('Invalid file type. Please upload an valid file. (pdf, png, jpg)', 'danger')\n if target == 'animal':\n return redirect(\"/animal/\"+str(animal_id))\n elif target == 'terrarium':\n return redirect(\"/terrarium/\"+str(animal_id))\n \n file = Document(name=name,\n filename=filename,\n animal_id=animal_id,\n terrarium_id=terrarium_id)\n db.session.add(file)\n db.session.commit()\n\n flash('Added document successfully!', 'success')\n current_app.logger.info(\"Added document!\") \n else:\n flash('No file found!', 'danger')\n current_app.logger.info(\"Error adding document!\")\n\n if target == 'animal':\n return redirect(\"/animal/\"+str(animal_id))\n elif target == 'terrarium':\n return redirect(\"/terrarium/\"+str(animal_id))\n \n if target == 'animal':\n animal = Animal.query.add_columns(Animal.id, Animal.name).filter(Animal.id==id).one()\n return render_template('document_add.html', id=id, animal=animal, form=form, target=\"animal\")\n elif target == 'terrarium':\n terrarium = Terrarium.query.add_columns(Terrarium.id, Terrarium.name).filter(Terrarium.id==id).one()\n return render_template('document_add.html', id=id, terrarium=terrarium, form=form, target=\"terrarium\")\n \n@document_bp.route('/edit/', methods=['POST','GET'])\n@login_required\ndef edit(id):\n UPLOAD_FOLDER = current_app.config['UPLOAD_FOLDER']\n\n document = Document.query.filter(Document.id==id).first()\n\n form = DocumentForm(CombinedMultiDict((request.files, request.form)), obj=document)\n\n if form.validate_on_submit():\n\n document.name = form.name.data\n print(f\"animal: {document.animal_id}\")\n print(f\"terrarium: {document.terrarium_id}\")\n\n # Check if a new image file is provided\n if form.filename.data:\n file = form.filename.data\n if file.filename == '':\n # No new file provided\n filename = document.filename\n elif allowed_file(file.filename):\n # New valid file provided\n filename = f\"{uuid.uuid4().hex[:8]}_{secure_filename(file.filename)}\"\n file.save(os.path.join(f\"{UPLOAD_FOLDER}/documents\", filename))\n # Delete old file\n try:\n file_path = os.path.join(f\"{UPLOAD_FOLDER}/documents\", str(document.filename))\n if os.path.exists(file_path):\n os.remove(file_path)\n except:\n print(f\"Could not delete old file: {document.filename}\")\n else:\n # Invalid file format\n flash('Invalid file format. Please upload an image file.', 'error')\n if int(document.animal_id) > 0:\n return redirect(\"/animal/\"+str(document.animal_id))\n else:\n return redirect(\"/terrarium/\"+str(document.terrarium_id))\n else:\n filename = document.filename\n \n document.filename = filename\n\n db.session.add(document)\n db.session.commit()\n \n flash('Changes to document saved!', 'success')\n current_app.logger.info(f\"Modified document with id: {id} !\")\n\n if int(document.animal_id) > 0:\n return redirect(\"/animal/\"+str(document.animal_id))\n else:\n return redirect(\"/terrarium/\"+str(document.terrarium_id))\n \n return jsonify({'htmlresponse': render_template('document_edit.html', form=form, id=id)})\n \n@document_bp.route('/delete/', methods=['POST'])\n@login_required\ndef delete(id):\n UPLOAD_FOLDER = current_app.config['UPLOAD_FOLDER']\n if request.method == 'POST': \n document = Document.query.get_or_404(id)\n\n # Delete the file\n file_path = os.path.join(f\"{UPLOAD_FOLDER}/documents\", str(document.filename))\n if os.path.exists(file_path):\n os.remove(file_path)\n\n # Delete data into the database\n db.session.delete(document)\n db.session.commit()\n flash('Deleted document successfully!', 'success')\n current_app.logger.info(f\"Deleted document with id: {id} !\")\n\n return \"\", 200", "repo_name": "Brazier85/personal_zoo", "sub_path": "blueprints/document/document.py", "file_name": "document.py", "file_ext": "py", "file_size_in_byte": 6127, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.Blueprint", "line_number": 11, "usage_type": "call"}, {"api_name": "flask.current_app.config", "line_number": 16, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 16, "usage_type": "name"}, {"api_name": "flask.send_from_directory", "line_number": 18, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 14, "usage_type": "name"}, {"api_name": "flask.current_app.config", "line_number": 23, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 23, "usage_type": "name"}, {"api_name": "forms.DocumentForm", "line_number": 25, "usage_type": "call"}, {"api_name": "werkzeug.datastructures.CombinedMultiDict", "line_number": 25, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 25, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 25, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 25, "usage_type": "attribute"}, {"api_name": "uuid.uuid4", "line_number": 44, "usage_type": "call"}, {"api_name": "werkzeug.utils.secure_filename", "line_number": 44, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 47, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 49, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 51, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 60, "usage_type": "call"}, {"api_name": "flask.current_app.logger.info", "line_number": 61, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 61, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 61, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 63, "usage_type": "call"}, {"api_name": "flask.current_app.logger.info", "line_number": 64, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 64, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 64, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 67, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 69, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 73, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 76, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 21, "usage_type": "name"}, {"api_name": "flask.current_app.config", "line_number": 81, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 81, "usage_type": "name"}, {"api_name": "forms.DocumentForm", "line_number": 85, "usage_type": "call"}, {"api_name": "werkzeug.datastructures.CombinedMultiDict", "line_number": 85, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 85, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 85, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 85, "usage_type": "attribute"}, {"api_name": "uuid.uuid4", "line_number": 101, "usage_type": "call"}, {"api_name": "werkzeug.utils.secure_filename", "line_number": 101, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 112, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 114, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 116, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 125, "usage_type": "call"}, {"api_name": "flask.current_app.logger.info", "line_number": 126, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 126, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 126, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 129, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 131, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 133, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 133, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 79, "usage_type": "name"}, {"api_name": "flask.current_app.config", "line_number": 138, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 138, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 139, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 139, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 150, "usage_type": "call"}, {"api_name": "flask.current_app.logger.info", "line_number": 151, "usage_type": "call"}, {"api_name": "flask.current_app.logger", "line_number": 151, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 151, "usage_type": "name"}, {"api_name": "flask_login.login_required", "line_number": 136, "usage_type": "name"}]} +{"seq_id": "2819612655", "text": "import flask\nimport flask_login\nimport datetime\nimport pymorphy2\nimport os\nfrom flask import Flask, render_template, redirect, request, send_from_directory\nfrom flask_login import LoginManager, login_user, login_required, logout_user\nfrom random import shuffle\n\nfrom data import db_session\nfrom data.users import User\nfrom data.jobs import Jobs\nfrom data.services import Services\nfrom data.branches import Branch\nfrom data.register import RegisterForm\nfrom data.login import LoginForm\nfrom data.editprofile import EditProfileForm\nfrom data.editservice import EditServiceForm\nfrom data.editjob import EditJobForm\nfrom data.addservice import AddServiceForm\nfrom data.addjob import AddJobForm\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'yandexlyceum_secret_key'\napp.config['UPLOADED_PHOTOS_DEST'] = os.path.join(basedir, 'uploads')\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\n\n@app.template_filter('dtfilter')\ndef dtfilter(date):\n morph = pymorphy2.MorphAnalyzer(lang='ru')\n day = morph.parse('день')[0]\n hour = morph.parse('час')[0]\n minutes = morph.parse('минута')[0]\n second = morph.parse('секунда')[0]\n res = datetime.datetime.now() - date\n if res.month:\n return f'{res.month} {day.make_agree_with_number(res.days).word}' \\\n f'{res.days} {day.make_agree_with_number(res.days).word}' \\\n f'{res.seconds // 3600} {hour.make_agree_with_number(res.seconds // 3600).word} ' \\\n f'{(res.seconds // 60) % 60} {minutes.make_agree_with_number((res.seconds // 60) % 60).word} ' \\\n f'{res.seconds % 60 % 60} {second.make_agree_with_number(res.seconds % 60 % 60).word}'\n if res.days:\n return f'{res.days} {day.make_agree_with_number(res.days).word} ' \\\n f'{res.seconds // 3600} {hour.make_agree_with_number(res.seconds // 3600).word} ' \\\n f'{(res.seconds // 60) % 60} {minutes.make_agree_with_number((res.seconds // 60) % 60).word} ' \\\n f'{res.seconds % 60 % 60} {second.make_agree_with_number(res.seconds % 60 % 60).word}'\n if res.seconds // 3600:\n return f'{res.seconds // 3600} {hour.make_agree_with_number(res.seconds // 3600).word} ' \\\n f'{(res.seconds // 60) % 60} {minutes.make_agree_with_number((res.seconds // 60) % 60).word} ' \\\n f'{res.seconds % 60 % 60} {second.make_agree_with_number(res.seconds % 60 % 60).word}'\n if (res.seconds // 60) % 60:\n return f'{(res.seconds // 60) % 60} {minutes.make_agree_with_number((res.seconds // 60) % 60).word} ' \\\n f'{res.seconds % 60 % 60} {second.make_agree_with_number(res.seconds % 60 % 60).word}'\n return f'{res.seconds % 60 % 60} {second.make_agree_with_number(res.seconds % 60 % 60).word}'\n\n\n@app.template_filter('stddate')\ndef stddate(date):\n return date.strftime('%d/%m/%Y')\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n db_sess = db_session.create_session()\n return db_sess.query(User).get(user_id)\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n if form.validate_on_submit():\n db_sess = db_session.create_session()\n user = db_sess.query(User).filter(User.email == form.email.data).first()\n if user and user.check_password(form.password.data):\n login_user(user, remember=form.remember_me.data)\n return redirect(\"/\")\n return render_template('login.html', message=\"Неверный логин или пароль\", form=form)\n return render_template('login.html', title='Авторизация', form=form)\n\n\n@app.route('/logout')\n@login_required\ndef logout():\n logout_user()\n return redirect(\"/\")\n\n\n@app.route('/register', methods=['GET', 'POST'])\ndef reqister():\n form = RegisterForm()\n if form.validate_on_submit():\n if form.password.data != form.password_again.data:\n return render_template('register.html', title='Регистрация', form=form,\n message=\"Пароли не совпадают\")\n db_sess = db_session.create_session()\n if db_sess.query(User).filter(User.email == form.email.data).first():\n return render_template('register.html', title='Регистрация', form=form,\n message=\"Пользователь с этой почтой уже существует\")\n if db_sess.query(User).filter(User.nickname == form.nickname.data).first():\n return render_template('register.html', title='Регистрация', form=form,\n message=\"Пользователь с этим никнеймом уже существует\")\n user = User(\n email=form.email.data,\n nickname=form.nickname.data,\n surname=form.surname.data,\n name=form.name.data,\n speciality=form.speciality.data\n )\n user.set_password(form.password.data)\n db_sess.add(user)\n db_sess.commit()\n return redirect('/login')\n return render_template('register.html', title='Регистрация', form=form)\n\n\n@app.route('/preview/services/')\ndef response_service_preview(s_id):\n db_sess = db_session.create_session()\n image = db_sess.query(Services).get(s_id)\n if image:\n return app.response_class(image.preview, mimetype='application/octet-stream')\n else:\n return flask.abort(404)\n\n\n@app.route('/preview/jobs/')\ndef response_job_preview(s_id):\n db_sess = db_session.create_session()\n image = db_sess.query(Jobs).get(s_id)\n if image:\n return app.response_class(image.preview, mimetype='application/octet-stream')\n else:\n return flask.abort(404)\n\n\n@app.route(\"/\")\ndef index():\n db_sess = db_session.create_session()\n services = db_sess.query(Services).all()\n users = db_sess.query(User).all()\n branches = db_sess.query(Branch).all()\n names = {name.id: name.nickname for name in users}\n emails = {email.id: email.email for email in users}\n branche = {branch.id: branch.specialization for branch in branches}\n return render_template(\"index.html\", services=services, names=names, emails=emails, branches=branche,\n title='Доступные услуги')\n\n\n@app.route(\"/jobs\")\ndef ind_jobs():\n db_sess = db_session.create_session()\n jobs = db_sess.query(Jobs).all()\n users = db_sess.query(User).all()\n names = {name.id: name.nickname for name in users}\n emails = {email.id: email.email for email in users}\n return render_template(\"jobs.html\", jobs=jobs, names=names, emails=emails,\n title='Доступные вакансии')\n\n\n@app.route(\"/myprofile\")\ndef myprofile():\n if flask_login.current_user.is_authenticated:\n db_sess = db_session.create_session()\n users = db_sess.query(User).all()\n services = db_sess.query(Services).all()\n jobs = db_sess.query(Jobs).all()\n branches = db_sess.query(Branch).all()\n emails = {email.id: email.email for email in users}\n branche = {branch.id: branch.specialization for branch in branches}\n return render_template(\"myprofile.html\", services=services, emails=emails, jobs=jobs, branches=branche,\n title='Мой профиль')\n else:\n return redirect(\"/login\")\n\n\n@app.route('/editprofile', methods=['GET', 'POST'])\ndef editprofile():\n if flask_login.current_user.is_authenticated:\n edit_profile_form = EditProfileForm()\n if edit_profile_form.validate_on_submit():\n db_sess = db_session.create_session()\n u_id = flask_login.current_user.id\n # if edit_profile_form.password.data != edit_profile_form.password_again.data:\n # return render_template('editprofile.html', title='Editing a profile', form=edit_profile_form,\n # message=\"Passwords don't match\")\n if edit_profile_form.new_password.data:\n user = db_sess.query(User).filter_by(id=u_id).first()\n if user.check_password(edit_profile_form.old_password.data):\n user.set_password(edit_profile_form.new_password.data)\n else:\n return render_template('editprofile.html', title='Изменить профиль', form=edit_profile_form,\n message=\"Старый пароль не корректен или не введен\")\n elif edit_profile_form.old_password.data:\n return render_template('editprofile.html', title='Изменить профиль', form=edit_profile_form,\n message=\"Новый пароль не введен\")\n if edit_profile_form.name.data:\n db_sess.query(User).filter_by(id=u_id).update({'name': edit_profile_form.surname.data})\n if edit_profile_form.surname.data:\n db_sess.query(User).filter_by(id=u_id).update({'surname': edit_profile_form.name.data})\n if edit_profile_form.speciality.data:\n db_sess.query(User).filter_by(id=u_id).update({'speciality': edit_profile_form.speciality.data})\n db_sess.commit()\n return redirect('/')\n return render_template('editprofile.html', title='Изменить профиль', form=edit_profile_form)\n else:\n return redirect(\"/login\")\n\n\n@app.route('/editservice/', methods=['GET', 'POST'])\ndef editservice(s_id):\n if flask_login.current_user.is_authenticated:\n edit_service_form = EditServiceForm()\n if request.method == 'POST':\n db_sess = db_session.create_session()\n if edit_service_form.service.data:\n db_sess.query(Services).filter_by(id=s_id).update({'service': edit_service_form.service.data})\n if edit_service_form.description.data:\n db_sess.query(Services).filter_by(id=s_id).update({'description': edit_service_form.description.data})\n if edit_service_form.branch.data:\n db_sess.query(Services).filter_by(id=s_id).update({'branch_id': edit_service_form.branch.data})\n if edit_service_form.price.data:\n db_sess.query(Services).filter_by(id=s_id).update({'price': edit_service_form.price.data})\n if edit_service_form.preview.data:\n if edit_service_form.preview.data.content_type.split('/')[1] in ['jpg', 'jpeg', 'png']:\n file = edit_service_form.preview.data.read()\n db_sess.query(Services).filter_by(id=s_id).update({'preview': file})\n else:\n return render_template('editservice.html', title='Изменить услугу', form=edit_service_form,\n message='Загруженный файл не удовлетворяет формату')\n db_sess.query(Services).filter_by(id=s_id).update({'action': edit_service_form.action.data})\n db_sess.commit()\n return redirect('/myprofile')\n return render_template('editservice.html', title='Изменить услугу', form=edit_service_form)\n else:\n return redirect(\"/login\")\n\n\n@app.route('/addservice', methods=['GET', 'POST'])\ndef addservice():\n if flask_login.current_user.is_authenticated:\n add_service_form = AddServiceForm()\n if request.method == 'POST':\n db_sess = db_session.create_session()\n u_id = flask_login.current_user.id\n if not add_service_form.branch.data:\n return render_template('addservice.html', title='Добавить услугу', form=add_service_form,\n message='Категория не указана')\n elif add_service_form.preview.data:\n if add_service_form.preview.data.content_type.split('/')[1] in ['jpg', 'jpeg', 'png']:\n file = add_service_form.preview.data.read()\n service = Services(\n service=add_service_form.service.data,\n contractor=u_id,\n description=add_service_form.description.data,\n branch_id=add_service_form.branch.data,\n price=add_service_form.price.data,\n preview=file\n )\n db_sess.add(service)\n db_sess.commit()\n else:\n return render_template('addservice.html', title='Добавить услугу', form=add_service_form,\n message='Загруженный файл не удовлетворяет формату')\n else:\n service = Services(\n service=add_service_form.service.data,\n contractor=u_id,\n description=add_service_form.description.data,\n branch_id=add_service_form.branch.data,\n price=add_service_form.price.data,\n )\n db_sess.add(service)\n db_sess.commit()\n return redirect('/myprofile')\n return render_template('addservice.html', title='Добавить услугу', form=add_service_form)\n else:\n return redirect(\"/login\")\n\n\n@app.route('/editjob/', methods=['GET', 'POST'])\ndef editjob(s_id):\n if flask_login.current_user.is_authenticated:\n edit_job_form = EditJobForm()\n if request.method == 'POST':\n db_sess = db_session.create_session()\n if edit_job_form.job.data:\n db_sess.query(Jobs).filter_by(id=s_id).update({'job': edit_job_form.job.data})\n if edit_job_form.description.data:\n db_sess.query(Jobs).filter_by(id=s_id).update({'description': edit_job_form.description.data})\n if edit_job_form.price.data:\n db_sess.query(Jobs).filter_by(id=s_id).update({'price': edit_job_form.price.data})\n if edit_job_form.preview.data:\n if edit_job_form.preview.data.content_type.split('/')[1] in ['jpg', 'jpeg', 'png']:\n file = edit_job_form.preview.data.read()\n db_sess.query(Jobs).filter_by(id=s_id).update({'preview': file})\n else:\n return render_template('editjob.html', title='Изменить вакансию', form=edit_job_form,\n message='Загруженный файл не удовлетворяет формату')\n db_sess.query(Jobs).filter_by(id=s_id).update({'action': edit_job_form.action.data})\n db_sess.commit()\n return redirect('/myprofile')\n return render_template('editjob.html', title='Изменить вакансию', form=edit_job_form)\n else:\n return redirect(\"/login\")\n\n\n@app.route('/addjob', methods=['GET', 'POST'])\ndef addjob():\n if flask_login.current_user.is_authenticated:\n add_job_form = AddJobForm()\n if request.method == 'POST':\n db_sess = db_session.create_session()\n u_id = flask_login.current_user.id\n if add_job_form.preview.data:\n if add_job_form.preview.data.content_type.split('/')[1] in ['jpg', 'jpeg', 'png']:\n file = add_job_form.preview.data.read()\n job = Jobs(\n job=add_job_form.job.data,\n client=u_id,\n description=add_job_form.description.data,\n price=add_job_form.price.data,\n preview=file\n )\n db_sess.add(job)\n db_sess.commit()\n else:\n return render_template('addjob.html', title='Добавить вакансию', form=add_job_form,\n message='Загруженный файл не удовлетворяет формату')\n else:\n job = Jobs(\n job=add_job_form.job.data,\n contractor=u_id,\n description=add_job_form.description.data,\n price=add_job_form.price.data,\n )\n db_sess.add(job)\n db_sess.commit()\n return redirect('/myprofile')\n return render_template('addjob.html', title='Добавить вакансию', form=add_job_form)\n else:\n return redirect(\"/login\")\n\n\nif __name__ == '__main__':\n db_session.global_init(\"db/freelance_exchange.db\")\n app.run()\n", "repo_name": "notjik/Freelance-Exchange", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 16871, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "os.path.abspath", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 23, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "flask_login.LoginManager", "line_number": 28, "usage_type": "call"}, {"api_name": "pymorphy2.MorphAnalyzer", "line_number": 34, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 39, "usage_type": "attribute"}, {"api_name": "data.db_session.create_session", "line_number": 68, "usage_type": "call"}, {"api_name": "data.db_session", "line_number": 68, "usage_type": "name"}, {"api_name": "data.users.User", "line_number": 69, "usage_type": "argument"}, {"api_name": "data.login.LoginForm", "line_number": 74, "usage_type": "call"}, {"api_name": "data.db_session.create_session", "line_number": 76, "usage_type": "call"}, {"api_name": "data.db_session", "line_number": 76, "usage_type": "name"}, {"api_name": "data.users.User", "line_number": 77, "usage_type": "argument"}, {"api_name": "data.users.User.email", "line_number": 77, "usage_type": "attribute"}, {"api_name": "flask_login.login_user", "line_number": 79, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 80, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 81, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 82, "usage_type": "call"}, {"api_name": "flask_login.logout_user", "line_number": 88, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 89, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 86, "usage_type": "name"}, {"api_name": "data.register.RegisterForm", "line_number": 94, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 97, "usage_type": "call"}, {"api_name": "data.db_session.create_session", "line_number": 99, "usage_type": "call"}, {"api_name": "data.db_session", "line_number": 99, "usage_type": "name"}, {"api_name": "data.users.User", "line_number": 100, "usage_type": "argument"}, {"api_name": "data.users.User.email", "line_number": 100, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 101, "usage_type": "call"}, {"api_name": "data.users.User", "line_number": 103, "usage_type": "argument"}, {"api_name": "data.users.User.nickname", "line_number": 103, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 104, "usage_type": "call"}, {"api_name": "data.users.User", "line_number": 106, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 116, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 117, "usage_type": "call"}, {"api_name": "data.db_session.create_session", "line_number": 122, "usage_type": "call"}, {"api_name": "data.db_session", "line_number": 122, "usage_type": "name"}, {"api_name": "data.services.Services", "line_number": 123, "usage_type": "argument"}, {"api_name": "flask.abort", "line_number": 127, "usage_type": "call"}, {"api_name": "data.db_session.create_session", "line_number": 132, "usage_type": "call"}, {"api_name": "data.db_session", "line_number": 132, "usage_type": "name"}, {"api_name": "data.jobs.Jobs", "line_number": 133, "usage_type": "argument"}, {"api_name": "flask.abort", "line_number": 137, "usage_type": "call"}, {"api_name": "data.db_session.create_session", "line_number": 142, "usage_type": "call"}, {"api_name": "data.db_session", "line_number": 142, "usage_type": "name"}, {"api_name": "data.services.Services", "line_number": 143, "usage_type": "argument"}, {"api_name": "data.users.User", "line_number": 144, "usage_type": "argument"}, {"api_name": "data.branches.Branch", "line_number": 145, "usage_type": "argument"}, {"api_name": "flask.render_template", "line_number": 149, "usage_type": "call"}, {"api_name": "data.db_session.create_session", "line_number": 155, "usage_type": "call"}, {"api_name": "data.db_session", "line_number": 155, "usage_type": "name"}, {"api_name": "data.jobs.Jobs", "line_number": 156, "usage_type": "argument"}, {"api_name": "data.users.User", "line_number": 157, "usage_type": "argument"}, {"api_name": "flask.render_template", "line_number": 160, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 166, "usage_type": "attribute"}, {"api_name": "data.db_session.create_session", "line_number": 167, "usage_type": "call"}, {"api_name": "data.db_session", "line_number": 167, "usage_type": "name"}, {"api_name": "data.users.User", "line_number": 168, "usage_type": "argument"}, {"api_name": "data.services.Services", "line_number": 169, "usage_type": "argument"}, {"api_name": "data.jobs.Jobs", "line_number": 170, "usage_type": "argument"}, {"api_name": "data.branches.Branch", "line_number": 171, "usage_type": "argument"}, {"api_name": "flask.render_template", "line_number": 174, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 177, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 182, "usage_type": "attribute"}, {"api_name": "data.editprofile.EditProfileForm", "line_number": 183, "usage_type": "call"}, {"api_name": "data.db_session.create_session", "line_number": 185, "usage_type": "call"}, {"api_name": "data.db_session", "line_number": 185, "usage_type": "name"}, {"api_name": "flask_login.current_user", "line_number": 186, "usage_type": "attribute"}, {"api_name": "data.users.User", "line_number": 191, "usage_type": "argument"}, {"api_name": "flask.render_template", "line_number": 195, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 198, "usage_type": "call"}, {"api_name": "data.users.User", "line_number": 201, "usage_type": "argument"}, {"api_name": "data.users.User", "line_number": 203, "usage_type": "argument"}, {"api_name": "data.users.User", "line_number": 205, "usage_type": "argument"}, {"api_name": "flask.redirect", "line_number": 207, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 208, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 210, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 215, "usage_type": "attribute"}, {"api_name": "data.editservice.EditServiceForm", "line_number": 216, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 217, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 217, "usage_type": "name"}, {"api_name": "data.db_session.create_session", "line_number": 218, "usage_type": "call"}, {"api_name": "data.db_session", "line_number": 218, "usage_type": "name"}, {"api_name": "data.services.Services", "line_number": 220, "usage_type": "argument"}, {"api_name": "data.services.Services", "line_number": 222, "usage_type": "argument"}, {"api_name": "data.services.Services", "line_number": 224, "usage_type": "argument"}, {"api_name": "data.services.Services", "line_number": 226, "usage_type": "argument"}, {"api_name": "data.services.Services", "line_number": 230, "usage_type": "argument"}, {"api_name": "flask.render_template", "line_number": 232, "usage_type": "call"}, {"api_name": "data.services.Services", "line_number": 234, "usage_type": "argument"}, {"api_name": "flask.redirect", "line_number": 236, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 237, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 239, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 244, "usage_type": "attribute"}, {"api_name": "data.addservice.AddServiceForm", "line_number": 245, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 246, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 246, "usage_type": "name"}, {"api_name": "data.db_session.create_session", "line_number": 247, "usage_type": "call"}, {"api_name": "data.db_session", "line_number": 247, "usage_type": "name"}, {"api_name": "flask_login.current_user", "line_number": 248, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 250, "usage_type": "call"}, {"api_name": "data.services.Services", "line_number": 255, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 266, "usage_type": "call"}, {"api_name": "data.services.Services", "line_number": 269, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 278, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 279, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 281, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 286, "usage_type": "attribute"}, {"api_name": "data.editjob.EditJobForm", "line_number": 287, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 288, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 288, "usage_type": "name"}, {"api_name": "data.db_session.create_session", "line_number": 289, "usage_type": "call"}, {"api_name": "data.db_session", "line_number": 289, "usage_type": "name"}, {"api_name": "data.jobs.Jobs", "line_number": 291, "usage_type": "argument"}, {"api_name": "data.jobs.Jobs", "line_number": 293, "usage_type": "argument"}, {"api_name": "data.jobs.Jobs", "line_number": 295, "usage_type": "argument"}, {"api_name": "data.jobs.Jobs", "line_number": 299, "usage_type": "argument"}, {"api_name": "flask.render_template", "line_number": 301, "usage_type": "call"}, {"api_name": "data.jobs.Jobs", "line_number": 303, "usage_type": "argument"}, {"api_name": "flask.redirect", "line_number": 305, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 306, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 308, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 313, "usage_type": "attribute"}, {"api_name": "data.addjob.AddJobForm", "line_number": 314, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 315, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 315, "usage_type": "name"}, {"api_name": "data.db_session.create_session", "line_number": 316, "usage_type": "call"}, {"api_name": "data.db_session", "line_number": 316, "usage_type": "name"}, {"api_name": "flask_login.current_user", "line_number": 317, "usage_type": "attribute"}, {"api_name": "data.jobs.Jobs", "line_number": 321, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 331, "usage_type": "call"}, {"api_name": "data.jobs.Jobs", "line_number": 334, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 342, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 343, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 345, "usage_type": "call"}, {"api_name": "data.db_session.global_init", "line_number": 349, "usage_type": "call"}, {"api_name": "data.db_session", "line_number": 349, "usage_type": "name"}]} +{"seq_id": "26246295460", "text": "from flask import Flask, request, Response, jsonify\nfrom model import db, User, CreateDB\nfrom model import app as application\nimport simplejson as json\nfrom sqlalchemy.exc import IntegrityError\napp = Flask(__name__)\n\n\n\"\"\" CONSTANTS \"\"\"\nAPP_VERSION = 'v1'\nEXPENSES_API = '/' + APP_VERSION + '/' + 'expenses'\nJSON_CONTENT = 'application/json'\n\n\n\"\"\" Content type \"\"\"\ndef valid_content_type(request_content_type):\n return request_content_type == JSON_CONTENT\n\n\n\"\"\" ERROR 415 Invalid Content-type \"\"\"\n@app.errorhandler(415)\ndef invalid_content(error=None):\n message = {\n 'status': 415,\n 'message': 'Invalid Content Type: ' + request.headers['Content-Type']\n }\n resp = jsonify(message)\n resp.status_code = 415\n return resp\n\n\n\"\"\" ERROR 404 Page not Found \"\"\"\n@app.errorhandler(404)\ndef not_found(error=None):\n message = {\n 'status': 404,\n 'message': 'Not Found: ' + request.url,\n }\n resp = jsonify(message)\n resp.status_code = 404\n return resp\n\n\n@app.route('/')\ndef index():\n\treturn 'Hello World! Welcome to the expense manager\\n'\n\n\ndef request_parser(request_in):\n # Create User object from request\n request = json.loads(request_in.get_data())\n print(\"Request: {}\".format(request))\n user = User(request['name'],\n request['email'],\n request['category'],\n request['description'],\n request['link'],\n int(request['estimated_costs']),\n request['submit_date'])\n return user\n\n\ndef response_parser(user):\n # Format the response\n data = json.dumps({'id': str(user.id),\n 'name': user.name,\n 'email': user.email,\n 'category': user.category,\n 'description': user.description,\n 'link': user.link,\n 'estimated_costs': str(user.estimated_costs),\n 'submit_date': user.submit_date,\n 'status': user.status,\n 'decision_date': user.decision_date}, indent=4)\n return data\n\n\"\"\" POST REQUEST \"\"\"\n\n\n@app.route(EXPENSES_API, methods=['POST'])\ndef add_expense():\n try:\n # Update database\n user = request_parser(request)\n print(\"User : {}\".format(user))\n db.session.add(user)\n db.session.commit()\n print(\"Post: Insert Successful\")\n # Response\n user = User.query.filter_by(email=user.email,\n submit_date=user.submit_date,\n estimated_costs=user.estimated_costs).first_or_404()\n data = response_parser(user)\n print(\"Post: Query Successful\")\n except IntegrityError:\n return Response(status=400)\n\n resp = Response(data, status=201, mimetype=JSON_CONTENT)\n return resp\n\n\"\"\" GET REQUEST \"\"\"\n\n\n@app.route(EXPENSES_API + '/', methods=['GET'])\ndef get_expense(expense_id):\n # Select expense from db\n try:\n user = User.query.filter_by(id=expense_id).first_or_404()\n print(\"Get: Query Successful\")\n data = response_parser(user)\n except IntegrityError:\n return not_found()\n\n resp = Response(data, status=200, mimetype=JSON_CONTENT)\n return resp\n\n\"\"\" PUT REQUEST \"\"\"\n\n\n@app.route(EXPENSES_API + '/', methods=['PUT'])\ndef update_expense(expense_id):\n try:\n update_data = json.loads(request.get_data())\n print(\"Update : {} for id {}\".format(update_data, expense_id))\n db.session.query(User).filter(User.id == expense_id).\\\n update(update_data, synchronize_session=False)\n db.session.commit()\n print(\"Put: Query Successful\")\n except IntegrityError:\n return not_found()\n return Response(status=202)\n\n\"\"\" DELETE REQUEST \"\"\"\n\n\n@app.route(EXPENSES_API + '/', methods=['DELETE'])\ndef delete_expense(expense_id):\n try:\n db.session.query(User).filter(User.id == expense_id).delete()\n db.session.commit()\n print(\"Delete: Query Successful\")\n except IntegrityError:\n return not_found()\n return Response(status=204)\n\n\"\"\" USERS \"\"\"\n\n\n@app.route('/users')\ndef users():\n\ttry:\n\t\tusers = User.query.all()\n\t\tusers_dict = {}\n\t\tfor user in users:\n\t\t\tusers_dict[user.username] = {\n\t\t\t\t\t\t\t'email': user.email\n\t\t\t\t\t\t}\n\n\t\treturn json.dumps(users_dict)\n\texcept IntegrityError:\n\t\treturn json.dumps({})\n\n\"\"\" DB INFO \"\"\"\n\n\n@app.route('/info')\ndef app_status():\n\treturn json.dumps({'server_info': application.config['SQLALCHEMY_DATABASE_URI']})\n\n\"\"\" CREATE DB \"\"\"\n\n\ndef create_database():\n CreateDB()\n print(\"Database created\")\n return json.dumps({'status':'True'})\n\n\"\"\" CREATE TABLE \"\"\"\n\n\ndef create_user_table():\n\ttry:\n\t\tdb.create_all()\n\t\treturn json.dumps({'status':'True'})\n\texcept IntegrityError:\n\t\treturn json.dumps({'status':'False'})\n\n\"\"\" MAIN \"\"\"\n\n\nif __name__ == '__main__':\n create_database()\n create_user_table()\n print(\"Table created\")\n print(\"Starting Server --> localhost:80\")\n app.run(host=\"0.0.0.0\", port=80, debug=True)\n", "repo_name": "udaykd09/Expense-Manager-Docker", "sub_path": "www/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 5102, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 6, "usage_type": "call"}, {"api_name": "flask.request.headers", "line_number": 25, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 25, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 27, "usage_type": "call"}, {"api_name": "flask.request.url", "line_number": 37, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 37, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 39, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 51, "usage_type": "name"}, {"api_name": "simplejson.loads", "line_number": 51, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 52, "usage_type": "argument"}, {"api_name": "model.User", "line_number": 53, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 53, "usage_type": "name"}, {"api_name": "flask.request", "line_number": 54, "usage_type": "name"}, {"api_name": "flask.request", "line_number": 55, "usage_type": "name"}, {"api_name": "flask.request", "line_number": 56, "usage_type": "name"}, {"api_name": "flask.request", "line_number": 57, "usage_type": "name"}, {"api_name": "flask.request", "line_number": 58, "usage_type": "name"}, {"api_name": "flask.request", "line_number": 59, "usage_type": "name"}, {"api_name": "simplejson.dumps", "line_number": 65, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 84, "usage_type": "argument"}, {"api_name": "model.db.session.add", "line_number": 86, "usage_type": "call"}, {"api_name": "model.db.session", "line_number": 86, "usage_type": "attribute"}, {"api_name": "model.db", "line_number": 86, "usage_type": "name"}, {"api_name": "model.db.session.commit", "line_number": 87, "usage_type": "call"}, {"api_name": "model.db.session", "line_number": 87, "usage_type": "attribute"}, {"api_name": "model.db", "line_number": 87, "usage_type": "name"}, {"api_name": "model.User.query.filter_by", "line_number": 90, "usage_type": "call"}, {"api_name": "model.User.query", "line_number": 90, "usage_type": "attribute"}, {"api_name": "model.User", "line_number": 90, "usage_type": "name"}, {"api_name": "sqlalchemy.exc.IntegrityError", "line_number": 95, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 96, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 98, "usage_type": "call"}, {"api_name": "model.User.query.filter_by", "line_number": 108, "usage_type": "call"}, {"api_name": "model.User.query", "line_number": 108, "usage_type": "attribute"}, {"api_name": "model.User", "line_number": 108, "usage_type": "name"}, {"api_name": "sqlalchemy.exc.IntegrityError", "line_number": 111, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 114, "usage_type": "call"}, {"api_name": "simplejson.loads", "line_number": 123, "usage_type": "call"}, {"api_name": "flask.request.get_data", "line_number": 123, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 123, "usage_type": "name"}, {"api_name": "model.db.session.query", "line_number": 125, "usage_type": "call"}, {"api_name": "model.User", "line_number": 125, "usage_type": "argument"}, {"api_name": "model.db.session", "line_number": 125, "usage_type": "attribute"}, {"api_name": "model.db", "line_number": 125, "usage_type": "name"}, {"api_name": "model.User.id", "line_number": 125, "usage_type": "attribute"}, {"api_name": "model.db.session.commit", "line_number": 127, "usage_type": "call"}, {"api_name": "model.db.session", "line_number": 127, "usage_type": "attribute"}, {"api_name": "model.db", "line_number": 127, "usage_type": "name"}, {"api_name": "sqlalchemy.exc.IntegrityError", "line_number": 129, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 131, "usage_type": "call"}, {"api_name": "model.db.session.query", "line_number": 139, "usage_type": "call"}, {"api_name": "model.User", "line_number": 139, "usage_type": "argument"}, {"api_name": "model.db.session", "line_number": 139, "usage_type": "attribute"}, {"api_name": "model.db", "line_number": 139, "usage_type": "name"}, {"api_name": "model.User.id", "line_number": 139, "usage_type": "attribute"}, {"api_name": "model.db.session.commit", "line_number": 140, "usage_type": "call"}, {"api_name": "model.db.session", "line_number": 140, "usage_type": "attribute"}, {"api_name": "model.db", "line_number": 140, "usage_type": "name"}, {"api_name": "sqlalchemy.exc.IntegrityError", "line_number": 142, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 144, "usage_type": "call"}, {"api_name": "model.User.query.all", "line_number": 152, "usage_type": "call"}, {"api_name": "model.User.query", "line_number": 152, "usage_type": "attribute"}, {"api_name": "model.User", "line_number": 152, "usage_type": "name"}, {"api_name": "simplejson.dumps", "line_number": 159, "usage_type": "call"}, {"api_name": "sqlalchemy.exc.IntegrityError", "line_number": 160, "usage_type": "name"}, {"api_name": "simplejson.dumps", "line_number": 161, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 168, "usage_type": "call"}, {"api_name": "model.app.config", "line_number": 168, "usage_type": "attribute"}, {"api_name": "model.app", "line_number": 168, "usage_type": "name"}, {"api_name": "model.CreateDB", "line_number": 174, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 176, "usage_type": "call"}, {"api_name": "model.db.create_all", "line_number": 183, "usage_type": "call"}, {"api_name": "model.db", "line_number": 183, "usage_type": "name"}, {"api_name": "simplejson.dumps", "line_number": 184, "usage_type": "call"}, {"api_name": "sqlalchemy.exc.IntegrityError", "line_number": 185, "usage_type": "name"}, {"api_name": "simplejson.dumps", "line_number": 186, "usage_type": "call"}]} +{"seq_id": "73588124863", "text": "import numpy as np\nfrom scipy.sparse import coo_matrix\nfrom scipy.linalg import svd\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\n\n# Path to network files if they are not in the same folder\npath = ''\n\nn_nodes = 1000\n\nfor dataset in [\"normal-1\", \"normal-2\", \"normal-3\",\n \"normal-4\", \"lowcc\", \"lowcon\",\n \"highcon\", \"highcc\", \"normal-3-highrate\",\n \"normal-4-lownoise\"]:\n\n name = path + 'network_' + dataset + '.txt'\n raw_graph = np.loadtxt(name, delimiter=\",\")\n row = raw_graph[:, 0] - 1\n col = raw_graph[:, 1] - 1\n data = raw_graph[:, 2]\n valid_index = data > 0\n net = coo_matrix((data[valid_index], (row[valid_index], col[valid_index])),\n shape=(n_nodes, n_nodes))\n\n graph = net.toarray()\n\n _, singular_values, _ = svd(graph)\n singular_values /= singular_values.sum()\n plt.plot(np.sort(singular_values)[::-1], label=dataset)\nplt.legend(loc=\"best\", prop={'size': 12}).draw_frame(False)\nplt.ylabel('Singular values', size=12)\nplt.xlabel('Components', size=12)\nplt.savefig(\"singular_values_all.pdf\", bbox_inches='tight')\n\nplt.close()\n\nfor dataset in [\"normal-1\", \"normal-2\", \"normal-3\",\n \"normal-4\", \"lowcc\", \"lowcon\",\n \"highcon\", \"highcc\", \"normal-3-highrate\",\n \"normal-4-lownoise\"]:\n\n name = path + 'network_' + dataset + '.txt'\n raw_graph = np.loadtxt(name, delimiter=\",\")\n row = raw_graph[:, 0] - 1\n col = raw_graph[:, 1] - 1\n data = raw_graph[:, 2]\n valid_index = data > 0\n net = coo_matrix((data[valid_index], (row[valid_index], col[valid_index])),\n shape=(n_nodes, n_nodes))\n\n graph = net.toarray()\n\n clf = PCA(whiten=True)\n clf = clf.fit(graph)\n plt.plot(np.sort(clf.explained_variance_ratio_[::])[::-1], label=dataset)\nplt.legend(loc=\"best\", prop={'size': 12}).draw_frame(False)\nplt.ylabel('Explained variance ratio', size=12)\nplt.xlabel('Components', size=12)\n\nplt.savefig(\"explained_variance_all.pdf\", bbox_inches='tight')\n", "repo_name": "asutera/kaggle-connectomics", "sub_path": "code/ranks.py", "file_name": "ranks.py", "file_ext": "py", "file_size_in_byte": 2050, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "24", "api": [{"api_name": "numpy.loadtxt", "line_number": 18, "usage_type": "call"}, {"api_name": "scipy.sparse.coo_matrix", "line_number": 23, "usage_type": "call"}, {"api_name": "scipy.linalg.svd", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "numpy.sort", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "numpy.loadtxt", "line_number": 44, "usage_type": "call"}, {"api_name": "scipy.sparse.coo_matrix", "line_number": 49, "usage_type": "call"}, {"api_name": "sklearn.decomposition.PCA", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 56, "usage_type": "name"}, {"api_name": "numpy.sort", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 58, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}]} +{"seq_id": "477978463", "text": "\"\"\"\nUtils and wrappers for scoring lemmatizers.\n\"\"\"\n\nfrom stanza.models.common.utils import ud_scores\n\ndef score(system_conllu_file, gold_conllu_file):\n \"\"\" Wrapper for lemma scorer. \"\"\"\n evaluation = ud_scores(gold_conllu_file, system_conllu_file)\n el = evaluation[\"Lemmas\"]\n p, r, f = el.precision, el.recall, el.f1\n return p, r, f\n\n", "repo_name": "stanfordnlp/stanza", "sub_path": "stanza/models/lemma/scorer.py", "file_name": "scorer.py", "file_ext": "py", "file_size_in_byte": 350, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6858, "dataset": "github-code", "pt": "24", "api": [{"api_name": "stanza.models.common.utils.ud_scores", "line_number": 9, "usage_type": "call"}]} +{"seq_id": "11581671602", "text": "# -*- coding:utf-8 -*-\n\nfrom django import forms\nfrom django.core.exceptions import ValidationError\nfrom django.contrib.auth.admin import User\nfrom .models import CadastrarPessoa\n\nclass CadastrarPessoaForm(forms.ModelForm):\n class Meta:\n model = CadastrarPessoa\n\n fields = (\n 'nome',\n 'sobrenome',\n 'apelido',\n 'sexo',\n 'datanascimento',\n 'email',\n 'senha',\n 'cep',\n 'endereco',\n 'nro',\n 'bairro',\n 'cidade',\n 'estado',\n 'tipo_pessoa',\n 'foto'\n )\n\n widgets = {\n 'senha': forms.PasswordInput,\n }\n\n\n def clean_email(self):\n email = self.cleaned_data['email']\n print('Email:', email)\n number_occurrences = User.objects.filter(email=email).count()\n print('Usuario:', User.objects.filter(email=email))\n print('Numero de Ocorrencias:', number_occurrences)\n if number_occurrences > 0:\n raise ValidationError(u'Email Já cadastrado')\n return self.cleaned_data['email']", "repo_name": "prdioliveira/django-project", "sub_path": "pessoa/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 1138, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.forms.ModelForm", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 8, "usage_type": "name"}, {"api_name": "models.CadastrarPessoa", "line_number": 10, "usage_type": "name"}, {"api_name": "django.forms.PasswordInput", "line_number": 31, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 31, "usage_type": "name"}, {"api_name": "django.contrib.auth.admin.User.objects.filter", "line_number": 38, "usage_type": "call"}, {"api_name": "django.contrib.auth.admin.User.objects", "line_number": 38, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.admin.User", "line_number": 38, "usage_type": "name"}, {"api_name": "django.contrib.auth.admin.User.objects.filter", "line_number": 39, "usage_type": "call"}, {"api_name": "django.contrib.auth.admin.User.objects", "line_number": 39, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.admin.User", "line_number": 39, "usage_type": "name"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 42, "usage_type": "call"}]} +{"seq_id": "8858485249", "text": "from kubernetes import client, config\nimport os\n\n\ndef main():\n # Configs can be set in Configuration class directly or using helper\n # utility. If no argument provided, the config will be loaded from\n # default location.\n # Change kube config location (set up in scripts/env-minikube.sh)\n kubeconfig = os.environ['KUBECONFIG']\n\n config.load_kube_config(config_file=kubeconfig)\n\n v1 = client.CoreV1Api()\n print(\"\\nListing pods with their IPs:\\n\\n\")\n ret = v1.list_pod_for_all_namespaces(watch=False)\n print(\"{:15s} {:30s} {:50s}\".format(\"Pod IP\", \"Namespace\", \"Pod Name\"))\n print(\"-\"*100)\n for i in ret.items:\n print(\"{!s:15s} {:30s} {:50s}\".format(i.status.pod_ip, i.metadata.namespace, i.metadata.name))\n\n\nif __name__ == '__main__':\n main()", "repo_name": "flugel-it/minikube-wks", "sub_path": "podsLister/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 785, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "os.environ", "line_number": 10, "usage_type": "attribute"}, {"api_name": "kubernetes.config.load_kube_config", "line_number": 12, "usage_type": "call"}, {"api_name": "kubernetes.config", "line_number": 12, "usage_type": "name"}, {"api_name": "kubernetes.client.CoreV1Api", "line_number": 14, "usage_type": "call"}, {"api_name": "kubernetes.client", "line_number": 14, "usage_type": "name"}]} +{"seq_id": "1238476334", "text": "import requests\nimport xml.etree.ElementTree as et\nimport aux_collection_insert\nfrom datetime import datetime\n\n\nlast_dates = {}\nformato_data_1 = '%d/%m/%Y'\nformato_data_2 = '%d-%m-%Y'\nformato_data_3 = '%Y-%m-%dT%H:%M:%S'\n\nultimos_monitoramentos = aux_collection_insert.consulta_BD(\"SELECT mon.id, mo.cota, mo.volume, mo.volume_percentual, date_format(mo.data_informacao,'%d-%m-%Y') FROM tb_monitoramento mo RIGHT JOIN (SELECT r.id, max(m.data_informacao) AS maior_data FROM tb_reservatorio r LEFT OUTER JOIN tb_monitoramento m ON r.id=m.id_reservatorio GROUP BY r.id) mon ON mo.id_reservatorio=mon.id AND mon.maior_data=mo.data_informacao WHERE mon.id IN (19123,19116,19122,19124,19125,19121,19126);\")\nfor monit in ultimos_monitoramentos:\n\tif monit[-1] is not None:\n\t\tlast_dates[monit[0]] = datetime.strptime(monit[-1],formato_data_2)\n\ndata_final = datetime.now()\nuhes = ['19123','19116','19122','19124','19125','19121','19126']\n\ncabecalho = ['Codigo','Reservatorio','Cota','Capacidade','Volume','VolumePercentual','DataInformacao']\nto_insert = []\nto_insert_monitoring = []\nreserv_info = aux_collection_insert.consulta_BD(\"SELECT id, capacidade, volume_minimo, volume_util FROM INSA.tb_reservatorio where id in (19123,19116,19122,19124,19125,19121,19126);\")\n# capacidade, volume_minimo, volume_util\nuhe_info = {}\nfor row in reserv_info:\n\tuhe_info[str(row[0])] = [float(row[1])] + [row[2]] + [row[3]]\nfor uhe in uhes:\n\tif uhe not in last_dates:\n\t\tstart = datetime.strptime('01/01/1970',formato_data_1)\n\telse:\n\t\tstart = last_dates[int(uhe)]\n\tinit = start.strftime(formato_data_1)\n\tend = data_final.strftime(formato_data_1)\n\tif start < data_final:\n\t\tresponse = requests.get('http://sarws.ana.gov.br/SarWebService.asmx/DadosHistoricosSIN?CodigoReservatorio='+ uhe +'&DataInicial='+ init +'&DataFinal='+ end)\n\t\ttree = et.fromstring(response.content)\n\t\tfor row in tree:\n\t\t\t#id_reservatorio,volume_util_acumulado,cota,afluencia,defluencia,data_informacao,fonte\n\t\t\tline = []\n\t\t\t#id_reservatorio,cota,volume,volume_percentual,data_informacao,visualizacao,fonte\n\t\t\tline_monitoring = [uhe,0,0,0,0,1,'ANA']\n\t\t\tfor element in row:\n\t\t\t\tif element.tag.replace('{http://sarws.ana.gov.br}','') != 'nome_reservatorio':\n\t\t\t\t\tif element.tag.replace('{http://sarws.ana.gov.br}','') == 'data_medicao':\n\t\t\t\t\t\tline += [datetime.strptime(element.text,formato_data_3).strftime(formato_data_3)] + ['ANA']\n\t\t\t\t\t\tto_insert += [line]\n\t\t\t\t\t\tline_monitoring[4] = datetime.strptime(element.text,formato_data_3).strftime(formato_data_3)\n\t\t\t\t\t\tto_insert_monitoring += [line_monitoring]\n\t\t\t\t\telif element.tag.replace('{http://sarws.ana.gov.br}','') == 'cota':\n\t\t\t\t\t\tline += [element.text]\n\t\t\t\t\t\tline_monitoring[1] = element.text\n\t\t\t\t\telif element.tag.replace('{http://sarws.ana.gov.br}','') == 'volumeUtil':\n\t\t\t\t\t\tif element.text is not None:\n\t\t\t\t\t\t\tvol_ac = float(str(element.text))*uhe_info[uhe][2]/100\n\t\t\t\t\t\t\tline += [format(vol_ac,'.2f')]\n\t\t\t\t\t\t\tline_monitoring[2] = format(vol_ac+uhe_info[uhe][1],'.2f')\n\t\t\t\t\t\t\tline_monitoring[3] = format((vol_ac+uhe_info[uhe][1])*100/uhe_info[uhe][0],'.2f')\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tline += [element.text]\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\telse:\n\t\t\t\t\t\tline += [element.text]\n\t\taux_collection_insert.update_BD(\"UPDATE tb_user_reservatorio SET atualizacao_reservatorio = 1 WHERE id_reservatorio=\"+uhe+\";\")\naux_collection_insert.insert_many_BD_uhe(to_insert)\naux_collection_insert.insert_many_BD(to_insert_monitoring)\n", "repo_name": "analytics-ufcg/sab-api", "sub_path": "script/uhe.py", "file_name": "uhe.py", "file_ext": "py", "file_size_in_byte": 3401, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "aux_collection_insert.consulta_BD", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 15, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 17, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 17, "usage_type": "name"}, {"api_name": "aux_collection_insert.consulta_BD", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 30, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 30, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 36, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.fromstring", "line_number": 37, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 37, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 46, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 46, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 48, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 48, "usage_type": "name"}, {"api_name": "aux_collection_insert.update_BD", "line_number": 64, "usage_type": "call"}, {"api_name": "aux_collection_insert.insert_many_BD_uhe", "line_number": 65, "usage_type": "call"}, {"api_name": "aux_collection_insert.insert_many_BD", "line_number": 66, "usage_type": "call"}]} +{"seq_id": "17627597200", "text": "# Copyrigh The Chromium OS Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"Get speaker/microphone status from cras_client_test, /proc/asound and\n atrus.log.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport logging\nimport re\n\n\nNUM_AUDIO_STREAM_IN_MEETING = 3\n\ndef get_soundcard_by_name(dut, name):\n \"\"\"\n Returns the soundcard number of specified soundcard by name.\n @param dut: The handle of the device under test.\n @param name: The name of Speaker\n For example: 'Hangouts Meet speakermic'\n @returns the soundcard, if no device found returns None.\n \"\"\"\n soundcard = None\n cmd = \"cat /proc/asound/cards | grep \\\"{}\\\" | grep USB\".format(name)\n logging.info('---cmd: %s', cmd)\n try:\n soundcard = dut.run(cmd, ignore_status=True).stdout.strip().split()[0]\n except Exception as e:\n soundcard = None\n logging.exception('Fail to execute %s.', cmd)\n if soundcard:\n soundcard = \"card{}\".format(soundcard)\n logging.info('---audio card %s', soundcard)\n else:\n logging.exception('Fail to get sound card, cli=%s.', cmd)\n return soundcard\n\ndef check_soundcard_by_name(dut, name):\n \"\"\"\n check soundcard by name exists\n @param dut: The handle of the device under test.\n @param name: The name of Speaker\n For example: 'Hangouts Meet speakermic'\n @returns: True, None if test passes,\n False, errMsg if test fails\n \"\"\"\n if get_soundcard_by_name(dut, name):\n return True, None\n else:\n return False, 'Soundcard is not found under /proc/asound/cards.'\n\ndef check_audio_stream(dut, is_in_meeting):\n \"\"\"\n Verify speaker is streaming or not streaming as expected.\n @param dut: The handle of the device under test.\n @is_in_meeting: True if CfM is in meeting, False, if not\n @returns: True, None if test passes,\n False, errMsg if test fails\n \"\"\"\n number_stream = get_number_of_active_streams(dut)\n if is_in_meeting:\n if number_stream >= NUM_AUDIO_STREAM_IN_MEETING:\n return True, None\n else:\n return False, 'Number of Audio streams is not expected.'\n else:\n if number_stream <= NUM_AUDIO_STREAM_IN_MEETING:\n return True, None\n else:\n return False, 'Number of Audio streams is not expected.'\n\ndef get_audio_stream_state(dut, soundcard):\n \"\"\"\n Returns the state of stream0 for specified soundcard.\n\n @param dut: The handle of the device under test. Should be initialized in\n autotest.\n @param soundcard: soundcard\n For example: 'card0'\n\n @returns the list of state of steam0, \"Running\" or \"Stop\"\n\n \"\"\"\n stream_state = []\n try:\n cmd = (\"cat /proc/asound/%s/stream0 | grep Status | \"\n \"awk -v N=2 '{print $N}'\" % soundcard)\n stream_state = dut.run(cmd, ignore_status=True).stdout.split()\n except Exception as e:\n logging.exception('Fail to run cli: %s.', cmd)\n return stream_state\n\n\ndef check_default_speaker_volume(dut, cfm_facade):\n \"\"\"Check volume of speaker is the same as expected.\n @param dut: The handle of the device under test.\n @param cfm_facade: the handle of cfm facade\n @returns True, None if default speakers have same volume as one read\n from hotrod,\n False, errMsg, otherwise\n \"\"\"\n try:\n expected_volume = int(cfm_facade.get_speaker_volume())\n except Exception as e:\n errmsg = 'Fail to run telemetry api to get speaker volume.'\n logging.exception(errmsg)\n return False, errmsg\n if expected_volume < 1:\n return False, 'Fail to get speaker volume from Hotrod.'\n nodes = get_nodes_for_default_speakers_cras(dut)\n if not nodes:\n logging.info('---Fail to get node for default speaker.')\n return False, 'Fail to get node for default speaker.'\n for node in nodes:\n cras_volume = get_speaker_volume_cras(dut, node)\n logging.info('---Volume for default speaker are sync for '\n 'node %s? cfm: %d, cras: %d.'\n 'format(node, expected_volume, cras_volume)')\n if not expected_volume == cras_volume:\n logging.info('---Volume Check Fail for default speaker: '\n 'expected_volume:%d, actual_volume:%d.'\n 'format(expected_volume, cras_volume)')\n return False, ('Volume Check fails for default speaker: '\n 'expected_volume:%d, actual_volume:%d',\n '% expected_volume, cras_volume')\n logging.info('---Expected volume: %d, actual: %d',\n expected_volume, cras_volume)\n return True, None\n\ndef get_number_of_active_streams(dut):\n \"\"\"\n Returns the number of active stream.\n @param dut: The handle of the device under test. Should be initialized in\n autotest.\n @returns the number of active streams.\n \"\"\"\n cmd = (\"cras_test_client --dump_server_info \"\n \"| grep 'Num active streams:' \"\n \"| awk -v N=4 '{print $N}'\")\n\n try:\n number_of_streams = int(dut.run(cmd, ignore_status=True).stdout.strip())\n except Exception as e:\n logging.exception('Fail to execute cli to get number of streams: %s.',\n cmd)\n return None\n logging.info('---number of audio streaming: %d', number_of_streams)\n return number_of_streams\n\n\ndef get_nodes_for_default_speakers_cras(dut):\n \"\"\"get node for default speakers from cras_test_client.\n @param dut: The handle of the device under test. Should be initialized in\n autotest.\n @returns the list of nodes for default speakers. If device not found,\n returns [].\n \"\"\"\n nodes = []\n cmd = (\"cras_test_client --dump_server_info | awk '/Output Nodes:/,\"\n \"/Input Devices:/'\")\n try:\n lines = dut.run(cmd, ignore_status=True).stdout.splitlines()\n except Exception as e:\n logging.exception('Fail to execute cli to get nodes for default'\n 'speaker: %s', cmd)\n return nodes\n for _line in lines:\n match = re.findall(r\"(\\d+):\\d+.*USB\\s+\\*.*\", _line)\n if match:\n nodes.append(match[0])\n logging.info('---found nodes for default speaker %s', nodes)\n return nodes\n\n\ndef get_speaker_for_node_cras(dut, node):\n \"\"\"get node for default speakers from cras_test_client.\n @param dut: The handle of the device under test. Should be initialized in\n autotest.\n\n @returns the list of nodes for default speakers. If device not found,\n returns [].\n \"\"\"\n cmd = (\"cras_test_client --dump_server_info | awk '/Output Devices:/,\"\n \"/Output Nodes:/' | grep '%s'\" % node)\n\n try:\n line = dut.run(cmd, ignore_status=True).stdout.stripe()\n speaker = re.findall(r\"^[0-9]+\\s*(.*):\\s+USB\\s+Audio:\", line)[0]\n except Exception as e:\n logging.exception('Fail to execute cli to get nodes for default'\n 'speaker: %s.', cmd)\n\n logging.info('---speaker for %s is %s', node, speaker)\n return speaker\n\n\ndef get_nodes_for_default_microphone_cras(dut):\n \"\"\"get node for default microphones from cras_test_client.\n @param dut: The handle of the device under test. Should be initialized in\n autotest.\n\n @returns the list of nodes for default microphone. If device not found,\n returns [].\n \"\"\"\n nodes = None\n cmd = (\"cras_test_client --dump_server_info | awk '/Input Nodes:/,\"\n \"/Attached clients:/'\")\n try:\n lines = dut.run(cmd, ignore_status=True).stdout.splitlines()\n for _line in lines:\n nodes.append(re.findall(r\"(\\d+):\\d+.*USB\\s+\\*.*\", _line)[0])\n except Exception as e:\n logging.exception('Fail to execute cli to get nodes for default'\n ' speaker: %s.', cmd)\n return nodes\n\n\ndef get_microphone_for_node_cras(dut, node):\n \"\"\"get node for default speakers from cras_test_client.\n @param dut: The handle of the device under test. Should be initialized in\n autotest.\n\n @returns the list of nodes for default speakers. If device not found,\n returns [].\n \"\"\"\n cmd = (\"cras_test_client --dump_server_info | awk '/Input Devices:/,\"\n \"/Input Nodes:/' | grep '%s' \" % node)\n\n try:\n line = dut.run(cmd, ignore_status=True).stdout\n microphone = re.findall(r\"10\\t(.*):\\s+USB\\s+Audio:\", line)[0]\n except Exception as e:\n logging.exception('Fail to execute cli to get nodes for default'\n ' speaker: %s.', cmd)\n logging.info('---mic for %s is %s', node, microphone)\n return microphone\n\n\ndef get_speaker_volume_cras(dut, node):\n \"\"\"get volume for speaker from cras_test_client based on node\n @param dut: The handle of the device under test. Should be initialized in\n autotest.\n @param node: The node of Speaker\n Example cli:\n cras_test_client --dump_server_info | awk\n '/Output Nodes:/,/Input Devices:/' | grep 9:0 |\n awk -v N=3 '{print $N}'\n\n @returns the volume of speaker. If device not found, returns None.\n \"\"\"\n cmd = (\"cras_test_client --dump_server_info | awk '/Output Nodes:/,\"\n \"/Input Devices:/' | grep -E 'USB' | grep '%s':0 \"\n \"| awk -v N=3 '{print $N}'\" % node)\n try:\n volume = int(dut.run(cmd, ignore_status=True).stdout.strip())\n except Exception as e:\n logging.exception('Fail to execute cli %s to get volume for node %d',\n cmd, node)\n return None\n return volume\n\n\ndef check_cras_mic_mute(dut, cfm_facade):\n \"\"\"\n check microphone is muted or unmuted as expected/.\n @param dut: The handle of the device under test.\n @param cfm_facade: facade of CfM\n @param is_mic_muted: True if muted, False otherwise\n @returns True, none if test passes\n False, errMsg if test fails\n \"\"\"\n try:\n is_mic_muted = cfm_facade.is_mic_muted()\n except Exception as e:\n errmsg = 'Fail to run telemetry api to check mute state for mic.'\n logging.exception(errmsg)\n return False, errmsg\n actual_muted = get_mic_muted_cras(dut)\n if is_mic_muted == actual_muted:\n return True, None\n else:\n if is_mic_muted:\n logging.info('Hotrod setting: microphone is muted')\n else:\n logging.info('Hotrod setting: microphone is not muted')\n if actual_muted:\n logging.info('cras setting: microphone is muted')\n else:\n logging.info('cras setting: microphone is not muted')\n return False, 'Microphone is not muted/unmuted as shown in Hotrod.'\n\ndef check_is_preferred_speaker(dut, name):\n \"\"\"\n check preferred speaker is speaker to be tested.\n @param dut: The handle of the device under test.\n @param cfm_facade: facade of CfM\n @param name: name of speaker\n @returns True, none if test passes\n False, errMsg if test fails\n \"\"\"\n node = None\n cmd = (\"cras_test_client --dump_server_info | awk \"\n \"'/Output Devices:/,/Output Nodes:/' \"\n \"| grep '%s' \" % name)\n try:\n output = dut.run(cmd, ignore_status=True).stdout.strip()\n except Exception as e:\n logging.exception('Fail to run cli %s to find %s in cras_test_client.',\n cmd, node)\n return False, 'Fail to run cli {}:, reason: {}'.format(cmd, str(e))\n logging.info('---output = %s', output)\n if output:\n node = output.split()[0]\n logging.info('---found node for %s is %s', name, node)\n else:\n return False, 'Fail in get node for speaker in cras.'\n default_nodes = get_nodes_for_default_speakers_cras(dut)\n logging.info('---default speaker node is %s', default_nodes)\n if node in default_nodes:\n return True, None\n return False, '{} is not set to preferred speaker.'.format(name)\n\n\ndef check_is_preferred_mic(dut, name):\n \"\"\"check preferred mic is set to speaker to be tested.\"\"\"\n cmd = (\"cras_test_client --dump_server_info | \"\n \"awk '/Input Devices/,/Input Nodes/' | grep '%s' | \"\n \"awk -v N=1 '{print $N}'\" % name)\n logging.info('---cmd = %s',cmd)\n try:\n mic_node = dut.run(cmd, ignore_status=True).stdout.strip()\n logging.info('---mic_node : %s', mic_node)\n except Exception as e:\n logging.exception('Fail to execute: %s to check preferred mic.', cmd)\n return False, 'Fail to run cli.'\n try:\n cmd = (\"cras_test_client --dump_server_info | awk '/Input Nodes:/,\"\n \"/Attached clients:/' | grep default \"\n \"| awk -v N=2 '{print $N}'\")\n mic_node_default = dut.run(cmd, ignore_status=True).stdout.strip()\n if not mic_node_default:\n cmd = (\"cras_test_client --dump_server_info | awk '/Input Nodes:/,\"\n \"/Attached clients:/' | grep '%s' \"\n \"| awk -v N=2 '{print $N}'\" %name)\n mic_node_default = dut.run(cmd,ignore_status=True).stdout.strip()\n logging.info('---%s',cmd)\n logging.info('---%s', mic_node_default)\n except Exception as e:\n msg = 'Fail to execute: {} to check preferred mic'.format(cmd)\n logging.exception(msg)\n return False, msg\n logging.info('---mic node:%s, default node:%s',\n mic_node, mic_node_default)\n if mic_node == mic_node_default.split(':')[0]:\n return True, None\n return False, '{} is not preferred microphone.'.format(name)\n\n\ndef get_mic_muted_cras(dut):\n \"\"\"\n Get the status of mute or unmute for microphone\n @param dut: the handle of CfM under test\n @returns True if mic is muted\n False if mic not not muted\n \"\"\"\n cmd = 'cras_test_client --dump_server_info | grep \"Capture Gain\"'\n try:\n microphone_muted = dut.run(cmd, ignore_status=True).stdout.strip()\n except Exception as e:\n logging.exception('Fail to execute: %s.', cmd)\n return False, 'Fail to execute: {}.'.format(cmd)\n logging.info('---%s', microphone_muted)\n if \"Muted\" in microphone_muted:\n return True\n else:\n return False\n\n\ndef check_speaker_exist_cras(dut, name):\n \"\"\"\n Check speaker exists in cras.\n @param dut: The handle of the device under test.\n @param name: name of speaker\n @returns: True, None if test passes,\n False, errMsg if test fails\n \"\"\"\n cmd = (\"cras_test_client --dump_server_info | awk \"\n \"'/Output Devices:/, /Output Nodes:/' \"\n \"| grep '%s'\" % name)\n try:\n speaker = dut.run(cmd, ignore_status=True).stdout.splitlines()[0]\n except Exception as e:\n logging.exception('Fail to find %s in cras_test_client running %s.',\n name, cmd)\n speaker = None\n logging.info('---cmd: %s\\n---output = %s', cmd, speaker)\n if speaker:\n return True, None\n return False, 'Fail to execute cli {}: Reason: {}'.format(cmd, str(e))\n\n\ndef check_microphone_exist_cras(dut, name):\n \"\"\"\n Check microphone exists in cras.\n @param dut: The handle of the device under test.\n @param name: name of speaker\n @returns: True, None if test passes,\n False, errMsg if test fails\n \"\"\"\n microphone = None\n cmd = (\"cras_test_client --dump_server_info | awk \"\n \"'/Input Devices:/, /Input Nodes:/' \"\n \"| grep '%s'\" % name )\n try:\n microphone = dut.run(cmd, ignore_status=True).stdout.splitlines()[0]\n except Exception as e:\n logging.exception('Fail to execute cli %s.', cmd)\n logging.info('---cmd: %s\\n---output = %s', cmd, microphone)\n if microphone:\n return True, None\n return False, 'Fail to find microphone {}.'.format(name)\n\ndef check_audio_stream(dut, is_in_meet):\n \"\"\"\n Verify speaker is streaming or not streaming as expected.\n @param dut: The handle of the device under test.\n @is_in_meeting: True if CfM is in meeting, False, if not\n @returns: True, None if test passes,\n False, errMsg if test fails\n \"\"\"\n number_stream = get_number_of_active_streams(dut)\n if is_in_meet:\n if number_stream >= NUM_AUDIO_STREAM_IN_MEETING:\n return True, None\n else:\n return False, 'Number of Audio streams is not expected.'\n else:\n if number_stream <= NUM_AUDIO_STREAM_IN_MEETING:\n return True, None\n else:\n return False, 'Number of Audio streams is not expected.'\n\n", "repo_name": "kindle4jerry/honor-play-kernel-9.0-kindle4jerry", "sub_path": "external/autotest/client/common_lib/cros/manual/audio_helper.py", "file_name": "audio_helper.py", "file_ext": "py", "file_size_in_byte": 16745, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "20", "api": [{"api_name": "logging.info", "line_number": 27, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 32, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 35, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 37, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 92, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 108, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 114, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 118, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 122, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 128, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 146, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 149, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 166, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 170, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 173, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 190, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 192, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 195, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 213, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 215, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 233, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 235, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 237, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 259, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 278, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 285, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 287, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 289, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 291, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 310, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 313, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 316, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 320, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 331, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 334, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 336, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 348, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 349, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 352, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 354, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 372, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 374, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 395, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 398, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 419, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 420, "usage_type": "call"}]} +{"seq_id": "20641344116", "text": "from flask import Flask\nfrom flask_login import LoginManager\nfrom application.config import Config\nfrom application.database import db\n\napp=None\nDB_NAME = \"project.sqlite3\"\n\ndef create_app():\n app = Flask(__name__,template_folder='templates')\n app.config.from_object(Config)\n app.config['SECRET_KEY'] = '480627f8209a377319dfe2fdbbfeb145234907922af3dc2b96365d6c9bf4420b'\n db.init_app(app)\n app.app_context().push()\n return app\n\napp= create_app()\nfrom application.controllers import *\n\n\nfrom application.models import Users\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n@login_manager.user_loader\ndef load_user(user_id):\n return Users.query.get(int(user_id))\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\",port=5000,debug=False)", "repo_name": "myneo936/quantifiedSelf", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 770, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 10, "usage_type": "call"}, {"api_name": "application.config.Config", "line_number": 11, "usage_type": "argument"}, {"api_name": "application.database.db.init_app", "line_number": 13, "usage_type": "call"}, {"api_name": "application.database.db", "line_number": 13, "usage_type": "name"}, {"api_name": "flask_login.LoginManager", "line_number": 22, "usage_type": "call"}, {"api_name": "application.models.Users.query.get", "line_number": 26, "usage_type": "call"}, {"api_name": "application.models.Users.query", "line_number": 26, "usage_type": "attribute"}, {"api_name": "application.models.Users", "line_number": 26, "usage_type": "name"}]} +{"seq_id": "86483912385", "text": "import sys\nimport argparse\nimport traceback\nimport tl.exceptions\nfrom tl.utility.logging import Logger\n\n\ndef parser():\n return {\n 'help': 'retrieves candidates based on trigram matches'\n }\n\n\ndef add_arguments(parser):\n \"\"\"\n Parse Arguments\n Args:\n parser: (argparse.ArgumentParser)\n\n \"\"\"\n\n parser.add_argument('-c', '--column', action='store', type=str, dest='column', required=True,\n help='the column used for retrieving candidates.')\n\n parser.add_argument('-n', action='store', type=int, dest='size', default=50,\n help='maximum number of candidates to retrieve')\n\n parser.add_argument('-o', '--output-column', action='store', type=str, dest='output_column_name',\n default=\"retrieval_score\",\n help='the output column name where the normalized scores will be stored.'\n 'Default is retrieval_score')\n\n parser.add_argument('--auxiliary-fields', action='store', type=str, dest='auxiliary_fields', default=None,\n help='A comma separated string of auxiliary field names in the elasticsearch.'\n 'A file will be created for each of the specified field at the location specified by'\n ' the `--auxiliary-folder` option. If this option is specified then,'\n ' `--auxiliary-folder` must also be specified.')\n\n parser.add_argument('--auxiliary-folder', action='store', type=str, dest='auxiliary_folder', default=None,\n help='location where the auxiliary files for auxiliary fields will be stored.'\n 'If this option is specified then `--auxiliary-fields` must also be specified.')\n\n parser.add_argument('--property', action='store', type=str, dest='property', default=None,\n help='matching candidates must have this property')\n\n parser.add_argument('--isa', action='store', type=str, dest='isa', default=None,\n help='matching candidates must be isntance of this qnode')\n\n parser.add_argument('--pseudo-gt-column', action='store', type=str, dest='pgt_column', default=None,\n help='column which specifies whether a candidate is part of pseudo ground truth or not. '\n 'if specified, the trigram search will be performed on all non pseudo ground truth cells')\n\n parser.add_argument('input_file', nargs='?', type=argparse.FileType('r'), default=sys.stdin)\n\n\ndef run(**kwargs):\n from tl.candidate_generation.get_trigram_matches import TriGramMatches\n import pandas as pd\n import time\n try:\n auxiliary_fields = kwargs.get('auxiliary_fields', None)\n auxiliary_folder = kwargs.get('auxiliary_folder', None)\n\n if (auxiliary_folder is not None and auxiliary_fields is None) or (\n auxiliary_folder is None and auxiliary_fields is not None):\n raise Exception(\"Both the options `--auxiliary-fields` and `--auxiliary-folder` have to be specified \"\n \"if either one is specified\")\n\n if auxiliary_fields is not None:\n auxiliary_fields = auxiliary_fields.split(\",\")\n\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n start = time.time()\n tgm = TriGramMatches(es_url=kwargs['url'],\n es_index=kwargs['index'],\n es_user=kwargs['user'],\n es_pass=kwargs['password'],\n output_column_name=kwargs['output_column_name'],\n pgt_column=kwargs['pgt_column'])\n odf = tgm.get_trigram_matches(kwargs['column'],\n size=kwargs['size'], df=df,\n auxiliary_fields=auxiliary_fields,\n auxiliary_folder=auxiliary_folder,\n property=kwargs['property'],\n isa=kwargs['isa'])\n end = time.time()\n logger = Logger(kwargs[\"logfile\"])\n logger.write_to_file(args={\n \"command\": \"get-trigram-matches\",\n \"time\": end - start\n })\n odf.to_csv(sys.stdout, index=False)\n except:\n message = 'Command: get-trigram-matches\\n'\n message += 'Error Message: {}\\n'.format(traceback.format_exc())\n raise tl.exceptions.TLException(message)\n", "repo_name": "usc-isi-i2/table-linker", "sub_path": "tl/cli/get-trigram-matches.py", "file_name": "get-trigram-matches.py", "file_ext": "py", "file_size_in_byte": 4532, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 21, "dataset": "github-code", "pt": "24", "api": [{"api_name": "argparse.FileType", "line_number": 53, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 53, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 72, "usage_type": "call"}, {"api_name": "time.time", "line_number": 73, "usage_type": "call"}, {"api_name": "tl.candidate_generation.get_trigram_matches.TriGramMatches", "line_number": 74, "usage_type": "call"}, {"api_name": "time.time", "line_number": 86, "usage_type": "call"}, {"api_name": "tl.utility.logging.Logger", "line_number": 87, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 92, "usage_type": "attribute"}, {"api_name": "traceback.format_exc", "line_number": 95, "usage_type": "call"}, {"api_name": "tl.exceptions.exceptions.TLException", "line_number": 96, "usage_type": "call"}, {"api_name": "tl.exceptions.exceptions", "line_number": 96, "usage_type": "attribute"}, {"api_name": "tl.exceptions", "line_number": 96, "usage_type": "name"}]} +{"seq_id": "72575886129", "text": "import argparse\nimport pathlib\n\nimport utils_requirements\n\n\"\"\"\nUtilities to manage requirements files.\nNOTE: this should use ONLY the standard library and not import anything else\nbecause this is used for boostrapping with no requirements installed.\n\"\"\"\n\n\ndef gen_requirements():\n description = \"\"\"\n Create or replace the `--requirements-file` file FILE requirements file with all\n locally installed Python packages.all Python packages found installed in `--site-packages-dir`\n \"\"\"\n parser = argparse.ArgumentParser(description=description)\n\n parser.add_argument(\n \"-s\",\n \"--site-packages-dir\",\n dest=\"site_packages_dir\",\n type=pathlib.Path,\n required=True,\n metavar=\"DIR\",\n help=\"Path to the 'site-packages' directory where wheels are installed such as lib/python3.6/site-packages\",\n )\n parser.add_argument(\n \"-r\",\n \"--requirements-file\",\n type=pathlib.Path,\n metavar=\"FILE\",\n default=\"requirements.txt\",\n help=\"Path to the requirements file to update or create.\",\n )\n\n args = parser.parse_args()\n\n utils_requirements.lock_requirements(\n site_packages_dir=args.site_packages_dir,\n requirements_file=args.requirements_file,\n )\n\n\nif __name__ == \"__main__\":\n gen_requirements()\n", "repo_name": "nexB/scancode-toolkit", "sub_path": "etc/scripts/gen_requirements.py", "file_name": "gen_requirements.py", "file_ext": "py", "file_size_in_byte": 1320, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1846, "dataset": "github-code", "pt": "20", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 18, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 32, "usage_type": "attribute"}, {"api_name": "utils_requirements.lock_requirements", "line_number": 40, "usage_type": "call"}]} +{"seq_id": "3307602822", "text": "__author__ = 'pat'\n'''\nBidirectional Recurrent Neural Network\nwith Connectionist Temporal Classification (CTC)\n courtesy of https://github.com/shawntan/rnn-experiment\n courtesy of https://github.com/rakeshvar/rnn_ctc\nimplemented in Theano and optimized for use on a GPU\n'''\n\nimport theano\nimport theano.tensor as T\nfrom theano_toolkit import utils as U\nfrom theano_toolkit import updates\nimport numpy as np\nimport cPickle as pickle\nimport time\n\n#THEANO_FLAGS='device=cpu,floatX=float32'\n#theano.config.warn_float64='warn'\n\n#theano.config.optimizer = 'fast_compile'\ntheano.config.exception_verbosity='high'\ntheano.config.on_unused_input='warn'\n\n\nclass FeedForwardLayer:\n def __init__(self, inputs, input_size, output_size, rng, dropout_rate, parameters=None):\n self.activation_fn = lambda x: T.minimum(x * (x > 0), 20)\n\n if parameters is None:\n self.W = U.create_shared(U.initial_weights(input_size, output_size), name='W')\n self.b = U.create_shared(U.initial_weights(output_size), name='b')\n else:\n self.W = theano.shared(parameters['W'], name='W')\n self.b = theano.shared(parameters['b'], name='b')\n\n\n self.output = T.cast(self.activation_fn( (T.dot(inputs, self.W) + self.b)*(1.0-dropout_rate) ), dtype=theano.config.floatX)\n\n self.params = [self.W, self.b]\n\n def get_parameters(self):\n params = {}\n for param in self.params:\n params[param.name] = param.get_value()\n return params\n\n def set_parameters(self, parameters):\n self.W.set_value(parameters['W'])\n self.b.set_value(parameters['b'])\n\n\nclass RecurrentLayer:\n def __init__(self, inputs, input_size, output_size, is_backward=False, parameters=None):\n\n if parameters is None:\n self.W_if = U.create_shared(U.initial_weights(input_size, output_size), name='W_if')\n self.W_ff = U.create_shared(U.initial_weights(output_size, output_size), name='W_ff')\n self.b = U.create_shared(U.initial_weights(output_size), name='b')\n else:\n self.W_if = theano.shared(parameters['W_if'], name='W_if')\n self.W_ff = theano.shared(parameters['W_ff'], name='W_ff')\n self.b = theano.shared(parameters['b'], name='b')\n\n initial = T.zeros((output_size,))\n self.is_backward = is_backward\n self.activation_fn = lambda x: T.cast(T.minimum(x * (x > 0), 20), dtype='float32')#dtype=theano.config.floatX)\n \n nonrecurrent = T.dot(inputs, self.W_if) + self.b\n\n self.output, _ = theano.scan(\n lambda in_t, out_tminus1, weights: self.activation_fn(in_t + T.dot(out_tminus1, weights)),\n sequences=[nonrecurrent],\n outputs_info=[initial],\n non_sequences=[self.W_ff],\n go_backwards=self.is_backward\n )\n\n self.params = [self.W_if, self.W_ff, self.b]\n\n def get_parameters(self):\n params = {}\n for param in self.params:\n params[param.name] = param.get_value()\n return params\n\n def set_parameters(self, parameters):\n self.W_if.set_value(parameters['W_if'])\n self.W_ff.set_value(parameters['W_ff'])\n self.b.set_value(parameters['b'])\n\n\nclass SoftmaxLayer:\n def __init__(self, inputs, input_size, output_size, parameters=None):\n\n if parameters is None:\n self.W = U.create_shared(U.initial_weights(input_size, output_size), name='W')\n self.b = U.create_shared(U.initial_weights(output_size), name='b')\n else:\n self.W = theano.shared(parameters['W'], name='W')\n self.b = theano.shared(parameters['b'], name='b')\n\n self.output = T.nnet.softmax(T.dot(inputs, self.W) + self.b)\n self.params = [self.W, self.b]\n\n def get_parameters(self):\n params = {}\n for param in self.params:\n params[param.name] = param.get_value()\n return params\n\n def set_parameters(self, parameters):\n self.W.set_value(parameters['W'])\n self.b.set_value(parameters['b'])\n\n\n\nclass BRNN:\n def __init__(self, input_dimensionality, output_dimensionality, params=None, learning_rate=0.0001, momentum=.25):\n self.input_dimensionality = input_dimensionality\n self.output_dimensionality = output_dimensionality\n self.learning_rate = learning_rate\n srng = theano.tensor.shared_randomstreams.RandomStreams(seed=1234)\n\n input_seq = T.fmatrix('input_seq')\n dropoutRate = T.fscalar('dropoutRate')\n\n if params is None:\n self.ff1 = FeedForwardLayer(input_seq, self.input_dimensionality, 2000, rng=srng, dropout_rate=dropoutRate)\n self.ff2 = FeedForwardLayer(self.ff1.output, 2000, 1000, rng=srng, dropout_rate=dropoutRate)\n self.ff3 = FeedForwardLayer(self.ff2.output, 1000, 800, rng=srng, dropout_rate=dropoutRate)\n self.rf = RecurrentLayer(self.ff3.output, 800, 500, False) # Forward layer\n self.rb = RecurrentLayer(self.ff3.output, 800, 500, True) # Backward layer\n\n # REVERSE THE BACKWARDS RECURRENT OUTPUTS IN TIME (from [T-1, 0] ===> [0, T-1]\n self.s = SoftmaxLayer(T.concatenate((self.rf.output, self.rb.output[::-1, :]), axis=1), 2*500, self.output_dimensionality)\n\n else:\n self.ff1 = FeedForwardLayer(input_seq, self.input_dimensionality, 2000, parameters=params[0], rng=srng, dropout_rate=dropoutRate)\n self.ff2 = FeedForwardLayer(self.ff1.output, 2000, 1000, parameters=params[1], rng=srng, dropout_rate=dropoutRate)\n self.ff3 = FeedForwardLayer(self.ff2.output, 1000, 800, parameters=params[2], rng=srng, dropout_rate=dropoutRate)\n self.rf = RecurrentLayer(self.ff3.output, 800, 500, False, parameters=params[3]) # Forward layer\n self.rb = RecurrentLayer(self.ff3.output, 800, 500, True, parameters=params[4]) # Backward layer\n\n # REVERSE THE BACKWARDS RECURRENT OUTPUTS IN TIME (from [T-1, 0] ===> [0, T-1]\n self.s = SoftmaxLayer(T.concatenate((self.rf.output, self.rb.output[::-1, :]), axis=1), 2*500, self.output_dimensionality, parameters=params[5])\n\n\n self.probabilities = theano.function(\n inputs=[input_seq, dropoutRate],\n outputs=[self.s.output],\n allow_input_downcast=True\n )\n\n\n def dump(self, f_path):\n f = file(f_path, 'wb')\n for obj in [self.ff1.get_parameters(), self.ff2.get_parameters(), self.ff3.get_parameters(), self.rf.get_parameters(), self.rb.get_parameters(), self.s.get_parameters()]:\n pickle.dump(obj, f, protocol=pickle.HIGHEST_PROTOCOL)\n f.close()\n\nclass Network:\n def __init__(self):\n self.nn = None\n\n def create_network(self, input_dimensionality, output_dimensionality, learning_rate=0.01, momentum=.25):\n self.nn = BRNN(input_dimensionality, output_dimensionality, params=None, learning_rate=learning_rate, momentum=momentum)\n return self.nn\n\n def load_network(self, path, input_dimensionality, output_dimensionality, learning_rate=0.00001, momentum=.75):\n f = file(path, 'rb')\n parameters = []\n for i in np.arange(6):\n parameters.append(pickle.load(f))\n f.close()\n\n self.nn = BRNN(input_dimensionality, output_dimensionality, params=parameters, learning_rate=learning_rate, momentum=momentum)\n return self.nn\n\n def dump_network(self, path):\n if self.nn is None:\n return False\n\n self.nn.dump(path)\n\n def get_network(self):\n assert(self.nn is not None)\n return [self.nn.ff1.get_parameters(), self.nn.ff2.get_parameters(), self.nn.ff3.get_parameters(), self.nn.rf.get_parameters(), self.nn.rb.get_parameters(), self.nn.s.get_parameters()]\n\n def set_network(self, parameters):\n assert(type(parameters) == list)\n assert(len(parameters) == 6)\n\n self.nn.ff1.set_parameters(parameters[0])\n self.nn.ff2.set_parameters(parameters[1])\n self.nn.ff3.set_parameters(parameters[2])\n self.nn.rf.set_parameters(parameters[3])\n self.nn.rb.set_parameters(parameters[4])\n self.nn.s.set_parameters(parameters[5])\n \n def set_network_from_file(self, fname):\n f = file(fname, 'rb')\n parameters = []\n for i in np.arange(6):\n parameters.append(pickle.load(f))\n f.close()\n \n self.set_network(parameters)\n", "repo_name": "patyork/AutomaticSpeechChunker", "sub_path": "speech_model_trained.py", "file_name": "speech_model_trained.py", "file_ext": "py", "file_size_in_byte": 8464, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 16, "dataset": "github-code", "pt": "24", "api": [{"api_name": "theano.config", "line_number": 22, "usage_type": "attribute"}, {"api_name": "theano.config", "line_number": 23, "usage_type": "attribute"}, {"api_name": "theano.tensor.minimum", "line_number": 28, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 28, "usage_type": "name"}, {"api_name": "theano_toolkit.utils.create_shared", "line_number": 31, "usage_type": "call"}, {"api_name": "theano_toolkit.utils", "line_number": 31, "usage_type": "name"}, {"api_name": "theano_toolkit.utils.initial_weights", "line_number": 31, "usage_type": "call"}, {"api_name": "theano_toolkit.utils.create_shared", "line_number": 32, "usage_type": "call"}, {"api_name": "theano_toolkit.utils", "line_number": 32, "usage_type": "name"}, {"api_name": "theano_toolkit.utils.initial_weights", "line_number": 32, "usage_type": "call"}, {"api_name": "theano.shared", "line_number": 34, "usage_type": "call"}, {"api_name": "theano.shared", "line_number": 35, "usage_type": "call"}, {"api_name": "theano.tensor.cast", "line_number": 38, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 38, "usage_type": "name"}, {"api_name": "theano.tensor.dot", "line_number": 38, "usage_type": "call"}, {"api_name": "theano.config", "line_number": 38, "usage_type": "attribute"}, {"api_name": "theano_toolkit.utils.create_shared", "line_number": 57, "usage_type": "call"}, {"api_name": "theano_toolkit.utils", "line_number": 57, "usage_type": "name"}, {"api_name": "theano_toolkit.utils.initial_weights", "line_number": 57, "usage_type": "call"}, {"api_name": "theano_toolkit.utils.create_shared", "line_number": 58, "usage_type": "call"}, {"api_name": "theano_toolkit.utils", "line_number": 58, "usage_type": "name"}, {"api_name": "theano_toolkit.utils.initial_weights", "line_number": 58, "usage_type": "call"}, {"api_name": "theano_toolkit.utils.create_shared", "line_number": 59, "usage_type": "call"}, {"api_name": "theano_toolkit.utils", "line_number": 59, "usage_type": "name"}, {"api_name": "theano_toolkit.utils.initial_weights", "line_number": 59, "usage_type": "call"}, {"api_name": "theano.shared", "line_number": 61, "usage_type": "call"}, {"api_name": "theano.shared", "line_number": 62, "usage_type": "call"}, {"api_name": "theano.shared", "line_number": 63, "usage_type": "call"}, {"api_name": "theano.tensor.zeros", "line_number": 65, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 65, "usage_type": "name"}, {"api_name": "theano.tensor.cast", "line_number": 67, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 67, "usage_type": "name"}, {"api_name": "theano.tensor.minimum", "line_number": 67, "usage_type": "call"}, {"api_name": "theano.tensor.dot", "line_number": 69, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 69, "usage_type": "name"}, {"api_name": "theano.scan", "line_number": 71, "usage_type": "call"}, {"api_name": "theano.tensor.dot", "line_number": 72, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 72, "usage_type": "name"}, {"api_name": "theano_toolkit.utils.create_shared", "line_number": 97, "usage_type": "call"}, {"api_name": "theano_toolkit.utils", "line_number": 97, "usage_type": "name"}, {"api_name": "theano_toolkit.utils.initial_weights", "line_number": 97, "usage_type": "call"}, {"api_name": "theano_toolkit.utils.create_shared", "line_number": 98, "usage_type": "call"}, {"api_name": "theano_toolkit.utils", "line_number": 98, "usage_type": "name"}, {"api_name": "theano_toolkit.utils.initial_weights", "line_number": 98, "usage_type": "call"}, {"api_name": "theano.shared", "line_number": 100, "usage_type": "call"}, {"api_name": "theano.shared", "line_number": 101, "usage_type": "call"}, {"api_name": "theano.tensor.nnet.softmax", "line_number": 103, "usage_type": "call"}, {"api_name": "theano.tensor.nnet", "line_number": 103, "usage_type": "attribute"}, {"api_name": "theano.tensor", "line_number": 103, "usage_type": "name"}, {"api_name": "theano.tensor.dot", "line_number": 103, "usage_type": "call"}, {"api_name": "theano.tensor.shared_randomstreams.RandomStreams", "line_number": 123, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 123, "usage_type": "attribute"}, {"api_name": "theano.tensor.fmatrix", "line_number": 125, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 125, "usage_type": "name"}, {"api_name": "theano.tensor.fscalar", "line_number": 126, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 126, "usage_type": "name"}, {"api_name": "theano.tensor.concatenate", "line_number": 136, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 136, "usage_type": "name"}, {"api_name": "theano.tensor.concatenate", "line_number": 146, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 146, "usage_type": "name"}, {"api_name": "theano.function", "line_number": 149, "usage_type": "call"}, {"api_name": "cPickle.dump", "line_number": 159, "usage_type": "call"}, {"api_name": "cPickle.HIGHEST_PROTOCOL", "line_number": 159, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 173, "usage_type": "call"}, {"api_name": "cPickle.load", "line_number": 174, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 204, "usage_type": "call"}, {"api_name": "cPickle.load", "line_number": 205, "usage_type": "call"}]} +{"seq_id": "5331491661", "text": "from rest_framework import serializers\nfrom wq.db import rest\nfrom wq.db.rest.serializers import ModelSerializer\nfrom .models import FileSource, URLSource\nfrom ..rest import user_filter\n\n\n@rest.register(\n FileSource,\n url=\"filesources\",\n background_sync=False,\n filter=user_filter,\n show_in_index=\"can_change\",\n section=\"Data Wizard\",\n order=200,\n icon=\"wizard\",\n)\nclass FileSourceSerializer(ModelSerializer):\n user = serializers.HiddenField(default=serializers.CurrentUserDefault())\n\n class Meta:\n model = FileSource\n fields = \"__all__\"\n\n\n\n@rest.register(\n URLSource,\n url=\"urlsources\",\n background_sync=False,\n filter=user_filter,\n show_in_index=\"can_change\",\n section=\"Data Wizard\",\n order=201,\n icon=\"wizard\",\n)\nclass URLSourceSerializer(ModelSerializer):\n user = serializers.HiddenField(default=serializers.CurrentUserDefault())\n\n class Meta:\n model = URLSource\n fields = \"__all__\"\n", "repo_name": "wq/django-data-wizard", "sub_path": "data_wizard/sources/rest.py", "file_name": "rest.py", "file_ext": "py", "file_size_in_byte": 975, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 322, "dataset": "github-code", "pt": "24", "api": [{"api_name": "wq.db.rest.serializers.ModelSerializer", "line_number": 18, "usage_type": "name"}, {"api_name": "rest_framework.serializers.HiddenField", "line_number": 19, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 19, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CurrentUserDefault", "line_number": 19, "usage_type": "call"}, {"api_name": "models.FileSource", "line_number": 22, "usage_type": "name"}, {"api_name": "wq.db.rest.register", "line_number": 8, "usage_type": "call"}, {"api_name": "models.FileSource", "line_number": 9, "usage_type": "argument"}, {"api_name": "wq.db.rest", "line_number": 8, "usage_type": "name"}, {"api_name": "rest.user_filter", "line_number": 12, "usage_type": "name"}, {"api_name": "wq.db.rest.serializers.ModelSerializer", "line_number": 37, "usage_type": "name"}, {"api_name": "rest_framework.serializers.HiddenField", "line_number": 38, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 38, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CurrentUserDefault", "line_number": 38, "usage_type": "call"}, {"api_name": "models.URLSource", "line_number": 41, "usage_type": "name"}, {"api_name": "wq.db.rest.register", "line_number": 27, "usage_type": "call"}, {"api_name": "models.URLSource", "line_number": 28, "usage_type": "argument"}, {"api_name": "wq.db.rest", "line_number": 27, "usage_type": "name"}, {"api_name": "rest.user_filter", "line_number": 31, "usage_type": "name"}]} +{"seq_id": "27707723906", "text": "import urllib\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse, Http404\nfrom django.db.models import Exists, F, OuterRef\nfrom django.urls import reverse\nfrom django.utils.html import format_html\nfrom django.conf import settings\nfrom api.models import Project, Message\nimport api\nfrom mod import dispatch_module_hook\nfrom patchew.logviewer import LogView\nimport subprocess\n\nPAGE_SIZE = 50\n\n\ndef try_get_git_head():\n try:\n return (\n \"-\"\n + subprocess.check_output([\"git\", \"rev-parse\", \"--short\", \"HEAD\"]).decode()\n )\n except Exception:\n return \"\"\n\n\ndef render_page(request, template_name, **data):\n data[\"patchew_version\"] = settings.VERSION + try_get_git_head()\n dispatch_module_hook(\"render_page_hook\", request=request, context_data=data)\n return render(request, template_name, context=data)\n\n\ndef prepare_message(request, project, m, for_message_view):\n name, addr = m.sender\n m.sender_full_name = \"%s <%s>\" % (name, addr)\n m.sender_display_name = name or addr\n m.url = reverse(\n \"series_detail\", kwargs={\"project\": project.name, \"message_id\": m.message_id}\n )\n m.status_tags = []\n m.extra_links = []\n if m.is_series_head:\n m.num_patches = m.get_num_patches()\n m.total_patches = m.get_total_patches()\n if m.num_patches < m.total_patches:\n missing = m.total_patches - m.num_patches\n m.status_tags.append(\n {\n \"title\": \"Series not complete (%d %s not received)\"\n % (missing, \"patches\" if missing > 1 else \"patch\"),\n \"type\": \"warning\",\n \"char\": \"?\",\n }\n )\n\n # hook points for plugins\n m.has_other_revisions = False\n m.extra_status = []\n m.extra_ops = []\n dispatch_module_hook(\n \"prepare_message_hook\", request=request, message=m, for_message_view=for_message_view\n )\n if m.is_merged:\n m.status_tags = [\n {\"title\": \"Series merged\", \"type\": \"success\", \"char\": \"Merged\"}\n ]\n return m\n\n\ndef prepare_patches(request, m, max_depth=None):\n if m.total_patches == 1:\n return []\n replies = m.get_replies().filter(is_patch=True)\n commit_replies = api.models.Message.objects.filter(\n in_reply_to=OuterRef(\"message_id\")\n )\n replies = replies.annotate(has_replies=Exists(commit_replies))\n project = m.project\n return [prepare_message(request, project, x, True) for x in replies]\n\n\ndef prepare_series(request, s, skip_patches=False):\n r = []\n project = s.project\n\n def add_msg_recurse(m, skip_patches, depth=0):\n a = prepare_message(request, project, m, True)\n a.indent_level = min(depth, 4)\n r.append(a)\n replies = m.get_replies()\n non_patches = [x for x in replies if not x.is_patch]\n patches = []\n if not skip_patches:\n patches = [x for x in replies if x.is_patch]\n for x in non_patches + patches:\n add_msg_recurse(x, False, depth + 1)\n\n add_msg_recurse(s, skip_patches)\n return r\n\n\ndef prepare_results(request, obj):\n rendered_results = []\n for result in obj.results.all():\n html = result.render()\n if html is None:\n continue\n result.html = html\n rendered_results.append(result)\n return rendered_results\n\n\ndef prepare_series_list(request, sl):\n return [prepare_message(request, s.project, s, False) for s in sl]\n\n\ndef prepare_projects():\n return api.models.Project.objects.filter(parent_project=None).order_by(\n \"-display_order\", \"name\"\n )\n\n\ndef view_project_list(request):\n return render_page(request, \"project-list.html\", projects=prepare_projects())\n\n\ndef gen_page_links(query, cur_page, pagesize, extra_params):\n # stop a little after the current page\n limit = max(cur_page + 3, 10)\n\n # include one extra record in the limit, so that the final \"...\" can be printed,\n # but do not go all the way to the end\n total = query[: pagesize * limit + 1].count()\n max_page = int((total + pagesize - 1) / pagesize)\n start = 10 if max_page <= 10 else 3\n\n ret = []\n ddd = False\n i = 1\n offset = 1\n while offset <= total:\n if (i > start and abs(i - cur_page) >= 3 and max_page - i >= 3) or (offset > pagesize * limit):\n if not ddd:\n result = {\"title\": \"...\", \"class\": \"disabled\", \"url\": \"\"}\n ret.append(result)\n ddd = True\n else:\n result = {\"title\": str(i), \"url\": \"?page=\" + str(i) + extra_params}\n if i == cur_page:\n result[\"class\"] = \"active\"\n ret.append(result)\n ddd = False\n\n i += 1\n offset += pagesize\n\n return ret\n\n\ndef get_page_from_request(request):\n try:\n return int(request.GET[\"page\"])\n except Exception:\n return 1\n\n\ndef prepare_navigate_list(cur, *path):\n \"\"\"each path is (view_name, kwargs, title)\"\"\"\n r = [{\"url\": reverse(\"project_list\"), \"title\": \"Patchew\"}]\n for it in path:\n r.append({\"url\": reverse(it[0], kwargs=it[1]), \"title\": it[2]})\n r.append({\"title\": cur, \"url\": \"\", \"class\": \"active\"})\n return r\n\n\ndef render_series_list_page(\n request,\n base_query,\n search=None,\n project=None,\n title=\"Search results\",\n link_icon=None,\n link_url=None,\n link_text=None,\n keywords=[],\n is_search=False,\n button_url=None,\n button_data=None,\n button_text=None,\n):\n sort = request.GET.get(\"sort\")\n cur_page = get_page_from_request(request)\n start = (cur_page - 1) * PAGE_SIZE\n params = \"\"\n if sort:\n params += \"&\" + urllib.parse.urlencode({\"sort\": sort})\n if search is not None:\n params += \"&\" + urllib.parse.urlencode({\"q\": search})\n cur = 'search \"%s\"' % search\n if project:\n nav_path = prepare_navigate_list(\n cur, (\"series_list\", {\"project\": project}, project)\n )\n else:\n nav_path = prepare_navigate_list(cur)\n else:\n search = \"project:%s\" % project\n nav_path = prepare_navigate_list(project)\n page_links = gen_page_links(base_query, cur_page, PAGE_SIZE, params)\n\n if sort == \"replied\":\n query = base_query.order_by(F(\"last_reply_date\").desc(nulls_last=True), \"-date\")\n order_by_reply = True\n else:\n query = base_query.order_by(\"-date\")\n order_by_reply = False\n query = query.prefetch_related(\"topic\", \"results\")\n series = query[start : start + PAGE_SIZE]\n if not series and cur_page > 1:\n raise Http404(\"Page not found\")\n\n if project:\n title += \" for \" + project\n return render_page(\n request,\n \"series-list.html\",\n series=prepare_series_list(request, series),\n page_links=page_links,\n search=search,\n is_search=is_search,\n title=title,\n project=project,\n link_icon=link_icon,\n link_url=link_url,\n link_text=link_text,\n keywords=keywords,\n order_by_reply=order_by_reply,\n navigate_links=nav_path,\n button_url=button_url,\n button_data=button_data,\n button_text=button_text,\n )\n\n\ndef view_search_help(request):\n from markdown import markdown\n\n nav_path = prepare_navigate_list(\"Search help\")\n return render_page(\n request,\n \"search-help.html\",\n navigate_links=nav_path,\n search_help_doc=markdown(api.search.SearchEngine.__doc__),\n )\n\n\ndef view_project_detail(request, project):\n po = api.models.Project.objects.filter(name=project).first()\n if not po:\n raise Http404(\"Project not found\")\n nav_path = prepare_navigate_list(\n \"Information\", (\"series_list\", {\"project\": project}, project)\n )\n po.extra_info = []\n po.extra_status = []\n po.extra_ops = []\n dispatch_module_hook(\"prepare_project_hook\", request=request, project=po)\n return render_page(\n request,\n \"project-detail.html\",\n results=prepare_results(request, po),\n project=po,\n navigate_links=nav_path,\n search=\"\",\n )\n\n\ndef view_search(request):\n from api.search import SearchEngine\n\n search = request.GET.get(\"q\", \"\").strip()\n se = SearchEngine([search], request.user)\n query = se.search_series()\n return render_series_list_page(\n request,\n query,\n search=search,\n project=se.project(),\n keywords=se.last_keywords(),\n is_search=True,\n )\n\n\ndef view_series_list(request, project):\n prj = api.models.Project.objects.filter(name=project).first()\n if not prj:\n raise Http404(\"Project not found\")\n query = api.models.Message.objects.series_heads(prj.id)\n return render_series_list_page(\n request,\n query,\n project=project,\n title=\"All series\",\n link_icon=\"fa fa-list\",\n link_url=reverse(\"project_detail\", kwargs={\"project\": project}),\n link_text=\"More information about \" + project + \"...\",\n )\n\n\ndef view_mbox(request, project, message_id):\n s = api.models.Message.objects.find_message(message_id, project)\n if not s:\n raise Http404(\"Series not found\")\n mbox = s.get_mbox_with_tags()\n if not mbox:\n raise Http404(\"Series not complete\")\n return HttpResponse(mbox, content_type=\"text/plain\")\n\n\ndef view_series_detail(request, project, message_id):\n s = api.models.Message.objects.find_series(message_id, project)\n if not s:\n raise Http404(\"Series not found\")\n nav_path = prepare_navigate_list(\n \"View series\", (\"series_list\", {\"project\": project}, project)\n )\n search = \"id:\" + message_id\n is_cover_letter = not s.is_patch\n messages = prepare_series(request, s, is_cover_letter)\n series = messages[0]\n if s.num_patches >= s.total_patches:\n mbox_url = reverse(\n \"mbox\", kwargs={\"project\": project, \"message_id\": message_id}\n )\n title = \"Download series mbox\" if is_cover_letter else \"Download mbox\"\n series.extra_links.append(\n {\n \"html\": format_html('{}', mbox_url, title),\n \"icon\": \"download\",\n }\n )\n return render_page(\n request,\n \"series-detail.html\",\n subject=s.subject,\n stripped_subject=s.stripped_subject,\n has_other_revisions=series.has_other_revisions,\n version=s.version,\n message_id=s.message_id,\n series=series,\n is_cover_letter=is_cover_letter,\n is_head=True,\n project=project,\n navigate_links=nav_path,\n search=search,\n results=prepare_results(request, s),\n patches=prepare_patches(request, s),\n messages=messages,\n )\n\n\ndef view_series_message(request, project, thread_id, message_id):\n s = api.models.Message.objects.find_series(thread_id, project)\n if not s:\n raise Http404(\"Series not found\")\n m = api.models.Message.objects.filter(\n message_id=message_id, in_reply_to=thread_id\n ).first()\n if not m:\n raise Http404(\"Message not found\")\n nav_path = prepare_navigate_list(\n \"View patch\",\n (\"series_list\", {\"project\": project}, project),\n (\"series_detail\", {\"project\": project, \"message_id\": thread_id}, s.subject),\n )\n search = \"id:\" + thread_id\n series = prepare_message(request, s.project, s, True)\n messages = prepare_series(request, m)\n mbox_url = reverse(\"mbox\", kwargs={\"project\": project, \"message_id\": message_id})\n series.extra_links.append(\n {\n \"html\": format_html('Download mbox', mbox_url),\n \"icon\": \"download\",\n }\n )\n return render_page(\n request,\n \"series-detail.html\",\n subject=m.subject,\n stripped_subject=s.stripped_subject,\n has_other_revisions=series.has_other_revisions,\n version=s.version,\n message_id=m.message_id,\n series=series,\n is_cover_letter=False,\n is_head=False,\n project=project,\n navigate_links=nav_path,\n search=search,\n results=[],\n patches=prepare_patches(request, s),\n messages=messages,\n )\n\n\nclass ProjectLogViewer(LogView):\n def get_result(self, request, **kwargs):\n project = kwargs[\"project\"]\n obj = Project.objects.filter(name=project).first()\n if not obj:\n raise Http404(\"Project not found: \" + series)\n return obj.results.filter(name=kwargs[\"name\"]).first()\n\n\nclass SeriesLogViewer(LogView):\n def get_result(self, request, **kwargs):\n project = kwargs[\"project\"]\n po = Project.objects.filter(name=project).first()\n if not po:\n raise Http404(\"Project not found: \" + series)\n series = kwargs[\"message_id\"]\n obj = Message.objects.find_series(series, project)\n if not obj:\n raise Http404(\"Message not found: \" + series)\n return obj.results.filter(name=kwargs[\"name\"]).first()\n", "repo_name": "patchew-project/patchew", "sub_path": "www/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 13084, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 67, "dataset": "github-code", "pt": "20", "api": [{"api_name": "subprocess.check_output", "line_number": 22, "usage_type": "call"}, {"api_name": "django.conf.settings.VERSION", "line_number": 29, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 29, "usage_type": "name"}, {"api_name": "mod.dispatch_module_hook", "line_number": 30, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 31, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 38, "usage_type": "call"}, {"api_name": "mod.dispatch_module_hook", "line_number": 61, "usage_type": "call"}, {"api_name": "api.models.Message.objects.filter", "line_number": 75, "usage_type": "call"}, {"api_name": "api.models", "line_number": 75, "usage_type": "attribute"}, {"api_name": "django.db.models.OuterRef", "line_number": 76, "usage_type": "call"}, {"api_name": "django.db.models.Exists", "line_number": 78, "usage_type": "call"}, {"api_name": "api.models.Project.objects.filter", "line_number": 119, "usage_type": "call"}, {"api_name": "api.models", "line_number": 119, "usage_type": "attribute"}, {"api_name": "django.urls.reverse", "line_number": 170, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 172, "usage_type": "call"}, {"api_name": "urllib.parse.urlencode", "line_number": 197, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 197, "usage_type": "attribute"}, {"api_name": "urllib.parse.urlencode", "line_number": 199, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 199, "usage_type": "attribute"}, {"api_name": "django.db.models.F", "line_number": 213, "usage_type": "call"}, {"api_name": "django.http.Http404", "line_number": 221, "usage_type": "call"}, {"api_name": "markdown.markdown", "line_number": 254, "usage_type": "call"}, {"api_name": "api.search", "line_number": 254, "usage_type": "attribute"}, {"api_name": "api.models.Project.objects.filter", "line_number": 259, "usage_type": "call"}, {"api_name": "api.models", "line_number": 259, "usage_type": "attribute"}, {"api_name": "django.http.Http404", "line_number": 261, "usage_type": "call"}, {"api_name": "mod.dispatch_module_hook", "line_number": 268, "usage_type": "call"}, {"api_name": "api.search.SearchEngine", "line_number": 283, "usage_type": "call"}, {"api_name": "api.models.Project.objects.filter", "line_number": 296, "usage_type": "call"}, {"api_name": "api.models", "line_number": 296, "usage_type": "attribute"}, {"api_name": "django.http.Http404", "line_number": 298, "usage_type": "call"}, {"api_name": "api.models.Message.objects.series_heads", "line_number": 299, "usage_type": "call"}, {"api_name": "api.models", "line_number": 299, "usage_type": "attribute"}, {"api_name": "django.urls.reverse", "line_number": 306, "usage_type": "call"}, {"api_name": "api.models.Message.objects.find_message", "line_number": 312, "usage_type": "call"}, {"api_name": "api.models", "line_number": 312, "usage_type": "attribute"}, {"api_name": "django.http.Http404", "line_number": 314, "usage_type": "call"}, {"api_name": "django.http.Http404", "line_number": 317, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 318, "usage_type": "call"}, {"api_name": "api.models.Message.objects.find_series", "line_number": 322, "usage_type": "call"}, {"api_name": "api.models", "line_number": 322, "usage_type": "attribute"}, {"api_name": "django.http.Http404", "line_number": 324, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 333, "usage_type": "call"}, {"api_name": "django.utils.html.format_html", "line_number": 339, "usage_type": "call"}, {"api_name": "api.models.Message.objects.find_series", "line_number": 364, "usage_type": "call"}, {"api_name": "api.models", "line_number": 364, "usage_type": "attribute"}, {"api_name": "django.http.Http404", "line_number": 366, "usage_type": "call"}, {"api_name": "api.models.Message.objects.filter", "line_number": 367, "usage_type": "call"}, {"api_name": "api.models", "line_number": 367, "usage_type": "attribute"}, {"api_name": "django.http.Http404", "line_number": 371, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 380, "usage_type": "call"}, {"api_name": "django.utils.html.format_html", "line_number": 383, "usage_type": "call"}, {"api_name": "patchew.logviewer.LogView", "line_number": 407, "usage_type": "name"}, {"api_name": "api.models.Project.objects.filter", "line_number": 410, "usage_type": "call"}, {"api_name": "api.models.Project.objects", "line_number": 410, "usage_type": "attribute"}, {"api_name": "api.models.Project", "line_number": 410, "usage_type": "name"}, {"api_name": "django.http.Http404", "line_number": 412, "usage_type": "call"}, {"api_name": "patchew.logviewer.LogView", "line_number": 416, "usage_type": "name"}, {"api_name": "api.models.Project.objects.filter", "line_number": 419, "usage_type": "call"}, {"api_name": "api.models.Project.objects", "line_number": 419, "usage_type": "attribute"}, {"api_name": "api.models.Project", "line_number": 419, "usage_type": "name"}, {"api_name": "django.http.Http404", "line_number": 421, "usage_type": "call"}, {"api_name": "api.models.Message.objects.find_series", "line_number": 423, "usage_type": "call"}, {"api_name": "api.models.Message.objects", "line_number": 423, "usage_type": "attribute"}, {"api_name": "api.models.Message", "line_number": 423, "usage_type": "name"}, {"api_name": "django.http.Http404", "line_number": 425, "usage_type": "call"}]} +{"seq_id": "35246475850", "text": "__author__ = \"Johannes Köster, Julian de Ruiter\"\n__copyright__ = \"Copyright 2016, Johannes Köster and Julian de Ruiter\"\n__email__ = \"koester@jimmy.harvard.edu, julianderuiter@gmail.com\"\n__license__ = \"MIT\"\n\n\nimport tempfile\nfrom os import path\nfrom snakemake.shell import shell\nfrom snakemake_wrapper_utils.java import get_java_opts\nfrom snakemake_wrapper_utils.samtools import get_samtools_opts\n\n\n# Extract arguments.\nextra = snakemake.params.get(\"extra\", \"\")\nlog = snakemake.log_fmt_shell(stdout=False, stderr=True)\nsort = snakemake.params.get(\"sorting\", \"none\")\nsort_order = snakemake.params.get(\"sort_order\", \"coordinate\")\nsort_extra = snakemake.params.get(\"sort_extra\", \"\")\nsamtools_opts = get_samtools_opts(snakemake, param_name=\"sort_extra\")\njava_opts = get_java_opts(snakemake)\n\n\nindex = snakemake.input.idx\nif isinstance(index, str):\n index = path.splitext(snakemake.input.idx)[0]\nelse:\n index = path.splitext(snakemake.input.idx[0])[0]\n\n\n# Check inputs/arguments.\nif not isinstance(snakemake.input.reads, str) and len(snakemake.input.reads) not in {\n 1,\n 2,\n}:\n raise ValueError(\"input must have 1 (single-end) or 2 (paired-end) elements\")\n\n\nif sort_order not in {\"coordinate\", \"queryname\"}:\n raise ValueError(\"Unexpected value for sort_order ({})\".format(sort_order))\n\n\n# Determine which pipe command to use for converting to bam or sorting.\nif sort == \"none\":\n # Simply convert to bam using samtools view.\n pipe_cmd = \"samtools view {samtools_opts}\"\n\nelif sort == \"samtools\":\n # Add name flag if needed.\n if sort_order == \"queryname\":\n sort_extra += \" -n\"\n\n # Sort alignments using samtools sort.\n pipe_cmd = \"samtools sort {samtools_opts} {sort_extra} -T {tmpdir}\"\n\nelif sort == \"picard\":\n # Sort alignments using picard SortSam.\n pipe_cmd = \"picard SortSam {java_opts} {sort_extra} --INPUT /dev/stdin --TMP_DIR {tmpdir} --SORT_ORDER {sort_order} --OUTPUT {snakemake.output[0]}\"\n\nelse:\n raise ValueError(f\"Unexpected value for params.sort ({sort})\")\n\nwith tempfile.TemporaryDirectory() as tmpdir:\n shell(\n \"(bwa mem\"\n \" -t {snakemake.threads}\"\n \" {extra}\"\n \" {index}\"\n \" {snakemake.input.reads}\"\n \" | \" + pipe_cmd + \") {log}\"\n )\n", "repo_name": "snakemake/snakemake-wrappers", "sub_path": "bio/bwa/mem/wrapper.py", "file_name": "wrapper.py", "file_ext": "py", "file_size_in_byte": 2244, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 182, "dataset": "github-code", "pt": "24", "api": [{"api_name": "snakemake.shell.params.get", "line_number": 15, "usage_type": "call"}, {"api_name": "snakemake.shell.params", "line_number": 15, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 15, "usage_type": "name"}, {"api_name": "snakemake.shell.log_fmt_shell", "line_number": 16, "usage_type": "call"}, {"api_name": "snakemake.shell", "line_number": 16, "usage_type": "name"}, {"api_name": "snakemake.shell.params.get", "line_number": 17, "usage_type": "call"}, {"api_name": "snakemake.shell.params", "line_number": 17, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 17, "usage_type": "name"}, {"api_name": "snakemake.shell.params.get", "line_number": 18, "usage_type": "call"}, {"api_name": "snakemake.shell.params", "line_number": 18, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 18, "usage_type": "name"}, {"api_name": "snakemake.shell.params.get", "line_number": 19, "usage_type": "call"}, {"api_name": "snakemake.shell.params", "line_number": 19, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 19, "usage_type": "name"}, {"api_name": "snakemake_wrapper_utils.samtools.get_samtools_opts", "line_number": 20, "usage_type": "call"}, {"api_name": "snakemake.shell", "line_number": 20, "usage_type": "argument"}, {"api_name": "snakemake_wrapper_utils.java.get_java_opts", "line_number": 21, "usage_type": "call"}, {"api_name": "snakemake.shell", "line_number": 21, "usage_type": "argument"}, {"api_name": "snakemake.shell.input", "line_number": 24, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 24, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "name"}, {"api_name": "snakemake.shell.input", "line_number": 26, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 26, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "name"}, {"api_name": "snakemake.shell.input", "line_number": 28, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 28, "usage_type": "name"}, {"api_name": "snakemake.shell.input", "line_number": 32, "usage_type": "attribute"}, {"api_name": "snakemake.shell", "line_number": 32, "usage_type": "name"}, {"api_name": "tempfile.TemporaryDirectory", "line_number": 63, "usage_type": "call"}, {"api_name": "snakemake.shell.shell", "line_number": 64, "usage_type": "call"}]} +{"seq_id": "21767544995", "text": "\"\"\"\n\t쿠팡 상품 상세정보 관련 파일\n\n\t쿠팡 products_id,items_id, vendor_id 총 3개로 1건 조회후\n 관련 내용을 result_es 리스트 안에 넣어 almost_done.py(master 파일로) 이동\n \n making_es(products_id,items_id,vendor_id) \n return 값 result_es;\n result_es [0] -> 필수 고시 정보 제목 ex) 제품명, 생산자 및 소재지 등\n result_es [1] -> 필수 고시 정보 content ex) \"칠성사이다\" ,\"중국\" 등 내용\n result_es [2] -> 제품의 상세 정보 \n result_es [3] -> 배송비 정책\n \n making_kategorie(products_id,vendor_id) -> 쿠팡 카테고리 수집\n return c[5:-1]\n checking_sex(category) -> 성별 정보 카테고리 값을 보고 판별\n return sextp\n\n making_maker_nm(es) -> 제조자/생산자 찾음\n\n making_origin_nm(es) -> 제조국/원산지 찾음\n\n\t2021-06-14 kdi : 개발\n\n\"\"\"\nimport requests\nimport re\nfrom bs4 import BeautifulSoup\nimport json\nfrom setuptools.package_index import HREF\nfrom selenium import webdriver\nfrom openpyxl import load_workbook # 파일 불러오기\nfrom openpyxl import Workbook\n\n\ndef making_es(products_id,items_id,vendor_id) : \n url1 = f\"https://www.coupang.com/vp/products/{products_id}/items/{items_id}/vendoritems/{vendor_id}\"\n headers = {\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36\"}\n #print(url1)\n\n res = requests.get(url1, headers=headers)\n res.raise_for_status()\n subdict = json.loads(res.text)\n # with open(\"ex_book.lxml\", \"w\", encoding=\"utf8\") as f:\n # f.write(res.text)\n #배송\n \n delivery_fee = str(subdict['returnPolicyVo']['vendorItemDeliveryNotice']['deliveryCharge']).split('
    ')[0]\n #print(\"배송기간 : \" + str(subdict['returnPolicyVo']['vendorItemDeliveryNotice']['shippingPeriod']))\n if delivery_fee == \"무료배송\" :\n delivery_fee = 0\n else :\n delivery_fee = delivery_fee.split(\"원\")[0]\n delivery_fee = delivery_fee.replace(\",\",\"\")\n \n #essentials(필수 표기 정보)\n #title\n es = list()\n for b in subdict ['essentials']:\n es.append(b['title'])\n\n #content\n es_con = list()\n for b in subdict ['essentials']:\n es_con.append(b['description'])\n #print(es)\n\n #details\n #es_detail = making_detials(subdict)\n es_detail = list()\n set_div=\"\"\n saving_div = \"\"\n a = \"
    \"\n if len(subdict['details']) == 1 :\n if subdict['details'][0]['vendorItemContentDescriptions'][0]['detailType'] == 'IMAGE':\n set_div1 =\" \"+\"
    \"+\"\\n\"+\" \"\n for some in subdict['details'][0]['vendorItemContentDescriptions'] :\n set_div2 =\"
    \"+\"\\n\"+\" \"\n img = \"\"+\"\\\"\\\"\"+\"\"+\"\\n\"+\" \"+\"
    \"+\"\\n\"+\" \"+\"
    \" +\"\\n\"\n set_div = set_div1+ set_div2 + img + onerror + width\n #print(a)\n # print(saving_div)\n else :\n set_div1 =\" \"+\"
    \"+\"\\n\"+\" \"\n for some in subdict['details'][0]['vendorItemContentDescriptions'] :\n set_div2 =\"
    \"+\"\\n\"+\" \"\n content = f\"{some['content']}\"+\"\\n\"+\" \"+\"
    \"+\"\\n\"+\" \"+\"
    \" + \"\\n\"\n set_div = set_div1+ set_div2 + content\n\n saving_div += set_div \n a = a + \"\\n\" + saving_div +\" \" +\"\\n\"+\" \"+\"
    \"\n else :\n for c in subdict ['details']:\n if c['vendorItemContentDescriptions'][0]['detailType'] == 'IMAGE':\n set_div1 =\" \"+\"
    \"+\"\\n\"+\" \"\n set_div2 =\"
    \"+\"\\n\"+\" \"\n img = \"\"+\"\\\"\\\"\"+\"\"+\"\\n\"+\" \"+\"
    \"+\"\\n\"+\" \"+\"
    \" +\"\\n\"\n set_div = set_div1+ set_div2 + img + onerror + width\n else :\n set_div1 =\" \"+\"
    \"+\"\\n\"+\" \"\n set_div2 =\"
    \"+\"\\n\"+\" \"\n content = f\"{c['vendorItemContentDescriptions'][0]['content']}\"+\"\\n\"+\" \"+\"
    \"+\"\\n\"+\" \"+\"
    \" + \"\\n\"\n set_div = set_div1+ set_div2 + content\n\n saving_div += set_div \n #print(a)\n # print(saving_div)\n a = a + \"\\n\" + saving_div +\" \"+\" \"+\"\"\n #print(a)\n es_detail.append(a)\n #print(es_con)\n result_es = [es,es_con,es_detail,delivery_fee]\n return result_es\n\n\n#쿠팡 카테고리 수집\ndef making_kategorie(products_id,vendor_id) : \n url2 = f\"https://www.coupang.com/vp/products/{products_id}/breadcrumb-gnbmenu?&invalidProduct=false&invalidUnknownProduct=false&vendorItemId={vendor_id}&_=1621305025902\"\n headers = {\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36\"}\n res = requests.get(url2, headers=headers)\n res.raise_for_status()\n soup = BeautifulSoup(res.text, \"lxml\")\n Kategorie= soup.find_all(\"a\", attrs={\"class\":\"breadcrumb-link\"})# 카테고리\n i=0\n for Kat in Kategorie:\n Kategorie[i] = Kat.get_text().strip()\n i+=1\n c=\"\"\n for k in Kategorie:\n c=c+k+\">\"\n return c[5:-1]\n\n#성별 판별 \ndef checking_sex(category) :\n sex_tp = '해당없음'\n if re.search(r'여성.+?',category, re.S) :\n sex_tp = '여'\n elif re.search(r'여아.+?',category, re.S) :\n sex_tp = '여'\n elif re.search(r'남성.+?',category, re.S) :\n sex_tp = '남'\n elif re.search(r'남아.+?',category, re.S) :\n sex_tp = '남'\n else :\n sex_tp = '해당없음'\n\n return sex_tp\n\n#제조사/생산자 판별\n\ndef making_maker_nm(es) :\n maker_nm = \"\"\n for i in es[0]:\n #정규식으로 이름 케이스 들이 다양함\n if re.search(r'제조자.+?',i,re.S) :\n maker_nm = es[1][es[0].index(i)]\n elif re.search(r'생산자.+?',i,re.S):\n maker_nm = es[1][es[0].index(i)]\n elif re.search(r'제조업소.+?',i,re.S):\n maker_nm = es[1][es[0].index(i)]\n elif re.search(r'화장품제조업자 및.+?',i,re.S):\n maker_nm = es[1][es[0].index(i)]\n return maker_nm\n\n#제조국/원산지 판별\n\ndef making_origin_nm(es) : \n origin_nm = \"\"\n #print(es[0])\n for i in es[0]:\n if re.search(r'제조국',i,re.S) :\n origin_nm = es[1][es[0].index(i)]\n elif re.search(r'원산.+?',i,re.S):\n origin_nm = es[1][es[0].index(i)]\n \n #print(\"원산지 : \" + origin_nm)\n if re.search(r'국.+?',origin_nm,re.S) :\n origin_nm = '국산'\n elif re.search(r'대한.+?',origin_nm,re.S) :\n origin_nm = '국산'\n elif re.search(r'한.+?',origin_nm,re.S) :\n origin_nm = '국산'\n else :\n origin_nm = '기타'\n\n\n return origin_nm\n", "repo_name": "diakes/coupang_crawler_python", "sub_path": "Shopling_product_registration/making_essential.py", "file_name": "making_essential.py", "file_ext": "py", "file_size_in_byte": 8309, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "requests.get", "line_number": 41, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 43, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 124, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 126, "usage_type": "call"}, {"api_name": "re.search", "line_number": 140, "usage_type": "call"}, {"api_name": "re.S", "line_number": 140, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 142, "usage_type": "call"}, {"api_name": "re.S", "line_number": 142, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 144, "usage_type": "call"}, {"api_name": "re.S", "line_number": 144, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 146, "usage_type": "call"}, {"api_name": "re.S", "line_number": 146, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 159, "usage_type": "call"}, {"api_name": "re.S", "line_number": 159, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 161, "usage_type": "call"}, {"api_name": "re.S", "line_number": 161, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 163, "usage_type": "call"}, {"api_name": "re.S", "line_number": 163, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 165, "usage_type": "call"}, {"api_name": "re.S", "line_number": 165, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 175, "usage_type": "call"}, {"api_name": "re.S", "line_number": 175, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 177, "usage_type": "call"}, {"api_name": "re.S", "line_number": 177, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 181, "usage_type": "call"}, {"api_name": "re.S", "line_number": 181, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 183, "usage_type": "call"}, {"api_name": "re.S", "line_number": 183, "usage_type": "attribute"}, {"api_name": "re.search", "line_number": 185, "usage_type": "call"}, {"api_name": "re.S", "line_number": 185, "usage_type": "attribute"}]} +{"seq_id": "25070666015", "text": "#!/usr/bin/env python3\n\n\"\"\"Test FD device support.\"\"\"\n\nimport array\nimport socket\nimport tempfile\nimport threading\nimport time\n\nfrom testlib import check\nfrom testlib.log import log\nfrom testlib.test import Test\nfrom testlib.proc import Script\n\nJUNK_FRAME = b\"\\xFF\" * 80\n\n\ndef start_fd_server(unix: socket.socket, payload: bytes, file_desc: int) -> None:\n \"\"\"Start UNIX socket server and then the FD to the first connected client.\"\"\"\n\n def send_fd() -> None:\n conn, _ = unix.accept()\n with conn:\n log.info(\"accepted connection %s\", conn)\n ancillary = array.array(\"i\", [file_desc])\n conn.sendmsg([payload], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, ancillary)])\n\n threading.Thread(target=send_fd).start()\n\n\ndef test_device_fd(ctx: Test) -> None:\n \"\"\"Test some FD device error conditions.\"\"\"\n\n foo = ctx.node(init=\"set DeviceType fd\")\n\n log.info(\"test with empty Device\")\n _, err = foo.cmd(\"start\", code=1)\n check.is_in(\"Could not read device\", err)\n\n log.info(\"test with too long UNIX socket path\")\n device = \"x\" * 110\n _, err = foo.cmd(\"start\", \"-o\", f\"Device={device}\", code=1)\n check.is_in(\"Unix socket path too long\", err)\n\n foo.cmd(\"set\", \"Device\", \"/dev/null\")\n\n log.info(\"check that Mode=switch fails\")\n _, err = foo.cmd(\"start\", \"-o\", \"Mode=switch\", code=1)\n check.is_in(\"Switch mode not supported\", err)\n\n log.info(\"test with incorrect Device\")\n _, err = foo.cmd(\"start\", code=1)\n check.is_in(\"Receiving fd from Unix socket\", err)\n check.is_in(\"Could not connect to Unix socket\", err)\n\n log.info(\"test with invalid FD\")\n _, err = foo.cmd(\"start\", \"-o\", \"Device=-1\", code=1)\n check.is_in(\"Could not open\", err)\n\n log.info(\"create a UNIX socket to transfer FD\")\n unix = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n unix_path = tempfile.mktemp()\n unix.bind(unix_path)\n unix.listen(1)\n\n foo.cmd(\"set\", \"Device\", unix_path)\n myself, him = socket.socketpair(socket.AF_UNIX)\n\n log.info(\"start with empty data\")\n start_fd_server(unix, b\"\", him.fileno())\n _, err = foo.cmd(\"start\", \"-o\", f\"Device={unix_path}\", code=1)\n check.is_in(\"Could not read from unix socket\", err)\n\n foo_log = foo.sub(\"log\")\n foo.add_script(Script.TINC_UP)\n\n log.info(\"start with correct amount of data\")\n start_fd_server(unix, b\" \", him.fileno())\n\n log.info(\"wait for tincd to connect\")\n _, err = foo.cmd(\"start\", \"-o\", f\"Device={unix_path}\", \"--logfile\", foo_log, \"-d10\")\n foo[Script.TINC_UP].wait()\n check.is_in(\"adapter set up\", err)\n\n log.info(\"send junk data and make sure tincd receives it\")\n for _ in range(10):\n myself.send(JUNK_FRAME)\n time.sleep(0.1)\n\n foo.add_script(Script.TINC_DOWN)\n foo.cmd(\"stop\")\n foo[Script.TINC_DOWN].wait()\n\n check.in_file(foo_log, \"Unknown IP version while reading packet from fd/\")\n\n\nwith Test(\"test FD device\") as context:\n test_device_fd(context)\n", "repo_name": "gsliepen/tinc", "sub_path": "test/integration/device_fd.py", "file_name": "device_fd.py", "file_ext": "py", "file_size_in_byte": 2973, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1787, "dataset": "github-code", "pt": "24", "api": [{"api_name": "socket.socket", "line_number": 19, "usage_type": "attribute"}, {"api_name": "testlib.log.log.info", "line_number": 25, "usage_type": "call"}, {"api_name": "testlib.log.log", "line_number": 25, "usage_type": "name"}, {"api_name": "array.array", "line_number": 26, "usage_type": "call"}, {"api_name": "socket.SOL_SOCKET", "line_number": 27, "usage_type": "attribute"}, {"api_name": "socket.SCM_RIGHTS", "line_number": 27, "usage_type": "attribute"}, {"api_name": "threading.Thread", "line_number": 29, "usage_type": "call"}, {"api_name": "testlib.test.Test", "line_number": 32, "usage_type": "name"}, {"api_name": "testlib.log.log.info", "line_number": 37, "usage_type": "call"}, {"api_name": "testlib.log.log", "line_number": 37, "usage_type": "name"}, {"api_name": "testlib.check.is_in", "line_number": 39, "usage_type": "call"}, {"api_name": "testlib.check", "line_number": 39, "usage_type": "name"}, {"api_name": "testlib.log.log.info", "line_number": 41, "usage_type": "call"}, {"api_name": "testlib.log.log", "line_number": 41, "usage_type": "name"}, {"api_name": "testlib.check.is_in", "line_number": 44, "usage_type": "call"}, {"api_name": "testlib.check", "line_number": 44, "usage_type": "name"}, {"api_name": "testlib.log.log.info", "line_number": 48, "usage_type": "call"}, {"api_name": "testlib.log.log", "line_number": 48, "usage_type": "name"}, {"api_name": "testlib.check.is_in", "line_number": 50, "usage_type": "call"}, {"api_name": "testlib.check", "line_number": 50, "usage_type": "name"}, {"api_name": "testlib.log.log.info", "line_number": 52, "usage_type": "call"}, {"api_name": "testlib.log.log", "line_number": 52, "usage_type": "name"}, {"api_name": "testlib.check.is_in", "line_number": 54, "usage_type": "call"}, {"api_name": "testlib.check", "line_number": 54, "usage_type": "name"}, {"api_name": "testlib.check.is_in", "line_number": 55, "usage_type": "call"}, {"api_name": "testlib.check", "line_number": 55, "usage_type": "name"}, {"api_name": "testlib.log.log.info", "line_number": 57, "usage_type": "call"}, {"api_name": "testlib.log.log", "line_number": 57, "usage_type": "name"}, {"api_name": "testlib.check.is_in", "line_number": 59, "usage_type": "call"}, {"api_name": "testlib.check", "line_number": 59, "usage_type": "name"}, {"api_name": "testlib.log.log.info", "line_number": 61, "usage_type": "call"}, {"api_name": "testlib.log.log", "line_number": 61, "usage_type": "name"}, {"api_name": "socket.socket", "line_number": 62, "usage_type": "call"}, {"api_name": "socket.AF_UNIX", "line_number": 62, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 62, "usage_type": "attribute"}, {"api_name": "tempfile.mktemp", "line_number": 63, "usage_type": "call"}, {"api_name": "socket.socketpair", "line_number": 68, "usage_type": "call"}, {"api_name": "socket.AF_UNIX", "line_number": 68, "usage_type": "attribute"}, {"api_name": "testlib.log.log.info", "line_number": 70, "usage_type": "call"}, {"api_name": "testlib.log.log", "line_number": 70, "usage_type": "name"}, {"api_name": "testlib.check.is_in", "line_number": 73, "usage_type": "call"}, {"api_name": "testlib.check", "line_number": 73, "usage_type": "name"}, {"api_name": "testlib.proc.Script.TINC_UP", "line_number": 76, "usage_type": "attribute"}, {"api_name": "testlib.proc.Script", "line_number": 76, "usage_type": "name"}, {"api_name": "testlib.log.log.info", "line_number": 78, "usage_type": "call"}, {"api_name": "testlib.log.log", "line_number": 78, "usage_type": "name"}, {"api_name": "testlib.log.log.info", "line_number": 81, "usage_type": "call"}, {"api_name": "testlib.log.log", "line_number": 81, "usage_type": "name"}, {"api_name": "testlib.proc.Script.TINC_UP", "line_number": 83, "usage_type": "attribute"}, {"api_name": "testlib.proc.Script", "line_number": 83, "usage_type": "name"}, {"api_name": "testlib.check.is_in", "line_number": 84, "usage_type": "call"}, {"api_name": "testlib.check", "line_number": 84, "usage_type": "name"}, {"api_name": "testlib.log.log.info", "line_number": 86, "usage_type": "call"}, {"api_name": "testlib.log.log", "line_number": 86, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 89, "usage_type": "call"}, {"api_name": "testlib.proc.Script.TINC_DOWN", "line_number": 91, "usage_type": "attribute"}, {"api_name": "testlib.proc.Script", "line_number": 91, "usage_type": "name"}, {"api_name": "testlib.proc.Script.TINC_DOWN", "line_number": 93, "usage_type": "attribute"}, {"api_name": "testlib.proc.Script", "line_number": 93, "usage_type": "name"}, {"api_name": "testlib.check.in_file", "line_number": 95, "usage_type": "call"}, {"api_name": "testlib.check", "line_number": 95, "usage_type": "name"}, {"api_name": "testlib.test.Test", "line_number": 98, "usage_type": "call"}]} +{"seq_id": "32876330396", "text": "import sys, os, glob, re\nimport pandas as pd\npd.options.mode.chained_assignment = None\nimport argparse\nfrom Bio import SeqIO\nfrom datetime import datetime\nfrom utils.generic_functions import *\n\n'''\n\nusage example\npython3 ~/tesis_code/miRNAs_utils/summary_pita_results.py -d pita_results_15-jan -r /home/lchapado/bio_programs/PITA/3UTRhuman.fa -p aligment -e -10 -m 2\n\nath_miR165a_5p_pita_results.tab\nrequires to install xlsxwriter\n'''\npita_result_estension = '_results.tab'\ndef check_arg (args=None) :\n '''\n The function is used for parsing the input parameters form the command line using the standard python package argparse.\n The package itself is handling the validation and the return errors messages\n Input:\n args # Contains the arguments from the command line\n Return:\n parser.parse_args() # The variable contains the valid parameters\n '''\n parser = argparse.ArgumentParser(prog = 'summary_pita_results.py',\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description= 'part of miRNA set of tools')\n\n parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.0.1')\n\n #parser.add_argument('-g', '--genefile', required = False , help = 'file having the list of genes')\n\n parser.add_argument('-d', '--dir', required = True, help = 'directory with the PITA result files')\n\n parser.add_argument('-r', '--reference', required = True, help ='3UTR genome reference file')\n\n #parser.add_argument('-m', '--mirnas', required = True, help='directory with the miRNAs fasta files')\n\n parser.add_argument('-p', '--prefix', required = True, help='prefix file for output results')\n\n parser.add_argument('-e', '--score', required = True, help = 'filter by maximum energy score')\n\n parser.add_argument('-m','--min', required = True, help = 'minimun number of target genes')\n\n return parser.parse_args()\n\ndef convert_pita_dict_to_panda (target_genes_dict):\n '''\n Description:\n The function get the dicitonnary and conver it to panda dataframe.\n Input:\n target_genes_dict # directory to convert\n Return:\n target_genes_dict\n Gene Annotation Start End microRNA Seed ddG\n UTR\tmicroRNA\tStart\tEnd\tSeed\tLoop\tdGduplex\tdG5\tdG3\tdG0\tdG1\tdGopen\tddG\n ENST00000310015|SP3\tath_miR165a-5p\t6872\t6864\t8:0:1\t0\t-21.1\t-7.1\t-14\t-29.49\t-27.61\t-1.87\t-19.22\n ENST00000320285|AGPAT4\tath_miR165a-5p\t4781\t4773\t8:0:1\t0\t-24.52\t-9.3\t-15.22\t-41.37\t-35.52\t-5.85\t-18.66\n '''\n heading = {'Gene':[], 'Annotation':[], 'Start':[], 'End':[], 'microRNA':[], 'Seed':[], 'ddG':[]}\n converted_df = pd.DataFrame(heading)\n for gene, utrs in target_genes_dict.items():\n for utr in utrs.keys():\n for index in range(len(utrs[utr]['data'])):\n start, end = utrs[utr]['data'][index]['Start_End'].split('_')\n new_row = {'Gene':gene, 'Annotation':utr, 'Start':start, 'End':end, 'microRNA':utrs[utr]['data'][index]['microRNA'],\n 'Seed':utrs[utr]['data'][index]['Seed'], 'ddG':utrs[utr]['data'][index]['ddG']}\n converted_df = converted_df.append(new_row, ignore_index = True)\n\n return converted_df\n\n\n\ndef fetch_target_genes_data(files_to_process, min_energy):\n '''\n Description:\n The function get the target genes form the PITA output files and reduce the\n results whith the ones that have less energy value as indicated in min_energy\n and it stores in target_genes_dict\n Input:\n files_to_process # output PITA directory\n min_energy # minimun value to filter the target genes\n Return:\n target_genes_dict\n UTR\tmicroRNA\tStart\tEnd\tSeed\tLoop\tdGduplex\tdG5\tdG3\tdG0\tdG1\tdGopen\tddG\n ENST00000310015|SP3\tath_miR165a-5p\t6872\t6864\t8:0:1\t0\t-21.1\t-7.1\t-14\t-29.49\t-27.61\t-1.87\t-19.22\n ENST00000320285|AGPAT4\tath_miR165a-5p\t4781\t4773\t8:0:1\t0\t-24.52\t-9.3\t-15.22\t-41.37\t-35.52\t-5.85\t-18.66\n '''\n target_genes_dict = {}\n gene_start_end_dict = {}\n\n for file in files_to_process:\n panda_df = pd.read_csv(file, sep ='\\t', header=0)\n selected_df = panda_df[panda_df['ddG'] <= min_energy]\n\n selected_df[['UTR','Gene']] = selected_df['UTR'].str.split('|',expand = True)\n #selected_df[['UTR','Gene']] = selected_df.loc[:,['UTR']].str.split('|',expand = True)\n selected_df['Start_End'] = selected_df['Start'].apply(str).str.cat(selected_df['End'].apply(str),sep = '_')\n for index, row in selected_df.iterrows():\n if not row['Gene'] in target_genes_dict:\n target_genes_dict[row['Gene']] = {}\n gene_start_end_dict[row['Gene']] = []\n\n if row['Start_End'] not in gene_start_end_dict[row['Gene']]:\n if not row['UTR'] in target_genes_dict[row['Gene']] :\n target_genes_dict[row['Gene']][row['UTR']] ={}\n target_genes_dict[row['Gene']][row['UTR']]['positions']= []\n target_genes_dict[row['Gene']][row['UTR']]['data'] = []\n data = {}\n data['microRNA'] = row['microRNA']\n data['Start_End'] = row['Start_End']\n data['Seed'] = row['Seed']\n data['ddG'] = row['ddG']\n\n target_genes_dict[row['Gene']][row['UTR']]['data'].append(data)\n target_genes_dict[row['Gene']][row['UTR']]['positions'].append(row['Start_End'])\n gene_start_end_dict[row['Gene']].append(row['Start_End'])\n else:\n # find the existing value\n found = False\n for utr in target_genes_dict[row['Gene']].keys():\n if not row['Start_End'] in target_genes_dict[row['Gene']][utr]['positions']:\n continue\n\n for index_data in range(len(target_genes_dict[row['Gene']][utr])):\n if not row['Start_End'] == target_genes_dict[row['Gene']][utr]['data'][index_data]['Start_End'] and row['microRNA'] == target_genes_dict[row['Gene']][utr]['data'][index_data]['microRNA'] :\n continue\n found = True\n if row['ddG'] < target_genes_dict[row['Gene']][utr]['data'][index_data]['ddG']:\n target_genes_dict[row['Gene']][utr]['data'][index_data]['ddG'] = row['ddG']\n target_genes_dict[row['Gene']][utr]['data'][index_data]['Seed'] = row['Seed']\n break\n if not found:\n data = {}\n data['microRNA'] = row['microRNA']\n data['Start_End'] = row['Start_End']\n data['Seed'] = row['Seed']\n data['ddG'] = row['ddG']\n target_genes_dict[row['Gene']][utr]['data'].append(data)\n break\n\n return target_genes_dict\n\ndef filter_min_target_genes(target_genes_dict, min_number_target_gene):\n '''\n Description:\n The function filter the target genes, returning a dataframe with only the ones that the matches\n is equal or bigger to min_number_target_gene\n Input:\n files_to_process # output PITA directory\n min_energy # minimun value to filter the target genes\n Return:\n converted_df\n '''\n converted_df ={}\n heading = {'Gene':[], 'Annotation':[],'microRNA':[], 'Number_of_sites':pd.Series([], dtype='int'), 'Start_End':[]}\n converted_df = pd.DataFrame(heading)\n for gene, utrs in target_genes_dict.items():\n\n number_found = 0\n if len(utrs) >= min_number_target_gene:\n number_found = len(utrs)\n else:\n for utr in utrs.keys():\n number_found += len(utrs[utr]['positions'])\n if number_found >= min_number_target_gene:\n for utr in utrs.keys():\n n_sites = len(utrs[utr]['positions'])\n new_row = {'Gene':gene, 'Annotation':utr, 'microRNA':utrs[utr]['data'][0]['microRNA'], 'Number_of_sites': n_sites, 'Start_End':','.join(utrs[utr]['positions'])}\n converted_df = converted_df.append(new_row, ignore_index = True)\n\n return converted_df\n\nif __name__ == '__main__' :\n if len(sys.argv) == 1:\n print('Usage summary_pita_results.py[arguments]')\n print('Type summary_pita_results.py --help for more information')\n exit(2)\n arguments = check_arg(sys.argv[1:])\n start_time = datetime.now()\n if not file_exists(arguments.reference):\n print ('3UTR reference genome does not exists\\n')\n exit(2)\n if not directory_exists(arguments.dir):\n print ('directory with output results form PITA does not exists')\n exit(2)\n try:\n score = float(arguments.score)\n except:\n print('score must be a number')\n exit(2)\n try:\n min_number_target_gene = int(arguments.min)\n except:\n print('minimun number of target genes must be an integer')\n exit(2)\n\n filter_name = '_results.tab'\n out_file_name = 'prueba_multi.xlsx'\n excel_file = pd.ExcelWriter(out_file_name, engine = 'xlsxwriter')\n filter_files = os.path.join(arguments.dir,'*' + filter_name)\n files_to_process =glob.glob(filter_files)\n for file in files_to_process:\n print('Processing ',file)\n target_genes_dict = fetch_target_genes_data([file], score)\n filter_min_target_df = filter_min_target_genes(target_genes_dict, min_number_target_gene)\n gene_target_df = convert_pita_dict_to_panda(target_genes_dict)\n sheet_name = os.path.basename(file).replace(filter_name,'')\n save_dataframe_to_excel_multiple_sheet(gene_target_df,excel_file,sheet_name)\n save_dataframe_to_excel_multiple_sheet(filter_min_target_df,excel_file,'min_target_' + sheet_name)\n # add all miRNAs files\n if len(files_to_process) >1:\n print('Processing all miRNAs')\n target_genes_dict = fetch_target_genes_data(files_to_process, score)\n gene_target_df = convert_pita_dict_to_panda(target_genes_dict)\n save_dataframe_to_excel_multiple_sheet(gene_target_df,excel_file,'all_miRNAs')\n excel_file.save()\n", "repo_name": "luissian/microbiomeProject", "sub_path": "summary_pita_results.py", "file_name": "summary_pita_results.py", "file_ext": "py", "file_size_in_byte": 10286, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pandas.options", "line_number": 3, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 27, "usage_type": "call"}, {"api_name": "argparse.RawDescriptionHelpFormatter", "line_number": 28, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 63, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 95, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 158, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 159, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 177, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 181, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 182, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 182, "usage_type": "name"}, {"api_name": "pandas.ExcelWriter", "line_number": 202, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 203, "usage_type": "call"}, {"api_name": "os.path", "line_number": 203, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 204, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 210, "usage_type": "call"}, {"api_name": "os.path", "line_number": 210, "usage_type": "attribute"}]} +{"seq_id": "16252552809", "text": "import pygame\nfrom monster import Monster\nimport config\nimport text\n\nclass combat():\n\n def __init__(self, char, mon, console):\n self.char = char\n self.mon = mon\n self.console = console\n console.push_text(text.monster[self.mon.name])\n\n def do_combat_turn(self, cmd):\n if self.combat_turn(cmd):\n endcombat = pygame.event.Event(config.ENDCOMBAT)\n pygame.event.post(endcombat)\n elif not self.char.is_alive():\n gameover = pygame.event.Event(config.GAMEOVER)\n pygame.event.post(gameover)\n elif not self.mon.is_alive():\n string = \"You defeated the \" + self.mon.name + \"!\"\n self.console.push_text(string)\n win = pygame.event.Event(config.WIN)\n pygame.event.post(win)\n else:\n if self.char.remaining_actions == 0:\n while not self.mon.remaining_actions == 0:\n self.combat_turn(0)\n\n newturn = pygame.event.Event(config.NEWTURN)\n pygame.event.post(newturn)\n self.mon.update()\n\n\n def combat_turn(self, cmd):\n if self.char.remaining_actions > 0 and cmd > 0:\n char_damage = self.do_action(cmd, self.char)\n else:\n char_damage = 0\n if self.mon.remaining_actions > 0:\n mon_damage = self.do_action(self.mon.get_action(), self.mon)\n else:\n mon_damage = 0\n\n if char_damage == 1:\n if self.char.flee():\n self.console.push_text(\"You flee from the fight!\")\n return True\n elif char_damage < 0 and mon_damage > 1:\n string = \"The \" + self.mon.name + \" hits you for \" + str(mon_damage-2 + char_damage) + \" damage.\"\n self.console.push_text(string)\n self.char.take_damage(mon_damage-2 + char_damage, self.mon.get_venom())\n elif char_damage < 0 and mon_damage < 0:\n string = \"You lock eyes with the \" + self.mon.name + \". Neiher of you makes a move.\"\n self.console.push_text(string)\n elif char_damage == 0:\n if mon_damage == 1:\n string = \"You stand still, watching as the \" + self.mon.name + \" saunters off.\"\n self.console.push_text(string)\n return True\n elif mon_damage == 0:\n string = \"Both you and the \" + self.mon.name + \" look strangly at each other's laughable attempt to escape.\"\n self.console.push_text(string)\n elif mon_damage > 0:\n string = \"The \" + self.mon.name + \" looks on as you stumble around trying to escape.\"\n self.console.push_text(string)\n else:\n string = \"While you try to escape, the \" + self.mon.name + \" hits you for \" + str(mon_damage-2) + \" damage.\"\n venom = self.mon.get_venom()\n self.char.take_damage(mon_damage-2, venom)\n if venom > 0:\n self.console.push_text(\"You've been poisoned!\")\n elif char_damage > 1:\n if mon_damage == 1:\n if self.mon.flee():\n string = \"The \" + self.mon.name + \" fled!\"\n self.console.push_text(string)\n return True\n elif mon_damage < 0:\n a = char_damage-2 + self.char.weapon.dmg + mon_damage\n if a < 0:\n a = 0\n string = \"You hit the \" + self.mon.name + \" for \" + str(a) + \" damage.\"\n self.console.push_text(string)\n self.mon.take_damage(a)\n elif mon_damage == 0:\n string = \"You hit the \" + self.mon.name + \" for \" + str(char_damage-2 + self.char.weapon.dmg) + \" damage, while it tries to run away. \"\n self.console.push_text(string)\n self.mon.take_damage(char_damage-2 + self.char.weapon.dmg)\n else:\n string = \"You hit the \" + self.mon.name + \" for \" + str(char_damage-2 + self.char.weapon.dmg) + \" damage.\"\n self.console.push_text(string)\n self.mon.take_damage(char_damage-2 + self.char.weapon.dmg)\n string = \"The \" + self.mon.name + \" hits you for \" + str(mon_damage-2) + \" damage.\"\n self.console.push_text(string)\n venom = self.mon.get_venom()\n self.char.take_damage(mon_damage-2, venom)\n if venom > 0:\n self.console.push_text(\"You've been poisoned!\")\n\n return False\n\n def do_action(self, action, actor):\n if action == 1:\n return actor.deal_damage() + 2\n elif action == 2:\n return actor.defend()\n elif action == 3:\n return actor.flee()\n\n", "repo_name": "Larsera/sonen-game-jam-h15", "sub_path": "combat_handler.py", "file_name": "combat_handler.py", "file_ext": "py", "file_size_in_byte": 4793, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "text.monster", "line_number": 12, "usage_type": "attribute"}, {"api_name": "pygame.event.Event", "line_number": 16, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 16, "usage_type": "attribute"}, {"api_name": "config.ENDCOMBAT", "line_number": 16, "usage_type": "attribute"}, {"api_name": "pygame.event.post", "line_number": 17, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 17, "usage_type": "attribute"}, {"api_name": "pygame.event.Event", "line_number": 19, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 19, "usage_type": "attribute"}, {"api_name": "config.GAMEOVER", "line_number": 19, "usage_type": "attribute"}, {"api_name": "pygame.event.post", "line_number": 20, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 20, "usage_type": "attribute"}, {"api_name": "pygame.event.Event", "line_number": 24, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 24, "usage_type": "attribute"}, {"api_name": "config.WIN", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pygame.event.post", "line_number": 25, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 25, "usage_type": "attribute"}, {"api_name": "pygame.event.Event", "line_number": 31, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 31, "usage_type": "attribute"}, {"api_name": "config.NEWTURN", "line_number": 31, "usage_type": "attribute"}, {"api_name": "pygame.event.post", "line_number": 32, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 32, "usage_type": "attribute"}]} +{"seq_id": "37980441305", "text": "import torch\nfrom torch import nn\nimport numpy as np\n\nimport random\n\n\nclass QFunction(nn.Module):\n def __init__(self, state_dim, action_n):\n super().__init__()\n self.state_dim = state_dim\n self.action_n = action_n\n\n self.network = nn.Sequential(\n nn.Linear(state_dim, 64),\n nn.ReLU(),\n nn.Linear(64, 64),\n nn.ReLU(),\n nn.Linear(64, action_n),\n )\n\n def forward(self, states):\n return self.network(states)\n\n\nclass DQN(nn.Module):\n def __init__(\n self,\n state_dim,\n action_dim,\n gamma=0.99,\n lr=1e-3,\n batch_size=64,\n epsilon_decrease=0.02,\n epsilon_min=0.01,\n ):\n super().__init__()\n self.state_dim = state_dim\n self.action_dim = action_dim\n self.q_function = QFunction(self.state_dim, self.action_dim)\n self.gamma = gamma\n self.batch_size = batch_size\n self.epsilon = 1\n self.epsilon_decrease = epsilon_decrease\n self.epsilon_min = epsilon_min\n self.memory = []\n self.optimzaer = torch.optim.Adam(self.q_function.parameters(), lr=lr)\n\n @torch.no_grad()\n def get_action(self, state):\n q_values = self.q_function(torch.FloatTensor(state))\n argmax_action = torch.argmax(q_values)\n probs = self.epsilon * np.ones(self.action_dim) / self.action_dim\n probs[argmax_action] += 1 - self.epsilon\n action = np.random.choice(np.arange(self.action_dim), p=probs)\n return action\n\n @torch.no_grad()\n def get_max_q_values(self, next_states):\n return torch.max(self.q_function(next_states), dim=1).values\n\n def fit(self, state, action, reward, done, next_state):\n self.memory.append([state, action, reward, int(done), next_state])\n\n if len(self.memory) < self.batch_size:\n return\n\n batch = random.sample(self.memory, self.batch_size)\n states, actions, rewards, dones, next_states = map(\n torch.tensor, list(zip(*batch))\n )\n\n max_q_values = self.get_max_q_values(next_states)\n targets = rewards + self.gamma * (1 - dones) * max_q_values\n q_values = self.q_function(states)[torch.arange(self.batch_size), actions]\n\n loss = torch.mean((q_values - targets.detach()) ** 2)\n loss.backward()\n self.optimzaer.step()\n self.optimzaer.zero_grad()\n\n self.epsilon -= self.epsilon_decrease\n self.epsilon = max(self.epsilon_min, self.epsilon)\n\n\nclass TargetDQN(DQN):\n def __init__(\n self,\n state_dim,\n action_dim,\n gamma=0.99,\n lr=1e-3,\n batch_size=64,\n target_update=10,\n epsilon_decrease=0.01,\n epilon_min=0.01,\n ):\n super().__init__(\n state_dim, action_dim, gamma, lr, batch_size, epsilon_decrease, epilon_min\n )\n self.target_q_function = QFunction(state_dim, action_dim)\n\n state_dict = self.q_function.network.state_dict()\n self.target_q_function.network.load_state_dict(state_dict)\n\n for p in self.target_q_function.network.parameters():\n p.requires_grad = False\n\n self.target_update = target_update\n self.fit_calls = 0\n \n def update_target(self):\n pass\n\n @torch.no_grad()\n def get_max_q_values(self, next_states):\n return torch.max(self.target_q_function(next_states), dim=1).values\n\n def fit(self, state, action, reward, done, next_state):\n super().fit(state, action, reward, done, next_state)\n\n self.fit_calls += 1\n if self.fit_calls >= self.target_update:\n self.update_target()\n self.fit_calls = 0\n\n\nclass HardTargetDQN(TargetDQN):\n def update_target(self):\n state_dict = self.q_function.network.state_dict()\n self.target_q_function.network.load_state_dict(state_dict)\n\n\nclass SoftTargetDQN(TargetDQN):\n def __init__(\n self,\n state_dim,\n action_dim,\n gamma=0.99,\n lr=1e-3,\n tau=0.1,\n batch_size=64,\n epsilon_decrease=0.01,\n epilon_min=0.01,\n ):\n super().__init__(\n state_dim,\n action_dim,\n gamma,\n lr,\n batch_size,\n 1,\n epsilon_decrease,\n epilon_min,\n )\n self.tau = tau\n\n def update_target(self):\n # theta' = tau * theta + (1 - tau) * theta'\n target_dict = self.target_q_function.state_dict()\n for name, param in self.q_function.named_parameters():\n target_dict[name] = self.tau * param.data + (1 - self.tau) * target_dict[name]\n self.target_q_function.load_state_dict(target_dict)\n\n\nclass DoubleDQN(SoftTargetDQN):\n def get_max_q_values(self, next_states):\n next_states_q = self.q_function(next_states)\n best_actions = torch.argmax(next_states_q, axis=1)\n\n max_q_values = self.target_q_function(next_states)[\n np.arange(0, self.batch_size), best_actions\n ]\n\n return max_q_values\n", "repo_name": "Cattharine/product_owner_rl", "sub_path": "algorithms/deep_q_networks.py", "file_name": "deep_q_networks.py", "file_ext": "py", "file_size_in_byte": 5087, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "torch.nn.Module", "line_number": 8, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 8, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 14, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 14, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 15, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 15, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 16, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 17, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 18, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 18, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 26, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 26, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 47, "usage_type": "attribute"}, {"api_name": "torch.FloatTensor", "line_number": 51, "usage_type": "call"}, {"api_name": "torch.argmax", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 55, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 55, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 49, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 58, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 70, "usage_type": "attribute"}, {"api_name": "torch.arange", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.mean", "line_number": 77, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 117, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 115, "usage_type": "call"}, {"api_name": "torch.argmax", "line_number": 169, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 172, "usage_type": "call"}]} +{"seq_id": "74760599743", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Aug 25 19:30:52 2020\r\n\r\n@author: DaiHoang\r\n\"\"\"\r\n\r\nimport tensorflow as tf\r\nfrom tensorflow.keras.utils import to_categorical\r\nimport numpy as np\r\nfrom keras.utils import np_utils\r\n#from parameters import doa_samples\r\nfrom scipy.linalg import cholesky, ldl, toeplitz\r\nfrom tqdm import tqdm\r\n\r\nc = 3e8\r\nfc = 1e9\r\nwavelength = c/fc\r\nd = 0.5*wavelength\r\nresolution = 0.1\r\ndoa_samples = np.arange(-60, 60, resolution)\r\n\r\ndef attenuation_coef():\r\n sign_real = 1 if np.random.random() < 0.5 else -1\r\n sign_imag = 1 if np.random.random() < 0.5 else -1\r\n return (sign_real*np.random.normal(0, 1) + sign_imag*1j*np.random.normal(0, 1))/np.sqrt(2)\r\n\r\ndef DoAs_samples(N_signals=4, DoAs_spacing=1):\r\n DoAs_truth = []\r\n while len(DoAs_truth) < N_signals: # to ensure no same DoA in this list\r\n DoA_tmp = np.random.uniform(-60, 60)\r\n # Assign the very first DoA value or only append DoAs out of spacing\r\n if len(DoAs_truth) == 0 or np.sum(np.abs(np.array(DoAs_truth) - DoA_tmp) > DoAs_spacing) == len(DoAs_truth):\r\n DoAs_truth.append(DoA_tmp)\r\n return DoAs_truth\r\n\r\ndef DoA_onehot(DoAs, resolution):\r\n DoA_samples = np.arange(-60, 60, resolution)\r\n spec_truth = np.zeros(len(DoA_samples))\r\n for i in range(len(DoA_samples)):\r\n for DoA in DoAs:\r\n if np.abs(DoA_samples[i] - DoA) < 1e-2: \r\n spec_truth[i] = 1\r\n return spec_truth\r\n\r\ndef array_signal_calculator(SNRdB, delta_SNRdB, N_antenas, N_snapshots, DOAs, N_coherent=None):\r\n N_signals = len(DOAs)\r\n M = N_antenas//2\r\n if N_coherent is None: N_coherent = np.random.randint(0, high=N_signals+1)\r\n # position of array\r\n array_geom = np.expand_dims(np.array(np.arange(-M, M+1)), axis=-1)*d # position # = [0, 0,15, ..., 1.35] \r\n # noise matrix\r\n N = (np.random.normal(size=(N_antenas, N_snapshots)) + 1j*np.random.normal(size=(N_antenas, N_snapshots)))/np.sqrt(2) # size = (N_antenas, N_snapshot)\r\n std_noise = np.std(N)\r\n \r\n snrdB = np.random.uniform(low=SNRdB - delta_SNRdB/2, high=SNRdB + delta_SNRdB/2);\r\n\r\n array_signal = 0\r\n S_hist = []\r\n for sig in range(N_signals):\r\n phase_shift_array = 2*np.pi*array_geom/wavelength*np.sin(DOAs[sig]*np.pi/180) \r\n # size = (10, 1)\r\n A = np.exp(-1j*phase_shift_array) # steering vectors'matrix, size = (N_antenas, N_signals) = (N_antenas, 1)\r\n if sig <= N_coherent:\r\n if sig == 0: \r\n S_0 = np.random.normal(size=(1, N_snapshots)) + 1j*np.random.normal(size=(1, N_snapshots)) # path-gain, size = (N_signals, N_snapshots) = (1, N_snapshots)\r\n S = 1*S_0\r\n else:\r\n S = attenuation_coef()*S_0\r\n else:\r\n S = np.random.normal(size=(1, N_snapshots)) + 1j*np.random.normal(size=(1, N_snapshots)) # path-gain, size = (N_signals, N_snapshots) = (1, N_snapshots)\r\n S = 10**(snrdB/20)*S/np.sqrt(2)\r\n array_signal += A.dot(S) \r\n X = array_signal + N \r\n return X, std_noise, N_coherent\r\n\r\ndef data_covariance(R, normalized=True, diag_element=False):\r\n # Collect elements in upper triangle of Covariance matrix\r\n cov_vector = []\r\n for r in range(R.shape[0]):\r\n cov_vector.extend(R[r, (r+1):])\r\n cov_vector_ = np.asarray(cov_vector)\r\n if diag_element:\r\n cov_vector_ = np.concatenate([np.diag(R).real, cov_vector_.real, cov_vector_.imag])\r\n else:\r\n cov_vector_ = np.concatenate([cov_vector_.real, cov_vector_.imag])\r\n if normalized:\r\n #cov_data = cov_vector_/np.linalg.norm(cov_vector_)\r\n cov_data = cov_vector_/np.linalg.norm(cov_vector_)\r\n else:\r\n cov_data = cov_vector_\r\n return cov_data\r\n\r\ndef data_toeplitz(X, SNRdB, N_antenas, N_snapshots):\r\n M = N_antenas//2\r\n SNR = 10**(SNRdB/10)\r\n\r\n # covariance matrix\r\n R = X.dot(np.matrix.getH(X))/N_snapshots # R.shape = (N_antenas, N_antenas)\r\n \r\n ### Construct F and G ###\r\n F = 0 \r\n # Construct full-row Toeplitz covariance matrix - F\r\n #for r in range(M+1):\r\n for r in range(R.shape[0]):\r\n Rm_tmp = R[r, :]\r\n Rm = toeplitz(Rm_tmp[:M+1][::-1], Rm_tmp[M:])\r\n F += Rm.dot(np.matrix.getH(Rm))\r\n \r\n # Collect eigenvalues from toeplitz algorithm\r\n #R_bar = F + np.identity(M+1).dot(np.matrix.getH(F)).dot(np.identity(M+1))\r\n \r\n ## Forward/Backward algorithm\r\n J = np.eye(M+1)[:, :: -1]\r\n R_bar = (F + J.dot(np.conj(F)).dot(J))/2\r\n eig_values, eig_vectors = data_eigens(R_bar)\r\n \r\n # Collect elements in upper triangle of Covariance matrix\r\n cov_data = data_covariance(R_bar)\r\n return cov_data, R_bar, eig_values, eig_vectors\r\n\r\ndef covariance_fbss(X, SNRdB, N_antenas, N_snapshots, M_fbss=None):\r\n # Reference: Forward/Backward Spatial Smoothing Techniques for Coherent Signal Indentification\r\n # Input: M_fbss is the number of antennas in each sub-array (not the total antennas)\r\n # N_sub_antenas <= N_antenas - N_signals + 1\r\n if M_fbss is None: M_fbss = N_antenas//2 # M\r\n L = N_antenas - M_fbss + 1 # L\r\n \r\n R_f = np.zeros((M_fbss, M_fbss), dtype=complex)\r\n for l in range(L):\r\n X_lf = X[l:l+M_fbss, :]\r\n #R_f += X_lf.dot(np.matrix.getH(X_lf))/(L*N_snapshots)\r\n R_f += X_lf.dot(np.matrix.getH(X_lf))/N_snapshots\r\n \r\n # Quick way to calculate R_b\r\n change = np.eye(M_fbss)\r\n R_b = np.dot(change[:, :: -1], np.conj(R_f).dot(change[:, :: -1]))\r\n \r\n '''\r\n R_b = np.zeros((N_sub_antenas, N_sub_antenas), dtype=complex)\r\n for i_sub in range(N_subarrays):\r\n X_tmp = X[::-1, :]\r\n X_lb = np.conj(X_tmp[i_sub:i_sub+N_sub_antenas, :])\r\n R_b += X_lb.dot(np.matrix.getH(X_lb))/(N_subarrays*N_snapshots)\r\n '''\r\n R_avg = (R_f + R_b)/2\r\n #return R_f # Uncomment this line to perform FOSS algorithm\r\n return R_avg\r\n\r\ndef data_fbss(X, SNRdB, N_antenas, N_snapshots, std_noise=None, M_fbss=None): \r\n R_fbss = covariance_fbss(X, SNRdB, N_antenas, N_snapshots, M_fbss=M_fbss)\r\n if std_noise is not None: R_fbss += np.eye(R_fbss.shape[0])*(std_noise**2)\r\n eig_values, eig_vectors = data_eigens(R_fbss)\r\n # Collect elements in upper triangle of Cholesky deomposition\r\n #chol_vector, chol_norm = data_cholesky(R_fbss)\r\n ldl_L, ldl_D = data_LDL(R_fbss)\r\n return R_fbss, eig_values, eig_vectors, ldl_L, ldl_D\r\n\r\ndef EGM_liked_output(arr_sorted):\r\n delta_max = (arr_sorted[0] - arr_sorted[-1])/(len(arr_sorted) - 1)\r\n outputs = []\r\n for i in range(len(arr_sorted) - 1):\r\n delta = arr_sorted[i] - arr_sorted[i+1]\r\n if delta <= delta_max:\r\n outputs.append(delta)\r\n outputs = np.concatenate((outputs, np.zeros(len(arr_sorted) - len(outputs))))\r\n return outputs\r\n\r\ndef data_cholesky(R):\r\n # Collect elements in upper triangle of Cholesky deomposition\r\n chol = cholesky(R, lower=False)\r\n chol_vector = []\r\n for r in range(chol.shape[0]):\r\n chol_vector.extend(chol[r, (r+1):])\r\n chol_vector = np.asarray(chol_vector)\r\n chol_vector = np.concatenate([chol_vector.real, chol_vector.imag])\r\n chol_norm = np.linalg.norm(chol, axis=1, keepdims=False)\r\n return chol_vector, chol_norm\r\n\r\ndef data_LDL(R):\r\n # Collect elements in upper triangle of Cholesky deomposition\r\n chol, d, _ = ldl(R, lower=False)\r\n chol_vector = []\r\n for r in range(chol.shape[0]):\r\n chol_vector.extend(chol[r, (r+1):])\r\n chol_vector = np.asarray(chol_vector)\r\n chol_vector = np.concatenate([chol_vector.real, chol_vector.imag])\r\n d = -np.sort(-np.diag(d.real)) # Decending sort\r\n d = np.round(d, 5)\r\n return chol_vector, d\r\n\r\ndef data_eigens(R):\r\n eig_values, eig_vectors = np.linalg.eig(R)\r\n eig_values = eig_values.real\r\n # Decending sort\r\n eig_values = -np.sort(-np.real(eig_values)) \r\n eig_vectors = eig_vectors[:, np.argsort(-np.real(eig_values))]\r\n return eig_values, eig_vectors\r\n\r\ndef data_root_music(R, N_antenas, N_signals, input_only=False):\r\n M = N_antenas//2\r\n eig_vals, eig_vect = data_eigens(R)\r\n Qn = eig_vect[:, N_signals:M+1]\r\n # Calculate the noise subspace\r\n C = Qn.dot(np.matrix.getH(Qn))\r\n # Construct the co-effiecent in polynomial equation (DNN input)\r\n f = []\r\n f_X = []\r\n for di in np.arange(-M, M+1)[::-1]:\r\n if di < 0:\r\n f_X.append(np.sum(np.diag(C, di)))\r\n f.append(np.sum(np.diag(C, di)))\r\n X = np.concatenate((np.real(f_X), np.imag(f_X)), axis = 0)\r\n X = X/np.linalg.norm(X)\r\n\r\n #X = data_covariance(C, normalized=False, diag_element=True)\r\n if input_only: return X\r\n # Root-Output of the DNN (DNN output)\r\n r = np.roots(f)\r\n #y = np.concatenate((np.real(r), np.imag(r)), axis = 0)\r\n abs_r = np.abs(r)\r\n r = r[np.argsort(-abs_r)]\r\n idx = np.where(np.abs(r) < 1)[0][:N_signals]\r\n \r\n DoAs_est = []\r\n for i in idx:\r\n #doa = np.math.asin(-np.angle(r[i])/np.pi)*180/np.pi\r\n doa = np.math.asin(-np.angle(r[i])/np.pi)\r\n DoAs_est.append(doa)\r\n y = np.sort(DoAs_est)\r\n return X, y\r\n\r\ndef angle_rounding(DoAs, resolution):\r\n DoAs_rounding = []\r\n DoA_samples = np.arange(-60, 60, resolution)\r\n for DoA in DoAs:\r\n for s in range(len(DoA_samples) - 1):\r\n if DoA >= DoA_samples[s] and DoA < DoA_samples[s+1]:\r\n DoA_mean = np.mean([DoA_samples[s], DoA_samples[s+1]])\r\n if DoA >= DoA_mean:\r\n DoAs_rounding.append(DoA_samples[s+1])\r\n else:\r\n DoAs_rounding.append(DoA_samples[s])\r\n if len(DoAs_rounding) >= len(DoAs): break\r\n return DoAs_rounding\r\n\r\ndef dataset_Nsignals_fbss(SNRdB, delta_SNRdB, N_antenas, N_snapshots, N_signals_min, N_signals_max, M_fbss, N_repeat=10000, random_flag=False):\r\n delta_DoA = 2\r\n data = {}\r\n data['eigen_fbss'] = []\r\n data['y_Nsignals'] = []\r\n data['DoAs'] = []\r\n\r\n for rep in tqdm(range(N_repeat)):\r\n # if rep%(N_repeat//10)==0: print('<=========== Repetition: %d ============>'%rep)\r\n if random_flag:\r\n N_signals = np.random.randint(N_signals_min, N_signals_max+1)\r\n N_coherent = np.random.randint(0, N_signals)\r\n DOAs = DoAs_samples(N_signals, delta_DoA)\r\n\r\n X, _, _ = array_signal_calculator(SNRdB, delta_SNRdB, N_antenas, N_snapshots, DOAs, N_coherent=N_coherent)\r\n # Data from FBSS algprithm\r\n _, eigen_fbss, _, _, _ = data_fbss(X, SNRdB, N_antenas, N_snapshots, std_noise=None, M_fbss=M_fbss)\r\n #data['X'].append(X)\r\n data['eigen_fbss'].append(eigen_fbss) \r\n # Output for N_signals detection and DoA estimation\r\n data['y_Nsignals'].append(np_utils.to_categorical(N_signals, N_antenas//2 + 2))\r\n data['DoAs'].append(DOAs)\r\n\r\n else:\r\n for N_signals in range(N_signals_min, N_signals_max+1):\r\n DOAs = DoAs_samples(N_signals, delta_DoA)\r\n N_coherent = np.random.randint(0, N_signals)\r\n X, std_noise, _ = array_signal_calculator(SNRdB, delta_SNRdB, N_antenas, N_snapshots, DOAs, N_coherent=N_coherent)\r\n # Data from FBSS algprithm\r\n _, eigen_fbss, _, _, _ = data_fbss(X, SNRdB, N_antenas, N_snapshots, std_noise=None, M_fbss=M_fbss)\r\n #data['X'].append(X)\r\n data['eigen_fbss'].append(eigen_fbss)\r\n # Output for N_signals detection and DoA estimation\r\n data['y_Nsignals'].append(np_utils.to_categorical(N_signals, N_antenas//2 + 2))\r\n data['DoAs'].append(DOAs)\r\n return data\r\n\r\ndef dataset_Nsignals_toep(SNRdB, delta_SNRdB, N_antenas, N_snapshots, N_signals_min, N_signals_max, N_repeat=10000, random_flag=False):\r\n delta_DoA = 2\r\n data = {}\r\n data['eigen_toep'] = []\r\n data['y_Nsignals'] = []\r\n data['DoAs'] = []\r\n\r\n for rep in tqdm(range(N_repeat)):\r\n # if rep%(N_repeat//10)==0: print('<=========== Repetition: %d ============>'%rep)\r\n if random_flag:\r\n N_signals = np.random.randint(N_signals_min, N_signals_max+1)\r\n N_coherent = np.random.randint(0, N_signals)\r\n DOAs = DoAs_samples(N_signals, delta_DoA)\r\n\r\n X, _, _ = array_signal_calculator(SNRdB, delta_SNRdB, N_antenas, N_snapshots, DOAs, N_coherent=N_coherent)\r\n # Data from Toeplitz-FBSS algprithm\r\n _, _, eigen_toep, _ = data_toeplitz(X, SNRdB, N_antenas, N_snapshots)\r\n data['eigen_toep'].append(eigen_toep) \r\n # Output for N_signals detection and DoA estimation\r\n data['y_Nsignals'].append(np_utils.to_categorical(N_signals, N_antenas//2 + 2))\r\n data['DoAs'].append(DOAs)\r\n\r\n else:\r\n for N_signals in range(N_signals_min, N_signals_max+1):\r\n DOAs = DoAs_samples(N_signals, delta_DoA)\r\n N_coherent = np.random.randint(0, N_signals)\r\n X, std_noise, _ = array_signal_calculator(SNRdB, delta_SNRdB, N_antenas, N_snapshots, DOAs, N_coherent=N_coherent)\r\n # Data from FBSS algprithm\r\n _, _, eigen_toep, _ = data_toeplitz(X, SNRdB, N_antenas, N_snapshots)\r\n #data['X'].append(X)\r\n data['eigen_toep'].append(eigen_toep) \r\n # Output for N_signals detection and DoA estimation\r\n data['y_Nsignals'].append(np_utils.to_categorical(N_signals, N_antenas//2 + 2))\r\n data['DoAs'].append(DOAs)\r\n return data\r\n\r\n\r\ndef dataset_generator():\r\n c = 3e8\r\n fc = 1e9\r\n wavelength = c/fc\r\n d = 0.5*wavelength\r\n\r\n # Generate dataset with various SNRs\r\n # delta_SNRdB_arr = [0, 2, 4, 8, 16]\r\n delta_SNRdB_arr = [4]\r\n SNRdB_arr = [10]\r\n N_antennas_arr = [35, 45, 55]\r\n # SNRdB_arr = [-10, 0, 10, 20, 30] \r\n N_snapshots_arr = [1000] \r\n \r\n #SNRdB_arr = [10]\r\n # N_antennas_arr = [25]\r\n # resolution = 0.2\r\n resolution_arr = [0.1]\r\n \r\n for SNRdB in SNRdB_arr:\r\n for N_antenas in N_antennas_arr:\r\n for N_snapshots in N_snapshots_arr:\r\n for delta_SNRdB in delta_SNRdB_arr:\r\n \r\n # Nsignals detection dataset\r\n print('<=========== Generating dataset for Nsignals detection ============>')\r\n ## Toeplitz-FBSS algorithm with various number of \r\n # Data for training\r\n print('\\n<=========== Dataset Toeplitz-FBSS ============>')\r\n dataset_path = './train/dataset_Nsignals_clas_toep_%d_dB_%d_delta_%d_antenas_%d_snap.npy'\\\r\n %(SNRdB, delta_SNRdB, N_antenas, N_snapshots)\r\n data = dataset_Nsignals_toep(SNRdB, delta_SNRdB, N_antenas, N_snapshots, N_signals_min=1, \\\r\n N_signals_max=6, N_repeat=20000)\r\n np.save(dataset_path, data)\r\n # Data for testing\r\n print('\\n<=========== Testset Toeplitz-FBSS ============>')\r\n testset_path = './test/testset_Nsignals_clas_toep_%d_dB_%d_delta_%d_antenas_%d_snap.npy'\\\r\n %(SNRdB, delta_SNRdB, N_antenas, N_snapshots)\r\n data = dataset_Nsignals_toep(SNRdB, delta_SNRdB, N_antenas, N_snapshots, N_signals_min=1, \\\r\n N_signals_max=6, N_repeat=10000, random_flag=True)\r\n np.save(testset_path, data)\r\n\r\ndataset_generator()\r\n\r\n ", "repo_name": "daihoang25/FTMR_SignalEnum", "sub_path": "dataset_generator.py", "file_name": "dataset_generator.py", "file_ext": "py", "file_size_in_byte": 15644, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "numpy.arange", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.random.random", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 24, "usage_type": "attribute"}, {"api_name": "numpy.random.random", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 25, "usage_type": "attribute"}, {"api_name": "numpy.random.normal", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 26, "usage_type": "attribute"}, {"api_name": "numpy.sqrt", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 31, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 49, "usage_type": "attribute"}, {"api_name": "numpy.expand_dims", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 53, "usage_type": "attribute"}, {"api_name": "numpy.sqrt", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 56, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 61, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 66, "usage_type": "attribute"}, {"api_name": "numpy.random.normal", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 71, "usage_type": "attribute"}, {"api_name": "numpy.sqrt", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 89, "usage_type": "attribute"}, {"api_name": "numpy.matrix.getH", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.matrix", "line_number": 99, "usage_type": "attribute"}, {"api_name": "scipy.linalg.toeplitz", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.matrix.getH", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.matrix", "line_number": 108, "usage_type": "attribute"}, {"api_name": "numpy.eye", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.conj", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.matrix.getH", "line_number": 133, "usage_type": "call"}, {"api_name": "numpy.matrix", "line_number": 133, "usage_type": "attribute"}, {"api_name": "numpy.eye", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.conj", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 166, "usage_type": "call"}, {"api_name": "scipy.linalg.cholesky", "line_number": 171, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 175, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 177, "usage_type": "attribute"}, {"api_name": "scipy.linalg.ldl", "line_number": 182, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 186, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 187, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 188, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 188, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 189, "usage_type": "call"}, {"api_name": "numpy.linalg.eig", "line_number": 193, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 193, "usage_type": "attribute"}, {"api_name": "numpy.sort", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.real", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 197, "usage_type": "call"}, {"api_name": "numpy.real", "line_number": 197, "usage_type": "call"}, {"api_name": "numpy.matrix.getH", "line_number": 205, "usage_type": "call"}, {"api_name": "numpy.matrix", "line_number": 205, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 209, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 212, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 212, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 213, "usage_type": "call"}, {"api_name": "numpy.real", "line_number": 213, "usage_type": "call"}, {"api_name": "numpy.imag", "line_number": 213, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 214, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 214, "usage_type": "attribute"}, {"api_name": "numpy.roots", "line_number": 219, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 221, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 222, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 223, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 223, "usage_type": "call"}, {"api_name": "numpy.math.asin", "line_number": 228, "usage_type": "call"}, {"api_name": "numpy.math", "line_number": 228, "usage_type": "attribute"}, {"api_name": "numpy.angle", "line_number": 228, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 228, "usage_type": "attribute"}, {"api_name": "numpy.sort", "line_number": 230, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 235, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 239, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 254, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 257, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 257, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 258, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 258, "usage_type": "attribute"}, {"api_name": "keras.utils.np_utils.to_categorical", "line_number": 267, "usage_type": "call"}, {"api_name": "keras.utils.np_utils", "line_number": 267, "usage_type": "name"}, {"api_name": "numpy.random.randint", "line_number": 273, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 273, "usage_type": "attribute"}, {"api_name": "keras.utils.np_utils.to_categorical", "line_number": 280, "usage_type": "call"}, {"api_name": "keras.utils.np_utils", "line_number": 280, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 291, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 294, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 294, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 295, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 295, "usage_type": "attribute"}, {"api_name": "keras.utils.np_utils.to_categorical", "line_number": 303, "usage_type": "call"}, {"api_name": "keras.utils.np_utils", "line_number": 303, "usage_type": "name"}, {"api_name": "numpy.random.randint", "line_number": 309, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 309, "usage_type": "attribute"}, {"api_name": "keras.utils.np_utils.to_categorical", "line_number": 316, "usage_type": "call"}, {"api_name": "keras.utils.np_utils", "line_number": 316, "usage_type": "name"}, {"api_name": "numpy.save", "line_number": 354, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 361, "usage_type": "call"}]} +{"seq_id": "2602462540", "text": "\"\"\"\nUsing ResNet-18 on 227 X 227 X 3 images\nPrevious AlexNet implementation found below\n\n\"\"\"\n\nimport torch\nimport torch.nn as nn\n\nclass StartingNetwork(torch.nn.Module):\n\n def __init__(self):\n super().__init__()\n\n # Initial Convolutional Layer (227 X 227) --> (55 X 55)\n self.c1 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=11, stride=4, padding=1, bias=True)\n\n # Loading in ResNet-18 from PyTorch \n model = torch.hub.load('pytorch/vision:v0.8.0', 'resnet18', pretrained=True)\n self.resnet = torch.nn.Sequential(*(list(model.children())[:-1]))\n\n # Used to reduce output of ResNet \n self.f1 = nn.Linear(512, 512)\n self.f2 = nn.Linear(512, 5)\n\n\n def forward(self, x):\n x = self.c1(x) # (3 X 227 X 227) --> (3 X 55 X 55)\n nn.ReLU()\n\n x = self.resnet(x) # (3 X 55 X 55) --> (512 X 1 X 1)\n nn.ReLU()\n\n x = torch.flatten(x, 1) # (512 X 1 X 1) --> (512)\n x = self.f1(x)\n nn.ReLU()\n\n nn.Dropout(p=0.5, inplace=True) # (512) --> (512)\n\n x = self.f2(x) # (512) --> (5)\n return x\n\n\n\n\"\"\"\nPrevious implementation: AlexNet (accuracy: TBD)\n\n self.c1 = nn.Conv2d(in_channels=3, out_channels=96, kernel_size=11, stride=4, padding=1, bias=True)\n self.m1 = nn.MaxPool2d(kernel_size=3, stride=2)\n self.c2 = nn.Conv2d(in_channels=96, out_channels=256, kernel_size=5, padding=2, bias=True)\n self.m2 = nn.MaxPool2d(kernel_size=3, stride=2)\n self.c3 = nn.Conv2d(in_channels=256, out_channels=384, kernel_size=3, padding=1, bias=True)\n self.c4 = nn.Conv2d(in_channels=384, out_channels=384, kernel_size=3, padding=1, bias=True)\n self.c5 = nn.Conv2d(in_channels=384, out_channels=256, kernel_size=3, padding=1, bias=True)\n self.m3 = nn.MaxPool2d(kernel_size=3, stride=2)\n\n self.f1 = nn.Linear(in_features=9216, out_features=4096) # Changed to 256 * 6 * 6 from 6400\n self.f2 = nn.Linear(in_features=4096, out_features=4096)\n self.f3 = nn.Linear(in_features=4096, out_features=5)\n # self.f4 = nn.Linear(in_features=64, out_features=5)\n\n # self.s1 = nn.Softmax(dim=5) # Four diseases + 1 healthy\n\n x = self.c1(x) # [b, 96, 55, 55]\n nn.ReLU()\n\n x = self.m1(x) # [b, 96, 27, 27]\n\n x = self.c2(x) # [b, 256, 27, 27]\n nn.ReLU()\n\n x = self.m2(x) # [b, 256, 13, 13]\n\n x = self.c3(x) # [b, 384, 13, 13]\n nn.ReLU()\n\n x = self.c4(x) # [b, 384, 13, 13]\n nn.ReLU()\n\n x = self.c5(x) # [b, 256, 13, 13]\n nn.ReLU()\n\n x = self.m3(x) # [b, 256, 6, 6]\n\n x = torch.flatten(x, 1) # [50, 9216]\n\n x = self.f1(x)\n nn.ReLU()\n\n nn.Dropout(p=0.5, inplace=True)\n self.f2 = nn.Linear(in_features=4096, out_features=4096)\n nn.ReLU()\n\n nn.Dropout(p=0.5, inplace=True)\n self.f3 = nn.Linear(in_features=4096, out_features=5)\n\n\"\"\"\n", "repo_name": "uclaacmai/leaf-us-alone", "sub_path": "networks/StartingNetwork.py", "file_name": "StartingNetwork.py", "file_ext": "py", "file_size_in_byte": 2821, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "torch.nn", "line_number": 10, "usage_type": "attribute"}, {"api_name": "torch.nn.Conv2d", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 16, "usage_type": "name"}, {"api_name": "torch.hub.load", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.hub", "line_number": 19, "usage_type": "attribute"}, {"api_name": "torch.nn.Sequential", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "attribute"}, {"api_name": "torch.nn.Linear", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 24, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 29, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.flatten", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.nn.ReLU", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 38, "usage_type": "name"}]} +{"seq_id": "31776171407", "text": "# -*- coding: utf-8 -*-\n# @Author: yong\n# @Date: 2022-12-07 09:46:43\n# @Last Modified by: yong\n# @Last Modified time: 2022-12-21 19:12:07\n# @Author: foxwy\n# @Method: conjugate-gradient algorithm\n# @Paper: Ultrafast quantum state tomography with feed-forward neural networks\n\nimport sys\nimport numpy as np\nimport torch\nfrom time import perf_counter\nfrom tqdm import tqdm\n\nsys.path.append('../..')\nfrom Basis.Basic_Function import (qmt_torch, \n qmt_torch_pure, \n qmt_matrix, \n qmt_matrix_torch, \n get_default_device, \n proj_spectrahedron_torch)\nfrom evaluation.Fidelity import Fid\nfrom Basis.Basis_State import Mea_basis, State\n\n\ndef qse_cgls(M, n_qubits, P_data, epochs, fid, map_method, P_proj, result_save, device='cpu'):\n \"\"\"\n conjugate-gradient algorithm, see paper\n ``Superfast maximum-likelihood reconstruction for quantum tomography``.\n \n Args:\n M (tensor): The POVM, size (K, 2, 2).\n n_qubits (int): The number of qubits.\n P_data (tensor): The probability distribution obtained from the experimental measurements.\n epochs (int): Maximum number of iterations.\n fid (Fid): Class for calculating fidelity.\n map_method (str): State-mapping method, include ['chol', 'chol_h', 'proj_F', 'proj_S', 'proj_A'].\n P_proj (float): P order.\n result_save (set): A collection that holds process data.\n device (torch.device): GPU or CPU. \n\n Stops:\n Reach the maximum number of iterations or quantum fidelity greater than or equal to 0.99 or other conditions.\n\n Examples::\n see ``FNN/FNN_learn`` or main.\n \"\"\"\n # parameter\n opts = {'adjustment': 0.5, 'mincondchange': -torch.inf, 'step_adjust': 2, 'a2': 0.1, 'a3': 0.2}\n\n d = torch.tensor(2**n_qubits)\n M = M.to(torch.complex128)\n P_data = P_data.to(torch.double)\n eps = np.finfo(np.complex128).eps\n threshold_step = torch.sqrt(d) * d * eps\n threshold_fval = -P_data[P_data > 0].dot(torch.log(P_data[P_data > 0]))\n\n # rho init\n A = (torch.eye(d) / torch.sqrt(d)).to(torch.complex128).to(device)\n rho = (torch.eye(d) / d).to(torch.complex128).to(device)\n\n # -----line search stuff-----\n a2 = opts['a2']\n a3 = opts['a3']\n\n # discard zero-vauled frequencies\n probs = qmt_torch(rho, [M] * n_qubits)\n adj = P_data / probs\n adj[P_data == 0] = 0\n rmatrix = qmt_matrix_torch(adj.to(torch.complex128), [M] * n_qubits)\n\n condchange = torch.inf\n\n if opts['mincondchange'] > 0:\n hessian_proxy = P_data / probs**2\n hessian_proxy[P_data == 0] = 0\n old_hessian_proxy = hessian_proxy\n\n fval = -P_data[P_data > 0].dot(torch.log(probs[P_data > 0]))\n\n # iterative\n pbar = tqdm(range(epochs))\n time_all = 0\n stop_i = -1\n for i in pbar:\n time_b = perf_counter()\n\n curvature_too_large = False\n\n if opts['mincondchange'] > 0:\n if i > 0:\n condchange = torch.real(torch.acos(torch.real(old_hessian_proxy.dot(hessian_proxy)) / torch.norm(old_hessian_proxy) / torch.norm(hessian_proxy)))\n\n # the gradient\n if i == 0:\n # gradient\n G = torch.matmul(A, rmatrix - torch.eye(d).to(device))\n # conjugate-gradient\n H = G\n else:\n G_next = torch.matmul(A, rmatrix - torch.eye(d).to(device))\n polakribiere = torch.real(torch.matmul(G_next.reshape(-1, 1).T.conj(), (G_next.reshape(-1, 1) - opts['adjustment'] * G.reshape(-1, 1)))) / torch.norm(G)**2\n gamma = torch.maximum(polakribiere, torch.tensor(0))\n # conjugate-gradient\n H = G_next + gamma * H\n # gradient\n G = G_next\n\n # line search\n A2 = A + a2 * H\n A3 = A + a3 * H\n rho2 = torch.matmul(A2.T.conj(), A2)\n rho2 = rho2 / torch.trace(rho2)\n rho3 = torch.matmul(A3.T.conj(), A3)\n rho3 = rho3 / torch.trace(rho3)\n probs2 = qmt_torch(rho2, [M] * n_qubits)\n probs3 = qmt_torch(rho3, [M] * n_qubits)\n\n l1 = fval\n l2 = -P_data[P_data > 0].dot(torch.log(probs2[P_data > 0]))\n l3 = -P_data[P_data > 0].dot(torch.log(probs3[P_data > 0]))\n alphaprod = 0.5 * ((l3 - l1) * a2**2 - (l2 - l1) * a3**2) / ((l3 - l1) * a2 - (l2 - l1) * a3)\n \n if torch.isnan(alphaprod) or alphaprod > 1 / eps or alphaprod < 0:\n candidates = [0, a2, a3]\n l_list = [l1, l2, l3]\n index = l_list.index(min(l_list))\n if opts['step_adjust'] > 1:\n if torch.isnan(alphaprod) or alphaprod > 1 / eps:\n # curvature too small to estimate properly\n a2 = opts['step_adjust'] * a2\n a3 = opts['step_adjust'] * a3\n elif alphaprod < 0:\n # curvature too large, so steps overshoot parabola\n a2 = a2 / opts['step_adjust']\n a3 = a3 / opts['step_adjust']\n curvature_too_large = True\n\n alphaprod = candidates[index]\n\n # update\n A = A + alphaprod * H\n A = A / torch.norm(A)\n old_rho = rho\n\n\n # map\n if map_method == 'chol':\n T = torch.tril(A)\n T_temp = torch.matmul(T.T.conj(), T)\n rho = T_temp / torch.trace(T_temp)\n elif map_method == 'chol_h':\n T_temp = torch.matmul(A.T.conj(), A)\n rho = T_temp / torch.trace(T_temp)\n else:\n rho = proj_spectrahedron_torch(A, device, map_method, P_proj)\n\n probs = qmt_torch(rho, [M] * n_qubits)\n fval = -P_data[P_data > 0].dot(torch.log(probs[P_data > 0]))\n\n # check threshold\n steps_i = 0.5 * torch.sqrt(d) * torch.norm(rho - old_rho)\n satisfied_step = steps_i <= threshold_step\n satisfied_fval = fval <= threshold_fval\n\n if i < epochs - 1:\n adj = P_data / probs\n adj[P_data == 0] = 0\n rmatrix = qmt_matrix_torch(adj.to(torch.complex128), [M] * n_qubits)\n\n if opts['mincondchange'] > 0:\n old_hessian_proxy = hessian_proxy\n hessian_proxy = P_data / probs**2\n hessian_proxy[P_data == 0] = 0\n\n time_e = perf_counter()\n time_all += time_e - time_b\n\n # evalution\n if i % 2 == 0:\n Fc = fid.cFidelity_rho(rho.to(torch.complex64))\n Fq = fid.Fidelity(rho.to(torch.complex64))\n\n result_save['time'].append(time_all)\n result_save['epoch'].append(i)\n result_save['Fc'].append(Fc)\n result_save['Fq'].append(Fq)\n pbar.set_description(\"CGL --Fc {:.8f} | Fq {:.8f} | time {:.4f} | epochs {:d}\".format(Fc, Fq, time_all, i))\n\n if (not curvature_too_large and satisfied_step) or satisfied_fval or condchange < opts['mincondchange']:\n stop_i = i\n break\n\n if Fq >= 0.99:\n break\n\n pbar.close()\n\n if stop_i == -1:\n stop_i = epochs - 1\n return rho, stop_i, time_all\n\n\nif __name__ == '__main__':\n n_qubits = 10\n POVM = 'Tetra4'\n ty_state = 'mixed'\n na_state = 'GHZi_P'\n P_state = 0.5\n device = get_default_device()\n\n M = Mea_basis(POVM).M\n M = torch.from_numpy(M).to(device)\n\n state_star, rho_star = State().Get_state_rho(na_state, n_qubits, P_state)\n rho_star = torch.from_numpy(rho_star).to(torch.complex64).to(device)\n\n fid = Fid(basis=POVM, n_qubits=n_qubits, ty_state=ty_state, rho_star=rho_star, M=M, device=device)\n \n P_data = qmt_torch(rho_star, [M] * n_qubits)\n\n result_save = {'time': [],\n 'epoch': [],\n 'Fc': [],\n 'Fq': []}\n qse_cgls(M, n_qubits, P_data, 200, fid, 'chol_h', 2, result_save, device)\n", "repo_name": "foxwy/QST-NNGMs-FNN", "sub_path": "models/MLE_Pytorch/qse_cgls.py", "file_name": "qse_cgls.py", "file_ext": "py", "file_size_in_byte": 7933, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sys.path.append", "line_number": 16, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 16, "usage_type": "attribute"}, {"api_name": "torch.inf", "line_number": 50, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.complex128", "line_number": 53, "usage_type": "attribute"}, {"api_name": "torch.double", "line_number": 54, "usage_type": "attribute"}, {"api_name": "numpy.finfo", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.complex128", "line_number": 55, "usage_type": "attribute"}, {"api_name": "torch.sqrt", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.log", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.eye", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.sqrt", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.complex128", "line_number": 60, "usage_type": "attribute"}, {"api_name": "torch.eye", "line_number": 61, "usage_type": "call"}, {"api_name": "torch.complex128", "line_number": 61, "usage_type": "attribute"}, {"api_name": "Basis.Basic_Function.qmt_torch", "line_number": 68, "usage_type": "call"}, {"api_name": "Basis.Basic_Function.qmt_matrix_torch", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.complex128", "line_number": 71, "usage_type": "attribute"}, {"api_name": "torch.inf", "line_number": 73, "usage_type": "attribute"}, {"api_name": "torch.log", "line_number": 80, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 83, "usage_type": "call"}, {"api_name": "time.perf_counter", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.real", "line_number": 93, "usage_type": "call"}, {"api_name": "torch.acos", "line_number": 93, "usage_type": "call"}, {"api_name": "torch.norm", "line_number": 93, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 98, "usage_type": "call"}, {"api_name": "torch.eye", "line_number": 98, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 102, "usage_type": "call"}, {"api_name": "torch.eye", "line_number": 102, "usage_type": "call"}, {"api_name": "torch.real", "line_number": 103, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 103, "usage_type": "call"}, {"api_name": "torch.norm", "line_number": 103, "usage_type": "call"}, {"api_name": "torch.maximum", "line_number": 104, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 104, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 113, "usage_type": "call"}, {"api_name": "torch.trace", "line_number": 114, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 115, "usage_type": "call"}, {"api_name": "torch.trace", "line_number": 116, "usage_type": "call"}, {"api_name": "Basis.Basic_Function.qmt_torch", "line_number": 117, "usage_type": "call"}, {"api_name": "Basis.Basic_Function.qmt_torch", "line_number": 118, "usage_type": "call"}, {"api_name": "torch.log", "line_number": 121, "usage_type": "call"}, {"api_name": "torch.log", "line_number": 122, "usage_type": "call"}, {"api_name": "torch.isnan", "line_number": 125, "usage_type": "call"}, {"api_name": "torch.isnan", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.norm", "line_number": 144, "usage_type": "call"}, {"api_name": "torch.tril", "line_number": 150, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 151, "usage_type": "call"}, {"api_name": "torch.trace", "line_number": 152, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 154, "usage_type": "call"}, {"api_name": "torch.trace", "line_number": 155, "usage_type": "call"}, {"api_name": "Basis.Basic_Function.proj_spectrahedron_torch", "line_number": 157, "usage_type": "call"}, {"api_name": "Basis.Basic_Function.qmt_torch", "line_number": 159, "usage_type": "call"}, {"api_name": "torch.log", "line_number": 160, "usage_type": "call"}, {"api_name": "torch.sqrt", "line_number": 163, "usage_type": "call"}, {"api_name": "torch.norm", "line_number": 163, "usage_type": "call"}, {"api_name": "Basis.Basic_Function.qmt_matrix_torch", "line_number": 170, "usage_type": "call"}, {"api_name": "torch.complex128", "line_number": 170, "usage_type": "attribute"}, {"api_name": "time.perf_counter", "line_number": 177, "usage_type": "call"}, {"api_name": "torch.complex64", "line_number": 182, "usage_type": "attribute"}, {"api_name": "torch.complex64", "line_number": 183, "usage_type": "attribute"}, {"api_name": "Basis.Basic_Function.get_default_device", "line_number": 211, "usage_type": "call"}, {"api_name": "Basis.Basis_State.Mea_basis", "line_number": 213, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 214, "usage_type": "call"}, {"api_name": "Basis.Basis_State.State", "line_number": 216, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 217, "usage_type": "call"}, {"api_name": "torch.complex64", "line_number": 217, "usage_type": "attribute"}, {"api_name": "evaluation.Fidelity.Fid", "line_number": 219, "usage_type": "call"}, {"api_name": "Basis.Basic_Function.qmt_torch", "line_number": 221, "usage_type": "call"}]} +{"seq_id": "14482064568", "text": "#!/usr/bin/env python3\n# *******************************************************\n# Type: Motion controller\n# \n# Motion controller for the mouse\n# Handles state machine and low level spine and leg control.\n# \n# Author: Alex Rohregger\n# Contact: alex.rohregger@tum.de\n# Last-edited: 26.04.2021\n# *********************************************************\n\n# Import the leg and motionplanner modules\nfrom mouse_controller.leg_controller import Leg_Controller\nfrom mouse_controller.state_machine.leg_state_machine import Leg_State_Machine\nfrom mouse_controller.mouse_parameters_dir import Gait_Parameters, Mouse_Parameters\nfrom time import sleep\n\nimport numpy as np\nimport math\nfrom time import sleep\nimport time\nfrom mujoco_py import load_model_from_path, MjSim, MjViewer\nimport matplotlib.pyplot as plt\nimport sys, getopt\n\n\nclass Motion_Module:\n def __init__(self, vis_flag, turn_mode, walk_mode, for_turn_rate, the_fre):\n self.model_name = \"dynamic_4l_t3_empty.xml\"\n #self.model_name = \"dynamic_4l_t3_test_site.xml\"\n self.model_path = \"../models/\"+self.model_name\n self.model = load_model_from_path(self.model_path)\n self.sim = MjSim(self.model)\n self.vis_flag = vis_flag\n if self.vis_flag:\n self.viewer = MjViewer(self.sim)\n\n self.fixPoint = \"body_ss\"\n self.movePath = [[],[],[]]\n self.moveVel = []\n self.run_time = 10000\n self.dead_time = 1000\n self.init_mouse_variables(turn_mode, walk_mode, for_turn_rate, the_fre)\n self.init_controllers()\n self.main()\n\n def init_mouse_variables(self, turn_mode, walk_mode, for_turn_rate, the_fre):\n fre = the_fre\n self.trg_spine_mode = 1\n # Gait: Trt\n # lb: 0.5m --> -0.90, 1m --> -0.85\n # sb: 0.5m --> -0.75, 1m --> -0.41\n # mb: 0.5m --> -0.60, 1m --> -0.60\n self.trg_vel = 0.5\n gaie_mode = walk_mode\n #0: only leg, 1: only spine, 2: mix\n self.trg_turn = turn_mode\n self.turn_rate = for_turn_rate\n self.gait_parameters2 = Gait_Parameters(fre)\n self.mouse_parameters = Mouse_Parameters()\n if gaie_mode ==0:\n self.general_st_parameters2 = self.gait_parameters2.st_trot_parameters\n elif gaie_mode == 1:\n self.general_st_parameters2 = self.gait_parameters2.st_trot_parameters1\n else:\n self.general_st_parameters2 = self.gait_parameters2.walk_trot_parameters\n self.front_leg_parameters2 = self.gait_parameters2.st_trot_param_f\n self.rear_leg_parameters2 = self.gait_parameters2.st_trot_param_r\n def init_controllers(self):\n # Initialize the key components of the motion module\n # Spine modes:\n # 0: purely turning motion, nothing else\n # 1: turning motion + spine modulation\n # 2: turning motion + balance mode (balance mode for 2 and 3 leg contact)\n self.spine_mode = 0\n self.offset_mode = False\n self.balance_mode = True\n self.fsm = Leg_State_Machine(self.general_st_parameters2)\n self.leg_controller = Leg_Controller(self.gait_parameters2, self.mouse_parameters)\n self.vel_in = 0.0\n self.buttons = [0]*4\n self.prev_buttons = [0]*4\n self.leg_n = 0\n\n def motion_node(self):\n # Initialize the node\n self.fsm.timer.reset_times()\n sleep(0.002)\n \n self.vel_in = self.trg_vel\n\n # Subscribe to the ps4 controller\n for i in range(self.dead_time):\n q_legs = [0.42,1,0.42,1,-0.15,-0.66,-0.15,-0.66]\n vel_val = self.gen_messages(q_legs, 0, 0)\n\n start_steps = 500\n for i in range(self.run_time + start_steps):\n vel = self.vel_in * np.ones((4,))\n leg_states, leg_timings, norm_time = self.fsm.run_state_machine()\n\n if self.trg_turn == 0:\n target_leg_positions, q_legs, q_spine = self.leg_controller.run_controller(leg_states, leg_timings, norm_time, vel, self.turn_rate, self.spine_mode, self.offset_mode)\n q_spine = 0\n elif self.trg_turn == 1:\n cur_turn_rate = 0\n target_leg_positions, q_legs, q_spine = self.leg_controller.run_controller(leg_states, leg_timings, norm_time, vel, cur_turn_rate, self.spine_mode, self.offset_mode)\n cur_turn_rate = self.turn_rate\n _, _, q_spine = self.leg_controller.run_controller(leg_states, leg_timings, norm_time, vel, cur_turn_rate, self.spine_mode, self.offset_mode)\n elif self.trg_turn == 2:\n target_leg_positions, q_legs, q_spine = self.leg_controller.run_controller(leg_states, leg_timings, norm_time, vel, self.turn_rate, self.spine_mode, self.offset_mode)\n else:\n print('Error !!!!!!!')\n\n q_tail = self.tail_extension(norm_time, self.vel_in)\n\n vel_val = self.gen_messages(q_legs, q_spine, q_tail)\n if i >= start_steps:\n tData = self.sim.data.get_site_xpos(self.fixPoint)\n self.moveVel.append(vel_val)\n for i in range(3):\n self.movePath[i].append(tData[i])\n\n def tail_extension(self, timing: float,vel: float, offset=0, scaling=0.5) -> float:\n # THis function helps extend the spine stride during gait.\n # Timing value: is normalized time value [0,1]\n scale = min(4.5*np.abs(vel)**2, scaling)\n q_tail = scale*np.cos(2*np.pi*timing+offset)\n return q_tail\n\n \n def oriention_data_store(self):\n data = self.sim.data.sensordata\n servo_pos_leg = data[:8]\n servo_pos_aux = data[8:12]\n contact_sensors = data[12:16]\n imu_sensor = data[16:]\n framepos = imu_sensor[:3]\n framequat = imu_sensor[3:7]\n framelinvel = imu_sensor[7:10]\n accelerometer = imu_sensor[10:13]\n gyro = imu_sensor[13:]\n \n return framelinvel\n\n def gen_messages(self, q_legs, q_spine, q_tail):\n vel_x, vel_y, vel_z = self.oriention_data_store()\n vel_val = math.sqrt(vel_x*vel_x + vel_y*vel_y)\n\n q_values = np.concatenate((q_legs,np.array(([q_tail,0,0,q_spine]))))\n q_values.astype(dtype=np.float32)\n\n self.sim.data.ctrl[:] = q_values\n self.sim.step()\n if self.vis_flag:\n self.viewer.render() \n\n return vel_val\n\n def main(self):\n start_time = time.time()\n self.motion_node()\n\nif __name__ == \"__main__\":\n err_flag = 0\n\n turn_mode = 0\n walk_mode = 0\n for_turn_rate = 1\n the_fre = 0.8\n\n argv = sys.argv[1:]\n opts, args = getopt.getopt(argv, \"t:w:r:f:\")\n #t (turn mode): 0: leg-based, 1: spine-based, 2: mix-based\n turning_mode = {\"lb\": 0, \"sb\": 1, \"mb\": 2}\n #w (walk rate): 0: trt, 1: walk, 2: lat\n walking_mode = {\"trt\": 0, \"walk\": 1, \"lat\": 2}\n #t (turning rate): a float in [-1, 1]\n #f (frequency): a float [0, 1.5]\n for opt, arg in opts:\n if opt in ['-t']:\n if arg in turning_mode.keys():\n turn_mode = turning_mode[arg]\n else:\n err_flag = 1\n elif opt in ['-w']:\n if arg in walking_mode.keys():\n walk_mode = walking_mode[arg]\n else:\n err_flag = 1\n elif opt in ['-r']:\n for_turn_rate = float(arg)\n if abs(for_turn_rate) > 1:\n err_flag = 1\n elif opt in ['-f']:\n fre = float(arg)\n if abs(fre) > 1:\n err_flag = 1\n else:\n err_flag = 1\n\n if err_flag:\n print(\"Error with parameters !!!\")\n else:\n vis_flag = True\n Motion_Module(vis_flag, turn_mode, walk_mode, for_turn_rate, the_fre)\n\n", "repo_name": "zhenshan-bing/NeRmo", "sub_path": "Simulation Results/turn/src/Test_turning.py", "file_name": "Test_turning.py", "file_ext": "py", "file_size_in_byte": 7763, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "mujoco_py.load_model_from_path", "line_number": 33, "usage_type": "call"}, {"api_name": "mujoco_py.MjSim", "line_number": 34, "usage_type": "call"}, {"api_name": "mujoco_py.MjViewer", "line_number": 37, "usage_type": "call"}, {"api_name": "mouse_controller.mouse_parameters_dir.Gait_Parameters", "line_number": 60, "usage_type": "call"}, {"api_name": "mouse_controller.mouse_parameters_dir.Mouse_Parameters", "line_number": 61, "usage_type": "call"}, {"api_name": "mouse_controller.state_machine.leg_state_machine.Leg_State_Machine", "line_number": 79, "usage_type": "call"}, {"api_name": "mouse_controller.leg_controller.Leg_Controller", "line_number": 80, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 129, "usage_type": "attribute"}, {"api_name": "math.sqrt", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 152, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 162, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 173, "usage_type": "attribute"}, {"api_name": "getopt.getopt", "line_number": 174, "usage_type": "call"}]} +{"seq_id": "12755020008", "text": "# Put the code for your API here.\nimport os\nimport joblib\nimport pandas as pd\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel, Field\n\nfrom src.ml.model import *\n\nif \"DYNO\" in os.environ and os.path.isdir(\".dvc\"):\n os.system(\"dvc config core.no_scm true\")\n os.system(\"dvc config core.hardlink_lock true\")\n if os.system(\"dvc pull\") != 0:\n exit(\"dvc pull failed\")\n os.system(\"rm -r .dvc .apt/usr/lib/dvc\")\n\n\nclass InputData(BaseModel):\n age: int = Field(example=60)\n workclass: str = Field(example=' Private')\n fnlgt: int = Field(example=132529)\n education: str = Field(example=' HS-grad')\n education_num: int = Field(example=9)\n marital_status: str = Field(example=' Married-civ-spouse')\n occupation: str = Field(example=' Craft-repair')\n relationship: str = Field(example=' Husband')\n race: str = Field(example=' White')\n sex: str = Field(example=' Male')\n capital_gain: int = Field(example=0)\n capital_loss: int = Field(example=0)\n hours_per_week: int = Field(example=40)\n native_country: str = Field(example='Other value')\n\n\n\napp = FastAPI()\n\n\n@app.get(\"/\")\nasync def greetings():\n return {'Hi': 'This a Census Bureau classifier'}\n\n\n@app.post('/predict')\nasync def predict(data: InputData):\n pipe = joblib.load('./models/model_pipe.pkl')\n x = dict()\n for key, value in data.dict().items():\n if key != 'salary':\n x[key] = [value]\n x = pd.DataFrame(x)\n\n x.columns = [col.strip().replace('-', '_') for col in x.columns]\n categorical_feats = x.select_dtypes(include=['object']).columns\n\n for feature in categorical_feats:\n x[feature] = x[feature].str.strip()\n x[feature].iloc[np.where(x.workclass == '?')] = np.nan\n x.native_country[x.native_country != 'United-States'] = 'Other_value'\n\n\n y_pred = inference(pipe, x)[0]\n\n tag = '<=50K' if y_pred == 0 else '>50K'\n\n return {'Answer': tag}\n", "repo_name": "joesider9/CensusBurreauClassifier", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1925, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "os.environ", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.system", "line_number": 11, "usage_type": "call"}, {"api_name": "os.system", "line_number": 12, "usage_type": "call"}, {"api_name": "os.system", "line_number": 13, "usage_type": "call"}, {"api_name": "os.system", "line_number": 15, "usage_type": "call"}, {"api_name": "pydantic.BaseModel", "line_number": 18, "usage_type": "name"}, {"api_name": "pydantic.Field", "line_number": 19, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 20, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 21, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 22, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 23, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 24, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 25, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 26, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 27, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 28, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 29, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 30, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 31, "usage_type": "call"}, {"api_name": "pydantic.Field", "line_number": 32, "usage_type": "call"}, {"api_name": "fastapi.FastAPI", "line_number": 36, "usage_type": "call"}, {"api_name": "joblib.load", "line_number": 46, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 51, "usage_type": "call"}]} +{"seq_id": "684328365", "text": "import argparse\nimport concurrent.futures\nimport csv\nimport datetime\nimport joblib\nimport numpy as np\nimport os\nimport pyaudio\n\nfrom classify import classify_sound\nfrom dBAlgorithm import get_rms, rms_to_decibels\nfrom hmmlearn import hmm\nfrom python_speech_features import mfcc\nfrom scipy.io import wavfile\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"device_index\",\n help=\"Corre el script getDeviceIndex.py para encontrar este dato.\",\n type=int)\nparser.add_argument(\"samp_rate\",\n help=\"Ingresa la taza de muestreo de tu dispositivo.\",\n type=int)\nparser.add_argument(\"seconds\", \n help=\"Ingresa cada cuantos segundos quieres que el dispositivo almacene informacion.\",\n type=int)\nparser.add_argument(\"modelPath\", \n help=\"Ingresa la ruta al modelo que deseas utilizar.\")\nargs = parser.parse_args()\n\nnp.seterr(divide = 'ignore')\n\n# Setup del archivo CSV\n\n# Setup del stream de PyAudio\nform_1 = pyaudio.paInt16 \nchans = 1 \nsamp_rate = args.samp_rate \nduration = args.seconds \nchunk = samp_rate * duration\ndev_index = args.device_index \n\n# Class to handle all HMM related processing\nclass HMMTrainer(object):\n def __init__(self, model_name='GaussianHMM', n_components=4, cov_type='diag', n_iter=1000):\n self.model_name = model_name\n self.n_components = n_components\n self.cov_type = cov_type\n self.n_iter = n_iter\n self.models = []\n\n if self.model_name == 'GaussianHMM':\n self.model = hmm.GaussianHMM(n_components=self.n_components, \n covariance_type=self.cov_type, n_iter=self.n_iter)\n else:\n raise TypeError('Invalid model type')\n\n # X is a 2D numpy array where each row is 13D\n def train(self, X):\n np.seterr(all='ignore')\n self.models.append(self.model.fit(X))\n\n # Run the model on input data\n def get_score(self, input_data):\n return self.model.score(input_data)\n\nif __name__ == '__main__':\n\n hmm_models = joblib.load(args.modelPath)\n audio = pyaudio.PyAudio()\n stream = audio.open(\n format = form_1,\n channels = chans,\n rate = samp_rate,\n input_device_index = dev_index,\n input = True,\n frames_per_buffer = chunk\n )\n\n with open('data.csv', 'a', newline='') as file:\n writer = csv.writer(file)\n try:\n with concurrent.futures.ThreadPoolExecutor() as executor:\n while True:\n print(\"Grabando...\")\n date = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n data = stream.read(chunk, exception_on_overflow=False)\n frames = np.frombuffer(data, dtype=\"int16\")\n rms = get_rms(data)\n dB = rms_to_decibels(rms,95)\n tag = None\n if(dB > 20):\n prediction = executor.submit(classify_sound, [frames, chans, audio, form_1, samp_rate, hmm_models]) \n writer.writerow([date, dB, prediction.result()])\n else:\n writer.writerow([date, dB, tag])\n except KeyboardInterrupt:\n pass\n\n stream.close()\n audio.terminate()", "repo_name": "RicardoBanuelos/CITEDI-AudioDataCollector", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 3397, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.seterr", "line_number": 30, "usage_type": "call"}, {"api_name": "pyaudio.paInt16", "line_number": 35, "usage_type": "attribute"}, {"api_name": "hmmlearn.hmm.GaussianHMM", "line_number": 52, "usage_type": "call"}, {"api_name": "hmmlearn.hmm", "line_number": 52, "usage_type": "name"}, {"api_name": "numpy.seterr", "line_number": 59, "usage_type": "call"}, {"api_name": "joblib.load", "line_number": 68, "usage_type": "call"}, {"api_name": "pyaudio.PyAudio", "line_number": 69, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 80, "usage_type": "call"}, {"api_name": "concurrent.futures.futures.ThreadPoolExecutor", "line_number": 82, "usage_type": "call"}, {"api_name": "concurrent.futures.futures", "line_number": 82, "usage_type": "attribute"}, {"api_name": "concurrent.futures", "line_number": 82, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 85, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 85, "usage_type": "attribute"}, {"api_name": "numpy.frombuffer", "line_number": 87, "usage_type": "call"}, {"api_name": "dBAlgorithm.get_rms", "line_number": 88, "usage_type": "call"}, {"api_name": "dBAlgorithm.rms_to_decibels", "line_number": 89, "usage_type": "call"}, {"api_name": "classify.classify_sound", "line_number": 92, "usage_type": "argument"}]} +{"seq_id": "6610029878", "text": "import pyomo.environ as pyo\nimport mpisppy.utils.sputils as sputils\nimport numpy as np\nimport itertools\nimport time\nimport sys\nimport mpisppy.spbase as spbase\n\nfrom mpisppy import MPI\nfrom pyomo.core.plugins.transform.discrete_vars import RelaxIntegerVars\nfrom mpisppy.utils.sputils import find_active_objective\nfrom mpisppy.utils.lshaped_cuts import LShapedCutGenerator\nfrom mpisppy.spopt import set_instance_retry\nfrom pyomo.core import (\n Objective, SOSConstraint, Constraint, Var\n)\nfrom pyomo.core.expr.visitor import identify_variables\nfrom pyomo.repn.standard_repn import generate_standard_repn\nfrom pyomo.core.expr.numeric_expr import LinearExpression\n\nclass LShapedMethod(spbase.SPBase):\n \"\"\" Base class for the L-shaped method for two-stage stochastic programs.\n\n Warning:\n This class explicitly assumes minimization.\n\n Args:\n options (dict):\n Dictionary of options. Possible (optional) options include\n\n - root_scenarios (list) - List of scenario names to include as\n part of the root problem (default [])\n - store_subproblems (boolean) - If True, the BendersDecomp object\n will maintain a dictionary containing the subproblems created by\n the BendersCutGenerator.\n - relax_root (boolean) - If True, the LP relaxation of the root\n problem is solved (i.e. integer variables in the root problem\n are relaxed).\n - scenario_creator_kwargs (dict) - Keyword args to pass to the scenario_creator.\n - valid_eta_lb (dict) - Dictionary mapping scenario names to valid\n lower bounds for the eta variables--i.e., a valid lower (outer)\n bound on the optimal objective value for each scenario. If none\n are provided, the lower bound is set to -sys.maxsize *\n scenario_prob, which may cause numerical errors.\n - indx_to_stage (dict) - Dictionary mapping the index of every\n variable in the model to the stage they belong to.\n all_scenario_names (list):\n List of all scenarios names present in the model (strings).\n scenario_creator (callable): \n Function which take a scenario name (string) and returns a\n Pyomo Concrete model with some things attached.\n scenario_denouement (callable, optional):\n Function which does post-processing and reporting.\n all_nodenames (list, optional): \n List of all node name (strings). Can be `None` for two-stage\n problems.\n mpicomm (MPI comm, optional):\n MPI communicator to use between all scenarios. Default is\n `MPI.COMM_WORLD`.\n scenario_creator_kwargs (dict, optional): \n Keyword arguments to pass to `scenario_creator`.\n \"\"\"\n def __init__(\n self, \n options,\n all_scenario_names,\n scenario_creator,\n scenario_denouement=None,\n all_nodenames=None,\n mpicomm=None,\n scenario_creator_kwargs=None,\n ):\n super().__init__(\n options,\n all_scenario_names,\n scenario_creator,\n scenario_denouement=scenario_denouement,\n all_nodenames=all_nodenames,\n mpicomm=mpicomm,\n scenario_creator_kwargs=scenario_creator_kwargs,\n )\n if self.multistage:\n raise Exception(\"LShaped does not currently support multiple stages\")\n self.options = options\n self.options_check()\n self.all_scenario_names = all_scenario_names\n self.root = None\n self.root_vars = None\n self.scenario_count = len(all_scenario_names)\n\n self.store_subproblems = False\n if \"store_subproblems\" in options:\n self.store_subproblems = options[\"store_subproblems\"]\n\n self.root_scenarios = None\n if \"root_scenarios\" in options:\n self.root_scenarios = options[\"root_scenarios\"]\n\n self.relax_root = False \n if \"relax_root\" in options:\n self.relax_root = options[\"relax_root\"]\n\n self.valid_eta_lb = None\n if \"valid_eta_lb\" in options:\n self.valid_eta_lb = options[\"valid_eta_lb\"]\n self.compute_eta_bound = False\n else: # fit the user does not provide a bound, compute one\n self.valid_eta_lb = { scen : (-sys.maxsize - 1) * 1. / len(self.all_scenario_names) \\\n for scen in self.all_scenario_names }\n self.compute_eta_bound = True\n\n if scenario_creator_kwargs is None:\n self.scenario_creator_kwargs = dict()\n else:\n self.scenario_creator_kwargs = scenario_creator_kwargs\n self.indx_to_stage = None\n self.has_valid_eta_lb = self.valid_eta_lb is not None\n self.has_root_scens = self.root_scenarios is not None\n\n if self.store_subproblems:\n self.subproblems = dict.fromkeys(scenario_names)\n\n def options_check(self):\n \"\"\" Check to ensure that the user-specified options are valid. Requried\n options are:\n\n - root_solver (string) - Solver to use for the root problem.\n - sp_solver (string) - Solver to use for the subproblems.\n \"\"\"\n required = [\"root_solver\", \"sp_solver\"]\n if \"root_solver_options\" not in self.options:\n self.options[\"root_solver_options\"] = dict()\n if \"sp_solver_options\" not in self.options:\n self.options[\"sp_solver_options\"] = dict()\n self._options_check(required, self.options)\n\n def _add_root_etas(self, root, index):\n def _eta_bounds(m, s):\n return (self.valid_eta_lb[s],None)\n root.eta = pyo.Var(index, within=pyo.Reals, bounds=_eta_bounds)\n\n def _create_root_no_scenarios(self):\n\n # using the first scenario as a basis\n root = self.scenario_creator(\n self.all_scenario_names[0], **self.scenario_creator_kwargs\n )\n\n if self.relax_root:\n RelaxIntegerVars().apply_to(root)\n\n nonant_list, nonant_ids = _get_nonant_ids(root)\n\n self.root_vars = nonant_list\n\n for constr_data in list(itertools.chain(\n root.component_data_objects(SOSConstraint, active=True, descend_into=True)\n , root.component_data_objects(Constraint, active=True, descend_into=True))):\n if not _first_stage_only(constr_data, nonant_ids):\n _del_con(constr_data)\n\n # delete the second stage variables\n for var in list(root.component_data_objects(Var, active=True, descend_into=True)):\n if id(var) not in nonant_ids:\n _del_var(var)\n\n self._add_root_etas(root, self.all_scenario_names)\n\n # pulls the current objective expression, adds in the eta variables,\n # and removes the second stage variables from the expression\n obj = find_active_objective(root)\n\n repn = generate_standard_repn(obj.expr, quadratic=True)\n if len(repn.nonlinear_vars) > 0:\n raise ValueError(\"LShaped does not support models with nonlinear objective functions\")\n\n linear_vars = list()\n linear_coefs = list()\n quadratic_vars = list()\n quadratic_coefs = list()\n ## we'll assume the constant is part of stage 1 (wlog it is), just\n ## like the first-stage bits of the objective\n constant = repn.constant \n\n ## only keep the first stage variables in the objective\n for coef, var in zip(repn.linear_coefs, repn.linear_vars):\n id_var = id(var)\n if id_var in nonant_ids:\n linear_vars.append(var)\n linear_coefs.append(coef)\n for coef, (x,y) in zip(repn.quadratic_coefs, repn.quadratic_vars):\n id_x = id(x)\n id_y = id(y)\n if id_x in nonant_ids and id_y in nonant_ids:\n quadratic_coefs.append(coef)\n quadratic_vars.append((x,y))\n\n # checks if model sense is max, if so negates the objective\n if not self.is_minimizing:\n for i,coef in enumerate(linear_coefs):\n linear_coefs[i] = -coef\n for i,coef in enumerate(quadratic_coefs):\n quadratic_coefs[i] = -coef\n\n # add the etas\n for var in root.eta.values():\n linear_vars.append(var)\n linear_coefs.append(1)\n\n expr = LinearExpression(constant=constant, linear_coefs=linear_coefs,\n linear_vars=linear_vars)\n if quadratic_coefs:\n expr += pyo.quicksum(\n (coef*x*y for coef,(x,y) in zip(quadratic_coefs, quadratic_vars))\n )\n\n root.del_component(obj)\n\n # set root objective function\n root.obj = pyo.Objective(expr=expr, sense=pyo.minimize)\n\n self.root = root\n\n def _create_root_with_scenarios(self):\n\n ef_scenarios = self.root_scenarios\n\n ## we want the correct probabilities to be set when\n ## calling create_EF\n if len(ef_scenarios) > 1:\n def scenario_creator_wrapper(name, **creator_options):\n scenario = self.scenario_creator(name, **creator_options)\n if not hasattr(scenario, '_mpisppy_probability'):\n scenario._mpisppy_probability = 1./len(self.all_scenario_names)\n return scenario\n root = sputils.create_EF(\n ef_scenarios,\n scenario_creator_wrapper,\n scenario_creator_kwargs=self.scenario_creator_kwargs,\n )\n\n nonant_list, nonant_ids = _get_nonant_ids_EF(root)\n else:\n root = self.scenario_creator(\n ef_scenarios[0],\n **self.scenario_creator_kwargs,\n )\n if not hasattr(root, '_mpisppy_probability')\\\n or root._mpisppy_probability == \"uniform\":\n root._mpisppy_probability = 1./len(self.all_scenario_names)\n\n nonant_list, nonant_ids = _get_nonant_ids(root)\n\n self.root_vars = nonant_list\n\n # creates the eta variables for scenarios that are NOT selected to be\n # included in the root problem\n eta_indx = [scenario_name for scenario_name in self.all_scenario_names\n if scenario_name not in self.root_scenarios]\n self._add_root_etas(root, eta_indx)\n\n obj = find_active_objective(root)\n\n repn = generate_standard_repn(obj.expr, quadratic=True)\n if len(repn.nonlinear_vars) > 0:\n raise ValueError(\"LShaped does not support models with nonlinear objective functions\")\n linear_vars = list(repn.linear_vars)\n linear_coefs = list(repn.linear_coefs)\n quadratic_coefs = list(repn.quadratic_coefs)\n\n # adjust coefficients by scenario/bundle probability\n scen_prob = root._mpisppy_probability\n for i,var in enumerate(repn.linear_vars):\n if id(var) not in nonant_ids:\n linear_coefs[i] *= scen_prob\n\n for i,(x,y) in enumerate(repn.quadratic_vars):\n # only multiply through once\n if id(x) not in nonant_ids:\n quadratic_coefs[i] *= scen_prob\n elif id(y) not in nonant_ids:\n quadratic_coefs[i] *= scen_prob\n\n # NOTE: the LShaped code negates the objective, so\n # we do the same here for consistency\n if not self.is_minimizing:\n for i,coef in enumerate(linear_coefs):\n linear_coefs[i] = -coef\n for i,coef in enumerate(quadratic_coefs):\n quadratic_coefs[i] = -coef\n\n # add the etas\n for var in root.eta.values():\n linear_vars.append(var)\n linear_coefs.append(1)\n\n expr = LinearExpression(constant=repn.constant, linear_coefs=linear_coefs,\n linear_vars=linear_vars)\n if repn.quadratic_vars:\n expr += pyo.quicksum(\n (coef*x*y for coef,(x,y) in zip(quadratic_coefs, repn.quadratic_vars))\n )\n\n root.del_component(obj)\n\n # set root objective function\n root.obj = pyo.Objective(expr=expr, sense=pyo.minimize)\n\n self.root = root\n\n def _create_shadow_root(self):\n\n root = pyo.ConcreteModel()\n\n arb_scen = self.local_scenarios[self.local_scenario_names[0]]\n nonants = arb_scen._mpisppy_node_list[0].nonant_vardata_list\n\n root_vars = list()\n for v in nonants:\n nonant_shadow = pyo.Var(name=v.name)\n root.add_component(v.name, nonant_shadow)\n root_vars.append(nonant_shadow)\n \n if self.has_root_scens:\n eta_indx = [scenario_name for scenario_name in self.all_scenario_names\n if scenario_name not in self.root_scenarios]\n else:\n eta_indx = self.all_scenario_names\n self._add_root_etas(root, eta_indx)\n\n root.obj = None\n self.root = root\n self.root_vars = root_vars\n\n def set_eta_bounds(self):\n if self.compute_eta_bound:\n ## for scenarios not in self.local_scenarios, these will be a large negative number\n this_etas_lb = np.fromiter((self.valid_eta_lb[scen] for scen in self.all_scenario_names),\n float, count=len(self.all_scenario_names))\n\n all_etas_lb = np.empty_like(this_etas_lb)\n\n self.mpicomm.Allreduce(this_etas_lb, all_etas_lb, op=MPI.MAX)\n\n for idx, s in enumerate(self.all_scenario_names):\n self.valid_eta_lb[s] = all_etas_lb[idx]\n \n # root may not have etas for every scenarios\n for s, v in self.root.eta.items():\n v.setlb(self.valid_eta_lb[s])\n\n def create_root(self):\n \"\"\" creates a ConcreteModel from one of the problem scenarios then\n modifies the model to serve as the root problem \n \"\"\"\n if self.cylinder_rank == 0:\n if self.has_root_scens:\n self._create_root_with_scenarios()\n else:\n self._create_root_no_scenarios()\n else: \n ## if we're not rank0, just create a root to\n ## hold the nonants and etas; rank0 will do \n ## the optimizing\n self._create_shadow_root()\n \n def attach_nonant_var_map(self, scenario_name):\n instance = self.local_scenarios[scenario_name]\n\n subproblem_to_root_vars_map = pyo.ComponentMap()\n for var, rvar in zip(instance._mpisppy_data.nonant_indices.values(), self.root_vars):\n if var.name not in rvar.name:\n raise Exception(\"Error: Complicating variable mismatch, sub-problem variables changed order\")\n subproblem_to_root_vars_map[var] = rvar \n\n # this is for interefacing with PH code\n instance._mpisppy_model.subproblem_to_root_vars_map = subproblem_to_root_vars_map\n\n def create_subproblem(self, scenario_name):\n \"\"\" the subproblem creation function passed into the\n BendersCutsGenerator \n \"\"\"\n instance = self.local_scenarios[scenario_name]\n\n nonant_list, nonant_ids = _get_nonant_ids(instance) \n\n # NOTE: since we use generate_standard_repn below, we need\n # to unfix any nonants so they'll properly appear\n # in the objective\n fixed_nonants = [ var for var in nonant_list if var.fixed ]\n for var in fixed_nonants:\n var.fixed = False\n\n # pulls the scenario objective expression, removes the first stage variables, and sets the new objective\n obj = find_active_objective(instance)\n\n if not hasattr(instance, \"_mpisppy_probability\"):\n instance._mpisppy_probability = 1. / self.scenario_count\n _mpisppy_probability = instance._mpisppy_probability\n\n repn = generate_standard_repn(obj.expr, quadratic=True)\n if len(repn.nonlinear_vars) > 0:\n raise ValueError(\"LShaped does not support models with nonlinear objective functions\")\n\n linear_vars = list()\n linear_coefs = list()\n quadratic_vars = list()\n quadratic_coefs = list()\n ## we'll assume the constant is part of stage 1 (wlog it is), just\n ## like the first-stage bits of the objective\n constant = repn.constant \n\n ## only keep the second stage variables in the objective\n for coef, var in zip(repn.linear_coefs, repn.linear_vars):\n id_var = id(var)\n if id_var not in nonant_ids:\n linear_vars.append(var)\n linear_coefs.append(_mpisppy_probability*coef)\n for coef, (x,y) in zip(repn.quadratic_coefs, repn.quadratic_vars):\n id_x = id(x)\n id_y = id(y)\n if id_x not in nonant_ids or id_y not in nonant_ids:\n quadratic_coefs.append(_mpisppy_probability*coef)\n quadratic_vars.append((x,y))\n\n # checks if model sense is max, if so negates the objective\n if not self.is_minimizing:\n for i,coef in enumerate(linear_coefs):\n linear_coefs[i] = -coef\n for i,coef in enumerate(quadratic_coefs):\n quadratic_coefs[i] = -coef\n\n expr = LinearExpression(constant=constant, linear_coefs=linear_coefs,\n linear_vars=linear_vars)\n if quadratic_coefs:\n expr += pyo.quicksum(\n (coef*x*y for coef,(x,y) in zip(quadratic_coefs, quadratic_vars))\n )\n\n instance.del_component(obj)\n\n # set subproblem objective function\n instance.obj = pyo.Objective(expr=expr, sense=pyo.minimize)\n\n ## need to do this here for validity if computing the eta bound\n if self.relax_root:\n # relaxes any integrality constraints for the subproblem\n RelaxIntegerVars().apply_to(instance)\n\n if self.compute_eta_bound:\n for var in fixed_nonants:\n var.fixed = True\n opt = pyo.SolverFactory(self.options[\"sp_solver\"])\n if self.options[\"sp_solver_options\"]:\n for k,v in self.options[\"sp_solver_options\"].items():\n opt.options[k] = v\n\n if sputils.is_persistent(opt):\n set_instance_retry(instance, opt, scenario_name)\n res = opt.solve(tee=False)\n else:\n res = opt.solve(instance, tee=False)\n\n eta_lb = res.Problem[0].Lower_bound\n\n self.valid_eta_lb[scenario_name] = eta_lb\n\n # if not done above\n if not self.relax_root:\n # relaxes any integrality constraints for the subproblem\n RelaxIntegerVars().apply_to(instance)\n\n # iterates through constraints and removes first stage constraints from the model\n # the id dict is used to improve the speed of identifying the stage each variables belongs to\n for constr_data in list(itertools.chain(\n instance.component_data_objects(SOSConstraint, active=True, descend_into=True)\n , instance.component_data_objects(Constraint, active=True, descend_into=True))):\n if _first_stage_only(constr_data, nonant_ids):\n _del_con(constr_data)\n\n # creates the sub map to remove first stage variables from objective expression\n complicating_vars_map = pyo.ComponentMap()\n subproblem_to_root_vars_map = pyo.ComponentMap()\n\n # creates the complicating var map that connects the first stage variables in the sub problem to those in\n # the root problem -- also set the bounds on the subproblem root vars to be none for better cuts\n for var, rvar in zip(nonant_list, self.root_vars):\n if var.name not in rvar.name: # rvar.name may be part of a bundle\n raise Exception(\"Error: Complicating variable mismatch, sub-problem variables changed order\")\n complicating_vars_map[rvar] = var\n subproblem_to_root_vars_map[var] = rvar \n\n # these are already enforced in the root\n # don't need to be enfored in the subproblems\n var.setlb(None)\n var.setub(None)\n var.fixed = False\n\n # this is for interefacing with PH code\n instance._mpisppy_model.subproblem_to_root_vars_map = subproblem_to_root_vars_map\n\n if self.store_subproblems:\n self.subproblems[scenario_name] = instance\n\n return instance, complicating_vars_map\n\n def lshaped_algorithm(self, converger=None):\n \"\"\" function that runs the lshaped.py algorithm\n \"\"\"\n if converger:\n converger = converger(self, self.cylinder_rank, self.n_proc)\n max_iter = 30\n if \"max_iter\" in self.options:\n max_iter = self.options[\"max_iter\"]\n tol = 1e-8\n if \"tol\" in self.options:\n tol = self.options[\"tol\"]\n verbose = True\n if \"verbose\" in self.options:\n verbose = self.options[\"verbose\"]\n root_solver = self.options[\"root_solver\"]\n sp_solver = self.options[\"sp_solver\"]\n\n # creates the root problem\n self.create_root()\n m = self.root\n assert hasattr(m, \"obj\")\n\n # prevents problems from first stage variables becoming unconstrained\n # after processing\n _init_vars(self.root_vars)\n\n # sets up the BendersCutGenerator object\n m.bender = LShapedCutGenerator()\n\n m.bender.set_input(root_vars=self.root_vars, tol=tol, comm=self.mpicomm)\n\n # let the cut generator know who's using it, probably should check that this is called after set input\n m.bender.set_ls(self)\n\n # set the eta variables, removing this from the add_suproblem function so we can\n\n # Pass all the scenarios in the problem to bender.add_subproblem\n # and let it internally handle which ranks get which scenarios\n if self.has_root_scens:\n sub_scenarios = [\n scenario_name for scenario_name in self.local_scenario_names\n if scenario_name not in self.root_scenarios\n ]\n else:\n sub_scenarios = self.local_scenario_names\n for scenario_name in self.local_scenario_names:\n if scenario_name in sub_scenarios:\n subproblem_fn_kwargs = dict()\n subproblem_fn_kwargs['scenario_name'] = scenario_name\n m.bender.add_subproblem(\n subproblem_fn=self.create_subproblem,\n subproblem_fn_kwargs=subproblem_fn_kwargs,\n root_eta=m.eta[scenario_name],\n subproblem_solver=sp_solver,\n subproblem_solver_options=self.options[\"sp_solver_options\"]\n )\n else:\n self.attach_nonant_var_map(scenario_name)\n\n # set the eta bounds if computed\n # by self.create_subproblem\n self.set_eta_bounds()\n\n if self.cylinder_rank == 0:\n opt = pyo.SolverFactory(root_solver)\n if opt is None:\n raise Exception(\"Error: Failed to Create Master Solver\")\n\n # set options\n for k,v in self.options[\"root_solver_options\"].items():\n opt.options[k] = v\n\n is_persistent = sputils.is_persistent(opt)\n if is_persistent:\n set_instance_retry(m, opt, \"root\")\n\n t = time.time()\n res, t1, t2 = None, None, None\n\n # benders solve loop, repeats the benders root - subproblem\n # loop until either a no more cuts can are generated\n # or the maximum iterations limit is reached\n for self.iter in range(max_iter):\n if verbose and self.cylinder_rank == 0:\n if self.iter > 0:\n print(\"Current Iteration:\", self.iter + 1, \"Time Elapsed:\", \"%7.2f\" % (time.time() - t), \"Time Spent on Last Master:\", \"%7.2f\" % t1,\n \"Time Spent Generating Last Cut Set:\", \"%7.2f\" % t2, \"Current Objective:\", \"%7.2f\" % m.obj.expr())\n else:\n print(\"Current Iteration:\", self.iter + 1, \"Time Elapsed:\", \"%7.2f\" % (time.time() - t), \"Current Objective: -Inf\")\n t1 = time.time()\n x_vals = np.zeros(len(self.root_vars))\n eta_vals = np.zeros(self.scenario_count)\n outer_bound = np.zeros(1)\n if self.cylinder_rank == 0:\n if is_persistent:\n res = opt.solve(tee=False)\n else:\n res = opt.solve(m, tee=False)\n # LShaped is always minimizing\n outer_bound[0] = res.Problem[0].Lower_bound\n for i, var in enumerate(self.root_vars):\n x_vals[i] = var.value\n for i, eta in enumerate(m.eta.values()):\n eta_vals[i] = eta.value\n\n self.mpicomm.Bcast(x_vals, root=0)\n self.mpicomm.Bcast(eta_vals, root=0)\n self.mpicomm.Bcast(outer_bound, root=0)\n\n if self.is_minimizing:\n self._LShaped_bound = outer_bound[0]\n else:\n # LShaped is always minimizing, so negate\n # the outer bound for sharing broadly\n self._LShaped_bound = -outer_bound[0]\n\n if self.cylinder_rank != 0:\n for i, var in enumerate(self.root_vars):\n var._value = x_vals[i]\n for i, eta in enumerate(m.eta.values()):\n eta._value = eta_vals[i]\n t1 = time.time() - t1\n\n # The hub object takes precedence over the converger\n # We'll send the nonants now, and check for a for\n # convergence\n if self.spcomm:\n self.spcomm.sync(send_nonants=True)\n if self.spcomm.is_converged():\n break\n\n t2 = time.time()\n cuts_added = m.bender.generate_cut()\n t2 = time.time() - t2\n if self.cylinder_rank == 0:\n for c in cuts_added:\n if is_persistent:\n opt.add_constraint(c)\n if verbose and len(cuts_added) == 0:\n print(\n f\"Converged in {self.iter+1} iterations.\\n\"\n f\"Total Time Elapsed: {time.time()-t:7.2f} \"\n f\"Time Spent on Last Master: {t1:7.2f} \"\n f\"Time spent verifying second stage: {t2:7.2f} \"\n f\"Final Objective: {m.obj.expr():7.2f}\"\n )\n self.first_stage_solution_available = True\n self.tree_solution_available = True\n break\n if verbose and self.iter == max_iter - 1:\n print(\"WARNING MAX ITERATION LIMIT REACHED !!! \")\n else:\n if len(cuts_added) == 0:\n break\n # The hub object takes precedence over the converger\n if self.spcomm:\n self.spcomm.sync(send_nonants=False)\n if self.spcomm.is_converged():\n break\n if converger:\n converger.convergence_value()\n if converger.is_converged():\n if verbose and self.cylinder_rank == 0:\n print(\n f\"Converged to user criteria in {self.iter+1} iterations.\\n\"\n f\"Total Time Elapsed: {time.time()-t:7.2f} \"\n f\"Time Spent on Last Master: {t1:7.2f} \"\n f\"Time spent verifying second stage: {t2:7.2f} \"\n f\"Final Objective: {m.obj.expr():7.2f}\"\n )\n break\n return res\n\ndef _del_con(c):\n parent = c.parent_component()\n if parent.is_indexed():\n parent.__delitem__(c.index())\n else:\n assert parent is c\n c.parent_block().del_component(c)\n\ndef _del_var(v):\n parent = v.parent_component()\n if parent.is_indexed():\n parent.__delitem__(v.index())\n else:\n assert parent is v\n block = v.parent_block()\n block.del_component(v)\n\ndef _get_nonant_ids(instance):\n assert len(instance._mpisppy_node_list) == 1\n # set comprehension\n nonant_list = instance._mpisppy_node_list[0].nonant_vardata_list\n return nonant_list, { id(var) for var in nonant_list }\n\ndef _get_nonant_ids_EF(instance):\n assert len(instance._mpisppy_data.nlens) == 1\n\n ndn, nlen = list(instance._mpisppy_data.nlens.items())[0]\n\n ## this is for the cut variables, so we just need (and want)\n ## exactly one set of them\n nonant_list = list(instance.ref_vars[ndn,i] for i in range(nlen))\n\n ## this is for adjusting the objective, so needs all the nonants\n ## in the EF\n snames = instance._ef_scenario_names\n\n nonant_ids = set()\n for s in snames:\n nonant_ids.update( (id(v) for v in \\\n getattr(instance, s)._mpisppy_node_list[0].nonant_vardata_list)\n )\n return nonant_list, nonant_ids \n\ndef _first_stage_only(constr_data, nonant_ids):\n \"\"\" iterates through the constraint in a scenario and returns if it only\n has first stage variables\n \"\"\"\n for var in identify_variables(constr_data.body):\n if id(var) not in nonant_ids: \n return False\n return True\n\ndef _init_vars(varlist):\n '''\n for every pyomo var in varlist without a value,\n sets it to the lower bound (if it exists), or\n the upper bound (if it exists, and the lower bound\n does note) or 0 (if neither bound exists).\n '''\n value = pyo.value\n for var in varlist:\n if var.value is not None:\n continue\n if var.lb is not None:\n var.set_value(value(var.lb))\n elif var.ub is not None:\n var.set_value(value(var.ub))\n else:\n var.set_value(0)\n\n\n\ndef main():\n import mpisppy.tests.examples.farmer as ref\n import os\n # Turn off output from all ranks except rank 1\n if MPI.COMM_WORLD.Get_rank() != 0:\n sys.stdout = open(os.devnull, 'w')\n scenario_names = ['scen' + str(i) for i in range(3)]\n bounds = {i:-432000 for i in scenario_names}\n options = {\n \"root_solver\": \"gurobi_persistent\",\n \"sp_solver\": \"gurobi_persistent\",\n \"sp_solver_options\" : {\"threads\" : 1},\n \"valid_eta_lb\": bounds,\n \"max_iter\": 10,\n }\n\n ls = LShapedMethod(options, scenario_names, ref.scenario_creator)\n res = ls.lshaped_algorithm()\n if ls.cylinder_rank == 0:\n print(res)\n\n\nif __name__ == '__main__':\n main()\n", "repo_name": "Pyomo/mpi-sppy", "sub_path": "mpisppy/opt/lshaped.py", "file_name": "lshaped.py", "file_ext": "py", "file_size_in_byte": 30853, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 47, "dataset": "github-code", "pt": "20", "api": [{"api_name": "mpisppy.spbase.SPBase", "line_number": 21, "usage_type": "attribute"}, {"api_name": "mpisppy.spbase", "line_number": 21, "usage_type": "name"}, {"api_name": "sys.maxsize", "line_number": 108, "usage_type": "attribute"}, {"api_name": "pyomo.environ.Var", "line_number": 140, "usage_type": "call"}, {"api_name": "pyomo.environ", "line_number": 140, "usage_type": "name"}, {"api_name": "pyomo.environ.Reals", "line_number": 140, "usage_type": "attribute"}, {"api_name": "pyomo.core.plugins.transform.discrete_vars.RelaxIntegerVars", "line_number": 150, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 156, "usage_type": "call"}, {"api_name": "pyomo.core.SOSConstraint", "line_number": 157, "usage_type": "argument"}, {"api_name": "pyomo.core.Constraint", "line_number": 158, "usage_type": "argument"}, {"api_name": "pyomo.core.Var", "line_number": 163, "usage_type": "argument"}, {"api_name": "mpisppy.utils.sputils.find_active_objective", "line_number": 171, "usage_type": "call"}, {"api_name": "pyomo.repn.standard_repn.generate_standard_repn", "line_number": 173, "usage_type": "call"}, {"api_name": "pyomo.core.expr.numeric_expr.LinearExpression", "line_number": 210, "usage_type": "call"}, {"api_name": "pyomo.environ.quicksum", "line_number": 213, "usage_type": "call"}, {"api_name": "pyomo.environ", "line_number": 213, "usage_type": "name"}, {"api_name": "pyomo.environ.Objective", "line_number": 220, "usage_type": "call"}, {"api_name": "pyomo.environ", "line_number": 220, "usage_type": "name"}, {"api_name": "pyomo.environ.minimize", "line_number": 220, "usage_type": "attribute"}, {"api_name": "mpisppy.utils.sputils.create_EF", "line_number": 236, "usage_type": "call"}, {"api_name": "mpisppy.utils.sputils", "line_number": 236, "usage_type": "name"}, {"api_name": "mpisppy.utils.sputils.find_active_objective", "line_number": 262, "usage_type": "call"}, {"api_name": "pyomo.repn.standard_repn.generate_standard_repn", "line_number": 264, "usage_type": "call"}, {"api_name": "pyomo.core.expr.numeric_expr.LinearExpression", "line_number": 297, "usage_type": "call"}, {"api_name": "pyomo.environ.quicksum", "line_number": 300, "usage_type": "call"}, {"api_name": "pyomo.environ", "line_number": 300, "usage_type": "name"}, {"api_name": "pyomo.environ.Objective", "line_number": 307, "usage_type": "call"}, {"api_name": "pyomo.environ", "line_number": 307, "usage_type": "name"}, {"api_name": "pyomo.environ.minimize", "line_number": 307, "usage_type": "attribute"}, {"api_name": "pyomo.environ.ConcreteModel", "line_number": 313, "usage_type": "call"}, {"api_name": "pyomo.environ", "line_number": 313, "usage_type": "name"}, {"api_name": "pyomo.environ.Var", "line_number": 320, "usage_type": "call"}, {"api_name": "pyomo.environ", "line_number": 320, "usage_type": "name"}, {"api_name": "numpy.fromiter", "line_number": 338, "usage_type": "call"}, {"api_name": "numpy.empty_like", "line_number": 341, "usage_type": "call"}, {"api_name": "mpisppy.MPI.MAX", "line_number": 343, "usage_type": "attribute"}, {"api_name": "mpisppy.MPI", "line_number": 343, "usage_type": "name"}, {"api_name": "pyomo.environ.ComponentMap", "line_number": 370, "usage_type": "call"}, {"api_name": "pyomo.environ", "line_number": 370, "usage_type": "name"}, {"api_name": "mpisppy.utils.sputils.find_active_objective", "line_number": 395, "usage_type": "call"}, {"api_name": "pyomo.repn.standard_repn.generate_standard_repn", "line_number": 401, "usage_type": "call"}, {"api_name": "pyomo.core.expr.numeric_expr.LinearExpression", "line_number": 433, "usage_type": "call"}, {"api_name": "pyomo.environ.quicksum", "line_number": 436, "usage_type": "call"}, {"api_name": "pyomo.environ", "line_number": 436, "usage_type": "name"}, {"api_name": "pyomo.environ.Objective", "line_number": 443, "usage_type": "call"}, {"api_name": "pyomo.environ", "line_number": 443, "usage_type": "name"}, {"api_name": "pyomo.environ.minimize", "line_number": 443, "usage_type": "attribute"}, {"api_name": "pyomo.core.plugins.transform.discrete_vars.RelaxIntegerVars", "line_number": 448, "usage_type": "call"}, {"api_name": "pyomo.environ.SolverFactory", "line_number": 453, "usage_type": "call"}, {"api_name": "pyomo.environ", "line_number": 453, "usage_type": "name"}, {"api_name": "mpisppy.utils.sputils.is_persistent", "line_number": 458, "usage_type": "call"}, {"api_name": "mpisppy.utils.sputils", "line_number": 458, "usage_type": "name"}, {"api_name": "mpisppy.spopt.set_instance_retry", "line_number": 459, "usage_type": "call"}, {"api_name": "pyomo.core.plugins.transform.discrete_vars.RelaxIntegerVars", "line_number": 471, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 475, "usage_type": "call"}, {"api_name": "pyomo.core.SOSConstraint", "line_number": 476, "usage_type": "argument"}, {"api_name": "pyomo.core.Constraint", "line_number": 477, "usage_type": "argument"}, {"api_name": "pyomo.environ.ComponentMap", "line_number": 482, "usage_type": "call"}, {"api_name": "pyomo.environ", "line_number": 482, "usage_type": "name"}, {"api_name": "pyomo.environ.ComponentMap", "line_number": 483, "usage_type": "call"}, {"api_name": "pyomo.environ", "line_number": 483, "usage_type": "name"}, {"api_name": "mpisppy.utils.lshaped_cuts.LShapedCutGenerator", "line_number": 534, "usage_type": "call"}, {"api_name": "pyomo.environ.SolverFactory", "line_number": 571, "usage_type": "call"}, {"api_name": "pyomo.environ", "line_number": 571, "usage_type": "name"}, {"api_name": "mpisppy.utils.sputils.is_persistent", "line_number": 579, "usage_type": "call"}, {"api_name": "mpisppy.utils.sputils", "line_number": 579, "usage_type": "name"}, {"api_name": "mpisppy.spopt.set_instance_retry", "line_number": 581, "usage_type": "call"}, {"api_name": "time.time", "line_number": 583, "usage_type": "call"}, {"api_name": "time.time", "line_number": 592, "usage_type": "call"}, {"api_name": "time.time", "line_number": 595, "usage_type": "call"}, {"api_name": "time.time", "line_number": 596, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 597, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 598, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 599, "usage_type": "call"}, {"api_name": "time.time", "line_number": 628, "usage_type": "call"}, {"api_name": "time.time", "line_number": 638, "usage_type": "call"}, {"api_name": "time.time", "line_number": 640, "usage_type": "call"}, {"api_name": "time.time", "line_number": 648, "usage_type": "call"}, {"api_name": "time.time", "line_number": 672, "usage_type": "call"}, {"api_name": "pyomo.core.expr.visitor.identify_variables", "line_number": 727, "usage_type": "call"}, {"api_name": "pyomo.environ.value", "line_number": 739, "usage_type": "attribute"}, {"api_name": "pyomo.environ", "line_number": 739, "usage_type": "name"}, {"api_name": "mpisppy.MPI.COMM_WORLD.Get_rank", "line_number": 756, "usage_type": "call"}, {"api_name": "mpisppy.MPI.COMM_WORLD", "line_number": 756, "usage_type": "attribute"}, {"api_name": "mpisppy.MPI", "line_number": 756, "usage_type": "name"}, {"api_name": "sys.stdout", "line_number": 757, "usage_type": "attribute"}, {"api_name": "os.devnull", "line_number": 757, "usage_type": "attribute"}, {"api_name": "mpisppy.tests.examples.farmer.scenario_creator", "line_number": 768, "usage_type": "attribute"}, {"api_name": "mpisppy.tests.examples.farmer", "line_number": 768, "usage_type": "name"}]} +{"seq_id": "70403763583", "text": "from selenium import webdriver\r\nimport time\r\nimport unittest\r\nimport sys\r\nimport os\r\nsys.path.append(os.path.join(os.path.dirname(__file__), \"...\", \"...\"))\r\nfrom Pages.loginPage import LoginPage\r\nfrom Pages.searchEncounterPage import SearchEncounterPage\r\nimport HtmlTestRunner\r\n\r\n\r\nclass LoginTest(unittest.TestCase):\r\n\r\n @classmethod\r\n def setUpClass(cls):\r\n cls.driver = webdriver.Chrome(\"C:\\Program Files (x86)\\chromedriver.exe\")\r\n cls.driver.implicitly_wait(10)\r\n cls.driver.maximize_window()\r\n\r\n def test_login_valid(self):\r\n driver = self.driver\r\n driver.get(\"https://lynx.wildbook.org/login.jsp\")\r\n login = LoginPage(driver)\r\n login.enter_username(\"ENTER_YOUR_USER\")\r\n login.enter_password(\"ENTER YOUR PASSWORD\")\r\n login.click_login()\r\n current_url = login.check_url()\r\n self.assertTrue(current_url == \"https://lynx.wildbook.org/welcome.jsp\")\r\n\r\n # searchencounter = SearchEncounterPage(driver)\r\n # searchencounter.click_location_filter_text()\r\n # searchencounter.set_location_filter_text_locationid(\"CATSMO\")\r\n # searchencounter.click_search()\r\n\r\n\r\n # self.driver.find_element_by_name(\"username\").send_keys(\"userR\") # we enter the password\r\n # self.driver.find_element_by_name(\"password\").send_keys(\"123456\") # we enter the password\r\n # self.driver.find_element_by_id(\"logMeIn\").click() # click in login\r\n\r\n @unittest.skip(\"we are skipping this test\")\r\n def test_login_valid_invalid_user(self):\r\n driver = self.driver\r\n driver.get(\"https://lynx.wildbook.org/login.jsp\")\r\n login = LoginPage(driver)\r\n login.enter_username(\"ENTERYOURUSER\")\r\n login.enter_password(\"PASSWORD\")\r\n login.click_login()\r\n welcome_url = \"https://lynx.wildbook.org/welcome.jsp\"\r\n current_url = login.check_url()\r\n self.assertEqual(welcome_url, current_url)\r\n\r\n #driver.current_url\r\n\r\n\r\n @classmethod\r\n def tearDownClass(cls): #will run after all the tests are completed\r\n cls.driver.close()\r\n cls.driver.quit()\r\n print(\"Test Completed\")\r\n\r\nif __name__ == '__main__':\r\n unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output=\"C:/Users/kowarika/PycharmProjects/wildbookEncounters/Reports\"))\r\n", "repo_name": "kowariknando/wildbookEncounters", "sub_path": "chrome-data/BrowserMetrics/Tests/login.py", "file_name": "login.py", "file_ext": "py", "file_size_in_byte": 2318, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sys.path.append", "line_number": 6, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 6, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 12, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 16, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 16, "usage_type": "name"}, {"api_name": "Pages.loginPage.LoginPage", "line_number": 23, "usage_type": "call"}, {"api_name": "Pages.loginPage.LoginPage", "line_number": 44, "usage_type": "call"}, {"api_name": "unittest.skip", "line_number": 40, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 62, "usage_type": "call"}, {"api_name": "HtmlTestRunner.HTMLTestRunner", "line_number": 62, "usage_type": "call"}]} +{"seq_id": "40211102363", "text": "from flask import Flask, render_template, request\r\nimport requests\r\nfrom bs4 import BeautifulSoup as bs\r\nfrom urllib.request import urlopen as uReq\r\nimport pymongo\r\n\r\napp=Flask(__name__)\r\n@app.route('/',methods=['GET'])\r\ndef homepage():\r\n return render_template('index.html')\r\n@app.route('/search',methods=['POST'])\r\ndef search():\r\n if request.method=='POST':\r\n Link=request.form['locations']\r\n restraunts_links = Link+\"/reviews\"\r\n header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 RuxitSynthetic/1.0 v6392933410 t38550 ath9b965f92 altpub'}\r\n final_restarauntlink = requests.get(restraunts_links, headers=header)\r\n final_res_html = bs(final_restarauntlink.text, \"html.parser\")\r\n fetch_reviws_page = final_res_html.find_all('div', {\"class\": \"sc-1y3q50z-3 eiMLBn\"})\r\n review_box = fetch_reviws_page[2]\r\n reviews_box_link = review_box.span.a['href']\r\n entering_into_reviews = requests.get(reviews_box_link, headers=header)\r\n soup_reviews = bs(entering_into_reviews.text, \"html.parser\")\r\n comment = soup_reviews.find_all('p', {\"class\": \"sc-1hez2tp-0 sc-jdeSqf kGmIUp\"})\r\n print(comment)\r\n empty_list = []\r\n for reviews in comment:\r\n lissts = reviews.text\r\n mydict = {\"Name\": \"\", \"Rating\": \"\",\"Comment\": lissts}\r\n empty_list.append(mydict)\r\n\r\n return render_template(\"results.html\",reviews=empty_list)\r\n\r\n\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n app.run(debug=True)", "repo_name": "harsh0703-harsh/Zomato_Reviews_Scrapping", "sub_path": "zomato_we_scrapping/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1581, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 7, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 10, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 13, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 13, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 14, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 14, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 17, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 18, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 22, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 23, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 32, "usage_type": "call"}]} +{"seq_id": "39450015106", "text": "import os\r\nimport pandas as pd\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom keras.backend import clear_session\r\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\r\nfrom keras.models import load_model\r\nfrom PIL import Image\r\nimport argparse\r\n\r\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\r\n\r\naspect_to_model = {'overall': 'acceptable.hdf5', 'clarity': 'blur.hdf5', 'clarity_od': 'blur_od.hdf5',\r\n 'clarity_macula': 'blur_macula.hdf5', 'clarity_others': 'blur_others.hdf5',\r\n 'illuminate': 'illuminate.hdf5', 'illuminate_od': 'illuminate_od.hdf5',\r\n 'illuminate_macula': 'illuminate_macula.hdf5', 'illuminate_others': 'illuminate_others.hdf5',\r\n 'position': 'structure.hdf5', 'position_od': 'structure_od.hdf5', 'position_macula': 'structure_macula.hdf5',\r\n 'cataract': 'cataract.hdf5'}\r\n\r\nparser = argparse.ArgumentParser(description = 'configuration')\r\nparser.add_argument('--mode', type=int, default=1, choices=[1, 2], help='1 indicates quality classification and 2 indicates real-time guidance')\r\nparser.add_argument('--image_dir', default='images', help='directory of test images')\r\nparser.add_argument('--image_size', type=int, default=512, help='image resolution (need to match the models)')\r\nargs = parser.parse_args()\r\n\r\nif args.mode == 1:\r\n res_dict = dict([(k, []) for k in aspect_to_model.keys()])\r\n for aspect in list(aspect_to_model.keys()):\r\n clear_session()\r\n model = load_model(os.path.join('models/', aspect_to_model[aspect]), compile=False)\r\n all_fn = sorted(os.listdir(args.image_dir))\r\n for fn in all_fn:\r\n try:\r\n image = Image.open(os.path.join(args.image_dir, fn)).convert('RGB')\r\n image = image.resize((512, 512))\r\n image = np.array(image) / 255.\r\n image = image.reshape(1, 512, 512, -1)\r\n y_pred_prob = float(np.squeeze(model.predict(image)))\r\n res_dict[aspect].append(y_pred_prob)\r\n except:\r\n print('error when opening {}'.format(fn))\r\n continue\r\n df_proba = pd.DataFrame(res_dict, index=all_fn)\r\n df_pred = df_proba.applymap(lambda x: 1 if x > 0.5 else 0)\r\n df_pred['illuminate_od'] = df_proba['illuminate_od'].map(lambda x: 1 if x > 0.2 else 0)\r\n df_pred['illuminate_macula'] = df_proba['illuminate_macula'].map(lambda x: 1 if x > 0.39 else 0)\r\n df_pred = df_pred.drop(['cataract'], axis=1)\r\n df_proba = df_proba.drop(['cataract'], axis=1)\r\n df_proba.to_excel('results/quality_proba.xlsx')\r\n df_pred.to_excel('results/quality_pred.xlsx')\r\n\r\nelse:\r\n all_fn = sorted(os.listdir(args.image_dir))\r\n predictions = []\r\n for fn in all_fn:\r\n result = ''\r\n for aspect in ['overall', 'position', 'illuminate', 'clarity', 'cataract']:\r\n clear_session()\r\n model = load_model(os.path.join('/data/yellowcard/llx/models/', aspect_to_model[aspect]), compile=False)\r\n try:\r\n image = Image.open(os.path.join(args.image_dir, fn)).convert('RGB')\r\n image = image.resize((512, 512))\r\n image = np.array(image) / 255.\r\n image = image.reshape(1, 512, 512, -1)\r\n y_pred_prob = float(np.squeeze(model.predict(image)))\r\n\r\n except:\r\n print('error when opening {}'.format(fn))\r\n continue\r\n if aspect == 'overall' and y_pred_prob <= 0.5:\r\n result = 'finish'\r\n break\r\n if aspect == 'position' and y_pred_prob > 0.5:\r\n result = 'recapture'\r\n break\r\n if aspect == 'illuminate' and y_pred_prob > 0.5:\r\n result = 'recapture'\r\n break\r\n if aspect == 'clarity' and y_pred_prob <= 0.5:\r\n result = 'finish'\r\n break\r\n if aspect == 'cataract':\r\n if y_pred_prob > 0.5:\r\n result = 'referral'\r\n else:\r\n result = 'recapture'\r\n predictions.append(result)\r\n df = pd.DataFrame({'prediction': predictions}, index=all_fn)\r\n df.to_excel('results/advice_pred.xlsx')", "repo_name": "liulx37/Deep-Fundus", "sub_path": "inference.py", "file_name": "inference.py", "file_ext": "py", "file_size_in_byte": 4286, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "os.environ", "line_number": 11, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 20, "usage_type": "call"}, {"api_name": "keras.backend.clear_session", "line_number": 29, "usage_type": "call"}, {"api_name": "keras.models.load_model", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path", "line_number": 30, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 31, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 34, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 34, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 38, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 43, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 53, "usage_type": "call"}, {"api_name": "keras.backend.clear_session", "line_number": 58, "usage_type": "call"}, {"api_name": "keras.models.load_model", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path", "line_number": 59, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 61, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 61, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path", "line_number": 61, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 65, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 88, "usage_type": "call"}]} +{"seq_id": "2341327915", "text": "import matplotlib.pyplot as plt\n\n# Pie chart, where the slices will be ordered and plotted counter-clockwise:\nlabels = 'Northern Michigan', 'Upper Peninsula', 'SW Michigan', 'SE Michigan'\ncoolFactor = [75, 50, 30, 16]\nexplode = (.1, 0, 0, 0) # only \"explode\" the 1st wedge\nwedgeColors=('tomato','mediumseagreen','plum','darkslategray')\nfig1, ax1 = plt.subplots()\nax1.pie(coolFactor, explode=explode, labels=labels, autopct='%3.1f%%', shadow=False, startangle=0)\nax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\nplt.suptitle(\"Best Places in Michigan Factor\")\n\nplt.show()\n", "repo_name": "dunck2020/CIT228", "sub_path": "DataProject/fun_pie.py", "file_name": "fun_pie.py", "file_ext": "py", "file_size_in_byte": 601, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "matplotlib.pyplot.subplots", "line_number": 8, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 8, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.suptitle", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}]} +{"seq_id": "27406713126", "text": "from __future__ import annotations\n\nfrom typing import Any\nimport json\nimport simplejson\n\nfrom requests import Session\nfrom requests.models import Response as BaseResponse\nfrom requests.exceptions import HTTPError\nfrom urllib.parse import quote, quote_plus\n\nfrom .enum_ import Enum\nfrom .translator import TranslatableMeta\n\n\nclass Response(BaseResponse):\n \"\"\"Subclass of requests.Response with a modified Response.json() method.\"\"\"\n\n def __init__(self, namespace: dict) -> None:\n self.__dict__ = namespace\n\n def json(self) -> Any:\n \"\"\"Returns Str, List, and Dict items rather than their builtin superclasses. If there is no data will return None rather than raising JSONDecodeError.\"\"\"\n try:\n return TranslatableMeta.translator.translate(super().json())\n except (json.JSONDecodeError, simplejson.JSONDecodeError):\n return None\n\n\nclass Http(Session):\n \"\"\"\n Subclass of requests.Session which takes a 'base_url' constructor argument and prepends it to all future requests.\n It returns Str, List, and Dict instances when deserializing json from responses and can automatically quote all urls passed to its http methods.\n \"\"\"\n\n class QuoteLevel(Enum):\n NONE = NORMAL = PLUS = Enum.Auto()\n\n Error, Response = HTTPError, Response\n\n def __init__(self, base_url: str = \"\", auth: tuple[str, str] = None, quote_level: Http.QuoteLevel = QuoteLevel.NONE) -> None:\n super().__init__()\n self.base_url, self.auth, self.quote_level = base_url.strip('/'), auth, quote_level\n\n def __repr__(self) -> str:\n return f\"{type(self).__name__}(base_url={repr(self.base_url)}, auth={repr(self.auth)}, headers={repr(self.headers)})\"\n\n def request(self, method: str, url: str, *args: Any, **kwargs: Any) -> Any:\n response_raw: BaseResponse = super().request(method=method,\n url=self._quote_encode(f\"{self.base_url}/{url.strip('/')}\".strip(\"/\")),\n *args, **kwargs)\n return Response(response_raw.__dict__)\n\n def _quote_encode(self, url: str) -> str:\n return self.QuoteLevel[self.quote_level].map_to({\n self.QuoteLevel.NONE: lambda url_: url_,\n self.QuoteLevel.NORMAL: lambda url_: quote(url_),\n self.QuoteLevel.PLUS: lambda url_: quote_plus(url_),\n })(url)\n", "repo_name": "matthewgdv/subtypes", "sub_path": "subtypes/http.py", "file_name": "http.py", "file_ext": "py", "file_size_in_byte": 2408, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "requests.models.Response", "line_number": 16, "usage_type": "name"}, {"api_name": "translator.TranslatableMeta.translator.translate", "line_number": 25, "usage_type": "call"}, {"api_name": "translator.TranslatableMeta.translator", "line_number": 25, "usage_type": "attribute"}, {"api_name": "translator.TranslatableMeta", "line_number": 25, "usage_type": "name"}, {"api_name": "json.JSONDecodeError", "line_number": 26, "usage_type": "attribute"}, {"api_name": "simplejson.JSONDecodeError", "line_number": 26, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 22, "usage_type": "name"}, {"api_name": "requests.Session", "line_number": 30, "usage_type": "name"}, {"api_name": "enum_.Enum", "line_number": 36, "usage_type": "name"}, {"api_name": "enum_.Enum.Auto", "line_number": 37, "usage_type": "call"}, {"api_name": "enum_.Enum", "line_number": 37, "usage_type": "name"}, {"api_name": "requests.exceptions.HTTPError", "line_number": 39, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 48, "usage_type": "name"}, {"api_name": "requests.models.Response", "line_number": 49, "usage_type": "name"}, {"api_name": "urllib.parse.quote", "line_number": 57, "usage_type": "call"}, {"api_name": "urllib.parse.quote_plus", "line_number": 58, "usage_type": "call"}]} +{"seq_id": "34913911239", "text": "import numpy as np\nimport multiprocessing as mp\nimport time\nclass test():\n def __init__(self):\n self.v=np.array([0,0,0,0])\n self.results=[]\n\n def _collect_result(self, result):\n self.results.append(result)\n\n def _exc(self):\n print('self.v={}'.format(self.v))\n return self.v\n\n def _pri(self,idx):\n print('idx:{},cpu:{}'.format(idx,mp.current_process()))\n self.v[idx-1]=idx\n time.sleep(5)\n return self._exc()\n\n def run(self):\n print('start')\n pool=mp.Pool(2)\n for idx in [1,2,3,4]:\n pool.apply_async(self._pri, args=(idx,), callback=self._collect_result)\n pool.close()\n pool.join()\n print('end')\n\nt=test()\nstarttime = time.time()\nt.run()\nprint('That took {} seconds'.format(time.time() - starttime))\nprint(t.results)\n", "repo_name": "SiyanZhou97/VAE", "sub_path": "autoencodercmp/test_multiprocess.py", "file_name": "test_multiprocess.py", "file_ext": "py", "file_size_in_byte": 846, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "numpy.array", "line_number": 6, "usage_type": "call"}, {"api_name": "multiprocessing.current_process", "line_number": 17, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 19, "usage_type": "call"}, {"api_name": "multiprocessing.Pool", "line_number": 24, "usage_type": "call"}, {"api_name": "time.time", "line_number": 32, "usage_type": "call"}, {"api_name": "time.time", "line_number": 34, "usage_type": "call"}]} +{"seq_id": "42640269030", "text": "\"\"\"Detects faces using the HARR cascade classifier\n\nUsing OpenCV we are able to detect if there are faces\nin the image. The CascadeClassifier is pretrained model\nthat will convolve kernels to determine any facial features.\nIt can detect multiple faces in an image but will not \nconduct facial recognition. If the input parameter is \na face, the method will reply true. \n\"\"\"\n\nimport cv2 as cv\nfrom sysVariable import FACE_DETECTION_MODULE\nface_cascade = cv.CascadeClassifier(FACE_DETECTION_MODULE)\n\n\ndef faceDetection(imgPath):\n \"\"\"Detects faces that are within an image\n\n Args:\n imgPath ([file]): [a path to an image that\n was taken recently]\n\n Returns:\n [boolean]: [if there is a face detected\n the result will be true,\n if not, the result false.]\n \"\"\"\n\n # Read the image from the local path\n img = cv.imread(imgPath)\n\n # Convert the image to gscale\n grayImg = gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n # Apply the model to the image\n faces = face_cascade.detectMultiScale(grayImg)\n\n # We only care if there is an image in the picture.\n # If there is no image, the result would be 0\n if len(faces) > 0:\n return True\n else:\n return False\n\n ", "repo_name": "WillTUW/facial-recognition-locking-service", "sub_path": "deviceCode/cameraDevice/devCode/faceDetection.py", "file_name": "faceDetection.py", "file_ext": "py", "file_size_in_byte": 1241, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "cv2.CascadeClassifier", "line_number": 13, "usage_type": "call"}, {"api_name": "sysVariable.FACE_DETECTION_MODULE", "line_number": 13, "usage_type": "argument"}, {"api_name": "cv2.imread", "line_number": 30, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 33, "usage_type": "attribute"}]} +{"seq_id": "4317175913", "text": "from Crypto.Cipher import PKCS1_OAEP\nfrom Crypto.PublicKey import RSA\n\nnombre_texto = \"\"\n\ndef inicio():\n print (\"Elige una llave privada a usar\")\n print (\"1.- Betito 2.- Alicia 3.- Jimenita\")\n opcion = int (input())\n\n if opcion == 1:\n nombre_texto = \"Betito\"\n elif opcion == 2:\n nombre_texto = \"Alicia\"\n elif opcion == 3:\n nombre_texto = \"Jimenita\"\n else:\n print (\"Valor no aceptado\")\n inicio()\n textoClaro = lector_archivo(nombre_texto)\n bytesClaro = bytes(textoClaro, encoding=\"utf8\")\n\n #llamar a llave publica\n ruta = \"LlavesPublicas/llavepub\" + nombre_texto + \".pem\"\n llavepublica = RSA.import_key(open(ruta).read())\n cifrador = PKCS1_OAEP.new(llavepublica)\n textoCifrado = cifrador.encrypt(bytesClaro)\n rutacifrado = \"objetosCifrados/cifrado\" + nombre_texto + \".txt\"\n cifrado_docs = open(rutacifrado, \"wb\")\n cifrado_docs.write(textoCifrado)\n cifrado_docs.close()\n\ndef lector_archivo(nombreUsuario):\n ruta = \"ArchivosTXT/base\" + nombreUsuario + \".txt\"\n file = open(ruta, \"r\")\n texto = file.read()\n return texto\n\ninicio()", "repo_name": "luisgdov1/RSA", "sub_path": "cifrador.py", "file_name": "cifrador.py", "file_ext": "py", "file_size_in_byte": 1126, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "Crypto.PublicKey.RSA.import_key", "line_number": 25, "usage_type": "call"}, {"api_name": "Crypto.PublicKey.RSA", "line_number": 25, "usage_type": "name"}, {"api_name": "Crypto.Cipher.PKCS1_OAEP.new", "line_number": 26, "usage_type": "call"}, {"api_name": "Crypto.Cipher.PKCS1_OAEP", "line_number": 26, "usage_type": "name"}]} +{"seq_id": "70984452528", "text": "from gamebook.terminal_output import TerminalOutput\nfrom gamebook.scene import Scene\nimport pytest\n\n\ndef test_is_content_recieved():\n example_desc = \"this is an example scene\"\n\n example_scene = Scene(\"exapmle scene\",\n desc=example_desc,\n options=[])\n\n output_instance = TerminalOutput()\n\n assert output_instance.output(example_scene.show_desc()) ==\\\n print(example_desc)\n\n\ndef test_content_is_empty_error():\n output_instance = TerminalOutput()\n\n content_error = \"no content recieved\"\n empty_scene = Scene(\"\", \"\", options=[])\n\n with pytest.raises(ValueError) as error_text:\n assert output_instance.output(empty_scene.get_name())\n assert str(error_text.value) == content_error\n", "repo_name": "arielofer/gamebook-maker", "sub_path": "tests/test_terminal_output.py", "file_name": "test_terminal_output.py", "file_ext": "py", "file_size_in_byte": 766, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "2", "api": [{"api_name": "gamebook.scene.Scene", "line_number": 9, "usage_type": "call"}, {"api_name": "gamebook.terminal_output.TerminalOutput", "line_number": 13, "usage_type": "call"}, {"api_name": "gamebook.terminal_output.TerminalOutput", "line_number": 20, "usage_type": "call"}, {"api_name": "gamebook.scene.Scene", "line_number": 23, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "41159254651", "text": "#Find Sublinks For A Given Link\nimport bs4\nimport requests\nimport csv\n\n\ndef link(x): #Find Link And Store In A Csv File.\n url = 'https://www.drugs.com' + x\n req = requests.get(url)\n soup = bs4.BeautifulSoup(req.text, 'lxml')\n with open('link.csv', 'a', newline='') as CsvFile:\n writer = csv.writer(CsvFile)\n for links in soup.find_all('a', attrs={'class': 'ddc-btn ddc-btn-sm'}):\n # print(links.get('href'))\n csvRow = [links.get('href')] #Just Extract The Links.\n writer.writerow(csvRow)\n\n\ndef fetch():\n file_obj = open('OTC_FOR_A.csv', 'r') # opening a file which contain the list of links.\n for r in csv.reader(file_obj):\n r = list(csv.reader(file_obj)) # Convert A Given Csv File To A 2D List.\n for a in range(1, 2264):\n print(a)\n link(r[a][1]) # here r[m][n] we have [m] as row and [n] as column.\n\n\nfetch()\n", "repo_name": "Abhijeet-Ahirwar/Online_Crawler", "sub_path": "Extract_All_Sublinks.py", "file_name": "Extract_All_Sublinks.py", "file_ext": "py", "file_size_in_byte": 1047, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "requests.get", "line_number": 9, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 10, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 12, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 21, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 22, "usage_type": "call"}]} +{"seq_id": "70586327422", "text": "from twilio.rest import Client\n\nACCOUNT_SID = \"Your account SID\"\nAUTH_TOKEN = \"Your auth token\"\nTWILO_VIRT_NUMBER = \"Your Twilo number\"\nTWILO_VERIFIED_NUMBER = \"Verified number\"\n\n\nclass NotificationManager:\n\n def send_message(self, text):\n client = Client(ACCOUNT_SID, AUTH_TOKEN)\n message = client.messages.create(\n body=text,\n from_=TWILO_VIRT_NUMBER,\n to=TWILO_VERIFIED_NUMBER\n )\n print(message.status)\n", "repo_name": "padgettanna/Python-Projects", "sub_path": "FlightDeals/notification_manager.py", "file_name": "notification_manager.py", "file_ext": "py", "file_size_in_byte": 470, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "twilio.rest.Client", "line_number": 12, "usage_type": "call"}]} +{"seq_id": "14206969027", "text": "import requests\nimport re\nfrom bs4 import BeautifulSoup\nimport pygame, sys\nimport math\nimport random\nimport math\nimport threading\nimport time\n\n\n# 주식\nr = requests.get('https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=0&ie=utf8&query=주식')\n\ndown = True\nvalue = 0.0\n\ndef get_data():\n global down, value\n while True:\n if r.status_code == 200:\n parse = BeautifulSoup(r.text, 'html.parser')\n info = parse.find_all('span', class_='spt_con dw')\n if len(info) == 0:\n info = parse.find_all('span', class_='spt_con up')\n info = info[0]\n down = info.find_all('span', class_='ico')[0].text == \"하락\"\n value = float(info.find_all('em')[0].text)\n print('get data....', info.find_all('span', class_='ico')[0].text, value)\n time.sleep(10)\n\nthd = threading.Thread(target=get_data)\nthd.start()\n\npygame.init()\nscreen = pygame.display.set_mode((800,600))\nclock = pygame.time.Clock()\n\nclass Particle:\n def __init__(self):\n self.x = random.randrange(0, screen.get_width())\n self.y = random.randrange(0, screen.get_height())\n self.size = 10\n self.color = (0,0,255) if down else (255,0,0)\n self.y_dir = value * 0.1 * (1 if down else -1)\n def draw(self):\n self.x += random.randrange(-2,3)\n self.y += self.y_dir\n \n pygame.draw.circle(screen, self.color, [self.x ,self.y], self.size)\n if self.x < 0 or self.x > screen.get_width() or self.y < 0 or self.y > screen.get_height() or self.size < 0:\n self.x = random.randrange(0,screen.get_width())\n self.y = 0 if down else screen.get_height()\n self.y_dir = value * 0.1 * (1 if down else -1)\n self.size = 10\n\n\n\nparticles = [Particle() for _ in range(10)]\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n screen.fill((30, 30, 30))\n for p in particles:\n p.draw()\n pygame.display.update()\n \n clock.tick(120)\n\n\n \n\n", "repo_name": "byulparan/wesa2021", "sub_path": "05.draw_data.py", "file_name": "05.draw_data.py", "file_ext": "py", "file_size_in_byte": 2101, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "requests.get", "line_number": 13, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 22, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 30, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 32, "usage_type": "call"}, {"api_name": "pygame.init", "line_number": 35, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 36, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 36, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 37, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 37, "usage_type": "attribute"}, {"api_name": "random.randrange", "line_number": 41, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 42, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 47, "usage_type": "call"}, {"api_name": "pygame.draw.circle", "line_number": 50, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 50, "usage_type": "attribute"}, {"api_name": "random.randrange", "line_number": 52, "usage_type": "call"}, {"api_name": "pygame.event.get", "line_number": 62, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 62, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 63, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 64, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 65, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 69, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 69, "usage_type": "attribute"}]} +{"seq_id": "6222271712", "text": "#!/usr/bin/python\nimport os\nimport sys\n\nfrom lib.convert import Convert\n\n\nclass CmdWindows:\n __os = \"\"\n\n def __init__(self, operating_system):\n self.__os = operating_system\n\n @staticmethod\n def get_string(*args):\n if len(args) == 0:\n input_text = \"\"\n else:\n input_text = args[0]\n\n sys.stdout.flush()\n try:\n text = input(input_text)\n except KeyboardInterrupt:\n return \"\"\n return text\n\n @staticmethod\n def get_number(*args):\n if len(args) == 0:\n input_text = \"\"\n else:\n input_text = args[0]\n text = CmdWindows.get_string(input_text)\n return Convert.get_number(text)\n\n def clear(self):\n if self.__os == \"nt\":\n os.system(\"cls\")\n elif self.__os == \"posix\":\n from subprocess import call\n call([\"clear\"], shell=True)\n\n @staticmethod\n def pause():\n return CmdWindows.get_string('Press ENTER key to continue')\n", "repo_name": "yes4me/adb_tool", "sub_path": "lib/cmd_windows.py", "file_name": "cmd_windows.py", "file_ext": "py", "file_size_in_byte": 1025, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sys.stdout.flush", "line_number": 21, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 21, "usage_type": "attribute"}, {"api_name": "lib.convert.Convert.get_number", "line_number": 35, "usage_type": "call"}, {"api_name": "lib.convert.Convert", "line_number": 35, "usage_type": "name"}, {"api_name": "os.system", "line_number": 39, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 42, "usage_type": "call"}, {"api_name": "{'call': 'subprocess.call'}.get_string", "line_number": 46, "usage_type": "call"}]} +{"seq_id": "2405505941", "text": "from utils import letter\nimport time\nimport os\ndef init() :\n title = \"\"\n\n for c in \"T Y P I N G T E S T\" : \n title += c\n print(title)\n time.sleep(0.05)\n os.system('cls')\n print(\"T Y P I N G T E S T\")\n time.sleep(0.5)\n print(\"쉬운 오픈 소스 영어 타자연습 프로그램\")\n print(\"Easy Open Source English Typing Practice Program\")\n time.sleep(0.5)\n print(\"version 0.1.1 Ahlpa\")\n time.sleep(0.5)\n print(\"GitHub 리포지토리에 기여하여 프로그램을 발전시켜주세요!\")\n print(\"Github : https://github.com/KaiNiGHt/typingtest\")\n os.system(\"pause\")\n while True:\n os.system(\"cls\")\n n = input(\"단계 입력 (1 : 자리연습, 2 : 낱말연습, 3, 4 : 짧은글 연습. 나가려면 -1 혹은 exit를 입력하세요.) : \")\n if n >= \"1\" and n <= \"4\" :\n letter.Letter('./utils/database/english/resource/letter_' + n + '.txt')\n elif n == \"exit\" or n == \"-1\":\n print(\"종료합니다.\")\n time.sleep(1)\n break\n elif n == \"d\" or n == \"devmode\" or n ==\"developer\" or n == \"dev\" :\n letter.Letter('./utils/database/english/resource/developer.txt')\n else:\n print(\"오류 : 입력이 올바르지 않습니다.\")\n time.sleep(1)\n os.system(\"cls\")\n\n\n\n\n", "repo_name": "Kyanite0029/typingtest", "sub_path": "mainscreen.py", "file_name": "mainscreen.py", "file_ext": "py", "file_size_in_byte": 1356, "program_lang": "python", "lang": "ko", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "time.sleep", "line_number": 10, "usage_type": "call"}, {"api_name": "os.system", "line_number": 11, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 13, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 16, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 18, "usage_type": "call"}, {"api_name": "os.system", "line_number": 21, "usage_type": "call"}, {"api_name": "os.system", "line_number": 23, "usage_type": "call"}, {"api_name": "utils.letter.Letter", "line_number": 26, "usage_type": "call"}, {"api_name": "utils.letter", "line_number": 26, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 29, "usage_type": "call"}, {"api_name": "utils.letter.Letter", "line_number": 32, "usage_type": "call"}, {"api_name": "utils.letter", "line_number": 32, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 35, "usage_type": "call"}, {"api_name": "os.system", "line_number": 36, "usage_type": "call"}]} +{"seq_id": "12339866932", "text": "from flask import Flask, render_template, request\nfrom flask import redirect, url_for\nimport pickle\nimport json\nimport numpy as np\n\napp = Flask(__name__)\niris = [\"Setosa\", \"Versicolor\", \"Virginica\"]\ndatasets = {'data': [], 'answer': []}\nsepal_length = None\nsepal_width = None\npetal_length = None\npetal_width = None\ncount = 0\n\n# オブジェクトの呼び出し\nwith open('./app/static/model/model.pickle', 'rb') as f:\n clf = pickle.load(f)\n\n# index.htmlへ移動\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n# 予測\n@app.route(\"/pred\", methods=[\"post\"])\ndef pred():\n global iris, clf, sepal_length, sepal_width, petal_length, petal_width\n try:\n sepal_length = float(request.form[\"sepal_length\"])\n sepal_width = float(request.form[\"sepal_width\"])\n petal_length = float(request.form[\"petal_length\"])\n petal_width = float(request.form[\"petal_width\"])\n except:\n return render_template(\"index.html\", error=\"error\")\n\n input = np.array([[sepal_length, sepal_width, petal_length, petal_width]])\n index = clf.predict(input)[0]\n name = iris[index]\n return render_template(\"index.html\", name=name)\n\n# add.htmlへ移動\n@app.route(\"/add\")\ndef add():\n global iris, sepal_length, sepal_width, petal_length, petal_width\n return render_template(\"add.html\", sepal_length=sepal_length, sepal_width=sepal_width, petal_length=petal_length, petal_width=petal_width, iris=iris)\n\n# データを追加\n@app.route(\"/add_data\", methods=[\"post\"])\ndef add_data():\n global count, datasets, iris, sepal_length, sepal_width, petal_length, petal_width\n try:\n new_sepal_length = float(request.form[\"sepal_length\"])\n new_sepal_width = float(request.form[\"sepal_width\"])\n new_petal_length = float(request.form[\"petal_length\"])\n new_petal_width = float(request.form[\"petal_width\"])\n new_answer = int(iris.index(request.form[\"answer\"]))\n \n except:\n return render_template(\"add.html\", sepal_length=sepal_length, sepal_width=sepal_width, petal_length=petal_length, petal_width=petal_width, iris=iris, error=\"error\")\n \n datasets[\"data\"].append(new_sepal_length)\n datasets[\"data\"].append(new_sepal_width)\n datasets[\"data\"].append(new_petal_length)\n datasets[\"data\"].append(new_petal_width)\n datasets[\"answer\"].append(new_answer)\n\n sepal_length = None\n sepal_width = None\n petal_length = None\n petal_width = None\n count += 1\n \n with open(\"./app/static/jsons/{:06d}.json\".format(count), \"w\") as f:\n json.dump(datasets, f, indent=4, ensure_ascii=False)\n \n datasets = {'data': [], 'answer': []}\n return render_template(\"Top.html\")\n\n# データを見る\n#@app.route(\"/show_data\")\n#def show_data():\n# global datasets\n# return render_template(\"show.html\", datasets=datasets)\n\nif __name__ == \"__main__\":\n app.run(debug=True)", "repo_name": "ryusuke0215/My-first-web", "sub_path": "app/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 2938, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 7, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 18, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 23, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 30, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 30, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 31, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 31, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 32, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 32, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 33, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 33, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 37, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 40, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 46, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 53, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 53, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 54, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 54, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 55, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 55, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 56, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 56, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 57, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 57, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 60, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 75, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 78, "usage_type": "call"}]} +{"seq_id": "71224496063", "text": "from datetime import datetime, timedelta, date\nfrom django.core.paginator import Paginator\nfrom django.shortcuts import render\nfrom django.views.generic import ListView, DetailView\nfrom .models import Song, Day, Person\nfrom django.db.models import Q\n\n\ndef search_song_view(request):\n query = request.GET.get(\"q\", None)\n qs = Song.objects.all()\n if query is not None:\n qs = qs.filter(\n Q(title__icontains=query) | Q(artist__icontains=query)\n )\n paginator = Paginator(qs.order_by('artist'), 25)\n else:\n paginator = Paginator(qs.order_by('-day__date', 'artist'), 25)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n context = {\n 'page_obj': page_obj,\n }\n template_name = 'main.html'\n return render(request, template_name, context)\n\n\nclass DayListView(ListView):\n model = Day\n template_name = \"day.html\"\n paginate_by = 5\n ordering = ['-date', 'id']\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data()\n context[\"days_table\"] = self.get_days_table()\n return context\n\n def get_days_table(self):\n days = Day.objects.all().order_by(\"-date\")[:7] # zwraca listę wszystkich dni\n count = []\n for d in days:\n count_song = d.song_set.count()\n dates = d.date\n lista = {\n \"count\": count_song,\n \"day\": dates,\n }\n count.append(lista)\n return count\n\n\n # def __get_day_pk(self, days):\n # number_days = []\n # for day in days:\n # number_days.append(day.pk)\n # # number_day = day.pk #te 2 linijki powodowały, że jak zwrócę se number_day\n # # number_days.append(number_day) # to zwróci mi tylko ostatnie pk a nie wszystkie\n # return number_days\n\n\nclass PersonDetailView(DetailView):\n model = Person\n template_name = \"person_detail.html\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data()\n context[\"days\"] = self.get_days()\n return context\n\n # literowanie po 100 dniach\n def get_days(self):\n days_count = 100 #liczba dni wyzwania\n start_date = date(2020, 7, 27) # data startowa\n days_list = self.__get_person_days() # przenosi do funkcji, która pobiera listę dni dla Perosn\n active_days = [] # nowa zmienna tworząca pustą listę, to której będą zaisywane dane jako context\n for i in range(days_count):\n today = start_date + timedelta(days=i) # to tworzy datę, która zawsze jest większa o 1 dzień\n active_day = {\n \"date\": today,\n \"active\": self.__is_active(today, days_list),\n \"future\": self.__future_day(today),\n }\n active_days.append(active_day)\n return active_days\n\n def __get_person_days(self):\n person_songs = self.object.song_set.all()\n days_list = []\n for song in person_songs:\n days_list.append(song.day.date)\n return days_list\n\n def __is_active(self, today, days_list):\n return today in days_list ## zwraca z listy wszyskich dat, datę do days_list, ta data jest powiązana z istnijacym obiektem w bazie\n\n def __future_day(self, today):\n now = date.today()\n return today > now\n\n\n # def __get_song(self, songs):\n # return song in songs\n\n # Moja funkcja do sprawdzenia czy to przyszły dzień\n # def __get_future_days(self):\n # now = date.today()\n # future_days = []\n # days_count = 100 #liczba dni wyzwania\n # start_date = date(2020, 7, 27) # data startowa\n # for i in range(days_count):\n # today = start_date + timedelta(days=i) # to tworzy datę, która zawsze jest większa o 1 dzień\n # if today > now:\n # future_days.append(today)\n # return future_days\n # def __is_future(self, today, future_days):\n # return today in future_days\n\n # Małyszowy sposób na sprawdzenie czy obiekt znajduje sie na liście\n # def get_context_data(self, **kwargs):\n # context = super().get_context_data()\n # context[\"days\"] = self.get_days()\n # return context\n #\n # def get_days(self):\n # days_to_check = self.__get_all_days()\n # days_list = self.__get_person_days()\n # active_days = []\n # for day in days_to_check:\n # active_day = {\n # \"date\": day,\n # \"active\": self.__is_active(day, days_list),\n # }\n # active_days.append(active_day)\n # return active_days\n #\n # def __get_person_days(self):\n # person_songs = self.object.song_set.all()\n # days_list = []\n # for song in person_songs:\n # days_list.append(song.day.date)\n # return days_list\n #\n # def __is_active(self, today, days_list):\n # return today in days_list\n #\n # def __get_all_days(self):\n # return Day.objects.all().values_list(\"date\", flat=True)\n", "repo_name": "Drizii/DayChallange", "sub_path": "challange/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 5132, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "models.Song.objects.all", "line_number": 11, "usage_type": "call"}, {"api_name": "models.Song.objects", "line_number": 11, "usage_type": "attribute"}, {"api_name": "models.Song", "line_number": 11, "usage_type": "name"}, {"api_name": "django.db.models.Q", "line_number": 14, "usage_type": "call"}, {"api_name": "django.core.paginator.Paginator", "line_number": 16, "usage_type": "call"}, {"api_name": "django.core.paginator.Paginator", "line_number": 18, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 25, "usage_type": "call"}, {"api_name": "django.views.generic.ListView", "line_number": 28, "usage_type": "name"}, {"api_name": "models.Day", "line_number": 29, "usage_type": "name"}, {"api_name": "models.Day.objects.all", "line_number": 40, "usage_type": "call"}, {"api_name": "models.Day.objects", "line_number": 40, "usage_type": "attribute"}, {"api_name": "models.Day", "line_number": 40, "usage_type": "name"}, {"api_name": "django.views.generic.DetailView", "line_number": 62, "usage_type": "name"}, {"api_name": "models.Person", "line_number": 63, "usage_type": "name"}, {"api_name": "datetime.date", "line_number": 74, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 78, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 98, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 98, "usage_type": "name"}]} +{"seq_id": "73485210621", "text": "# completion\nimport requests\nimport json\n\nurl = \"https:/your_end_point/openai/deployments/chatgptv1/chat/completions?api-version=2023-03-15-preview\"\n\nheaders = {\n \"Content-Type\": \"application/json\",\n \"api-key\": \"your_key\"\n}\n\ndata = {\n \"messages\": [\n {\"role\": \"system\", \"content\": \"You are an AI assistant that helps people find information.\"},\n {\"role\": \"user\", \"content\": \"hello\"}\n ],\n \"max_tokens\": 800,\n \"temperature\": 0.7,\n \"frequency_penalty\": 0,\n \"presence_penalty\": 0,\n \"top_p\": 0.95,\n \"stop\": None\n}\n\nresponse = requests.post(url, headers=headers, data=json.dumps(data))\n\njson_data = response.json()\nprint(json_data['choices'][0]['message']['content'])", "repo_name": "JackeyLove1/python-tools", "sub_path": "GPT/openai-service/completions.py", "file_name": "completions.py", "file_ext": "py", "file_size_in_byte": 704, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "requests.post", "line_number": 25, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "9208919615", "text": "import numpy as np\nimport cPickle as pickle\nimport os\nimport sys\nimport copy\nfrom ase import Atoms,io\nfrom ase.io.trajectory import write_trajectory\nfrom ase.constraints import FixBondLength, FixedPlane\nfrom ase.optimize import QuasiNewton,BFGS\nfrom ase.calculators.calculator import Calculator\n#Change for actual version\nfrom ase.neb import NEB\n\nclass AidanDrag:\n \"\"\"Class for running various forms of the drag method for finding transition states.\n All drag methods require the input of an initial and final state, the number of images to be created, \n a reaction coordinate defining the relaxation constraints, and a calculator object for optimizations.\n The output is a numpy file, a pickle file, and a set of traj files, corresponding to the intermediate images. \n The npz file contains lists of relaxed and unrelaxed energies, number of relaxations needed, and projected forces.\n These are in bisection (not reaction coordinate) order.\n The pckl file just contains a list of the relaxed energies, in reaction coordinate order.\n The traj files are also in reaction coordinate order.\n initial_state and final_state: ASE atoms objects. Should already be relaxed. Constraints will be passed on to other images.\n num_imgs: an integer. Number of intermediate images to create along the reaction path.\n rxn_coord: a tuple of atom indicies (a1,a2) for a fixed bond length calc or a vector to relax perp. to.\n calculator: An ASE calculator object to use for force calculations. Will be copied to all images.\n path_type: 'linear' or 'idpp'. Determines the creation of the initial path. Either linear or IDPP interpolation.\n relax_num: An integer. If not 0, determines how many images are greedily relaxed. If 0, all images are relaxed.\n metric: 'force' or 'energy'. Metric used to select images to greedily relax.\n 'force' chooses those with the lowest tangental forces. 'energy', those with the highest potential energies.\n path_sampling: 'standard' or 'bisection'. How the path images are distributed. \n 'standard' is just an even sampling. 'bisection' bisects in the direction of lowest force, sampling the TS region more.\n optimizer: An ASE optimizer object. The optimizer used for the image relaxations If None, then QuasiNewton is used.\n logfile: String. Name for the optimizer logfiles (for relaxing drag images).\n traj: String. Name for the trajectory files of the relaxed drag images.\n outdir: String. Directory prefix for the path (if 'bisection' is used) and drag image calculations\"\"\"\n def __init__(self,initial_state, final_state, num_imgs,rxn_coord, calculator,path_type='linear',relax_num=-1,metric='energy',path_sampling = 'standard',optimizer = None,logfile='',traj='',outdir='',verbose=False,write=False,**kwargs):\n self.IS = initial_state\n self.FS = final_state\n self.nimgs = num_imgs\n self.rxn_coord = rxn_coord\n self.calc = calculator\n self.path_type = path_type\n #self.datafile=datafile\n self.verbose=verbose\n self.write = write\n self.kwargs = kwargs\n if relax_num<=0:\n self.relax_num = self.nimgs+relax_num\n else:\n self.relax_num = relax_num\n if not optimizer:\n self.optimizer = QuasiNewton\n else:\n self.optimizer = optimizer\n self.metric = metric\n self.sampling = path_sampling\n if not logfile:\n self.logfile='optDrag'\n else:\n self.logfile = logfile\n if not traj:\n self.traj='Drag'\n else:\n self.traj=traj\n if not outdir:\n self.outdir='Drag'\n else:\n self.outdir=outdir\n\n #The main method. Creates the path and relaxes the appropriate images. \n #Returns the used trajectory files and a pckl file with a list of energies.\n def run(self,quick=False):\n #First create the initial path\n if self.sampling == 'bisection':\n self.path,self.energy_list,self.force_list= self.create_bisection_path()\n elif self.sampling =='standard':\n if self.write:\n self.inds = range(self.nimgs)\n if self.path_type =='linear' or self.path_type =='Linear':\n self.path = self.linear_interpolation(self.IS,self.FS,self.nimgs)\n elif self.path_type =='IDPP' or self.path_type =='idpp':\n #self.path = self.linear_interpolation(self.IS,self.FS,self.nimgs)\n #self.path = [self.IS] + [self.IS.copy()]*self.nimgs + [self.FS]\n self.path = [self.IS]\n for i in range(self.nimgs):\n self.path+=[self.IS.copy()]\n self.path+=[self.FS]\n neb_=NEB(self.path,k=0.15,climb=True)\n neb_.interpolate(method='idpp')\n #self.mod_idpp_interpolate(self.path,traj=None,log=None,mic=False)\n #elif self.path_type=='fit':\n # self.energy_inds=[]\n #assert self.datafile is not None\n # from fitted_path import activity_path,direct_path, loocv_path\n # assert 'datafile' in self.kwargs\n #if 'weight' not in self.kwargs:\n #self.kwargs['weight']=0.\n # if 'fit_type' not in self.kwargs and 'degree' not in self.kwargs:\n # self.kwargs['fit_type']=3\n #self.path = loocv_path(self.IS,self.FS,self.nimgs,self.datafile,weight=0.,degree=1.,rel_rc=True)\n #self.path = direct_path(self.IS,self.FS,self.nimgs,self.kwargs.pop('datafile'),**self.kwargs)\n # self.path = activity_path(self.IS,self.FS,self.kwargs.pop('datafile'),**self.kwargs)\n else: \n raise ValueError('%s is an invalid input for the path_type. Please use either \"linear\" or \"IDPP\".' % self.path_type) \n for img in self.path:\n self.attach_calculator(img)\n else:\n raise ValueError('%s is an invalid input for path_sampling. Please use \"bisection\" or \"standard\".' % self.path_sampling) \n #Write the path for posterity. Verbose option maybe?\n write_trajectory(self.traj+'Path.traj',self.path)\n \n #Next, select the images to be relaxed\n assert self.relax_num<=self.nimgs\n if self.relax_num == self.nimgs:\n if self.verbose:\n self.select_images()\n self.relax_imgs=self.path[1:-1]\n elif self.relax_num >0:\n self.relax_imgs=self.select_images()\n else:\n if self.verbose:\n self.select_images()\n else:\n pass\n \n #Verbose..... inits, og_forces, and tangent should be temporary\n if self.verbose:\n pickle.dump({'Forces':self.force_list,'Energies':self.energy_list,'Inits':self.inits,'OG_Forces':self.og_forces,'Indices':self.inds},open(self.logfile+'_extra.pckl','wb'))\n if not quick:\n #Now relax the images...\n if hasattr(self,'relax_imgs'):\n energies=self.relax_images()\n #Output?\n TS_ind = np.argmax(energies)\n TS_energy = energies[TS_ind]\n #Add in option here\n pickle.dump(energies,open(self.logfile+'Results.pckl','wb'))\n if self.write:\n np.savez('Relaxation_results.npz',times=[0]*self.nimgs,inds=self.inds,geosteps=np.array(self.geosteps)[self.inds],energies = np.array(energies)[self.inds], forces=np.array(self.force_list)[self.inds],old_energies=np.array(self.energy_list)[self.inds]) \n\n #Simple linear interpolation. num_imgs=intermediate images\n def linear_interpolation(self,initial_state, final_state,num_imgs):\n path = [initial_state]\n for i in range(num_imgs):\n new_sys = initial_state.copy()\n new_pos = initial_state.get_positions() + ((i+1.)/(num_imgs+1.))*(final_state.get_positions()-initial_state.get_positions())\n new_sys.set_positions(new_pos)\n path.append(new_sys)\n path.append(final_state)\n return path\n\n #Creates a bisection path. After the first bisected image, others are created\n #in the direction of the lowest force (most uphill on PES).\n def create_bisection_path(self):\n #Creates the first bisected image\n if self.path_type =='linear' or self.path_type=='Linear':\n path = self.linear_interpolation(self.IS,self.FS,1)\n elif self.path_type =='idpp' or self.path_type == 'IDPP':\n path=[self.IS,self.IS.copy(),self.FS]\n neb_=NEB(path,k=0.15,climb=True)\n neb_.interpolate(method='idpp')\n '''elif self.path_type=='fit':\n from fitted_path import loocv_direct_func,loocv_func\n assert 'datafile' in self.kwargs\n if 'weight' not in self.kwargs:\n self.kwargs['weight']=0.\n if 'fit_type' not in self.kwargs:\n self.kwargs['fit_type']=3\n ads_inds = [a.index for a in self.IS if a.tag==0]\n lc = np.linalg.norm(self.IS.get_positions()[2]-self.IS.get_positions()[3])\n rc_i = np.linalg.norm(self.IS.get_positions()[ads_inds[0]]-self.IS.get_positions()[ads_inds[-1]])\n rc_f = np.linalg.norm(self.FS.get_positions()[ads_inds[0]]-self.FS.get_positions()[ads_inds[-1]])\n #target = (rc_i+rc_f)/2.\n #target/=lc\n target = 0.5\n target_list = [0.,0.5,1.]\n func = loocv_direct_func(self.IS,self.FS,self.kwargs.pop('datafile'),**self.kwargs)\n #func = loocv_func(self.IS,self.FS,**self.kwargs)\n nimg = func(target)\n #nimg = loocv_func(self.IS,self.FS,tar_rc,self.datafile,weight=0.,degree=1.,rel_rc=True)\n path = [self.IS,nimg,self.FS]\n '''#Create energy and force lists so they can be re-used if we go greedy\n old_energy_list=[]\n force_list=[]\n current_ind=1\n tangent =path[-1].get_positions()-path[0].get_positions()\n if self.verbose:\n og_forces=[]\n inits=[]\n #l_r=[]\n #l_r_forces=[]\n #l_r.append('m')\n if self.write:\n energy_inds=[0]\n #Iterate through the specified number of times\n for i in range(self.nimgs-1):\n current_system=path[current_ind]\n #Get a calc and set the appropriate directory\n self.attach_calculator(current_system)\n current_system.get_calculator().set(outdir=self.outdir+'_path')\n #Calculate and collect the forces and energies\n forces = current_system.get_forces()\n nrg = current_system.get_potential_energy()\n old_energy_list.insert(current_ind-1,nrg)\n #Get the forces in both directions along the reaction path\n left_tan = path[current_ind-1].get_positions() - path[current_ind].get_positions()\n left_tan/=np.sqrt(np.vdot(left_tan,left_tan))\n right_tan = path[current_ind+1].get_positions() - path[current_ind].get_positions()\n right_tan /=np.sqrt(np.vdot(right_tan,right_tan))\n lforce = np.vdot(forces,left_tan)\n rforce = np.vdot(forces,right_tan)\n #l_r_forces.append([lforce,rforce])\n #Collect the min force\n force_list.insert(current_ind-1,np.min([lforce,rforce]))\n if self.verbose:\n inits.insert(current_ind-1, current_system.get_positions())\n og_forces.insert(current_ind-1,forces)\n #Check for the correct direction and then create the new image\n if rforce0:\n if self.metric=='force':\n #Want lowest force\n inds = np.argsort(self.force_list)[:self.relax_num]\n inds = np.sort(inds)\n #rimages = list(np.array(path)[inds])\n for ind in inds:\n rimages.append(self.path[ind+1])\n elif self.metric=='energy':\n #Want highest energy\n inds = np.argsort(self.energy_list)[-1*self.relax_num:]\n inds = np.sort(inds)\n #rimages=list(np.array(path)[inds])\n for ind in inds:\n rimages.append(self.path[ind+1])\n else:\n raise ValueError('%s is not a valid choice for the metric. Please use either \"force\" or \"energy\"' % metric)\n #for i in range(len(rimages)):\n # rimages[i] = Atoms(list(rimages[i]))\n return rimages\n\n #From ase. Modified to now be per image. I hope.\n #Seems to fail, so nevermind. need NEB forces or else all of the images are almost the same\n def mod_idpp_interpolate(self,path, traj='idpp.traj', log='idpp.log', fmax=0.1,\n optimizer=BFGS, mic=False):\n d1 = path[0].get_all_distances(mic=mic)\n d2 = path[-1].get_all_distances(mic=mic)\n d = (d2 - d1) / (len(path) - 1)\n old = []\n for i, image in enumerate(path):\n old.append(image.calc)\n image.calc = IDPP(d1 + i * d, mic=mic)\n opt = optimizer(image, trajectory=traj, logfile=log)\n opt.run(fmax=fmax)\n for image, calc in zip(path, old):\n image.calc = calc\n\n\n #Set the appropriate constraints and then relax the images\n #Outputs trajectory files and pckl file of energies\n def relax_images(self):\n energies =[]\n if self.write:\n geosteps=[]\n times=[]\n #Set the appropriate constraints\n for i,image in enumerate(self.relax_imgs):\n ads_inds = [j for j,a in enumerate(image) if a.tag==0]\n #FBL\n if isinstance(self.rxn_coord,tuple):\n assert len(self.rxn_coord)==2\n constraints = [FixBondLength(self.rxn_coord[0],self.rxn_coord[1])] \n #Relax perp to a vector\n elif isinstance(self.rxn_coord,np.ndarray):\n assert p.shape[0] ==len(image)\n assert p.shape[1] ==3 \n constraints=[FixedPlane(ai,self.rxn_coord[ai]) for ai in ads_inds]\n elif isinstance(self.rxn_coord,list):\n if isinstance(self.rxn_coord[0],list):\n #Perp again\n constraints=[FixedPlane(ai,self.rxn_coord[ai]) for ai in ads_inds]\n else:\n #FBL again\n constraints = [FixBondLength(self.rxn_coord[0],self.rxn_coord[1])]\n else:\n raise TypeError('The reaction coordinate must be a list, tuple, or numpy array')\n image.set_constraint(image.constraints+constraints)\n #Calc has to be reset. New outdir set as well.\n self.attach_calculator(image)\n image.get_calculator().set(outdir=self.outdir+'%i' % (i+1))\n #Optimizer and traj file is set and then we are off!\n opt = self.optimizer(image,logfile=self.logfile+'%i.log' % (i+1))\n traj = io.PickleTrajectory(self.traj +'%i.traj' % (i+1), 'w', image)\n opt.attach(traj)\n if self.write:\n c_,steps =opt.Aidan_run(fmax=0.02,threshold=0)\n geosteps.append(steps) \n else:\n opt.run(fmax=0.02)\n energies.append(image.get_potential_energy()) \n #Write the \"TS\" geometry to its own trajectory file\n write_trajectory(self.traj+'_TS.traj',[self.relax_imgs[np.argmax(energies)]])\n if self.write:\n self.geosteps=geosteps\n return energies \n \n #Quick curve fitting method from ASE's NEB class\n def fit0(self,E, F, R, cell=None, pbc=None):\n \"\"\"Constructs curve parameters from the NEB images.\"\"\"\n E = np.array(E) - E[0]\n n = len(E)\n Efit = np.empty((n - 1) * 20 + 1)\n Sfit = np.empty((n - 1) * 20 + 1)\n\n s = [0]\n dR = np.zeros_like(R)\n for i in range(n):\n if i < n - 1:\n dR[i] = R[i + 1] - R[i]\n if cell is not None and pbc is not None:\n dR[i], _ = find_mic(dR[i], cell, pbc)\n s.append(s[i] + sqrt((dR[i]**2).sum()))\n else:\n dR[i] = R[i] - R[i - 1]\n if cell is not None and pbc is not None:\n dR[i], _ = find_mic(dR[i], cell, pbc)\n\n lines = []\n dEds0 = None\n for i in range(n):\n d = dR[i]\n if i == 0:\n ds = 0.5 * s[1]\n elif i == n - 1:\n ds = 0.5 * (s[-1] - s[-2])\n else:\n ds = 0.25 * (s[i + 1] - s[i - 1])\n\n d = d / sqrt((d**2).sum())\n dEds = -(F[i] * d).sum()\n x = np.linspace(s[i] - ds, s[i] + ds, 3)\n y = E[i] + dEds * (x - s[i])\n lines.append((x, y))\n\n if i > 0:\n s0 = s[i - 1]\n s1 = s[i]\n x = np.linspace(s0, s1, 20, endpoint=False)\n c = np.linalg.solve(np.array([(1, s0, s0**2, s0**3),\n (1, s1, s1**2, s1**3),\n (0, 1, 2 * s0, 3 * s0**2),\n (0, 1, 2 * s1, 3 * s1**2)]),\n np.array([E[i - 1], E[i], dEds0, dEds]))\n y = c[0] + x * (c[1] + x * (c[2] + x * c[3]))\n Sfit[(i - 1) * 20:i * 20] = x\n Efit[(i - 1) * 20:i * 20] = y\n\n dEds0 = dEds\n\n Sfit[-1] = s[-1]\n Efit[-1] = E[-1]\n return s, E, Sfit, Efit, lines\n\n #Gets the barrier from the Drag calculation. Based off of the method from ASE's NEBtools. \n #If fit=True, the barrier is estimated based on the interpolated fit to the images; if fit=False,\n #the barrier is taken as the maximum energy image without interpolation.\n #Set raw=True to get the raw energy of the transition state instead of the forward barrier.\n def get_barrier(self,fit=False,raw=True):\n s, E, Sfit, Efit, lines = self.get_fit()\n dE = E[-1] - E[0]\n if fit:\n barrier = max(Efit)\n else:\n barrier = max(E)\n if raw:\n #Should this be relax_imgs instead? Do we have a calc for the IS?\n barrier += self.path[0].get_potential_energy()\n return barrier, dE\n\n #Makes a band plot on a matplotlib axes object, unless ax=None.\n #Adapeted from ASE's NEBtools\n def plot_band(self,ax=None):\n if not ax:\n from matplotlib import pyplot\n fig = pyplot.figure()\n ax = fig.add_subplot(111)\n else:\n fig = None\n s, E, Sfit, Efit, lines = self.get_fit()\n ax.plot(s, E, 'o')\n for x, y in lines:\n ax.plot(x, y, '-g')\n ax.plot(Sfit, Efit, 'k-')\n ax.set_xlabel('path [$\\AA$]')\n ax.set_ylabel('energy [eV]')\n Ef = max(Efit) - E[0]\n Er = max(Efit) - E[-1]\n dE = E[-1] - E[0]\n ax.set_title('$E_\\mathrm{f} \\\\approx$ %.3f eV; '\n '$E_\\mathrm{r} \\\\approx$ %.3f eV; '\n '$\\\\Delta E$ = %.3f eV'\n % (Ef, Er, dE))\n return fig\n\n #Used to create a fit to the Drag image results and return the results.\n #Adpated from ASE's NEBtools\n def get_fit(self):\n images = self.relax_imgs\n if not hasattr(images, 'repeat'):\n from ase.gui.images import Images\n images = Images(images)\n N = images.repeat.prod()\n natoms = images.natoms // N\n R = images.P[:, :natoms]\n E = images.E\n F = images.F[:, :natoms]\n s, E, Sfit, Efit, lines = fit0(E, F, R, images.A[0], images.pbc)\n return s, E, Sfit, Efit, lines\n\n\n#From ase\nclass IDPP(Calculator):\n \"\"\"Image dependent pair potential.\n\n See:\n\n Improved initial guess for minimum energy path calculations.\n\n Chem. Phys. 140, 214106 (2014)\n \n\"\"\"\n implemented_properties = ['energy', 'forces']\n\n def __init__(self, target, mic):\n Calculator.__init__(self)\n self.target = target\n self.mic = mic\n\n def calculate(self, atoms, properties, system_changes):\n Calculator.calculate(self, atoms, properties, system_changes)\n\n P = atoms.get_positions()\n d = []\n D = []\n for p in P:\n Di = P - p\n if self.mic:\n Di, di = find_mic(Di, atoms.get_cell(), atoms.get_pbc())\n else:\n di = np.sqrt((Di**2).sum(1))\n d.append(di)\n D.append(Di)\n d = np.array(d)\n D = np.array(D)\n\n dd = d - self.target\n d.ravel()[::len(d) + 1] = 1 # avoid dividing by zero\n d4 = d**4\n e = 0.5 * (dd**2 / d4).sum()\n f = -2 * ((dd * (1 - 2 * dd / d) / d**5)[..., np.newaxis] * D).sum(0)\n self.results = {'energy': e, 'forces': f}\n\n\n", "repo_name": "machinegungeek/drag_module", "sub_path": "AidanDrag.py", "file_name": "AidanDrag.py", "file_ext": "py", "file_size_in_byte": 27415, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "ase.optimize.QuasiNewton", "line_number": 53, "usage_type": "name"}, {"api_name": "ase.neb.NEB", "line_number": 89, "usage_type": "call"}, {"api_name": "ase.io.trajectory.write_trajectory", "line_number": 111, "usage_type": "call"}, {"api_name": "cPickle.dump", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 135, "usage_type": "call"}, {"api_name": "cPickle.dump", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.savez", "line_number": 140, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 140, "usage_type": "call"}, {"api_name": "ase.neb.NEB", "line_number": 161, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 208, "usage_type": "call"}, {"api_name": "numpy.vdot", "line_number": 208, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 210, "usage_type": "call"}, {"api_name": "numpy.vdot", "line_number": 210, "usage_type": "call"}, {"api_name": "numpy.vdot", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.vdot", "line_number": 212, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 215, "usage_type": "call"}, {"api_name": "ase.neb.NEB", "line_number": 227, "usage_type": "call"}, {"api_name": "ase.neb.NEB", "line_number": 246, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 274, "usage_type": "call"}, {"api_name": "numpy.vdot", "line_number": 274, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 276, "usage_type": "call"}, {"api_name": "numpy.vdot", "line_number": 276, "usage_type": "call"}, {"api_name": "numpy.vdot", "line_number": 277, "usage_type": "call"}, {"api_name": "numpy.vdot", "line_number": 278, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 280, "usage_type": "call"}, {"api_name": "copy.copy", "line_number": 296, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 308, "usage_type": "call"}, {"api_name": "numpy.vdot", "line_number": 308, "usage_type": "call"}, {"api_name": "numpy.vdot", "line_number": 321, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 322, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 326, "usage_type": "call"}, {"api_name": "numpy.vdot", "line_number": 326, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 328, "usage_type": "call"}, {"api_name": "numpy.vdot", "line_number": 328, "usage_type": "call"}, {"api_name": "numpy.vdot", "line_number": 329, "usage_type": "call"}, {"api_name": "numpy.vdot", "line_number": 330, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 331, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 341, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 342, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 348, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 349, "usage_type": "call"}, {"api_name": "ase.optimize.BFGS", "line_number": 362, "usage_type": "name"}, {"api_name": "ase.constraints.FixBondLength", "line_number": 389, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 391, "usage_type": "attribute"}, {"api_name": "ase.constraints.FixedPlane", "line_number": 394, "usage_type": "call"}, {"api_name": "ase.constraints.FixedPlane", "line_number": 398, "usage_type": "call"}, {"api_name": "ase.constraints.FixBondLength", "line_number": 401, "usage_type": "call"}, {"api_name": "ase.io.PickleTrajectory", "line_number": 410, "usage_type": "call"}, {"api_name": "ase.io", "line_number": 410, "usage_type": "name"}, {"api_name": "ase.io.trajectory.write_trajectory", "line_number": 419, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 419, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 427, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 429, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 430, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 433, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 458, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 465, "usage_type": "call"}, {"api_name": "numpy.linalg.solve", "line_number": 466, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 466, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 466, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 470, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 502, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 502, "usage_type": "name"}, {"api_name": "ase.gui.images.Images", "line_number": 528, "usage_type": "call"}, {"api_name": "ase.calculators.calculator.Calculator", "line_number": 539, "usage_type": "name"}, {"api_name": "ase.calculators.calculator.Calculator.__init__", "line_number": 552, "usage_type": "call"}, {"api_name": "ase.calculators.calculator.Calculator", "line_number": 552, "usage_type": "name"}, {"api_name": "ase.calculators.calculator.Calculator.calculate", "line_number": 557, "usage_type": "call"}, {"api_name": "ase.calculators.calculator.Calculator", "line_number": 557, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 567, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 570, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 571, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 577, "usage_type": "attribute"}]} +{"seq_id": "72647625326", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom data_creator import input_data\n\n\nplt.style.use('ggplot')\n\nnum_categories = int(input(\"Enter the number of categories: \"))\n\n# categories = []\n# for i in range(num_categories):\n# categories.append(input(f\"Enter category {i+1}: \"))\n\nnum_observers = int(input(\"Enter the number of observations: \"))\n\ndata = categories, data = input_data(num_categories, num_observers, 0, 100)\n\n\n\n\n\n\nangles=np.linspace(0,2*np.pi,num_categories, endpoint=False)\nprint(angles)\n\nangles=np.concatenate((angles,[angles[0]]))\nprint(angles)\n\n# HARDCOED FOR NOW DON'T JUDGE\n\ncategories.append(categories[0])\ndata[\"Ankkit\"].append(data[\"Ankkit\"][0])\n\n\n\n\nfig=plt.figure(figsize=(6,6))\nax=fig.add_subplot(polar=True)#basic plot\nax.plot(angles,data[\"Ankkit\"], 'o--', color='g', label='Ankkit')\n#fill plot\nax.fill(angles, data[\"Ankkit\"], alpha=0.25, color='g')\n#Add labels\nax.set_thetagrids(angles * 180/np.pi, categories)\nplt.grid(True)\nplt.tight_layout()\nplt.legend()\nplt.show()", "repo_name": "chpsmstr/Radar-Chart-Maker", "sub_path": "simple.py", "file_name": "simple.py", "file_ext": "py", "file_size_in_byte": 1005, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "matplotlib.pyplot.style.use", "line_number": 6, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 6, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 6, "usage_type": "name"}, {"api_name": "data_creator.input_data", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 23, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 43, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}]} +{"seq_id": "30372602074", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 13 11:36:19 2017\n\n@author: radhakrishnan\n\n@description: Optical setup consisting of a simple Shack-Hartmann wavefront\nsensor with deformable mirror. Atmospheric turbulence is simulated.\n\"\"\"\n## General imports\nfrom hcipy import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n## Create aperture and pupil grid\nwavelength = 1e-6\nN = 256\nD = 0.01\npupil_grid = make_pupil_grid(N, D)\nfocal_grid = make_focal_grid(pupil_grid, 8, 20, wavelength)\nprop = FraunhoferPropagator(pupil_grid, focal_grid)\naperture = circular_aperture(D)\n#aperture = rectangular_aperture(1,1)\n\n## Create the microlens array\nF_mla = 100\nN_mla = 20\n\nshwfs = SquareShackHartmannWavefrontSensorOptics(pupil_grid, F_mla, N_mla, D)\nshwfse = ShackHartmannWavefrontSensorEstimator(shwfs.mla_grid, shwfs.micro_lens_array.mla_index)\n\n## Create the wavefront at the entrance pupil\nwf = Wavefront(aperture(pupil_grid), wavelength)\n\n## Create the deformable mirror\nnum_modes = 60\ndm_modes = make_zernike_basis(num_modes, D, pupil_grid, 2, False)\nzernike_freeform = DeformableMirror(dm_modes)\n\nplt.ion()\nfor i in range(num_modes):\n\t## Extract the centers of the lenslets\n\tact_levels = np.zeros(num_modes)\n\tact_levels[i] = 1e-7\n\tzernike_freeform.actuators = act_levels\n\tdm_wf = zernike_freeform(wf)\n\tsh_wf = shwfs(dm_wf)\n\tsh_img = sh_wf.intensity\n\tlenslet_centers = shwfse.estimate([sh_img])\n\n\tplt.clf()\n\timshow_field(sh_img)\n\tplt.plot(lenslet_centers[0,:], lenslet_centers[1,:], 'r,')\n\tplt.colorbar()\n\tplt.draw()\n\tplt.pause(0.00001)\nplt.ioff()", "repo_name": "syhaffert/hcipy", "sub_path": "examples2/shack_hartmann_test.py", "file_name": "shack_hartmann_test.py", "file_ext": "py", "file_size_in_byte": 1550, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "2", "api": [{"api_name": "matplotlib.pyplot.ion", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 53, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 53, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.draw", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.pause", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 56, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ioff", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}]} +{"seq_id": "71620449661", "text": "import os\nimport math\nimport re\nimport lib\n\n## Author: Alexander Molodyh\n## Date: 10/21/2017\n## Class: CS360\n## Assignment: Python_Lab Part 1 and 2\n\n# inserts content into the designated file. \n# Ex: if we have an element \"look_at<%s, 0, %s>\" and we insert\n# x, z as our parameters, then look_at will become \ndef mod_file(file_to_mod, file_content):\n modded_file = file_to_mod % file_content\n return modded_file\n\n\n# generate a list that contains the pov modded file, pov output name \n# and image output name.\ndef create_pov_file_list(file_content):\n t = 0.0\n y = 2.6\n file_num = 0#the image and pov file name indexes\n radius_list = []\n while t < (2 * math.pi):\n z = -8 * math.cos(t)#z coordinate for the camera\n x = 8 * math.sin(t)# x coordinate for the camera\n x2 = (-2 * math.cos(t)) * -1 #x coordinate for the cylindar above the paper\n z2 = (2 * math.sin(t)) * -1#x coordinate for the cylindar above the paper\n y += .001#y coordinate for the camera\n t += .008;\n v1 = lib.Vector(x=x2, y=.5, z=z2)#cylinder vector for lower section\n v2 = lib.Vector(x=0, y=2, z=0)#cylinder vector for center section\n\n modded_file = get_replaced_cylinder(create_cylinder(v1, v2), file_content)\n modded_file = mod_file(modded_file, (x, y, z))#file with new coordinates\n out_pov_name = 'data\\\\%s.pov' % str(file_num)#pov output name\n out_image_name = 'img\\\\%s.png' % str(file_num)#image output name\n file_num += 1\n #file with changed x, and z coordinates pov file number and image number\n pov_tuple = (modded_file, out_pov_name, out_image_name)\n\n #contains the pov file content, number, and the image name for every iteration\n radius_list.append(pov_tuple)\n \n return radius_list\n\n\n#searches for the cylinder, replaces it and then returns a\n#new file with the modified areas.\ndef get_replaced_cylinder(cylinder, pov_file):\n cylinder_reg = r'cylinder {<(\\S+, \\S+, \\S+)>, <(\\S+, \\S+, \\S+)>, (\\S+) pigment {(\\S+)} finish { (\\S+)( )+(\\d) } }//to change'\n replaced = re.sub(cylinder_reg, cylinder.build(), pov_file)\n return replaced \n\n\n## Creates a cylinder object for pov-ray.\n## param v1, v2 must be Vectors from the lib.modifiers module.\ndef create_cylinder(v1, v2):\n pigment = lib.Pigment('Red')\n finish = lib.Finish('ambient', 2)\n items_list = [pigment, finish]\n cylinder = lib.Cylinder(v1, v2, .15, '', items_list)\n return cylinder\n\n\n# generates all of the pov files for every x, y, z iteration\ndef create_pov_files(pov_file_list):\n for pov in pov_file_list:\n create_pov_file(pov[0], pov[1])\n\n# generates a single pov file\ndef create_pov_file(file_content, out_file_name):\n file_output = open(out_file_name, 'w')\n file_output.write(file_content)\n file_output.close()\n return file_output\n\n\n# generates all of the images based off all the pov files\ndef create_images(pov_file_list):\n for pov in pov_file_list:\n create_image(pov[1], pov[2])\n\n# generates a single image file \ndef create_image(file_name, output_img_name):\n pov_cmd = \"pvengine.exe +I%s +O%s -D -V +A +H600 +W800 /EXIT\"\n cmd = pov_cmd % (file_name, output_img_name)\n os.system(cmd)\n\n# opens a file and returns it as a string\ndef open_file(filename):\n fin = open(filename)\n sdl = fin.read()\n fin.close\n return sdl\n\n\n#compiles the video from the image names provided in a list\ndef compile_movie(images):\n images_path = 'mencoder mf://@img/image_names -mf w=800:h=600:fps=35:type=png -ovc lavc \\\n -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o output.avi '\n os.system(images_path)\n\n#creates and returns a list of image names\ndef create_image_names_file(image_names_list):\n image_names_file = 'img/image_names'\n imgs_file = open(image_names_file, 'w')\n for img in image_names_list:\n imgs_file.write(img[2] + '\\n')\n imgs_file.close()\n return imgs_file\n\n\ndef main():\n pov_file = open_file('base.pov')#read in initial pov file\n #create a list of tuples containing modified pov files \n #and file names for both pov and image files.\n pov_file_list = create_pov_file_list(pov_file)\n create_pov_files(pov_file_list)#generates all the pov files\n create_images(pov_file_list)#generates all the image files\n img_names = create_image_names_file(pov_file_list)#creates a list of image names\n compile_movie(img_names)#compiles the movie\n\n\nif __name__ == '__main__':\n main()", "repo_name": "AlexMolodyh/CS360", "sub_path": "Week4/python_lab/animate.py", "file_name": "animate.py", "file_ext": "py", "file_size_in_byte": 4505, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "math.pi", "line_number": 26, "usage_type": "attribute"}, {"api_name": "math.cos", "line_number": 27, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 28, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 29, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 30, "usage_type": "call"}, {"api_name": "lib.Vector", "line_number": 33, "usage_type": "call"}, {"api_name": "lib.Vector", "line_number": 34, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 54, "usage_type": "call"}, {"api_name": "lib.Pigment", "line_number": 61, "usage_type": "call"}, {"api_name": "lib.Finish", "line_number": 62, "usage_type": "call"}, {"api_name": "lib.Cylinder", "line_number": 64, "usage_type": "call"}, {"api_name": "os.system", "line_number": 90, "usage_type": "call"}, {"api_name": "os.system", "line_number": 104, "usage_type": "call"}]} +{"seq_id": "40424602141", "text": "#!/usr/bin/python3\n\nfrom collections import deque\nimport re\nfrom sys import stdin\n\nstate_parser = re.compile(r'initial state: ([.#]+)')\nrule_parser = re.compile(r'([.#]+) => ([.#])')\n\nclass pottrie(object):\n def __init__(self, state):\n self.children = dict()\n self.state = state\n\npottrie = dict()\n\ndef rotated(lst, n):\n for i in range(len(lst)):\n yield lst[(i + n) % len(lst)]\n\ndef add_rule(rule, output):\n # start with root\n node = pottrie\n\n # rearrange so we look from center to right then back from left\n states = rule[2:] + rule[0:2]\n\n for state in rotated(rule, 2):\n if state not in node:\n node[state] = dict()\n node = node[state]\n\n node['value'] = output\n\ndef apply_rules(states):\n node = pottrie\n current = states[2]\n\n for state in rotated(states, 2):\n if state not in node:\n return current\n node = node[state]\n\n return node['value']\n\ndef parse_input():\n initial = state_parser.match(next(stdin)).group(1)\n \n #skip blank line\n next(stdin)\n\n for line in stdin:\n rule, output = rule_parser.match(line).groups()\n\n # only care about rules that actually change the pot\n if rule[2] != output:\n add_rule(rule, output)\n\n return (deque(initial), 0)\n\ndef windows(pots):\n window = deque(['.'] * 5)\n\n for pot in pots:\n window.popleft()\n window.append(pot)\n\n yield window\n\n for _ in range(4):\n window.popleft()\n window.append('.')\n\n yield window\n\ndef next_state(pots, start):\n next_pots = deque()\n next_start = start - 2\n\n for window in windows(pots):\n next_pots.append(apply_rules(window))\n\n # trim left\n left = next_pots.popleft()\n while left == '.':\n left = next_pots.popleft()\n next_start += 1\n next_pots.appendleft(left)\n\n # trim right\n right = next_pots.pop()\n while right == '.':\n right = next_pots.pop()\n next_pots.append(right)\n\n return next_pots, next_start\n\ndef sum_pots(pots, start):\n total = 0\n index = start\n\n for pot in pots:\n if pot == '#':\n total += index\n index += 1\n\n return total\n\npots, start = parse_input()\nseen = {}\n\nfor gen in range(20):\n pots, start = next_state(pots, start)\n\nprint(sum_pots(pots, start))\n\nTARGET = 50000000000\n# while generating out to practically infinity, look for a cycle\nfor gen in range(20, TARGET):\n pots, start = next_state(pots, start)\n key = ''.join(pots)\n if key in seen:\n # we've found a cycle, compute start offset based on gen offet\n prev_gen, prev_start = seen[key]\n offset_start = start - prev_start\n offset_gen = gen - prev_gen\n remaining_gens = TARGET - gen - 1 # this off by one haunts me\n\n # compute the start into the future\n # sanity check we get there nicely (they wouldn't give us an evil puzzle would they?)\n if remaining_gens % offset_gen != 0:\n raise 'cannot reach target in whole steps'\n\n future_start = remaining_gens // offset_gen * offset_start + start\n\n print(sum_pots(pots, future_start))\n break\n seen[key] = (gen, start)\n\n \n", "repo_name": "djimenez/aoc", "sub_path": "aoc2018/12/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 3209, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "re.compile", "line_number": 7, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 8, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 47, "usage_type": "argument"}, {"api_name": "sys.stdin", "line_number": 50, "usage_type": "argument"}, {"api_name": "sys.stdin", "line_number": 52, "usage_type": "name"}, {"api_name": "collections.deque", "line_number": 59, "usage_type": "call"}, {"api_name": "collections.deque", "line_number": 62, "usage_type": "call"}, {"api_name": "collections.deque", "line_number": 77, "usage_type": "call"}]} +{"seq_id": "5369552422", "text": "\"\"\"CLI for crawling through results from sweeps and processing that data\n\"\"\"\n\nimport argparse\nimport os\nfrom pathlib import Path\nfrom utils import METRICS, get_metrics_from_folder\n\n# Parse commandline for input directory for getting results from\nparser = argparse.ArgumentParser(description=\"Process a sweep of the control parameters\")\nparser.add_argument(\"top_directory\", help=\"Top level directory containing sweep results\")\nargs = parser.parse_args()\n\n# Get the paths for all the folders containing results\nresult_dirs = [args.top_directory + folder for folder in os.listdir(args.top_directory)]\n\n# Create overall dictionary containing results\n# format: results_dict[(k, offset)] = RobotInfo\n# Save directories for any results that couldn't be processed\nbad_results = []\nresults_dict = {}\nfor result_dir in result_dirs:\n result_folder = result_dir.split('/')[-1]\n k = result_folder.split('_')[1]\n offset = result_folder.split('_')[3]\n try:\n metrics = get_metrics_from_folder(Path(result_dir))\n except FileNotFoundError:\n bad_results.append(result_folder)\n print(f\"k: {k} | offset: {offset} | metrics:\\n{metrics}\")\n results_dict[(k, offset)] = metrics\n", "repo_name": "melindamalley/ArmyAntSim", "sub_path": "process_data/process_control_sweeps.py", "file_name": "process_control_sweeps.py", "file_ext": "py", "file_size_in_byte": 1188, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 10, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 15, "usage_type": "call"}, {"api_name": "utils.get_metrics_from_folder", "line_number": 27, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 27, "usage_type": "call"}]} +{"seq_id": "71885316845", "text": "from bs4 import BeautifulSoup\nfrom contextlib import closing\nfrom selenium import webdriver\nfrom selenium.webdriver import Firefox,Chrome\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport logging\nimport pandas as pd\nimport re\nimport requests\nimport string\nimport sys\nimport unidecode\nimport urllib\n\ndef findLink(url,year):\n\ttry:\n\t\theaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}\n\t\tpage=requests.get(url,headers=headers)\n\t\tif page.status_code==200:\n\t\t\tsoup=BeautifulSoup(page.text,'html.parser')\n\t\t\tlink=soup.find('h1').find('a')['href']\n\t\telse:\n\t\t\tprint(page.status_code)\n\t\t\tlink='error'\n\t\twith open('yearUrlWebby/WebbyUrl'+year+'.csv','a+') as f:\n\t\t\tf.write(link+'\\n')\n\t\treturn link\n\texcept:\n\t\treturn url+'#'*10\n\ndef setDriverOptions():\n\toptions \t\t\t\t= Options()\n\toptions.binary_location = 'webEvPy/bin/chromium-browser'\n\tchrome_driver_binary\t= 'webEvPy/bin/chromedriver'\n\toptions.add_argument('--headless')\n\treturn\twebdriver.Chrome(options=options)\n\ndef main(filename,year):\n\tbrowser=setDriverOptions()\n\tcat=pd.read_csv(filename)\n\twith open('yearUrlWebby/WebbyUrl'+year+'.csv','a+') as f:\n\t\tf.write('urls\\n')\n\tfor category in cat['category']:\n\t\turl='https://www.webbyawards.com/winners/'+str(year)+str(category).strip()\n\t\tbrowser.get(url)\n\t\tbrowser.implicitly_wait(10)\n\t\theader = browser.find_elements_by_tag_name('h2')\n\t\tWebDriverWait(browser, timeout=10).until(lambda x: x.find_elements_by_tag_name('h2'))\n\t\tpage_source = browser.page_source\n\t\tsoup=BeautifulSoup(page_source,'html.parser')\n\t\tlinks=soup.findAll('h2',{'class':'mod-winners-gallery__title'})\n\t\twith open('yearUrlWebby/WebbyUrl'+year+'.csv','a+') as f:\n\t\t\tfor i in links:\n\t\t\t\tl=i.find('a')\n\t\t\t\tnextUrl='https://www.webbyawards.com'+str(l['href'])\n\t\t\t\tprint(category,findLink(nextUrl,str(year)))\n\nif __name__=='__main__':\n\tfilename \t= sys.argv[-1]\n\tyear\t\t= sys.argv[-2]\n\tmain(filename,year)\n", "repo_name": "ABHISHEKVALSAN/Website-Evolution", "sub_path": "src/webbyUrls.py", "file_name": "webbyUrls.py", "file_ext": "py", "file_size_in_byte": 2025, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "2", "api": [{"api_name": "requests.get", "line_number": 19, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 21, "usage_type": "call"}, {"api_name": "selenium.webdriver.chrome.options.Options", "line_number": 33, "usage_type": "call"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 37, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 37, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 41, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.ui.WebDriverWait", "line_number": 49, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 51, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 60, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 61, "usage_type": "attribute"}]} +{"seq_id": "32166697630", "text": "# Standard libraries\nimport os\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\n\n# Seeds\nimport random\n\n# PyTorch\nimport torch\nimport torch.utils.data as data\n\n# Custom libraries\nfrom networks.SimpleMLPs import MLPsumV2\nfrom dataloader_pickles import DataloaderEvalV5\nimport utils\n\n# Average profiles preprocessing\nfrom pycytominer.operations.transform import RobustMAD\nfrom pycytominer import feature_select\n\n# Statistics\nimport scipy.stats as stats\n\n# Argument parser\nimport argparse\n\n\ndef fulleval(args):\n ##\n NUM_WORKERS = 0\n device = torch.device(\"cuda:0\") if torch.cuda.is_available() else torch.device(\"cpu\")\n print(\"Device:\", device)\n print(\"Number of workers:\", NUM_WORKERS)\n\n # Set random seed for reproducibility\n manualSeed = 42\n print(\"Random Seed:\", manualSeed)\n random.seed(manualSeed)\n torch.manual_seed(manualSeed)\n np.random.seed(manualSeed)\n\n ## Load model\n save_name_extension = 'model_bestval_simpleMLP_V1' # extension of the saved model\n model_name = save_name_extension\n print('Loading:', model_name)\n\n input_dim = args.model_input_size\n kFilters = args.kfilters\n latent_dim = 2048\n output_dim = 2048\n model = MLPsumV2(input_dim=input_dim, latent_dim=latent_dim, output_dim=output_dim,\n k=kFilters, dropout=0, cell_layers=1,\n proj_layers=2, reduction='sum')\n if torch.cuda.is_available():\n model.cuda()\n\n save_features_to_csv = args.save_csv_features\n train_val_split = 1.0\n\n percent_matching = args.find_sister_compounds # If false calculate percent replicating\n\n if percent_matching:\n encoding_label = 'moa'\n mAP_label = 'Metadata_moa'\n bestMOAs = pd.DataFrame()\n else:\n encoding_label = 'pert_iname'\n mAP_label = 'Metadata_pert_iname'\n\n dataset_name = args.dataset_name\n MAPfilename = f'mAP_{dataset_name}_{args.dose_point}'\n\n path = args.model_path\n fullpath = os.path.join(path, 'files', model_name)\n\n if 'ckpt' in model_name:\n model.load_state_dict(torch.load(fullpath)['model_state_dict'])\n else:\n model.load_state_dict(torch.load(fullpath))\n model.eval()\n\n\n remove_noisy_cells = True\n\n if input_dim == 1745:\n remove_columns = ['Cells_RadialDistribution_FracAtD_DNA_1of4', 'Cells_RadialDistribution_FracAtD_DNA_2of4',\n 'Cells_RadialDistribution_FracAtD_DNA_3of4', 'Cells_RadialDistribution_FracAtD_DNA_4of4',\n 'Cells_RadialDistribution_MeanFrac_DNA_1of4', 'Cells_RadialDistribution_MeanFrac_DNA_2of4',\n 'Cells_RadialDistribution_MeanFrac_DNA_3of4', 'Cells_RadialDistribution_MeanFrac_DNA_4of4',\n 'Cells_RadialDistribution_RadialCV_DNA_1of4', 'Cells_RadialDistribution_RadialCV_DNA_2of4',\n 'Cells_RadialDistribution_RadialCV_DNA_3of4', 'Cells_RadialDistribution_RadialCV_DNA_4of4',\n 'Cytoplasm_RadialDistribution_FracAtD_DNA_1of4', 'Cytoplasm_RadialDistribution_FracAtD_DNA_2of4',\n 'Cytoplasm_RadialDistribution_FracAtD_DNA_3of4', 'Cytoplasm_RadialDistribution_FracAtD_DNA_4of4',\n 'Cytoplasm_RadialDistribution_MeanFrac_DNA_1of4', 'Cytoplasm_RadialDistribution_MeanFrac_DNA_2of4',\n 'Cytoplasm_RadialDistribution_MeanFrac_DNA_3of4', 'Cytoplasm_RadialDistribution_MeanFrac_DNA_4of4',\n 'Cytoplasm_RadialDistribution_RadialCV_DNA_1of4', 'Cytoplasm_RadialDistribution_RadialCV_DNA_2of4',\n 'Cytoplasm_RadialDistribution_RadialCV_DNA_3of4', 'Cytoplasm_RadialDistribution_RadialCV_DNA_4of4',\n 'Nuclei_RadialDistribution_FracAtD_DNA_1of4', 'Nuclei_RadialDistribution_FracAtD_DNA_2of4',\n 'Nuclei_RadialDistribution_FracAtD_DNA_3of4', 'Nuclei_RadialDistribution_FracAtD_DNA_4of4',\n 'Nuclei_RadialDistribution_MeanFrac_DNA_1of4', 'Nuclei_RadialDistribution_MeanFrac_DNA_2of4',\n 'Nuclei_RadialDistribution_MeanFrac_DNA_3of4', 'Nuclei_RadialDistribution_MeanFrac_DNA_4of4',\n 'Nuclei_RadialDistribution_RadialCV_DNA_1of4', 'Nuclei_RadialDistribution_RadialCV_DNA_2of4',\n 'Nuclei_RadialDistribution_RadialCV_DNA_3of4', 'Nuclei_RadialDistribution_RadialCV_DNA_4of4']\n else:\n remove_columns = None\n\n\n ## Load all data\n rootDir = fr'datasets/{dataset_name}'\n plateDirs = [x[0] for x in os.walk(rootDir)][1:]\n platenames = [x.split('_')[-1] for x in plateDirs]\n\n metadata_dir = args.metadata_path # path to metadata\n barcode_platemap = pd.read_csv(os.path.join(metadata_dir, 'barcode_platemap.csv'), index_col=False)\n barcode_platemap = barcode_platemap[barcode_platemap['Assay_Plate_Barcode'].isin(platenames)]\n\n repurposing_info = pd.read_csv(os.path.join(metadata_dir, 'repurposing_info_long.tsv'), index_col=False,\n low_memory=False, sep='\\t', usecols=[\"broad_id\", \"pert_iname\", \"moa\"])\n repurposing_info = repurposing_info.rename(columns={\"broad_id\": \"broad_sample\"})\n repurposing_info = repurposing_info.drop_duplicates()\n\n platemaps = barcode_platemap['Plate_Map_Name'].tolist()\n platenames = barcode_platemap['Assay_Plate_Barcode'].tolist()\n\n plateDirs = ['DataLoader_'+x for x in platenames]\n\n if remove_columns is None:\n holdouts = ['SQ00015116', 'SQ00015117', 'SQ00015118', 'SQ00015119', 'SQ00015120', 'SQ00015121', 'SQ00015122',\n 'SQ00015123', 'SQ00015125', 'SQ00015126'] # with 1745 features\n I = [i for i, y in enumerate(platenames) if y in holdouts]\n for ele in sorted(I, reverse=True):\n del plateDirs[ele]\n del platemaps[ele]\n del platenames[ele]\n\n assert len(plateDirs) == len(platenames) == len(platemaps)\n\n # Initialize variables\n average_perturbation_map = {}\n\n bigdf = []\n for i, pDir in enumerate(plateDirs):\n platestring = pDir.split('_')[-1]\n print('Getting data from: ' + platestring)\n C_plate_map = pd.read_csv(os.path.join(metadata_dir, 'platemap', platemaps[i]+'.txt'), sep='\\t')\n C_metadata = utils.addDataPathsToMetadata(rootDir, C_plate_map, pDir)\n if args.dose_point == '10':\n df = C_metadata[np.logical_and(C_metadata['mmoles_per_liter'] > 9, C_metadata['mmoles_per_liter'] < 11)]\n elif args.dose_point == '3':\n df = C_metadata[np.logical_and(C_metadata['mmoles_per_liter'] > 2.9, C_metadata['mmoles_per_liter'] < 6)]\n bigdf.append(df)\n\n bigdf = pd.merge(pd.concat(bigdf), repurposing_info, on='broad_sample', how='left')\n bigdf = utils.filterData(bigdf, 'negcon', encode='pert_iname', mode='LINCS')\n shape1 = bigdf.shape[0]\n bigdf.dropna(inplace=True) # drop all compounds without annotations for pert_iname (and moa)\n shape2 = bigdf.shape[0]\n print(\"Removed\", shape1-shape2, \"wells due to missing annotation of pert_iname and moa.\")\n bigdf = bigdf[bigdf.Metadata_labels.duplicated(keep=False)]\n shape3 = bigdf.shape[0]\n print(\"Removed\", shape2-shape3, \"unique compound wells.\")\n print('Using', shape3, \"wells\")\n\n Total, _ = utils.train_val_split(bigdf, 1.0, sort=True)\n ValDataset = DataloaderEvalV5(Total, remove_columns=remove_columns, remove_noisy_cells=remove_noisy_cells)\n loader = data.DataLoader(ValDataset, batch_size=1, shuffle=False,\n drop_last=False, pin_memory=False, num_workers=NUM_WORKERS)\n\n\n ## Create feature dataframes\n MLP_profiles = pd.DataFrame()\n average_profiles = pd.DataFrame()\n filtered_average_profiles = pd.DataFrame()\n\n print('Calculating Features')\n\n with torch.no_grad():\n for (points, labels, filtered_points) in tqdm(loader):\n if points.shape[1] == 1:\n continue\n #points = torch.zeros(1, 1, args.model_input_size)\n\n feats, _ = model(points)\n # Append everything to dataframes\n c1 = pd.concat([pd.DataFrame(feats), pd.Series(labels)], axis=1)\n MLP_profiles = pd.concat([MLP_profiles, c1])\n\n # Calculate benchmark\n c2 = pd.concat([pd.DataFrame(points.mean(dim=1)), pd.Series(labels)], axis=1)\n average_profiles = pd.concat([average_profiles, c2])\n\n # Calculate filtered benchmark\n c3 = pd.concat([pd.DataFrame(filtered_points.mean(dim=1)), pd.Series(labels)], axis=1)\n filtered_average_profiles = pd.concat([filtered_average_profiles, c3])\n\n\n ## Rename columns and normalize features\n # Rename feature columns\n MLP_profiles.columns = [f\"f{x}\" for x in range(MLP_profiles.shape[1] - 1)] + ['Metadata_labels']\n average_profiles.columns = [f\"Cells_{x}\" for x in range(average_profiles.shape[1] - 1)] + ['Metadata_labels']\n filtered_average_profiles.columns = [f\"Cells_{x}\" for x in range(filtered_average_profiles.shape[1] - 1)] + ['Metadata_labels']\n\n MLP_profiles = MLP_profiles[MLP_profiles.Metadata_labels.duplicated(keep=False)] # filter out non-replicates\n average_profiles = average_profiles[average_profiles.Metadata_labels.duplicated(keep=False)] # filter out non-replicates\n filtered_average_profiles = filtered_average_profiles[filtered_average_profiles.Metadata_labels.duplicated(keep=False)] # filter out non-replicates\n\n MLP_profiles.reset_index(drop=True, inplace=True)\n average_profiles.reset_index(drop=True, inplace=True)\n filtered_average_profiles.reset_index(drop=True, inplace=True)\n\n print('MLP_profiles shape: ', MLP_profiles.shape)\n print('average_profiles shape: ', average_profiles.shape)\n print('filtered_average_profiles shape: ', filtered_average_profiles.shape)\n\n ## Preprocess the average profiles\n import time\n st = time.time()\n scaler = RobustMAD(epsilon=0)\n fitted_scaler = scaler.fit(average_profiles.iloc[:, :-1])\n features = fitted_scaler.transform(average_profiles.iloc[:, :-1])\n features = feature_select(average_profiles.iloc[:, :-1], operation=[\"variance_threshold\",\n \"correlation_threshold\",\n \"drop_na_columns\",\n \"blocklist\"])\n average_profiles = pd.concat([features, average_profiles.iloc[:, -1]], axis=1)\n et = time.time()\n print('Average preprocessing time is ', et - st)\n\n scaler = RobustMAD(epsilon=0)\n fitted_scaler = scaler.fit(filtered_average_profiles.iloc[:, :-1])\n features = fitted_scaler.transform(filtered_average_profiles.iloc[:, :-1])\n features = feature_select(filtered_average_profiles.iloc[:, :-1], operation=[\"variance_threshold\",\n \"correlation_threshold\",\n \"drop_na_columns\",\n \"blocklist\"])\n filtered_average_profiles = pd.concat([features, filtered_average_profiles.iloc[:, -1]], axis=1)\n\n ## Save all the dataframes to .csv files!\n try:\n os.mkdir(args.output_path)\n except:\n pass\n\n try:\n os.mkdir(f'{args.output_path}/{dataset_name}_profiles')\n except:\n pass\n\n\n if save_features_to_csv:\n MLP_profiles.to_csv(f'{args.output_path}/{dataset_name}_profiles/MLP_profiles_{args.dose_point}.csv', index=False)\n average_profiles.to_csv(f'{args.output_path}/{dataset_name}_profiles/average_profiles_{args.dose_point}.csv', index=False)\n filtered_average_profiles.to_csv(f'{args.output_path}/{dataset_name}_profiles/filtered_average_profiles_{args.dose_point}.csv', index=False)\n split = int(MLP_profiles.shape[0] * train_val_split)\n\n temp_df = bigdf[['Metadata_labels', 'moa', 'pert_iname']][~bigdf.Metadata_labels.duplicated(keep='last')]\n temp_df = temp_df.rename(columns={'moa': 'Metadata_moa', 'pert_iname': 'Metadata_pert_iname'})\n MLP_profiles = pd.merge(MLP_profiles, temp_df, on='Metadata_labels')\n average_profiles = pd.merge(average_profiles, temp_df, on='Metadata_labels')\n filtered_average_profiles = pd.merge(filtered_average_profiles, temp_df, on='Metadata_labels')\n\n print('Dropping ', MLP_profiles.shape[0] - MLP_profiles.dropna().reset_index(drop=True).shape[0], 'rows due to NaNs')\n MLP_profiles = MLP_profiles.dropna().reset_index(drop=True)\n average_profiles = average_profiles.dropna().reset_index(drop=True)\n filtered_average_profiles = filtered_average_profiles.dropna().reset_index(drop=True)\n print('New size:', MLP_profiles.shape)\n shuffled_profiles = average_profiles.copy()\n shuffled_profiles.iloc[:, :-3] = pd.DataFrame.from_records(np.ones(shuffled_profiles.iloc[:, :-3].shape))\n\n ## Calculate mean average precision\n ap_mlp = utils.CalculateMAP(MLP_profiles, 'cosine_similarity',\n groupby=mAP_label, percent_matching=percent_matching)\n ap_bm = utils.CalculateMAP(average_profiles, 'cosine_similarity',\n groupby=mAP_label, percent_matching=percent_matching)\n ap_bm_filtered = utils.CalculateMAP(filtered_average_profiles, 'cosine_similarity',\n groupby=mAP_label, percent_matching=percent_matching)\n ap_shuffled = utils.CalculateMAP(shuffled_profiles, 'cosine_similarity',\n groupby=mAP_label, percent_matching=percent_matching)\n\n ap_mlp['compound'] = ap_mlp.compound.str.replace('|', '/')\n ap_bm['compound'] = ap_bm.compound.str.replace('|', '/')\n ap_bm_filtered['compound'] = ap_bm_filtered.compound.str.replace('|', '/')\n\n # Save results\n ap_mlp['count'] = [1]*len(ap_mlp)\n ap_bm['count'] = [1]*len(ap_bm)\n ap_bm_filtered['count'] = [1]*len(ap_bm_filtered)\n\n try:\n os.mkdir(f'{args.output_path}/{dataset_name}')\n except:\n pass\n ap_mlp.groupby('compound').agg({'AP': 'mean', 'count': 'sum'}).to_csv(f'{args.output_path}/{dataset_name}/MLP_mAP_{args.dose_point}_{encoding_label}.csv')\n ap_bm.groupby('compound').agg({'AP': 'mean', 'count': 'sum'}).to_csv(f'{args.output_path}/{dataset_name}/average_mAP_{args.dose_point}_{encoding_label}.csv')\n ap_bm_filtered.groupby('compound').agg({'AP': 'mean', 'count': 'sum'}).to_csv(f'{args.output_path}/{dataset_name}/filtered_average_mAP_{args.dose_point}_{encoding_label}.csv')\n\n ap_mlp.to_csv(f'{args.output_path}/{dataset_name}/raw_MLP_mAP_{args.dose_point}_{encoding_label}.csv')\n ap_bm.to_csv(f'{args.output_path}/{dataset_name}/raw_average_mAP_{args.dose_point}_{encoding_label}.csv')\n ap_bm_filtered.to_csv(f'{args.output_path}/{dataset_name}/raw_filtered_average_mAP_{args.dose_point}_{encoding_label}.csv')\n\n print('Total mean mAP MLP:', ap_mlp.AP.mean(), '\\nTotal mean precision at R MLP:', ap_mlp['precision at R'].mean())\n print(ap_mlp.groupby('compound').mean().sort_values('AP').iloc[-30:, :].round(4).to_markdown())\n print('\\n')\n print('Total mean mAP BM:', ap_bm.AP.mean(), '\\nTotal mean precision at R BM:', ap_bm['precision at R'].mean())\n print(ap_bm.groupby('compound').mean().sort_values('AP').iloc[-30:, :].round(4).to_markdown())\n print('\\n')\n print('Total mean mAP filtered BM:', ap_bm_filtered.AP.mean(), '\\nTotal mean precision at R BM:', ap_bm_filtered['precision at R'].mean())\n print(ap_bm_filtered.groupby('compound').mean().sort_values('AP').iloc[-30:, :].round(4).to_markdown())\n print('\\n')\n print('Total mean mAP shuffled:', ap_shuffled.AP.mean(), '\\nTotal mean precision at R shuffled:', ap_shuffled['precision at R'].mean())\n\n print('\\n')\n # Conduct Welch's t-Test and print the result\n print(\"Welch's t-test between mlp mAP and bm mAP:\", stats.ttest_ind(np.array(ap_mlp.AP), np.array(ap_bm.AP), equal_var=False))\n print('\\n')\n\n # WRITE TO FILE\n try:\n os.mkdir(f'{args.output_path}/mAPs')\n except:\n pass\n\n f = open(f'{args.output_path}/mAPs/{MAPfilename}.txt', 'a')\n f.write('\\n')\n f.write('\\n')\n f.write(f'Dataset: {args.dataset_name}')\n f.write('\\n')\n f.write('\\n')\n f.write('MLP results')\n f.write('\\n')\n f.write('Total mean:' + str(ap_mlp.AP.mean()))\n f.write('\\n')\n f.write(f'Training samples || mean:{ap_mlp.iloc[:split,1].mean()}\\n' + ap_mlp.iloc[:split, :].groupby(\n 'compound').mean().sort_values(by='AP',ascending=False).to_markdown())\n f.write('\\n')\n f.write(f'Validation samples || mean:{ap_mlp.iloc[split:,1].mean()}\\n' + ap_mlp.iloc[split:, :].groupby(\n 'compound').mean().sort_values(by='AP',ascending=False).to_markdown())\n f.write('\\n')\n f.write('\\n')\n f.write('BM results')\n f.write('\\n')\n f.write('Total mean:' + str(ap_bm.AP.mean()))\n f.write('\\n')\n f.write(f'Training samples || mean:{ap_bm.iloc[:split, 1].mean()}\\n' + ap_bm.iloc[:split, :].groupby(\n 'compound').mean().sort_values(by='AP', ascending=False).to_markdown())\n f.write('\\n')\n f.write(f'Validation samples || mean:{ap_bm.iloc[split:, 1].mean()}\\n' + ap_bm.iloc[split:, :].groupby(\n 'compound').mean().sort_values(by='AP', ascending=False).to_markdown())\n f.write('\\n')\n f.write('\\n')\n f.write('Shuffled results')\n f.write('\\n')\n f.write('Total mean:' + str(ap_shuffled.AP.mean()))\n f.write('\\n')\n f.write(f'Training samples || mean:{ap_shuffled.iloc[:split, 1].mean()}\\n' + ap_shuffled.iloc[:split, :].groupby(\n 'compound').mean().sort_values(by='AP', ascending=False).to_markdown())\n f.write('\\n')\n f.write(f'Validation samples || mean:{ap_shuffled.iloc[split:, 1].mean()}\\n' + ap_shuffled.iloc[split:, :].groupby(\n 'compound').mean().sort_values(by='AP', ascending=False).to_markdown())\n f.close()\n\n # Add to a large dataframe\n if percent_matching:\n allresultsdf =pd.DataFrame({'mAP model': [ap_mlp.iloc[:, 1].mean()],\n 'mAP BM': [ap_bm.iloc[:, 1].mean()],\n 'mAP filtered BM': [ap_bm_filtered.iloc[:, 1].mean()],\n 'mAP shuffled': [ap_shuffled.iloc[:, 1].mean()]})\n sorted_dictionary = {k: [v] for k, v in sorted(average_perturbation_map.items(), key=lambda item: item[1], reverse=True)}\n bestmoas = pd.DataFrame(sorted_dictionary)\n else:\n allresultsdf = pd.DataFrame({'Training mAP model': [ap_mlp.iloc[:split, 1].mean()],\n 'Training mAP BM': [ap_bm.iloc[:split, 1].mean()],\n 'Training mAP filtered BM': [ap_bm_filtered.iloc[:split, 1].mean()],\n 'Training mAP shuffled': [ap_shuffled.iloc[:split, 1].mean()],\n 'Validation mAP model': [ap_mlp.iloc[split:, 1].mean()],\n 'Validation mAP BM': [ap_bm.iloc[split:, 1].mean()],\n 'Validation mAP filtered BM': [ap_bm_filtered.iloc[split:, 1].mean()],\n 'Validation mAP shuffled': [ap_shuffled.iloc[split:, 1].mean()]})\n\n ## Organize all results and save them\n PLATES = [x.split('_')[-1] for x in plateDirs]\n PLATES.sort()\n allresultsdf['plate'] = '_'.join(PLATES)\n\n allresultsdf = allresultsdf.set_index('plate')\n print(allresultsdf.round(4).to_markdown())\n\n if percent_matching:\n allresultsdf.to_csv(f'{args.output_path}/{dataset_name}_moa_map.csv')\n else:\n allresultsdf.to_csv(f'{args.output_path}/{dataset_name}_replicating_map.csv')\n\n if percent_matching:\n bestmoas.to_csv(f'{args.output_path}/bestMoAs_{dataset_name}.csv')\n\n\n\n## MAIN\nif __name__=='__main__':\n # Instantiate the parser\n parser = argparse.ArgumentParser(description=\"Evaluate a trained model by calculating mAP for either\"\n \"finding a compound's replicate or sister compound.\",\n fromfile_prefix_chars='@')\n\n # Optional positional argument\n parser.add_argument('model_input_size', nargs='?', const=1781, type=int,\n help='Number of single cell features.')\n # Optional positional argument\n parser.add_argument('kfilters', nargs='?', const=1/2, type=float,\n help='Times division of the number of filters in the hidden model layers')\n # Optional positional argument\n parser.add_argument('save_csv_features', nargs='?', const=True, type=bool,\n help='If True save the model aggregated profiles as a .csv file.')\n # Optional positional argument\n parser.add_argument('find_sister_compounds', nargs='?', const=False, type=bool,\n help='If True calculate mAP for finding sister compounds, for compound replicates if False.')\n\n # Optional positional argument\n parser.add_argument('dataset_name', nargs='?', const='LINCS', type=str,\n help='Dataset name')\n # Optional positional argument\n parser.add_argument('model_path', nargs='?', const='wandb/latest-run/files', type=str,\n help='Number of epochs to train the model')\n # Optional positional argument\n parser.add_argument('metadata_path', nargs='?', const='aws_scripts/metadata/platemaps/2016_04_01_a549_48hr_batch1',\n type=str, help='Number of epochs to train the model')\n # Optional positional argument\n parser.add_argument('dose_point', nargs='?', const='10', type=str,\n help='Dose point for which to calculate the metrics. Either 10 or 3.33 uM')\n # Optional positional argument\n parser.add_argument('output_path', nargs='?', const='FinalModelResults/mAP', type=str, help='Path to save all output files')\n\n # Parse arguments\n args = parser.parse_args()\n\n print(\"Argument values:\")\n print('model input size:', args.model_input_size)\n print('kfilters:', args.kfilters)\n print('find sister compounds:', args.find_sister_compounds)\n print('dataset name:', args.dataset_name)\n print('model path:', args.model_path)\n print('metadata path:', args.metadata_path)\n print('dose point:', args.dose_point)\n print('output_path:', args.output_path)\n\n fulleval(args)\n\n", "repo_name": "carpenter-singh-lab/2023_vanDijk_CytoSummaryNet", "sub_path": "FullEval_CP_LINCS.py", "file_name": "FullEval_CP_LINCS.py", "file_ext": "py", "file_size_in_byte": 22510, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "torch.cuda.is_available", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 33, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 33, "usage_type": "call"}, {"api_name": "random.seed", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.manual_seed", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 42, "usage_type": "attribute"}, {"api_name": "networks.SimpleMLPs.MLPsumV2", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 56, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 67, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path", "line_number": 76, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 79, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 81, "usage_type": "call"}, {"api_name": "os.walk", "line_number": 112, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 116, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 116, "usage_type": "call"}, {"api_name": "os.path", "line_number": 116, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 119, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 119, "usage_type": "call"}, {"api_name": "os.path", "line_number": 119, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 147, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 147, "usage_type": "call"}, {"api_name": "os.path", "line_number": 147, "usage_type": "attribute"}, {"api_name": "utils.addDataPathsToMetadata", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 152, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 155, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 155, "usage_type": "call"}, {"api_name": "utils.filterData", "line_number": 156, "usage_type": "call"}, {"api_name": "utils.train_val_split", "line_number": 166, "usage_type": "call"}, {"api_name": "dataloader_pickles.DataloaderEvalV5", "line_number": 167, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 168, "usage_type": "call"}, {"api_name": "torch.utils.data", "line_number": 168, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 173, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 174, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 175, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 179, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 180, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 187, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 187, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 187, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 188, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 191, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 191, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 191, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 192, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 195, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 195, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 195, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 196, "usage_type": "call"}, {"api_name": "time.time", "line_number": 219, "usage_type": "call"}, {"api_name": "pycytominer.operations.transform.RobustMAD", "line_number": 220, "usage_type": "call"}, {"api_name": "pycytominer.feature_select", "line_number": 223, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 227, "usage_type": "call"}, {"api_name": "time.time", "line_number": 228, "usage_type": "call"}, {"api_name": "pycytominer.operations.transform.RobustMAD", "line_number": 231, "usage_type": "call"}, {"api_name": "pycytominer.feature_select", "line_number": 234, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 238, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 242, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 247, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 260, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 261, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 262, "usage_type": "call"}, {"api_name": "pandas.DataFrame.from_records", "line_number": 270, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 270, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 270, "usage_type": "call"}, {"api_name": "utils.CalculateMAP", "line_number": 273, "usage_type": "call"}, {"api_name": "utils.CalculateMAP", "line_number": 275, "usage_type": "call"}, {"api_name": "utils.CalculateMAP", "line_number": 277, "usage_type": "call"}, {"api_name": "utils.CalculateMAP", "line_number": 279, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 292, "usage_type": "call"}, {"api_name": "scipy.stats.ttest_ind", "line_number": 316, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 316, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 316, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 321, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 366, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 371, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 373, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 403, "usage_type": "call"}]} +{"seq_id": "26273154974", "text": "from os import listdir, path, getcwd\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#This assumes the desired spreadsheets are contained in: working_directory/spreadsheets\nLOAD_PATH = path.join(getcwd(), \"spreadsheets\")\n\n\ndirectoryList = listdir(LOAD_PATH)\n\n# This will make a DF containing the prices against dates for all whiskies of a particular brand and barrel code.\n# E.G: For Auchroisk HHR we get a DF containing the dates/prices of Auchroisk HHR with all the different bond dates.\ndef GenerateGroupWhiskyDF(whiskyName, barrelCode):\n listOfWhiskies = []\n df = pd.DataFrame(columns=[\"Date\", \"Price\"])\n df_index = 0\n for directoryFile in directoryList:\n if \".xlsx\" not in directoryFile:\n continue\n\n print(\"Working on: \" + directoryFile)\n\n # UNCOMMENT TO CREATE DF FOR ALL WHISKIES INSTEAD OF THE ONE PASSED\n # Getting the whisky name and barrel code from the file name.\n directoryFileFormatted = directoryFile.replace(\"_\", \" \")\n splitString = directoryFileFormatted.split()\n newWhiskyName = splitString[0]\n period = splitString[1]\n newBarrelCode = splitString[2]\n\n if newWhiskyName == whiskyName and newBarrelCode == barrelCode:\n listOfWhiskies.append(directoryFile)\n print(\"Adding \" + whiskyName + \" \" + period + \" \" + barrelCode)\n file = path.join(LOAD_PATH, directoryFile)\n newdf = pd.read_excel(file)\n dates = newdf[\"Date\"][0:]\n\n newdf_index = 0\n # df.loc[df_index] = newdf.loc[newdf_index]\n for date in dates:\n if date not in df[\"Date\"][0:]:\n df_index += 1\n df.loc[df_index] = newdf.loc[newdf_index]\n # for main_df_date in df[\"Date\"][0:]:\n # # print(main_df_date)\n # if date > main_df_date:\n # df_index += 1\n # df.loc[df_index] = newdf.loc[newdf_index]\n # break\n newdf_index += 1\n\n df = pd.DataFrame(index=df[\"Date\"].values) # This is a dataframe with only an index and no columns\n df.sort_index(inplace=True)\n print(listOfWhiskies)\n print(df)\n for whiskyFileName in listOfWhiskies:\n file = path.join(LOAD_PATH, whiskyFileName)\n temp_df = pd.read_excel(file, index_col=\"Date\")\n # print(temp_df[:5])\n df = df.join(temp_df, how=\"outer\")\n df = df[~df.index.duplicated(keep='first')]\n df.fillna(method=\"ffill\", inplace=True)\n return df\n\n # oldWhiskyName = whiskyName\n # oldBarrelCode = barrelCode\n\nwhisky = \"inchgower\"\nbarrelCode = \"HHR\"\ndf = GenerateGroupWhiskyDF(whisky, barrelCode)\ndf.to_excel(\"output.xlsx\", \"sheet1\")\nprint(df)\n# df.plot()\n# plt.show()\n\n# fig = plt.figure()\n# fig.suptitle(whisky.capitalize() + \": \" + barrelCode, fontsize=14, fontweight=\"bold\")\n# chart = fig.add_subplot(111)\n# chart.set_xlabel(\"Date\")\n# chart.set_ylabel(\"Average Daily Deal Price\")\ndf.plot()\nplt.show()\n\n# Adjust for age and line up\n\n\n", "repo_name": "JLBastians/whisky_scraper", "sub_path": "group_whiskies.py", "file_name": "group_whiskies.py", "file_ext": "py", "file_size_in_byte": 3075, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "os.path.join", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "name"}, {"api_name": "os.getcwd", "line_number": 6, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 9, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "name"}, {"api_name": "pandas.read_excel", "line_number": 35, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path", "line_number": 57, "usage_type": "name"}, {"api_name": "pandas.read_excel", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}]} +{"seq_id": "32811595575", "text": "from data import DATA\nfrom report import Report\nfrom transaction import Transaction\n\n\ndef get_data():\n return [Transaction(row['Date'], row['Account'], row['Type'], row['Amount']) for row in DATA]\n\n\ndef get_all_month_types(data):\n months = []\n types = []\n accounts = {}\n for row in data:\n if row.date.month not in months:\n months.append(row.date.month)\n if row.type not in types:\n types.append(row.type)\n if row.account not in accounts:\n accounts[row.account] = 0\n\n return months, types, accounts\n\n\ndef filter_by_date(data, month):\n return [row for row in data if row.date.month == month]\n\n\ndef filter_by_type(data, transaction_type):\n return [row for row in data if row.type == transaction_type]\n\n\ndef main():\n data = get_data()\n months, types, accounts = get_all_month_types(data)\n for month in months:\n month_transaction = filter_by_date(data, month)\n report = Report(month, month_transaction, accounts, types)\n report.print_report()\n\n\nif __name__ == '__main__':\n main()\n", "repo_name": "massih/acorn-test", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1085, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "transaction.Transaction", "line_number": 7, "usage_type": "call"}, {"api_name": "data.DATA", "line_number": 7, "usage_type": "name"}, {"api_name": "report.Report", "line_number": 38, "usage_type": "call"}, {"api_name": "report.print_report", "line_number": 39, "usage_type": "call"}]} +{"seq_id": "21920657135", "text": "from scipy.misc import imread, imresize, imsave\r\nimport numpy as np\r\nimport os\r\n\r\n\r\ndef clipread(paths, offsets, size=(128, 171), crop_size=(112, 112), mode='RGB', interp='bilinear'):\r\n \"\"\"\r\n data load\r\n :param paths: path to video frames\r\n :param offsets: Crop window offset in form of [from_H, to_H, from_W, to_W], example: (0, 112, 24, 136)\r\n :param size: size of out put\r\n :param crop_size: size of the output cropped image\r\n :param mode: \"rgb/L\"\r\n :param interp: Interpolation to use for re-sizing, example: 'nearest', 'lanczos', 'bilinear', 'bicubic' or 'cubic'\r\n :return: Cropped clip (depth, crop_height, crop_width, channels) in float32 format, pixel values in [0, 255]\r\n \"\"\"\r\n assert mode in ('RGB', 'L'), 'Mode is either RGB or L'\r\n\r\n clips = []\r\n\r\n x = 0\r\n y = 1\r\n for file_name in paths:\r\n # Read video frame\r\n# prevent from empty jpg files\r\n try:\r\n im = imread(file_name, mode=mode)\r\n y+=1\r\n except OSError:\r\n im = imread(paths[0+x], mode=mode)\r\n x+=1 \r\n\r\n\r\n\r\n\r\n # Resize frame to init resolution and crop then resize to target resolution\r\n if mode == 'RGB':\r\n im = imresize(im, size=size, interp=interp)\r\n data = im[offsets[0]:offsets[1], offsets[2]:offsets[3], :]\r\n im = imresize(data, size=crop_size, interp=interp)\r\n else:\r\n im = imresize(im, size=size, interp=interp)\r\n data = im[offsets[0]:offsets[1], offsets[2]:offsets[3]]\r\n im = imresize(data, size=crop_size, interp=interp)\r\n\r\n clips.append(im)\r\n clips = np.array(clips, dtype=np.float32)\r\n if mode == 'RGB':\r\n return clips\r\n return np.expand_dims(clips, axis=3)\r\n\r\n\r\n#randcrop for avoid noise\r\ndef randcrop(scales, size=(128, 171)):\r\n \"\"\"\r\n Generate random offset for crop window\r\n :param scales: List of scales for crop window, example: (128, 112, 96, 84)\r\n :param size: Tuple, size of the image\r\n :return: Crop window offsets in form of (from_H, to_H, from_W, to_W), example: (0, 112, 24, 136)\r\n \"\"\"\r\n scales = np.array(scales) if isinstance(scales, (list, tuple)) else np.array([scales])\r\n scale = scales[np.random.randint(len(scales))]\r\n height, width = size\r\n\r\n max_h = height - scale\r\n max_w = width - scale\r\n\r\n off_h = np.random.randint(max_h) if max_h > 0 else 0\r\n off_w = np.random.randint(max_w) if max_w > 0 else 0\r\n\r\n return off_h, off_h + scale, off_w, off_w + scale\r\n\r\n#different crop opt but not use\r\ndef centercrop(scale, size=(128, 171)):\r\n \"\"\"\r\n Generate center offset for crop window\r\n :param scale: Int, a scale for crop window, example: 112\r\n :param size: Tuple, size of the image, example: (128, 171)\r\n :return: Crop window offsets in form of (from_H, to_H, from_W, to_W), example: (8, 120, 29, 141)\r\n \"\"\"\r\n height, width = size\r\n\r\n off_h = np.ceil((height - scale) / 2).astype(int)\r\n off_w = np.ceil((width - scale) / 2).astype(int)\r\n\r\n return off_h, off_h + scale, off_w, off_w + scale\r\n\r\n#just test whether it can work\r\ndef _demo_read_clip():\r\n \"\"\"\r\n read video frames and return ararry of cropped frames\r\n \"\"\"\r\n frame_dir = 'E:/proroot/dataset/traindata/hmdb/50_FIRST_DATES_sit_f_cm_np1_fr_med_24/'\r\n paths = [frame_dir +str (f + 1)+'.jpg' for f in range(0, 0 + 16)]\r\n\r\n # Random crop 16 times to see the differences\r\n clips = []\r\n for _ in range(16):\r\n offs = randcrop(scales=[128, 112, 96, 84], size=(128, 171))\r\n # offs = centercrop(scale=64, size=(128, 171))\r\n clip = clipread(paths=paths, offsets=offs, size=(128, 171), crop_size=(112, 112), mode='RGB')\r\n\r\n # Random flip left-right\r\n if np.random.rand(1, 1).squeeze() > 0.5:\r\n clip = np.flip(clip, axis=2)\r\n clips.append(np.hstack(clip))\r\n\r\n # Saving to a single images, each row is a clip\r\n clips = np.vstack(clips).squeeze()\r\n print('Min:', clips.min(), 'Max:', clips.max())\r\n imsave('E:/proroot/dataset/traindata/hmdb/50_FIRST_DATES_sit_f_cm_np1_fr_med_24/clips.png', clips)\r\n\r\n\r\nif __name__ == '__main__':\r\n print('Demo video processing!')\r\n _demo_read_clip()\r\n", "repo_name": "Ghostdpc/posture", "sub_path": "dataload.py", "file_name": "dataload.py", "file_ext": "py", "file_size_in_byte": 4203, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "scipy.misc.imread", "line_number": 27, "usage_type": "call"}, {"api_name": "scipy.misc.imread", "line_number": 30, "usage_type": "call"}, {"api_name": "scipy.misc.imresize", "line_number": 38, "usage_type": "call"}, {"api_name": "scipy.misc.imresize", "line_number": 40, "usage_type": "call"}, {"api_name": "scipy.misc.imresize", "line_number": 42, "usage_type": "call"}, {"api_name": "scipy.misc.imresize", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 47, "usage_type": "attribute"}, {"api_name": "numpy.expand_dims", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 62, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 68, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 69, "usage_type": "attribute"}, {"api_name": "numpy.ceil", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 104, "usage_type": "attribute"}, {"api_name": "numpy.flip", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 109, "usage_type": "call"}, {"api_name": "scipy.misc.imsave", "line_number": 111, "usage_type": "call"}]} +{"seq_id": "2661187705", "text": "# -*- coding: utf-8 -*-\n# @Time : 2021/4/20 20:32\n# @Author : XiaYouRan\n# @Email : youran.xia@foxmail.com\n# @File : main.py\n# @Software: PyCharm\n\n\nfrom wangyiyun.music import wyy_main\nfrom kugou.music import kg_main\nfrom kuwo.music import kw_main\nfrom utils.util import welcome\n\n\ndef select():\n print('目前支持的播放器类型: 1. 网易云\\t2. 酷狗\\t3. 酷我')\n input_str = input('请选择播放器类型(-1退出): ')\n if input_str == '-1':\n exit()\n elif input_str == '1':\n wyy_main()\n elif input_str == '2':\n kg_main()\n elif input_str == '3':\n kw_main()\n else:\n print('输入无效!!!')\n\n\nif __name__ == '__main__':\n welcome()\n select()\n\n", "repo_name": "xiayouran/Musicer", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 722, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 203, "dataset": "github-code", "pt": "2", "api": [{"api_name": "wangyiyun.music.wyy_main", "line_number": 21, "usage_type": "call"}, {"api_name": "kugou.music.kg_main", "line_number": 23, "usage_type": "call"}, {"api_name": "kuwo.music.kw_main", "line_number": 25, "usage_type": "call"}, {"api_name": "utils.util.welcome", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "35401481760", "text": "from django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponse\nfrom .forms import UserLoginForm, UserRehisterForm\nimport json\n\ndef user_login(request):\n if request.method == \"POST\":\n user_login_form = UserLoginForm(data=request.POST)\n # print(user_login_form)\n if user_login_form.is_valid():\n data = user_login_form.cleaned_data\n # print(data)\n user = authenticate(username=data['username'], password=data[\"password\"])\n # print(\"user\")\n # print(data['username'])\n # print(data[\"password\"])\n # print(user)\n if user:\n login(request, user)\n return redirect(\"blogtest:article_list\")\n else:\n return HttpResponse(user_login_form)\n else:\n return HttpResponse(\"账号/密码不合法,请重新输入\")\n elif request.method == \"GET\":\n user_login_form = UserLoginForm()\n context = {\"form\": user_login_form}\n # print(context)\n return render(request, \"userprofile/login.html\", context)\n else:\n return HttpResponse(\"请使用GET或POST请求数据8\")\n\n\ndef user_logout(request):\n logout(request)\n return redirect(\"blogtest:article_list\")\n\n\ndef user_register(request):\n if request.method == \"POST\":\n user_register_form = UserRehisterForm(data=request.POST)\n print(user_register_form)\n if user_register_form.is_valid():\n new_user = user_register_form.save(commit=False)\n new_user.set_password(user_register_form.cleaned_data['password'])\n new_user.save()\n login(request, new_user)\n return redirect('blogtest:article_list')\n else:\n return HttpResponse(\"注册表单输入有误,请重新输入~\")\n elif request.method == \"GET\":\n user_register_form = UserRehisterForm()\n context = {'form': user_register_form }\n return render(request, \"userprofile/register.html\", context)\n else:\n return HttpResponse(\"请使用GET或POST请求数据8\")", "repo_name": "Reagannnnnn/dajango_blog", "sub_path": "userprofile/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2167, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "forms.UserLoginForm", "line_number": 9, "usage_type": "call"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 14, "usage_type": "call"}, {"api_name": "django.contrib.auth.login", "line_number": 20, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 21, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 23, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 25, "usage_type": "call"}, {"api_name": "forms.UserLoginForm", "line_number": 27, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 30, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 32, "usage_type": "call"}, {"api_name": "django.contrib.auth.logout", "line_number": 36, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 37, "usage_type": "call"}, {"api_name": "forms.UserRehisterForm", "line_number": 42, "usage_type": "call"}, {"api_name": "django.contrib.auth.login", "line_number": 48, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 49, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 51, "usage_type": "call"}, {"api_name": "forms.UserRehisterForm", "line_number": 53, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 55, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 57, "usage_type": "call"}]} +{"seq_id": "8818614016", "text": "\"\"\"empty message\n\nRevision ID: 6ae826ac8ddd\nRevises: 144cf7179caa\nCreate Date: 2023-08-06 13:40:57.653110\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '6ae826ac8ddd'\ndown_revision = '144cf7179caa'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('show', schema=None) as batch_op:\n batch_op.add_column(sa.Column('show_date', sa.DateTime(), nullable=True))\n batch_op.drop_column('date')\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('show', schema=None) as batch_op:\n batch_op.add_column(sa.Column('date', postgresql.TIMESTAMP(), autoincrement=False, nullable=True))\n batch_op.drop_column('show_date')\n\n # ### end Alembic commands ###\n", "repo_name": "amrtaweel12/fyyur_website", "sub_path": "migrations/versions/6ae826ac8ddd_.py", "file_name": "6ae826ac8ddd_.py", "file_ext": "py", "file_size_in_byte": 975, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "alembic.op.batch_alter_table", "line_number": 21, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 21, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.DateTime", "line_number": 22, "usage_type": "call"}, {"api_name": "alembic.op.batch_alter_table", "line_number": 30, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 30, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 31, "usage_type": "call"}, {"api_name": "sqlalchemy.dialects.postgresql.TIMESTAMP", "line_number": 31, "usage_type": "call"}, {"api_name": "sqlalchemy.dialects.postgresql", "line_number": 31, "usage_type": "name"}]} +{"seq_id": "73915112046", "text": "from typing import Dict\n\nimport torch\n\nfrom ofasys.configure import register_config\n\nfrom .base import BaseMetric, MetricConfig\n\n\n@register_config(\"ofasys.metric\", \"vqa_score\", MetricConfig)\nclass VqaScore(BaseMetric):\n def __init__(self, cfg: MetricConfig):\n super().__init__(cfg)\n\n def compute(self, hyps, refs) -> Dict:\n logging_output = {}\n scores = [ref.get(hyp, 0) for ref, hyp in zip(refs, hyps)]\n logging_output[\"_vqa_score_sum\"] = sum(scores)\n logging_output[\"_vqa_cnt\"] = len(scores)\n return logging_output\n\n def report(self, logging_outputs: Dict) -> None:\n def sum_logs(key):\n result = sum(log.get(key, 0) for log in logging_outputs)\n if torch.is_tensor(result):\n result = result.cpu()\n return result\n\n def compute_score(meters):\n score = meters[\"_vqa_score_sum\"].sum / meters[\"_vqa_cnt\"].sum\n score = score if isinstance(score, float) else score.item()\n return round(score, 4)\n\n if sum_logs(\"_vqa_cnt\") > 0:\n self.metrics.log_scalar(\"_vqa_score_sum\", sum_logs(\"_vqa_score_sum\"))\n self.metrics.log_scalar(\"_vqa_cnt\", sum_logs(\"_vqa_cnt\"))\n self.metrics.log_derived(\"vqa_score\", compute_score)\n", "repo_name": "OFA-Sys/OFASys", "sub_path": "ofasys/metric/vqa_score.py", "file_name": "vqa_score.py", "file_ext": "py", "file_size_in_byte": 1291, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 131, "dataset": "github-code", "pt": "2", "api": [{"api_name": "base.BaseMetric", "line_number": 11, "usage_type": "name"}, {"api_name": "base.MetricConfig", "line_number": 12, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 15, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.is_tensor", "line_number": 25, "usage_type": "call"}, {"api_name": "ofasys.configure.register_config", "line_number": 10, "usage_type": "call"}, {"api_name": "base.MetricConfig", "line_number": 10, "usage_type": "argument"}]} +{"seq_id": "14377111566", "text": "import argparse\nimport os\nimport os.path as osp\nimport mmcv\nfrom mmcv import Config, DictAction\nfrom tqdm import tqdm\nfrom mmdet.datasets import build_dataset\nfrom mmdet.utils import update_data_root\nimport numpy as np\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Evaluate metric of the '\n 'results saved in pkl format')\n parser.add_argument('--config',default='/home/tju531/hwr/mmdetection/configs/a_fgvoc/7_atss_r50_fpn_1x_fgvoc.py',\n help='Config of the model')\n parser.add_argument('--pkl_results',\n default='/home/tju531/hwr/mmdet_works/results/7_atss_r50_fpn_1x_fgvoc/0_raw.pkl',\n help='Results in pickle format')\n parser.add_argument('--save_dir',\n default='/home/tju531/hwr/mmdet_works/txt/',\n help='Results in pickle format')\n args = parser.parse_args()\n return args\n\n## 12 e 5 0.489 0.785 0.550 0.373 0.494 0.552\ndef main():\n args = parse_args()\n\n cfg = Config.fromfile(args.config)\n # update data root according to MMDET_DATASETS\n update_data_root(cfg)\n cfg.data.test.test_mode = True\n dataset = build_dataset(cfg.data.test)\n\n if not osp.exists(args.save_dir):\n os.makedirs(args.save_dir)\n\n # 加载测试结果\n results = mmcv.load(args.pkl_results)\n # num_imgs个列表,每个列表又有num_classes个列表,最小列表为num,5表示这张图片有该类别num个,5代表四个坐标+概率\n # annotations 测试图片对应的gt的bbox\n # annotations = [dataset.get_ann_info(i) for i in range(len(outputs))]\n # 得到图片信息 dataset.ann_file是测试图片的txt文件\n # test_txt = dataset.ann_file\n # data_infos = dataset.load_annotations(test_txt)\n #\n for i, (result, ) in enumerate(zip(results)):\n if i>2:\n break\n data_info = dataset.prepare_train_img(i)\n img_name= data_info['img_metas'][0].data['ori_filename']\n name = img_name.split('/')[-1].split('.')[0]+'.txt'\n\n txt_f = open(args.save_dir+ name, 'w+', encoding='utf-8')\n\n for j in range(len(result)):\n # 每张图片都有num_class个列表 代表不同的类型,(n,num_class)\n # 如果 n =0 表示这张图片上没有这个类别\n n = result[j].shape[0]\n if n!=0: # 有这个类别\n cls = dataset.CLASSES[j]\n # 这张图片中,这个类别有n 个\n for m in range(n):\n # 转换成np.array,保留几位小数,转成str写入txt\n strNums = np.round(np.array(result[j][m]), 2)\n txt_f.write(cls + \" \")\n\n for x in strNums:\n txt_f.write(str(x) + \" \")\n txt_f.write('\\n')\n # # 如果概率 >0.6 才写入\n # if strNums[-1]>0.6:\n # txt_f.write(cls+\" \")\n # for x in strNums:\n # txt_f.write(str(x)+\" \")\n # txt_f.write('\\n')\n txt_f.close()\n print(\"已完成 {}\".format(i))\n\n\nif __name__ == '__main__':\n main()\n", "repo_name": "hewanru-bit/fg_mmdet", "sub_path": "demo/res2txt.py", "file_name": "res2txt.py", "file_ext": "py", "file_size_in_byte": 3261, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "2", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 12, "usage_type": "call"}, {"api_name": "mmcv.Config.fromfile", "line_number": 29, "usage_type": "call"}, {"api_name": "mmcv.Config", "line_number": 29, "usage_type": "name"}, {"api_name": "mmdet.utils.update_data_root", "line_number": 31, "usage_type": "call"}, {"api_name": "mmdet.datasets.build_dataset", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 36, "usage_type": "call"}, {"api_name": "mmcv.load", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 65, "usage_type": "call"}]} +{"seq_id": "27993404635", "text": "#!/usr/bin/env python3\n# basic rle compression program\n# by nicklausw\n\n# this format works as follows.\n# one byte is read, and that is\n# how many of the next byte to copy over. repeat.\n# when the first byte is $ff, the copy is done.\n\nimport sys\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"in_file\", help=\"the chr data to be rle'd\")\nparser.add_argument(\"out_file\", help=\"the rle'd output\")\nargs = parser.parse_args()\n\nf_in = open(args.in_file, 'rb')\nf_out = open(args.out_file, 'wb')\n\n# python doesn't need variable initialization i think,\n# but for clarity's sake.\nbyte_n = int.from_bytes(f_in.read(1), byteorder='little') # byte\nbyte_c = 0 # byte count\n\nsingle_build = 0 # number of single-byte pairs\nsingle_list = bytearray()\n\nf_in.seek(0) \n\nfor c in f_in.read():\n if c != byte_n or byte_c == 0xFD:\n # what if we might be building up 1's?\n if byte_c == 1:\n single_list.append(byte_n)\n single_build += 1\n byte_n = c\n else:\n if single_build > 2:\n # it's worth making a list\n f_out.write(bytes([0xFE, single_build]))\n \n for d in single_list:\n f_out.write(bytes([d]))\n \n single_build = 0\n single_list = []\n \n elif single_build == 1:\n # not worth a list\n \n while single_build < 2:\n f_out.write(bytes([1, single_list[single_build - 1]]))\n single_build += 1\n \n single_build = 0\n single_list = []\n \n elif single_build == 2:\n # not worth a list\n \n single_build = 0\n \n while single_build < 2:\n f_out.write(bytes([1, single_list[single_build]]))\n single_build += 1\n \n single_build = 0\n single_list = []\n \n \n f_out.write(bytes([byte_c]))\n f_out.write(bytes([byte_n]))\n \n byte_c = 1\n byte_n = c\n else:\n byte_c += 1\n\nif single_build > 2:\n # it's worth making a list\n \n f_out.write(bytes([0xFE, single_build]))\n \n for d in single_list:\n f_out.write(bytes([d]))\n \nelif single_build > 0:\n # not worth a list\n \n while single_build < 2:\n f_out.write(bytes([1, single_list[single_build - 1]]))\n single_build += 1\n\n# now catch the last time around\nif byte_c > 0:\n f_out.write(bytes([byte_c]))\n f_out.write(bytes([byte_n]))\n\n# the end mark\nf_out.write(bytes([0xFF]))\n\nf_in.close()\nf_out.close()\n", "repo_name": "nicklausw/fighter", "sub_path": "tools/rle.py", "file_name": "rle.py", "file_ext": "py", "file_size_in_byte": 2413, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "24", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 13, "usage_type": "call"}]} +{"seq_id": "42259515616", "text": "from django.urls import path\nfrom .views import home, search, detail\n\n\n# url for the home page first, create a view for it \nurlpatterns = [\n\tpath('', home, name='home'),\n\tpath('search', search, name='search'),\n\tpath('', detail, name='detail'),\n]", "repo_name": "kasiakor/django-recipes", "sub_path": "main/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 251, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "views.home", "line_number": 7, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "views.search", "line_number": 8, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "views.detail", "line_number": 9, "usage_type": "argument"}]} +{"seq_id": "19581519129", "text": "from datetime import datetime\n\nfrom pydantic import BaseModel, root_validator\n\nfrom app.core.schemas import root_validator_round_floats\n\n\nclass ScoreAvgResponse(BaseModel):\n quiz_id: int = None\n user_id: int = None\n company_id: int = None\n total_questions: int\n total_correct_answers: float\n avg_score: float\n\n @root_validator(pre=True)\n def round_values(cls, values):\n return root_validator_round_floats(values)\n\n\nclass ScoreTimeResponse(BaseModel):\n avg_score: float\n created_at: datetime\n\n @root_validator(pre=True)\n def round_values(cls, values):\n return root_validator_round_floats(values)\n\n\nclass QuizScoresTimeResponse(BaseModel):\n quiz_id: int\n result: list[ScoreTimeResponse]\n\n\nclass UserScoresTimeResponse(BaseModel):\n user_id: int\n result: list[ScoreTimeResponse]\n\n\nclass QuizTimeResponse(BaseModel):\n quiz_id: int\n created_at: datetime\n\n\nclass UserTimeResponse(BaseModel):\n user_id: int\n created_at: datetime\n", "repo_name": "mys1erious/meduzzen-knowledge-control", "sub_path": "app/analytics/schemas.py", "file_name": "schemas.py", "file_ext": "py", "file_size_in_byte": 995, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "pydantic.BaseModel", "line_number": 8, "usage_type": "name"}, {"api_name": "app.core.schemas.root_validator_round_floats", "line_number": 18, "usage_type": "call"}, {"api_name": "pydantic.root_validator", "line_number": 16, "usage_type": "call"}, {"api_name": "pydantic.BaseModel", "line_number": 21, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 23, "usage_type": "name"}, {"api_name": "app.core.schemas.root_validator_round_floats", "line_number": 27, "usage_type": "call"}, {"api_name": "pydantic.root_validator", "line_number": 25, "usage_type": "call"}, {"api_name": "pydantic.BaseModel", "line_number": 30, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 35, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 40, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 42, "usage_type": "name"}, {"api_name": "pydantic.BaseModel", "line_number": 45, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 47, "usage_type": "name"}]} +{"seq_id": "16978220518", "text": "from collections import defaultdict\nfrom math import ceil\n\ndef toMinutes(time):\n t = time.split(':')\n return int(t[0])*60 + int(t[1])\n\ndef solution(fees, records):\n answer = []\n cars = defaultdict(list)\n result = defaultdict(int)\n for record in records:\n rec = record.split()\n cars[rec[1]].append(toMinutes(rec[0]))\n \n for k, v in cars.items():\n if len(v) % 2 == 1:\n v.append(toMinutes('23:59'))\n \n for k, v in cars.items():\n time = 0\n for i in range(0, len(v), 2):\n time += v[i+1] - v[i]\n f = fees[1]\n if time > fees[0]:\n f += ceil((time-fees[0])/fees[2])*fees[3]\n result[k] = f\n \n charge = []\n for k,v in result.items():\n charge.append([k,v])\n charge.sort()\n \n for c in charge:\n answer.append(c[1])\n return answer", "repo_name": "rlacksgus97/algorithms", "sub_path": "프로그래머스/lv2/92341. 주차 요금 계산/주차 요금 계산.py", "file_name": "주차 요금 계산.py", "file_ext": "py", "file_size_in_byte": 877, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "collections.defaultdict", "line_number": 10, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 11, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 26, "usage_type": "call"}]} +{"seq_id": "74331548526", "text": "import torch\nimport matplotlib.pyplot as plt\nimport os\nimport numpy as np\nfrom matplotlib import ticker\n\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'True'\n\nresult = torch.load(\"../analysis-and-draw/data/CNN-30-CIFAR_17-result.pt\").cpu()\ncorrect_num = result.sum(dim=1)\noccur = result.int().sum(dim=0)\n\nlst = list()\nfor i in range(31):\n lst.append((occur == i).int().sum().item())\n\nlst1 = [0] * 31\nlst2 = [0] * 31\n\nfalse_list = torch.load(\"../analysis-and-draw/data/CNN_CIFAR_17-false.pt\")\n\nfor i in range(50000):\n if i in false_list:\n lst2[occur[i]] += 1\n else:\n lst1[occur[i]] += 1\n\nfor i in range(31):\n assert lst1[i] + lst2[i] == lst[i]\n\nplt.rcParams['figure.figsize'] = (10.0, 6.0)\n\nplt.bar(np.arange(31), lst, width=0.25, label=\"All Samples\")\nplt.bar(np.arange(31) + 0.25, lst1, width=0.25, label=\"Correct Samples in Model to Fix\")\nplt.bar(np.arange(31) + 0.5, lst2, width=0.25, label=\"Wrong Samples in Model to Fix\")\nplt.xticks(np.arange(31) + 0.25, np.arange(31))\nplt.xlabel('Learnable Rate')\nplt.ylabel('Percentage')\nplt.legend(loc='upper left')\nplt.xlim(-0.5, 31)\nax = plt.gca()\n\n\ndef to_percent(temp, position):\n return '%d' % (temp / 500) + '%'\n\n\nax.yaxis.set_major_formatter(ticker.FuncFormatter(to_percent))\nplt.show()\n", "repo_name": "fzdy1914/NUS-FYP", "sub_path": "ResidualLoss/FYP_GRAPH/CNN-l2-30-learnable_hist-wrt-false.py", "file_name": "CNN-l2-30-learnable_hist-wrt-false.py", "file_ext": "py", "file_size_in_byte": 1255, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "os.environ", "line_number": 7, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 9, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 31, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.ticker.FuncFormatter", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.ticker", "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": "10430300668", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport datetime\n\nimport six\nfrom nose.tools import ok_, assert_raises, assert_equal\nfrom nose.tools.trivial import eq_\n\nfrom booleano.operations.operands.constants import Number, String\nfrom booleano.operations.variables import NumberVariable, BooleanVariable, StringVariable, DateVariable, \\\n DateTimeVariable, SetVariable, NativeVariable, DurationVariable\nfrom booleano.parser.symbol_table_builder import SymbolTableBuilder\nfrom booleano.parser import SymbolTable, Bind, Grammar\nfrom booleano.parser.core import EvaluableParseManager\n\n\nclass TestNativeVariableEvaluableParseManager(object):\n \"\"\"\n Tests for the :class:`EvaluableParseManager` with caching disabled.\n\n \"\"\"\n\n # A symbol table to be used across the tests:\n symbol_table = SymbolTable(\n \"root\",\n (\n Bind(\"myint\", NumberVariable(\"myint\")),\n Bind(\"mybool\", BooleanVariable(\"mybool\")),\n Bind(\"mystring\", StringVariable(\"mystring\")),\n Bind(\"mydate\", DateVariable(\"mydate\")),\n Bind(\"mydate2\", DateVariable(\"mydate2\")),\n Bind(\"mydatetime\", DateTimeVariable(\"mydatetime\")),\n Bind(\"mydatetime2\", DateTimeVariable(\"mydatetime2\")),\n Bind(\"myset\", SetVariable(\"myset\")),\n Bind(\"myintbis\", NumberVariable(\"myint\")),\n ),\n SymbolTable(\n \"sub\",\n (\n Bind(\"myint\", NumberVariable(\"sub.myint\")),\n ),\n ),\n SymbolTable(\n \"const\",\n (\n Bind(\"hello\", String(\"hello\")),\n Bind(\"li\", String(\"li\")),\n )\n )\n )\n\n mgr = EvaluableParseManager(symbol_table, Grammar(belongs_to='in', is_subset='is subset of'))\n\n def test_variable_values_myint(self):\n ok_(self.mgr.parse('myint > 0')({'myint': 1}))\n ok_(not self.mgr.parse('myint > 0')({'myint': 0}))\n ok_(self.mgr.parse('myint == 1')({'myint': 1}))\n ok_(not self.mgr.parse('myint == 1')({'myint': 0}))\n ok_(self.mgr.parse('myint < 1')({'myint': 0}))\n ok_(not self.mgr.parse('myint < 0')({'myint': 2}))\n\n def test_variable_values_mybool(self):\n ok_(self.mgr.parse('mybool')({'mybool': True}))\n ok_(not self.mgr.parse('mybool')({'mybool': False}))\n ok_(self.mgr.parse('mybool > 0')({'mybool': True}))\n ok_(not self.mgr.parse('mybool > 0')({'mybool': False}))\n ok_(self.mgr.parse('mybool == 1')({'mybool': True}))\n ok_(not self.mgr.parse('mybool == 1')({'mybool': False}))\n ok_(self.mgr.parse('mybool < 1')({'mybool': False}))\n ok_(not self.mgr.parse('mybool < 0')({'mybool': True}))\n\n def test_variable_values_mystring(self):\n mystring = {'mystring': \"hello\"}\n # equiality\n ok_(self.mgr.parse('mystring == \"hello\"')(mystring))\n ok_(not self.mgr.parse('mystring != \"hello\"')(mystring))\n ok_(self.mgr.parse('mystring != \"hell\"')(mystring))\n ok_(not self.mgr.parse('mystring == \"hell\"')(mystring))\n # inequality\n ok_(self.mgr.parse('mystring > \"hella\"')(mystring))\n ok_(self.mgr.parse('mystring < \"hellz\"')(mystring))\n ok_(self.mgr.parse('mystring < \"hellz\"')(mystring))\n ok_(self.mgr.parse('mystring <= \"hello\"')(mystring))\n ok_(self.mgr.parse('mystring >= \"hello\"')(mystring))\n # inequality reversed\n ok_(self.mgr.parse('\"hella\" < mystring')(mystring))\n ok_(self.mgr.parse('\"hellz\" > mystring')(mystring))\n ok_(self.mgr.parse('\"hellz\" > mystring')(mystring))\n ok_(self.mgr.parse('\"hello\" >= mystring')(mystring))\n ok_(self.mgr.parse('\"hello\" >= mystring')(mystring))\n # bool\n ok_(self.mgr.parse('mystring')(mystring))\n ok_(not self.mgr.parse('~ mystring')(mystring))\n ok_(not self.mgr.parse('mystring')({'mystring': ''}))\n ok_(self.mgr.parse('~ mystring')({'mystring': ''}))\n # membership\n ok_(self.mgr.parse('mystring is subset of \"zhelloy\"')(mystring))\n ok_(not self.mgr.parse('mystring is subset of \"zhellai\"')(mystring))\n ok_(not self.mgr.parse('mystring is subset of \"hello\"')(mystring))\n ok_(self.mgr.parse('mystring in \"ahelloa\"')(mystring))\n ok_(self.mgr.parse('mystring in \"hello\"')(mystring))\n ok_(not self.mgr.parse('mystring in \"hola\"')(mystring))\n # inversed membership\n ok_(self.mgr.parse('\"he\" in mystring')(mystring))\n ok_(self.mgr.parse('\"lo\" in mystring')(mystring))\n ok_(not self.mgr.parse('\"li\" in mystring')(mystring))\n ok_(self.mgr.parse('\"he\" is subset of mystring')(mystring))\n ok_(self.mgr.parse('\"lo\" is subset of mystring')(mystring))\n ok_(not self.mgr.parse('\"li\" is subset of mystring')(mystring))\n ok_(not self.mgr.parse(' \"hello\" is subset of mystring')(mystring))\n # test to string\n ok_(not self.mgr.parse('const:hello is subset of mystring')(mystring))\n ok_(not self.mgr.parse('const:li in mystring')(mystring))\n\n def test_variable_str(self):\n eq_(\"%s\" % NativeVariable('coucou'), 'Scop variable for coucou [NativeVariable]')\n eq_(\"%s\" % BooleanVariable('name'), 'Scop variable for name [BooleanVariable]')\n eq_(\"%s\" % NumberVariable('age'), 'Scop variable for age [NumberVariable]')\n\n def test_variable_values_date(self):\n mydate = {\n 'mydate': datetime.date(2017, 1, 15),\n 'mydate2': datetime.date(2017, 1, 17),\n }\n ok_(self.mgr.parse('mydate')(mydate))\n\n ok_(self.mgr.parse('mydate < \"2017-01-18\"')(mydate))\n ok_(self.mgr.parse('mydate < \"18-01-2017\"')(mydate))\n ok_(not self.mgr.parse('mydate < \"12-01-2017\"')(mydate))\n ok_(self.mgr.parse('mydate > \"12-01-2017\"')(mydate))\n\n ok_(self.mgr.parse('mydate == \"15-01-2017\"')(mydate))\n ok_(not self.mgr.parse('mydate == 1')(mydate))\n ok_(not self.mgr.parse('mydate == \"13-01-2017\"')(mydate))\n ok_(self.mgr.parse('mydate < mydate2')(mydate))\n ok_(not self.mgr.parse('mydate > mydate2')(mydate))\n ok_(not self.mgr.parse('mydate == mydate2')(mydate))\n\n def test_variable_values_datetime(self):\n mydatetime = {\n 'mydatetime': datetime.datetime(2017, 1, 15, 12, 25),\n 'mydatetime2': datetime.datetime(2017, 1, 17, 12, 23),\n }\n ok_(self.mgr.parse('mydatetime')(mydatetime))\n\n ok_(self.mgr.parse('mydatetime < \"2017-01-15 12:25:02\"')(mydatetime))\n ok_(self.mgr.parse('mydatetime > \"2017-01-15 12:24:52\"')(mydatetime))\n ok_(self.mgr.parse('mydatetime < \"2017-01-15 13:00:00\"')(mydatetime))\n ok_(self.mgr.parse('mydatetime < \"18-01-2017 12:25:02\"')(mydatetime))\n ok_(self.mgr.parse('mydatetime < \"18-01-2017 12:25:02\"')(mydatetime))\n ok_(not self.mgr.parse('mydatetime < \"12-01-2017 12:25:02\"')(mydatetime))\n ok_(self.mgr.parse('mydatetime > \"12-01-2017 12:25:02\"')(mydatetime))\n\n ok_(self.mgr.parse('mydatetime == \"15-01-2017 12:25:00\"')(mydatetime))\n ok_(not self.mgr.parse('mydatetime == 1')(mydatetime))\n ok_(not self.mgr.parse('mydatetime == \"13-01-2017 12:25:02\"')(mydatetime))\n ok_(self.mgr.parse('mydatetime < mydatetime2')(mydatetime))\n ok_(not self.mgr.parse('mydatetime > mydatetime2')(mydatetime))\n ok_(not self.mgr.parse('mydatetime == mydatetime2')(mydatetime))\n\n def test_variable_values_set(self):\n myset = {\n \"myset\": {1, 2, 3},\n }\n ok_(self.mgr.parse(\"1 is subset of myset \")(myset))\n ok_(self.mgr.parse(\"{1, 2} is subset of myset \")(myset))\n ok_(not self.mgr.parse(\"{1, 2, 3} is subset of myset \")(myset))\n ok_(self.mgr.parse(\"1 in myset \")(myset))\n ok_(self.mgr.parse(\"{1, 2} in myset \")(myset))\n ok_(self.mgr.parse(\"{1, 2, 3} in myset \")(myset))\n\n def test_variable_values_namespaced(self):\n myints = {\n \"myint\": 1,\n \"sub.myint\": 4\n }\n ok_(self.mgr.parse('sub:myint > 3')(myints))\n ok_(self.mgr.parse('sub:myint < 5')(myints))\n ok_(self.mgr.parse('sub:myint == 4')(myints))\n ok_(self.mgr.parse('sub:myint > myint')(myints))\n ok_(not self.mgr.parse('sub:myint < myint')(myints))\n ok_(not self.mgr.parse('sub:myint == myint')(myints))\n\n def test_format_date(self):\n dt = DateVariable(\"mydate\", '%d %m %y')\n assert_raises(ValueError, dt._from_native_string, \"2001-03-04\")\n eq_(dt._from_native_string( \"04 03 01\"), datetime.date(2001, 3, 4))\n\n def test_multi_formats(self):\n dt = DateVariable(\"mydate\", ['%d %m %Y', '%Y %m %d'])\n assert_raises(ValueError, dt._from_native_string, \"2001-03-04\")\n assert_raises(ValueError, dt._from_native_string, \"04-03-2001\")\n eq_(dt._from_native_string(\"04 03 2001\"), datetime.date(2001, 3, 4))\n eq_(dt._from_native_string(\"2001 03 04\"), datetime.date(2001, 3, 4))\n\n\nclass TestDurationVariable(object):\n\n def test_default_durations_formats(self):\n d = DurationVariable('ctx_name')\n eq_(d._from_native_string('1d'), datetime.timedelta(days=1))\n eq_(d._from_native_string('1d2s'), datetime.timedelta(days=1, seconds=2))\n eq_(d._from_native_string('1d4m2s'), datetime.timedelta(days=1, seconds=2, minutes=4))\n eq_(d._from_native_string('1d5h4m2s'), datetime.timedelta(days=1, seconds=2, minutes=4, hours=5))\n eq_(d._from_native_string('1 days 5 hours 4 minutes 2 seconds'), datetime.timedelta(days=1, seconds=2, minutes=4, hours=5))\n eq_(d._from_native_string('1days 5hours 4minutes 2seconds'), datetime.timedelta(days=1, seconds=2, minutes=4, hours=5))\n eq_(d._from_native_string('1 days 2 seconds'), datetime.timedelta(days=1, seconds=2))\n\n def test_custom_duration_formats(self):\n\n dv = DurationVariable('ctx_name', r'^((?P\\d+?) ?j(ours?)?)?')\n assert_raises(ValueError, dv._from_native_string, \"1d\")\n eq_(dv._from_native_string('1j'), datetime.timedelta(days=1))\n eq_(dv._from_native_string('1jour'), datetime.timedelta(days=1))\n eq_(dv._from_native_string('1jours'), datetime.timedelta(days=1))\n\n def test_multi_custom_duration_format(self):\n dv = DurationVariable('ctx_name', [r'^((?P\\d+?) ?j(ours?)?)?', r'^((?P\\d+?) ?d(ías)?)?'])\n assert_raises(ValueError, dv._from_native_string, \"1s\")\n eq_(dv._from_native_string('1j'), datetime.timedelta(days=1))\n eq_(dv._from_native_string('1jour'), datetime.timedelta(days=1))\n eq_(dv._from_native_string('1jours'), datetime.timedelta(days=1))\n eq_(dv._from_native_string('1d'), datetime.timedelta(days=1))\n eq_(dv._from_native_string('1días'), datetime.timedelta(days=1))\n\n def test_bad_formated_date(self):\n d = DurationVariable('ctx_name')\n assert_raises(ValueError, d._from_native_string, \"\")\n assert_raises(ValueError, d._from_native_string, \"1j\") # bad j unit\n assert_raises(ValueError, d._from_native_string, \"10s10d\") # bad order\n assert_raises(ValueError, d._from_native_string, \"1d2h3s5h\") # repeated h\n\n\nclass TestVariableLazyResolve(object):\n\n def test_raw_val(self):\n c = NumberVariable('n')\n eq_(c.to_python({'n': 1}), 1)\n\n def test_lazy_val(self):\n calls = []\n\n def lazy(context):\n calls.append(1)\n return context['n']\n\n eq_(calls, [])\n c = NumberVariable(lazy)\n eq_(calls, [])\n eq_(c.to_python({'n': 1}), 1)\n eq_(calls, [1])\n eq_(c.to_python({'n': 1}), 1)\n eq_(calls, [1, 1])\n\n\nclass TestVariableSymbolTableBuilder(object):\n FakeVariable = type(str('FakeVariable'), (NativeVariable,), {})\n FakeVariableSub = type(str('FakeVariable'), (FakeVariable,), {})\n\n MyString = type(str('MyString'), (str,), {})\n MyStringVariable = type(str('MyStringVariable'), (NativeVariable,), {})\n\n def test_registering(self):\n vb = SymbolTableBuilder()\n ok_(len(vb.registered_variables) == 0)\n vb.register(int, self.FakeVariable)\n ok_(len(vb.registered_variables) == 1)\n vb.register(float, self.FakeVariable)\n ok_(len(vb.registered_variables) == 2)\n\n @vb.register(six.text_type)\n class TextVariable(NativeVariable):\n pass\n\n ok_(len(vb.registered_variables) == 3)\n\n def test_registering_error(self):\n vb = SymbolTableBuilder()\n vb.register(int, self.FakeVariable)\n assert_raises(Exception, vb.register, int, self.FakeVariableSub)\n\n def test_resolve_type(self):\n\n vb = SymbolTableBuilder()\n vb.register(str, self.FakeVariable)\n # sub class of str resolve to common FakeVariable\n assert_equal(vb.find_for_type(str), self.FakeVariable)\n assert_equal(vb.find_for_type(self.MyString), self.FakeVariable)\n\n # registering more concrete class: this one take precedence\n vb.register(self.MyString, self.MyStringVariable)\n assert_equal(vb.find_for_type(str), self.FakeVariable)\n assert_equal(vb.find_for_type(self.MyString), self.MyStringVariable)\n\n def test_creation_table(self):\n vb = SymbolTableBuilder()\n vb.register(six.text_type, self.FakeVariable)\n vb.register(int, self.FakeVariableSub)\n st = vb(\"root\", {\"name\": \"katara\", \"age\": 15})\n assert_equal(st, SymbolTable('root', (\n Bind(\"name\", self.FakeVariable),\n Bind(\"age\", self.FakeVariableSub),\n )))\n\n def test_creation_table_with_type(self):\n vb = SymbolTableBuilder()\n vb.register(six.text_type, self.FakeVariable)\n vb.register(int, self.FakeVariableSub)\n st = vb(\"root\", {\"name\": six.text_type, \"age\": 15})\n assert_equal(st, SymbolTable('root', (\n Bind(\"name\", self.FakeVariable),\n Bind(\"age\", self.FakeVariableSub),\n )))\n\n def test_creation_table_unknown_type(self):\n vb = SymbolTableBuilder()\n vb.register(six.text_type, self.FakeVariable)\n vb.register(int, self.FakeVariableSub)\n assert_raises(Exception,\n vb, \"root\", {\"name\": \"katara\", \"age\": 15.}\n )\n\n\n", "repo_name": "Yupeek/booleano", "sub_path": "tests/operations/test_variables.py", "file_name": "test_variables.py", "file_ext": "py", "file_size_in_byte": 14286, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "24", "api": [{"api_name": "booleano.parser.SymbolTable", "line_number": 24, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 27, "usage_type": "call"}, {"api_name": "booleano.operations.variables.NumberVariable", "line_number": 27, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 28, "usage_type": "call"}, {"api_name": "booleano.operations.variables.BooleanVariable", "line_number": 28, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 29, "usage_type": "call"}, {"api_name": "booleano.operations.variables.StringVariable", "line_number": 29, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 30, "usage_type": "call"}, {"api_name": "booleano.operations.variables.DateVariable", "line_number": 30, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 31, "usage_type": "call"}, {"api_name": "booleano.operations.variables.DateVariable", "line_number": 31, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 32, "usage_type": "call"}, {"api_name": "booleano.operations.variables.DateTimeVariable", "line_number": 32, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 33, "usage_type": "call"}, {"api_name": "booleano.operations.variables.DateTimeVariable", "line_number": 33, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 34, "usage_type": "call"}, {"api_name": "booleano.operations.variables.SetVariable", "line_number": 34, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 35, "usage_type": "call"}, {"api_name": "booleano.operations.variables.NumberVariable", "line_number": 35, "usage_type": "call"}, {"api_name": "booleano.parser.SymbolTable", "line_number": 37, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 40, "usage_type": "call"}, {"api_name": "booleano.operations.variables.NumberVariable", "line_number": 40, "usage_type": "call"}, {"api_name": "booleano.parser.SymbolTable", "line_number": 43, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 46, "usage_type": "call"}, {"api_name": "booleano.operations.operands.constants.String", "line_number": 46, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 47, "usage_type": "call"}, {"api_name": "booleano.operations.operands.constants.String", "line_number": 47, "usage_type": "call"}, {"api_name": "booleano.parser.core.EvaluableParseManager", "line_number": 52, "usage_type": "call"}, {"api_name": "booleano.parser.Grammar", "line_number": 52, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 55, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 56, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 57, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 58, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 59, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 60, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 63, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 64, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 65, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 66, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 67, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 68, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 69, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 70, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 75, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 76, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 77, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 78, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 80, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 81, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 82, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 83, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 84, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 86, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 87, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 88, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 89, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 90, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 92, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 93, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 94, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 95, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 97, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 98, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 99, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 100, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 101, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 102, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 104, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 105, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 106, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 107, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 108, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 109, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 110, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 112, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 113, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 116, "usage_type": "call"}, {"api_name": "booleano.operations.variables.NativeVariable", "line_number": 116, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 117, "usage_type": "call"}, {"api_name": "booleano.operations.variables.BooleanVariable", "line_number": 117, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 118, "usage_type": "call"}, {"api_name": "booleano.operations.variables.NumberVariable", "line_number": 118, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 122, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 123, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 125, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 127, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 128, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 129, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 130, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 132, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 133, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 134, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 135, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 136, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 137, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 141, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 142, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 144, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 146, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 147, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 148, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 149, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 150, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 151, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 152, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 154, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 155, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 156, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 157, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 158, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 159, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 165, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 166, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 167, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 168, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 169, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 170, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 177, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 178, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 179, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 180, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 181, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 182, "usage_type": "call"}, {"api_name": "booleano.operations.variables.DateVariable", "line_number": 185, "usage_type": "call"}, {"api_name": "nose.tools.assert_raises", "line_number": 186, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 187, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 187, "usage_type": "call"}, {"api_name": "booleano.operations.variables.DateVariable", "line_number": 190, "usage_type": "call"}, {"api_name": "nose.tools.assert_raises", "line_number": 191, "usage_type": "call"}, {"api_name": "nose.tools.assert_raises", "line_number": 192, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 193, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 193, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 194, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 194, "usage_type": "call"}, {"api_name": "booleano.operations.variables.DurationVariable", "line_number": 200, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 201, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 201, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 202, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 202, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 203, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 203, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 204, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 204, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 205, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 205, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 206, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 206, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 207, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 207, "usage_type": "call"}, {"api_name": "booleano.operations.variables.DurationVariable", "line_number": 211, "usage_type": "call"}, {"api_name": "nose.tools.assert_raises", "line_number": 212, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 213, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 213, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 214, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 214, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 215, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 215, "usage_type": "call"}, {"api_name": "booleano.operations.variables.DurationVariable", "line_number": 218, "usage_type": "call"}, {"api_name": "nose.tools.assert_raises", "line_number": 219, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 220, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 220, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 221, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 221, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 222, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 222, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 223, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 223, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 224, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 224, "usage_type": "call"}, {"api_name": "booleano.operations.variables.DurationVariable", "line_number": 227, "usage_type": "call"}, {"api_name": "nose.tools.assert_raises", "line_number": 228, "usage_type": "call"}, {"api_name": "nose.tools.assert_raises", "line_number": 229, "usage_type": "call"}, {"api_name": "nose.tools.assert_raises", "line_number": 230, "usage_type": "call"}, {"api_name": "nose.tools.assert_raises", "line_number": 231, "usage_type": "call"}, {"api_name": "booleano.operations.variables.NumberVariable", "line_number": 237, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 238, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 247, "usage_type": "call"}, {"api_name": "booleano.operations.variables.NumberVariable", "line_number": 248, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 249, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 250, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 251, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 252, "usage_type": "call"}, {"api_name": "nose.tools.trivial.eq_", "line_number": 253, "usage_type": "call"}, {"api_name": "booleano.operations.variables.NativeVariable", "line_number": 257, "usage_type": "name"}, {"api_name": "booleano.operations.variables.NativeVariable", "line_number": 261, "usage_type": "name"}, {"api_name": "booleano.parser.symbol_table_builder.SymbolTableBuilder", "line_number": 264, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 265, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 267, "usage_type": "call"}, {"api_name": "nose.tools.ok_", "line_number": 269, "usage_type": "call"}, {"api_name": "booleano.operations.variables.NativeVariable", "line_number": 272, "usage_type": "name"}, {"api_name": "six.text_type", "line_number": 271, "usage_type": "attribute"}, {"api_name": "nose.tools.ok_", "line_number": 275, "usage_type": "call"}, {"api_name": "booleano.parser.symbol_table_builder.SymbolTableBuilder", "line_number": 278, "usage_type": "call"}, {"api_name": "nose.tools.assert_raises", "line_number": 280, "usage_type": "call"}, {"api_name": "booleano.parser.symbol_table_builder.SymbolTableBuilder", "line_number": 284, "usage_type": "call"}, {"api_name": "nose.tools.assert_equal", "line_number": 287, "usage_type": "call"}, {"api_name": "nose.tools.assert_equal", "line_number": 288, "usage_type": "call"}, {"api_name": "nose.tools.assert_equal", "line_number": 292, "usage_type": "call"}, {"api_name": "nose.tools.assert_equal", "line_number": 293, "usage_type": "call"}, {"api_name": "booleano.parser.symbol_table_builder.SymbolTableBuilder", "line_number": 296, "usage_type": "call"}, {"api_name": "six.text_type", "line_number": 297, "usage_type": "attribute"}, {"api_name": "nose.tools.assert_equal", "line_number": 300, "usage_type": "call"}, {"api_name": "booleano.parser.SymbolTable", "line_number": 300, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 301, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 302, "usage_type": "call"}, {"api_name": "booleano.parser.symbol_table_builder.SymbolTableBuilder", "line_number": 306, "usage_type": "call"}, {"api_name": "six.text_type", "line_number": 307, "usage_type": "attribute"}, {"api_name": "six.text_type", "line_number": 309, "usage_type": "attribute"}, {"api_name": "nose.tools.assert_equal", "line_number": 310, "usage_type": "call"}, {"api_name": "booleano.parser.SymbolTable", "line_number": 310, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 311, "usage_type": "call"}, {"api_name": "booleano.parser.Bind", "line_number": 312, "usage_type": "call"}, {"api_name": "booleano.parser.symbol_table_builder.SymbolTableBuilder", "line_number": 316, "usage_type": "call"}, {"api_name": "six.text_type", "line_number": 317, "usage_type": "attribute"}, {"api_name": "nose.tools.assert_raises", "line_number": 319, "usage_type": "call"}]} +{"seq_id": "30121538912", "text": "# 画像のスクレイピングはできたが解像度が 110x134\nimport requests\nimport re\nfrom bs4 import BeautifulSoup\n\nurl = 'http://www.yurugp.jp/ranking/?year=2018'\n# PATH = './Users/hyhy/Documents/YURUCHARA_GANs/Scraping/scraping_env/IMG'\n\nresponse = requests.get(url)\nsoup = BeautifulSoup(response.text, 'lxml')\nlinks = soup.find_all('img', src=re.compile(\n '^http://www.yurugp.jp/img/uploads/character'))\nfor link in links:\n print(link['src'])\n\n r = requests.get(link['src'])\n with open('img/' + link['src'].split('/')[-1], 'wb') as file:\n file.write(r.content)\n", "repo_name": "hyhy-poemer/yuruchara_scraping", "sub_path": "test3.py", "file_name": "test3.py", "file_ext": "py", "file_size_in_byte": 592, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "requests.get", "line_number": 9, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 10, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 11, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 16, "usage_type": "call"}]} +{"seq_id": "12195064364", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\npython3 calculate_av_utt_lengths.py -i train\n\n\"\"\"\n\n\nimport argparse\n\n\ndef set_args():\n ap = argparse.ArgumentParser()\n ap.add_argument('-i', nargs='*', help='input file(s)')\n return ap.parse_args()\n\n\ndef av_length(files):\n\n c = 0\n tokens = 0\n\n for file in files:\n with open(file, 'r', encoding='utf8') as f:\n for line in f:\n c += 1\n tokens += len(line.strip().split())\n\n print('lines counted: {}'.format(c))\n print('tokens counted: {}'.format(tokens))\n print('average tokens per line: {:.2f}'.format((tokens/c)))\n\n\nif __name__ == \"__main__\":\n args = set_args()\n\n av_length(args.i)\n", "repo_name": "tannonk/two-headed-master", "sub_path": "scripts/calculate_av_utt_lengths.py", "file_name": "calculate_av_utt_lengths.py", "file_ext": "py", "file_size_in_byte": 710, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "20", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 14, "usage_type": "call"}]} +{"seq_id": "43148218989", "text": "import os\r\nimport sys\r\nimport pickle\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport pingouin as pg\r\nimport matplotlib.ticker as mtick\r\n\r\nfrom matplotlib import rcParams\r\nfrom wesanderson import wes_palettes\r\nfrom numpy.random import RandomState\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom matplotlib.ticker import MultipleLocator, IndexLocator, FixedLocator\r\nfrom scipy.special import expit\r\nfrom matplotlib.patches import Patch\r\nfrom scipy.stats import chisquare, zscore\r\n\r\nsns.set_context('notebook',font_scale=1.4)\r\nsns.set_style('ticks', {'axes.spines.right':False, 'axes.spines.top':False})\r\n# sns.set_style({'axes.facecolor':'.9','figure.facecolor':'.9'})\r\nrcParams['font.family'] = 'sans-serif'\r\nrcParams['font.sans-serif'] = 'Arial'\r\nrcParams['savefig.dpi'] = 300\r\n# rcParams['savefig.format'] = 'png'\r\n\r\ncons = ['CS+','CS-']\r\nphases = ['baseline','acquisition','extinction']\r\ngroups = ['healthy','ptsd']\r\n\r\nsub_args = [1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,20,21,23,24,25,26]\r\np_sub_args = [101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,118, 120, 121, 122, 123, 124, 125]\r\nall_sub_args = sub_args + p_sub_args\r\n\r\nsmt_sub_args = [2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,20,21,101,102,103,104,105,106,107,108,109,110,111,112,113,114,116,117,118,120]\r\nxcl_sub_args = [2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,19,21,101,102,103,104,105,106,107,108,109,110,111,112,113,114,116,117,118]\r\n\r\nsubjects = {'healthy':sub_args,\r\n 'ptsd':p_sub_args,\r\n 'all':all_sub_args}\r\n\r\ngpal = list((wes_palettes['Zissou'][0],wes_palettes['Royal1'][1]))\r\ncpal = ['darkorange','grey']\r\nspal = list((wes_palettes['Darjeeling1'][-1],wes_palettes['Darjeeling1'][0],wes_palettes['Darjeeling1'][1],))\r\nspal = sns.color_palette(spal,n_colors=3,desat=.8)\r\ntpal = list((wes_palettes['Chevalier'][0],wes_palettes['Chevalier'][1]))\r\ncpoint = sns.color_palette(cpal,n_colors=2,desat=.75)\r\nphase_convert = {1:'baseline',2:'acquisition',3:'extinction'}\r\nphase2int = {'baseline':1,'acquisition':2,'extinction':3}\r\n\r\n# WORK = '/work/05426/ach3377/lonestar/'\r\n# HOME = '/home1/05426/ach3377/'\r\n# SCRATCH = '/scratch/05426/ach3377/'\r\n# gPPI_codebase = HOME + 'gPPI/'\r\n\r\ndef mkdir(path,local=False):\r\n if not local and not os.path.exists(path):\r\n os.makedirs(path)\r\ndef lgroup(x):\r\n if x > 100: return 'ptsd'\r\n else: return 'healthy'\r\n\r\n#these are BIDS-app made\r\ndata_dir = os.path.join(os.path.expanduser('~'),'Documents','fearmem')\r\nbids_dir = os.path.join(data_dir,'fm-bids')\r\n\r\n# bids_dir = os.path.join(SCRATCH,'fc-bids')\r\n# deriv = os.path.join(bids_dir, 'derivatives')\r\n# prep_dir = os.path.join(deriv,'fmriprep')\r\n# fs_dir = os.path.join(deriv,'freesurfer')\r\n\r\n#these are user made\r\n# model = os.path.join(deriv,'model');#mkdir(model)\r\n# preproc = os.path.join(deriv,'preproc');#mkdir(preproc)\r\n# group_masks = os.path.join(deriv,'group_masks')\r\n\r\n\r\n\r\n# std_1mm_brain = os.path.join(WORK,'standard','MNI152_T1_1mm_brain.nii.gz')\r\n# std_3mm_brain = os.path.join(WORK,'standard','MNI152_T1_3mm_brain.nii.gz')\r\n# std_3mm_brain_mask = os.path.join(WORK,'standard','MNI152_T1_3mm_brain_mask.nii.gz')\r\n# std_2009_brain = os.path.join(SCRATCH,'standard','MNI152NLin2009cAsym_T1_1mm_brain.nii.gz')\r\n# std_2009_brain_mask = os.path.join(SCRATCH,'standard','MNI152NLin2009cAsym_T1_1mm_brain_mask.nii.gz')\r\n# std_2009_brain_3mm = os.path.join(SCRATCH,'standard','MNI152NLin2009cAsym_T1_3mm_brain.nii.gz')\r\n# std_2009_brain_mask_3mm = os.path.join(SCRATCH,'standard','MNI152NLin2009cAsym_T1_3mm_brain_mask.nii.gz')\r\n\r\ntasks = {'baseline':{'n_trials':48,'ses':1,'n_tr':259},\r\n 'acquisition':{'n_trials':48,'ses':1,'n_tr':259},\r\n 'extinction':{'n_trials':48,'ses':1,'n_tr':259},\r\n 'renewal':{'n_trials':24,'ses':2,'n_tr':135},\r\n 'memory_run-01':{'n_trials':80,'ses':2,'n_tr':310},\r\n 'memory_run-02':{'n_trials':80,'ses':2,'n_tr':310},\r\n 'memory_run-03':{'n_trials':80,'ses':2,'n_tr':310},\r\n 'localizer_run-01':{'n_trials':24,'ses':2,'n_tr':240},\r\n 'localizer_run-02':{'n_trials':24,'ses':2,'n_tr':240},\r\n 'source_memory_typicality':{},\r\n }\r\n\r\nslices={'CS+':{\r\n 'baseline':{'encoding':slice(0,24),\r\n 'retrieval':slice(144,168)},\r\n \r\n 'acquisition':{'encoding':slice(24,48),\r\n 'retrieval':slice(168,192)},\r\n\r\n 'early_extinction':{'encoding':slice(48,56),\r\n 'retrieval':slice(192,200)},\r\n \r\n 'extinction':{'encoding':slice(56,72),\r\n 'retrieval':slice(200,216)}},\r\n 'CS-':{\r\n 'baseline':{'encoding':slice(72,96),\r\n 'retrieval':slice(216,240)},\r\n \r\n 'acquisition':{'encoding':slice(96,120),\r\n 'retrieval':slice(240,264)},\r\n\r\n 'early_extinction':{'encoding':slice(120,128),\r\n 'retrieval':slice(264,272)},\r\n \r\n 'extinction':{'encoding':slice(128,144),\r\n 'retrieval':slice(272,288)}}}\r\n\r\nmem_slices = {'CS+':{\r\n 'baseline':slice(0,24),\r\n \r\n 'acquisition':slice(24,48),\r\n\r\n 'early_extinction':slice(48,56),\r\n \r\n 'extinction':slice(56,72),\r\n\r\n 'foil':slice(72,120)},\r\n\r\n 'CS-':{\r\n 'baseline':slice(120,144),\r\n \r\n 'acquisition':slice(144,168),\r\n\r\n 'early_extinction':slice(168,176),\r\n \r\n 'extinction':slice(176,192),\r\n\r\n 'foil':slice(192,240)}}\r\n\r\nclass bids_meta(object):\r\n\r\n def __init__(self, sub):\r\n \r\n self.num = int(sub)\r\n \r\n self.fsub = 'sub-FC{0:0=3d}'.format(self.num)\r\n\r\n self.subj_dir = os.path.join(bids_dir, self.fsub)\r\n self.events = os.path.join(self.subj_dir, 'events')\r\n\r\n self.behav = {}\r\n for task in tasks: self.behav[task] = self.load(task)\r\n self.cs_lookup()\r\n\r\n self.mem_df = pd.concat([self.behav['memory_run-01'],self.behav['memory_run-02'],self.behav['memory_run-03']]).reset_index(drop=True)\r\n\r\n def load(self,task):\r\n try:\r\n file = pd.read_csv(os.path.join(self.events,self.fsub+'_task-'+task+'_events.tsv'),sep='\\t')\r\n file['subject'] = self.num\r\n return file\r\n except FileNotFoundError:\r\n pass\r\n \r\n def cs_lookup(self): \r\n if self.behav['acquisition'].loc[0,'stimulus'][0] == 'a':\r\n self.csplus = 'animals'\r\n self.csminus = 'tools'\r\n elif self.behav['acquisition'].loc[0,'stimulus'][0] == 't':\r\n self.csplus = 'tool'\r\n self.csminus = 'animal'\r\n\r\n # self.prep_dir = os.path.join(prep_dir,self.fsub)\r\n # self.fs_dir = os.path.join(fs_dir,self.fsub)\r\n\r\n # self.model_dir = os.path.join(model,self.fsub);mkdir(self.model_dir,local)\r\n # self.feat_dir = os.path.join(self.model_dir,'feats');mkdir(self.feat_dir,local)\r\n # self.preproc_dir = os.path.join(preproc,self.fsub);mkdir(self.preproc_dir,local)\r\n \r\n # self.reference = os.path.join(self.preproc_dir,'reference');mkdir(self.reference,local)\r\n # self.t1 = os.path.join(self.reference,'T1w.nii.gz')\r\n # self.t1_mask = os.path.join(self.reference,'T1w_mask.nii.gz')\r\n # self.t1_brain = os.path.join(self.reference,'T1w_brain.nii.gz')\r\n # self.refvol = os.path.join(self.reference,'boldref.nii.gz')\r\n # self.refvol_mask = os.path.join(self.reference,'boldref_mask.nii.gz')\r\n # self.refvol_brain = os.path.join(self.reference,'boldref_brain.nii.gz')\r\n \r\n # self.ref2std = os.path.join(self.reference,'ref2std.mat')\r\n # self.std2ref = os.path.join(self.reference,'std2ref.mat')\r\n\r\n # self.ref2std3 = os.path.join(self.reference,'ref2std3.mat')\r\n # self.std32ref = os.path.join(self.reference,'std32ref.mat')\r\n\r\n\r\n # self.ref2t1 = os.path.join(self.reference,'ref2t1.mat')\r\n # self.t12std_nii = os.path.join(self.reference,'t12std')\r\n # self.t12std = os.path.join(self.reference,'t12std.mat')\r\n # self.t12std_warp = os.path.join(self.reference,'t12std_warp')\r\n\r\n # self.func = os.path.join(self.preproc_dir,'func');mkdir(self.func,local)\r\n # self.beta = os.path.join(self.preproc_dir,'lss_betas');mkdir(self.beta,local) \r\n\r\n # self.fs_regmat = os.path.join(self.reference,'RegMat.dat')\r\n # self.faa = os.path.join(self.reference,'aparc+aseg.nii.gz')\r\n # self.saa = os.path.join(self.reference,'std_aparc+aseg.nii.gz')\r\n \r\n # self.masks = os.path.join(self.preproc_dir,'masks');mkdir(self.masks,local)\r\n # self.weights = os.path.join(self.preproc_dir,'rsa_weights');mkdir(self.weights,local)\r\n\r\n # self.rsa = os.path.join(self.model_dir,'rsa_results');mkdir(self.rsa,local)\r\n\r\ndef pdm(x,y,tail='two',nperm=10000):\r\n '''ASSUMES PAIRED DATA (x,y)\r\n tail = 'two' (default) or \"greater\" ''' \r\n \r\n if type(x) == pd.core.series.Series:\r\n x = x.values\r\n\r\n if type(y) == pd.core.series.Series:\r\n y = y.values\r\n\r\n assert x.shape == y.shape\r\n\r\n if True in np.isnan(x) or True in np.isnan(y):\r\n del_x = np.where(np.isnan(x) == True)[0]\r\n del_y = np.where(np.isnan(y) == True)[0]\r\n del_ = np.unique(np.concatenate((del_x,del_y)))\r\n\r\n x = np.delete(x,del_)\r\n y = np.delete(y,del_)\r\n \r\n _n = x.shape[0]\r\n\r\n diff = x - y\r\n fixed = diff.mean()\r\n\r\n\r\n R = RandomState(42)\r\n perm_res = np.zeros(nperm)\r\n for i in range(nperm):\r\n flip = R.choice([-1,1],_n)\r\n samp = diff * flip\r\n perm_res[i] = samp.mean()\r\n\r\n if tail == 'greater':\r\n p = np.mean(perm_res > fixed)\r\n elif tail == 'two':\r\n p = np.mean(np.abs(perm_res) > np.abs(fixed))\r\n\r\n print(pg.ttest(x,y,paired=True))\r\n return fixed, p, perm_res\r\n\r\ndef onesample_bdm(x,mu=0,tail='two-tailed',n_boot=10000):\r\n R = np.random.RandomState(42)\r\n\r\n boot_res = np.zeros(n_boot)\r\n\r\n for i in range(n_boot):\r\n boot_res[i] = R.choice(x,size=x.shape,replace=True).mean()\r\n avg = x.mean()\r\n\r\n if tail == 'two-tailed':\r\n if avg > mu:\r\n p = (1 - np.mean(boot_res > mu)) * 2\r\n else:\r\n p = (1 - np.mean(boot_res < mu)) * 2\r\n ci = (np.percentile(boot_res,2.5),np.percentile(boot_res,97.5))\r\n\r\n elif tail == 'greater':\r\n p = 1 - np.mean(boot_res > mu)\r\n ci = (np.percentile(boot_res,5),np.percentile(boot_res,100))\r\n\r\n elif tail == 'less':\r\n p = 1 - np.mean(boot_res < mu)\r\n ci = (np.percentile(boot_res,0),np.percentile(boot_res,95))\r\n\r\n if p == 0.0: p = 1/n_boot\r\n\r\n res = pd.DataFrame({'mu':mu,'avg':avg,'CI_l':ci[0],'CI_u':ci[1],'p':p,'tail':tail},index=[0])\r\n return res.round(4)", "repo_name": "dunsmoorlab/fc_memory_study", "sub_path": "analysis/fm_config.py", "file_name": "fm_config.py", "file_ext": "py", "file_size_in_byte": 11318, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "seaborn.set_context", "line_number": 21, "usage_type": "call"}, {"api_name": "seaborn.set_style", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.rcParams", "line_number": 24, "usage_type": "name"}, {"api_name": "matplotlib.rcParams", "line_number": 25, "usage_type": "name"}, {"api_name": "matplotlib.rcParams", "line_number": 26, "usage_type": "name"}, {"api_name": "wesanderson.wes_palettes", "line_number": 44, "usage_type": "name"}, {"api_name": "wesanderson.wes_palettes", "line_number": 46, "usage_type": "name"}, {"api_name": "seaborn.color_palette", "line_number": 47, "usage_type": "call"}, {"api_name": "wesanderson.wes_palettes", "line_number": 48, "usage_type": "name"}, {"api_name": "seaborn.color_palette", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path", "line_number": 59, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path", "line_number": 66, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 67, "usage_type": "call"}, {"api_name": "os.path", "line_number": 67, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 156, "usage_type": "call"}, {"api_name": "os.path", "line_number": 156, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 157, "usage_type": "call"}, {"api_name": "os.path", "line_number": 157, "usage_type": "attribute"}, {"api_name": "pandas.concat", "line_number": 163, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 167, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 167, "usage_type": "call"}, {"api_name": "os.path", "line_number": 167, "usage_type": "attribute"}, {"api_name": "pandas.core", "line_number": 224, "usage_type": "attribute"}, {"api_name": "pandas.core", "line_number": 227, "usage_type": "attribute"}, {"api_name": "numpy.isnan", "line_number": 232, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 233, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 233, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 234, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 234, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 235, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 235, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 237, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 238, "usage_type": "call"}, {"api_name": "numpy.random.RandomState", "line_number": 246, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 247, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 254, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 256, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 256, "usage_type": "call"}, {"api_name": "pingouin.ttest", "line_number": 258, "usage_type": "call"}, {"api_name": "numpy.random.RandomState", "line_number": 262, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 262, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 264, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 272, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 274, "usage_type": "call"}, {"api_name": "numpy.percentile", "line_number": 275, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 278, "usage_type": "call"}, {"api_name": "numpy.percentile", "line_number": 279, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 282, "usage_type": "call"}, {"api_name": "numpy.percentile", "line_number": 283, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 287, "usage_type": "call"}]} +{"seq_id": "20666043740", "text": "# requires python 3.8 or less\n# check compatibility --> https://pypi.org/project/PyAutoGUI/#description\n#!conda activate py38 \n\nimport os,time\nimport pyautogui\nimport keyboard\n\nfrom selenium import webdriver\n\nfrom highscore_manager import highscore_manager as HSM\nhsm = HSM()\n\nDIR = os.path.dirname(os.path.realpath(__file__))\n\ndef get_browser(visible= True):\n #options\n options = webdriver.ChromeOptions()\n options.add_argument('test-type')\n # options.add_argument(\"--no-sandbox\") # no sandboxing\n # chrome_options.add_argument(\"--load-extension=\" + unpackedExtensionPath)\n options.add_argument('--js-flags=--expose-gc')\n options.add_argument('--enable-precise-memory-info')\n options.add_argument('--disable-popups-blocking')\n options.add_argument('--disable-default-apps')\n options.add_argument('test-type=browser')\n options.add_argument('disable-infobars')\n # options.add_argument('window-size=800x600')\n # options.add_argument('window-size=1600x1200')\n options.add_argument('start-maximized')\n options.add_argument('log-level=3')\n # options.add_argument(\"user-data-dir=C:\\\\Users\\\\JGarza\\\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\\\\Default\") \n\n if visible == False:\n options.add_argument('headless')\n \n return webdriver.Chrome(executable_path=os.path.join(DIR,'chromedriver.exe'),options=options)\n\n\nbrowser = get_browser(True)\nbrowser.get('https://googledino.com/')\n# full screen\npyautogui.getWindowsWithTitle(\"Google Dinosaur Game - Google Chrome\")[0].maximize()\n\n\n\nXYs = [\n [1620,720],\n [1619,720],\n [1618,720],\n [1617,720],\n [1616,720],\n [1615,720],\n\n [1620,718],\n [1619,718],\n [1618,718],\n [1617,718],\n [1616,718],\n [1615,718],\n\n [1620,715],\n [1619,715],\n [1618,715],\n [1617,715],\n [1616,715],\n [1615,715],\n ]\n\n#R=83 G=83 B=83 \n\npyautogui.keyDown('space')\n\nscore = 0 \n\nwhile 1:\n \n for xy in XYs:\n if pyautogui.pixel(xy[0],xy[1])==(83,83,83): \n print(xy[0],xy[1],'jump!')\n pyautogui.keyDown('space')\n time.sleep(0.0001)\n pyautogui.keyUp('space')\n score += 1\n # break\n\n if pyautogui.pixel(1971,646)==(83,83,83): \n print('💀 -> 🔁')\n print(score,hsm.data['score'])\n if score > hsm.data['score']:\n hsm.data['score'] = score\n hsm.save()\n score = 0 \n\n\n pyautogui.press('return')\n\n if keyboard.is_pressed('esc')==True:\n print('end program')\n break \n\n", "repo_name": "jgarza9788/Python_Pro_Bootcamp", "sub_path": "Sections/Section93_automate_dinosaurs/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2540, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "highscore_manager.highscore_manager", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 14, "usage_type": "call"}, {"api_name": "selenium.webdriver.ChromeOptions", "line_number": 18, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 18, "usage_type": "name"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 37, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 37, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "pyautogui.getWindowsWithTitle", "line_number": 43, "usage_type": "call"}, {"api_name": "pyautogui.keyDown", "line_number": 72, "usage_type": "call"}, {"api_name": "pyautogui.pixel", "line_number": 79, "usage_type": "call"}, {"api_name": "pyautogui.keyDown", "line_number": 81, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 82, "usage_type": "call"}, {"api_name": "pyautogui.keyUp", "line_number": 83, "usage_type": "call"}, {"api_name": "pyautogui.pixel", "line_number": 87, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 96, "usage_type": "call"}, {"api_name": "keyboard.is_pressed", "line_number": 98, "usage_type": "call"}]} +{"seq_id": "9828143939", "text": "import os\nimport re\nimport string\nfrom nltk.corpus import stopwords\nimport pymorphy2\nfrom nltk.tokenize import word_tokenize\nfrom tqdm import tqdm\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import display\n\n\ndef get_texts(main_dir):\n texts = []\n\n for root, dirs, files in os.walk(main_dir):\n for name in files:\n with open(os.path.join(root, name), 'r', encoding='utf-8-sig') as f:\n text = f.read().splitlines()\n text = ' '.join(text)\n text = re.sub(r' 9999 00:00:0,500 --> 00:00:2,00 www.tvsubtitles.net', '', text)\n text = re.sub(r'\\d', '', text)\n text = re.sub(r'[A-Za-z]', '', text)\n texts.append(text)\n return texts\n\n\ndef preprocess(texts):\n stops = stopwords.words('russian')\n stops.extend(['это', 'весь'])\n morph = pymorphy2.MorphAnalyzer()\n\n preprocessed_texts = []\n for t in tqdm(texts):\n t = t.translate(str.maketrans('', '', string.punctuation)).lower()\n t = word_tokenize(t)\n t = [morph.parse(word)[0].normal_form for word in t if morph.parse(word)[0].normal_form not in stops]\n preprocessed_texts.append(' '.join(t))\n\n return preprocessed_texts\n\n\ndef inverted_index(preprocessed_texts):\n vectorizer = CountVectorizer(analyzer='word')\n X = vectorizer.fit_transform(preprocessed_texts)\n df = pd.DataFrame(X.todense(), columns=vectorizer.get_feature_names())\n print('matrix Term-Document:')\n display(df)\n\n return df\n\n\ndef tasks(df):\n morph = pymorphy2.MorphAnalyzer()\n\n print('#1: the most frequent word in the collection:', df.sum(axis=0).idxmax(axis=\"columns\"),\n '(frequency: %s)\\n' % df.sum(axis=0).max())\n\n print('#2: one of the rarest word in the collection:', df.sum(axis=0).idxmin(axis=\"columns\"),\n '(frequency: %s)\\n' % df.sum(axis=0).min())\n\n new_df = df.replace(0, np.nan)\n print('#3: words that are in all documents:',\n ', '.join(list(new_df.dropna(axis='columns').columns)) + '\\n')\n\n characters = [['Моника', 'Мон'], ['Рэйчел', 'Рейч'], ['Чендлер', 'Чэндлер', 'Чен'],\n ['Фиби', 'Фибс'], ['Росс'], ['Джоуи', 'Джои', 'Джо']]\n char_freq = {}\n for ch in characters:\n normal = [morph.parse(name)[0].normal_form for name in ch]\n char_freq[ch[0]] = df[normal].sum(axis=0).sum()\n\n print('#4: how many times was each character used in subtitles '\n '(all variants of the name are taken into account):',\n char_freq, '\\nthe most frequent character:', max(char_freq))\n\n\ndef main():\n main_dir = './friends-data'\n texts = get_texts(main_dir)\n preprocessed = preprocess(texts)\n main_df = inverted_index(preprocessed)\n tasks(main_df)\n\n\nif __name__ == \"__main__\":\n main()\n", "repo_name": "schwarzzzzz/info-search", "sub_path": "hw1_Kazakov.py", "file_name": "hw1_Kazakov.py", "file_ext": "py", "file_size_in_byte": 2900, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "os.walk", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "re.sub", "line_number": 22, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 23, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 24, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 30, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 30, "usage_type": "name"}, {"api_name": "pymorphy2.MorphAnalyzer", "line_number": 32, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 35, "usage_type": "call"}, {"api_name": "string.punctuation", "line_number": 36, "usage_type": "attribute"}, {"api_name": "nltk.tokenize.word_tokenize", "line_number": 37, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text.CountVectorizer", "line_number": 45, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 47, "usage_type": "call"}, {"api_name": "IPython.display.display", "line_number": 49, "usage_type": "call"}, {"api_name": "pymorphy2.MorphAnalyzer", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 63, "usage_type": "attribute"}]} +{"seq_id": "44069336871", "text": "from projen.awscdk import AwsCdkPythonApp\n\nproject = AwsCdkPythonApp(\n author_email=\"cleghornw@protonmail.com\",\n author_name=\"William Cleghorn\",\n cdk_version=\"2.1.0\",\n module_name=\"aws_rip\",\n name=\"aws-rip\",\n poetry=True,\n version=\"0.1.0\",\n)\n\nproject.synth()", "repo_name": "Agorist-Digital/aws-rip", "sub_path": ".projenrc.py", "file_name": ".projenrc.py", "file_ext": "py", "file_size_in_byte": 279, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "projen.awscdk.AwsCdkPythonApp", "line_number": 3, "usage_type": "call"}]} +{"seq_id": "39209553361", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 12 10:37:23 2021\r\n\r\n@author: Mo\r\n\"\"\"\r\n# import os\r\n\r\nimport statistics as stat\r\nfrom search_space_manager.sample_models import *\r\nfrom load_data.load_data import *\r\nfrom search_space_manager.search_space import *\r\nfrom search_space_manager.map_functions import *\r\nfrom search_algo.PCRS import *\r\nfrom GNN_models.graph_regression import *\r\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\r\n\r\nset_seed()\r\n\r\n\r\ndef Evaluate_best_model(submodel):\r\n set_seed()\r\n search_metric = config[\"param\"][\"search_metric\"]\r\n z_final = int(config[\"param\"][\"z_final\"])\r\n epochs = int(config[\"param\"][\"best_model_epochs\"])\r\n best_loss_param_path = f\"{config['path']['performance_distribution_folder']}/best_model_param.pth\"\r\n\r\n type_task = config[\"dataset\"][\"type_task\"]\r\n\r\n timestart = time.time() # to record the total time to get the performance distribution set\r\n\r\n gcn, train_model, test_model = get_train(type_task)\r\n\r\n train_loader, val_loader, test_loader = load_dataset(config[\"dataset\"][\"type_experiment\"])\r\n\r\n model, criterion, optimizer = get_model_instance2(submodel, gcn)\r\n scheduler = ReduceLROnPlateau(optimizer, mode='max', factor=0.1, patience=10, verbose=True)\r\n best_model_training_record = defaultdict(list)\r\n\r\n best_loss = 99999999\r\n for epoch in range(epochs):\r\n train_loss = train_model(model, train_loader, criterion, optimizer, epoch + 1)\r\n train_performances = test_model(model, test_loader)\r\n train_val= train_performances[\"pcc\"]\r\n best_model_training_record[\"epoch\"].append(epoch)\r\n best_model_training_record[\"train_loss\"].append(train_loss)\r\n for k, v in train_performances.items():\r\n best_model_training_record[k].append(v)\r\n\r\n if train_loss < best_loss:\r\n best_loss = train_loss\r\n torch.save(model.state_dict(), best_loss_param_path)\r\n scheduler.step(train_val)\r\n df = pd.DataFrame.from_dict(best_model_training_record, orient=\"columns\")\r\n best_model_training_record_file = f'{config[\"path\"][\"result_folder\"]}/best_model_training_record.csv'\r\n df.to_csv(best_model_training_record_file)\r\n\r\n # # torch.save(model.state_dict(), f'{config[\"path\"][\"best_model_folder\"]}/temp_model_dict.pth')\r\n best_model, criterion, optimizer = get_model_instance2(submodel, gcn)\r\n best_model.load_state_dict(torch.load(best_loss_param_path))\r\n\r\n performances = test_model(best_model, test_loader)\r\n for metric, val in performances.items():\r\n add_config(\"results\", f\"AutoCDRP_{metric}\", val)\r\n return performances", "repo_name": "BeObm/AutoCDRP", "sub_path": "search_algo/get_test_acc.py", "file_name": "get_test_acc.py", "file_ext": "py", "file_size_in_byte": 2627, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "torch.optim.lr_scheduler.ReduceLROnPlateau", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.optim.lr_scheduler.save", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.optim.lr_scheduler", "line_number": 52, "usage_type": "name"}, {"api_name": "torch.optim.lr_scheduler.load", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.optim.lr_scheduler", "line_number": 60, "usage_type": "name"}]} +{"seq_id": "74319257010", "text": "\"\"\"\nUtilities for traversing and manipulating trees.\n\nIt can be helpful to operate on an input model as if it were akin to an\nabstract syntax tree (AST), arranging the transformation from raw input to one\n(or more) output forms as a series of transformations.\nThis is how multi-pass compilers work, where the overall transformation is\nlaid out as a series of discrete steps, each of which becomes easier to\ndebug and maintain.\n\nSimilarly, this approach can be helpful in massaging an input model into one\nor more output models which ease code-generation.\n\nSteps such as data validation and emitting the final code is best done using\nclasses deriving from the `NodeVisitor` class, while transformations, defined\nas the transition from one kind of node to another, is best implemented by\nderiving from the `NodeTransformer` class.\n\nSee tests for examples of use.\n\"\"\"\nimport functools\nfrom typing import Any, Union, List\n\n\nTreeOp = Union[\"NodeVisitor\", \"NodeTransformer\"]\n\n\nclass OnDispatch:\n def __init__(self, node_type, method):\n self.node_types = [node_type]\n self.__method = method\n\n @property\n def method(self):\n return self.__method\n\n def __call__(self, *args, **kwargs):\n return self.__method(*args, **kwargs)\n\n\nclass OnVisit(OnDispatch):\n ...\n\n\nclass OnTransform(OnDispatch):\n ...\n\n\ndef on_visit(node_type, *node_types):\n \"\"\"Mark method as handler for visits of nodes of type `node_type` or in `node_types`.\n\n Use this decorator on methods in a `NodeVisitor` class to mark methods as\n handlers for calls to `visit` when providing `node_type` or any of the types\n in `node_types`.\n\n Args:\n node_type: node_type for which this handler should be used\n *node_types: (optional) additional node_types for which to use this handler\n\n Returns:\n A decorated handler object.\n \"\"\"\n\n def decorator(f):\n if isinstance(f, OnVisit):\n wrapper = f\n wrapper.node_types.append(node_type)\n else:\n wrapper = OnVisit(node_type, f)\n functools.update_wrapper(wrapper, f)\n\n for nt in node_types:\n wrapper.node_types.append(nt)\n return wrapper\n\n return decorator\n\n\ndef on_transform(node_type, *node_types):\n \"\"\"Mark method as handler for transformations of nodes of type `node_type` or in `node_types`.\n\n Use this decorator on methods in a `NodeTransformer` class to mark methods as\n handlers for calls to `transform` when providing `node_type` or any of the types\n in `node_types`.\n\n Args:\n node_type: node_type for which this handler should be used\n *node_types: (optional) additional node_types for which to use this handler\n\n Returns:\n A decorated handler object.\n \"\"\"\n\n def decorator(f):\n if isinstance(f, OnTransform):\n wrapper = f\n wrapper.node_types.append(node_type)\n else:\n wrapper = OnTransform(node_type, f)\n functools.update_wrapper(wrapper, f)\n\n for nt in node_types:\n wrapper.node_types.append(nt)\n\n return wrapper\n\n return decorator\n\n\nclass NodeVisitorMeta(type):\n def __new__(cls, name, bases, dct):\n typ = super().__new__(cls, name, bases, dct)\n\n base_handlers = (getattr(b, \"__visitors\", {}) for b in bases)\n visitors = {}\n\n for bh in base_handlers:\n visitors.update(bh)\n\n for val in dct.values():\n if not isinstance(val, OnVisit):\n continue\n for node_type in val.node_types:\n visitors[node_type] = val\n\n setattr(typ, \"__visitors\", visitors)\n\n return typ\n\n def __call__(cls, *args, **kwargs):\n obj = type.__call__(cls, *args, **kwargs)\n\n # bind handler methods on object, this allows calling e.g. `obj.visit_a(node)`\n # as opposed to `obj.visit_a(obj, node)`.\n for ident, val in {ident: getattr(obj, ident) for ident in dir(obj)}.items():\n if isinstance(val, OnVisit):\n setattr(obj, ident, val.method.__get__(obj))\n\n return obj\n\n\nclass NodeVisitor(metaclass=NodeVisitorMeta):\n \"\"\"Base class with which to implement a visitor.\n\n Implement a visitor, a type of class capable of traversing a tree by\n using a series of visit operations, one per type of node, to traverse the tree.\n Visitors are especially useful for implementing validation of nodes in the\n tree and for traversing trees as part of the code-generation step.\n\n To start traversal, pass the tree to the `visit` method.\n Traversal works by defining a `visit` method on the visitor for each\n type of node, which in turn calls `visit` on each of its child nodes\n to continue traversing down the tree.\n This approach is named visitor after the GoF \"Visitor\" pattern.\n\n Note:\n For every node for which there is no specific handler, `visit_default`\n is called. The default behavior of `visit_default` is to raise a\n `NotImplementedError`.\n To install a visit handler, write a method taking 1 argument, `node`,\n and decorate it using the `on_visit()` decorator, passing the decorator\n one or more `Type` objects (~classes), marking the types of nodes to\n handle using the method.\n\n Note:\n * inheritance works (unlike functools.singledispatchmethod)\n * handlers are inherited, and can be overridden\n * method names of handlers MUST remain unique. If defining several\n handlers using the same method name, only the last handler is retained.\n * handlers must be decorated with `on_visit` as the _last_ decorator,\n wrapping handlers in other decorators breaks the ability to identify\n a method as a handler.\n * a single handler can handle multiple types of nodes, either by:\n * decorating the handler multiple times using `@on_visit(...)`\n * passing multiple arguments to `@on_visit(...)`\n \"\"\"\n\n def visit_default(self, node: Any) -> None:\n \"\"\"Default visit function for nodes of types for which there is no specific visit function.\n\n This method defines the default action when calling `visit` on a node for\n which handler has been defined for the node's exact type.\n The default behavior is to raise an error, but this method may be overridden\n by a deriving class to e.g. trigger a NOOP.\n\n Args:\n node: the node to visit. This node is of a type for which the visitor\n has no existing `visit` function.\n\n Returns:\n None\n \"\"\"\n raise NotImplementedError(f\"visit {type(node).__name__} not implemented.\")\n\n def visit(self, node: Any) -> None:\n \"\"\"Visit node `node`.\n\n Visit node. If a specific handler is registered for the node's exact type,\n use it. Otherwise, call `visit_default`.\n\n Args:\n node: the node to visit\n\n Returns:\n None\n \"\"\"\n m = getattr(self, \"__visitors\").get(type(node))\n if m is None:\n self.visit_default(node)\n return\n # pass `self` explicitly as 'methods' are not bound\n m(self, node)\n\n\nclass NodeTransformerMeta(type):\n def __new__(cls, name, bases, dct):\n typ = super().__new__(cls, name, bases, dct)\n\n base_handlers = (getattr(b, \"__transformers\", {}) for b in bases)\n transformers = {}\n\n for bh in base_handlers:\n transformers.update(bh)\n\n for val in dct.values():\n if not isinstance(val, OnTransform):\n continue\n for node_type in val.node_types:\n transformers[node_type] = val\n\n setattr(typ, \"__transformers\", transformers)\n\n return typ\n\n def __call__(cls, *args, **kwargs):\n obj = type.__call__(cls, *args, **kwargs)\n\n # bind handler methods on object, this allows calling e.g. `obj.visit_a(node)`\n # as opposed to `obj.visit_a(obj, node)`.\n for ident, val in {ident: getattr(obj, ident) for ident in dir(obj)}.items():\n if isinstance(val, OnTransform):\n setattr(obj, ident, val.method.__get__(obj))\n\n return obj\n\n\nclass NodeTransformer(metaclass=NodeTransformerMeta):\n \"\"\"Base class with which to implement a transformer.\n\n Implement a transformer, a type of class capable of traversing a tree and\n to replace some/all of the traversed nodes as it does so.\n Transformers are especially useful for implementing rewrite operations where\n specific nodes are replaced/modified to make subsequent parsing and eventually\n code generation easier.\n\n To start traversal, pass the tree to the `transform` method.\n Traversal works by defining a `transform` method on the transformer for each\n type of node, which in turn calls `transform` on each of its child nodes\n to continue traversing down the tree. The return value of each transform\n handler should be the transformed sub-tree.\n In this way, parts or all of the tree may be transformed as part of the\n operation.\n\n Note:\n For every node for which there is no specific handler, `transform_default` is called.\n The default behavior of `transform_default` is to raise a `NotImplementedError`.\n To install a transform handler, write a method taking 1 argument, `node`,\n and decorate it using the `on_transform()` decorator, passing the decorator\n one or more `Type` objects (~classes), marking the types of nodes to\n handle using the method.\n\n Note:\n * inheritance works (unlike functools.singledispatchmethod)\n * handlers are inherited, and can be overridden\n * method names of handlers MUST remain unique. If defining several\n handlers using the same method name, only the last handler is retained.\n * handlers must be decorated with `on_transform` as the _last_ decorator,\n wrapping handlers in other decorators breaks the ability to identify\n a method as a handler.\n * a single handler can handle multiple types of nodes, either by:\n * decorating the handler multiple times using `@on_visit(...)`\n * passing multiple arguments to `@on_visit(...)`\n \"\"\"\n\n def transform_default(self, node: Any) -> Any:\n \"\"\"Default transform function for nodes of types for which there is no specific transform function.\n\n This method defines the default action when calling `transform` on a node for\n which handler has been defined for the node's exact type.\n The default behavior is to raise an error, but this method may be overridden\n by a deriving class to e.g. return back the same object.\n\n Args:\n node: the node to transform. This node is of a type for which the transformer\n has no existing `transform` function.\n\n Returns:\n Raises the `NotImplementedError`\n \"\"\"\n raise NotImplementedError(f\"transform {type(node).__name__} not implemented.\")\n\n def transform(self, node: Any) -> Any:\n \"\"\"Transform node `node`.\n\n Transform node. If a specific handler is registered for the node's exact type,\n use it. Otherwise, call `transform_default`.\n\n Args:\n node: the node to transform\n\n Returns:\n The result of calling the transform handler, may be a new, transformed\n node, may be the same node.\n \"\"\"\n m = getattr(self, \"__transformers\").get(type(node))\n if m is None:\n return self.transform_default(node)\n # pass `self` explicitly as 'methods' are not bound\n return m(self, node)\n\n\ndef parse_tree(pipeline: List[TreeOp], tree: Any) -> Any:\n \"\"\"Parse tree by applying a series of visitors and transformers.\n\n Args:\n pipeline: A series of operations to perform on the tree, each of which\n is a visitor or transformer.\n tree: The input tree/model.\n\n Returns:\n The resulting tree/model from applying each operation in order.\n \"\"\"\n for step in pipeline:\n if isinstance(step, NodeTransformer):\n tree = step.transform(tree)\n elif isinstance(step, NodeVisitor):\n step.visit(tree)\n else:\n raise RuntimeError(f\"{type(step)!r}, expected NodeTransformer|NodeVisitor\")\n return tree\n\n\n__all__ = [\n \"TreeOp\",\n \"on_visit\",\n \"on_transform\",\n \"NodeVisitor\",\n \"NodeTransformer\",\n \"parse_tree\",\n]\n", "repo_name": "jwdevantier/gcgen", "sub_path": "gcgen/api/tree.py", "file_name": "tree.py", "file_ext": "py", "file_size_in_byte": 12573, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "20", "api": [{"api_name": "typing.Union", "line_number": 25, "usage_type": "name"}, {"api_name": "functools.update_wrapper", "line_number": 70, "usage_type": "call"}, {"api_name": "functools.update_wrapper", "line_number": 100, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 178, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 195, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 285, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 302, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 322, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 322, "usage_type": "name"}]} +{"seq_id": "38276731388", "text": "#!/usr/bin/python\nimport datetime\nimport pandas as pd\nimport csv\nimport numpy as np\nimport datetime\nimport Helper_Functions\nimport Import_Files\nimport pickle\nimport csv\n\ndef previousTrimAggregator(crew_trim_history_master):\n prev_trim_df = pd.DataFrame()\n output_df = pd.DataFrame()\n # Column names for final data frame\n column_names = ['date','no_qtr_spans',\n 'brush_acres','no_of_rem','no_of_trims',\n 'qsp_hr','brush_hr','rem_hr',\n 'trim_hr','total_cost', 'total_hr']\n for circuit_id in crew_trim_history_master.keys():\n # Get current trim data\n curr_data = crew_trim_history_master[circuit_id]\n curr_data_df = pd.DataFrame(curr_data, columns=column_names)\n curr_agg_dict = cthAggregateFunction(curr_data_df, prefix=\"curr\")\n prev_circuit_id, prev_trim_yr, curr_trim_yr = Helper_Functions.getPrevTrim(circuit_id, crew_trim_history_master)\n # Get previous trim data\n if np.isnan(prev_trim_yr):\n # Store NaN vals if no prev trim exists\n prev_cols = ['prev_' + col for col in column_names if col != 'date']\n nan_vals = [np.NaN for col in column_names if col != 'date']\n prev_agg_dict = dict(zip(prev_cols, nan_vals))\n else:\n prev_data = crew_trim_history_master[prev_circuit_id]\n prev_data_df = pd.DataFrame(prev_data, columns=column_names)\n prev_agg_dict = cthAggregateFunction(prev_data_df, prefix=\"prev\")\n prev_trim_df = prev_trim_df.append({'circuit_id': circuit_id, 'prev_circuit_id': prev_circuit_id}, ignore_index=True)\n output_dict = dict(curr_agg_dict)\n output_dict.update(prev_agg_dict)\n output_dict['prev_trim_yr'] = prev_trim_yr\n output_dict['yrs_since_trim'] = curr_trim_yr - prev_trim_yr\n output_dict['circuit_id'] = circuit_id\n output_df = output_df.append(output_dict, ignore_index = True)\n prev_trim_df.to_csv(Import_Files.prev_trim_f, index=False)\n return(output_df)\n\ndef featureStats (input_feature):\n input_feature = pd.to_numeric(input_feature)\n return(\n input_feature.sum(skipna = \"True\"),\n )\n\ndef cthAggregateFunction(previous_trim_data_df, prefix):\n final_agg_features = {}\n start_date = pd.to_datetime(previous_trim_data_df.date).min()\n end_date = pd.to_datetime(previous_trim_data_df.date).max()\n final_agg_features[prefix + '_' + 'durtn_days'] = (end_date - start_date).days\n n_col = previous_trim_data_df.shape[1]\n for i in previous_trim_data_df.columns[1:n_col]:\n feat_names = [prefix + '_' + i]#,\"mean_\" + i,\"std_\" + i,\"skew_\" + i]\n feat_values = featureStats(previous_trim_data_df[i])\n for j in range(0,len(feat_names)):\n final_agg_features[feat_names[j]] = feat_values[j]\n return(final_agg_features)\n\n\nclass CrewTrimHistoryFactory():\n def __init__(self, total_cleaned_cth_data_input,output_pickle_file, carryover_f, last_trim_month_collector):\n self.total_cleaned_cth_data_input = total_cleaned_cth_data_input\n self.df = pd.DataFrame()\n self.output_pickle_file = output_pickle_file\n self.crew_trim_history_master = {}\n self.crew_trim_history_master_relevant = {}\n self.crew_trim_history_master_recalibrated = {}\n self.carryover_f = carryover_f\n self.crew_trim_cycle_maintenance = list(set(Helper_Functions.getCrewTrimMainCycles()))\n self.circuit_id_month_lookup = {}\n self.last_trim_month_collector = last_trim_month_collector\n sql_flg = 0\n with open(Import_Files.sql_flag) as f:\n csv_f = csv.reader(f)\n for row in csv_f:\n if row[0] == '1':\n sql_flg = 1\n with open( self.total_cleaned_cth_data_input) as f:\n csv_f = csv.reader(f)\n counter = 0\n for row in csv_f:\n if counter>0:\n substation_feeder = str(row[0])\n # Filter out substation names that we do not have legitimate id's for currently and OPEN circuits\n if len(substation_feeder) < 9:\n org_name = str(row[0])\n substation_feeder = Helper_Functions.substationFeederStandardizer(substation_feeder)\n year = str(row[2])[0:4]\n # Select data\n total_hr = float(row[8]) + float(row[9]) + float(row[10]) + float(row[11])\n data_sample = [row[2], row[4], row[5], row[6],\n row[7], row[8],\n row[9], row[10], row[11],\n row[12], total_hr]\n circuit_id = substation_feeder + '-' + year\n if circuit_id in self.crew_trim_history_master.keys():\n self.crew_trim_history_master[circuit_id].append(data_sample)\n else:\n self.crew_trim_history_master[circuit_id] = [data_sample]\n counter = counter + 1\n self.crew_trim_all_netbs = self.crew_trim_history_master\n ## Last Trim Month\n self.month_collector = {}\n for circuit_id,data in self.crew_trim_history_master.items():\n circuit_dates = []\n for d in data:\n circuit_dates.append(datetime.datetime.strptime(d[0],\"%Y%m%d\").date())\n circuit_dates = min(circuit_dates) \n self.month_collector[circuit_id] = circuit_dates.month \n with open(self.last_trim_month_collector,'wb') as f:\n pickle.dump(self.month_collector, f, pickle.HIGHEST_PROTOCOL)\n\n \n ### Deal with cross over from Dec Y1 to Jan Y2\n blacklist_circuit_id = self.createBlackList()\n \n # Filter out blacklisted id's\n for circuit_id in self.crew_trim_history_master.keys():\n if circuit_id not in blacklist_circuit_id:\n self.crew_trim_history_master_recalibrated[circuit_id] = self.crew_trim_history_master[circuit_id]\n else:\n pass\n self.crew_trim_history_master = self.crew_trim_history_master_recalibrated\n \n ## Filter out non cycle trims as best as feasible \n self.useful_circuits,self.dates,self.trims,self.costs = self.initialRecursion()\n self.useful_circuits_cp, self.non_cycle_trims_cp = self.recursionIteration2()\n self.keep_trims = {}\n \n ## Keep only useful _circuits \n for circuit_id , data in self.crew_trim_history_master.items() :\n if circuit_id in list(set(self.useful_circuits_cp)):\n self.keep_trims [circuit_id] = data\n else:\n pass \n self.df = previousTrimAggregator(self.keep_trims)\n \n def getFeatures(self):\n return(self.df)\n\n def writeFeatures(self):\n self.df.to_pickle(self.output_pickle_file)\n with open(Import_Files.useful_circuits,'wb') as f:\n pickle.dump(self.useful_circuits_cp, f, pickle.HIGHEST_PROTOCOL)\n \n \n def initialRecursion(self):\n circuit_ids = {}\n costs = {}\n trims = {}\n dates = {}\n for key,value in self.crew_trim_history_master.items():\n local_cost = 0\n local_dates = []\n local_trims = 0\n for sample in value:\n local_cost += float(sample[9])\n local_dates.append(sample[0])\n local_trims += float(sample[4])\n costs[key] = local_cost \n dates[key] = local_dates\n trims[key] = local_trims \n \n circuit_yr_dict = {}\n for key in self.crew_trim_history_master.keys():\n new_key = key.split(\"-\")[0] + \"-\" + key.split(\"-\")[1]\n yr = key.split(\"-\")[2]\n if new_key in circuit_yr_dict.keys(): \n circuit_yr_dict[new_key].append( yr)\n else:\n circuit_yr_dict[new_key] = [yr]\n \n useful_circuits = [] \n for key,value in circuit_yr_dict.items():\n value = [int(x) for x in value]\n viable_pairs = {}\n for v in value:\n local_value = [x for x in value if x-v > 3]\n if len(local_value) > 0:\n cost_v = costs[key + \"-\" + str(v)]\n costs_x = [{x:cost_v + costs[key + \"-\" + str(x)]} for x in local_value] \n costs_x_mx = max([ cost_v + costs[key + \"-\" + str(x)] for x in local_value]) \n for yr in costs_x: \n if list(yr.values())[0] == costs_x_mx:\n mx_yr = list(yr.keys())[0]\n viable_pairs[(str(v) + \"_\" + str(mx_yr))] = costs_x_mx\n if len(viable_pairs) > 0:\n mx_viable_pair_cst = max([x for x in viable_pairs.values()])\n final_mx_pair = 0\n final_mx_cost = 0\n for pair,pr_cost in viable_pairs.items():\n if pr_cost == mx_viable_pair_cst:\n final_mx_pair = pair\n final_mx_cost = pr_cost\n useful_circuits.append(key + \"-\" + final_mx_pair.split(\"_\")[0]) \n useful_circuits.append(key + \"-\" + final_mx_pair.split(\"_\")[1]) \n return(useful_circuits,dates,trims,costs)\n\n \n def recursionIteration2(self):\n non_cycle_trims = [x for x in self.crew_trim_history_master.keys() if x not in self.useful_circuits] \n non_cycle_trims_cp = non_cycle_trims.copy()\n ## From non cycle trims to useful trims\n ## Hand pick based on specific heuristics - flags\n for circuit in non_cycle_trims: \n flg1 = 0\n flg2 = 0\n flg3 = 0\n feasible_trim_years = [int(circuit.split('-')[2]), (int(circuit.split('-')[2])-1), (int(circuit.split('-')[2])+1)]\n feasible_trims = [circuit.split('-')[0] + '-' + circuit.split('-')[1] + '-' + str(x) for x in feasible_trim_years]\n if feasible_trims[0] in self.crew_trim_cycle_maintenance or feasible_trims[1] in self.crew_trim_cycle_maintenance or feasible_trims[2] in self.crew_trim_cycle_maintenance:\n flg1 = 1\n if len(set(self.dates[circuit])) > 1:\n flg2 = 1\n if self.trims[circuit] > 0:\n flg3 = 1 \n if flg1 == 1 and flg2 == 1 and flg3 == 1:\n self.useful_circuits.append(circuit)\n non_cycle_trims_cp.remove(circuit)\n useful_circuits_cp = self.useful_circuits.copy()\n ## From useful trims to non cycle trims \n ## Hand pick based on specific heuristics - flags\n for circuit in self.useful_circuits:\n flg1 = 0\n flg2 = 0\n flg3 = 0\n if self.trims[circuit] == 0:\n flg1 = 1\n if len(set(self.dates[circuit])) ==1:\n flg2 = 1\n feasible_trim_years = [int(circuit.split('-')[2]), (int(circuit.split('-')[2])-1)]\n feasible_trims = [circuit.split('-')[0] + '-' + circuit.split('-')[1] + '-' + str(x) for x in feasible_trim_years]\n if circuit not in feasible_trims:\n flg3 = 1 \n if (flg1 == 1 and flg2 == 1) or flg3 == 1 :\n useful_circuits_cp.remove(circuit)\n non_cycle_trims_cp.append(circuit)\n return(useful_circuits_cp,non_cycle_trims_cp) \n\n def createBlackList(self):\n blacklist_circuit_id = []\n for circuit_id in self.crew_trim_history_master.keys():\n # Check if there is a circuit id in the next year\n circuit_id_next_yr = circuit_id.split('-')[0] + '-' + circuit_id.split('-')[1] +'-' + str(int(circuit_id.split('-')[2]) +1)\n if circuit_id_next_yr in self.crew_trim_history_master.keys():\n circuit_id_dates = [(datetime.datetime.strptime(x[0],\"%Y%m%d\")).date() for x in self.crew_trim_history_master[circuit_id]]\n circuit_id_next_year_dates = [(datetime.datetime.strptime(x[0],\"%Y%m%d\")).date() for x in self.crew_trim_history_master[circuit_id_next_yr]]\n circuit_id_max = max(circuit_id_dates)\n circuit_id_next_year_dates_min = min(circuit_id_next_year_dates)\n # If the trim in the next year is within 14 days of the trim in the previous year\n difference_between_dates = (circuit_id_next_year_dates_min - circuit_id_max)\n if difference_between_dates < datetime.timedelta(days = 14):\n temp_dict = self.crew_trim_history_master[circuit_id]\n blacklist_circuit_id.append(circuit_id)\n ## Change the year to the following year\n for crew_data_sample in range(0,(len(temp_dict))):\n temp_dict[crew_data_sample][0] = str(circuit_id_next_year_dates_min).replace(\"-\",\"\")\n self.crew_trim_history_master[circuit_id_next_yr].append(temp_dict[crew_data_sample])\n pd.Series(blacklist_circuit_id, name='circuit_id').to_csv(self.carryover_f, header=True, index=False) \n return(blacklist_circuit_id)", "repo_name": "ayushtalwar/AmerenAAFinal", "sub_path": "Step_2_CrewTrimHistoryFactory.py", "file_name": "Step_2_CrewTrimHistoryFactory.py", "file_ext": "py", "file_size_in_byte": 13440, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "2", "api": [{"api_name": "pandas.DataFrame", "line_number": 13, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 14, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 23, "usage_type": "call"}, {"api_name": "Helper_Functions.getPrevTrim", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.NaN", "line_number": 30, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 34, "usage_type": "call"}, {"api_name": "Import_Files.prev_trim_f", "line_number": 43, "usage_type": "attribute"}, {"api_name": "pandas.to_numeric", "line_number": 47, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 54, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 55, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 69, "usage_type": "call"}, {"api_name": "Helper_Functions.getCrewTrimMainCycles", "line_number": 75, "usage_type": "call"}, {"api_name": "Import_Files.sql_flag", "line_number": 79, "usage_type": "attribute"}, {"api_name": "csv.reader", "line_number": 80, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 85, "usage_type": "call"}, {"api_name": "Helper_Functions.substationFeederStandardizer", "line_number": 93, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 113, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 113, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 117, "usage_type": "call"}, {"api_name": "pickle.HIGHEST_PROTOCOL", "line_number": 117, "usage_type": "attribute"}, {"api_name": "Import_Files.useful_circuits", "line_number": 149, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 150, "usage_type": "call"}, {"api_name": "pickle.HIGHEST_PROTOCOL", "line_number": 150, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 252, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 252, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 253, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 253, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 258, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 265, "usage_type": "call"}]} +{"seq_id": "32807218772", "text": "from django.shortcuts import render\nfrom django.views.generic import TemplateView\nfrom django.template.loader import render_to_string\nfrom django.contrib.auth.decorators import login_required\nfrom weasyprint import HTML\nfrom django.http import HttpResponse\nfrom dailyTrainingLog.DataProccesing import GetDataFromTimeStation\nimport datetime\n\n\ndef building_pages(location, today):\n timestationData = GetDataFromTimeStation(location)\n data, not_in = timestationData.run()\n \n context = {\n 'today_date': today,\n 'employees_names':data,\n 'not_in':not_in,\n 'location':location\n }\n \n html_string = render_to_string('dailyTrainingLog/template.html', context=context)\n html = HTML(string=html_string)\n rendered_pdf = html.render()\n return [rendered_pdf]\n\n@login_required\ndef dailyTrainigLog_pdf(request, location):\n today = datetime.datetime.now().strftime('%m/%d/%Y')\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = (f'inline; filename={location}-dailyTrainingLog-{today}.pdf')\n documents = building_pages(location, today)\n all_pages = [page for document in documents for page in document.pages]\n documents[0].copy(all_pages).write_pdf(response)\n return response\n\n", "repo_name": "CesarRodriguezPro/IBKFullWebsite", "sub_path": "dailyTrainingLog/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1275, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "2", "api": [{"api_name": "dailyTrainingLog.DataProccesing.GetDataFromTimeStation", "line_number": 12, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 22, "usage_type": "call"}, {"api_name": "weasyprint.HTML", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 29, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 29, "usage_type": "attribute"}, {"api_name": "django.http.HttpResponse", "line_number": 30, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 27, "usage_type": "name"}]} +{"seq_id": "5952682466", "text": "from decouple import config\n\nDIR = config(\"APIDIR\")+ \"/initialisation/\"\nbaseURI = config(\"BASEURI\")\n\n\ndef createInconsistencyError(inconsistencies):\n errorMessages = []\n for inconsistency in inconsistencies:\n spec = inconsistency[\"spec\"][\"value\"].strip(baseURI)\n feat1 = inconsistency[\"feat1\"][\"value\"].strip(baseURI)\n feat2 = inconsistency[\"feat2\"][\"value\"].strip(baseURI)\n confType = inconsistency[\"type\"][\"value\"]\n errorMessages.append(spec + \" has a \" + confType +\n \" concerning the following feature(s): \"+feat1 + \", \" + feat2)\n return '\\n'.join(errorMessages)\n\n\n\n\ndef checkInitialConsistencies(connection):\n queryName = DIR + \"featConsistency.sparql\"\n with open(queryName,\"r\") as queryFile:\n query = queryFile.read()\n result = connection.select(query)\n if len(result[\"results\"][\"bindings\"]) != 0:\n print(createInconsistencyError(result[\"results\"][\"bindings\"]))\n", "repo_name": "leanderpfeiffer/SharedAgentKnowledgeBase", "sub_path": "app/api/initialisation/checkInitialConsistencies.py", "file_name": "checkInitialConsistencies.py", "file_ext": "py", "file_size_in_byte": 977, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "decouple.config", "line_number": 3, "usage_type": "call"}, {"api_name": "decouple.config", "line_number": 4, "usage_type": "call"}]} +{"seq_id": "982186728", "text": "import pathlib\n\n# The directory containing this file\nPARENT_DIR = pathlib.Path(__file__).parent\n\n# The text of the README file\nREADME = (PARENT_DIR / \"README.rst\").read_text()\n\nSETUP_ARGS = dict(\n name=\"GeneticAlgos\",\n version=\"1.0.2\",\n description=\"Simple and powerful Python library for creating genetic algorithms.\",\n long_description=README,\n long_description_content_type=\"text/x-rst\",\n url=\"https://geneticalgos.readthedocs.io/en/latest/\",\n author=\"Lukas Kozelnicky\",\n author_email=\"python@kozelnicky.com\",\n license=\"MIT\",\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: 3.10\",\n ],\n python_requires=\">=3.7\",\n py_modules=[\n \"geneticalgos\",\n ],\n install_requires=[\n \"numpy\",\n ],\n project_urls={\n \"Documentation\": \"https://geneticalgos.readthedocs.io/en/latest/\",\n \"Source\": \"https://github.com/lkozelnicky/GeneticAlgos\",\n },\n)\n\nif __name__ == \"__main__\":\n from setuptools import setup, find_packages\n\n SETUP_ARGS[\"packages\"] = find_packages()\n setup(**SETUP_ARGS)\n", "repo_name": "lkozelnicky/GeneticAlgos", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 1459, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pathlib.Path", "line_number": 4, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 46, "usage_type": "call"}, {"api_name": "setuptools.setup", "line_number": 47, "usage_type": "call"}]} +{"seq_id": "25636426685", "text": "import logging, traceback\n\nfrom datetime import datetime\n\nfrom database import Cursor\nfrom tasks import task\n\nfrom util.itemdraft import pre_draft, run_draft\nfrom util.email import Email\n\nlog = logging.getLogger(__name__)\n\n# Grabs any locked matches where we haven't already created a draft\nFIND_MATCH_DRAFT_QUERY = \"\"\"\nSELECT id, teams FROM matches\nWHERE (state in ('LOCKED', 'WAITING', 'RESULT')) AND itemstate='LOCKED'\nAND id NOT IN (SELECT match FROM item_drafts);\n\"\"\"\n\n@task()\ndef create_item_drafts():\n with Cursor() as c:\n for match in c.execute(FIND_MATCH_DRAFT_QUERY).fetchall():\n if not match:\n continue\n log.info(\"Creating new item drafts for match #%s\", match.id)\n\n for team in match.teams:\n c.insert(\"item_drafts\", {\n \"match\": match.id,\n \"team\": team,\n \"state\": \"PENDING\"\n })\n\nFIND_ITEM_DRAFT_QUERY = \"SELECT id, match, team FROM item_drafts WHERE state='PENDING'\"\n\nFIND_AND_LOCK_ITEM_DRAFT = \"\"\"\nUPDATE item_drafts z\nSET state='STARTED', started_at=now()\nFROM (SELECT id FROM item_drafts WHERE state='PENDING' ORDER BY id LIMIT 1) AS draft\nWHERE z.id=draft.id\nRETURNING z.id, z.match, z.team\n\"\"\"\n\n@task()\ndef run_item_drafts():\n with Cursor() as c:\n draft = c.execute(FIND_AND_LOCK_ITEM_DRAFT).fetchone()\n\n # If we don't have any we're done\n if not draft:\n return\n\n # Grab all won bets\n won_bets = c.execute(\"\"\"\n SELECT id, value FROM bets WHERE match=%s AND team=%s AND state='CONFIRMED'\"\"\",\n (draft.match, draft.team)).fetchall(as_list=True)\n\n # Grab all \"lost\" items\n lost_items = c.execute(\"\"\"\n SELECT i.id, i.price FROM\n (SELECT unnest(b.items) AS item_id FROM bets b WHERE b.match=%s AND b.team!=%s AND state='CONFIRMED') b\n JOIN items i ON id=item_id\"\"\", (draft.match, draft.team)).fetchall(as_list=True)\n\n # Calculate the total value placed on the match\n total_value = c.execute(\n \"SELECT sum(value) as v FROM bets WHERE match=%s AND state='CONFIRMED'\", (draft.match, )).fetchone().v or 0\n\n # Calculate value of winning team\n winner_value = c.execute(\n \"SELECT sum(value) as v FROM bets WHERE match=%s AND team=%s AND state='CONFIRMED'\",\n (draft.match, draft.team)).fetchone().v or 0\n\n if not total_value or not winner_value:\n log.error(\"[Draft #%s] Cannot complete!\", draft.id)\n c.execute(\"UPDATE item_drafts SET state='FAILED' WHERE id=%s\", (draft.id, ))\n return\n\n value_mod = ((int(total_value) * 1.0) / int(winner_value))\n log.debug(\"value: %s\", value_mod)\n\n # Calculate return value for winners\n draft_bets = map(lambda i: (i.id, value_mod * float(i.value)), won_bets)\n log.debug(\"bets: %s\", draft_bets)\n\n try:\n log.info(\"[Draft #%s] starting pre-draft\", draft.id)\n pre_draft(draft.id, draft_bets, lost_items)\n\n log.info(\"[Draft #%s] running full draft\", draft.id)\n run_draft(draft.id)\n c.execute(\"UPDATE item_drafts SET state='COMPLETED' WHERE id=%s\", (draft.id, ))\n except:\n log.exception(\"Item Draft %s Failed\", draft.id)\n c.execute(\"UPDATE item_drafts SET state='FAILED' WHERE id=%s\", (draft.id, ))\n\n", "repo_name": "b1naryth1ef/orpheus", "sub_path": "app/tasks/itemdraft.py", "file_name": "itemdraft.py", "file_ext": "py", "file_size_in_byte": 3429, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "logging.getLogger", "line_number": 11, "usage_type": "call"}, {"api_name": "database.Cursor", "line_number": 22, "usage_type": "call"}, {"api_name": "tasks.task", "line_number": 20, "usage_type": "call"}, {"api_name": "database.Cursor", "line_number": 47, "usage_type": "call"}, {"api_name": "util.itemdraft.pre_draft", "line_number": 88, "usage_type": "call"}, {"api_name": "util.itemdraft.run_draft", "line_number": 91, "usage_type": "call"}, {"api_name": "tasks.task", "line_number": 45, "usage_type": "call"}]} +{"seq_id": "30262040482", "text": "from collections import deque\nimport sys\ninput = sys.stdin.readline\n\n\nn, m, v = map(int, input().split())\n\n\ngraph = [[0] * (n+1) for _ in range(n+1)]\nfor _ in range(m):\n node_1, node_2 = map(int, input().split())\n graph[node_1][node_2] = graph[node_2][node_1] = 1\n\nvisited_dfs = [False] * (n+1)\nvisited_bfs = [False] * (n+1)\n\ndef dfs(graph, v, visited):\n visited[v] = True\n print(v, end=' ')\n for i in range(1, n+1):\n if not visited[i] and graph[v][i] == 1:\n dfs(graph, i, visited)\n\ndef bfs(graph, v, visited):\n queue = deque([v])\n visited[v] = True\n while queue:\n start = queue.popleft()\n print(start, end= ' ')\n for i in range(1, n+1):\n if not visited[i] and graph[start][i] == 1:\n queue.append(i)\n visited[i] = True\n\ndfs(graph, v, visited_dfs)\nprint()\nbfs(graph, v, visited_bfs)", "repo_name": "Designated-Hitter/Week02---Algorithm", "sub_path": "21_Q1260/Q1260_JHC.py", "file_name": "Q1260_JHC.py", "file_ext": "py", "file_size_in_byte": 885, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "sys.stdin", "line_number": 3, "usage_type": "attribute"}, {"api_name": "collections.deque", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "26923847147", "text": "import pytest\nimport torch\n\nfrom approve.models import APPr, HeteroAPPr\n\n\ndef test_APPr():\n x = torch.tensor([[0.5], [0.5]])\n edge_index = torch.tensor([[0], [1]])\n\n model = APPr(K=30, alpha=0.5)\n assert str(model) == \"APPr(K=30, alpha=0.5)\"\n\n def check_returned():\n returned = model(x, edge_index)\n assert torch.allclose(returned, torch.tensor([[1 / 3], [2 / 3]]))\n\n check_returned()\n assert model._norm is not None\n check_returned()\n\n model.reset_parameters()\n assert model._norm is None\n\n\n@pytest.mark.parametrize(\n \"kwargs\",\n [\n dict(),\n dict(alpha_exp_dict={\"paper\": 0, \"venue\": 0}),\n dict(\n beta_exp_dict={\n (\"paper\", \"cites\", \"paper\"): 0,\n (\"venue\", \"publishes\", \"paper\"): 0,\n (\"paper\", \"rev_publishes\", \"venue\"): 0,\n }\n ),\n ],\n)\ndef test_HeteroAPPr(ex_hetero_data, kwargs):\n x_dict = {}\n for node_type, num_nodes in ex_hetero_data.num_nodes_dict.items():\n x_dict[node_type] = torch.ones((num_nodes, 1)) / num_nodes\n edge_index_dict = ex_hetero_data.edge_index_dict\n\n model = HeteroAPPr(K=30)\n assert str(model) == \"HeteroAPPr(K=30)\"\n\n def check_returned():\n returned = model(x_dict, edge_index_dict, **kwargs)\n assert torch.allclose(\n returned[\"paper\"],\n torch.tensor([[0.4511278272], [0.3383458555], [0.2105263323]]),\n )\n assert torch.allclose(\n returned[\"venue\"], torch.tensor([[0.8947368264], [0.1052631661]])\n )\n\n check_returned()\n assert model._norm is not None\n assert model._alpha_dict is not None\n assert model._beta_dict is not None\n check_returned()\n\n model.reset_parameters()\n assert model._norm is None\n assert model._alpha_dict is None\n assert model._beta_dict is None\n", "repo_name": "mrmrob003/approve", "sub_path": "tests/test_models.py", "file_name": "test_models.py", "file_ext": "py", "file_size_in_byte": 1858, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "torch.tensor", "line_number": 8, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 9, "usage_type": "call"}, {"api_name": "approve.models.APPr", "line_number": 11, "usage_type": "call"}, {"api_name": "torch.allclose", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 43, "usage_type": "call"}, {"api_name": "approve.models.HeteroAPPr", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.allclose", "line_number": 51, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.allclose", "line_number": 55, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 56, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 26, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 26, "usage_type": "attribute"}]} +{"seq_id": "14683085542", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport filecmp\nimport os\nimport sys\nimport argparse\nfrom collections import defaultdict\n\n\nclass TreeCmp:\n\n def __init__(self, dir1, dir2, shallow=True):\n\n if not os.path.isdir(dir1):\n raise NotADirectoryError(dir1)\n\n if not os.path.isdir(dir2):\n raise NotADirectoryError(dir2)\n\n self.left = dir1\n self.right = dir2\n self.shallow = shallow\n self.same_files = defaultdict(list)\n self.diff_files = defaultdict(list)\n self.funny_files = defaultdict(list)\n self.left_only = defaultdict(list)\n self.right_only = defaultdict(list)\n\n self.__cmp(self.left, self.right, shallow)\n\n def __cmp(self, dir1, dir2, shallow):\n dircmp = filecmp.dircmp(dir1, dir2)\n self.__recursive_cmp(dircmp, shallow)\n\n def __recursive_cmp(self, dircmp, shallow):\n\n dirs = (dircmp.left, dircmp.right)\n\n # 両方に存在するファイル\n match, mismatch, errors = filecmp.cmpfiles(dircmp.left, dircmp.right, dircmp.common_files, shallow)\n self.same_files[dirs].extend(match)\n self.diff_files[dirs].extend(mismatch)\n self.funny_files[dirs].extend(errors)\n\n # 左側のみに存在するファイル・ディレクトリ\n # ディレクトリの場合は再帰的にたどってファイルを追加\n for name in dircmp.left_only:\n path = os.path.join(dircmp.left, name)\n if os.path.isdir(path):\n for dirpath, dirnames, filenames in os.walk(path):\n self.left_only[(dirpath, \"\")].extend(filenames)\n else:\n self.left_only[dirs].append(name)\n\n # 右側のみに存在するファイル・ディレクトリ\n # ディレクトリの場合は再帰的にたどってファイルを追加\n for name in dircmp.right_only:\n path = os.path.join(dircmp.right, name)\n if os.path.isdir(path):\n for dirpath, dirnames, filenames in os.walk(path):\n self.right_only[(\"\", dirpath)].extend(filenames)\n else:\n self.right_only[dirs].append(name)\n\n # 両方に存在するディレクトリ\n for subdir in dircmp.subdirs.values():\n self.__recursive_cmp(subdir, shallow)\n\n\ndef _parse_args():\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"dir1\", type=str, help=\"left directory\")\n parser.add_argument(\"dir2\", type=str, help=\"right directory\")\n parser.add_argument(\"-f\", \"--full\", action=\"store_false\", dest=\"shallow\", help=\"compare contents of files\")\n parser.add_argument(\"-s\", \"--separator\", type=str, default=\"\\t\", help=\"specify field separator (default=\\\"\\\\t\\\")\")\n\n return parser.parse_args()\n\n\ndef _print_files(label, dict, sep=\"\\t\"):\n for dirs, files in dict.items():\n for filename in files:\n print(sep.join([label, filename, dirs[0], dirs[1]]))\n\n\ndef main():\n\n args = _parse_args()\n\n dir1 = args.dir1\n dir2 = args.dir2\n shallow = args.shallow\n sep = args.separator\n\n if not os.path.isdir(dir1):\n print(\"error: not a directory: {}\".format(dir1), file=sys.stderr)\n exit()\n\n if not os.path.isdir(dir2):\n print(\"error: not a directory: {}\".format(dir2), file=sys.stderr)\n exit()\n\n treecmp = TreeCmp(dir1, dir2, shallow)\n\n _print_files(\"same\", treecmp.same_files, sep)\n _print_files(\"diff\", treecmp.diff_files, sep)\n _print_files(\"funny\", treecmp.funny_files, sep)\n _print_files(\"left only\", treecmp.left_only, sep)\n _print_files(\"right only\", treecmp.right_only, sep)\n\n\nif __name__ == \"__main__\":\n main()\n", "repo_name": "amano41/dircmp", "sub_path": "treecmp.py", "file_name": "treecmp.py", "file_ext": "py", "file_size_in_byte": 3717, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "os.path.isdir", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path", "line_number": 18, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 24, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 25, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 26, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 27, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 28, "usage_type": "call"}, {"api_name": "filecmp.dircmp", "line_number": 33, "usage_type": "call"}, {"api_name": "filecmp.cmpfiles", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path", "line_number": 49, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "os.walk", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path", "line_number": 59, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path", "line_number": 60, "usage_type": "attribute"}, {"api_name": "os.walk", "line_number": 61, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 98, "usage_type": "call"}, {"api_name": "os.path", "line_number": 98, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 99, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 102, "usage_type": "call"}, {"api_name": "os.path", "line_number": 102, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 103, "usage_type": "attribute"}]} +{"seq_id": "41485562455", "text": "import csv\n\nimport requests\nimport json\nimport time\n# from nltk.sentiment.vader import SentimentIntensityAnalyzer as SIA\n\n# Set your header according to the form below\n# :: (by /u/)\n\n# Add your username below\nhdr = {'User-Agent': 'brendanb22'}\nurl = 'https://www.reddit.com/r/ethereum/.json'\nreq = requests.get(url, headers=hdr)\ncsvFile = open('reddit4.csv', 'a')\n#Use csv Writer\ncsvWriter = csv.writer(csvFile)\njson_data = json.loads(req.text)\ndata_all = json_data['data']['children']\n\nnum_of_posts = 0\nfor x in data_all:\n csvWriter.writerow([time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(x['data']['created'])), x['data']['title']])\n num_of_posts +=1\n\nwhile len(data_all) <= 5000:\n time.sleep(2)\n last = data_all[-1]['data']['name']\n url = 'https://www.reddit.com/r/ethereum/.json?after=' + str(last)\n req = requests.get(url, headers=hdr)\n data = json.loads(req.text)\n data_all += data['data']['children']\n for x in data['data']['children']:\n csvWriter.writerow([time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(x['data']['created'])), x['data']['title']])\n", "repo_name": "brendanbernstein/crawlers", "sub_path": "redditCrawler.py", "file_name": "redditCrawler.py", "file_ext": "py", "file_size_in_byte": 1098, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "requests.get", "line_number": 14, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 17, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 18, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 23, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 23, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 27, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 30, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 31, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 34, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 34, "usage_type": "call"}]} +{"seq_id": "41945646434", "text": "import logging\n\nfrom django.http import HttpResponse, StreamingHttpResponse\nfrom django.views.generic import TemplateView\nfrom django.contrib import messages\nfrom django.shortcuts import get_object_or_404\n\nfrom core.utils import download\nfrom gestion.models import Reclamation\n\nfrom gestion.forms import ReclamationForm\n\n\nclass CreateReclamationView(TemplateView):\n template_name = 'gestion/reclamation-nouveau.html'\n form_class = ReclamationForm\n\n def get_context_data(self, form=None, *args, **kwargs):\n context = super(CreateReclamationView, self).get_context_data(**kwargs)\n context['form'] = form if form else self.form_class()\n return context\n\n def post(self, request, **kwargs):\n context = self.get_context_data(**kwargs)\n form = self.form_class(request.POST, request.FILES)\n\n if not form.is_valid():\n context['form'] = form\n return self.render_to_response(context, status=400)\n try:\n reclamation = form.save()\n except Exception as e:\n _msg = 'Une erreur (%s) est survenue lors de la création de la réclamation : %s' % (type(e).__name__, e)\n messages.add_message(request, messages.ERROR,\n message=\"Une erreur est survenue lors de la création de la réclamation\")\n else:\n _msg = 'Réclamation %s (%s) créee avec succès' % (reclamation.objet, reclamation.statut)\n messages.add_message(request, messages.INFO, message=\"Réclamation créee avec succès\")\n return self.render_to_response(context, status=201)\n\n\nclass EditReclamationView(TemplateView):\n template_name = 'gestion/reclamation-modification.html'\n form_class = ReclamationForm\n\n def get_context_data(self, form=None, *args, **kwargs):\n context = super(EditReclamationView, self).get_context_data(**kwargs)\n reclamation = get_object_or_404(Reclamation, pk=kwargs.get('pk'))\n context['form'] = form if form else self.form_class(instance=reclamation)\n return context\n\n def post(self, request, **kwargs):\n reclamation = get_object_or_404(Reclamation, pk=kwargs.get('pk'))\n form = self.form_class(request.POST, instance=reclamation)\n if not form.is_valid():\n context = self.get_context_data(form=form, **kwargs)\n return self.render_to_response(context, status=400)\n # edite la réclamation\n try:\n reclamation = form.save()\n except Exception as e:\n _msg = 'Une erreur (%s) est survenue lors de la modification de la réclamation %s: %s' % (\n type(e).__name__, self.request.POST['label'], e)\n messages.add_message(request, messages.ERROR, message=_msg)\n context = self.get_context_data(form=form, **kwargs)\n return self.render_to_response(context, status=500)\n else:\n _msg = 'Réclamation de %s %s modifié avec succès' % (reclamation.objects, reclamation.statut)\n messages.add_message(request, messages.INFO, message=_msg)\n context = self.get_context_data(**kwargs)\n return self.render_to_response(context, status=200)\n\n\ndef download_reclamation(request, pk):\n reclamation = Reclamation.objects.filter(pk=pk)[0]\n filename = reclamation.fiche_pdf\n name = str(filename).split('/')[-1]\n\n response = download(request, pk, filename, name)\n return response\n\n\nclass ListReclamationView(TemplateView):\n template_name = 'gestion/reclamation-gestion.html'\n\n def get_context_data(self, *args, **kwargs):\n context = super(ListReclamationView, self).get_context_data(**kwargs)\n context['reclamations'] = Reclamation.objects.all()\n\n return context\n", "repo_name": "hugoVatos/testesgi", "sub_path": "gestion/views/reclamation.py", "file_name": "reclamation.py", "file_ext": "py", "file_size_in_byte": 3748, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "django.views.generic.TemplateView", "line_number": 14, "usage_type": "name"}, {"api_name": "gestion.forms.ReclamationForm", "line_number": 16, "usage_type": "name"}, {"api_name": "django.contrib.messages.add_message", "line_number": 34, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 34, "usage_type": "name"}, {"api_name": "django.contrib.messages.ERROR", "line_number": 34, "usage_type": "attribute"}, {"api_name": "django.contrib.messages.add_message", "line_number": 38, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 38, "usage_type": "name"}, {"api_name": "django.contrib.messages.INFO", "line_number": 38, "usage_type": "attribute"}, {"api_name": "django.views.generic.TemplateView", "line_number": 42, "usage_type": "name"}, {"api_name": "gestion.forms.ReclamationForm", "line_number": 44, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 48, "usage_type": "call"}, {"api_name": "gestion.models.Reclamation", "line_number": 48, "usage_type": "argument"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 53, "usage_type": "call"}, {"api_name": "gestion.models.Reclamation", "line_number": 53, "usage_type": "argument"}, {"api_name": "django.contrib.messages.add_message", "line_number": 64, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 64, "usage_type": "name"}, {"api_name": "django.contrib.messages.ERROR", "line_number": 64, "usage_type": "attribute"}, {"api_name": "django.contrib.messages.add_message", "line_number": 69, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 69, "usage_type": "name"}, {"api_name": "django.contrib.messages.INFO", "line_number": 69, "usage_type": "attribute"}, {"api_name": "gestion.models.Reclamation.objects.filter", "line_number": 75, "usage_type": "call"}, {"api_name": "gestion.models.Reclamation.objects", "line_number": 75, "usage_type": "attribute"}, {"api_name": "gestion.models.Reclamation", "line_number": 75, "usage_type": "name"}, {"api_name": "core.utils.download", "line_number": 79, "usage_type": "call"}, {"api_name": "django.views.generic.TemplateView", "line_number": 83, "usage_type": "name"}, {"api_name": "gestion.models.Reclamation.objects.all", "line_number": 88, "usage_type": "call"}, {"api_name": "gestion.models.Reclamation.objects", "line_number": 88, "usage_type": "attribute"}, {"api_name": "gestion.models.Reclamation", "line_number": 88, "usage_type": "name"}]} +{"seq_id": "4961253467", "text": "from typing import List\nimport hashlib\nimport hmac\n\n\ndef give_md5(messages: List) -> str:\n # fonction de hachage\n m = hashlib.md5()\n for message in messages:\n bytes_message = format_str_to_b(message)\n m.update(bytes_message)\n return m.hexdigest(), m.digest_size, m.name\n\ndef give_sha224(messages):\n # fonction de hachage\n s = hashlib.sha224()\n for message in messages:\n bytes_message = format_str_to_b(message)\n s.update(bytes_message)\n return s.hexdigest(), s.digest_size, s.name\n\n\ndef give_hmac(messages: List, secret_key: str) -> str:\n # clé secrète\n bytes_secret_key = format_str_to_b(secret_key)\n # fonction de hachage\n h = hmac.new(bytes_secret_key, digestmod=hashlib.sha1)\n for message in messages:\n bytes_message = format_str_to_b(message)\n h.update(bytes_message)\n return h.hexdigest(), h.digest_size, h.name\n\n\ndef format_str_to_b(string_to_b: str):\n binary_converted = string_to_b.encode('UTF-8')\n return binary_converted\n\n\ndef powm(b: int, e: int, m: int) -> int:\n \"\"\"\n Retourne b^e(mod m)\n\n Nous verrons qu’en cryptographie asymétrique, en particulier avec\n l’algorithme RSA, on a souvent besoin de calculer b^e (mod m)\n explicitement où b, e, m sont de “grands” entiers naturels. Ce calcul\n s’appelle exponentiation modulaire. b est appelé la base, e l’exposant\n et m le module.\n Par exemple, considérons le calcul de 341^943 (mod 1403). La méthode\n naïve consisterait à élever 341 à la puissance 943 puis effectuer la division\n euclidienne du résultat par 1403, le reste de cette division étant le nombre\n cherché.\n Une première difficulté est d’avoir à effectuer 942 multiplications (en\n pratique, les nombres sont beaucoup plus grands) suivies d’une division\n euclidienne.\n Mais la difficulté principale (rédhibitoire en pratique) est, qu’avec cette\n méthode, on est conduit à manipuler des nombres de plus en plus grands.\n\n Fort heureusement, il existe un algorithme efficace, appelé exponentiation\n par carrés (ou exponentiation rapide) qui combine deux opérations\n élémentaires : l’élévation au carré et la multiplication par la base b.\n\n :param b:\n :param e:\n :param m:\n :return:\n \"\"\"\n\n result = 1\n while e > 0:\n if e & 1 > 0: # e est impair\n result = (result * b) % m # on multiplie par la base b\n yield result\n\n e >>= 1 # on divise e par 2 (en décalage de bit vers la droite)\n b = (b * b) % m # on élève la base b au carré\n return result\n\n\nif __name__ == '__main__':\n messages_to_hash = ['Hello', 'you !', 'I love you.']\n print(f\"Md5 : {give_md5(messages_to_hash)}\")\n print(f\"Sha224 : {give_sha224(messages_to_hash)}\")\n secret_key = 'loulou'\n print(f\"HMAC : {give_hmac(messages_to_hash, secret_key)}\")\n print(list(powm(10, 2, 2)))\n\n\n", "repo_name": "BossaMuffin/Function_CryptoHash", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2949, "program_lang": "python", "lang": "fr", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "typing.List", "line_number": 6, "usage_type": "name"}, {"api_name": "hashlib.md5", "line_number": 8, "usage_type": "call"}, {"api_name": "hashlib.sha224", "line_number": 16, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 23, "usage_type": "name"}, {"api_name": "hmac.new", "line_number": 27, "usage_type": "call"}, {"api_name": "hashlib.sha1", "line_number": 27, "usage_type": "attribute"}]} +{"seq_id": "4517131778", "text": "from flask import Flask, render_template\r\nimport requests\r\nimport json\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route(\"/\")\r\ndef get_liturgy():\r\n url = \"https://liturgia.up.railway.app/\"\r\n\r\n response = requests.get(url)\r\n data = json.loads(response.text)\r\n\r\n titulos = [\r\n \"data\",\r\n \"liturgia\",\r\n \"cor\",\r\n \"dia\",\r\n \"oferendas\",\r\n \"comunhao\",\r\n \"primeiraLeitura\",\r\n \"segundaLeitura\",\r\n \"salmo\",\r\n \"evangelho\"\r\n ]\r\n\r\n correspondentes = []\r\n\r\n for titulo in titulos:\r\n correspondente = data.get(titulo, \"\")\r\n if isinstance(correspondente, dict):\r\n correspondente = tratamento_dados(correspondente, titulo)\r\n correspondentes.append((format_title(titulo), correspondente))\r\n\r\n return render_template('index.html', titulos_correspondentes=correspondentes)\r\n\r\ndef tratamento_dados(dados, titulo):\r\n correspondente = \"\"\r\n if \"referencia\" in dados:\r\n correspondente += dados[\"referencia\"]\r\n if \"titulo\" in dados:\r\n correspondente += \" - \" + dados[\"titulo\"]\r\n if \"texto\" in dados:\r\n correspondente += \"

    \" + dados[\"texto\"].replace(\"\\n\", \"
    \")\r\n if titulo == \"primeiraLeitura\":\r\n correspondente += \"

    - Palavra do Senhor.
    - Graças a Deus.\"\r\n elif titulo == \"evangelho\":\r\n correspondente += \"
    — Palavra da Salvação.
    — Glória a vós, Senhor.\"\r\n return correspondente.replace(\"\\n\", \"
    \")\r\n\r\ndef format_title(string):\r\n formatted = string[0].upper()\r\n for i in range(1, len(string)):\r\n if string[i].isupper():\r\n formatted += \" \" + string[i]\r\n else:\r\n formatted += string[i]\r\n return formatted\r\n\r\nif __name__ == \"__main__\":\r\n app.run()\r\n", "repo_name": "devbittencourt/site_jjp", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1775, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "flask.Flask", "line_number": 5, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 11, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 12, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 35, "usage_type": "call"}]} +{"seq_id": "34353016695", "text": "from datetime import datetime\nfrom datetime import date\nfrom pprint import pformat\nfrom six import iteritems\nimport re\nimport json\n\nfrom ..utils import sanitize_for_serialization\n\n# type hinting support\nfrom typing import TYPE_CHECKING\nfrom typing import List\nfrom typing import Dict\n\nif TYPE_CHECKING:\n from . import Referrer\n\nclass AppEventResponseSession(object):\n \"\"\"\n NOTE: This class is auto generated by the swagger code generator program.\n Do not edit the class manually.\n \"\"\"\n def __init__(self) -> None:\n \"\"\"\n AppEventResponseSession - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n and the value is json key in definition.\n \"\"\"\n self.swagger_types = {\n 'id': 'str',\n 'duration_in_seconds': 'int',\n 'event_count': 'int',\n 'screenview_count': 'int',\n 'referrer': 'Referrer',\n 'self_uri': 'str',\n 'created_date': 'datetime'\n }\n\n self.attribute_map = {\n 'id': 'id',\n 'duration_in_seconds': 'durationInSeconds',\n 'event_count': 'eventCount',\n 'screenview_count': 'screenviewCount',\n 'referrer': 'referrer',\n 'self_uri': 'selfUri',\n 'created_date': 'createdDate'\n }\n\n self._id = None\n self._duration_in_seconds = None\n self._event_count = None\n self._screenview_count = None\n self._referrer = None\n self._self_uri = None\n self._created_date = None\n\n @property\n def id(self) -> str:\n \"\"\"\n Gets the id of this AppEventResponseSession.\n The globally unique identifier for the object.\n\n :return: The id of this AppEventResponseSession.\n :rtype: str\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id: str) -> None:\n \"\"\"\n Sets the id of this AppEventResponseSession.\n The globally unique identifier for the object.\n\n :param id: The id of this AppEventResponseSession.\n :type: str\n \"\"\"\n \n\n self._id = id\n\n @property\n def duration_in_seconds(self) -> int:\n \"\"\"\n Gets the duration_in_seconds of this AppEventResponseSession.\n Indicates how long the customer has been in the app within this session.\n\n :return: The duration_in_seconds of this AppEventResponseSession.\n :rtype: int\n \"\"\"\n return self._duration_in_seconds\n\n @duration_in_seconds.setter\n def duration_in_seconds(self, duration_in_seconds: int) -> None:\n \"\"\"\n Sets the duration_in_seconds of this AppEventResponseSession.\n Indicates how long the customer has been in the app within this session.\n\n :param duration_in_seconds: The duration_in_seconds of this AppEventResponseSession.\n :type: int\n \"\"\"\n \n\n self._duration_in_seconds = duration_in_seconds\n\n @property\n def event_count(self) -> int:\n \"\"\"\n Gets the event_count of this AppEventResponseSession.\n The count of all events recorded during this session.\n\n :return: The event_count of this AppEventResponseSession.\n :rtype: int\n \"\"\"\n return self._event_count\n\n @event_count.setter\n def event_count(self, event_count: int) -> None:\n \"\"\"\n Sets the event_count of this AppEventResponseSession.\n The count of all events recorded during this session.\n\n :param event_count: The event_count of this AppEventResponseSession.\n :type: int\n \"\"\"\n \n\n self._event_count = event_count\n\n @property\n def screenview_count(self) -> int:\n \"\"\"\n Gets the screenview_count of this AppEventResponseSession.\n The count of all screen views recorded during this session.\n\n :return: The screenview_count of this AppEventResponseSession.\n :rtype: int\n \"\"\"\n return self._screenview_count\n\n @screenview_count.setter\n def screenview_count(self, screenview_count: int) -> None:\n \"\"\"\n Sets the screenview_count of this AppEventResponseSession.\n The count of all screen views recorded during this session.\n\n :param screenview_count: The screenview_count of this AppEventResponseSession.\n :type: int\n \"\"\"\n \n\n self._screenview_count = screenview_count\n\n @property\n def referrer(self) -> 'Referrer':\n \"\"\"\n Gets the referrer of this AppEventResponseSession.\n The referrer of the first event in the app session.\n\n :return: The referrer of this AppEventResponseSession.\n :rtype: Referrer\n \"\"\"\n return self._referrer\n\n @referrer.setter\n def referrer(self, referrer: 'Referrer') -> None:\n \"\"\"\n Sets the referrer of this AppEventResponseSession.\n The referrer of the first event in the app session.\n\n :param referrer: The referrer of this AppEventResponseSession.\n :type: Referrer\n \"\"\"\n \n\n self._referrer = referrer\n\n @property\n def self_uri(self) -> str:\n \"\"\"\n Gets the self_uri of this AppEventResponseSession.\n The URI for this object\n\n :return: The self_uri of this AppEventResponseSession.\n :rtype: str\n \"\"\"\n return self._self_uri\n\n @self_uri.setter\n def self_uri(self, self_uri: str) -> None:\n \"\"\"\n Sets the self_uri of this AppEventResponseSession.\n The URI for this object\n\n :param self_uri: The self_uri of this AppEventResponseSession.\n :type: str\n \"\"\"\n \n\n self._self_uri = self_uri\n\n @property\n def created_date(self) -> datetime:\n \"\"\"\n Gets the created_date of this AppEventResponseSession.\n Date of the session's first event, that is when the session starts. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z\n\n :return: The created_date of this AppEventResponseSession.\n :rtype: datetime\n \"\"\"\n return self._created_date\n\n @created_date.setter\n def created_date(self, created_date: datetime) -> None:\n \"\"\"\n Sets the created_date of this AppEventResponseSession.\n Date of the session's first event, that is when the session starts. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z\n\n :param created_date: The created_date of this AppEventResponseSession.\n :type: datetime\n \"\"\"\n \n\n self._created_date = created_date\n\n def to_dict(self):\n \"\"\"\n Returns the model properties as a dict\n \"\"\"\n result = {}\n\n for attr, _ in iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_json(self):\n \"\"\"\n Returns the model as raw JSON\n \"\"\"\n return json.dumps(sanitize_for_serialization(self.to_dict()))\n\n def to_str(self):\n \"\"\"\n Returns the string representation of the model\n \"\"\"\n return pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"\n For `print` and `pprint`\n \"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"\n Returns true if both objects are equal\n \"\"\"\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"\n Returns true if both objects are not equal\n \"\"\"\n return not self == other\n\n", "repo_name": "MyPureCloud/platform-client-sdk-python", "sub_path": "build/PureCloudPlatformClientV2/models/app_event_response_session.py", "file_name": "app_event_response_session.py", "file_ext": "py", "file_size_in_byte": 8298, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 16, "dataset": "github-code", "pt": "20", "api": [{"api_name": "typing.TYPE_CHECKING", "line_number": 15, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 205, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 216, "usage_type": "name"}, {"api_name": "six.iteritems", "line_number": 234, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 258, "usage_type": "call"}, {"api_name": "utils.sanitize_for_serialization", "line_number": 258, "usage_type": "call"}, {"api_name": "pprint.pformat", "line_number": 264, "usage_type": "call"}]} +{"seq_id": "24202769662", "text": "import argparse, sys, socket\r\nimport json\r\n#import _thread\r\nfrom server import *\r\nfrom client import *\r\nfrom account import *\r\nfrom shared import *\r\nimport threading\r\nimport select\r\n\r\ndef InitializeServer():\r\n\r\n # Dummy account details for the purpose of demo\r\n uid1 = 0\r\n uid2 = 1\r\n account_id = 0\r\n name1 = \"Raj\"\r\n name2 = \"Kumar\"\r\n email1 = \"raj@gmail.com\"\r\n email2 = \"kumar@gmail.com\"\r\n img_hash1 = \"ff81a1818589bd00\"\r\n img_hash2 = \"ff8191818181bd00\"\r\n\r\n user1 = User(uid1, account_id, name1, email1, img_hash1)\r\n user2 = User(uid2, account_id, name2, email2, img_hash2)\r\n\r\n users = []\r\n users.append(user1)\r\n users.append(user2)\r\n\r\n balance = 10000\r\n account = SharedAccount(account_id, balance, users)\r\n\r\n accounts = []\r\n accounts.append(account)\r\n\r\n server_obj = Server(accounts)\r\n\r\n return server_obj\r\n\r\ndef run_server():\r\n # Create a server object\r\n server = InitializeServer()\r\n\r\n # Create the socket\r\n print(\"Starting Server....\")\r\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n s.bind(('', 4000))\r\n s.listen(5)\r\n\r\n while True:\r\n # s.accept() is blocking\r\n conn, addr = s.accept()\r\n\r\n # Prints the IP and port of client when connected\r\n print('Connected to :', addr[0], ':', addr[1])\r\n\r\n # Start new thread for handling the client\r\n T = threading.Thread(target=handle_client, args=(conn,server,))\r\n T.start()\r\n\r\n # Close the socket when loop exits\r\n s.close()\r\n\r\n\r\ndef run_client(clientid: int, accountid: int):\r\n print(\"Starting Client....\")\r\n\r\n # Create the socket\r\n s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n\r\n # Connect to the server\r\n s.connect(('', 4000))\r\n\r\n client = Client(s, accountid, clientid)\r\n\r\n # Send the ID of the user and their account\r\n packet = {\r\n \"account_id\": accountid,\r\n \"client_id\": clientid\r\n }\r\n\r\n send_data(packet, s)\r\n\r\n while True:\r\n print(\"Enter a choice:\\n\")\r\n print(\"1. Credit Amount\\n\")\r\n print(\"2. Debit Amount\\n\")\r\n print(\"3. View Balance\\n\")\r\n print(\"4. Exit\\n\")\r\n\r\n # The select statement is used to select between the data being read from the socket and stdin\r\n read_list, write_list, excep_list = select.select([s, sys.stdin], [], [])\r\n\r\n flag = False\r\n\r\n # Check the data that has been read\r\n for inp in read_list:\r\n if inp == s: # If input data is from the socket\r\n request = receive_data(s)\r\n flag = True\r\n print(\"Request received from server: \", request['type'])\r\n if request['type'] == 'balance_response':\r\n if request['status'] == 'Authentication successful':\r\n print(\"Available Balance: \", request['balance'])\r\n else:\r\n print(\"Request Denied\")\r\n\r\n elif request['type'] == 'debit_response':\r\n if request['status'] == 'Successful':\r\n print(\"Available Balance after Debit: \", request['balance'])\r\n else:\r\n print(\"Request Denied\")\r\n break\r\n elif inp == sys.stdin: # If input data is from the stdin of client\r\n user_input = sys.stdin.readline()\r\n print(\"user_input:\", user_input)\r\n\r\n # Requests from the server are prioritized over user requests\r\n if flag == True:\r\n client.handle_client_request(request)\r\n continue\r\n\r\n # If there are no requests from the server, the user requests are executed\r\n if user_input == \"1\\n\":\r\n client.initiate_request(\"credit\")\r\n if user_input == \"2\\n\":\r\n client.initiate_request(\"debit\")\r\n if user_input == \"3\\n\":\r\n client.initiate_request(\"view_request\")\r\n if user_input == \"4\\n\":\r\n sys.exit()\r\n\r\n\r\n\r\ndef main():\r\n # Let the user choose from the two procedures: server and client\r\n # This choice is done through the command line arguments\r\n\r\n help_description = \"Welcome to the Shared Bank Account Management System\"\r\n\r\n # Initialize parser\r\n parser = argparse.ArgumentParser(description=help_description)\r\n\r\n # Adding optional arguments\r\n parser.add_argument(\"-m\", \"--mode\", help = \"Select between the server and the client mode\")\r\n parser.add_argument(\"-c\", \"--clientid\", type=int, help = \"Enter the client ID\")\r\n parser.add_argument(\"-a\", \"--accountid\", type=int, help = \"Enter the account ID\")\r\n\r\n # Read Arguments\r\n args = parser.parse_args()\r\n\r\n # If server process\r\n if args.mode == \"server\" or args.mode == \"s\" or args.mode == \"Server\" or args.mode == \"S\":\r\n run_server()\r\n elif args.mode == \"client\" or args.mode == \"c\" or args.mode == \"Client\" or args.mode == \"C\":\r\n if args.clientid >= 0 and args.accountid >= 0:\r\n run_client(args.clientid, args.accountid)\r\n else:\r\n print(\"Client ID or Account ID not specified or invalid\")\r\n\r\nif __name__==\"__main__\": \r\n main()", "repo_name": "suhasks123/visual-cryptography", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 5213, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "socket.socket", "line_number": 47, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 47, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 47, "usage_type": "attribute"}, {"api_name": "socket.SOL_SOCKET", "line_number": 48, "usage_type": "attribute"}, {"api_name": "socket.SO_REUSEADDR", "line_number": 48, "usage_type": "attribute"}, {"api_name": "threading.Thread", "line_number": 60, "usage_type": "call"}, {"api_name": "socket.socket", "line_number": 71, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 71, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 71, "usage_type": "attribute"}, {"api_name": "select.select", "line_number": 94, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 94, "usage_type": "attribute"}, {"api_name": "sys.stdin", "line_number": 116, "usage_type": "attribute"}, {"api_name": "sys.stdin.readline", "line_number": 117, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 117, "usage_type": "attribute"}, {"api_name": "client.handle_client_request", "line_number": 122, "usage_type": "call"}, {"api_name": "client.initiate_request", "line_number": 127, "usage_type": "call"}, {"api_name": "client.initiate_request", "line_number": 129, "usage_type": "call"}, {"api_name": "client.initiate_request", "line_number": 131, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 133, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 144, "usage_type": "call"}]} +{"seq_id": "21856785609", "text": "# coding: utf-8\n\nimport six\n\nfrom huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization\n\n\nclass SendVerificationCodeV2Req:\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n sensitive_list = []\n\n openapi_types = {\n 'receiver_type': 'int',\n 'timeout': 'int',\n 'email': 'str',\n 'lang': 'str'\n }\n\n attribute_map = {\n 'receiver_type': 'receiver_type',\n 'timeout': 'timeout',\n 'email': 'email',\n 'lang': 'lang'\n }\n\n def __init__(self, receiver_type=None, timeout=None, email=None, lang=None):\n \"\"\"SendVerificationCodeV2Req\n\n The model defined in huaweicloud sdk\n\n :param receiver_type: 发送验证码的类型: 2:发送邮件验证码\n :type receiver_type: int\n :param timeout: 发送验证码的超时时间。 如果不填的话,采用系统默认超时时间5分钟。 单位:分钟\n :type timeout: int\n :param email: 指定发送验证码的邮箱地址。\n :type email: str\n :param lang: 根据该参数的取值选择发送邮件验证码的语言。 zh-cn:中文en-us:英文\n :type lang: str\n \"\"\"\n \n \n\n self._receiver_type = None\n self._timeout = None\n self._email = None\n self._lang = None\n self.discriminator = None\n\n self.receiver_type = receiver_type\n if timeout is not None:\n self.timeout = timeout\n self.email = email\n if lang is not None:\n self.lang = lang\n\n @property\n def receiver_type(self):\n \"\"\"Gets the receiver_type of this SendVerificationCodeV2Req.\n\n 发送验证码的类型: 2:发送邮件验证码\n\n :return: The receiver_type of this SendVerificationCodeV2Req.\n :rtype: int\n \"\"\"\n return self._receiver_type\n\n @receiver_type.setter\n def receiver_type(self, receiver_type):\n \"\"\"Sets the receiver_type of this SendVerificationCodeV2Req.\n\n 发送验证码的类型: 2:发送邮件验证码\n\n :param receiver_type: The receiver_type of this SendVerificationCodeV2Req.\n :type receiver_type: int\n \"\"\"\n self._receiver_type = receiver_type\n\n @property\n def timeout(self):\n \"\"\"Gets the timeout of this SendVerificationCodeV2Req.\n\n 发送验证码的超时时间。 如果不填的话,采用系统默认超时时间5分钟。 单位:分钟\n\n :return: The timeout of this SendVerificationCodeV2Req.\n :rtype: int\n \"\"\"\n return self._timeout\n\n @timeout.setter\n def timeout(self, timeout):\n \"\"\"Sets the timeout of this SendVerificationCodeV2Req.\n\n 发送验证码的超时时间。 如果不填的话,采用系统默认超时时间5分钟。 单位:分钟\n\n :param timeout: The timeout of this SendVerificationCodeV2Req.\n :type timeout: int\n \"\"\"\n self._timeout = timeout\n\n @property\n def email(self):\n \"\"\"Gets the email of this SendVerificationCodeV2Req.\n\n 指定发送验证码的邮箱地址。\n\n :return: The email of this SendVerificationCodeV2Req.\n :rtype: str\n \"\"\"\n return self._email\n\n @email.setter\n def email(self, email):\n \"\"\"Sets the email of this SendVerificationCodeV2Req.\n\n 指定发送验证码的邮箱地址。\n\n :param email: The email of this SendVerificationCodeV2Req.\n :type email: str\n \"\"\"\n self._email = email\n\n @property\n def lang(self):\n \"\"\"Gets the lang of this SendVerificationCodeV2Req.\n\n 根据该参数的取值选择发送邮件验证码的语言。 zh-cn:中文en-us:英文\n\n :return: The lang of this SendVerificationCodeV2Req.\n :rtype: str\n \"\"\"\n return self._lang\n\n @lang.setter\n def lang(self, lang):\n \"\"\"Sets the lang of this SendVerificationCodeV2Req.\n\n 根据该参数的取值选择发送邮件验证码的语言。 zh-cn:中文en-us:英文\n\n :param lang: The lang of this SendVerificationCodeV2Req.\n :type lang: str\n \"\"\"\n self._lang = lang\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n if attr in self.sensitive_list:\n result[attr] = \"****\"\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n import simplejson as json\n if six.PY2:\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)\n\n def __repr__(self):\n \"\"\"For `print`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, SendVerificationCodeV2Req):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n", "repo_name": "huaweicloud/huaweicloud-sdk-python-v3", "sub_path": "huaweicloud-sdk-bssintl/huaweicloudsdkbssintl/v2/model/send_verification_code_v2_req.py", "file_name": "send_verification_code_v2_req.py", "file_ext": "py", "file_size_in_byte": 6061, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 104, "dataset": "github-code", "pt": "20", "api": [{"api_name": "six.iteritems", "line_number": 155, "usage_type": "call"}, {"api_name": "six.PY2", "line_number": 181, "usage_type": "attribute"}, {"api_name": "sys.setdefaultencoding", "line_number": 184, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 185, "usage_type": "call"}, {"api_name": "huaweicloudsdkcore.utils.http_utils.sanitize_for_serialization", "line_number": 185, "usage_type": "call"}]} +{"seq_id": "28023828675", "text": "from django.shortcuts import render, redirect\nfrom .forms import CollegeForm\nfrom .models import CollegeModel\n\n\ndef show(request):\n colleges = CollegeModel.objects.all()\n context = {'colleges':colleges}\n return render (request, 'college/show.html', context)\n\ndef add(request):\n form=CollegeForm()\n if request.method == 'POST':\n form=CollegeForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('show')\n else:\n form = CollegeForm()\n context={'form': form}\n return render (request, 'college/add.html', context)\n\ndef edit(request,pk):\n colleges = CollegeModel.objects.get(id=pk)\n form = CollegeForm(instance=colleges)\n if request.method == 'POST':\n form=CollegeForm(request.POST , instance=colleges)\n if form.is_valid():\n form.save()\n return redirect('show')\n # else:\n # form = CollegeForm()\n context={'form':form}\n return render (request, 'college/edit.html',context)\n\ndef delete(request,pk):\n colleges = CollegeModel.objects.get(id=pk)\n if request.method == 'POST':\n colleges.delete()\n return redirect('show')\n context={'college':colleges}\n return render (request, 'college/delete.html',context)", "repo_name": "adarshsachan-kiwi/demo", "sub_path": "college/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1280, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "models.CollegeModel.objects.all", "line_number": 7, "usage_type": "call"}, {"api_name": "models.CollegeModel.objects", "line_number": 7, "usage_type": "attribute"}, {"api_name": "models.CollegeModel", "line_number": 7, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 9, "usage_type": "call"}, {"api_name": "forms.CollegeForm", "line_number": 12, "usage_type": "call"}, {"api_name": "forms.CollegeForm", "line_number": 14, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 17, "usage_type": "call"}, {"api_name": "forms.CollegeForm", "line_number": 19, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 21, "usage_type": "call"}, {"api_name": "models.CollegeModel.objects.get", "line_number": 24, "usage_type": "call"}, {"api_name": "models.CollegeModel.objects", "line_number": 24, "usage_type": "attribute"}, {"api_name": "models.CollegeModel", "line_number": 24, "usage_type": "name"}, {"api_name": "forms.CollegeForm", "line_number": 25, "usage_type": "call"}, {"api_name": "forms.CollegeForm", "line_number": 27, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 30, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 34, "usage_type": "call"}, {"api_name": "models.CollegeModel.objects.get", "line_number": 37, "usage_type": "call"}, {"api_name": "models.CollegeModel.objects", "line_number": 37, "usage_type": "attribute"}, {"api_name": "models.CollegeModel", "line_number": 37, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 40, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 42, "usage_type": "call"}]} +{"seq_id": "9705584864", "text": "import cv2\nimport numpy as np\n\ndef getContours(img):\n contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)\n for cnt in contours:\n area = cv2.contourArea(cnt)\n #print(area)\n if area>500:\n cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)\n perimeter = cv2.arcLength(cnt,True)\n #print(perimeter)\n approx = cv2.approxPolyDP(cnt,0.02*perimeter,True)\n print(len(approx))\n objCorner = len(approx)\n x, y, w, h = cv2.boundingRect(approx)\n \n if objCorner ==3: objectType =\"Tri\"\n elif objCorner == 4:\n aspRatio = w/float(h)\n if aspRatio >0.98 and aspRatio <1.03: objectType= \"Square\"\n else:objectType=\"Rectangle\"\n elif objCorner>4: objectType= \"Circles\"\n else:objectType=\"None\"\n \n \n \n cv2.rectangle(imgContour,(x,y),(x+w,y+h),(0,255,0),1)\n cv2.putText(imgContour,objectType,(x+(w//2)-10,y+(h//2)-10),cv2.FONT_HERSHEY_COMPLEX,0.7,(0,0,0),2)\n\t\n\n\nimg = cv2.imread(\"images/shapes.png\")\nimgContour = img.copy()\nimgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\nimgBlur = cv2.GaussianBlur(imgGray,(7,7),1)\nimgCanny = cv2.Canny(imgBlur,150,150)\n\ngetContours(imgCanny)\n\ncv2.imshow(\"display\",imgCanny)\ncv2.imshow(\"display1\",imgContour)\ncv2.waitKey(0)", "repo_name": "muhammadabdullah329/opencv_tutorials", "sub_path": "edge_detection.py", "file_name": "edge_detection.py", "file_ext": "py", "file_size_in_byte": 1376, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "cv2.findContours", "line_number": 5, "usage_type": "call"}, {"api_name": "cv2.RETR_EXTERNAL", "line_number": 5, "usage_type": "attribute"}, {"api_name": "cv2.CHAIN_APPROX_NONE", "line_number": 5, "usage_type": "attribute"}, {"api_name": "cv2.contourArea", "line_number": 7, "usage_type": "call"}, {"api_name": "cv2.drawContours", "line_number": 10, "usage_type": "call"}, {"api_name": "cv2.arcLength", "line_number": 11, "usage_type": "call"}, {"api_name": "cv2.approxPolyDP", "line_number": 13, "usage_type": "call"}, {"api_name": "cv2.boundingRect", "line_number": 16, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 29, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_COMPLEX", "line_number": 29, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 35, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 35, "usage_type": "attribute"}, {"api_name": "cv2.GaussianBlur", "line_number": 36, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 37, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 41, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 42, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 43, "usage_type": "call"}]} +{"seq_id": "15689941867", "text": "from flask import Flask\nfrom flask_restful import Api, Resource\nimport ChessEngine\nfrom random import randint as rand\n\napp = Flask(__name__)\napi = Api(app)\n\ngames = {}\nindexFlip = {\n 0: 7,\n 1: 6,\n 2: 5,\n 3: 4,\n 4: 3,\n 5: 2,\n 6: 1,\n 7: 0\n}\n\nclass Board(Resource):\n def get(self, code = 0, userid = \"\", colour = \"white\"):\n if code in games:\n if userid in games[code][1]:\n game = games[code][0]\n else:\n return {\"board\": \"uuid not found\"}\n else:\n return {\"board\": \"code not found\"}\n if colour == \"white\":\n return {\"board\": games[code][0].board}\n else:\n board = []\n for i in reversed(games[code][0].board):\n board.append(list(reversed(i)))\n return {\"board\": board}\n\nclass Setup(Resource):\n def put(self, code = 0, userid = \"\"):\n if code == 0:\n code = rand(100000, 999999)\n while code in games:\n code = rand(100000, 999999)\n games[code] = [ChessEngine.GameState(), []]\n games[code][1].append(userid)\n return {\"code\": code}\n else:\n if code in games:\n if userid in games[code][1]:\n return {\"code\": code}\n elif len(games[code][1]) == 2:\n return {\"code\": -2}\n else:\n games[code][1].append(userid)\n return {\"code\": code}\n else:\n return {\"code\": -1}\n \nclass PreviousMove(Resource):\n def get(self, code = 0, userid = \"\", colour = \"white\"):\n if code in games:\n if userid in games[code][1]:\n game = games[code][0]\n else:\n return {\"error\": \"uuid not found\"}\n else:\n return {\"error\": \"code not found\"}\n prevMove = game.moveLog[-1]\n prevMoveInfo = [prevMove.startRow, prevMove.startCol, prevMove.endRow, prevMove.endCol]\n if colour == \"black\":\n for i in range(4):\n prevMoveInfo[i] = indexFlip[prevMoveInfo[i]]\n return {\"previousmove\": prevMoveInfo}\n \nclass MakeMove(Resource):\n def put(self, code=0, userid=\"\", colour=\"white\", startRow=0, startCol=0, endRow=0, endCol=0):\n if code in games:\n if userid in games[code][1]:\n game = games[code]\n else:\n return {\"error\": \"uuid not found\"}\n else:\n return {\"error\": \"code not found\"}\n if colour == \"black\":\n startRow = indexFlip[startRow]\n startCol = indexFlip[startCol]\n endRow = indexFlip[endRow]\n endCol = indexFlip[endCol]\n if len(game) == 2:\n game.append(game[0].getValidMoves())\n else:\n game[2] = game[0].getValidMoves()\n for move in game[2]:\n if move.startRow == startRow and move.startCol == startCol and move.endRow == endRow and move.endCol == endCol:\n game[0].makeMove(move)\n game[2] = []\n return {\"error\": \"none\"}\n return {\"error\": \"invalid move\"}\n\n\napi.add_resource(Board, \"/board///\")\napi.add_resource(Setup, \"/setup//\")\napi.add_resource(PreviousMove, \"/previousmove///\")\napi.add_resource(MakeMove, \"/makemove///////\")\n\nif __name__ == \"__main__\":\n app.run(debug=True)", "repo_name": "MaximumFire/A-Level", "sub_path": "Projects/Multiplayer Chess/server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 3613, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "flask.Flask", "line_number": 6, "usage_type": "call"}, {"api_name": "flask_restful.Api", "line_number": 7, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 21, "usage_type": "name"}, {"api_name": "flask_restful.Resource", "line_number": 38, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 41, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 43, "usage_type": "call"}, {"api_name": "ChessEngine.GameState", "line_number": 44, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 59, "usage_type": "name"}, {"api_name": "flask_restful.Resource", "line_number": 75, "usage_type": "name"}]} +{"seq_id": "73017083888", "text": "import datetime\nimport typing\nimport progressbar\nimport pathlib\nimport sqlite3\n\nimport sqlalchemy as sql\nfrom sqlalchemy.ext import declarative\n\nfrom deeplearning.benchpress.util import crypto\nfrom deeplearning.benchpress.util import distrib\nfrom deeplearning.benchpress.util import environment\nfrom deeplearning.benchpress.util import sqlutil\nfrom deeplearning.benchpress.util import logging as l\n\nfrom absl import flags\n\nFLAGS = flags.FLAGS\n\nBase = declarative.declarative_base()\n\nclass EERResults(Base):\n __tablename__ = \"eer)results\"\n \"\"\"\n DB Table for concentrated validation results.\n \"\"\"\n key : str = sql.Column(sql.String(1024), primary_key=True)\n results : str = sql.Column(sqlutil.ColumnTypes.UnboundedUnicodeText(), nullable = False)\n\nclass EERSample(Base, sqlutil.ProtoBackedMixin):\n \"\"\"A database row representing a AL model sample.\n\n \"\"\"\n __tablename__ = \"eer_samples\"\n # entry id\n id : int = sql.Column(sql.Integer, primary_key = True)\n # unique hash of sample text\n sha256 : str = sql.Column(sql.String(64), nullable = False, index = True)\n # Sample step iteration ID.\n sample_epoch : int = sql.Column(sql.Integer, nullable = False)\n # model's train step that generated the sample\n train_step : int = sql.Column(sql.Integer, nullable = False)\n # Original input where the feed came from\n src : str = sql.Column(sqlutil.ColumnTypes.UnboundedUnicodeText(), nullable = False)\n # Runtime features of input.\n runtime_features : str = sql.Column(sqlutil.ColumnTypes.UnboundedUnicodeText(), nullable = False)\n # Input to the model.\n input_features : str = sql.Column(sqlutil.ColumnTypes.UnboundedUnicodeText(), nullable = False)\n # Predicted label\n prediction : str = sql.Column(sqlutil.ColumnTypes.UnboundedUnicodeText(), nullable = False)\n # Date\n date_added : datetime.datetime = sql.Column(sql.DateTime, nullable=False)\n\n @classmethod\n def FromArgs(cls,\n id : int,\n sample_epoch : int,\n train_step : int,\n src : str,\n runtime_features : typing.Dict[str, float],\n input_features : typing.Dict[str, float],\n prediction : str,\n ) -> 'EERSample':\n str_input_features = '\\n'.join([\"{}:{}\".format(k, v) for k, v in input_features.items()])\n str_runtime_features = '\\n'.join([\"{}:{}\".format(k, v) for k, v in runtime_features.items()])\n sha256 = crypto.sha256_str(\n str(train_step)\n + src\n + str_runtime_features\n + str_input_features\n + prediction\n )\n return EERSample(\n id = id,\n sha256 = sha256,\n sample_epoch = sample_epoch,\n train_step = train_step,\n src = src,\n runtime_features = str_runtime_features,\n input_features = str_input_features,\n prediction = prediction,\n date_added = datetime.datetime.utcnow(),\n )\n\nclass EERSamples(sqlutil.Database):\n \"\"\"A database of Query-by-Committee samples.\"\"\"\n\n def __init__(self, url: str, must_exist: bool = False, is_replica: bool = False):\n if environment.WORLD_RANK == 0 or is_replica:\n super(EERSamples, self).__init__(url, Base, must_exist = must_exist)\n if environment.WORLD_SIZE > 1 and not is_replica:\n # Conduct engine connections to replicated preprocessed chunks.\n self.base_path = pathlib.Path(url.replace(\"sqlite:///\", \"\")).resolve().parent\n hash_id = self.base_path.name\n try:\n tdir = pathlib.Path(FLAGS.local_filesystem).resolve() / hash_id / \"node_committee_samples\"\n except Exception:\n tdir = pathlib.Path(\"/tmp\").resolve() / hash_id / \"node_committee_samples\"\n try:\n tdir.mkdir(parents = True, exist_ok = True)\n except Exception:\n pass\n self.replicated_path = tdir / \"samples_{}.db\".format(environment.WORLD_RANK)\n self.replicated = EERSamples(\n url = \"sqlite:///{}\".format(str(self.replicated_path)),\n must_exist = must_exist,\n is_replica = True\n )\n distrib.barrier()\n return\n\n @property\n def sample_count(self):\n \"\"\"Number of samples in DB.\"\"\"\n with self.get_session() as s:\n count = s.query(EERSample).count()\n return count\n\n @property\n def get_data(self):\n \"\"\"Return all database in list format\"\"\"\n with self.get_session() as s:\n return s.query(EERSample).all()\n\n @property\n def cur_sample_epoch(self):\n \"\"\"Return the most recent checkpointed current sample step.\"\"\"\n if self.sample_count > 0:\n with self.get_session() as s:\n return max([int(x.sample_epoch) for x in s.query(EERSample).all()])\n else:\n return 0\n\n @property\n def get_session(self):\n \"\"\"\n get proper DB session.\n \"\"\"\n if environment.WORLD_SIZE == 1 or environment.WORLD_RANK == 0:\n return self.Session\n else:\n return self.replicated.Session\n\n def add_samples(self, sample_epoch: int, samples: typing.Dict[str, typing.Any]) -> None:\n \"\"\"\n If not exists, add sample to Samples table.\n \"\"\"\n hash_cache = set()\n offset_idx = self.sample_count\n with self.get_session(commit = True) as s:\n for sample in samples:\n sample_entry = EERSample.FromArgs(\n id = offset_idx,\n sample_epoch = sample_epoch,\n train_step = sample['train_step'],\n src = sample['src'],\n runtime_features = sample['runtime_features'],\n input_features = sample['input_features'],\n prediction = sample['prediction'],\n )\n exists = s.query(EERSample).filter_by(sha256 = sample_entry.sha256).first()\n if not exists and sample_entry.sha256 not in hash_cache:\n s.add(sample_entry)\n hash_cache.add(sample_entry.sha256)\n offset_idx += 1\n s.commit()\n return\n", "repo_name": "fivosts/BenchPress", "sub_path": "deeplearning/benchpress/active_models/expected_error_reduction/eer_database.py", "file_name": "eer_database.py", "file_ext": "py", "file_size_in_byte": 5956, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 17, "dataset": "github-code", "pt": "20", "api": [{"api_name": "absl.flags.FLAGS", "line_number": 18, "usage_type": "attribute"}, {"api_name": "absl.flags", "line_number": 18, "usage_type": "name"}, {"api_name": "sqlalchemy.ext.declarative.declarative_base", "line_number": 20, "usage_type": "call"}, {"api_name": "sqlalchemy.ext.declarative", "line_number": 20, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 27, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 27, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 28, "usage_type": "call"}, {"api_name": "deeplearning.benchpress.util.sqlutil.ColumnTypes.UnboundedUnicodeText", "line_number": 28, "usage_type": "call"}, {"api_name": "deeplearning.benchpress.util.sqlutil.ColumnTypes", "line_number": 28, "usage_type": "attribute"}, {"api_name": "deeplearning.benchpress.util.sqlutil", "line_number": 28, "usage_type": "name"}, {"api_name": "deeplearning.benchpress.util.sqlutil.ProtoBackedMixin", "line_number": 30, "usage_type": "attribute"}, {"api_name": "deeplearning.benchpress.util.sqlutil", "line_number": 30, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 36, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 36, "usage_type": "attribute"}, {"api_name": "sqlalchemy.Column", "line_number": 38, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 38, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 40, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 40, "usage_type": "attribute"}, {"api_name": "sqlalchemy.Column", "line_number": 42, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 42, "usage_type": "attribute"}, {"api_name": "sqlalchemy.Column", "line_number": 44, "usage_type": "call"}, {"api_name": "deeplearning.benchpress.util.sqlutil.ColumnTypes.UnboundedUnicodeText", "line_number": 44, "usage_type": "call"}, {"api_name": "deeplearning.benchpress.util.sqlutil.ColumnTypes", "line_number": 44, "usage_type": "attribute"}, {"api_name": "deeplearning.benchpress.util.sqlutil", "line_number": 44, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 46, "usage_type": "call"}, {"api_name": "deeplearning.benchpress.util.sqlutil.ColumnTypes.UnboundedUnicodeText", "line_number": 46, "usage_type": "call"}, {"api_name": "deeplearning.benchpress.util.sqlutil.ColumnTypes", "line_number": 46, "usage_type": "attribute"}, {"api_name": "deeplearning.benchpress.util.sqlutil", "line_number": 46, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 48, "usage_type": "call"}, {"api_name": "deeplearning.benchpress.util.sqlutil.ColumnTypes.UnboundedUnicodeText", "line_number": 48, "usage_type": "call"}, {"api_name": "deeplearning.benchpress.util.sqlutil.ColumnTypes", "line_number": 48, "usage_type": "attribute"}, {"api_name": "deeplearning.benchpress.util.sqlutil", "line_number": 48, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 50, "usage_type": "call"}, {"api_name": "deeplearning.benchpress.util.sqlutil.ColumnTypes.UnboundedUnicodeText", "line_number": 50, "usage_type": "call"}, {"api_name": "deeplearning.benchpress.util.sqlutil.ColumnTypes", "line_number": 50, "usage_type": "attribute"}, {"api_name": "deeplearning.benchpress.util.sqlutil", "line_number": 50, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 52, "usage_type": "attribute"}, {"api_name": "sqlalchemy.Column", "line_number": 52, "usage_type": "call"}, {"api_name": "sqlalchemy.DateTime", "line_number": 52, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 60, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 61, "usage_type": "attribute"}, {"api_name": "deeplearning.benchpress.util.crypto.sha256_str", "line_number": 66, "usage_type": "call"}, {"api_name": "deeplearning.benchpress.util.crypto", "line_number": 66, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 82, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 82, "usage_type": "attribute"}, {"api_name": "deeplearning.benchpress.util.sqlutil.Database", "line_number": 85, "usage_type": "attribute"}, {"api_name": "deeplearning.benchpress.util.sqlutil", "line_number": 85, "usage_type": "name"}, {"api_name": "deeplearning.benchpress.util.environment.WORLD_RANK", "line_number": 89, "usage_type": "attribute"}, {"api_name": "deeplearning.benchpress.util.environment", "line_number": 89, "usage_type": "name"}, {"api_name": "deeplearning.benchpress.util.environment.WORLD_SIZE", "line_number": 91, "usage_type": "attribute"}, {"api_name": "deeplearning.benchpress.util.environment", "line_number": 91, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 93, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 96, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 98, "usage_type": "call"}, {"api_name": "deeplearning.benchpress.util.environment.WORLD_RANK", "line_number": 103, "usage_type": "attribute"}, {"api_name": "deeplearning.benchpress.util.environment", "line_number": 103, "usage_type": "name"}, {"api_name": "deeplearning.benchpress.util.distrib.barrier", "line_number": 109, "usage_type": "call"}, {"api_name": "deeplearning.benchpress.util.distrib", "line_number": 109, "usage_type": "name"}, {"api_name": "deeplearning.benchpress.util.environment.WORLD_SIZE", "line_number": 139, "usage_type": "attribute"}, {"api_name": "deeplearning.benchpress.util.environment", "line_number": 139, "usage_type": "name"}, {"api_name": "deeplearning.benchpress.util.environment.WORLD_RANK", "line_number": 139, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 144, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 144, "usage_type": "attribute"}]} +{"seq_id": "74629399730", "text": "#!/usr/bin/python\n\nimport matplotlib.pyplot as pyplot\n\n\ndef euler(a, b, n, y0, fun):\n h = (b - a) / n\n yp = [y0]\n xp = [a]\n for i in range(0, n):\n yp.append(yp[i]+h*fun(xp[i],yp[i]))\n xp.append(xp[i]+h)\n return xp, yp\n\n\ndef rk4(a, b, n, y0, fun):\n h = (b - a) / n\n yp = [y0]\n xp = [a]\n for i in range(0, n):\n k1 = h * fun(xp[i], yp[i])\n k2 = h * fun(xp[i] + h / 2., yp[i] + k1 / 2.)\n k3 = h * fun(xp[i] + h / 2., yp[i] + k2 / 2.)\n k4 = h * fun(xp[i] + h, yp[i] + k3)\n yp.append(yp[i] + (k1 + 2. * k2 + 2. * k3 + k4) / 6.)\n xp.append(xp[i]+h)\n return xp, yp\n\n\ndef ab3(a, b, n, y0, fun):\n h = (b - a) / n\n yp = [y0]\n xp = [a]\n for i in range(0,2):\n k1 = h * fun(xp[i], yp[i])\n k2 = h * fun(xp[i] + h / 2., yp[i] + k1 / 2.)\n k3 = h * fun(xp[i] + h / 2., yp[i] + k2 / 2.)\n k4 = h * fun(xp[i] + h, yp[i] + k3)\n yp.append(yp[i] + (k1 + 2. * k2 + 2. * k3 + k4) / 6.)\n xp.append(xp[i]+h)\n for i in range(2, n):\n yp.append(yp[i] + h / 12. * (23. * fun(xp[i], yp[i]) - 16. * fun(xp[i - 1], yp[i - 1]) +\n 5. * fun(xp[i - 2], yp[i - 2])))\n xp.append(xp[i]+h)\n return xp, yp\n\n\ndef func(x, y):\n return -y\n\n\ne1, e2 = euler(0, 1, 1, 1, func)\nr1, r2 = rk4(0, 1, 1, 1, func)\na1, a2 = ab3(0, 1, 1, 1, func)\npyplot.plot(e1, e2, 'r', r1, r2, 'b', a1, a2, 'g')\npyplot.legend(['Euler', 'Runge - Kutta', 'Adams - Bashforth'])\npyplot.show()\n\nfile = open('euler_1.txt', 'w')\nfile.write(str(euler(0, 10, 100, 1, func)))\nfile.close()\n\nfile = open('rk4_1.txt', 'w')\nfile.write(str(rk4(0, 10, 100, 1, func)))\nfile.close()\n\nfile = open('ab3_1.txt', 'w')\nfile.write(str(ab3(0, 10, 100, 1, func)))\nfile.close()\n", "repo_name": "pwr227078/Computional-Methods", "sub_path": "Pendulum/ivp(1).py", "file_name": "ivp(1).py", "file_ext": "py", "file_size_in_byte": 1777, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "matplotlib.pyplot.plot", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 56, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}]} +{"seq_id": "4381138917", "text": "import os\nimport requests\nimport base64\nfrom multiprocessing.dummy import Pool as ThreadPool\nimport datetime\n\n\ndef fulfill_req(ticker, expiry):\n api_url = os.environ.get(\"API_URL\")\n print(ticker + \" \" + expiry)\n for _ in range(3): # in case of unavailable data, retry twice\n filename = os.getcwd() + \"/data/\" + expiry + \"_exp/\" + ticker + \"_quotedata.csv\"\n payload = {\"ticker\": ticker, \"expiry\": expiry}\n with open(filename, \"wb\") as f, requests.get(\n api_url, stream=True, params=payload\n ) as r:\n try: # check if data is available\n r.raise_for_status()\n except requests.exceptions.HTTPError as e:\n print(e)\n f.write(\"Unavailable\".encode(\"utf-8\"))\n if r.status_code == 504: # check if timeout occurred\n print(\n \"gateway timeout, retrying search for \" + ticker + \" \" + expiry\n )\n continue\n elif r.status_code == 500: # internal server error\n print(\n \"internal server error, retrying search for \"\n + ticker\n + \" \"\n + expiry\n )\n continue\n else:\n for line in r.iter_lines():\n if len(line) % 4:\n # add padding:\n line += b\"===\"\n f.write(base64.b64decode(line) + \"\\n\".encode(\"utf-8\"))\n try: # check if data was received incorrectly\n options_file = open(filename, encoding=\"utf-8\")\n options_file.readlines()\n options_file.close()\n except:\n print(\"corrupted data, retrying search for \" + ticker + \" \" + expiry)\n else:\n print(\"request done for\", (ticker, expiry))\n break\n\n\ndef dwn_data():\n pool = ThreadPool()\n print(\"start:\", datetime.datetime.now())\n ticks_exp = [\n (\"spx\", \"monthly\"),\n (\"spx\", \"all\"),\n (\"ndx\", \"monthly\"),\n (\"ndx\", \"all\"),\n (\"rut\", \"monthly\"),\n (\"rut\", \"all\"),\n ]\n pool.starmap(fulfill_req, ticks_exp)\n pool.close()\n pool.join()\n print(\"end:\", datetime.datetime.now())\n\n\nif __name__ == \"__main__\":\n dwn_data()\n", "repo_name": "apmanikandan/gflows", "sub_path": "ticker_dwn.py", "file_name": "ticker_dwn.py", "file_ext": "py", "file_size_in_byte": 2366, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "20", "api": [{"api_name": "os.environ.get", "line_number": 9, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 12, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 14, "usage_type": "call"}, {"api_name": "requests.exceptions", "line_number": 19, "usage_type": "attribute"}, {"api_name": "base64.b64decode", "line_number": 40, "usage_type": "call"}, {"api_name": "multiprocessing.dummy.Pool", "line_number": 53, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 54, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 54, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 66, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 66, "usage_type": "attribute"}]} +{"seq_id": "38891942293", "text": "import requests,json\nfrom discord import Webhook,Embed,RequestsWebhookAdapter\n\ndef webhook_url():\n return ''\n\ndef avatar_url():\n return 'https://cdn.shopify.com/s/files/1/0219/2362/files/NiceKicks_Logo_downsized_black_140x.png?v=1565118222'\n\ndef get_variants():\n url = 'https://shopnicekicks.com/collections/mens-kicks/products/adidas-superstar-mens-running-white-black.json'\n resp = requests.get(url)\n j = json.loads(resp.text)\n product_title = j['product']['title']\n img_url = j['product']['image']['src']\n variants = j['product']['variants']\n result = []\n for v in variants:\n title = v['title']\n v_id = v['id']\n inventory_quantity = v['inventory_quantity']\n act_link = 'https://shopnicekicks.com/cart/{}:1'.format(v_id)\n v_result = '[{}]({})'.format(title,act_link)\n if inventory_quantity >0:\n result.append(v_result)\n return product_title, img_url, result\n\n\ndef send_webhook():\n url = webhook_url()\n product_title,img_url,result=get_variants()\n webhook = Webhook.from_url(url=url,adapter=RequestsWebhookAdapter())\n embed = Embed(title=product_title, url=url)\n embed.add_field(name='可用尺码', value='\\n'.join(result))\n embed.set_thumbnail(url=img_url)\n webhook.send(embed=embed,avatar_url=avatar_url(),username='shopnicekicks')\n\n\nsend_webhook()\n", "repo_name": "TOtobly/project2.py", "sub_path": "shopnicekicks.py", "file_name": "shopnicekicks.py", "file_ext": "py", "file_size_in_byte": 1360, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "requests.get", "line_number": 12, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 13, "usage_type": "call"}, {"api_name": "discord.Webhook.from_url", "line_number": 32, "usage_type": "call"}, {"api_name": "discord.Webhook", "line_number": 32, "usage_type": "name"}, {"api_name": "discord.RequestsWebhookAdapter", "line_number": 32, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 33, "usage_type": "call"}]} +{"seq_id": "72347384049", "text": "from django.db import models\nfrom django.contrib.auth.models import User\nimport datetime\n\n# Create your models here.\n\n\nclass CompanyProfile(models.Model):\n user = models.ForeignKey(User)\n company_name = models.CharField(max_length=250)\n last_nai = models.CharField(max_length=250)\n created = models.DateTimeField(default=None)\n updated = models.DateTimeField(default=datetime.datetime.now())\n deleted_flag = models.SmallIntegerField(default=0)\n\n# def __unicode__(self):\n# return self.user\n\n", "repo_name": "baseev/namma004", "sub_path": "company/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 558, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "django.db.models.Model", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 8, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 9, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User", "line_number": 9, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 9, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 10, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 10, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 11, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 11, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 12, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 12, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 13, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 13, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 13, "usage_type": "attribute"}, {"api_name": "django.db.models.SmallIntegerField", "line_number": 14, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 14, "usage_type": "name"}]} +{"seq_id": "35166628624", "text": "\nfrom numpy.lib.polynomial import _polyint_dispatcher\nfrom numpy.random import randint\nimport pyautogui\nimport cv2 as cv\nfrom PIL import ImageGrab\nfrom functools import partial\nimport time\nimport numpy as np\nimport win32gui\nimport datetime\nfrom support_functions import go_to_stage, locate_and_click, get_center, go_to_base, adjusted_click, click_element,adjusted_move\n\n\nclass Routine():\n\n def __init__(self):\n\n self.STATE = 0\n\n self.market_CD = None\n\n\n def routine(self):\n\n # get daily login rewards\n go_to_base()\n self.login_rewards()\n\n #go_to_base()\n #self.sparing_pit()\n\n # get mine rewards\n go_to_base()\n self.get_mine_gems()\n\n # Get shards from market\n go_to_base()\n self.market_refresh()\n \n # Campaign 7x run\n go_to_base()\n self.campaign_run()\n\n # Kill boss 3x times\n go_to_base()\n self.boss_run()\n \n #Level up hero three times\n go_to_base()\n self.go_to_tavern()\n\n # Get free shop rewards\n go_to_base()\n self.get_shop_rewards()\n\n # Play time rewards\n go_to_base()\n self.play_time_rewards()\n\n # Summon 3 heroes\n go_to_base()\n self.summon_heroes()\n\n # upgrade armor\n go_to_base()\n self.upgrade_armor()\n \n # Collect daily quests\n go_to_base()\n self.daily_quests_collect()\n\n # Collect arena champion\n #go_to_base()\n #self.arena_shop()\n\n \n \n def mini_routine(self):\n\n # Check sparring pit\n #go_to_base()\n #self.sparing_pit()\n\n # get mine rewards\n go_to_base()\n self.get_mine_gems()\n\n # Get shards from market\n go_to_base()\n self.market_refresh()\n\n # Play time rewards\n go_to_base()\n self.play_time_rewards()\n\n # Collect daily quests\n go_to_base()\n self.daily_quests_collect()\n\n # Collect arena champion\n #go_to_base()\n #self.arena_shop()\n\n def login_rewards(self):\n\n time.sleep(1)\n adjusted_click(-618.0,10)\n time.sleep(1)\n adjusted_click(-587.0, -286)\n time.sleep(1)\n \n\n def arena_shop(self):\n\n \n locate_and_click('battle', 0.6)\n locate_and_click('arena')\n \n locate_and_click('tag_arena')\n\n time.sleep(2)\n adjusted_click(-514, 180)\n time.sleep(1)\n adjusted_click(576, -118)\n time.sleep(2)\n locate_and_click('buy_champion')\n\n\n def go_to_tavern(self):\n\n # Champions location\n adjusted_click(332, 316)\n time.sleep(2)\n # Tavern location\n adjusted_click(179, 224)\n time.sleep(2)\n # Remove hero\n adjusted_click(213, -260)\n time.sleep(2)\n x, y = get_center()\n pyautogui.moveTo(x - 500, y)\n time.sleep(1)\n #pyautogui.dragTo((x - 500), y - 400, duration=3)\n for i in range(50):\n pyautogui.scroll(-1)\n \n time.sleep(2)\n #click hero\n adjusted_click(-489, 207)\n for i in range(50):\n pyautogui.scroll(-1)\n time.sleep(2)\n adjusted_click(-489, 207)\n #time.sleep(2)\n #adjusted_click(-400, 207)\n #time.sleep(2)\n #adjusted_click(-569, 207)\n time.sleep(2)\n adjusted_click(480, 312)\n time.sleep(2)\n \n\n def upgrade_armor(self):\n\n time.sleep(2)\n # Champions location\n adjusted_click(332, 316)\n time.sleep(2)\n # Item location\n adjusted_click(465, 39)\n time.sleep(2)\n # Upgrade location\n adjusted_click(-556, -43)\n time.sleep(2)\n # Upgrade item location\n for i in range(4):\n adjusted_click(126, 305)\n time.sleep(3)\n\n def sparing_pit(self):\n\n \n\n time.sleep(2)\n adjusted_move(400.0, 150.5)\n time.sleep(2)\n mouse_position = pyautogui.position()\n pyautogui.dragTo(mouse_position[0]- 500, mouse_position[1]-500, duration=5)\n\n time.sleep(2)\n adjusted_click(43, -103)\n time.sleep(2)\n\n # Check if heroes are ready to level up\n if pyautogui.locateOnScreen('./images/upgrade_to.png', confidence=0.9):\n while pyautogui.locateOnScreen('./images/upgrade_to.png', confidence=0.9):\n locate_and_click('upgrade_to')\n time.sleep(2)\n # Insert new hero\n if pyautogui.locateOnScreen('./images/max_level_sparring.png', confidence=0.9):\n locate_and_click('max_level_sparring', y_adj=-200, x_adj=20)\n time.sleep(2)\n locate_and_click('select_hero', y_adj=-100 ,conf=0.8)\n time.sleep(2)\n locate_and_click('confirm_sparring')\n\n # Check for max levels and insert new hero\n elif pyautogui.locateOnScreen('./images/max_level_sparring.png', confidence=0.9):\n while pyautogui.locateOnScreen('./images/max_level_sparring.png', confidence=0.9):\n locate_and_click('max_level_sparring', y_adj=-200, x_adj=20)\n time.sleep(2)\n locate_and_click('select_hero', y_adj=-100 ,conf=0.8)\n time.sleep(2)\n locate_and_click('confirm_sparring')\n \n # Check for empty sparring pits and insert heroes\n elif pyautogui.locateOnScreen('./images/select_champion.png', confidence=0.9):\n while pyautogui.locateOnScreen('./images/select_champion.png', confidence=0.9):\n locate_and_click('select_champion', y_adj=-200, x_adj=20)\n time.sleep(2)\n locate_and_click('select_hero', y_adj=-100 ,conf=0.8)\n time.sleep(2)\n locate_and_click('confirm_sparring')\n \n\n def market_refresh(self):\n\n go_to_base()\n\n if self.market_CD == None:\n self.market_CD = datetime.datetime.now()\n \n x, y = get_center()\n time.sleep(2)\n adjusted_move(400.0, 150.5)\n time.sleep(2)\n mouse_position = pyautogui.position()\n pyautogui.dragTo(mouse_position[0]+ 400, mouse_position[1]-400, duration=5)\n \n adjusted_click(93, -16)\n\n time.sleep(2)\n #for i in range(3)\n for i in range(5):\n try:\n if pyautogui.locateOnScreen('./images/mystery_shard_market.png', confidence=0.9):\n locate_and_click('mystery_shard_market')\n time.sleep(1)\n locate_and_click('get_mystery')\n\n time.sleep(1)\n if pyautogui.locateOnScreen('./images/ancient_shard_market.png', confidence=0.9):\n locate_and_click('ancient_shard_market')\n time.sleep(1)\n locate_and_click('get_ancient')\n except Exception:\n print(\"Shard not found\")\n\n for i in range(10):\n pyautogui.scroll(-1)\n\n for i in range(5):\n try:\n if pyautogui.locateOnScreen('./images/mystery_shard_market.png', confidence=0.9):\n locate_and_click('mystery_shard_market')\n time.sleep(1)\n locate_and_click('get_mystery')\n\n time.sleep(1)\n if pyautogui.locateOnScreen('./images/ancient_shard_market.png', confidence=0.9):\n locate_and_click('ancient_shard_market')\n time.sleep(1)\n locate_and_click('get_ancient')\n except Exception:\n print(\"Shard not found\")\n\n\n \n def campaign_run(self):\n\n # Battle location\n adjusted_click(505.0, 310.5)\n time.sleep(2)\n locate_and_click('campaing_location')\n time.sleep(2)\n\n # Select difficulty, default = brutal\n adjusted_click(-507.0, 318.5)\n time.sleep(2)\n # Normal loc\n adjusted_click(-507.0, 40.5)\n\n time.sleep(2)\n locate_and_click('clerog_castle')\n time.sleep(2)\n for i in range(7):\n pyautogui.scroll(-1)\n time.sleep(2)\n adjusted_click(510, 150)\n time.sleep(2)\n locate_and_click('start_clerog')\n\n n = 0\n while n < 6:\n time.sleep(1)\n print(f\"round {n+1}\")\n if pyautogui.locateOnScreen('./images/replay_clerog.png', confidence=0.7) != None:\n locate_and_click(\"replay_clerog\")\n n+=1\n\n time.sleep(10)\n\n\n def boss_run(self):\n\n # Battle location\n adjusted_click(505.0, 310.5)\n time.sleep(2)\n locate_and_click('campaing_location')\n time.sleep(2)\n\n # Select difficulty, default = brutal\n adjusted_click(-507.0, 318.5)\n time.sleep(2)\n # Normal loc\n adjusted_click(-507.0, 40.5)\n time.sleep(2)\n\n locate_and_click('clerog_castle')\n time.sleep(2)\n for i in range(7):\n pyautogui.scroll(-1)\n time.sleep(2)\n adjusted_click(510, 300)\n time.sleep(2)\n locate_and_click('start_clerog')\n\n n = 0\n while n < 2:\n time.sleep(1)\n print(f\"round {n+1}\")\n if pyautogui.locateOnScreen('./images/replay_clerog.png', confidence=0.7) != None:\n locate_and_click(\"replay_clerog\")\n n+=1\n\n time.sleep(10)\n\n def summon_heroes(self):\n\n time.sleep(2)\n adjusted_move(400.0, 150.5)\n time.sleep(2)\n mouse_position = pyautogui.position()\n pyautogui.dragTo(mouse_position[0]+ 500, mouse_position[1]+400, duration=5)\n\n adjusted_click(-156.0, 93.5)\n time.sleep(2)\n locate_and_click('summon_green')\n time.sleep(4)\n locate_and_click('summon_green_2')\n time.sleep(4)\n locate_and_click('summon_green_2')\n time.sleep(4)\n go_to_base()\n\n def daily_quests_collect(self):\n\n # Quests location\n adjusted_click(-248, 316)\n\n time.sleep(2)\n while pyautogui.locateOnScreen('./images/claim_daily.png') != None:\n locate_and_click('claim_daily')\n time.sleep(1)\n if pyautogui.locateOnScreen('./images/quests_continue.png') != None:\n locate_and_click('quests_continue')\n\n\n def to_leveling(self):\n\n time.sleep(2)\n # Battle location\n adjusted_click(505.0, 310.5)\n locate_and_click('to_leveling', 0.6)\n\n\n\n def play_time_rewards(self):\n '''\n Collects all playtime rewards\n '''\n time.sleep(1)\n adjusted_click(550.0, 221.5)\n time.sleep(1)\n #loc = pyautogui.locateOnScreen('./images/playtime_1.png', confidence=0.8)\n #location = pyautogui.center(loc)\n adjusted_click(-344, 112)\n #click_element(location[0], location[1])\n\n pct = 140\n time.sleep(2)\n for i in range(5):\n adjusted_click(-344 + pct, 112)\n pct += 140\n time.sleep(2)\n\n def get_mine_gems(self):\n\n x, y = get_center()\n time.sleep(2)\n adjusted_move(400.0, 150.5)\n time.sleep(2)\n mouse_position = pyautogui.position()\n pyautogui.dragTo(mouse_position[0]+ 400, mouse_position[1]-400, duration=5)\n locate_and_click('mine', conf=0.7)\n\n def get_shop_rewards(self):\n \n time.sleep(1)\n locate_and_click('shop_free')\n locate_and_click('mystery_shard')\n locate_and_click('claim')\n locate_and_click('ancient_shard')\n locate_and_click('claim')\n\n locate_and_click('limited_offer')\n \n adjusted_click(-360, -252)\n #click_element(location[0], location[1])\n\n pct = 70\n time.sleep(2)\n for i in range(13):\n adjusted_click(-360 + pct, -252)\n pct += 70\n locate_and_click('claim_free_gift')\n time.sleep(2)\n\n\n\n\n#r = Routine()\n#r.market_refresh()", "repo_name": "NikoK93/Raider", "sub_path": "routines.py", "file_name": "routines.py", "file_ext": "py", "file_size_in_byte": 12113, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "support_functions.go_to_base", "line_number": 27, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 34, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 38, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 42, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 46, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 50, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 54, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 58, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 62, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 66, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 70, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 86, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 90, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 94, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 98, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 107, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 108, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 109, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 110, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 111, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 117, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 118, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 120, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 122, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 123, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 124, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 125, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 126, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 127, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 133, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 134, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 136, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 137, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 139, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 140, "usage_type": "call"}, {"api_name": "support_functions.get_center", "line_number": 141, "usage_type": "call"}, {"api_name": "pyautogui.moveTo", "line_number": 142, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 143, "usage_type": "call"}, {"api_name": "pyautogui.scroll", "line_number": 146, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 148, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 150, "usage_type": "call"}, {"api_name": "pyautogui.scroll", "line_number": 152, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 153, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 154, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 159, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 160, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 161, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 166, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 168, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 169, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 171, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 172, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 174, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 175, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 178, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 179, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 185, "usage_type": "call"}, {"api_name": "support_functions.adjusted_move", "line_number": 186, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 187, "usage_type": "call"}, {"api_name": "pyautogui.position", "line_number": 188, "usage_type": "call"}, {"api_name": "pyautogui.dragTo", "line_number": 189, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 191, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 192, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 193, "usage_type": "call"}, {"api_name": "pyautogui.locateOnScreen", "line_number": 196, "usage_type": "call"}, {"api_name": "pyautogui.locateOnScreen", "line_number": 197, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 198, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 199, "usage_type": "call"}, {"api_name": "pyautogui.locateOnScreen", "line_number": 201, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 202, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 203, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 204, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 205, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 206, "usage_type": "call"}, {"api_name": "pyautogui.locateOnScreen", "line_number": 209, "usage_type": "call"}, {"api_name": "pyautogui.locateOnScreen", "line_number": 210, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 211, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 212, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 213, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 214, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 215, "usage_type": "call"}, {"api_name": "pyautogui.locateOnScreen", "line_number": 218, "usage_type": "call"}, {"api_name": "pyautogui.locateOnScreen", "line_number": 219, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 220, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 221, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 222, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 223, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 224, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 229, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 232, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 232, "usage_type": "attribute"}, {"api_name": "support_functions.get_center", "line_number": 234, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 235, "usage_type": "call"}, {"api_name": "support_functions.adjusted_move", "line_number": 236, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 237, "usage_type": "call"}, {"api_name": "pyautogui.position", "line_number": 238, "usage_type": "call"}, {"api_name": "pyautogui.dragTo", "line_number": 239, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 241, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 243, "usage_type": "call"}, {"api_name": "pyautogui.locateOnScreen", "line_number": 247, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 248, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 249, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 250, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 252, "usage_type": "call"}, {"api_name": "pyautogui.locateOnScreen", "line_number": 253, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 254, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 255, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 256, "usage_type": "call"}, {"api_name": "pyautogui.scroll", "line_number": 261, "usage_type": "call"}, {"api_name": "pyautogui.locateOnScreen", "line_number": 265, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 266, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 267, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 268, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 270, "usage_type": "call"}, {"api_name": "pyautogui.locateOnScreen", "line_number": 271, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 272, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 273, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 274, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 283, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 284, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 285, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 286, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 289, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 290, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 292, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 294, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 295, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 296, "usage_type": "call"}, {"api_name": "pyautogui.scroll", "line_number": 298, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 299, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 300, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 301, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 302, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 306, "usage_type": "call"}, {"api_name": "pyautogui.locateOnScreen", "line_number": 308, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 309, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 312, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 318, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 319, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 320, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 321, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 324, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 325, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 327, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 328, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 330, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 331, "usage_type": "call"}, {"api_name": "pyautogui.scroll", "line_number": 333, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 334, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 335, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 336, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 337, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 341, "usage_type": "call"}, {"api_name": "pyautogui.locateOnScreen", "line_number": 343, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 344, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 347, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 351, "usage_type": "call"}, {"api_name": "support_functions.adjusted_move", "line_number": 352, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 353, "usage_type": "call"}, {"api_name": "pyautogui.position", "line_number": 354, "usage_type": "call"}, {"api_name": "pyautogui.dragTo", "line_number": 355, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 357, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 358, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 359, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 360, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 361, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 362, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 363, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 364, "usage_type": "call"}, {"api_name": "support_functions.go_to_base", "line_number": 365, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 370, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 372, "usage_type": "call"}, {"api_name": "pyautogui.locateOnScreen", "line_number": 373, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 374, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 375, "usage_type": "call"}, {"api_name": "pyautogui.locateOnScreen", "line_number": 376, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 377, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 382, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 384, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 385, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 393, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 394, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 395, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 398, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 402, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 404, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 406, "usage_type": "call"}, {"api_name": "support_functions.get_center", "line_number": 410, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 411, "usage_type": "call"}, {"api_name": "support_functions.adjusted_move", "line_number": 412, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 413, "usage_type": "call"}, {"api_name": "pyautogui.position", "line_number": 414, "usage_type": "call"}, {"api_name": "pyautogui.dragTo", "line_number": 415, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 416, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 420, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 421, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 422, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 423, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 424, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 425, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 427, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 429, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 433, "usage_type": "call"}, {"api_name": "support_functions.adjusted_click", "line_number": 435, "usage_type": "call"}, {"api_name": "support_functions.locate_and_click", "line_number": 437, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 438, "usage_type": "call"}]} +{"seq_id": "34394469509", "text": "import os\n\nimport openai\nfrom llama_index import GPTVectorStoreIndex, download_loader\n\nopenai.api_key = os.environ.get(\"OPENAI_API_KEY\")\n\nSimpleWebPageReader = download_loader(\"SimpleWebPageReader\")\nloader = SimpleWebPageReader()\nurl = \"https://modal.com/docs/guide/continuous-deployment#github-actions\"\ndocuments = loader.load_data(urls=[url])\ndocument = documents[0]\n\nindex = GPTVectorStoreIndex.from_documents(documents)\nquery_engine = index.as_query_engine(streaming=True)\nquery_engine.query(\n \"Extract the entire example yaml from the html.\"\n).print_response_stream()\n", "repo_name": "sweepai/sweep", "sub_path": "tests/archive/test_scraper.py", "file_name": "test_scraper.py", "file_ext": "py", "file_size_in_byte": 576, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5783, "dataset": "github-code", "pt": "20", "api": [{"api_name": "openai.api_key", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 6, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 6, "usage_type": "attribute"}, {"api_name": "llama_index.download_loader", "line_number": 8, "usage_type": "call"}, {"api_name": "llama_index.GPTVectorStoreIndex.from_documents", "line_number": 14, "usage_type": "call"}, {"api_name": "llama_index.GPTVectorStoreIndex", "line_number": 14, "usage_type": "name"}]} +{"seq_id": "35245443029", "text": "import cv2\r\nimport requests\r\nimport numpy as np\r\ndef main():\r\n url = 'http://192.168.1.4:8080/shot.jpg'\r\n \r\n while True:\r\n img_resp = requests.get(url)\r\n img_arr = np.array(bytearray(img_resp.content),dtype=np.uint8)\r\n img = cv2.imdecode(img_arr,-1)\r\n hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\r\n #red range\r\n red_lower=np.array([136,87,111],np.uint8)\r\n red_upper=np.array([180,255,255],np.uint8)\r\n #blue range\r\n blue_lower=np.array([100,50,50],np.uint8)\r\n blue_upper=np.array([140,255,255],np.uint8)\r\n #yellow range\r\n yellow_lower=np.array([22,60,200],np.uint8)\r\n yellow_upper=np.array([60,255,255],np.uint8)\r\n #finding the range of red,blue and yellow color in the image\r\n red=cv2.inRange(hsv, red_lower, red_upper)\r\n blue=cv2.inRange(hsv,blue_lower,blue_upper)\r\n yellow=cv2.inRange(hsv,yellow_lower,yellow_upper)\r\n \r\n res=cv2.bitwise_and(img, img, mask = red)\r\n res1=cv2.bitwise_and(img, img, mask = blue)\r\n res2=cv2.bitwise_and(img, img, mask = yellow) \r\n \r\n (_,contours,hierarchy)=cv2.findContours(red,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\r\n #Tracking the Red Color\r\n for pic, contour in enumerate(contours):\r\n\t\t area = cv2.contourArea(contour)\r\n\t\t if(area>300):\r\n\t\t\t\r\n\t\t\t x,y,w,h = cv2.boundingRect(contour)\t\r\n\t\t\t img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)\r\n\t\t\t cv2.putText(img,\"RED color\",(x,y),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255))\r\n \r\n (_,contours,hierarchy)=cv2.findContours(blue,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\r\n\t\t\t\r\n\t#Tracking the Blue Color\r\n for pic, contour in enumerate(contours):\r\n\t\t area = cv2.contourArea(contour)\r\n\t\t if(area>300):\r\n\t\t\t x,y,w,h = cv2.boundingRect(contour)\t\r\n\t\t\t img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)\r\n\t\t\t cv2.putText(img,\"Blue color\",(x,y),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,0,0))\r\n\r\n\t#Tracking the yellow Color\r\n (_,contours,hierarchy)=cv2.findContours(yellow,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\r\n \r\n for pic, contour in enumerate(contours):\r\n\t\t area = cv2.contourArea(contour)\r\n\t\t if(area>300):\r\n\t\t\t x,y,w,h = cv2.boundingRect(contour)\t\r\n\t\t\t img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)\r\n\t\t\t cv2.putText(img,\"yellow color\",(x,y),cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,255,0)) \r\n \r\n cv2.imshow(\"Color Tracking\",img)\r\n #cv2.imshow(\"red\",res)\r\n #cv2.imshow(\"blue\",res1)\r\n #cv2.imshow(\"yellow\",res2)\r\n if cv2.waitKey(1)==27:\r\n break\r\n cv2.destroyAllWindows()\r\n \r\nif __name__ == \"__main__\":\r\n main()", "repo_name": "kaushi99/Data-Science-Projects", "sub_path": "mobobjtrack.py", "file_name": "mobobjtrack.py", "file_ext": "py", "file_size_in_byte": 2819, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "requests.get", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 9, "usage_type": "attribute"}, {"api_name": "cv2.imdecode", "line_number": 10, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 11, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2HSV", "line_number": 11, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 13, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 14, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 16, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 17, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 19, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 20, "usage_type": "attribute"}, {"api_name": "cv2.inRange", "line_number": 22, "usage_type": "call"}, {"api_name": "cv2.inRange", "line_number": 23, "usage_type": "call"}, {"api_name": "cv2.inRange", "line_number": 24, "usage_type": "call"}, {"api_name": "cv2.bitwise_and", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.bitwise_and", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.bitwise_and", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.findContours", "line_number": 30, "usage_type": "call"}, {"api_name": "cv2.RETR_TREE", "line_number": 30, "usage_type": "attribute"}, {"api_name": "cv2.CHAIN_APPROX_SIMPLE", "line_number": 30, "usage_type": "attribute"}, {"api_name": "cv2.contourArea", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.boundingRect", "line_number": 36, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 37, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 38, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 38, "usage_type": "attribute"}, {"api_name": "cv2.findContours", "line_number": 40, "usage_type": "call"}, {"api_name": "cv2.RETR_TREE", "line_number": 40, "usage_type": "attribute"}, {"api_name": "cv2.CHAIN_APPROX_SIMPLE", "line_number": 40, "usage_type": "attribute"}, {"api_name": "cv2.contourArea", "line_number": 44, "usage_type": "call"}, {"api_name": "cv2.boundingRect", "line_number": 46, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 47, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 48, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 48, "usage_type": "attribute"}, {"api_name": "cv2.findContours", "line_number": 51, "usage_type": "call"}, {"api_name": "cv2.RETR_TREE", "line_number": 51, "usage_type": "attribute"}, {"api_name": "cv2.CHAIN_APPROX_SIMPLE", "line_number": 51, "usage_type": "attribute"}, {"api_name": "cv2.contourArea", "line_number": 54, "usage_type": "call"}, {"api_name": "cv2.boundingRect", "line_number": 56, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 57, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 58, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 58, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 60, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 64, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 66, "usage_type": "call"}]} +{"seq_id": "10694482742", "text": "from aiogram import types, Dispatcher\n\nfrom datetime import datetime\n\nfrom bot.data.alchemy.DML import find_userdata_by_id, create_new_user, update_user_data, find_text_string\nfrom bot.keyboards.user_keyboards import get_main_keyboard\nfrom bot.midleware.middleware import rate_limit\n\nimport logging\n\n\n@rate_limit(limit=5, key=\"start\")\nasync def cmd_start(msg: types.Message) -> None:\n \"\"\"\n Start message handler.\n :param msg:\n :return:\n \"\"\"\n try:\n\n user_data = await find_userdata_by_id(msg.from_user.id)\n\n text = await find_text_string(string_name=\"MSG_HI\")\n text = text.format(msg.from_user.first_name if msg.from_user.first_name else msg.from_user.id)\n\n if not user_data:\n await create_new_user(user_id=msg.from_user.id, last_call=datetime.now(), user_name=msg.from_user.username,\n first_name=msg.from_user.first_name, last_name=msg.from_user.last_name)\n\n else:\n text = await find_text_string(string_name=\"MSG_HI_AGAIN\")\n text = text.format(msg.from_user.first_name,\n datetime.strftime(user_data[1],\n '%Y-%m-%d %H:%M:%S'))\n await update_user_data(user_id=msg.from_user.id, last_call=datetime.now(), user_name=msg.from_user.username,\n first_name=msg.from_user.first_name, last_name=msg.from_user.last_name)\n\n await msg.answer(text=text, reply_markup=await get_main_keyboard())\n except Exception as exc:\n logging.exception(msg=exc)\n\n\n@rate_limit(limit=3, key=\"cb_btn_more_info\")\nasync def ikb_more_info(cb: types.callback_query):\n \"\"\"\n Callback handler\n :param cb:\n :return:\n \"\"\"\n try:\n if cb.data == \"cb_btn_more_info\":\n await cb.answer(await find_text_string(string_name=\"GET_MORE_INFO\"))\n except Exception as exc:\n logging.exception(msg=exc)\n\n\nasync def register_user_handlers(dp: Dispatcher) -> None:\n \"\"\"\n Register user handlers\n :param dp:\n :return:\n \"\"\"\n dp.register_message_handler(cmd_start, commands=[\"start\"])\n dp.register_callback_query_handler(callback=ikb_more_info)\n", "repo_name": "SergeyTorhov/aiogram_bot_sample", "sub_path": "bot/handlers/user_handlers.py", "file_name": "user_handlers.py", "file_ext": "py", "file_size_in_byte": 2208, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "aiogram.types.Message", "line_number": 13, "usage_type": "attribute"}, {"api_name": "aiogram.types", "line_number": 13, "usage_type": "name"}, {"api_name": "bot.data.alchemy.DML.find_userdata_by_id", "line_number": 21, "usage_type": "call"}, {"api_name": "bot.data.alchemy.DML.find_text_string", "line_number": 23, "usage_type": "call"}, {"api_name": "bot.data.alchemy.DML.create_new_user", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 27, "usage_type": "name"}, {"api_name": "bot.data.alchemy.DML.find_text_string", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.datetime.strftime", "line_number": 33, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 33, "usage_type": "name"}, {"api_name": "bot.data.alchemy.DML.update_user_data", "line_number": 35, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 35, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 35, "usage_type": "name"}, {"api_name": "bot.keyboards.user_keyboards.get_main_keyboard", "line_number": 38, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 40, "usage_type": "call"}, {"api_name": "bot.midleware.middleware.rate_limit", "line_number": 12, "usage_type": "call"}, {"api_name": "aiogram.types.callback_query", "line_number": 44, "usage_type": "attribute"}, {"api_name": "aiogram.types", "line_number": 44, "usage_type": "name"}, {"api_name": "bot.data.alchemy.DML.find_text_string", "line_number": 52, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 54, "usage_type": "call"}, {"api_name": "bot.midleware.middleware.rate_limit", "line_number": 43, "usage_type": "call"}, {"api_name": "aiogram.Dispatcher", "line_number": 57, "usage_type": "name"}]} +{"seq_id": "17975594516", "text": "import random\nimport mysql.connector\nfrom faker import Faker\n\n# Initialize faker\nfake = Faker()\n\nconn = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"\",\n database=\"mycart\"\n)\ncursor = conn.cursor()\n\n# Generate random dummy data for vendors\ndef generate_vendor_data(num_vendors):\n registration = []\n for vendor_id in range(1, num_vendors + 1):\n first_name = fake.first_name()\n last_name = fake.last_name()\n address = fake.address()\n email = fake.email()\n registration.append((vendor_id, first_name, last_name, address, email))\n return registration\n\n# Insert data into MySQL database\ndef insert_registration_into_mysql(registration):\n # Create a table if it doesn't exist\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS registration(\n vendor_id INT PRIMARY KEY,\n first_name VARCHAR(25),\n last_name VARCHAR(25),\n address VARCHAR(100),\n email VARCHAR(255)\n )\n ''')\n\n # Insert vendor data into the table\n insert_query = \"INSERT INTO registration (vendor_id, first_name, last_name, address, email) VALUES (%s, %s, %s, %s, %s)\"\n cursor.executemany(insert_query, registration)\n\n conn.commit()\n\n# Number of registration to generate\nnum_registration = 50\nvendor_data = generate_vendor_data(num_registration)\ninsert_registration_into_mysql(vendor_data)\n\n# Close the cursor and connection\ncursor.close()\nconn.close()\n", "repo_name": "shubham21222/Python-Database-Creation-Script", "sub_path": "sql_database.py", "file_name": "sql_database.py", "file_ext": "py", "file_size_in_byte": 1473, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "faker.Faker", "line_number": 6, "usage_type": "call"}, {"api_name": "mysql.connector.connector.connect", "line_number": 8, "usage_type": "call"}, {"api_name": "mysql.connector.connector", "line_number": 8, "usage_type": "attribute"}, {"api_name": "mysql.connector", "line_number": 8, "usage_type": "name"}]} +{"seq_id": "40070781165", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 30 01:24:37 2020\r\n\r\n@author: Jie.Hu\r\n\"\"\"\r\n\r\n\r\n\r\n''' 5: Decision Tree'''\r\nfrom sklearn.metrics import roc_auc_score, f1_score, accuracy_score, classification_report\r\nfrom sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score, GridSearchCV\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nclf_dt = DecisionTreeClassifier(random_state = 1337)\r\nclf_dt.fit(X, y)\r\n\r\n\r\ncv = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=1337)\r\nacc = cross_val_score(estimator = clf_dt, X = X, y = y, cv = cv, scoring='f1')\r\nacc.mean(), acc.std()\r\n\r\n\r\nparameters = {'criterion':['gini', 'entropy'],\r\n 'max_depth':[3,4,5],\r\n 'max_features':['auto', 'sqrt', 'log2'],\r\n 'min_samples_leaf':[1,2,3,4,5],\r\n 'min_samples_split':[2,4,6,8,9,10],\r\n 'class_weight':[{0:3,1:1}, {0:2,1:1}, {0:1,1:1}, {0:1,1:2}, {0:1,1:3}, 'balanced']}\r\n \r\ngrid_search = GridSearchCV(estimator = clf_dt,\r\n param_grid = parameters,\r\n scoring='f1',\r\n cv = cv,\r\n n_jobs = -1)\r\nstart_time = time.time()\r\ngrid_search = grid_search.fit(X, y)\r\nprint('Training time: {} minutes'.format(round((time.time() - start_time)/60, 2)))\r\ngrid_search.best_params_, grid_search.best_score_\r\n\r\n\r\n# last step\r\nclf_dt = DecisionTreeClassifier(criterion = 'gini',\r\n max_depth = 5, \r\n max_leaf_nodes = 10,\r\n max_features = 'auto',\r\n min_samples_leaf = 2,\r\n min_samples_split = 8,\r\n class_weight = {0: 1, 1: 3},\r\n random_state= 1337 )\r\nclf_dt.fit(X, y)\r\ny_pred = clf_dt.predict(X)\r\n\r\nacc = cross_val_score(estimator = clf_dt, X = X, y = y, cv = cv, scoring='f1')\r\nacc.mean(), acc.std()\r\n\r\nprint(classification_report(y, y_pred))\r\n\r\n\r\n# feature importance\r\nfi = clf_dt.feature_importances_\r\npredictors = [x for x in df.iloc[:, 2:].columns]\r\nfeat_imp = pd.Series(fi, predictors).sort_values(ascending=False)\r\nfeat_imp.plot(kind='bar', title='Feature Importances')\r\nplt.ylabel('Feature Importance Score')\r\n\r\nsub = pd.DataFrame({\"Attribute\": df.iloc[:, 2:].columns, \r\n \"Coefficient\": clf_dt.feature_importances_,\r\n \"Impact Index\": clf_dt.feature_importances_/(np.mean(clf_dt.feature_importances_))*100}).sort_values(by='Impact Index', ascending=False)\r\nsub.to_csv('C:/Users/Jie.Hu/Desktop/Driver Analysis/0420/DA_outputs_dt.csv', index=False)\r\n\r\n\r\n\r\nfrom sklearn.tree import export_graphviz\r\nfrom sklearn.externals.six import StringIO \r\nfrom IPython.display import Image \r\nimport pydotplus\r\n\r\nfeature_cols = df.iloc[:,2:].columns\r\n\r\ndot_data = StringIO()\r\n\r\nexport_graphviz(clf_dt, \r\n out_file=dot_data, \r\n filled=True, \r\n rounded=True,\r\n special_characters=True, \r\n feature_names = feature_cols, \r\n class_names=['Other','Top Box'])\r\ngraph = pydotplus.graph_from_dot_data(dot_data.getvalue()) \r\ngraph.write_png('explore.png')\r\nImage(graph.create_png())\r\n", "repo_name": "jieuhyl/Machine_Learning", "sub_path": "Supervised/Classification/DecisionTree_v1.py", "file_name": "DecisionTree_v1.py", "file_ext": "py", "file_size_in_byte": 3311, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 14, "usage_type": "call"}, {"api_name": "sklearn.model_selection.RepeatedStratifiedKFold", "line_number": 18, "usage_type": "call"}, {"api_name": "sklearn.model_selection.cross_val_score", "line_number": 19, "usage_type": "call"}, {"api_name": "sklearn.model_selection.GridSearchCV", "line_number": 30, "usage_type": "call"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 42, "usage_type": "call"}, {"api_name": "sklearn.model_selection.cross_val_score", "line_number": 53, "usage_type": "call"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 56, "usage_type": "call"}, {"api_name": "sklearn.externals.six.StringIO", "line_number": 80, "usage_type": "call"}, {"api_name": "sklearn.tree.export_graphviz", "line_number": 82, "usage_type": "call"}, {"api_name": "pydotplus.graph_from_dot_data", "line_number": 89, "usage_type": "call"}, {"api_name": "IPython.display.Image", "line_number": 91, "usage_type": "call"}]} +{"seq_id": "69819709490", "text": "from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nfrom django.conf import settings\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'dblog.views.home', name='home'),\n # url(r'^dblog/', include('dblog.foo.urls')),\n # Uncomment the admin/doc line below to enable admin documentation:\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n url(r'^comments/', include('django.contrib.comments.urls')),\n\n url(r'^static/(?P.*)$', 'django.views.static.serve',\n {'document_root': settings.STATIC_ROOT}),\n url(r'^$', 'blog.views.blog_list', name='blog_list'),\n url(r'^blog/', include('blog.urls')),\n)\n", "repo_name": "huchunxu/dblog", "sub_path": "dblog/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 856, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 14, "dataset": "github-code", "pt": "20", "api": [{"api_name": "django.contrib.admin.autodiscover", "line_number": 7, "usage_type": "call"}, {"api_name": "django.contrib.admin", "line_number": 7, "usage_type": "name"}, {"api_name": "django.conf.urls.patterns", "line_number": 9, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 14, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 14, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 16, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 16, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 16, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 16, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 17, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 17, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 19, "usage_type": "call"}, {"api_name": "django.conf.settings.STATIC_ROOT", "line_number": 20, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 20, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 21, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 22, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 22, "usage_type": "call"}]} +{"seq_id": "30463637155", "text": "from typing import List\n\nresult: List[str] = [\"\", \"\", \"\"] # instead of [] with later append\nheaders: List[str] = input().split(\",\")\nfor i in range(3): # instad of with open(infile, 'r')\n line: List[str] = input().split(\",\")\n if len(line) < len(headers): # != as < and >\n raise ValueError # different error\n if len(line) > len(headers):\n raise ValueError # different error\n result[i]: str = line # instead of (headers, line)\nprint(result) # print instead of return\n", "repo_name": "smadelineth/Lyra", "sub_path": "data_quality/examples_rewritten/homeworks/cis192/tadas412_csv_to_dict.py", "file_name": "tadas412_csv_to_dict.py", "file_ext": "py", "file_size_in_byte": 497, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "20", "api": [{"api_name": "typing.List", "line_number": 3, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 4, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 6, "usage_type": "name"}]} +{"seq_id": "73452886450", "text": "import os\nimport collections\nimport numpy as np\n\ndSpritesDataset = collections.namedtuple('dSpritesDataset', field_names=['images', 's_sizes', 's_dim', 's_bases'])\n\n\n#\n# Singleton to access datasets.\n#\nclass DataSet:\n\n instance = {}\n\n @staticmethod\n def get(images_archive):\n \"\"\"\n Getter\n :param images_archive: the file in which the dataset is stored\n :return: an object containing the dSprite dataset\n \"\"\"\n file_name = os.path.basename(images_archive)\n if file_name not in DataSet.instance.keys():\n loaders = {\n \"dsprites.npz\": DataSet.load_sprites_dataset,\n \"pong-v5.npz\": DataSet.load_openai_dataset,\n \"boxing-v5.npz\": DataSet.load_openai_dataset\n }\n DataSet.instance[file_name] = loaders[file_name](images_archive)\n return DataSet.instance[file_name]\n\n @staticmethod\n def load_sprites_dataset(images_archive):\n dataset = np.load(images_archive, allow_pickle=True, encoding='latin1')\n images = dataset['imgs'].reshape(-1, 64, 64, 1)\n metadata = dataset['metadata'][()]\n s_sizes = metadata['latents_sizes'] # [1 3 6 40 32 32]\n s_dim = s_sizes.size\n s_bases = np.concatenate((metadata['latents_sizes'][::-1].cumprod()[::-1][1:], np.array([1, ])))\n s_bases = np.squeeze(s_bases) # self.s_bases = [737280 245760 40960 1024 32]\n return dSpritesDataset(images, s_sizes, s_dim, s_bases)\n\n @staticmethod\n def load_openai_dataset(images_archive):\n dataset = np.load(images_archive, allow_pickle=True, encoding='latin1')\n return dSpritesDataset(dataset['images'].reshape(-1, 64, 64, 1), None, None, None)\n\n", "repo_name": "ChampiB/Deep_Active_Inference_Tasks", "sub_path": "singletons/DataSet.py", "file_name": "DataSet.py", "file_ext": "py", "file_size_in_byte": 1728, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "collections.namedtuple", "line_number": 5, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 45, "usage_type": "call"}]} +{"seq_id": "24180595909", "text": "\nimport pytest\nimport random\nimport time\nimport uhal\n\n\nuhal.setLogLevelTo( uhal.LogLevel.NOTICE )\n\n\n@pytest.fixture\ndef hw(pytestconfig):\n hwInterface = uhal.getDevice(\"hw\", pytestconfig.getoption(\"client\"), pytestconfig.getoption(\"addr\"))\n hwInterface.setTimeoutPeriod(10000)\n return hwInterface\n\n\ndef reset(csr_node):\n csr_node.getNode('rst').write(1)\n csr_node.getNode('rst').write(0)\n csr_node.getClient().dispatch()\n csr_node.getNode('ctr_rst').write(1)\n csr_node.getNode('ctr_rst').write(0)\n csr_node.getClient().dispatch()\n\nclass Controller:\n\n def __init__(self, testctrl_node, ctr_node, slave_idx, num, width=1, ported = False, expected = None, writeable=False, wraparound=False, reset_on_read=False):\n self._testctrl_node = testctrl_node\n self._ctr_node = ctr_node\n self._num = num\n self._width = width\n self._max_value = 2 ** (32*self._width) - 1\n self._slave_idx = slave_idx\n self._values_current = [0] * num if expected is None else expected\n self._values_sampled = [0] * num if expected is None else expected\n self._values_written = [0] * num\n self._ported = ported\n self._limit = not wraparound\n self._reset_on_read = reset_on_read\n self._writeable = writeable\n\n def increment(self, channel_mask, count, sleep=0):\n assert abs(count) < 0x10000000\n assert channel_mask < 2 ** (self._num + 1)\n self._testctrl_node.getNode('mask.channel').write(channel_mask)\n self._testctrl_node.getNode('mask.slave').write(2 ** self._slave_idx)\n self._testctrl_node.getNode('action.type').write(1 if count > 0 else 0)\n self._testctrl_node.getNode('action.wait').write(sleep)\n self._testctrl_node.getNode('action.count').write(abs(count))\n self._testctrl_node.getNode('start').write(1)\n self._testctrl_node.getClient().dispatch()\n self._testctrl_node.getNode('start').write(0)\n self._testctrl_node.getClient().dispatch()\n\n while True:\n active = self._testctrl_node.getNode('active').read()\n self._testctrl_node.getClient().dispatch()\n if not active:\n break\n time.sleep(1)\n\n for i in range(self._num):\n if (2 ** i) & channel_mask:\n self._values_current[i] += count\n if count < 0 and self._values_current[i] < 0:\n if self._limit:\n self._values_current[i] = 0\n else:\n self._values_current[i] += self._max_value + 1\n elif count > 0 and self._values_current[i] > self._max_value:\n if self._limit:\n self._values_current[i] = self._max_value\n else:\n self._values_current[i] -= (self._max_value + 1)\n\n\n def decrement(self, channel_mask, count, sleep=0):\n self.increment(channel_mask, -count, sleep)\n\n\n def set_values(self, values):\n assert len(values) == self._num\n self._values_current = values\n\n def update_sampled(self):\n for i in range(len(self._values_current)):\n self._values_sampled[i] = self._values_current[i]\n\n def read_value(self, i):\n assert i < self._num\n\n if self._ported:\n self._ctr_node.getNode('addr').write(i * self._width)\n xx = self._ctr_node.getNode('ctrs').readBlock(self._width)\n else:\n xx = self._ctr_node.getNode('ctrs').readBlockOffset(self._width, i * self._width)\n self._ctr_node.getClient().dispatch()\n\n if i == 0:\n self.update_sampled()\n if self._reset_on_read:\n self._values_current = [0] * self._num\n return sum([x * (2**(32*i)) for (i,x) in enumerate(xx)])\n\n def read_values(self, offset=0):\n if offset >= self._num:\n return []\n\n if self._ported:\n self._ctr_node.getNode('addr').write(offset * self._width)\n xx = self._ctr_node.getNode('ctrs').readBlock((self._num - offset) * self._width)\n else:\n xx = self._ctr_node.getNode('ctrs').readBlockOffset((self._num - offset) * self._width, offset * self._width)\n self._ctr_node.getClient().dispatch()\n\n values = [0] * (self._num - offset)\n for i in range(self._num - offset):\n for j in range(self._width):\n values[i] += xx[i * self._width + j] * (2 ** (32*j)) \n\n if offset == 0:\n self.update_sampled()\n if self._reset_on_read:\n self._values_current = [0] * self._num\n return values\n\n def write_value(self, i, x):\n assert i < self._num\n assert x > 0\n assert x <= self._max_value\n\n # Break up value in individual 32-bit words\n xx = [(x >> (32 * j)) & 0xFFFFFFFF for j in range(self._width)]\n\n if self._ported:\n self._ctr_node.getNode('addr').write(i * self._width)\n self._ctr_node.getNode('ctrs').writeBlock(xx)\n else:\n self._ctr_node.getNode('refs').writeBlockOffset(xx, i * self._width)\n self._ctr_node.getClient().dispatch()\n\n self._values_written[i] = x\n if i == (self._num - 1):\n for j in range(self._num):\n self._values_current[j] = self._values_written[j]\n\n def write_values(self, values):\n assert len(values) == self._num\n assert all(x > 0 for x in values)\n assert all(x <= self._max_value for x in values)\n\n # Break up all values into individual 32-bit words\n xx = []\n for x in values:\n xx += [(x >> (32 * j)) & 0xFFFFFFFF for j in range(self._width)]\n\n if self._ported:\n self._ctr_node.getNode('addr').write(0)\n self._ctr_node.getNode('ctrs').writeBlock(xx)\n else:\n self._ctr_node.getNode('refs').writeBlock(xx)\n self._ctr_node.getClient().dispatch()\n\n self._values_written = list(values)\n for i in range(self._num):\n self._values_current[i] = self._values_written[i]\n\n\n def check_values(self, incl_presample=True):\n # N.B. All counters are sampled when the first one is read\n\n # Part A: If more than one counter, read all counters except for first, to check they still have the last sampled value\n if incl_presample and self._num > 1:\n for i in range(1, self._num):\n x = self.read_value(i)\n assert x == self._values_sampled[i], \"Slave '{}' [{}], counter {} (pre-sample): Expected {}, but read {}\".format(self._ctr_node.getPath(), self._slave_idx, i, self._values_sampled[i], x)\n\n for i in range(self._num - 1, 0, -1):\n x = self.read_value(i)\n assert x == self._values_sampled[i], \"Slave '{}' [{}], counter {} (pre-sample): Expected {}, but read {}\".format(self._ctr_node.getPath(), self._slave_idx, i, self._values_sampled[i], x)\n\n xx = self.read_values(offset=1)\n for i in range(1, self._num):\n assert xx[i - 1] == self._values_sampled[i], \"Slave '{}' [{}], counter {} (pre-sample): Expected {}, but read {}\".format(self._ctr_node.getPath(), self._slave_idx, i, self._values_sampled[i], xx[i - 1])\n\n # Part B: Check values after sampling\n for i in range(self._num):\n x = self.read_value(i)\n assert x == self._values_sampled[i], \"Slave '{}' [{}], counter {}: Expected {}, but read {}\".format(self._ctr_node.getPath(), self._slave_idx, i, self._values_sampled[i], x)\n\n for i in range(self._num - 1, -1, -1):\n x = self.read_value(i)\n assert x == self._values_sampled[i], \"Slave '{}' [{}], counter {}: Expected {}, but read {}\".format(self._ctr_node.getPath(), self._slave_idx, i, self._values_sampled[i], x)\n\n xx = self.read_values()\n for i in range(self._num):\n assert xx[i] == self._values_sampled[i], \"Slave '{}' [{}], counter {}: Expected {}, but read {}\".format(self._ctr_node.getPath(), self._slave_idx, i, self._values_sampled[i], xx[i])\n\n return xx\n\n\n def run_tests(self, csr_node):\n\n # PART A: Check that counter = 0 after reset\n reset(csr_node)\n self.set_values([0] * self._num)\n self.check_values(incl_presample=False)\n\n reset(csr_node)\n self.check_values()\n\n\n # PART B: Increment & decrement each counter individually a few times\n for i in range(self._num):\n reset(csr_node)\n self.set_values([0] * self._num)\n self.check_values()\n channel_mask = 2 ** i\n\n # a. Increment a few times, checking counter value\n self.increment(channel_mask, 1)\n self.check_values()\n\n self.increment(channel_mask, 1)\n self.check_values()\n\n self.increment(channel_mask, 3)\n self.check_values()\n\n self.increment(channel_mask, 54)\n self.check_values()\n\n # b. Decrement a few times, checking counter value\n self.decrement(channel_mask, 1)\n self.check_values()\n\n self.decrement(channel_mask, 3)\n self.check_values()\n\n # c. Decrement counter below 0\n self.decrement(channel_mask, 54)\n assert self.check_values()[i] == (1 if not self._reset_on_read else 0)\n\n self.decrement(channel_mask, 10)\n self.check_values()\n\n self.decrement(channel_mask, 1)\n self.check_values()\n\n\n # PART C: Increment & decrement multiple counters at the same time\n if self._num > 1:\n # 1. Increment each counter a few times, checking counter value\n self.increment(0b1, 1)\n self.check_values()\n\n self.increment(0b1, 1)\n self.increment(0b0100100100100100 & ((2 ** self._num) - 1), 4)\n self.check_values()\n\n self.increment(0b1010101010101010 & ((2 ** self._num) - 1), 3)\n self.check_values()\n\n self.increment(2 ** (self._num - 1), 54)\n self.check_values()\n\n # 2. Decrement a few times, checking counter value\n self.decrement(0b1010101010101010 & ((2 ** self._num) - 1), 1)\n self.check_values()\n\n self.decrement(0b0101010101010101 & ((2 ** self._num) - 1), 1)\n self.check_values()\n\n self.decrement(0b1000100010001000 & ((2 ** self._num) - 1), 1)\n self.check_values()\n\n self.decrement(2 ** (self._num - 1), 15)\n self.check_values()\n\n\n # 3. Decrement counter below 0\n self.decrement(2 ** (self._num - 1), self.read_value(self._num - 1) - 1)\n assert self.check_values()[self._num - 1] == (1 if not self._reset_on_read else 0)\n assert all(x < 10 for x in self.check_values())\n\n self.decrement(2 ** (self._num - 1), 2)\n self.check_values()\n\n self.decrement(0b1010101010101010 & ((2 ** self._num) - 1), 5)\n self.check_values()\n\n self.decrement((2 ** self._num) - 1, 10)\n self.check_values()\n\n self.decrement(0b1, 42)\n self.check_values()\n\n\n # PART D: Reset counters by writing new values (skipped for read-only slaves)\n if self._writeable: \n\n for i in range(self._num):\n reset(csr_node)\n self.set_values([0] * self._num)\n self.check_values()\n channel_mask = 2 ** i\n\n # 1. Check that written values are not copied to counter registers\n # if value for last counter is not written\n for j in range(self._num - 1):\n self.write_value(j, 55 - j)\n self.check_values()\n self.increment(channel_mask, 1)\n self.check_values()\n self.decrement(channel_mask, 3)\n self.check_values()\n\n # 2. Increment a few times, checking counter value\n self.increment(channel_mask, 1)\n self.check_values()\n\n self.write_values([random.randint(0, self._max_value) for j in range(self._num)])\n self.increment(channel_mask, 1)\n self.check_values()\n \n self.increment(channel_mask, 3)\n self.check_values()\n\n self.write_values([random.randint(0, self._max_value) for j in range(self._num)])\n self.increment(channel_mask, 54)\n self.check_values()\n\n # Write value that's close to max value, to ensure incrementing past max value this time\n self.write_values([(self._max_value - j) for j in range(self._num)])\n self.increment(channel_mask, self._num + 3)\n\n # 3. Decrement a few times, checking counter value\n self.decrement(channel_mask, 1)\n self.check_values()\n\n self.write_values([random.randint(0, self._max_value) for j in range(self._num)])\n self.decrement(channel_mask, 3)\n self.check_values()\n\n # Write value that's close to 0, to ensure decrementing past 0 this time\n self.write_values([(self._num - j) for j in range(self._num)])\n self.decrement(channel_mask, self._num + 3)\n\n\n\n\n\n@pytest.mark.parametrize(\"idx,node_id,ported,params\", [\n (0, 'ctrs.block.small', False, {'num':1}),\n (1, 'ctrs.block.small_rw', False, {'num':1, 'writeable':True}),\n (2, 'ctrs.block.large', False, {'num':5}),\n (3, 'ctrs.block.large_wide', False, {'num':5, 'width':2}),\n (4, 'ctrs.block.large_wide_wraps', False, {'num':5, 'width':2, 'wraparound':True}),\n (5, 'ctrs.block.large_wide_readreset', False, {'num':5, 'width':2, 'reset_on_read':True}),\n (6, 'ctrs.block.large_wide_readreset_rw', False, {'num':5, 'width':2, 'reset_on_read':True, 'writeable':True}),\n (8, 'ctrs.ported.small', True, {'num':1}),\n (9, 'ctrs.ported.small_rw', True, {'num':1, 'writeable':True}),\n (10,'ctrs.ported.large', True, {'num':5}),\n (11,'ctrs.ported.large_wide', True, {'num':5, 'width':2}),\n (12,'ctrs.ported.large_wide_wraps', True, {'num':5, 'width':2, 'wraparound':True}),\n (13,'ctrs.ported.large_wide_readreset', True, {'num':5, 'width':2, 'reset_on_read':True}),\n (14,'ctrs.ported.large_wide_readreset_rw', True, {'num':5, 'width':2, 'reset_on_read':True, 'writeable':True}),\n ])\n\n\ndef test_slave_counter(hw, node_id, idx, ported, params):\n\n csr_node = hw.getNode('csr.ctrl')\n ctr_node = hw.getNode(node_id)\n ctrl = Controller(hw.getNode('testctrl'), ctr_node, idx, ported=ported, **params)\n\n ctrl.run_tests(hw.getNode('csr.ctrl'))\n", "repo_name": "ipbus/ipbus-firmware", "sub_path": "tests/ctr_slaves/scripts/test_ctr_slaves.py", "file_name": "test_ctr_slaves.py", "file_ext": "py", "file_size_in_byte": 15021, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 34, "dataset": "github-code", "pt": "20", "api": [{"api_name": "uhal.setLogLevelTo", "line_number": 8, "usage_type": "call"}, {"api_name": "uhal.LogLevel", "line_number": 8, "usage_type": "attribute"}, {"api_name": "uhal.getDevice", "line_number": 13, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 11, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 61, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 323, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 330, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 342, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 354, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 354, "usage_type": "attribute"}]} +{"seq_id": "15109668431", "text": "\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom .forms import SignupForm,Editpic\n\nfrom django.contrib.auth import authenticate,login,logout\nfrom django.contrib.auth.forms import AuthenticationForm\n# Create your views here.\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Album,Photo\n\n@login_required(login_url='/login/')\ndef gallery(request):\n scategory=request.GET.get('category')\n category=None\n \n user=request.user\n\n sidecategory=Album.objects.filter(user=user)\n if(scategory!=None):\n category=Album.objects.filter(user=user,title=scategory)\n else:\n category=Album.objects.filter(user=user)\n\n allpics=[]\n for i in category:\n \n allpics.append(Photo.objects.filter(category=i))\n \n photoobj=[]\n for i in allpics:\n for j in i:\n photoobj.append(j)\n \n if(scategory==None):\n scategory=\"ALL\"\n print(photoobj)\n print(category)\n context={\"album\":sidecategory,\"pics\":photoobj,'category':scategory}\n return render(request,'gallery.html',context)\n\n@login_required(login_url='/login/')\ndef viewphoto(request,pk):\n\n photo=Photo.objects.get(id=pk)\n \n return render(request,'photo.html',{\"photo\":photo})\n\n\n@login_required(login_url='/login/')\ndef addphoto(request):\n if(request.method=='POST'):\n data=request.POST\n category=None\n image=request.FILES.get('image')\n if(data['category']!='none'):\n print(data['category'])\n category=Album.objects.get(title=data['category'],user=request.user)\n print(category,type(category))\n print(\"album is\",request.user)\n elif(data['newcategory']!=''):\n category,created=Album.objects.get_or_create(title=data['newcategory'],user=request.user)\n else:\n category=None\n\n photo=Photo.objects.create(category=category,description=data['description'],title=data['title'],image=image)\n photo.save()\n \n return HttpResponseRedirect('/') \n \n \n category=Album.objects.filter(user=request.user)\n return render(request,'add.html',{\"category\":category})\n\ndef loginuser(request):\n if(request.method=='POST'):\n fm=AuthenticationForm(request=request,data=request.POST)\n if(fm.is_valid()):\n uname=fm.cleaned_data['username']\n pword=fm.cleaned_data['password']\n user=authenticate(username=uname,password=pword)\n if(user is not None):\n login(request,user)\n messages.success(request,'Welcome..We wish you have a wondeful experiencewith pixaStore')\n return HttpResponseRedirect('/')\n else:\n messages.error(request,'No Such User...plz Enter Correct Credentials') \n fm=AuthenticationForm()\n return render(request,'login.html',{'form':fm}) \n \n else:\n messages.error(request,'Plz enter valid data')\n fm=AuthenticationForm()\n return render(request,'login.html',{'form':fm}) \n\n fm=AuthenticationForm() \n return render(request,'login.html',{'form':fm})\n\ndef register(request):\n if(request.method=='POST'):\n fm=SignupForm(request.POST)\n if(fm.is_valid()):\n fm.save()\n messages.success(request,\"Account Created Successfully\")\n return HttpResponseRedirect('/login/')\n else:\n messages.error(request,'Username or password or email is invalid ..Plz enter corect details')\n return HttpResponseRedirect('/register/')\n\n\n fm=SignupForm()\n return render(request,'register.html',{'form':fm})\n\n\n@login_required(login_url='/login/')\ndef logoutuser(request):\n logout(request)\n messages.success(request,'Successfully Logged Out..Hope you had a Wonder Experience With PixaStore')\n return HttpResponseRedirect('/login/')\n\ndef deletePic(request,pk):\n pic=Photo.objects.get(id=pk)\n pic.delete()\n\n return HttpResponseRedirect('/')\n\ndef editpic(request,pk):\n\n if(request.method=='POST'):\n data=request.POST \n img=request.FILES.get('image') \n\n pic=Photo.objects.get(id=pk)\n\n edpic=Editpic(request.POST,request.FILES,instance=pic)\n edpic.save() \n return HttpResponseRedirect('/')\n\n pic=Photo.objects.get(id=pk)\n edpic=Editpic(instance=pic)\n return render(request,'editpic.html',{'pic':edpic})\n", "repo_name": "AnubhavChakrabortynits/imagegallery", "sub_path": "store/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 4516, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "models.Album.objects.filter", "line_number": 21, "usage_type": "call"}, {"api_name": "models.Album.objects", "line_number": 21, "usage_type": "attribute"}, {"api_name": "models.Album", "line_number": 21, "usage_type": "name"}, {"api_name": "models.Album.objects.filter", "line_number": 23, "usage_type": "call"}, {"api_name": "models.Album.objects", "line_number": 23, "usage_type": "attribute"}, {"api_name": "models.Album", "line_number": 23, "usage_type": "name"}, {"api_name": "models.Album.objects.filter", "line_number": 25, "usage_type": "call"}, {"api_name": "models.Album.objects", "line_number": 25, "usage_type": "attribute"}, {"api_name": "models.Album", "line_number": 25, "usage_type": "name"}, {"api_name": "models.Photo.objects.filter", "line_number": 30, "usage_type": "call"}, {"api_name": "models.Photo.objects", "line_number": 30, "usage_type": "attribute"}, {"api_name": "models.Photo", "line_number": 30, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 42, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 14, "usage_type": "call"}, {"api_name": "models.Photo.objects.get", "line_number": 47, "usage_type": "call"}, {"api_name": "models.Photo.objects", "line_number": 47, "usage_type": "attribute"}, {"api_name": "models.Photo", "line_number": 47, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 49, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 44, "usage_type": "call"}, {"api_name": "models.Album.objects.get", "line_number": 60, "usage_type": "call"}, {"api_name": "models.Album.objects", "line_number": 60, "usage_type": "attribute"}, {"api_name": "models.Album", "line_number": 60, "usage_type": "name"}, {"api_name": "models.Album.objects.get_or_create", "line_number": 64, "usage_type": "call"}, {"api_name": "models.Album.objects", "line_number": 64, "usage_type": "attribute"}, {"api_name": "models.Album", "line_number": 64, "usage_type": "name"}, {"api_name": "models.Photo.objects.create", "line_number": 68, "usage_type": "call"}, {"api_name": "models.Photo.objects", "line_number": 68, "usage_type": "attribute"}, {"api_name": "models.Photo", "line_number": 68, "usage_type": "name"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 71, "usage_type": "call"}, {"api_name": "models.Album.objects.filter", "line_number": 74, "usage_type": "call"}, {"api_name": "models.Album.objects", "line_number": 74, "usage_type": "attribute"}, {"api_name": "models.Album", "line_number": 74, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 75, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 52, "usage_type": "call"}, {"api_name": "django.contrib.auth.forms.AuthenticationForm", "line_number": 79, "usage_type": "call"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 83, "usage_type": "call"}, {"api_name": "django.contrib.auth.login", "line_number": 85, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 86, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 86, "usage_type": "name"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 87, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 89, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 89, "usage_type": "name"}, {"api_name": "django.contrib.auth.forms.AuthenticationForm", "line_number": 90, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 91, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 94, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 94, "usage_type": "name"}, {"api_name": "django.contrib.auth.forms.AuthenticationForm", "line_number": 95, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 96, "usage_type": "call"}, {"api_name": "django.contrib.auth.forms.AuthenticationForm", "line_number": 98, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 99, "usage_type": "call"}, {"api_name": "forms.SignupForm", "line_number": 103, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 106, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 106, "usage_type": "name"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 107, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 109, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 109, "usage_type": "name"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 110, "usage_type": "call"}, {"api_name": "forms.SignupForm", "line_number": 113, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 114, "usage_type": "call"}, {"api_name": "django.contrib.auth.logout", "line_number": 119, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 120, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 120, "usage_type": "name"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 121, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 117, "usage_type": "call"}, {"api_name": "models.Photo.objects.get", "line_number": 124, "usage_type": "call"}, {"api_name": "models.Photo.objects", "line_number": 124, "usage_type": "attribute"}, {"api_name": "models.Photo", "line_number": 124, "usage_type": "name"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 127, "usage_type": "call"}, {"api_name": "models.Photo.objects.get", "line_number": 135, "usage_type": "call"}, {"api_name": "models.Photo.objects", "line_number": 135, "usage_type": "attribute"}, {"api_name": "models.Photo", "line_number": 135, "usage_type": "name"}, {"api_name": "forms.Editpic", "line_number": 137, "usage_type": "call"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 139, "usage_type": "call"}, {"api_name": "models.Photo.objects.get", "line_number": 141, "usage_type": "call"}, {"api_name": "models.Photo.objects", "line_number": 141, "usage_type": "attribute"}, {"api_name": "models.Photo", "line_number": 141, "usage_type": "name"}, {"api_name": "forms.Editpic", "line_number": 142, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 143, "usage_type": "call"}]} +{"seq_id": "17650053320", "text": "import atexit\nfrom collections import namedtuple\nimport functools\nimport json\nimport logging\nimport multiprocessing\nimport os\nimport shutil\nimport sys\nimport tempfile\nimport time\nimport traceback\n\nfrom chromite.lib import gs\n\nimport common\nfrom autotest_lib.client.common_lib import error\nfrom autotest_lib.client.common_lib import host_states\nfrom autotest_lib.client.common_lib import time_utils\nfrom autotest_lib.client.common_lib import utils\nfrom autotest_lib.server import constants\nfrom autotest_lib.server import frontend\nfrom autotest_lib.server import hosts\nfrom autotest_lib.server.cros.dynamic_suite.constants import VERSION_PREFIX\nfrom autotest_lib.server.hosts import afe_store\nfrom autotest_lib.server.hosts import servo_host\nfrom autotest_lib.site_utils.deployment import commandline\nfrom autotest_lib.site_utils.stable_images import assign_stable_images\n\n\n_LOG_FORMAT = '%(asctime)s | %(levelname)-10s | %(message)s'\n\n_DEFAULT_POOL = constants.Labels.POOL_PREFIX + 'suites'\n\n_DIVIDER = '\\n============\\n'\n\n_LOG_BUCKET_NAME = 'chromeos-install-logs'\n\n_OMAHA_STATUS = 'gs://chromeos-build-release-console/omaha_status.json'\n\n# Lock reasons we'll pass when locking DUTs, depending on the\n# host's prior state.\n_LOCK_REASON_EXISTING = 'Repairing or deploying an existing host'\n_LOCK_REASON_NEW_HOST = 'Repairing or deploying a new host'\n\n_ReportResult = namedtuple('_ReportResult', ['hostname', 'message'])\n\n\nclass _NoAFEServoPortError(Exception):\n \"\"\"Exception when there is no servo port stored in the AFE.\"\"\"\n\n\nclass _MultiFileWriter(object):\n\n \"\"\"Group file objects for writing at once.\"\"\"\n\n def __init__(self, files):\n \"\"\"Initialize _MultiFileWriter.\n\n @param files Iterable of file objects for writing.\n \"\"\"\n self._files = files\n\n def write(self, s):\n \"\"\"Write a string to the files.\n\n @param s Write this string.\n \"\"\"\n for file in self._files:\n file.write(s)\n\n\ndef _get_upload_log_path(arguments):\n return 'gs://{bucket}/{name}'.format(\n bucket=_LOG_BUCKET_NAME,\n name=commandline.get_default_logdir_name(arguments))\n\n\ndef _upload_logs(dirpath, gspath):\n \"\"\"Upload report logs to Google Storage.\n\n @param dirpath Path to directory containing the logs.\n @param gspath Path to GS bucket.\n \"\"\"\n ctx = gs.GSContext()\n ctx.Copy(dirpath, gspath, recursive=True)\n\n\ndef _get_omaha_build(board):\n \"\"\"Get the currently preferred Beta channel build for `board`.\n\n Open and read through the JSON file provided by GoldenEye that\n describes what version Omaha is currently serving for all boards\n on all channels. Find the entry for `board` on the Beta channel,\n and return that version string.\n\n @param board The board to look up from GoldenEye.\n\n @return Returns a Chrome OS version string in standard form\n R##-####.#.#. Will return `None` if no Beta channel\n entry is found.\n \"\"\"\n ctx = gs.GSContext()\n omaha_status = json.loads(ctx.Cat(_OMAHA_STATUS))\n omaha_board = board.replace('_', '-')\n for e in omaha_status['omaha_data']:\n if (e['channel'] == 'beta' and\n e['board']['public_codename'] == omaha_board):\n milestone = e['chrome_version'].split('.')[0]\n build = e['chrome_os_version']\n return 'R%s-%s' % (milestone, build)\n return None\n\n\ndef _update_build(afe, report_log, arguments):\n \"\"\"Update the stable_test_versions table.\n\n This calls the `set_stable_version` RPC call to set the stable\n repair version selected by this run of the command. Additionally,\n this updates the stable firmware for the board. The repair version\n is selected from three possible versions:\n * The stable test version currently in the AFE database.\n * The version Omaha is currently serving as the Beta channel\n build.\n * The version supplied by the user.\n The actual version selected will be whichever of these three is\n the most up-to-date version.\n\n The stable firmware version will be set to whatever firmware is\n bundled in the selected repair image. If the selected repair image bundles\n firmware for more than one model, then the firmware for every model in the\n build will be updated.\n\n This function will log information about the available versions\n prior to selection. After selection the repair and firmware\n versions slected will be logged.\n\n @param afe AFE object for RPC calls.\n @param report_log File-like object for logging report output.\n @param arguments Command line arguments with options.\n\n @return Returns the version selected.\n \"\"\"\n # Gather the current AFE and Omaha version settings, and report them\n # to the user.\n cros_version_map = afe.get_stable_version_map(afe.CROS_IMAGE_TYPE)\n fw_version_map = afe.get_stable_version_map(afe.FIRMWARE_IMAGE_TYPE)\n afe_cros = cros_version_map.get_version(arguments.board)\n afe_fw = fw_version_map.get_version(arguments.board)\n omaha_cros = _get_omaha_build(arguments.board)\n report_log.write('AFE version is %s.\\n' % afe_cros)\n report_log.write('Omaha version is %s.\\n' % omaha_cros)\n report_log.write('AFE firmware is %s.\\n' % afe_fw)\n cros_version = afe_cros\n\n # Check whether we should upgrade the repair build to either\n # the Omaha or the user's requested build. If we do, we must\n # also update the firmware version.\n if (omaha_cros is not None\n and (cros_version is None or\n utils.compare_versions(cros_version, omaha_cros) < 0)):\n cros_version = omaha_cros\n if arguments.build and arguments.build != cros_version:\n if (cros_version is None\n or utils.compare_versions(cros_version, arguments.build) < 0):\n cros_version = arguments.build\n else:\n report_log.write('Selected version %s is too old; '\n 'using version %s'\n % (arguments.build, cros_version))\n\n afe_fw_versions = {arguments.board: afe_fw}\n fw_versions = assign_stable_images.get_firmware_versions(\n cros_version_map, arguments.board, cros_version)\n # At this point `cros_version` is our new repair build, and\n # `fw_version` is our new target firmware. Call the AFE back with\n # updates as necessary.\n if not arguments.nostable:\n if cros_version != afe_cros:\n cros_version_map.set_version(arguments.board, cros_version)\n\n if fw_versions != afe_fw_versions:\n for model, fw_version in fw_versions.iteritems():\n if fw_version is not None:\n fw_version_map.set_version(model, fw_version)\n else:\n fw_version_map.delete_version(model)\n\n # Report the new state of the world.\n report_log.write(_DIVIDER)\n report_log.write('Repair CrOS version for board %s is now %s.\\n' %\n (arguments.board, cros_version))\n for model, fw_version in fw_versions.iteritems():\n report_log.write('Firmware version for model %s is now %s.\\n' %\n (model, fw_version))\n return cros_version\n\n\ndef _create_host(hostname, afe, afe_host):\n \"\"\"Create a CrosHost object for a DUT to be installed.\n\n @param hostname Hostname of the target DUT.\n @param afe A frontend.AFE object.\n @param afe_host AFE Host object for the DUT.\n \"\"\"\n machine_dict = {\n 'hostname': hostname,\n 'afe_host': afe_host,\n 'host_info_store': afe_store.AfeStore(hostname, afe),\n }\n servo_args = hosts.CrosHost.get_servo_arguments({})\n return hosts.create_host(machine_dict, servo_args=servo_args)\n\n\ndef _try_lock_host(afe_host):\n \"\"\"Lock a host in the AFE, and report whether it succeeded.\n\n The lock action is logged regardless of success; failures are\n logged if they occur.\n\n @param afe_host AFE Host instance to be locked.\n\n @return `True` on success, or `False` on failure.\n \"\"\"\n try:\n logging.warning('Locking host now.')\n afe_host.modify(locked=True,\n lock_reason=_LOCK_REASON_EXISTING)\n except Exception as e:\n logging.exception('Failed to lock: %s', e)\n return False\n return True\n\n\ndef _try_unlock_host(afe_host):\n \"\"\"Unlock a host in the AFE, and report whether it succeeded.\n\n The unlock action is logged regardless of success; failures are\n logged if they occur.\n\n @param afe_host AFE Host instance to be unlocked.\n\n @return `True` on success, or `False` on failure.\n \"\"\"\n try:\n logging.warning('Unlocking host.')\n afe_host.modify(locked=False, lock_reason='')\n except Exception as e:\n logging.exception('Failed to unlock: %s', e)\n return False\n return True\n\n\ndef _update_host_attributes(afe, hostname, host_attrs):\n \"\"\"Update the attributes for a given host.\n\n @param afe AFE object for RPC calls.\n @param hostname Host name of the DUT.\n @param host_attrs Dictionary with attributes to be applied to the\n host.\n \"\"\"\n # Grab the servo hostname/port/serial from `host_attrs` if supplied.\n # For new servo V4 deployments, we require the user to supply the\n # attributes (because there are no appropriate defaults). So, if\n # none are supplied, we assume it can't be V4, and apply the\n # defaults for servo V3.\n host_attr_servo_host = host_attrs.get(servo_host.SERVO_HOST_ATTR)\n host_attr_servo_port = host_attrs.get(servo_host.SERVO_PORT_ATTR)\n host_attr_servo_serial = host_attrs.get(servo_host.SERVO_SERIAL_ATTR)\n servo_hostname = (host_attr_servo_host or\n servo_host.make_servo_hostname(hostname))\n servo_port = (host_attr_servo_port or\n str(servo_host.ServoHost.DEFAULT_PORT))\n afe.set_host_attribute(servo_host.SERVO_HOST_ATTR,\n servo_hostname,\n hostname=hostname)\n afe.set_host_attribute(servo_host.SERVO_PORT_ATTR,\n servo_port,\n hostname=hostname)\n if host_attr_servo_serial:\n afe.set_host_attribute(servo_host.SERVO_SERIAL_ATTR,\n host_attr_servo_serial,\n hostname=hostname)\n\n\ndef _get_afe_host(afe, hostname, host_attrs, arguments):\n \"\"\"Get an AFE Host object for the given host.\n\n If the host is found in the database, return the object\n from the RPC call with the updated attributes in host_attr_dict.\n\n If no host is found, create one with appropriate servo\n attributes and the given board label.\n\n @param afe AFE object for RPC calls.\n @param hostname Host name of the DUT.\n @param host_attrs Dictionary with attributes to be applied to the\n host.\n @param arguments Command line arguments with options.\n\n @return A tuple of the afe_host, plus a flag. The flag indicates\n whether the Host should be unlocked if subsequent operations\n fail. (Hosts are always unlocked after success).\n \"\"\"\n hostlist = afe.get_hosts([hostname])\n unlock_on_failure = False\n if hostlist:\n afe_host = hostlist[0]\n if not afe_host.locked:\n if _try_lock_host(afe_host):\n unlock_on_failure = True\n else:\n raise Exception('Failed to lock host')\n if afe_host.status not in host_states.IDLE_STATES:\n if unlock_on_failure and not _try_unlock_host(afe_host):\n raise Exception('Host is in use, and failed to unlock it')\n raise Exception('Host is in use by Autotest')\n # This host was pre-existing; if the user didn't supply\n # attributes, don't update them, because the defaults may\n # not be correct.\n if host_attrs:\n _update_host_attributes(afe, hostname, host_attrs)\n else:\n afe_host = afe.create_host(hostname,\n locked=True,\n lock_reason=_LOCK_REASON_NEW_HOST)\n afe_host.add_labels([constants.Labels.BOARD_PREFIX + arguments.board])\n _update_host_attributes(afe, hostname, host_attrs)\n afe_host = afe.get_hosts([hostname])[0]\n return afe_host, unlock_on_failure\n\n\ndef _install_firmware(host):\n \"\"\"Install dev-signed firmware after removing write-protect.\n\n At start, it's assumed that hardware write-protect is disabled,\n the DUT is in dev mode, and the servo's USB stick already has a\n test image installed.\n\n The firmware is installed by powering on and typing ctrl+U on\n the keyboard in order to boot the the test image from USB. Once\n the DUT is booted, we run a series of commands to install the\n read-only firmware from the test image. Then we clear debug\n mode, and shut down.\n\n @param host Host instance to use for servo and ssh operations.\n \"\"\"\n servo = host.servo\n # First power on. We sleep to allow the firmware plenty of time\n # to display the dev-mode screen; some boards take their time to\n # be ready for the ctrl+U after power on.\n servo.get_power_state_controller().power_off()\n servo.switch_usbkey('dut')\n servo.get_power_state_controller().power_on()\n time.sleep(10)\n # Dev mode screen should be up now: type ctrl+U and wait for\n # boot from USB to finish.\n servo.ctrl_u()\n if not host.wait_up(timeout=host.USB_BOOT_TIMEOUT):\n raise Exception('DUT failed to boot in dev mode for '\n 'firmware update')\n # Disable software-controlled write-protect for both FPROMs, and\n # install the RO firmware.\n for fprom in ['host', 'ec']:\n host.run('flashrom -p %s --wp-disable' % fprom,\n ignore_status=True)\n host.run('chromeos-firmwareupdate --mode=factory')\n # Get us out of dev-mode and clear GBB flags. GBB flags are\n # non-zero because boot from USB was enabled.\n host.run('/usr/share/vboot/bin/set_gbb_flags.sh 0',\n ignore_status=True)\n host.run('crossystem disable_dev_request=1',\n ignore_status=True)\n host.halt()\n\n\ndef _install_test_image(host, arguments):\n \"\"\"Install a test image to the DUT.\n\n Install a stable test image on the DUT using the full servo\n repair flow.\n\n @param host Host instance for the DUT being installed.\n @param arguments Command line arguments with options.\n \"\"\"\n # Don't timeout probing for the host usb device, there could be a bunch\n # of servos probing at the same time on the same servo host. And\n # since we can't pass None through the xml rpcs, use 0 to indicate None.\n if not host.servo.probe_host_usb_dev(timeout=0):\n raise Exception('No USB stick detected on Servo host')\n try:\n if not arguments.noinstall:\n if not arguments.nostage:\n host.servo.image_to_servo_usb(\n host.stage_image_for_servo())\n if arguments.full_deploy:\n _install_firmware(host)\n host.servo_install()\n except error.AutoservRunError as e:\n logging.exception('Failed to install: %s', e)\n raise Exception('chromeos-install failed')\n finally:\n host.close()\n\n\ndef _install_and_update_afe(afe, hostname, host_attrs, arguments):\n \"\"\"Perform all installation and AFE updates.\n\n First, lock the host if it exists and is unlocked. Then,\n install the test image on the DUT. At the end, unlock the\n DUT, unless the installation failed and the DUT was locked\n before we started.\n\n If installation succeeds, make sure the DUT is in the AFE,\n and make sure that it has basic labels.\n\n @param afe AFE object for RPC calls.\n @param hostname Host name of the DUT.\n @param host_attrs Dictionary with attributes to be applied to the\n host.\n @param arguments Command line arguments with options.\n \"\"\"\n afe_host, unlock_on_failure = _get_afe_host(afe, hostname, host_attrs,\n arguments)\n try:\n host = _create_host(hostname, afe, afe_host)\n _install_test_image(host, arguments)\n host.labels.update_labels(host)\n platform_labels = afe.get_labels(\n host__hostname=hostname, platform=True)\n if not platform_labels:\n platform = host.get_platform()\n new_labels = afe.get_labels(name=platform)\n if not new_labels:\n afe.create_label(platform, platform=True)\n afe_host.add_labels([platform])\n version = [label for label in afe_host.labels\n if label.startswith(VERSION_PREFIX)]\n if version:\n afe_host.remove_labels(version)\n except Exception as e:\n if unlock_on_failure and not _try_unlock_host(afe_host):\n logging.error('Failed to unlock host!')\n raise\n\n if not _try_unlock_host(afe_host):\n raise Exception('Install succeeded, but failed to unlock the DUT.')\n\n\ndef _install_dut(arguments, host_attr_dict, hostname):\n \"\"\"Deploy or repair a single DUT.\n\n @param arguments Command line arguments with options.\n @param host_attr_dict Dict mapping hostnames to attributes to be\n stored in the AFE.\n @param hostname Host name of the DUT to install on.\n\n @return On success, return `None`. On failure, return a string\n with an error message.\n \"\"\"\n # In some cases, autotest code that we call during install may\n # put stuff onto stdout with 'print' statements. Most notably,\n # the AFE frontend may print 'FAILED RPC CALL' (boo, hiss). We\n # want nothing from this subprocess going to the output we\n # inherited from our parent, so redirect stdout and stderr, before\n # we make any AFE calls. Note that this is reasonable because we're\n # in a subprocess.\n\n logpath = os.path.join(arguments.logdir, hostname + '.log')\n logfile = open(logpath, 'w')\n sys.stderr = sys.stdout = logfile\n _configure_logging_to_file(logfile)\n\n afe = frontend.AFE(server=arguments.web)\n try:\n _install_and_update_afe(afe, hostname,\n host_attr_dict.get(hostname, {}),\n arguments)\n except Exception as e:\n logging.exception('Original exception: %s', e)\n return str(e)\n return None\n\n\ndef _report_hosts(report_log, heading, host_results_list):\n \"\"\"Report results for a list of hosts.\n\n To improve visibility, results are preceded by a header line,\n followed by a divider line. Then results are printed, one host\n per line.\n\n @param report_log File-like object for logging report\n output.\n @param heading The header string to be printed before\n results.\n @param host_results_list A list of _ReportResult tuples\n to be printed one per line.\n \"\"\"\n if not host_results_list:\n return\n report_log.write(heading)\n report_log.write(_DIVIDER)\n for result in host_results_list:\n report_log.write('{result.hostname:30} {result.message}\\n'\n .format(result=result))\n report_log.write('\\n')\n\n\ndef _report_results(afe, report_log, hostnames, results):\n \"\"\"Gather and report a summary of results from installation.\n\n Segregate results into successes and failures, reporting\n each separately. At the end, report the total of successes\n and failures.\n\n @param afe AFE object for RPC calls.\n @param report_log File-like object for logging report output.\n @param hostnames List of the hostnames that were tested.\n @param results List of error messages, in the same order\n as the hostnames. `None` means the\n corresponding host succeeded.\n \"\"\"\n successful_hosts = []\n success_reports = []\n failure_reports = []\n for result, hostname in zip(results, hostnames):\n if result is None:\n successful_hosts.append(hostname)\n else:\n failure_reports.append(_ReportResult(hostname, result))\n if successful_hosts:\n afe.reverify_hosts(hostnames=successful_hosts)\n for h in afe.get_hosts(hostnames=successful_hosts):\n for label in h.labels:\n if label.startswith(constants.Labels.POOL_PREFIX):\n result = _ReportResult(h.hostname,\n 'Host already in %s' % label)\n success_reports.append(result)\n break\n else:\n h.add_labels([_DEFAULT_POOL])\n result = _ReportResult(h.hostname,\n 'Host added to %s' % _DEFAULT_POOL)\n success_reports.append(result)\n report_log.write(_DIVIDER)\n _report_hosts(report_log, 'Successes', success_reports)\n _report_hosts(report_log, 'Failures', failure_reports)\n report_log.write(\n 'Installation complete: %d successes, %d failures.\\n' %\n (len(success_reports), len(failure_reports)))\n\n\ndef _clear_root_logger_handlers():\n \"\"\"Remove all handlers from root logger.\"\"\"\n root_logger = logging.getLogger()\n for h in root_logger.handlers:\n root_logger.removeHandler(h)\n\n\ndef _configure_logging_to_file(logfile):\n \"\"\"Configure the logging module for `install_duts()`.\n\n @param log_file Log file object.\n \"\"\"\n _clear_root_logger_handlers()\n handler = logging.StreamHandler(logfile)\n formatter = logging.Formatter(_LOG_FORMAT, time_utils.TIME_FMT)\n handler.setFormatter(formatter)\n root_logger = logging.getLogger()\n root_logger.addHandler(handler)\n\n\ndef _get_used_servo_ports(servo_hostname, afe):\n \"\"\"\n Return a list of used servo ports for the given servo host.\n\n @param servo_hostname: Hostname of the servo host to check for.\n @param afe: AFE instance.\n\n @returns a list of used ports for the given servo host.\n \"\"\"\n used_ports = []\n host_list = afe.get_hosts_by_attribute(\n attribute=servo_host.SERVO_HOST_ATTR, value=servo_hostname)\n for host in host_list:\n afe_host = afe.get_hosts(hostname=host)\n if afe_host:\n servo_port = afe_host[0].attributes.get(servo_host.SERVO_PORT_ATTR)\n if servo_port:\n used_ports.append(int(servo_port))\n return used_ports\n\n\ndef _get_free_servo_port(servo_hostname, used_servo_ports, afe):\n \"\"\"\n Get a free servo port for the servo_host.\n\n @param servo_hostname: Hostname of the servo host.\n @param used_servo_ports: Dict of dicts that contain the list of used ports\n for the given servo host.\n @param afe: AFE instance.\n\n @returns a free servo port if servo_hostname is non-empty, otherwise an\n empty string.\n \"\"\"\n used_ports = []\n servo_port = servo_host.ServoHost.DEFAULT_PORT\n # If no servo hostname was specified we can assume we're dealing with a\n # servo v3 or older deployment since the servo hostname can be\n # inferred from the dut hostname (by appending '-servo' to it). We only\n # need to find a free port if we're using a servo v4 since we can use the\n # default port for v3 and older.\n if not servo_hostname:\n return ''\n # If we haven't checked this servo host yet, check the AFE if other duts\n # used this servo host and grab the ports specified for them.\n elif servo_hostname not in used_servo_ports:\n used_ports = _get_used_servo_ports(servo_hostname, afe)\n else:\n used_ports = used_servo_ports[servo_hostname]\n used_ports.sort()\n if used_ports:\n # Range is taken from servod.py in hdctools.\n start_port = servo_host.ServoHost.DEFAULT_PORT\n end_port = start_port - 99\n # We'll choose first port available in descending order.\n for port in xrange(start_port, end_port - 1, -1):\n if port not in used_ports:\n servo_port = port\n break\n used_ports.append(servo_port)\n used_servo_ports[servo_hostname] = used_ports\n return servo_port\n\n\ndef _get_afe_servo_port(host_info, afe):\n \"\"\"\n Get the servo port from the afe if it matches the same servo host hostname.\n\n @param host_info HostInfo tuple (hostname, host_attr_dict).\n\n @returns Servo port (int) if servo host hostname matches the one specified\n host_info.host_attr_dict, otherwise None.\n\n @raises _NoAFEServoPortError: When there is no stored host info or servo\n port host attribute in the AFE for the given host.\n \"\"\"\n afe_hosts = afe.get_hosts(hostname=host_info.hostname)\n if not afe_hosts:\n raise _NoAFEServoPortError\n\n servo_port = afe_hosts[0].attributes.get(servo_host.SERVO_PORT_ATTR)\n afe_servo_host = afe_hosts[0].attributes.get(servo_host.SERVO_HOST_ATTR)\n host_info_servo_host = host_info.host_attr_dict.get(\n servo_host.SERVO_HOST_ATTR)\n\n if afe_servo_host == host_info_servo_host and servo_port:\n return int(servo_port)\n else:\n raise _NoAFEServoPortError\n\n\ndef _get_host_attributes(host_info_list, afe):\n \"\"\"\n Get host attributes if a hostname_file was supplied.\n\n @param host_info_list List of HostInfo tuples (hostname, host_attr_dict).\n\n @returns Dict of attributes from host_info_list.\n \"\"\"\n host_attributes = {}\n # We need to choose servo ports for these hosts but we need to make sure\n # we don't choose ports already used. We'll store all used ports in a\n # dict of lists where the key is the servo_host and the val is a list of\n # ports used.\n used_servo_ports = {}\n for host_info in host_info_list:\n host_attr_dict = host_info.host_attr_dict\n # If the host already has an entry in the AFE that matches the same\n # servo host hostname and the servo port is set, use that port.\n try:\n host_attr_dict[servo_host.SERVO_PORT_ATTR] = _get_afe_servo_port(\n host_info, afe)\n except _NoAFEServoPortError:\n host_attr_dict[servo_host.SERVO_PORT_ATTR] = _get_free_servo_port(\n host_attr_dict[servo_host.SERVO_HOST_ATTR], used_servo_ports,\n afe)\n host_attributes[host_info.hostname] = host_attr_dict\n return host_attributes\n\n\ndef install_duts(argv, full_deploy):\n \"\"\"Install a test image on DUTs, and deploy them.\n\n This handles command line parsing for both the repair and\n deployment commands. The two operations are largely identical;\n the main difference is that full deployment includes flashing\n dev-signed firmware on the DUT prior to installing the test\n image.\n\n @param argv Command line arguments to be parsed.\n @param full_deploy If true, do the full deployment that includes\n flashing dev-signed RO firmware onto the DUT.\n \"\"\"\n # Override tempfile.tempdir. Some of the autotest code we call\n # will create temporary files that don't get cleaned up. So, we\n # put the temp files in our results directory, so that we can\n # clean up everything in one fell swoop.\n tempfile.tempdir = tempfile.mkdtemp()\n # MALCOLM:\n # Be comforted.\n # Let's make us med'cines of our great revenge,\n # To cure this deadly grief.\n atexit.register(shutil.rmtree, tempfile.tempdir)\n\n arguments = commandline.parse_command(argv, full_deploy)\n if not arguments:\n sys.exit(1)\n sys.stderr.write('Installation output logs in %s\\n' % arguments.logdir)\n\n # We don't want to distract the user with logging output, so we catch\n # logging output in a file.\n logging_file_path = os.path.join(arguments.logdir, 'debug.log')\n logfile = open(logging_file_path, 'w')\n _configure_logging_to_file(logfile)\n\n report_log_path = os.path.join(arguments.logdir, 'report.log')\n with open(report_log_path, 'w') as report_log_file:\n report_log = _MultiFileWriter([report_log_file, sys.stdout])\n afe = frontend.AFE(server=arguments.web)\n current_build = _update_build(afe, report_log, arguments)\n host_attr_dict = _get_host_attributes(arguments.host_info_list, afe)\n install_pool = multiprocessing.Pool(len(arguments.hostnames))\n install_function = functools.partial(_install_dut, arguments,\n host_attr_dict)\n results_list = install_pool.map(install_function, arguments.hostnames)\n _report_results(afe, report_log, arguments.hostnames, results_list)\n\n gspath = _get_upload_log_path(arguments)\n report_log.write('Logs will be uploaded to %s\\n' % (gspath,))\n\n try:\n _upload_logs(arguments.logdir, gspath)\n except Exception as e:\n upload_failure_log_path = os.path.join(arguments.logdir,\n 'gs_upload_failure.log')\n with open(upload_failure_log_path, 'w') as file:\n traceback.print_exc(limit=None, file=file)\n sys.stderr.write('Failed to upload logs;'\n ' failure details are stored in {}.\\n'\n .format(upload_failure_log_path))\n", "repo_name": "kindle4jerry/honor-play-kernel-9.0-kindle4jerry", "sub_path": "external/autotest/site_utils/deployment/install.py", "file_name": "install.py", "file_ext": "py", "file_size_in_byte": 29436, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "20", "api": [{"api_name": "autotest_lib.server.constants.Labels", "line_number": 33, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.constants", "line_number": 33, "usage_type": "name"}, {"api_name": "collections.namedtuple", "line_number": 46, "usage_type": "call"}, {"api_name": "autotest_lib.site_utils.deployment.commandline.get_default_logdir_name", "line_number": 76, "usage_type": "call"}, {"api_name": "autotest_lib.site_utils.deployment.commandline", "line_number": 76, "usage_type": "name"}, {"api_name": "chromite.lib.gs.GSContext", "line_number": 85, "usage_type": "call"}, {"api_name": "chromite.lib.gs", "line_number": 85, "usage_type": "name"}, {"api_name": "chromite.lib.gs.GSContext", "line_number": 103, "usage_type": "call"}, {"api_name": "chromite.lib.gs", "line_number": 103, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 104, "usage_type": "call"}, {"api_name": "autotest_lib.client.common_lib.utils.compare_versions", "line_number": 161, "usage_type": "call"}, {"api_name": "autotest_lib.client.common_lib.utils", "line_number": 161, "usage_type": "name"}, {"api_name": "autotest_lib.client.common_lib.utils.compare_versions", "line_number": 165, "usage_type": "call"}, {"api_name": "autotest_lib.client.common_lib.utils", "line_number": 165, "usage_type": "name"}, {"api_name": "autotest_lib.site_utils.stable_images.assign_stable_images.get_firmware_versions", "line_number": 173, "usage_type": "call"}, {"api_name": "autotest_lib.site_utils.stable_images.assign_stable_images", "line_number": 173, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.afe_store.AfeStore", "line_number": 209, "usage_type": "call"}, {"api_name": "autotest_lib.server.hosts.afe_store", "line_number": 209, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.CrosHost.get_servo_arguments", "line_number": 211, "usage_type": "call"}, {"api_name": "autotest_lib.server.hosts.CrosHost", "line_number": 211, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts", "line_number": 211, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.create_host", "line_number": 212, "usage_type": "call"}, {"api_name": "autotest_lib.server.hosts", "line_number": 212, "usage_type": "name"}, {"api_name": "logging.warning", "line_number": 226, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 230, "usage_type": "call"}, {"api_name": "logging.warning", "line_number": 246, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 249, "usage_type": "call"}, {"api_name": "autotest_lib.server.hosts.servo_host.SERVO_HOST_ATTR", "line_number": 267, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 267, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.SERVO_PORT_ATTR", "line_number": 268, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 268, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.SERVO_SERIAL_ATTR", "line_number": 269, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 269, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.make_servo_hostname", "line_number": 271, "usage_type": "call"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 271, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.ServoHost", "line_number": 273, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 273, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.SERVO_HOST_ATTR", "line_number": 274, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 274, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.SERVO_PORT_ATTR", "line_number": 277, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 277, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.SERVO_SERIAL_ATTR", "line_number": 281, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 281, "usage_type": "name"}, {"api_name": "autotest_lib.client.common_lib.host_states.IDLE_STATES", "line_number": 314, "usage_type": "attribute"}, {"api_name": "autotest_lib.client.common_lib.host_states", "line_number": 314, "usage_type": "name"}, {"api_name": "autotest_lib.server.constants.Labels", "line_number": 327, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.constants", "line_number": 327, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 355, "usage_type": "call"}, {"api_name": "autotest_lib.client.common_lib.error.AutoservRunError", "line_number": 399, "usage_type": "attribute"}, {"api_name": "autotest_lib.client.common_lib.error", "line_number": 399, "usage_type": "name"}, {"api_name": "logging.exception", "line_number": 400, "usage_type": "call"}, {"api_name": "autotest_lib.server.cros.dynamic_suite.constants.VERSION_PREFIX", "line_number": 438, "usage_type": "argument"}, {"api_name": "logging.error", "line_number": 443, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 469, "usage_type": "call"}, {"api_name": "os.path", "line_number": 469, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 471, "usage_type": "attribute"}, {"api_name": "sys.stdout", "line_number": 471, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.frontend.AFE", "line_number": 474, "usage_type": "call"}, {"api_name": "autotest_lib.server.frontend", "line_number": 474, "usage_type": "name"}, {"api_name": "logging.exception", "line_number": 480, "usage_type": "call"}, {"api_name": "autotest_lib.server.constants.Labels", "line_number": 535, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.constants", "line_number": 535, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 555, "usage_type": "call"}, {"api_name": "logging.StreamHandler", "line_number": 566, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 567, "usage_type": "call"}, {"api_name": "autotest_lib.client.common_lib.time_utils.TIME_FMT", "line_number": 567, "usage_type": "attribute"}, {"api_name": "autotest_lib.client.common_lib.time_utils", "line_number": 567, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 569, "usage_type": "call"}, {"api_name": "autotest_lib.server.hosts.servo_host.SERVO_HOST_ATTR", "line_number": 584, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 584, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.SERVO_PORT_ATTR", "line_number": 588, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 588, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.ServoHost", "line_number": 607, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 607, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.ServoHost", "line_number": 624, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 624, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.SERVO_PORT_ATTR", "line_number": 652, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 652, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.SERVO_HOST_ATTR", "line_number": 653, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 653, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.SERVO_HOST_ATTR", "line_number": 655, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 655, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.SERVO_PORT_ATTR", "line_number": 682, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 682, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.SERVO_PORT_ATTR", "line_number": 685, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 685, "usage_type": "name"}, {"api_name": "autotest_lib.server.hosts.servo_host.SERVO_HOST_ATTR", "line_number": 686, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.hosts.servo_host", "line_number": 686, "usage_type": "name"}, {"api_name": "tempfile.tempdir", "line_number": 709, "usage_type": "attribute"}, {"api_name": "tempfile.mkdtemp", "line_number": 709, "usage_type": "call"}, {"api_name": "atexit.register", "line_number": 714, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 714, "usage_type": "attribute"}, {"api_name": "tempfile.tempdir", "line_number": 714, "usage_type": "attribute"}, {"api_name": "autotest_lib.site_utils.deployment.commandline.parse_command", "line_number": 716, "usage_type": "call"}, {"api_name": "autotest_lib.site_utils.deployment.commandline", "line_number": 716, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 718, "usage_type": "call"}, {"api_name": "sys.stderr.write", "line_number": 719, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 719, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 723, "usage_type": "call"}, {"api_name": "os.path", "line_number": 723, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 727, "usage_type": "call"}, {"api_name": "os.path", "line_number": 727, "usage_type": "attribute"}, {"api_name": "sys.stdout", "line_number": 729, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.frontend.AFE", "line_number": 730, "usage_type": "call"}, {"api_name": "autotest_lib.server.frontend", "line_number": 730, "usage_type": "name"}, {"api_name": "multiprocessing.Pool", "line_number": 733, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 734, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 745, "usage_type": "call"}, {"api_name": "os.path", "line_number": 745, "usage_type": "attribute"}, {"api_name": "traceback.print_exc", "line_number": 748, "usage_type": "call"}, {"api_name": "sys.stderr.write", "line_number": 749, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 749, "usage_type": "attribute"}]} +{"seq_id": "23698561539", "text": "#!/usr/bin/env python\n\nimport os\nimport sys\nimport time\nfrom docker import Client\n\nimport print_utils\nimport kind\nimport utils\n\n\nPELOTON_K8S_NAME = \"peloton-k8s\"\n\nzk_url = None\ncli = Client(base_url=\"unix://var/run/docker.sock\")\nwork_dir = os.path.dirname(os.path.abspath(__file__))\n\n\n# Delete the kind cluster.\ndef teardown_k8s():\n k8s = kind.Kind(PELOTON_K8S_NAME)\n return k8s.teardown()\n\n\ndef teardown_mesos_agent(config, agent_index, is_exclusive=False):\n prefix = config[\"mesos_agent_container\"]\n if is_exclusive:\n prefix += \"-exclusive\"\n agent = prefix + repr(agent_index)\n utils.remove_existing_container(agent)\n\n\n#\n# Teardown mesos related containers.\n#\ndef teardown_mesos(config):\n # 1 - Remove all Mesos Agents\n for i in range(0, config[\"num_agents\"]):\n teardown_mesos_agent(config, i)\n for i in range(0, config.get(\"num_exclusive_agents\", 0)):\n teardown_mesos_agent(config, i, is_exclusive=True)\n\n # 2 - Remove Mesos Master\n utils.remove_existing_container(config[\"mesos_master_container\"])\n\n # 3- Remove orphaned mesos containers.\n for c in cli.containers(filters={\"name\": \"^/mesos-\"}, all=True):\n utils.remove_existing_container(c.get(\"Id\"))\n\n # 4 - Remove ZooKeeper\n utils.remove_existing_container(config[\"zk_container\"])\n\n\n# Start a kind cluster.\ndef run_k8s():\n print_utils.okgreen(\"starting k8s cluster\")\n k8s = kind.Kind(PELOTON_K8S_NAME)\n k8s.teardown()\n k8s.create()\n print_utils.okgreen(\"started k8s cluster\")\n\n\n#\n# Run mesos cluster\n#\ndef run_mesos(config):\n # Remove existing containers first.\n teardown_mesos(config)\n\n # Run zk\n cli.pull(config[\"zk_image\"])\n container = cli.create_container(\n name=config[\"zk_container\"],\n hostname=config[\"zk_container\"],\n host_config=cli.create_host_config(\n port_bindings={config[\"default_zk_port\"]: config[\"local_zk_port\"]}\n ),\n image=config[\"zk_image\"],\n detach=True,\n )\n cli.start(container=container.get(\"Id\"))\n print_utils.okgreen(\"started container %s\" % config[\"zk_container\"])\n\n # TODO: add retry\n print_utils.okblue(\"sleep 20 secs for zk to come up\")\n time.sleep(20)\n\n # Run mesos master\n cli.pull(config[\"mesos_master_image\"])\n container = cli.create_container(\n name=config[\"mesos_master_container\"],\n hostname=config[\"mesos_master_container\"],\n volumes=[\"/files\"],\n ports=[repr(config[\"master_port\"])],\n host_config=cli.create_host_config(\n port_bindings={config[\"master_port\"]: config[\"master_port\"]},\n binds=[\n work_dir + \"/files:/files\",\n work_dir + \"/mesos_config/etc_mesos-master:/etc/mesos-master\",\n ],\n privileged=True,\n ),\n environment=[\n \"MESOS_AUTHENTICATE_HTTP_READWRITE=true\",\n \"MESOS_AUTHENTICATE_FRAMEWORKS=true\",\n # TODO: Enable following flags for fully authentication.\n \"MESOS_AUTHENTICATE_HTTP_FRAMEWORKS=true\",\n \"MESOS_HTTP_FRAMEWORK_AUTHENTICATORS=basic\",\n \"MESOS_CREDENTIALS=/etc/mesos-master/credentials\",\n \"MESOS_LOG_DIR=\" + config[\"log_dir\"],\n \"MESOS_PORT=\" + repr(config[\"master_port\"]),\n \"MESOS_ZK=zk://{0}:{1}/mesos\".format(\n utils.get_container_ip(config[\"zk_container\"]),\n config[\"default_zk_port\"],\n ),\n \"MESOS_QUORUM=\" + repr(config[\"quorum\"]),\n \"MESOS_REGISTRY=\" + config[\"registry\"],\n \"MESOS_WORK_DIR=\" + config[\"work_dir\"],\n ],\n image=config[\"mesos_master_image\"],\n entrypoint=\"bash /files/run_mesos_master.sh\",\n detach=True,\n )\n cli.start(container=container.get(\"Id\"))\n master_container = config[\"mesos_master_container\"]\n print_utils.okgreen(\"started container %s\" % master_container)\n\n # Run mesos slaves\n cli.pull(config['mesos_slave_image'])\n for i in range(0, config['num_agents']):\n run_mesos_agent(config, i, i)\n for i in range(0, config.get('num_exclusive_agents', 0)):\n run_mesos_agent(\n config,\n i, config['num_agents'] + i,\n is_exclusive=True,\n exclusive_label_value=config.get('exclusive_label_value', ''))\n\n print_utils.okblue(\n \"sleep 60 secs for mesos agent to register with mesos master\")\n time.sleep(60)\n\n\n#\n# Run a mesos agent\n#\ndef run_mesos_agent(config, agent_index, port_offset, is_exclusive=False,\n exclusive_label_value=''):\n prefix = config[\"mesos_agent_container\"]\n attributes = config[\"attributes\"]\n if is_exclusive:\n prefix += \"-exclusive\"\n attributes += \";peloton/exclusive:\" + exclusive_label_value\n agent = prefix + repr(agent_index)\n port = config[\"local_agent_port\"] + port_offset\n container = cli.create_container(\n name=agent,\n hostname=agent,\n volumes=[\"/files\", \"/var/run/docker.sock\"],\n ports=[repr(config[\"default_agent_port\"])],\n host_config=cli.create_host_config(\n port_bindings={config[\"default_agent_port\"]: port},\n binds=[\n work_dir + \"/files:/files\",\n work_dir\n + \"/mesos_config/etc_mesos-slave:/etc/mesos-slave\",\n \"/var/run/docker.sock:/var/run/docker.sock\",\n ],\n privileged=True,\n ),\n environment=[\n \"MESOS_PORT=\" + repr(port),\n \"MESOS_MASTER=zk://{0}:{1}/mesos\".format(\n utils.get_container_ip(config[\"zk_container\"]),\n config[\"default_zk_port\"],\n ),\n \"MESOS_SWITCH_USER=\" + repr(config[\"switch_user\"]),\n \"MESOS_CONTAINERIZERS=\" + config[\"containers\"],\n \"MESOS_LOG_DIR=\" + config[\"log_dir\"],\n \"MESOS_ISOLATION=\" + config[\"isolation\"],\n \"MESOS_SYSTEMD_ENABLE_SUPPORT=false\",\n \"MESOS_IMAGE_PROVIDERS=\" + config[\"image_providers\"],\n \"MESOS_IMAGE_PROVISIONER_BACKEND={0}\".format(\n config[\"image_provisioner_backend\"]\n ),\n \"MESOS_APPC_STORE_DIR=\" + config[\"appc_store_dir\"],\n \"MESOS_WORK_DIR=\" + config[\"work_dir\"],\n \"MESOS_RESOURCES=\" + config[\"resources\"],\n \"MESOS_ATTRIBUTES=\" + attributes,\n \"MESOS_MODULES=\" + config[\"modules\"],\n \"MESOS_RESOURCE_ESTIMATOR=\" + config[\"resource_estimator\"],\n \"MESOS_OVERSUBSCRIBED_RESOURCES_INTERVAL=\"\n + config[\"oversubscribed_resources_interval\"],\n \"MESOS_QOS_CONTROLLER=\" + config[\"qos_controller\"],\n \"MESOS_QOS_CORRECTION_INTERVAL_MIN=\"\n + config[\"qos_correction_interval_min\"],\n ],\n image=config[\"mesos_slave_image\"],\n entrypoint=\"bash /files/run_mesos_slave.sh\",\n detach=True,\n )\n cli.start(container=container.get(\"Id\"))\n print_utils.okgreen(\"started container %s\" % agent)\n\n\n#\n# Run cassandra cluster\n#\ndef run_cassandra(config):\n utils.remove_existing_container(config[\"cassandra_container\"])\n cli.pull(config[\"cassandra_image\"])\n container = cli.create_container(\n name=config[\"cassandra_container\"],\n hostname=config[\"cassandra_container\"],\n host_config=cli.create_host_config(\n port_bindings={\n config[\"cassandra_cql_port\"]: config[\"cassandra_cql_port\"],\n config[\"cassandra_thrift_port\"]: config[\n \"cassandra_thrift_port\"\n ],\n },\n binds=[work_dir + \"/files:/files\"],\n ),\n environment=[\"MAX_HEAP_SIZE=1G\", \"HEAP_NEWSIZE=256M\"],\n image=config[\"cassandra_image\"],\n detach=True,\n entrypoint=\"bash /files/run_cassandra_with_stratio_index.sh\",\n )\n cli.start(container=container.get(\"Id\"))\n print_utils.okgreen(\"started container %s\" % config[\"cassandra_container\"])\n\n # Create cassandra store\n create_cassandra_store(config)\n\n\n#\n# Create cassandra store with retries\n#\ndef create_cassandra_store(config):\n retry_attempts = 0\n while retry_attempts < utils.max_retry_attempts:\n time.sleep(utils.sleep_time_secs)\n setup_exe = cli.exec_create(\n container=config[\"cassandra_container\"],\n cmd=\"/files/setup_cassandra.sh\",\n )\n show_exe = cli.exec_create(\n container=config[\"cassandra_container\"],\n cmd='cqlsh -e \"describe %s\"' % config[\"cassandra_test_db\"],\n )\n # by api design, exec_start needs to be called after exec_create\n # to run 'docker exec'\n resp = cli.exec_start(exec_id=setup_exe)\n if resp is \"\":\n resp = cli.exec_start(exec_id=show_exe)\n if \"CREATE KEYSPACE peloton_test WITH\" in resp:\n print_utils.okgreen(\"cassandra store is created\")\n return\n print_utils.warn(\"failed to create cassandra store, retrying...\")\n retry_attempts += 1\n\n print_utils.fail(\n \"Failed to create cassandra store after %d attempts, \"\n \"aborting...\" % utils.max_retry_attempts\n )\n sys.exit(1)\n\n\n#\n# Starts a container and waits for it to come up\n#\ndef start_and_wait(\n application_name, container_name, ports, config, extra_env=None,\n mounts=None,\n):\n if mounts is None:\n mounts = []\n\n # TODO: It's very implicit that the first port is the HTTP port, perhaps we\n # should split it out even more.\n election_zk_servers = None\n mesos_zk_path = None\n if zk_url is not None:\n election_zk_servers = zk_url\n mesos_zk_path = \"zk://{0}/mesos\".format(zk_url)\n else:\n election_zk_servers = \"{0}:{1}\".format(\n utils.get_container_ip(config[\"zk_container\"]),\n config[\"default_zk_port\"],\n )\n mesos_zk_path = \"zk://{0}:{1}/mesos\".format(\n utils.get_container_ip(config[\"zk_container\"]),\n config[\"default_zk_port\"],\n )\n cass_hosts = utils.get_container_ip(config[\"cassandra_container\"])\n env = {\n \"CONFIG_DIR\": \"config\",\n \"APP\": application_name,\n \"HTTP_PORT\": ports[0],\n \"DB_HOST\": utils.get_container_ip(config[\"cassandra_container\"]),\n \"ELECTION_ZK_SERVERS\": election_zk_servers,\n \"MESOS_ZK_PATH\": mesos_zk_path,\n \"MESOS_SECRET_FILE\": \"/files/hostmgr_mesos_secret\",\n \"CASSANDRA_HOSTS\": cass_hosts,\n \"ENABLE_DEBUG_LOGGING\": config[\"debug\"],\n \"DATACENTER\": \"\",\n # used to migrate the schema;used inside host manager\n \"AUTO_MIGRATE\": config[\"auto_migrate\"],\n \"CLUSTER\": \"minicluster\",\n 'AUTH_TYPE': os.getenv('AUTH_TYPE', 'NOOP'),\n 'AUTH_CONFIG_FILE': os.getenv('AUTH_CONFIG_FILE'),\n }\n if len(ports) > 1:\n env[\"GRPC_PORT\"] = ports[1]\n if extra_env:\n env.update(extra_env)\n environment = []\n for key, value in env.iteritems():\n environment.append(\"%s=%s\" % (key, value))\n # BIND_MOUNTS allows additional files to be mounted in the\n # the container. Expected format is a comma-separated list\n # of items of the form :\n extra_mounts = os.environ.get(\"BIND_MOUNTS\", \"\").split(\",\") or []\n mounts.extend(list(filter(None, extra_mounts)))\n container = cli.create_container(\n name=container_name,\n hostname=container_name,\n ports=[repr(port) for port in ports],\n environment=environment,\n host_config=cli.create_host_config(\n port_bindings={port: port for port in ports},\n binds=[work_dir + \"/files:/files\"] + mounts,\n ),\n # pull or build peloton image if not exists\n image=config[\"peloton_image\"],\n detach=True,\n )\n cli.start(container=container.get(\"Id\"))\n utils.wait_for_up(\n container_name, ports[0]\n ) # use the first port as primary\n\n\n#\n# Run peloton resmgr app\n#\ndef run_peloton_resmgr(config, enable_k8s=False):\n env = {}\n if enable_k8s:\n env.update({\"HOSTMGR_API_VERSION\": \"v1alpha\"})\n\n # TODO: move docker run logic into a common function for all apps to share\n for i in range(0, config[\"peloton_resmgr_instance_count\"]):\n # to not cause port conflicts among apps, increase port by 10\n # for each instance\n ports = [port + i * 10 for port in config[\"peloton_resmgr_ports\"]]\n name = config[\"peloton_resmgr_container\"] + repr(i)\n utils.remove_existing_container(name)\n start_and_wait(\n \"resmgr\",\n name,\n ports,\n config,\n extra_env=env,\n )\n\n\n#\n# Run peloton hostmgr app\n#\ndef run_peloton_hostmgr(config, enable_k8s=False):\n scarce_resource = \",\".join(config[\"scarce_resource_types\"])\n slack_resource = \",\".join(config[\"slack_resource_types\"])\n mounts = []\n env = {\n \"SCARCE_RESOURCE_TYPES\": scarce_resource,\n \"SLACK_RESOURCE_TYPES\": slack_resource,\n }\n if enable_k8s:\n k8s = kind.Kind(PELOTON_K8S_NAME)\n kubeconfig_dir = os.path.dirname(k8s.get_kubeconfig())\n mounts = [kubeconfig_dir + \":/.kube\"]\n env.update({\n \"ENABLE_K8S\": True,\n \"KUBECONFIG\": \"/.kube/kind-config-peloton-k8s\",\n })\n\n for i in range(0, config[\"peloton_hostmgr_instance_count\"]):\n # to not cause port conflicts among apps, increase port\n # by 10 for each instance\n ports = [port + i * 10 for port in config[\"peloton_hostmgr_ports\"]]\n name = config[\"peloton_hostmgr_container\"] + repr(i)\n utils.remove_existing_container(name)\n start_and_wait(\n \"hostmgr\",\n name,\n ports,\n config,\n extra_env=env,\n mounts=mounts,\n )\n\n\n#\n# Run peloton jobmgr app\n#\ndef run_peloton_jobmgr(config, enable_k8s=False):\n env = {\n \"MESOS_AGENT_WORK_DIR\": config[\"work_dir\"],\n \"JOB_TYPE\": os.getenv(\"JOB_TYPE\", \"BATCH\"),\n }\n if enable_k8s:\n env.update({\"HOSTMGR_API_VERSION\": \"v1alpha\"})\n\n for i in range(0, config[\"peloton_jobmgr_instance_count\"]):\n # to not cause port conflicts among apps, increase port by 10\n # for each instance\n ports = [port + i * 10 for port in config[\"peloton_jobmgr_ports\"]]\n name = config[\"peloton_jobmgr_container\"] + repr(i)\n utils.remove_existing_container(name)\n start_and_wait(\n \"jobmgr\",\n name,\n ports,\n config,\n extra_env=env,\n )\n\n\n#\n# Run peloton aurora bridge app\n#\ndef run_peloton_aurorabridge(config, enable_k8s=False):\n for i in range(0, config[\"peloton_aurorabridge_instance_count\"]):\n ports = [\n port + i * 10 for port in config[\"peloton_aurorabridge_ports\"]\n ]\n name = config[\"peloton_aurorabridge_container\"] + repr(i)\n utils.remove_existing_container(name)\n start_and_wait(\"aurorabridge\", name, ports, config)\n\n\n#\n# Run peloton placement app\n#\ndef run_peloton_placement(config, enable_k8s=False):\n i = 0\n for task_type in config[\"peloton_placement_instances\"]:\n # to not cause port conflicts among apps, increase port by 10\n # for each instance\n ports = [port + i * 10 for port in config[\"peloton_placement_ports\"]]\n name = config[\"peloton_placement_container\"] + repr(i)\n utils.remove_existing_container(name)\n if task_type == 'BATCH':\n app_type = 'placement'\n else:\n app_type = 'placement_' + task_type.lower()\n env = {\n \"APP_TYPE\": app_type,\n \"TASK_TYPE\": task_type,\n }\n if enable_k8s:\n env.update({\"HOSTMGR_API_VERSION\": \"v1alpha\"})\n start_and_wait(\n \"placement\",\n name,\n ports,\n config,\n extra_env=env,\n )\n i = i + 1\n\n\n#\n# Run peloton api proxy\n#\ndef run_peloton_apiproxy(config, enable_k8s=False):\n for i in range(0, config[\"peloton_apiproxy_instance_count\"]):\n ports = [\n port + i * 10 for port in config[\"peloton_apiproxy_ports\"]\n ]\n name = config[\"peloton_apiproxy_container\"] + repr(i)\n utils.remove_existing_container(name)\n start_and_wait(\"apiproxy\", name, ports, config)\n\n\n#\n# Run peloton archiver app\n#\ndef run_peloton_archiver(config, enable_k8s=False):\n for i in range(0, config[\"peloton_archiver_instance_count\"]):\n ports = [port + i * 10 for port in config[\"peloton_archiver_ports\"]]\n name = config[\"peloton_archiver_container\"] + repr(i)\n utils.remove_existing_container(name)\n start_and_wait(\n \"archiver\",\n name,\n ports,\n config,\n )\n", "repo_name": "fakeNetflix/uber-repo-peloton", "sub_path": "tools/minicluster/minicluster.py", "file_name": "minicluster.py", "file_ext": "py", "file_size_in_byte": 16781, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "docker.Client", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 17, "usage_type": "call"}, {"api_name": "kind.Kind", "line_number": 22, "usage_type": "call"}, {"api_name": "utils.remove_existing_container", "line_number": 31, "usage_type": "call"}, {"api_name": "utils.remove_existing_container", "line_number": 45, "usage_type": "call"}, {"api_name": "utils.remove_existing_container", "line_number": 49, "usage_type": "call"}, {"api_name": "utils.remove_existing_container", "line_number": 52, "usage_type": "call"}, {"api_name": "print_utils.okgreen", "line_number": 57, "usage_type": "call"}, {"api_name": "kind.Kind", "line_number": 58, "usage_type": "call"}, {"api_name": "print_utils.okgreen", "line_number": 61, "usage_type": "call"}, {"api_name": "print_utils.okgreen", "line_number": 83, "usage_type": "call"}, {"api_name": "print_utils.okblue", "line_number": 86, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 87, "usage_type": "call"}, {"api_name": "utils.get_container_ip", "line_number": 114, "usage_type": "call"}, {"api_name": "print_utils.okgreen", "line_number": 127, "usage_type": "call"}, {"api_name": "print_utils.okblue", "line_number": 140, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 142, "usage_type": "call"}, {"api_name": "utils.get_container_ip", "line_number": 175, "usage_type": "call"}, {"api_name": "print_utils.okgreen", "line_number": 204, "usage_type": "call"}, {"api_name": "utils.remove_existing_container", "line_number": 211, "usage_type": "call"}, {"api_name": "print_utils.okgreen", "line_number": 231, "usage_type": "call"}, {"api_name": "utils.max_retry_attempts", "line_number": 242, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 243, "usage_type": "call"}, {"api_name": "utils.sleep_time_secs", "line_number": 243, "usage_type": "attribute"}, {"api_name": "print_utils.okgreen", "line_number": 258, "usage_type": "call"}, {"api_name": "print_utils.warn", "line_number": 260, "usage_type": "call"}, {"api_name": "print_utils.fail", "line_number": 263, "usage_type": "call"}, {"api_name": "utils.max_retry_attempts", "line_number": 265, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 267, "usage_type": "call"}, {"api_name": "utils.get_container_ip", "line_number": 289, "usage_type": "call"}, {"api_name": "utils.get_container_ip", "line_number": 293, "usage_type": "call"}, {"api_name": "utils.get_container_ip", "line_number": 296, "usage_type": "call"}, {"api_name": "utils.get_container_ip", "line_number": 301, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 311, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 312, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 324, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 324, "usage_type": "attribute"}, {"api_name": "utils.wait_for_up", "line_number": 340, "usage_type": "call"}, {"api_name": "utils.remove_existing_container", "line_number": 359, "usage_type": "call"}, {"api_name": "kind.Kind", "line_number": 381, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 382, "usage_type": "call"}, {"api_name": "os.path", "line_number": 382, "usage_type": "attribute"}, {"api_name": "utils.remove_existing_container", "line_number": 394, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 411, "usage_type": "call"}, {"api_name": "utils.remove_existing_container", "line_number": 421, "usage_type": "call"}, {"api_name": "utils.remove_existing_container", "line_number": 440, "usage_type": "call"}, {"api_name": "utils.remove_existing_container", "line_number": 454, "usage_type": "call"}, {"api_name": "utils.remove_existing_container", "line_number": 484, "usage_type": "call"}, {"api_name": "utils.remove_existing_container", "line_number": 495, "usage_type": "call"}]} +{"seq_id": "11265580503", "text": "import os\nimport argparse\nimport imageio\nimport torch\nimport time\nimport numpy as np\nfrom data.dataset_synthetic_local import SynLocalDataset\nfrom data.local_identity_sampler import RandomLocalIdentiyiSampler\nfrom torch.utils.data import DataLoader\n\nfrom model.Autoencoder import GlobalEncoder\nfrom model.Autoencoder import LocalEncoder, LocalSilDecoder, LocalAppSplitRenderer\nfrom utils.tonemapping import GammaTMO\nfrom utils.loss import CosineSimilarity, NormalNLLLoss\nfrom utils.mapping.rotation import RotateByPixel\nfrom utils.mapping.radiometric_distorsion import RadiometricDistorsion, DistortImage\nfrom utils.mapping.log_mapping import linear2log, log2linear\nfrom utils.logger import *\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--debug\", action=\"store_true\", help=\"debug mode\")\nparser.add_argument(\"--override\", action=\"store_true\")\nparser.add_argument(\"--dataroot_syn\", type=str, default=\"../data/synthetic\")\nparser.add_argument(\"--split_dir_syn\", type=str, default='../data/synthetic/split')\nparser.add_argument(\"--filterfile_syn\", type=str, nargs='+', default=None)\nparser.add_argument(\"--log_image\", action=\"store_true\", help=\"use image in log space\")\nparser.add_argument(\"--log_mu\", type=float, default=16.0)\nparser.add_argument(\"--name\", type=str, required=True)\nparser.add_argument(\"--num_epoch\", type=int, required=True)\nparser.add_argument(\"--resume\", action=\"store_true\")\nparser.add_argument(\"--resume_epoch\", type=int, default=0)\nparser.add_argument(\"--load_sky_enc_path\", type=str, required=True)\nparser.add_argument(\"--load_sun_enc_path\", type=str, required=True)\nparser.add_argument(\"--batch_size\", type=int, required=True)\nparser.add_argument(\"--sky_dim\", type=int, default=8)\nparser.add_argument(\"--sun_dim\", type=int, default=53)\nparser.add_argument(\"--lr\", type=float, required=True)\nparser.add_argument(\"--lr_multistep_schedule\", type=int, nargs='+')\nparser.add_argument(\"--lr_multistep_gamma\", type=float, default=1.0)\nparser.add_argument(\"--l1_coeff\", type=float, required=True)\nparser.add_argument(\"--l2_coeff\", type=float, required=True)\nparser.add_argument(\"--l1_sil_coeff\", type=float, required=True)\nparser.add_argument(\"--l2_sil_coeff\", type=float, required=True)\nparser.add_argument(\"--identity_loss\", action=\"store_true\")\nparser.add_argument(\"--identity_loss_type\", type=str, default=\"L1\", choices=['L1', 'L2', 'COS'], help='L1|L2|COS')\nparser.add_argument(\"--identity_loss_coeff\", type=float, default=0)\nparser.add_argument(\"--cross_render_loss\", action=\"store_true\")\nparser.add_argument(\"--cross_render_l1_coeff\", type=float, default=0)\nparser.add_argument(\"--cross_render_l2_coeff\", type=float, default=0)\nparser.add_argument(\"--tmo_gamma\", type=float, default=2.2)\nparser.add_argument(\"--tmo_log_exposure\", type=float, default=-2)\nparser.add_argument(\"--radiometric_distorsion\", action=\"store_true\")\nparser.add_argument(\"--radiometric_distorsion_prob\", type=float, default=0.5)\nparser.add_argument(\"--rotation_distorsion\", action=\"store_true\")\nparser.add_argument(\"--rotation_distorsion_prob\", type=float, default=0.8)\nparser.add_argument(\"--save_every\", type=int, required=True)\nparser.add_argument(\"--plot_every\", type=int, required=True)\nparser.add_argument(\"--tb_save_image_every\", type=int, default=50)\nparser.add_argument(\"--eval_every\", type=int, required=True)\nparser.add_argument(\"--num_loader\", type=int, default=1)\nparser.add_argument(\"--save_dir\", type=str, required=True)\nparser.add_argument(\"--model_activ\", type=str, choices=['relu', 'lrelu'], default='relu')\n\nargs = parser.parse_args()\n\ndataroot_syn = args.dataroot_syn\ntrainsplit_syn = os.path.join(args.split_dir_syn, 'train.txt')\nvalsplit_syn = os.path.join(args.split_dir_syn, 'val.txt')\n\nos.makedirs(args.save_dir, exist_ok=True)\nos.makedirs(os.path.join(args.save_dir, args.name), exist_ok=(args.debug or args.override or args.resume))\ntask_dir = os.path.join(args.save_dir, args.name)\n\nsave_options_cmdline(task_dir, args)\nlogger = set_logger(task_dir)\ntb_logger = set_tb_logger(task_dir)\ntb_save_options_cmdline(tb_logger, args)\n\n# initialize models\nenc_global_sky = GlobalEncoder(cin=3, cout=args.sky_dim, activ=args.model_activ).to('cuda')\nenc_global_sky.load_state_dict(torch.load(args.load_sky_enc_path, map_location='cuda'))\nenc_global_sky.eval()\nenc_global_sun = GlobalEncoder(cin=3, cout=args.sun_dim, activ=args.model_activ).to('cuda')\nenc_global_sun.load_state_dict(torch.load(args.load_sun_enc_path, map_location='cuda'))\nenc_global_sun.eval()\nenc_local = LocalEncoder(cin=3, cout=64, activ=args.model_activ).to('cuda')\ndec_sil = LocalSilDecoder(cin=64, cout=1, activ=args.model_activ).to('cuda')\ndec_app = LocalAppSplitRenderer(cin_l=64, cin_sky=args.sky_dim, cin_sun=args.sun_dim, cout=3, activ=args.model_activ).to('cuda')\nMSE = torch.nn.MSELoss(reduction='mean')\nMAE = torch.nn.L1Loss(reduction='mean')\nBCE = torch.nn.BCELoss(reduction='mean')\nCE = torch.nn.CrossEntropyLoss(reduction='mean')\nCOS = CosineSimilarity()\nNNLL = NormalNLLLoss()\n# initialize optimizer\noptimizer = torch.optim.Adam([{\"params\": enc_local.parameters()}, \n {\"params\": dec_sil.parameters()}, \n {\"params\": dec_app.parameters()}], lr=args.lr)\nlr = args.lr\nscheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, list(args.lr_multistep_schedule), args.lr_multistep_gamma)\n\nprint(\"name: \", args.name)\nprint(\"task path: \", task_dir)\n\ntrainSet = SynLocalDataset(opt=args, dataroot=dataroot_syn, splitfile=trainsplit_syn, phase='train', filterfile=args.filterfile_syn)\nvalSet = SynLocalDataset(opt=args, dataroot=dataroot_syn, splitfile=valsplit_syn, phase='val', filterfile=args.filterfile_syn)\n\ntrainSampler = RandomLocalIdentiyiSampler(trainSet, dataroot=dataroot_syn, batch_size=args.batch_size, num_instance=2) # a pair of same local different global for cross-render constraint\n\ntrainLoader = DataLoader(trainSet, batch_size=args.batch_size, sampler=trainSampler, num_workers=args.num_loader, drop_last=True) # NOTE: 'shuffle' option inactive here, and 'drop_last' must be set True!\nvalLoader = DataLoader(valSet, batch_size=1, shuffle=False, num_workers=args.num_loader)\n\n# by default all counter set to 0\nstart_epoch = 0\ntotal_iter = 0\n\n# if resume training\nif args.resume and args.resume_epoch > 0:\n print(\"now resume training after epoch %d ...\" %(args.resume_epoch))\n start_epoch = args.resume_epoch\n total_iter = args.resume_epoch * len(trainSet) // args.batch_size\n enc_local_load_path = os.path.join(task_dir, 'checkpoints', 'enc_local_epoch_%d' %(args.resume_epoch))\n dec_sil_load_path = os.path.join(task_dir, 'checkpoints', 'dec_sil_epoch_%d' %(args.resume_epoch))\n dec_app_load_path = os.path.join(task_dir, 'checkpoints', 'dec_app_epoch_%d' %(args.resume_epoch))\n optimizer_load_path = os.path.join(task_dir, 'checkpoints', 'optimizer_epoch_%d' %(args.resume_epoch))\n scheduler_load_path = os.path.join(task_dir, 'checkpoints', 'scheduler_epoch_%d' %(args.resume_epoch))\n print('loading local encoder from ', enc_local_load_path)\n enc_local.load_state_dict(torch.load(enc_local_load_path, map_location='cuda'))\n print('loading silhouette decoder from ', dec_sil_load_path)\n dec_sil.load_state_dict(torch.load(dec_sil_load_path, map_location='cuda'))\n print('loading appearance decoder from ', dec_app_load_path)\n dec_app.load_state_dict(torch.load(dec_app_load_path, map_location='cuda'))\n print('loading optimizer from ', scheduler_load_path)\n optimizer.load_state_dict(torch.load(optimizer_load_path, map_location='cuda'))\n print('loading scheduler from ', scheduler_load_path)\n scheduler.load_state_dict(torch.load(scheduler_load_path, map_location='cuda'))\n\nfor ep in range(start_epoch, args.num_epoch):\n epoch_start_time = time.time()\n enc_global_sky.eval()\n enc_global_sun.eval()\n enc_local.train()\n dec_sil.train()\n dec_app.train()\n optimizer.zero_grad()\n tilmse = []\n tilmae = []\n try:\n lr = scheduler.get_last_lr()[0]\n except Exception as e:\n lr = scheduler.get_lr()[0]\n iter_data_time = time.time()\n for i, train_data in enumerate(trainLoader):\n iter_start_time = time.time()\n # retrieve the data\n global_tensor = train_data['global'].to('cuda')*4.0\n global_tensor.clamp_min_(0.0)\n global_tensor.clamp_max_(2000.0)\n local_tensor = train_data['local'].to('cuda')*4.0\n local_tensor.clamp_min_(0.0)\n local_tensor.clamp_max_(1.0) # NOTE: for local component is OK\n local_mask = train_data['local_mask'].to('cuda')\n cosine_mask_fine = train_data['cosine_mask_fine'].to('cuda')\n sun_pos_mask_fine = train_data['sun_pos_mask_fine'].to('cuda')\n\n if args.rotation_distorsion and np.random.rand() < args.rotation_distorsion_prob:\n rotate_pixels = np.random.randint(-63, 64)\n global_tensor = RotateByPixel(global_tensor, rotate_pixels)\n local_target_tensor = RotateByPixel(local_tensor, rotate_pixels)\n mask_target_tensor = RotateByPixel(local_mask, rotate_pixels)\n cosine_mask_fine = RotateByPixel(cosine_mask_fine, rotate_pixels)\n sun_pos_mask_fine = RotateByPixel(sun_pos_mask_fine, rotate_pixels)\n else:\n local_target_tensor = local_tensor\n mask_target_tensor = local_mask\n\n if args.radiometric_distorsion and np.random.rand() < args.radiometric_distorsion_prob:\n global_tensor, (exp_distortion, whl_distortion, gma_distortion) = RadiometricDistorsion(global_tensor)\n local_target_tensor = DistortImage(local_target_tensor, exp_distortion, whl_distortion, gma_distortion)\n\n if args.log_image:\n global_input_tensor = linear2log(global_tensor, args.log_mu)\n local_input_tensor = recon_local_target_tensor = linear2log(local_target_tensor, args.log_mu)\n else:\n global_input_tensor = global_tensor\n local_input_tensor = recon_local_target_tensor = local_target_tensor\n latent_global_sky = enc_global_sky(global_input_tensor.clamp_max(1.0)).detach()\n latent_global_sun = enc_global_sun(global_input_tensor).detach()\n latent_local = enc_local(local_input_tensor)\n if args.identity_loss:\n local_code_this = latent_local[0::2,:]\n local_code_other = latent_local[1::2,:]\n if args.identity_loss_type == 'L1':\n identity_loss = MAE(local_code_this, local_code_other)\n if args.identity_loss_type == 'L2':\n identity_loss = MSE(local_code_this, local_code_other)\n if args.identity_loss_type == 'COS':\n identity_loss = -COS(local_code_this, local_code_other)\n\n recon_local_mask = dec_sil(latent_local)\n recon_local = dec_app(latent_local, latent_global_sky, latent_global_sun, cosine_mask_fine)\n\n recon_mse_loss = MSE(recon_local*mask_target_tensor, recon_local_target_tensor*mask_target_tensor)\n recon_mae_loss = MAE(recon_local*mask_target_tensor, recon_local_target_tensor*mask_target_tensor)\n\n sil_mse_loss = MSE(recon_local_mask, mask_target_tensor)\n sil_mae_loss = MAE(recon_local_mask, mask_target_tensor)\n\n if args.log_image:\n image_recon_local = log2linear(recon_local.clamp_min(0), args.log_mu)\n else:\n image_recon_local = recon_local\n\n image_mse_loss = MSE(image_recon_local*mask_target_tensor, local_target_tensor*mask_target_tensor)\n image_mae_loss = MAE(image_recon_local*mask_target_tensor, local_target_tensor*mask_target_tensor)\n\n for im_idx in range(args.batch_size):\n tilmse.append(MSE(image_recon_local[im_idx]*mask_target_tensor[im_idx], local_target_tensor[im_idx]*mask_target_tensor[im_idx]).item())\n tilmae.append(MAE(image_recon_local[im_idx]*mask_target_tensor[im_idx], local_target_tensor[im_idx]*mask_target_tensor[im_idx]).item())\n\n if args.cross_render_loss:\n swaped_latent_local = torch.clone(latent_local)\n swaped_latent_local[0::2,:] = latent_local[1::2,:]\n swaped_latent_local[1::2,:] = latent_local[0::2,:]\n cross_recon_local = dec_app(swaped_latent_local, latent_global_sky, latent_global_sun, cosine_mask_fine)\n\n cross_recon_mse_loss = MSE(cross_recon_local*mask_target_tensor, recon_local_target_tensor*mask_target_tensor)\n cross_recon_mae_loss = MAE(cross_recon_local*mask_target_tensor, recon_local_target_tensor*mask_target_tensor)\n\n recon_loss = args.l1_coeff*recon_mae_loss + args.l2_coeff*recon_mse_loss\n recon_loss = recon_loss + args.l1_sil_coeff*sil_mae_loss + args.l2_sil_coeff*sil_mse_loss\n if args.identity_loss:\n recon_loss = recon_loss + args.identity_loss_coeff*identity_loss\n if args.cross_render_loss:\n recon_loss = recon_loss + args.cross_render_l1_coeff*cross_recon_mae_loss + args.cross_render_l2_coeff*cross_recon_mse_loss\n\n optimizer.zero_grad()\n recon_loss.backward()\n optimizer.step()\n\n iter_net_time = time.time()\n eta = ((iter_net_time - epoch_start_time) / (i + 1)) * len(trainLoader) - (\n iter_net_time - epoch_start_time)\n\n if (total_iter+1) % args.plot_every == 0 or args.debug:\n print(\n 'Name: {0} | Epoch: {1} | {2}/{3} | Iter:{4} | ReconErr: {5:.04f} | ImMSE: {6:.04f} | LR: {7:.04f} | dataT: {8:.02f} | netT: {9:.02f} | ETA: {10:02d}:{11:02d}'.format(\n args.name, ep, i+1, len(trainLoader), total_iter+1, recon_loss.item(), image_mse_loss.item(), lr,\n iter_start_time - iter_data_time,\n iter_net_time - iter_start_time, int(eta // 60),\n int(eta - 60 * (eta // 60))))\n if tb_logger:\n tb_logger.add_scalar(\"Local Loss (MSE Log)\" if args.log_image else \"Local Loss (MSE)\", recon_mse_loss.item(), total_iter+1)\n tb_logger.add_scalar(\"Local Loss (MAE Log)\" if args.log_image else \"Local Loss (MAE)\", recon_mae_loss.item(), total_iter+1)\n tb_logger.add_scalar(\"Sil Loss (MSE Log)\" if args.log_image else \"Sil Loss (MSE)\", sil_mse_loss.item(), total_iter+1)\n tb_logger.add_scalar(\"Sil Loss (MAE Log)\" if args.log_image else \"Sil Loss (MAE)\", sil_mae_loss.item(), total_iter+1)\n tb_logger.add_scalar(\"Image Loss (MSE)\", image_mse_loss.item(), total_iter+1)\n tb_logger.add_scalar(\"Image Loss (MAE)\", image_mae_loss.item(), total_iter+1)\n if args.identity_loss:\n tb_logger.add_scalar(\"Identity Loss (%s)\" %(args.identity_loss_type), identity_loss.item(), total_iter+1)\n if args.cross_render_loss:\n tb_logger.add_scalar(\"Cross Render Loss (MSE Log)\" if args.log_image else \"Cross Render Loss (MSE)\", cross_recon_mse_loss.item(), total_iter+1)\n tb_logger.add_scalar(\"Cross Render Loss (MAE Log)\" if args.log_image else \"Cross Render Loss (MAE)\", cross_recon_mae_loss.item(), total_iter+1)\n tb_logger.add_scalar(\"Learning Rate\", lr, total_iter+1)\n tb_logger.add_scalar(\"Data Load Time\", iter_start_time - iter_data_time, total_iter+1)\n tb_logger.add_scalar(\"Network Run Time\", iter_net_time - iter_start_time, total_iter+1)\n\n if (total_iter+1)%100==0:\n ldr_gt = GammaTMO(local_target_tensor, args.tmo_gamma, args.tmo_log_exposure)\n ldr_recon = GammaTMO(image_recon_local.clamp_min(0.0), args.tmo_gamma, args.tmo_log_exposure)\n\n image_gt_sample = local_target_tensor.cpu()[0] # C, H, W\n image_recon_sample = image_recon_local.clamp_min(0.0).cpu()[0]\n sil_gt_sample = mask_target_tensor.cpu()[0]\n sil_gt_sample = np.repeat(sil_gt_sample, 3, axis=0)\n sil_recon_sample = recon_local_mask.detach().cpu()[0]\n sil_recon_sample = np.repeat(sil_recon_sample, 3, axis=0)\n cos_mask_sample = cosine_mask_fine.detach().cpu()[0]\n cos_mask_sample = np.repeat(cos_mask_sample, 3, axis=0)\n sun_posmask_sample = sun_pos_mask_fine.cpu()[0]\n sun_posmask_sample = np.repeat(sun_posmask_sample, 3, axis=0)\n image_sample = torch.cat([image_gt_sample, image_recon_sample, cos_mask_sample], dim=2)\n image_sil_sample = torch.cat([sil_gt_sample, sil_recon_sample, sun_posmask_sample], dim=2)\n image_sample = torch.cat([image_sample, image_sil_sample], dim=1)\n\n ldr_image_gt_sample = ldr_gt.cpu()[0]\n ldr_image_recon_sample = ldr_recon.cpu()[0]\n ldr_image_sample = torch.cat([ldr_image_gt_sample, ldr_image_recon_sample, cos_mask_sample], dim=2)\n ldr_image_sample = torch.cat([ldr_image_sample, image_sil_sample], dim=1)\n\n tb_logger.add_image(\"DEBUG image sample\", image_sample, total_iter+1)\n tb_logger.add_image(\"LDR DEBUG image sample\", ldr_image_sample, total_iter+1)\n\n\n total_iter += 1\n iter_data_time = time.time()\n\n tilmse_array = np.array(tilmse)\n tilmae_array = np.array(tilmae)\n tilmae_array[tilmae_array==np.inf] = np.nan\n tilmse_array[tilmse_array==np.inf] = np.nan\n\n if tb_logger:\n tb_logger.add_scalar(\"Train Summary (MAE)\", np.nanmean(tilmae_array), ep+1)\n tb_logger.add_scalar(\"Train Summary (MSE)\", np.nanmean(tilmse_array), ep+1)\n tb_logger.add_scalar(\"Train Summary (RMSE)\", np.nanmean(np.sqrt(tilmse_array)), ep+1)\n\n print('-------------------------------------------------')\n print(' summary at %d epoch' %(ep+1))\n print('-------------------------------------------------')\n print(\"Stats: MAE = %f, MSE = %f, RMSE = %f\" %(np.nanmean(tilmae_array), np.nanmean(tilmse_array), np.nanmean(np.sqrt(tilmse_array))))\n print('-------------------------------------------------')\n print(' summary finish')\n print('-------------------------------------------------')\n\n if (ep+1) % args.eval_every == 0:\n enc_local.eval()\n dec_sil.eval()\n dec_app.eval()\n print('-------------------------------------------------')\n print(' eval at %d epoch' %(ep+1))\n print('-------------------------------------------------')\n os.makedirs(os.path.join(task_dir, 'samples'), exist_ok=True)\n os.makedirs(os.path.join(task_dir, 'samples', 'epoch_%d' %(ep+1)), exist_ok=True)\n os.makedirs(os.path.join(task_dir, 'samples', 'epoch_%d' %(ep+1), 'hdr'), exist_ok=True)\n os.makedirs(os.path.join(task_dir, 'samples', 'epoch_%d' %(ep+1), 'ldr'), exist_ok=True)\n vlmse = []\n vlmae = []\n vsilmse = []\n vsilmae = []\n vssim = []\n vilmse = []\n vilmae = []\n with torch.no_grad():\n val_start_time = time.time()\n iter_data_time = time.time()\n for i, val_data in enumerate(valLoader):\n iter_start_time = time.time()\n # retrieve the data\n global_tensor = val_data['global'].to('cuda')*4.0\n global_tensor.clamp_min_(0.0)\n global_tensor.clamp_max_(2000.0)\n local_tensor = val_data['local'].to('cuda')*4.0\n local_tensor.clamp_min_(0.0)\n local_tensor.clamp_max_(1.0)\n local_mask = val_data['local_mask'].to('cuda')\n cosine_mask_fine = val_data['cosine_mask_fine'].to('cuda')\n sun_pos_mask_fine = val_data['sun_pos_mask_fine'].to('cuda')\n\n local_target_tensor = local_tensor\n mask_target_tensor = local_mask\n\n if args.log_image:\n global_input_tensor = linear2log(global_tensor, args.log_mu)\n local_input_tensor = recon_local_target_tensor = linear2log(local_tensor, args.log_mu)\n else:\n global_input_tensor = global_tensor\n local_input_tensor = recon_local_target_tensor = local_tensor\n \n latent_global_sky = enc_global_sky(global_input_tensor.clamp_max(1.0))\n latent_global_sun = enc_global_sun(global_input_tensor)\n latent_local = enc_local(local_input_tensor)\n\n recon_local_mask = dec_sil(latent_local)\n recon_local = dec_app(latent_local, latent_global_sky, latent_global_sun, cosine_mask_fine)\n\n recon_mse_loss = MSE(recon_local*local_mask, recon_local_target_tensor*local_mask)\n recon_mae_loss = MAE(recon_local*local_mask, recon_local_target_tensor*local_mask)\n\n sil_mse_loss = MSE(recon_local_mask, mask_target_tensor)\n sil_mae_loss = MAE(recon_local_mask, mask_target_tensor)\n\n if args.log_image:\n image_recon_local = log2linear(recon_local.clamp_min(0), args.log_mu)\n else:\n image_recon_local = recon_local\n\n image_mse_loss = MSE(image_recon_local*local_mask, local_target_tensor*local_mask)\n image_mae_loss = MAE(image_recon_local*local_mask, local_target_tensor*local_mask)\n \n ldr_gt = GammaTMO(local_target_tensor, args.tmo_gamma, args.tmo_log_exposure)\n ldr_recon = GammaTMO(image_recon_local.clamp_min(0.0), args.tmo_gamma, args.tmo_log_exposure)\n\n iter_net_time = time.time()\n eta = ((iter_net_time - val_start_time) / (i + 1)) * len(valLoader) - (\n iter_net_time - val_start_time)\n\n print('Name: {0} | Epoch: {1} | {2}/{3} | ImMAE(Val): {4:.04f} | ImMSE(Val): {5:.04f} | dataT: {6:.02f} | netT: {7:.02f} | ETA: {8:02d}:{9:02d}'.format(\n args.name, ep, i+1, len(valLoader), image_mae_loss.item(), image_mse_loss.item(),\n iter_start_time - iter_data_time,\n iter_net_time - iter_start_time, int(eta // 60),\n int(eta - 60 * (eta // 60))))\n \n iter_data_time = time.time()\n \n if tb_logger and (i+1) % args.tb_save_image_every == 0:\n sample_idx = (i+1) // args.tb_save_image_every\n \n image_gt_sample = local_target_tensor.cpu()[0] # C, H, W\n image_recon_sample = image_recon_local.clamp_min(0.0).cpu()[0]\n sil_gt_sample = mask_target_tensor.cpu()[0]\n sil_gt_sample = np.repeat(sil_gt_sample, 3, axis=0)\n sil_recon_sample = recon_local_mask.cpu()[0]\n sil_recon_sample = np.repeat(sil_recon_sample, 3, axis=0)\n cos_mask_sample = cosine_mask_fine.cpu()[0]\n cos_mask_sample = np.repeat(cos_mask_sample, 3, axis=0)\n sun_posmask_sample = sun_pos_mask_fine.cpu()[0]\n sun_posmask_sample = np.repeat(sun_posmask_sample, 3, axis=0)\n image_sample = torch.cat([image_gt_sample, image_recon_sample, cos_mask_sample], dim=2)\n image_sil_sample = torch.cat([sil_gt_sample, sil_recon_sample, sun_posmask_sample], dim=2)\n image_sample = torch.cat([image_sample, image_sil_sample], dim=1)\n\n ldr_image_gt_sample = ldr_gt.cpu()[0]\n ldr_image_recon_sample = ldr_recon.cpu()[0]\n ldr_image_sample = torch.cat([ldr_image_gt_sample, ldr_image_recon_sample, cos_mask_sample], dim=2)\n ldr_image_sample = torch.cat([ldr_image_sample, image_sil_sample], dim=1)\n\n tb_logger.add_image(\"Val image sample %d\" %(sample_idx), image_sample, ep+1)\n tb_logger.add_image(\"LDR Val image sample %d\" %(sample_idx), ldr_image_sample, ep+1)\n imageio.imwrite(os.path.join(task_dir, 'samples', 'epoch_%d' %(ep+1), 'hdr', 'sample_%d.hdr' %(sample_idx)), np.transpose(image_sample.numpy(), (1, 2, 0)), format='HDR-FI')\n imageio.imwrite(os.path.join(task_dir, 'samples', 'epoch_%d' %(ep+1), 'ldr', 'sample_%d.png' %(sample_idx)), (np.transpose(ldr_image_sample.numpy(), (1, 2, 0))*255.0).astype(np.uint8), format='PNG')\n\n vlmse.append(recon_mse_loss.item())\n vlmae.append(recon_mae_loss.item())\n vsilmse.append(sil_mse_loss.item())\n vsilmae.append(sil_mae_loss.item())\n vilmse.append(image_mse_loss.item())\n vilmae.append(image_mae_loss.item())\n\n vlmse_array = np.array(vlmse)\n vlmae_array = np.array(vlmae)\n vsilmse_array = np.array(vsilmse)\n vsilmae_array = np.array(vsilmae)\n vilmse_array = np.array(vilmse)\n vilmae_array = np.array(vilmae)\n vilmae_array[vilmae_array==np.inf] = np.nan\n vilmse_array[vilmse_array==np.inf] = np.nan\n\n if tb_logger:\n tb_logger.add_scalar(\"Val Local Loss (MSE Log)\" if args.log_image else \"Val Local Loss (MSE)\", vlmse_array.mean(), ep+1)\n tb_logger.add_scalar(\"Val Local Loss (MAE Log)\" if args.log_image else \"Val Local Loss (MAE)\", vlmae_array.mean(), ep+1)\n tb_logger.add_scalar(\"Val Sil Loss (MSE Log)\" if args.log_image else \"Val Sil Loss (MSE)\", vsilmse_array.mean(), ep+1)\n tb_logger.add_scalar(\"Val Sil Loss (MAE Log)\" if args.log_image else \"Val Sil Loss (MAE)\", vsilmae_array.mean(), ep+1)\n tb_logger.add_scalar(\"Val Image Loss (MAE)\", np.nanmean(vilmae_array), ep+1)\n tb_logger.add_scalar(\"Val Image Loss (MSE)\", np.nanmean(vilmse_array), ep+1)\n tb_logger.add_scalar(\"Val Image Loss (RMSE)\", np.nanmean(np.sqrt(vilmse_array)), ep+1)\n\n print(\"Stats: MAE = %f, MSE = %f, RMSE = %f\" %(np.nanmean(vilmae_array), np.nanmean(vilmse_array), np.nanmean(np.sqrt(vilmse_array))))\n\n print('-------------------------------------------------')\n print(' eval finish')\n print('-------------------------------------------------')\n\n enc_local.train()\n dec_sil.train()\n dec_app.train()\n\n if (ep+1) % args.save_every == 0:\n os.makedirs(os.path.join(task_dir, 'checkpoints'), exist_ok=True)\n torch.save(enc_local.state_dict(), os.path.join(task_dir, 'checkpoints', 'enc_local_latest'))\n torch.save(enc_local.state_dict(), os.path.join(task_dir, 'checkpoints', 'enc_local_epoch_%d' %(ep+1)))\n torch.save(dec_sil.state_dict(), os.path.join(task_dir, 'checkpoints', 'dec_sil_latest'))\n torch.save(dec_sil.state_dict(), os.path.join(task_dir, 'checkpoints', 'dec_sil_epoch_%d' %(ep+1)))\n torch.save(dec_app.state_dict(), os.path.join(task_dir, 'checkpoints', 'dec_app_latest'))\n torch.save(dec_app.state_dict(), os.path.join(task_dir, 'checkpoints', 'dec_app_epoch_%d' %(ep+1)))\n torch.save(optimizer.state_dict(), os.path.join(task_dir, 'checkpoints', 'optimizer_latest'))\n torch.save(optimizer.state_dict(), os.path.join(task_dir, 'checkpoints', 'optimizer_epoch_%d' %(ep+1)))\n torch.save(scheduler.state_dict(), os.path.join(task_dir, 'checkpoints', 'scheduler_latest'))\n torch.save(scheduler.state_dict(), os.path.join(task_dir, 'checkpoints', 'scheduler_epoch_%d' %(ep+1)))\n\n scheduler.step()\n", "repo_name": "ChemJeff/SOLD-Net", "sub_path": "encoding/local_train.py", "file_name": "local_train.py", "file_ext": "py", "file_size_in_byte": 27725, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 12, "dataset": "github-code", "pt": "20", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 67, "usage_type": "call"}, {"api_name": "os.path", "line_number": 67, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path", "line_number": 68, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 70, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 71, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 71, "usage_type": "call"}, {"api_name": "os.path", "line_number": 71, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path", "line_number": 72, "usage_type": "attribute"}, {"api_name": "model.Autoencoder.GlobalEncoder", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 81, "usage_type": "call"}, {"api_name": "model.Autoencoder.GlobalEncoder", "line_number": 83, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 84, "usage_type": "call"}, {"api_name": "model.Autoencoder.LocalEncoder", "line_number": 86, "usage_type": "call"}, {"api_name": "model.Autoencoder.LocalSilDecoder", "line_number": 87, "usage_type": "call"}, {"api_name": "model.Autoencoder.LocalAppSplitRenderer", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.nn.MSELoss", "line_number": 89, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 89, "usage_type": "attribute"}, {"api_name": "torch.nn.L1Loss", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 90, "usage_type": "attribute"}, {"api_name": "torch.nn.BCELoss", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 91, "usage_type": "attribute"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 92, "usage_type": "attribute"}, {"api_name": "utils.loss.CosineSimilarity", "line_number": 93, "usage_type": "call"}, {"api_name": "utils.loss.NormalNLLLoss", "line_number": 94, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 96, "usage_type": "attribute"}, {"api_name": "torch.optim.lr_scheduler.MultiStepLR", "line_number": 100, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 100, "usage_type": "attribute"}, {"api_name": "data.dataset_synthetic_local.SynLocalDataset", "line_number": 105, "usage_type": "call"}, {"api_name": "data.dataset_synthetic_local.SynLocalDataset", "line_number": 106, "usage_type": "call"}, {"api_name": "data.local_identity_sampler.RandomLocalIdentiyiSampler", "line_number": 108, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 110, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 111, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 122, "usage_type": "call"}, {"api_name": "os.path", "line_number": 122, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 123, "usage_type": "call"}, {"api_name": "os.path", "line_number": 123, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 124, "usage_type": "call"}, {"api_name": "os.path", "line_number": 124, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 125, "usage_type": "call"}, {"api_name": "os.path", "line_number": 125, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 126, "usage_type": "call"}, {"api_name": "os.path", "line_number": 126, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 128, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 132, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 134, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 136, "usage_type": "call"}, {"api_name": "time.time", "line_number": 139, "usage_type": "call"}, {"api_name": "time.time", "line_number": 152, "usage_type": "call"}, {"api_name": "time.time", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 166, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 167, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 167, "usage_type": "attribute"}, {"api_name": "utils.mapping.rotation.RotateByPixel", "line_number": 168, "usage_type": "call"}, {"api_name": "utils.mapping.rotation.RotateByPixel", "line_number": 169, "usage_type": "call"}, {"api_name": "utils.mapping.rotation.RotateByPixel", "line_number": 170, "usage_type": "call"}, {"api_name": "utils.mapping.rotation.RotateByPixel", "line_number": 171, "usage_type": "call"}, {"api_name": "utils.mapping.rotation.RotateByPixel", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 177, "usage_type": "attribute"}, {"api_name": "utils.mapping.radiometric_distorsion.RadiometricDistorsion", "line_number": 178, "usage_type": "call"}, {"api_name": "utils.mapping.radiometric_distorsion.DistortImage", "line_number": 179, "usage_type": "call"}, {"api_name": "utils.mapping.log_mapping.linear2log", "line_number": 182, "usage_type": "call"}, {"api_name": "utils.mapping.log_mapping.linear2log", "line_number": 183, "usage_type": "call"}, {"api_name": "utils.mapping.log_mapping.log2linear", "line_number": 210, "usage_type": "call"}, {"api_name": "torch.clone", "line_number": 222, "usage_type": "call"}, {"api_name": "time.time", "line_number": 241, "usage_type": "call"}, {"api_name": "utils.tonemapping.GammaTMO", "line_number": 269, "usage_type": "call"}, {"api_name": "utils.tonemapping.GammaTMO", "line_number": 270, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 275, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 277, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 279, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 281, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 282, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 283, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 284, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 288, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 289, "usage_type": "call"}, {"api_name": "time.time", "line_number": 296, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 298, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 299, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 300, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 300, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 301, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 301, "usage_type": "attribute"}, {"api_name": "numpy.nanmean", "line_number": 304, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 305, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 306, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 306, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 311, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 311, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 323, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 323, "usage_type": "call"}, {"api_name": "os.path", "line_number": 323, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 324, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 324, "usage_type": "call"}, {"api_name": "os.path", "line_number": 324, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 325, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 325, "usage_type": "call"}, {"api_name": "os.path", "line_number": 325, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 326, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 326, "usage_type": "call"}, {"api_name": "os.path", "line_number": 326, "usage_type": "attribute"}, {"api_name": "torch.no_grad", "line_number": 334, "usage_type": "call"}, {"api_name": "time.time", "line_number": 335, "usage_type": "call"}, {"api_name": "time.time", "line_number": 336, "usage_type": "call"}, {"api_name": "time.time", "line_number": 338, "usage_type": "call"}, {"api_name": "utils.mapping.log_mapping.linear2log", "line_number": 354, "usage_type": "call"}, {"api_name": "utils.mapping.log_mapping.linear2log", "line_number": 355, "usage_type": "call"}, {"api_name": "utils.mapping.log_mapping.log2linear", "line_number": 374, "usage_type": "call"}, {"api_name": "utils.tonemapping.GammaTMO", "line_number": 381, "usage_type": "call"}, {"api_name": "utils.tonemapping.GammaTMO", "line_number": 382, "usage_type": "call"}, {"api_name": "time.time", "line_number": 384, "usage_type": "call"}, {"api_name": "time.time", "line_number": 394, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 402, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 404, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 406, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 408, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 409, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 410, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 411, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 415, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 416, "usage_type": "call"}, {"api_name": "imageio.imwrite", "line_number": 420, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 420, "usage_type": "call"}, {"api_name": "os.path", "line_number": 420, "usage_type": "attribute"}, {"api_name": "numpy.transpose", "line_number": 420, "usage_type": "call"}, {"api_name": "imageio.imwrite", "line_number": 421, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 421, "usage_type": "call"}, {"api_name": "os.path", "line_number": 421, "usage_type": "attribute"}, {"api_name": "numpy.transpose", "line_number": 421, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 421, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 430, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 431, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 432, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 433, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 434, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 435, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 436, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 436, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 437, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 437, "usage_type": "attribute"}, {"api_name": "numpy.nanmean", "line_number": 444, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 445, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 446, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 446, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 448, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 448, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 459, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 459, "usage_type": "call"}, {"api_name": "os.path", "line_number": 459, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 460, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 460, "usage_type": "call"}, {"api_name": "os.path", "line_number": 460, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 461, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 461, "usage_type": "call"}, {"api_name": "os.path", "line_number": 461, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 462, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 462, "usage_type": "call"}, {"api_name": "os.path", "line_number": 462, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 463, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 463, "usage_type": "call"}, {"api_name": "os.path", "line_number": 463, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 464, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 464, "usage_type": "call"}, {"api_name": "os.path", "line_number": 464, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 465, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 465, "usage_type": "call"}, {"api_name": "os.path", "line_number": 465, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 466, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 466, "usage_type": "call"}, {"api_name": "os.path", "line_number": 466, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 467, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 467, "usage_type": "call"}, {"api_name": "os.path", "line_number": 467, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 468, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 468, "usage_type": "call"}, {"api_name": "os.path", "line_number": 468, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 469, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 469, "usage_type": "call"}, {"api_name": "os.path", "line_number": 469, "usage_type": "attribute"}]} +{"seq_id": "34485657733", "text": "import wtforms\n\n\nclass TinyMce(object):\n \"\"\"\n Automatically makes TextProperty fields into TinyMCE editors (for the admin interface\n \"\"\"\n\n def __init__(self, controller):\n self.controller = controller\n self.controller.events.before_render += self.before_render.__get__(self)\n\n def before_render(self, controller, *args, **kwargs):\n form = controller.context.get('form', None)\n if form and isinstance(form, (wtforms.Form)):\n for field in form:\n if isinstance(field, wtforms.fields.simple.TextAreaField):\n field.flags.tinymce = True\n", "repo_name": "jonaeroy/woolies-form", "sub_path": "ferris/components/tiny_mce.py", "file_name": "tiny_mce.py", "file_ext": "py", "file_size_in_byte": 619, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "wtforms.Form", "line_number": 15, "usage_type": "attribute"}, {"api_name": "wtforms.fields", "line_number": 17, "usage_type": "attribute"}]} +{"seq_id": "42511843189", "text": "\"\"\"\n===========\nMultiSpike\n===========\n:class:`~sinabs.activation.MultiSpike` activation function.\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport torch\n\nimport sinabs.activation as sina\n\nv_mem = torch.linspace(0, 5.5, 500)\n\nspike_threshold = 1.0\nactivations = sina.MultiSpike.apply(v_mem, spike_threshold, sina.MultiGaussian())\nplt.plot(v_mem, activations)\nplt.xlabel(\"Neuron membrane potential\")\nplt.ylabel(\"Spike activation\")\nplt.tight_layout()\n", "repo_name": "synsense/sinabs", "sub_path": "docs/gallery/spike_fns/plot_multispike.py", "file_name": "plot_multispike.py", "file_ext": "py", "file_size_in_byte": 444, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 52, "dataset": "github-code", "pt": "20", "api": [{"api_name": "torch.linspace", "line_number": 13, "usage_type": "call"}, {"api_name": "sinabs.activation.MultiSpike.apply", "line_number": 16, "usage_type": "call"}, {"api_name": "sinabs.activation.MultiSpike", "line_number": 16, "usage_type": "attribute"}, {"api_name": "sinabs.activation", "line_number": 16, "usage_type": "name"}, {"api_name": "sinabs.activation.MultiGaussian", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}]} +{"seq_id": "36426143202", "text": "\"\"\"\nbasic_kmeans_service.py\n-----------------------\nService for performing KMeans clustering using optimized KMeans and MiniBatch KMeans.\n\"\"\"\n\n# pylint: disable=too-many-arguments\n# pylint: disable=R0914\n\nimport logging\nfrom typing import Optional, Union\nimport pandas as pd\nfrom fastapi import UploadFile\n\nfrom app.services.custom_kmeans import OptimizedKMeans, OptimizedMiniBatchKMeans\nfrom app.models.custom_kmeans_model import BasicKMeansResult\nfrom app.services.utils import (process_uploaded_file,normalize_dataframe, \n handle_categorical_data, transform_to_2d_cluster_model)\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\ndef perform_kmeans_from_file(\n file: UploadFile,\n distance_metric: str,\n kmeans_type: str,\n user_id: int,\n request_id: int,\n selected_columns: Union[None, list[int]] = None,\n user_k: Optional[int] = None,\n normalize: bool = True\n) -> BasicKMeansResult:\n \"\"\"\n Perform KMeans clustering on an uploaded file.\n \"\"\"\n data_frame, filename = process_uploaded_file(file, selected_columns)\n logger.info(\"Processed uploaded file. Shape: %s\", data_frame.shape)\n return _perform_kmeans(data_frame, filename, distance_metric, \n kmeans_type, user_id, request_id, user_k, normalize)\n\n\ndef perform_kmeans_from_dataframe(\n data_frame: pd.DataFrame,\n filename: str,\n distance_metric: str,\n kmeans_type: str,\n user_id: int,\n request_id: int,\n advanced_k: Optional[int] = None,\n normalize: bool = True\n) -> BasicKMeansResult:\n \"\"\"\n Perform KMeans clustering on a DataFrame.\n \"\"\"\n return _perform_kmeans(data_frame, filename, distance_metric, \n kmeans_type, user_id, request_id, advanced_k, normalize)\n\n# pylint: disable=R0801\ndef _perform_kmeans(\n data_frame: pd.DataFrame,\n filename: str,\n distance_metric: str,\n kmeans_type: str,\n user_id: int,\n request_id: int,\n k: int,\n normalize: bool = True\n) -> BasicKMeansResult:\n data_frame_cat=handle_categorical_data(data_frame)\n \n if normalize:\n data_frame = normalize_dataframe(data_frame_cat)\n else: \n data_frame = data_frame_cat\n \n data_np = data_frame.values\n \n logger.info(data_np[:5])\n \n logger.info(\"Converted data to numpy array. Shape: %s\", data_np.shape)\n\n # Initialize the KMeans model\n if kmeans_type == \"OptimizedKMeans\":\n model = OptimizedKMeans(k, distance_metric)\n elif kmeans_type == \"OptimizedMiniBatchKMeans\":\n model = OptimizedMiniBatchKMeans(k, distance_metric)\n else:\n raise ValueError(f\"Invalid kmeans_type: {kmeans_type}\")\n\n logger.info(\"Initialized %s model.\", kmeans_type)\n\n # Fit the model\n model.fit(data_np)\n logger.info(\"Fitted the model.\")\n\n # Add cluster assignments to the DataFrame\n data_frame['cluster'] = model.assign_labels(data_np)\n logger.info(\"Assigned labels to data.\")\n\n # Transform the results to the Cluster model structure\n clusters = transform_to_2d_cluster_model(data_frame, model.cluster_centers_)\n logger.info(\"Transformed data to Cluster models.\")\n\n x_label = data_frame.columns[0]\n y_label = data_frame.columns[1]\n\n logger.info(\"Completed perform_kmeans function.\")\n return BasicKMeansResult(\n user_id=user_id,\n request_id=request_id,\n cluster=clusters,\n x_label=x_label,\n y_label=y_label,\n iterations=model.iterations_,\n used_distance_metric=distance_metric,\n name=filename,\n k_value=k\n )\n", "repo_name": "axellotl22/progback", "sub_path": "app/services/basic_kmeans_service.py", "file_name": "basic_kmeans_service.py", "file_ext": "py", "file_size_in_byte": 3588, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "logging.getLogger", "line_number": 20, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 21, "usage_type": "attribute"}, {"api_name": "fastapi.UploadFile", "line_number": 24, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 29, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 30, "usage_type": "name"}, {"api_name": "app.services.utils.process_uploaded_file", "line_number": 36, "usage_type": "call"}, {"api_name": "app.models.custom_kmeans_model.BasicKMeansResult", "line_number": 32, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 43, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 49, "usage_type": "name"}, {"api_name": "app.models.custom_kmeans_model.BasicKMeansResult", "line_number": 51, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 60, "usage_type": "attribute"}, {"api_name": "app.services.utils.handle_categorical_data", "line_number": 69, "usage_type": "call"}, {"api_name": "app.services.utils.normalize_dataframe", "line_number": 72, "usage_type": "call"}, {"api_name": "app.services.custom_kmeans.OptimizedKMeans", "line_number": 84, "usage_type": "call"}, {"api_name": "app.services.custom_kmeans.OptimizedMiniBatchKMeans", "line_number": 86, "usage_type": "call"}, {"api_name": "app.services.utils.transform_to_2d_cluster_model", "line_number": 101, "usage_type": "call"}, {"api_name": "app.models.custom_kmeans_model.BasicKMeansResult", "line_number": 108, "usage_type": "call"}, {"api_name": "app.models.custom_kmeans_model.BasicKMeansResult", "line_number": 68, "usage_type": "name"}]} +{"seq_id": "34303375438", "text": "import json\nfrom datetime import datetime\n\nfrom django.contrib import messages\nfrom django.contrib.auth import get_user_model, authenticate, login, logout\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth.tokens import default_token_generator\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.exceptions import ValidationError\nfrom django.core.mail import EmailMessage\nfrom django.core.paginator import Paginator\nfrom django.core.validators import validate_email\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.urls import reverse\nfrom django.utils.encoding import force_bytes\nfrom django.utils.html import escape\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom django.views import View\nfrom . import models, forms, functions\nfrom django.utils.translation import gettext_lazy as _\nfrom . import sendgrid\n\n\nclass HomeView(View):\n def get(self, request):\n all_donations = models.Donation.objects.all()\n total_bags = sum([int(donation.quantity) for donation in all_donations])\n total_institutions = len(set([donation.institution for donation in all_donations]))\n\n context = {\n \"total_bags\": total_bags,\n \"total_institutions\": total_institutions,\n }\n if \"fetch_stats\" in request.GET:\n data = context\n return JsonResponse(data)\n\n foundations = models.Institution.objects.filter(type=1).order_by(\"name\")\n organizations = models.Institution.objects.filter(type=2).order_by(\"name\")\n collections = models.Institution.objects.filter(type=3).order_by(\"name\")\n results_per_page = 3\n\n paginated_foundations = Paginator(foundations, results_per_page)\n pf_dict = {page: paginated_foundations.page(page) for page in paginated_foundations.page_range}\n pf_page_range = paginated_foundations.get_elided_page_range(\n paginated_foundations.num_pages, on_each_side=2, on_ends=2)\n\n paginated_organizations = Paginator(organizations, results_per_page)\n po_dict = {page: paginated_organizations.page(page) for page in paginated_organizations.page_range}\n paginated_collections = Paginator(collections, results_per_page)\n pc_dict = {page: paginated_collections.page(page) for page in paginated_collections.page_range}\n\n context.update({\n \"pf_dict\": pf_dict,\n \"pf_page_range\": pf_page_range,\n \"po_dict\": po_dict,\n \"pc_dict\": pc_dict,\n })\n\n return render(request, 'index.html', context)\n\n\nclass AddDonationView(LoginRequiredMixin, View):\n def get(self, request):\n form = forms.DonationForm()\n categories = models.Category.objects.all()\n institutions = models.Institution.objects.all()\n countries = [\n {\"country\": _(\"Polska\"), \"number\": \"+48\"},\n {\"country\": _(\"Niemcy\"), \"number\": \"+49\"},\n {\"country\": _(\"Ukraina\"), \"number\": \"+380\"},\n ]\n return render(request, 'form.html', context={\n \"categories\": categories,\n \"institutions\": institutions,\n \"form\": form,\n \"countries\": countries,\n })\n\n def post(self, request):\n data = json.loads(request.body)\n form = forms.DonationForm(data)\n if form.is_valid():\n form = form.cleaned_data\n user = request.user\n phone_number = form.get(\"phone_number\")\n address = form.get(\"address\")\n zip_code = form.get(\"zip_code\")\n city = form.get(\"city\")\n bags = form.get(\"bags\")\n pick_up_date = form.get(\"pick_up_date\")\n pick_up_time = form.get(\"pick_up_time\")\n pick_up_comment = form.get(\"pick_up_comment\")\n input_institution = data.get(\"institution\")\n if input_institution.isdigit():\n institution = get_object_or_404(models.Institution, pk=int(input_institution))\n else:\n institution = None\n\n input_categories = data.get(\"categories\")\n cleaned_input_categories = [int(cat) for cat in input_categories if cat.isdigit()]\n categories = [models.Category.objects.filter(pk=pk)[0] for pk in cleaned_input_categories\n if models.Category.objects.filter(pk=pk)]\n\n if (categories and institution and\n functions.validate_phone_number(phone_number) and\n functions.validate_zip_code(zip_code) and\n functions.validate_date_and_time(pick_up_date, pick_up_time)\n and address and city and bags):\n donation = models.Donation.objects.create(\n quantity=bags,\n institution=institution,\n address=address,\n phone_number=phone_number,\n city=city,\n zip_code=zip_code,\n pick_up_date=pick_up_date,\n pick_up_time=pick_up_time,\n pick_up_comment=pick_up_comment,\n user=user,\n )\n donation.save()\n donation.categories.set(categories)\n donation.save()\n\n # Send email\n now = datetime.now()\n to_email = user.email\n subject = \"Potwierdzenie przekazania daru\"\n content = f\"\"\"\n To jest automatyczne potwierdzenie, nie odpowiadaj na nie.\n \n Cześć {user.username}!\n Dnia {now.date()} o godzinie {now.strftime(\"%H:%M\")} zarejestrowaliśmy nową darowiznę przekazaną z Twojego konta.\n Szczegóły poniżej:\n \n Kategorie: {', '.join([cat.name for cat in categories])}\n Organizacja: {institution}\n Liczba worków: {bags}\n Adres odbioru: {', '.join([address, zip_code, city])}\n Termin odbioru: {str(pick_up_date) + str(pick_up_time)}\n Dane kontaktowe: {', '.join([user.first_name, user.last_name, phone_number])}\n \n Dziękujemy!\n \"\"\"\n # Sendgrid service\n # sendgrid.send_mail(to_email, subject, content)\n\n # Old, console version, for testing\n donation_email = EmailMessage(subject, content, to=[to_email])\n donation_email.send()\n\n return redirect('app:donation_confirmation')\n else:\n messages.error(request, _(\"Formularz nie został zapisany. Popraw dane\"))\n return redirect('app:home')\n else:\n messages.error(request, form.errors)\n return redirect('app:add_donation')\n\n\nclass DonationConfirmedView(LoginRequiredMixin, View):\n def get(self, request):\n return render(request, 'form-confirmation.html')\n\n\nclass LoginView(View):\n def get(self, request):\n return render(request, 'login.html')\n\n def post(self, request):\n email = request.POST.get('email')\n password = request.POST.get('password')\n user = authenticate(request, username=email, password=password)\n if user is not None:\n login(request, user)\n return redirect('app:profile')\n else:\n messages.error(request, _(\"Niepoprawne dane\"))\n return redirect('app:register')\n\n\nclass RegisterView(View):\n def get(self, request):\n form = forms.CustomUserCreationForm()\n return render(request, 'register.html', context={\"form\": form})\n\n def post(self, request):\n\n form = forms.CustomUserCreationForm(request.POST)\n if form.is_valid():\n email = form.cleaned_data.get(\"email\")\n password1 = form.cleaned_data.get(\"password1\")\n password2 = form.cleaned_data.get(\"password2\")\n first_name = form.cleaned_data.get(\"name\")\n last_name = form.cleaned_data.get(\"surname\")\n\n user_exists = get_user_model().objects.filter(email=email)\n if user_exists:\n messages.error(request, _(\"Taki użytkownik już istnieje\"))\n return render(request, 'register.html', context={\"form\": form})\n\n # if password1 != password2:\n # messages.error(request, _(\"Hasła nie są zgodne\"))\n # return render(request, 'register.html', context={\"form\": form})\n\n user = form.save(commit=False)\n user.set_password(password1)\n user.username = email\n user.first_name = first_name\n user.last_name = last_name\n user.is_active = False\n user.save()\n\n # Send email\n subject = \"Aktywacja konta\"\n current_site = get_current_site(request)\n uid = urlsafe_base64_encode(force_bytes(user.pk))\n token = default_token_generator.make_token(user)\n activation_link = f\"http://{current_site}/accounts/activate/{uid}/{token}/\"\n content = f\"Cześć {user.username}!\\n Kliknij w poniższy link, by aktywować konto:\\n{activation_link}\"\n to_email = email\n sendgrid.send_mail(to_email, subject, content)\n\n # Old, console version\n # activation = EmailMessage(subject, content, to=[to_email])\n # activation.send()\n\n messages.success(request, _(\"Utworzono nowe konto\"))\n return render(request, \"registration/activation_link_sent.html\")\n\n messages.error(request, _(\"Błąd podczas zapisywania formularza\"))\n return render(request, 'register.html', context={\"form\": form})\n\n\nclass ActivateView(View):\n def get(self, request, uid, token):\n try:\n uid = urlsafe_base64_decode(uid).decode()\n user = get_user_model().objects.get(pk=uid)\n except(TypeError, ValueError, OverflowError, get_user_model().DoesNotExist):\n user = None\n if user is not None and default_token_generator.check_token(user, token):\n # activate user and log in:\n user.is_active = True\n user.save()\n login(request, user)\n messages.success(request, _(\"Pomyślnie aktywowano konto\"))\n return redirect(\"app:profile\")\n messages.error(request, _(\"Błędny link aktywacyjny\"))\n return redirect(\"app:register\")\n\n\nclass LogoutView(View):\n def get(self, request):\n logout(request)\n return redirect('app:home')\n\n\ndef json_donation(donation, status):\n donation = {\n \"pk\": donation.pk,\n \"quantity\": donation.quantity,\n \"categories\": [cat.name for cat in donation.categories.all()],\n \"institution\": donation.institution.name,\n \"pick_up_date\": donation.pick_up_date,\n \"pick_up_time\": donation.pick_up_time,\n \"is_taken\": donation.is_taken,\n \"status\": status,\n }\n\n data = {\n \"donation\": donation,\n }\n return data\n\n\nclass ProfileView(View):\n def get(self, request):\n User = get_user_model()\n user = User.objects.get(pk=request.user.pk)\n donations = models.Donation.objects.filter(user=user).order_by(\"pick_up_date\")\n return render(request, \"profile.html\", context={\"user\": user, \"donations\": donations})\n\n def post(self, request):\n data = json.loads(request.body)\n donation = get_object_or_404(models.Donation, pk=data.get(\"donationId\"))\n User = get_user_model()\n user = User.objects.get(pk=request.user.pk)\n\n if donation.user == user:\n status = data.get(\"takenStatus\")\n if status == 'true':\n donation.is_taken = True\n else:\n donation.is_taken = False\n donation.save()\n return JsonResponse(json_donation(donation, status))\n else:\n messages.error(request, _(\"Nie masz uprawnień do modyfikacji\"))\n return redirect('app:home')\n\n\nclass SettingsView(LoginRequiredMixin, View):\n def get(self, request):\n User = get_user_model()\n user = get_object_or_404(User, pk=request.user.pk)\n form = forms.CustomUserCreationForm(initial={\n \"name\": user.first_name,\n \"surname\": user.last_name,\n \"email\": user.email,\n })\n return render(request, 'settings.html', context={\"form\": form})\n\n def post(self, request):\n\n form = forms.CustomUserCreationForm(request.POST)\n if form.is_valid():\n user = request.user\n data = form.cleaned_data\n email = data.get(\"email\")\n first_name = data.get(\"name\")\n last_name = data.get(\"surname\")\n password = data.get(\"password1\")\n\n # check if a new email is already taken\n email_exists = get_user_model().objects.filter(email=email)\n for e_e in email_exists:\n if e_e.pk != user.pk:\n messages.error(request, _(\"Inny użytkownik ma już taki adres email\"))\n return redirect('app:settings')\n # check if the password is correct and make changes\n user = get_object_or_404(get_user_model(), pk=user.pk)\n if user.check_password(password):\n user.first_name = first_name\n user.last_name = last_name\n user.email = email\n user.username = email\n user.save()\n messages.success(request, _(\"Poprawnie zmieniono dane\"))\n return redirect('app:profile')\n else:\n messages.error(request, _(\"Podano niepoprawne dane\"))\n return redirect(\"app:settings\")\n\n messages.error(request, _(\"Podano niepoprawne dane\"))\n return redirect(\"app:settings\")\n\n\nclass CloseView(LoginRequiredMixin, View):\n def get(self, request):\n user = request.user\n form = forms.CustomUserCreationForm(initial={\n \"email\": user.email,\n })\n return render(request, \"close.html\", context={\"form\": form})\n\n def post(self, request):\n user = request.user\n form = forms.CustomUserCreationForm(request.POST)\n if form.is_valid():\n password = form.cleaned_data.get(\"password1\")\n if user.check_password(password):\n user.is_active = False\n user.save()\n messages.success(request, _(\"Konto zostało zamknięte.\"))\n return redirect(\"app:home\")\n messages.error(request, _(\"Niepoprawne dane\"))\n return redirect(\"app:close\")\n\n\nclass CheckEmailView(View):\n def post(self, request):\n email = json.loads(request.body).get(\"email\")\n\n try:\n validate_email(email)\n valid = True\n except ValidationError:\n valid = False\n\n if valid:\n exists = get_user_model().objects.filter(email=email)\n else:\n exists = []\n\n return JsonResponse({\"email\": email, \"valid\": valid, \"exists\": len(exists)})\n\n\nclass ContactView(View):\n def post(self, request):\n name = request.POST.get(\"name\")\n surname = request.POST.get(\"surname\")\n message = request.POST.get(\"message\")\n origin_site = request.headers.get(\"referer\", reverse('app:home'))\n if name and surname and message:\n if len(name) >= 3 and len(surname) >= 3 and len(message) >= 10:\n name = escape(name)\n surname = escape(surname)\n message = escape(message)\n\n # Send email\n now = datetime.now()\n admins = get_user_model().objects.filter(is_staff=1)\n subject = \"Formularz kontaktowy: nowa wiadomość\"\n content = f\"\"\"\n {now.strftime('%Y/%m/%d %H:%M:%s')}\n Nowa wiadomość od {name} {surname}:\n \n {message}\n \"\"\"\n\n to_emails = (admin.email for admin in admins)\n\n for to_email in to_emails:\n # Sendgrid version\n # sendgrid.send_mail(to_email, subject, content)\n\n # Old, console version\n message = EmailMessage(subject, content, to=[to_email])\n message.send()\n\n messages.success(request, _(\"Wiadomość wysłano pomyślnie\"))\n return redirect(origin_site)\n\n messages.error(request, _(\"Wiadomość nie została wysłana. Niepoprawnie wypełniony formularz\"))\n return redirect(origin_site)\n\n\nclass PasswordResetView(View):\n def get(self, request):\n form = forms.PasswordResetForm\n return render(request, \"registration/password_reset_form.html\", context={\"form\": form})\n\n def post(self, request):\n form = forms.PasswordResetForm(request.POST)\n if form.is_valid():\n email = form.cleaned_data.get(\"email\")\n exists = get_user_model().objects.filter(email=email)\n if exists:\n\n # Send email\n user = exists[0]\n subject = \"Przypomnienie hasła\"\n current_site = get_current_site(request)\n uid = urlsafe_base64_encode(force_bytes(user.pk))\n token = default_token_generator.make_token(user)\n password_reset_link = f\"http://{current_site}/accounts/reset/{uid}/{token}/\"\n content = f\"Cześć {user.username}!\\n Kliknij w poniższy link, by odzyskać hasło:\\n{password_reset_link}\"\n to_email = email\n\n # Sendgrid version\n # sendgrid.send_mail(to_email, subject, content)\n\n # Old, console version\n message = EmailMessage(subject, content, to=[to_email])\n message.send()\n\n return redirect('password_reset_done')\n\n messages.error(request, _(\"Nie ma takiego użytkownika w bazie danych\"))\n return redirect('password_reset')\n\n\n# Uncomment only for Sendgrid functionality\n\n# class PasswordResetConfirmView(View):\n# def get(self, request, uid, token):\n# User = get_user_model()\n# try:\n# uid = urlsafe_base64_decode(uid).decode()\n# user = User.objects.get(pk=uid)\n# except(TypeError, ValueError, OverflowError, User.DoesNotExist):\n# user = None\n# if user is not None and default_token_generator.check_token(user, token):\n# form = forms.SetPasswordForm(user)\n# return render(request, 'registration/password_reset_confirm.html', context={\"form\": form})\n#\n# messages.error(request, _(\"Błędny link aktywacyjny\"))\n# return redirect(\"app:login\")\n#\n# def post(self, request, uid, token):\n# form = forms.SetPasswordForm(request.POST)\n# if form.is_valid():\n# User = get_user_model()\n# try:\n# uid = urlsafe_base64_decode(uid).decode()\n# user = User.objects.get(pk=uid)\n# except(TypeError, ValueError, OverflowError, User.DoesNotExist):\n# user = None\n# if user is not None:\n# form.save()\n# login(request, user)\n# messages.success(request, _(\"Pomyślnie zmieniono hasło\"))\n# return redirect('password_reset_complete')\n#\n# messages.error(request, _(\"Nieprawidłowe dane\"))\n# return redirect('app:login')\n#\n", "repo_name": "Marcin-Fraszczak/Charity", "sub_path": "app/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 19746, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "django.views.View", "line_number": 25, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 37, "usage_type": "call"}, {"api_name": "django.core.paginator.Paginator", "line_number": 44, "usage_type": "call"}, {"api_name": "django.core.paginator.Paginator", "line_number": 49, "usage_type": "call"}, {"api_name": "django.core.paginator.Paginator", "line_number": 51, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 61, "usage_type": "call"}, {"api_name": "django.contrib.auth.mixins.LoginRequiredMixin", "line_number": 64, "usage_type": "name"}, {"api_name": "django.views.View", "line_number": 64, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 70, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 71, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 72, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 74, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 82, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 97, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 128, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 128, "usage_type": "name"}, {"api_name": "django.core.mail.EmailMessage", "line_number": 151, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 154, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 156, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 156, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 156, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 157, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 159, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 159, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 160, "usage_type": "call"}, {"api_name": "django.contrib.auth.mixins.LoginRequiredMixin", "line_number": 163, "usage_type": "name"}, {"api_name": "django.views.View", "line_number": 163, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 165, "usage_type": "call"}, {"api_name": "django.views.View", "line_number": 168, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 170, "usage_type": "call"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 175, "usage_type": "call"}, {"api_name": "django.contrib.auth.login", "line_number": 177, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 178, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 180, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 180, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 180, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 181, "usage_type": "call"}, {"api_name": "django.views.View", "line_number": 184, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 187, "usage_type": "call"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 199, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 201, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 201, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 201, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 202, "usage_type": "call"}, {"api_name": "django.contrib.sites.shortcuts.get_current_site", "line_number": 218, "usage_type": "call"}, {"api_name": "django.utils.http.urlsafe_base64_encode", "line_number": 219, "usage_type": "call"}, {"api_name": "django.utils.encoding.force_bytes", "line_number": 219, "usage_type": "call"}, {"api_name": "django.contrib.auth.tokens.default_token_generator.make_token", "line_number": 220, "usage_type": "call"}, {"api_name": "django.contrib.auth.tokens.default_token_generator", "line_number": 220, "usage_type": "name"}, {"api_name": "django.contrib.messages.success", "line_number": 230, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 230, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 230, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 231, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 233, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 233, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 233, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 234, "usage_type": "call"}, {"api_name": "django.views.View", "line_number": 237, "usage_type": "name"}, {"api_name": "django.utils.http.urlsafe_base64_decode", "line_number": 240, "usage_type": "call"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 241, "usage_type": "call"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 242, "usage_type": "call"}, {"api_name": "django.contrib.auth.tokens.default_token_generator.check_token", "line_number": 244, "usage_type": "call"}, {"api_name": "django.contrib.auth.tokens.default_token_generator", "line_number": 244, "usage_type": "name"}, {"api_name": "django.contrib.auth.login", "line_number": 248, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 249, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 249, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 249, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 250, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 251, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 251, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 251, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 252, "usage_type": "call"}, {"api_name": "django.views.View", "line_number": 255, "usage_type": "name"}, {"api_name": "django.contrib.auth.logout", "line_number": 257, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 258, "usage_type": "call"}, {"api_name": "django.views.View", "line_number": 279, "usage_type": "name"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 281, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 284, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 287, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 288, "usage_type": "call"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 289, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 299, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 301, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 301, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 301, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 302, "usage_type": "call"}, {"api_name": "django.contrib.auth.mixins.LoginRequiredMixin", "line_number": 305, "usage_type": "name"}, {"api_name": "django.views.View", "line_number": 305, "usage_type": "name"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 307, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 308, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 314, "usage_type": "call"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 328, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 331, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 331, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 331, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 332, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 334, "usage_type": "call"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 334, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 341, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 341, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 341, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 342, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 344, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 344, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 344, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 345, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 347, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 347, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 347, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 348, "usage_type": "call"}, {"api_name": "django.contrib.auth.mixins.LoginRequiredMixin", "line_number": 351, "usage_type": "name"}, {"api_name": "django.views.View", "line_number": 351, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 357, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 367, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 367, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 367, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 368, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 369, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 369, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 369, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 370, "usage_type": "call"}, {"api_name": "django.views.View", "line_number": 373, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 375, "usage_type": "call"}, {"api_name": "django.core.validators.validate_email", "line_number": 378, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 380, "usage_type": "name"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 384, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 388, "usage_type": "call"}, {"api_name": "django.views.View", "line_number": 391, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 396, "usage_type": "call"}, {"api_name": "django.utils.html.escape", "line_number": 399, "usage_type": "call"}, {"api_name": "django.utils.html.escape", "line_number": 400, "usage_type": "call"}, {"api_name": "django.utils.html.escape", "line_number": 401, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 404, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 404, "usage_type": "name"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 405, "usage_type": "call"}, {"api_name": "django.core.mail.EmailMessage", "line_number": 421, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 424, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 424, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 424, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 425, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 427, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 427, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 427, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 428, "usage_type": "call"}, {"api_name": "django.views.View", "line_number": 431, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 434, "usage_type": "call"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 440, "usage_type": "call"}, {"api_name": "django.contrib.sites.shortcuts.get_current_site", "line_number": 446, "usage_type": "call"}, {"api_name": "django.utils.http.urlsafe_base64_encode", "line_number": 447, "usage_type": "call"}, {"api_name": "django.utils.encoding.force_bytes", "line_number": 447, "usage_type": "call"}, {"api_name": "django.contrib.auth.tokens.default_token_generator.make_token", "line_number": 448, "usage_type": "call"}, {"api_name": "django.contrib.auth.tokens.default_token_generator", "line_number": 448, "usage_type": "name"}, {"api_name": "django.core.mail.EmailMessage", "line_number": 457, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 460, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 462, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 462, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 462, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 463, "usage_type": "call"}]} +{"seq_id": "74479069490", "text": "import logging\nimport os\nimport json\nimport datetime\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom auth_API.helpers import get_or_create_user_information, get_user_information\n\n# Get an instance of a logger\nfrom experiment.models import ExperimentContext\n\nlogger = logging.getLogger('experiment')\n\n\ndef stage_type(id, stage_num):\n stage_config = id % 2 \n if stage_config == 0:\n if stage_num == 0:\n return 'daphne_baseline'\n else:\n return 'daphne_group'\n elif stage_config == 1:\n if stage_num == 0:\n return 'daphne_group'\n else:\n return 'daphne_baseline'\n\n\n# Create your views here.\nclass StartExperiment(APIView):\n\n def get(self, request, format=None):\n\n # Check for experiments folder\n results_dir = './experiment/results'\n if not os.path.exists(results_dir):\n os.makedirs(results_dir)\n\n # Obtain ID number\n new_id = len(os.listdir(results_dir))\n\n # Create File so ID does not get repeated\n file_path = os.path.join(results_dir, str(new_id) + '.json')\n if os.path.exists(file_path):\n file_path = os.path.join(results_dir, str(new_id) + '_1.json')\n open(file_path, 'w')\n\n # Save experiment start info\n \n # User info needs to already exist and have user marked as experiment user\n user_info = get_user_information(request.session, request.user)\n\n if not user_info.is_experiment_user:\n return Response({\n \"error\": \"User is not set up as experiment user\"\n })\n\n # Ensure experiment is started again\n if hasattr(user_info, 'experimentcontext'):\n user_info.experimentcontext.delete()\n experiment_context = ExperimentContext(user_information=user_info, is_running=False, experiment_id=-1,\n current_state=\"\")\n experiment_context.save()\n\n experiment_context.experiment_id = new_id\n\n # Specific to current experiment\n experiment_context.experimentstage_set.all().delete()\n\n experiment_context.experimentstage_set.create(type=stage_type(new_id, 0),\n start_date=datetime.datetime.now(),\n end_date=datetime.datetime.now(),\n end_state=\"\")\n experiment_context.experimentstage_set.create(type=stage_type(new_id, 1),\n start_date=datetime.datetime.now(),\n end_date=datetime.datetime.now(),\n end_state=\"\")\n\n # Save experiment started on database\n experiment_context.is_running = True\n\n experiment_context.save()\n\n # Prepare return for client\n experiment_stages = []\n for stage in experiment_context.experimentstage_set.all():\n experiment_stages.append(stage.type)\n\n return Response(experiment_stages)\n\n\nclass StartStage(APIView):\n\n def get(self, request, stage, format=None):\n user_info = get_or_create_user_information(request.session, request.user, 'EOSS')\n experiment_context = user_info.experimentcontext\n experiment_stage = experiment_context.experimentstage_set.all().order_by(\"id\")[stage]\n experiment_stage.start_date = datetime.datetime.utcnow()\n experiment_stage.save()\n\n return Response({\n 'start_date': experiment_stage.start_date.isoformat()\n })\n\n\nclass FinishStage(APIView):\n\n def get(self, request, stage, format=None):\n user_info = get_or_create_user_information(request.session, request.user, 'EOSS')\n experiment_context = user_info.experimentcontext\n experiment_stage = experiment_context.experimentstage_set.all().order_by(\"id\")[stage]\n experiment_stage.end_date = datetime.datetime.utcnow()\n experiment_stage.end_state = experiment_context.current_state\n experiment_stage.save()\n\n return Response({\n 'end_date': experiment_stage.end_date.isoformat()\n })\n\n\nclass ReloadExperiment(APIView):\n\n def get(self, request, format=None):\n user_info = get_or_create_user_information(request.session, request.user, 'EOSS')\n if hasattr(user_info, 'experimentcontext'):\n experiment_context = user_info.experimentcontext\n if experiment_context.is_running:\n return Response({'is_running': True, 'experiment_data': json.loads(experiment_context.current_state)})\n return Response({ 'is_running': False })\n \n \nclass FinishExperiment(APIView):\n\n def get(self, request, format=None):\n user_info = get_or_create_user_information(request.session, request.user, 'EOSS')\n experiment_context = user_info.experimentcontext\n\n # Save experiment results to file\n save_experiment_to_file(experiment_context)\n\n experiment_context.delete()\n\n return Response('Experiment finished correctly!')\n\n\ndef save_experiment_to_file(experiment_context: ExperimentContext):\n # Save experiment results to file\n with open('./experiment/results/' + str(experiment_context.experiment_id) + '.json', 'w') as f:\n json_experiment = {\n \"experiment_id\": experiment_context.experiment_id,\n \"current_state\": json.loads(experiment_context.current_state) if experiment_context.current_state != \"\" else \"\",\n \"stages\": []\n }\n for stage in experiment_context.experimentstage_set.all():\n json_stage = {\n \"type\": stage.type,\n \"start_date\": stage.start_date.isoformat(),\n \"end_date\": stage.end_date.isoformat(),\n \"end_state\": json.loads(stage.end_state) if stage.end_state != \"\" else \"\",\n \"actions\": []\n }\n for action in stage.experimentaction_set.all():\n json_action = {\n \"action\": json.loads(action.action) if action.action != \"\" else \"\",\n \"date\": action.date.isoformat()\n }\n json_stage[\"actions\"].append(json_action)\n json_experiment[\"stages\"].append(json_stage)\n json.dump(json_experiment, f)\n", "repo_name": "seakers/daphne_brain", "sub_path": "experiment/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 6439, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "logging.getLogger", "line_number": 12, "usage_type": "call"}, {"api_name": "rest_framework.views.APIView", "line_number": 30, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path", "line_number": 36, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 37, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path", "line_number": 43, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "auth_API.helpers.get_user_information", "line_number": 51, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 54, "usage_type": "call"}, {"api_name": "experiment.models.ExperimentContext", "line_number": 61, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 71, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 71, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 72, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 72, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 75, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 75, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 76, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 76, "usage_type": "attribute"}, {"api_name": "rest_framework.response.Response", "line_number": 89, "usage_type": "call"}, {"api_name": "rest_framework.views.APIView", "line_number": 92, "usage_type": "name"}, {"api_name": "auth_API.helpers.get_or_create_user_information", "line_number": 95, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 98, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 98, "usage_type": "attribute"}, {"api_name": "rest_framework.response.Response", "line_number": 101, "usage_type": "call"}, {"api_name": "rest_framework.views.APIView", "line_number": 106, "usage_type": "name"}, {"api_name": "auth_API.helpers.get_or_create_user_information", "line_number": 109, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 112, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 112, "usage_type": "attribute"}, {"api_name": "rest_framework.response.Response", "line_number": 116, "usage_type": "call"}, {"api_name": "rest_framework.views.APIView", "line_number": 121, "usage_type": "name"}, {"api_name": "auth_API.helpers.get_or_create_user_information", "line_number": 124, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 128, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 128, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 129, "usage_type": "call"}, {"api_name": "rest_framework.views.APIView", "line_number": 132, "usage_type": "name"}, {"api_name": "auth_API.helpers.get_or_create_user_information", "line_number": 135, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 143, "usage_type": "call"}, {"api_name": "experiment.models.ExperimentContext", "line_number": 146, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 151, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 159, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 164, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 169, "usage_type": "call"}]} +{"seq_id": "41132276599", "text": "import logging\nimport queue\n\nimport bpy\n\nfrom urmoco.scheduler import Scheduler\nfrom urmoco.config import Config\nfrom urmoco.blender.sync import get_urmoco_sync\nfrom urmoco.blender.operators.base_modal_operator import \\\n get_synced_modal_operator_class\nfrom urmoco.blender.rig import set_ghost_hidden\nfrom urmoco.blender.state import get_mode, set_mode, set_status_text\nfrom urmoco.mode import Mode\n\nlogger = logging.getLogger(__name__)\n\ndef get_operators(config: Config, scheduler: Scheduler):\n base_operator = get_synced_modal_operator_class(\n config, scheduler\n )\n\n class PreferencesConfirmationOperator(base_operator):\n bl_idname = \"urmoco.startup\"\n bl_label = \"Startup\"\n\n @classmethod\n def poll(cls, context):\n return get_mode() is Mode.UNINITIALIZED\n\n def on_execute(self, context):\n self.report({\"INFO\"}, \"Starting urmoco\")\n\n config.config[\"robot\"][\n \"host\"\n ] = context.window_manager.urmoco_preferences.host\n config.config[\"robot\"][\n \"payload\"\n ] = context.window_manager.urmoco_preferences.payload\n\n sync = get_urmoco_sync(config, scheduler)\n bpy.app.timers.register(sync)\n\n scheduler.start_dfmoco_server(config)\n scheduler.start_backend(config)\n\n scheduler.ur_in_q.put({\"type\": \"hi\"})\n\n set_mode(Mode.AWAIT_RESPONSE)\n\n def on_request(self, context, request):\n if request[\"type\"] == \"startup\":\n set_mode(Mode.ON)\n set_status_text(\"Started urmoco\")\n set_ghost_hidden(False)\n\n def unexpected_load_handler(_a, _b):\n if get_mode() not in {Mode.OFF, Mode.UNINITIALIZED}:\n scheduler.ur_in_q.put({\"type\": \"power_off\"})\n logger.warning(\"urmoco shutdown: new blender file loaded without being powered off\")\n bpy.app.handlers.load_pre.append(unexpected_load_handler)\n\n return {\"FINISHED\"}\n\n def invoke(self, context, event):\n return context.window_manager.invoke_props_dialog(self, width=300)\n\n def draw(self, context):\n self.layout.prop(context.window_manager.urmoco_preferences, \"host\")\n self.layout.prop(context.window_manager.urmoco_preferences, \"payload\")\n\n return [PreferencesConfirmationOperator]\n", "repo_name": "emanuelbuholzer/blender-urmoco", "sub_path": "urmoco/blender/operators/startup.py", "file_name": "startup.py", "file_ext": "py", "file_size_in_byte": 2443, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "20", "api": [{"api_name": "logging.getLogger", "line_number": 15, "usage_type": "call"}, {"api_name": "urmoco.config.Config", "line_number": 17, "usage_type": "name"}, {"api_name": "urmoco.scheduler.Scheduler", "line_number": 17, "usage_type": "name"}, {"api_name": "urmoco.blender.operators.base_modal_operator.get_synced_modal_operator_class", "line_number": 18, "usage_type": "call"}, {"api_name": "urmoco.blender.state.get_mode", "line_number": 28, "usage_type": "call"}, {"api_name": "urmoco.mode.Mode.UNINITIALIZED", "line_number": 28, "usage_type": "attribute"}, {"api_name": "urmoco.mode.Mode", "line_number": 28, "usage_type": "name"}, {"api_name": "urmoco.blender.sync.get_urmoco_sync", "line_number": 40, "usage_type": "call"}, {"api_name": "bpy.app.timers.register", "line_number": 41, "usage_type": "call"}, {"api_name": "bpy.app", "line_number": 41, "usage_type": "attribute"}, {"api_name": "urmoco.blender.state.set_mode", "line_number": 48, "usage_type": "call"}, {"api_name": "urmoco.mode.Mode.AWAIT_RESPONSE", "line_number": 48, "usage_type": "attribute"}, {"api_name": "urmoco.mode.Mode", "line_number": 48, "usage_type": "name"}, {"api_name": "urmoco.blender.state.set_mode", "line_number": 52, "usage_type": "call"}, {"api_name": "urmoco.mode.Mode.ON", "line_number": 52, "usage_type": "attribute"}, {"api_name": "urmoco.mode.Mode", "line_number": 52, "usage_type": "name"}, {"api_name": "urmoco.blender.state.set_status_text", "line_number": 53, "usage_type": "call"}, {"api_name": "urmoco.blender.rig.set_ghost_hidden", "line_number": 54, "usage_type": "call"}, {"api_name": "urmoco.blender.state.get_mode", "line_number": 57, "usage_type": "call"}, {"api_name": "urmoco.mode.Mode.OFF", "line_number": 57, "usage_type": "attribute"}, {"api_name": "urmoco.mode.Mode", "line_number": 57, "usage_type": "name"}, {"api_name": "urmoco.mode.Mode.UNINITIALIZED", "line_number": 57, "usage_type": "attribute"}, {"api_name": "bpy.app.handlers.load_pre.append", "line_number": 60, "usage_type": "call"}, {"api_name": "bpy.app", "line_number": 60, "usage_type": "attribute"}]} +{"seq_id": "22354917204", "text": "from django.urls import reverse\n\nfrom faker import Faker\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom tests.factories import (\n CompanyFactory,\n IndustryFactory,\n SubscriptionFactory,\n UserFactory,\n)\n\n\nclass CompanyListTestCase(APITestCase):\n\n @classmethod\n def setUpTestData(cls) -> None:\n \"\"\"\n Setup tests data.\n\n :return:\n \"\"\"\n cls.user = UserFactory(level=2)\n cls.industry = IndustryFactory()\n\n def setUp(self) -> None:\n \"\"\"\n Setup tests.\n\n :return:\n \"\"\"\n self.fake = Faker()\n self.company_stub = CompanyFactory.stub(owner=self.user,\n industry=self.industry,\n logo=None)\n self.client.force_authenticate(user=self.user)\n self.url = reverse(\"companies:company_list\")\n\n def test_company_list_success(self):\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n def test_company_create_success(self):\n data = {\n \"owner\": self.company_stub.owner.pk,\n \"name\": self.company_stub.name,\n \"industry\": self.company_stub.industry.pk,\n \"website\": self.company_stub.website,\n \"size\": self.company_stub.size,\n \"founded\": self.company_stub.founded,\n \"description\": self.company_stub.description,\n }\n response = self.client.post(self.url, data=data)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n def test_company_create_bad_request(self):\n response = self.client.post(self.url, data={})\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n\nclass CompanyDetailsTestCase(APITestCase):\n\n @classmethod\n def setUpTestData(cls) -> None:\n \"\"\"\n Setup tests data.\n\n :return:\n \"\"\"\n cls.user = UserFactory(level=2)\n cls.company = CompanyFactory(owner=cls.user)\n\n def setUp(self) -> None:\n \"\"\"\n Setup tests.\n\n :return:\n \"\"\"\n self.fake = Faker()\n self.client.force_authenticate(user=self.user)\n self.company_stub = CompanyFactory.stub(owner=self.company.owner,\n industry=self.company.industry,\n logo=None)\n self.subscription = SubscriptionFactory(company=self.company)\n self.url = reverse(\"companies:company_detail\",\n kwargs={\"pk\": self.company.pk})\n\n def test_company_detail_success(self):\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n def test_company_update_success(self):\n data = {\n \"owner\": self.company_stub.owner.pk,\n \"name\": self.company_stub.name,\n \"industry\": self.company_stub.industry.pk,\n \"website\": self.company_stub.website,\n \"size\": self.company_stub.size,\n \"founded\": self.company_stub.founded,\n \"description\": self.company_stub.description,\n }\n response = self.client.patch(self.url, data=data)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n def test_company_update_bad_request(self):\n data = {\n \"company\": None,\n \"speciality\": self.fake.pyfloat(positive=True),\n \"experience\": self.fake.sentence(nb_words=8),\n \"owner\": self.user.pk,\n \"name\": self.fake.text(max_nb_chars=80),\n \"industry\": None,\n \"website\": self.fake.url(),\n \"size\": self.fake.sentence(nb_words=8),\n \"founded\": self.fake.date(),\n \"description\": self.fake.paragraph(),\n }\n response = self.client.patch(self.url, data=data)\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_company_delete_success(self):\n response = self.client.delete(self.url)\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n", "repo_name": "ewgen19892/jobadvisor", "sub_path": "tests/views/test_company_view.py", "file_name": "test_company_view.py", "file_ext": "py", "file_size_in_byte": 4162, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "rest_framework.test.APITestCase", "line_number": 14, "usage_type": "name"}, {"api_name": "tests.factories.UserFactory", "line_number": 23, "usage_type": "call"}, {"api_name": "tests.factories.IndustryFactory", "line_number": 24, "usage_type": "call"}, {"api_name": "faker.Faker", "line_number": 32, "usage_type": "call"}, {"api_name": "tests.factories.CompanyFactory.stub", "line_number": 33, "usage_type": "call"}, {"api_name": "tests.factories.CompanyFactory", "line_number": 33, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 37, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 41, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 41, "usage_type": "name"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 54, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 54, "usage_type": "name"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 58, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 58, "usage_type": "name"}, {"api_name": "rest_framework.test.APITestCase", "line_number": 61, "usage_type": "name"}, {"api_name": "tests.factories.UserFactory", "line_number": 70, "usage_type": "call"}, {"api_name": "tests.factories.CompanyFactory", "line_number": 71, "usage_type": "call"}, {"api_name": "faker.Faker", "line_number": 79, "usage_type": "call"}, {"api_name": "tests.factories.CompanyFactory.stub", "line_number": 81, "usage_type": "call"}, {"api_name": "tests.factories.CompanyFactory", "line_number": 81, "usage_type": "name"}, {"api_name": "tests.factories.SubscriptionFactory", "line_number": 84, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 85, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 90, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 90, "usage_type": "name"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 103, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 103, "usage_type": "name"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 119, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 119, "usage_type": "name"}, {"api_name": "rest_framework.status.HTTP_204_NO_CONTENT", "line_number": 123, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 123, "usage_type": "name"}]} +{"seq_id": "19341113927", "text": "# This code saves the data and lists the graphed data.\n\nimport tkinter as Tk\nfrom tkinter import *\nimport os\nimport gpiozero\n\nimport shutil\n\nwindowMaster = False\n\npin0 = gpiozero.LED(13)\n\ndef scrolldata(*args):\n listbox_time.yview(*args)\n listbox_distance.yview(*args)\n\ndef save():\n global windowMaster\n fileMade = False\n def close_window():\n global windowMaster\n windowMaster = False\n save_window.destroy()\n def submit():\n runName = folder_name.get()\n try:\n os.mkdir(path = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Saved_Runs/Manual_Save/' + runName)\n fileMade = True\n except:\n message = Label(save_window, text = \"Invalid File Name. Please enter another.\", font = (\"Times New Roman\", 12))\n message.place(x =50, y=200)\n fileMade = False\n if fileMade:\n src_time = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/Temp_Data/temp_time.txt'\n src_distance = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/Temp_Data/temp_distance.txt'\n dst_time = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Saved_Runs/Manual_Save/' + runName +'/' + runName + '_time.txt'\n dst_distance = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Saved_Runs/Manual_Save/' + runName +'/' + runName + '_distance.txt'\n shutil.copyfile(src_time, dst_time)\n shutil.copyfile(src_distance, dst_distance)\n message = Label(save_window, text = \"Save Successful. \", font = (\"Times New Roman\", 12))\n message.place(x =50, y=200)\n close = Button(save_window, text = 'Close', height = 2, width =20, command=close_window).place(x =400, y =200)\n btn_save = Button(root, text = 'Save Data', height = 2, width =34, command=save, state = 'disabled').place(x =75, y =900)\n\n # save the data (manual save)\n if not windowMaster:\n windowMaster = True\n save_window = Toplevel(root)\n save_window.geometry('700x300')\n save_window.title(\"Save Data\")\n instr= Label(save_window, text = \"Name of Folder for the Run:\", font = (\"Times New Roman\", 14))\n instr.place(x =50, y=20)\n folder_name= Entry(save_window, width =40)\n folder_name.focus_set()\n folder_name.pack(pady =50)\n submit = Button(save_window, text = 'Submit', height = 2, width =20, command=submit).place(x =400, y =200)\n save_window.protocol(\"WM_DELETE_WINDOW\", close_window)\n\n\n# Prevent the user from opening multiple instances\nwith open('/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/System_Communication/status_main2.txt', 'r') as file_object:\n status_main2 = file_object.read().rstrip()\n file_object.close()\nif status_main2 == '1':\n sys.exit(0)\nelse:\n pin0.on()\n with open('/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/System_Communication/status_main2.txt', 'w') as file_object:\n file_object.write('1')\n file_object.close()\n while True:\n #Check system_state\n with open('/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/System_Communication/system_state.txt', 'r') as file_object:\n system_state = file_object.read().rstrip()\n file_object.close()\n\n if(system_state == '0011') or (system_state == '0110'): # state where a graph is plotted\n\n # File Setup\n # Assume loading from temporary data\n file_path_distance = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/Temp_Data/temp_distance.txt'\n file_path_time = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/Temp_Data/temp_time.txt'\n\n #If the user is loading a graph\n if(system_state == '0110'):\n autosave_dir =os.listdir(path = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Saved_Runs/Autosaved')\n manualsave_dir =os.listdir(path = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Saved_Runs/Manual_Save')\n with open('/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/System_Communication/file_to_open.txt', 'r') as file_object:\n fileChoice = file_object.read().rstrip()\n file_object.close()\n\n directoryChoice = 0\n if fileChoice in manualsave_dir:\n directoryChoice = 1\n\n if directoryChoice == 1:\n file_path_distance = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Saved_Runs/Manual_Save/' + fileChoice + '/' + fileChoice + '_distance.txt'\n file_path_time = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Saved_Runs/Manual_Save/' + fileChoice + '/' + fileChoice + '_time.txt'\n else:\n file_path_distance = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Saved_Runs/Autosaved/' + fileChoice + '/' + fileChoice + '_distance.txt'\n file_path_time = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Saved_Runs/Autosaved/' + fileChoice + '/' + fileChoice + '_time.txt'\n\n\n # The Save Mode\n with open('/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/System_Communication/save_mode.txt', 'r') as file_object:\n save_mode = file_object.read().rstrip()\n file_object.close()\n # The Window\n root = Tk()\n root.geometry('500x1000')\n root.title(\"Listed Data\")\n\n # Labels\n label_time = Label(root, text = \"Time [s]\", font = (\"Times New Roman\", 14))\n label_time.place(x =100, y=20)\n label_distance = Label(root, text = \"Distance [mm]\", font = (\"Times New Roman\", 14))\n label_distance.place(x =325, y=20)\n\n # Save Button if Manual Save\n if (save_mode == '1'):\n btn_save = Button(root, text = 'Save Data', height = 2, width =34, command=save).place(x =75, y =900)\n\n # The Scrollbar\n scrollbar = Scrollbar(root)\n scrollbar.pack(side = RIGHT, fill =BOTH)\n\n # For time\n listbox_time = Listbox(root, height = 45, width =25)\n listbox_time.pack(side = LEFT, padx = 20, pady=60, anchor = 'n')\n listbox_time.config(yscrollcommand = scrollbar.set)\n with open(file_path_time, 'r') as file_object:\n time_data=file_object.readlines()\n file_object.close()\n for line in time_data:\n listbox_time.insert(END,line.rstrip() + ' [s] ')\n\n #For distance\n listbox_distance = Listbox(root, height = 45, width=25)\n listbox_distance.pack(side = RIGHT, padx =20,pady=60, anchor = 'n')\n listbox_distance.config(yscrollcommand= scrollbar.set)\n with open(file_path_distance, 'r') as file_object:\n distance_data=file_object.readlines()\n file_object.close()\n for line in distance_data:\n listbox_distance.insert(END,line.rstrip() + ' [mm] ')\n\n #Configure the scrollbar\n scrollbar.config (command = scrolldata)\n root.mainloop()\n\n # save the data (autosave)\n if (save_mode == '0'):\n with open('/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/System_Communication/run_number.txt', 'r') as file_object:\n run_number = file_object.read().rstrip()\n file_object.close()\n os.mkdir(path = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Saved_Runs/Autosaved/Auto_' + run_number)\n\n # Copy the temporary files\n src_time = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/Temp_Data/temp_time.txt'\n src_distance = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/Temp_Data/temp_distance.txt'\n dst_time = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Saved_Runs/Autosaved/Auto_' + run_number +'/Auto_' + run_number + '_time.txt'\n dst_distance = '/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Saved_Runs/Autosaved/Auto_' + run_number +'/Auto_' + run_number + '_distance.txt'\n shutil.copyfile(src_time, dst_time)\n shutil.copyfile(src_distance, dst_distance)\n\n # increment the run number\n with open('/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/System_Communication/run_number.txt', 'w') as file_object:\n file_object.write(str(int(run_number)+1))\n file_object.close()\n\n #Check system_state again\n with open('/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/System_Communication/system_state.txt', 'r') as file_object:\n system_state = file_object.read().rstrip()\n file_object.close()\n\n if(system_state == '0101'): # move to waiting state\n with open('/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/System_Communication/system_state.txt', 'w') as file_object: #move to append state\n file_object.write('0000')\n file_object.close()\n\n else: # change system_state to '0101'\n with open('/home/pi/Desktop/Educational_Duffing_Oscillator_for_Displaying_Chaotic_Motion/Program_Files/System_Communication/system_state.txt', 'w') as file_object: #move to append state\n file_object.write('0101')\n file_object.close()\n\n elif(system_state == '1111'):\n pin0.off()\n sys.exit(0)", "repo_name": "koy2/Senior-Design---Group-1--Educational-Duffing-Oscillator---2021-2022", "sub_path": "Program_Files/Codes/main_pt2.py", "file_name": "main_pt2.py", "file_ext": "py", "file_size_in_byte": 10609, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "gpiozero.LED", "line_number": 12, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 28, "usage_type": "call"}, {"api_name": "shutil.copyfile", "line_number": 39, "usage_type": "call"}, {"api_name": "shutil.copyfile", "line_number": 40, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 87, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 88, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 157, "usage_type": "call"}, {"api_name": "shutil.copyfile", "line_number": 164, "usage_type": "call"}, {"api_name": "shutil.copyfile", "line_number": 165, "usage_type": "call"}]} +{"seq_id": "36298806496", "text": "from django.shortcuts import render, redirect\n\nfrom django.contrib.auth.decorators import login_required\n\nfrom .models import Movies\nfrom .forms import MovieForm\nfrom .filters import MovieFilter, MovieToWatchFilter\nfrom django.contrib.auth.models import User\n\n\n# redirect to recommendations page if not logged in\n@login_required(login_url='movietowatch')\ndef home(request):\n movies = request.user.movies_set.all()\n\n# djnago filter\n filter = MovieFilter(request.GET, queryset=movies)\n movies = filter.qs\n\n context = {\n 'movies': movies.order_by('-id'),\n 'total_movies': movies.count(),\n 'unwatched': movies.filter(status=False).count(),\n 'filter': filter\n }\n return render(request, 'movies/index.html', context)\n\n\n@login_required(login_url='login')\ndef create(request):\n if request.POST:\n form = MovieForm(request.POST)\n# assign user to form\n form.instance.user = request.user\n if form.is_valid():\n form.save()\n return redirect('home')\n else: \n form = MovieForm()\n\n context = {'form': form}\n return render(request, 'movies/create.html', context)\n\n\n@login_required(login_url='login')\ndef update(request, pk):\n movie = Movies.objects.get(id=pk)\n\n if request.method == 'POST':\n form = MovieForm(request.POST, instance=movie)\n form.save()\n return redirect('home')\n else:\n form = MovieForm(instance=movie)\n\n context = {'form': form}\n return render(request, 'movies/create.html', context)\n\n\n@login_required(login_url='login')\ndef changeStatus(request, pk):\n movie = Movies.objects.get(id=pk)\n movie.status = not movie.status\n movie.save()\n return redirect('home')\n\n\n@login_required(login_url='login')\ndef delete(request, pk):\n movie = Movies.objects.get(id=pk)\n movie.delete()\n return redirect('home')\n\n\ndef movie_to_watch(request):\n if request.user.is_authenticated:\n# show all movies as recommendations except movies watchlisted by user\n# the titles of movies watchlisted by user is stored in a list\n# that list is excluded while showing movies for recommendations\n watchlisted_movies = [movie.title for movie in request.user.movies_set.all()]\n movies = Movies.objects.exclude(title__in=watchlisted_movies)\n else:\n movies = Movies.objects.all()\n\n# if two users have same movie then it is repeated in recommendations \n# so id of repeated movies are stored in exclude_id and excluded from query set\n seen_title = []\n exclude_id = []\n for obj in movies:\n if obj.title in seen_title:\n exclude_id += [obj.id]\n else:\n seen_title += [obj.title]\n movies = movies.exclude(id__in=exclude_id).order_by('-year')\n\n# djnago filter\n filter = MovieToWatchFilter(request.GET, queryset=movies)\n movies = filter.qs\n\n context = {\n 'movies': movies,\n 'filter': filter\n }\n return render(request, 'movies/movie_to_watch.html', context)\n\n\n@login_required(login_url='login')\ndef add_movietowatch(request, pk):\n# add movies from recommendations to watchlist\n movie = Movies.objects.get(id=pk)\n Movies.objects.create(\n user=request.user,\n title=movie.title,\n year=movie.year,\n genre=movie.genre\n )\n return redirect('movietowatch')\n\n\n\n# admin_home = user status page\ndef admin_home(request):\n# Check if admin or not\n if not request.user.is_staff:\n return redirect('home')\n\n users = User.objects.all()\n movies = Movies.objects.all()\n context = {\n 'users': users,\n 'total_movies': movies.count(),\n 'total_users': users.count()\n }\n return render(request, 'movies/admin_home.html', context)", "repo_name": "The-SP/Watchlist", "sub_path": "watchlist/movies/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 3715, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "filters.MovieFilter", "line_number": 17, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 26, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 12, "usage_type": "call"}, {"api_name": "forms.MovieForm", "line_number": 32, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 37, "usage_type": "call"}, {"api_name": "forms.MovieForm", "line_number": 39, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 42, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 29, "usage_type": "call"}, {"api_name": "models.Movies.objects.get", "line_number": 47, "usage_type": "call"}, {"api_name": "models.Movies.objects", "line_number": 47, "usage_type": "attribute"}, {"api_name": "models.Movies", "line_number": 47, "usage_type": "name"}, {"api_name": "forms.MovieForm", "line_number": 50, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 52, "usage_type": "call"}, {"api_name": "forms.MovieForm", "line_number": 54, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 57, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 45, "usage_type": "call"}, {"api_name": "models.Movies.objects.get", "line_number": 62, "usage_type": "call"}, {"api_name": "models.Movies.objects", "line_number": 62, "usage_type": "attribute"}, {"api_name": "models.Movies", "line_number": 62, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 65, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 60, "usage_type": "call"}, {"api_name": "models.Movies.objects.get", "line_number": 70, "usage_type": "call"}, {"api_name": "models.Movies.objects", "line_number": 70, "usage_type": "attribute"}, {"api_name": "models.Movies", "line_number": 70, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 72, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 68, "usage_type": "call"}, {"api_name": "models.Movies.objects.exclude", "line_number": 81, "usage_type": "call"}, {"api_name": "models.Movies.objects", "line_number": 81, "usage_type": "attribute"}, {"api_name": "models.Movies", "line_number": 81, "usage_type": "name"}, {"api_name": "models.Movies.objects.all", "line_number": 83, "usage_type": "call"}, {"api_name": "models.Movies.objects", "line_number": 83, "usage_type": "attribute"}, {"api_name": "models.Movies", "line_number": 83, "usage_type": "name"}, {"api_name": "filters.MovieToWatchFilter", "line_number": 97, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 104, "usage_type": "call"}, {"api_name": "models.Movies.objects.get", "line_number": 110, "usage_type": "call"}, {"api_name": "models.Movies.objects", "line_number": 110, "usage_type": "attribute"}, {"api_name": "models.Movies", "line_number": 110, "usage_type": "name"}, {"api_name": "models.Movies.objects.create", "line_number": 111, "usage_type": "call"}, {"api_name": "models.Movies.objects", "line_number": 111, "usage_type": "attribute"}, {"api_name": "models.Movies", "line_number": 111, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 117, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 107, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 125, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.all", "line_number": 127, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 127, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 127, "usage_type": "name"}, {"api_name": "models.Movies.objects.all", "line_number": 128, "usage_type": "call"}, {"api_name": "models.Movies.objects", "line_number": 128, "usage_type": "attribute"}, {"api_name": "models.Movies", "line_number": 128, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 134, "usage_type": "call"}]} +{"seq_id": "14149217461", "text": "#!/usr/bin/env python3\n\nimport rospy\nimport math\nfrom raiv_libraries.cnn import Cnn\nfrom raiv_libraries.rgb_cnn import RgbCnn\nfrom raiv_research.srv import GetBestPrediction, GetBestPredictionResponse\nfrom raiv_research.msg import Prediction, ListOfPredictions\nfrom raiv_research.msg import RgbAndDepthImages\nfrom raiv_libraries.srv import get_coordservice\nfrom raiv_libraries.srv import PickingBoxIsEmpty\nfrom raiv_libraries.srv import ClearPrediction, ClearPredictionResponse\nfrom raiv_research.srv import ProcessNewImage, ProcessNewImageResponse\nfrom raiv_libraries.get_coord_node import InBoxCoord\nfrom raiv_libraries.image_tools import ImageTools\nfrom sensor_msgs.msg import Image\nimport PIL\n\n\nRGB_IMAGE_TOPIC = \"/camera/color/image_raw\"\nDEPTH_IMAGE_TOPIC = \"/camera/aligned_depth_to_color/image_raw\"\nDEBUG = False\n\nclass NodeBestPrediction:\n \"\"\"\n This node is both a service and a publisher.\n * Service best_prediction_service : use a GetBestPrediction message (no input message and a ListOfPredictions output message)\n When this service is called, return the current best prediction and invalidate all the predictions in its neighborhood.\n * Publisher : publish on the 'predictions' topic a ListOfPredictions message\n\n How to run?\n * roslaunch realsense2_camera rs_camera.launch align_depth:=true (to provide a /camera/color/image_raw topic)\n * rosrun raiv_research node_visu_prediction.py (to view the success/fail prediction points on the image)\n * rosrun raiv_research node_best_prediction.py CKPT_FILE --invalidation_radius INT --image_topic STR (to provide a /predictions topic)\n * rosservice call /best_prediction_service (to get the current best prediction. It loads a new image and invalidates the points in the picking zone)\n\n \"\"\"\n def __init__(self, ckpt_model_file, invalidation_radius, image_topic):\n rospy.init_node('node_best_prediction')\n # Provide these services\n rospy.Service('/best_prediction_service', GetBestPrediction, self._best_prediction_service)\n rospy.Service('/Process_new_images', ProcessNewImage, self._process_new_images)\n # Publish these topics\n self.pub_images = rospy.Publisher('/new_images', RgbAndDepthImages, queue_size=10)\n self.pub_predictions = rospy.Publisher('/predictions', ListOfPredictions, queue_size=10)\n ### Use these services\n rospy.wait_for_service('/Is_Picking_Box_Empty')\n self.is_picking_box_empty_service = rospy.ServiceProxy('/Is_Picking_Box_Empty', PickingBoxIsEmpty)\n rospy.wait_for_service('/In_box_coordService')\n self.coord_serv = rospy.ServiceProxy('/In_box_coordService', get_coordservice)\n # Attributs\n self.invalidation_radius = invalidation_radius # When a prediction is selected, we invalidate all the previous predictions in this radius\n self.image_topic = image_topic\n self.model_path = ckpt_model_file\n self.model = RgbCnn.load_ckpt_model_file(self.model_path) # Load the selected model\n self.picking_point = None # No picking point yet\n self.prediction_processing = False\n self.predictions = [] # List of all predictions made for some random points\n\n #self._process_new_image(None)\n\n def generate_predictions(self):\n \"\"\"\n Main method which generates a list of predictions and publish it on the /predictions topic\n \"\"\"\n # Message used to send the list of all predictions\n msg_list_pred = ListOfPredictions()\n #self.coord_serv('random', InBoxCoord.PICK, InBoxCoord.ON_OBJECT, ImageTools.CROP_WIDTH, ImageTools.CROP_HEIGHT, None, None)\n ind_image = 0\n while not self._is_picking_box_empty():\n if self.prediction_processing:\n # Ask 'In_box_coordService' service for a random point in the picking box located on one of the objects\n resp = self.coord_serv('random_no_refresh', InBoxCoord.PICK, InBoxCoord.ON_OBJECT, ImageTools.CROP_WIDTH, ImageTools.CROP_HEIGHT, None, None)\n #if self._not_in_picking_zone(resp.x_pixel, resp.y_pixel): # Compute prediction only for necessary points (on an object, not in forbidden zone, ...)\n msg = Prediction()\n msg.x = resp.x_pixel\n msg.y = resp.y_pixel\n image_pil = ImageTools.ros_msg_to_pil(resp.rgb_crop)\n # Compute the prediction for this cropped image\n pred = RgbCnn.predict_from_pil_rgb_image(self.model, image_pil)\n msg.proba, _ = Cnn.compute_prob_and_class(pred)\n if DEBUG:\n # Save image for DEBUG\n name = f'img_{ind_image}_{msg.x}_{msg.y}_{msg.proba*100:.2f}.png'\n image_pil.save('../images_debug/'+name)\n ind_image += 1\n self.predictions.append(msg)\n #self.predictions.sort(key=lambda x: x.proba, reverse=True) # sort by decreasing proba\n msg_list_pred.predictions = self.predictions\n self.pub_predictions.publish(msg_list_pred) # Publish the current list of predictions [ [x1,y1,prediction_1], ..... ]\n rospy.sleep(0.001)\n print('End of bin picking operation')\n\n # Methods used when a service is called\n #\n def _process_new_images(self, req):\n \"\"\"\n Get new RGB and DEPTH images and publish them to the new_images topic (for node_visu_prediction.py and get_coord_node.py)\n Called by /Process_new_images service\n \"\"\"\n msg_image = rospy.wait_for_message(RGB_IMAGE_TOPIC, Image)\n msg_depth_image = rospy.wait_for_message(DEPTH_IMAGE_TOPIC, Image)\n msg = RgbAndDepthImages()\n msg.rgb_image = msg_image\n msg.depth_image = msg_depth_image\n self.pub_images.publish(msg)\n self.predictions = []\n self.prediction_processing = True\n return ProcessNewImageResponse()\n\n def _best_prediction_service(self, req):\n \"\"\"\n Called by /Process_new_image service\n \"\"\"\n # Find best prediction\n if not self.predictions: # This list is empty\n raise rospy.ServiceException(\"self.predictions : empty list in _best_prediction_service\")\n else: # Return the best prediction from 'predictions' list\n best_prediction = max(self.predictions, key=lambda p: p.proba)\n print(f'Best prediction = {best_prediction}')\n self.picking_point = (best_prediction.x, best_prediction.y)\n return GetBestPredictionResponse(best_prediction)\n\n # Other methods\n\n def _is_picking_box_empty(self):\n \"\"\"\n Test if picking box is empty.\n Called when we use the /Is_Picking_Box_Empty service\n \"\"\"\n picking_box_empty = self.is_picking_box_empty_service().empty_box\n if picking_box_empty:\n self.predictions = []\n return picking_box_empty\n\n #\n # If we take into account an invalidation radius\n #\n def _invalidate_neighborhood(self, x, y):\n \"\"\" Invalidate (remove) all the predictions in a circle of radius INVALIDATION_RADIUS centered in (x,y)\"\"\"\n self.predictions = [pred for pred in self.predictions if math.dist((pred.x, pred.y), (x, y)) > self.invalidation_radius]\n\n def _not_in_picking_zone(self, x, y):\n \"\"\" Return True if this (x,y) point is a good candidate i.e. is not in the invalidated zone (current picking zone).\n Prediction will be computed only for good candidate points.\n \"\"\"\n # Test if inside the picking zone (so, not a good candidate)\n return not (self.picking_point and math.dist((self.picking_point[0], self.picking_point[1]), (x, y)) < self.invalidation_radius)\n\n\n\nif __name__ == '__main__':\n import argparse\n # Analyse arguments\n parser = argparse.ArgumentParser(description='Compute a list of predictions for random points and provide the best one as a service.')\n parser.add_argument('ckpt_model_file', type=str, help='CKPT model file')\n parser.add_argument('--image_topic', type=str, default=\"/camera/color/image_raw\", help='Topic which provides an image')\n parser.add_argument('--invalidation_radius', type=int, default=30, help='Radius in pixels where predictions will be invalidated')\n args = parser.parse_args()\n try:\n node_best_pred = NodeBestPrediction(args.ckpt_model_file, args.invalidation_radius, args.image_topic)\n node_best_pred.generate_predictions()\n except rospy.ROSInterruptException:\n pass", "repo_name": "raiv-toulouse/raiv_research", "sub_path": "src/node_best_prediction.py", "file_name": "node_best_prediction.py", "file_ext": "py", "file_size_in_byte": 8548, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "rospy.init_node", "line_number": 39, "usage_type": "call"}, {"api_name": "rospy.Service", "line_number": 41, "usage_type": "call"}, {"api_name": "raiv_research.srv.GetBestPrediction", "line_number": 41, "usage_type": "argument"}, {"api_name": "rospy.Service", "line_number": 42, "usage_type": "call"}, {"api_name": "raiv_research.srv.ProcessNewImage", "line_number": 42, "usage_type": "argument"}, {"api_name": "rospy.Publisher", "line_number": 44, "usage_type": "call"}, {"api_name": "raiv_research.msg.RgbAndDepthImages", "line_number": 44, "usage_type": "argument"}, {"api_name": "rospy.Publisher", "line_number": 45, "usage_type": "call"}, {"api_name": "raiv_research.msg.ListOfPredictions", "line_number": 45, "usage_type": "argument"}, {"api_name": "rospy.wait_for_service", "line_number": 47, "usage_type": "call"}, {"api_name": "rospy.ServiceProxy", "line_number": 48, "usage_type": "call"}, {"api_name": "raiv_libraries.srv.PickingBoxIsEmpty", "line_number": 48, "usage_type": "argument"}, {"api_name": "rospy.wait_for_service", "line_number": 49, "usage_type": "call"}, {"api_name": "rospy.ServiceProxy", "line_number": 50, "usage_type": "call"}, {"api_name": "raiv_libraries.srv.get_coordservice", "line_number": 50, "usage_type": "argument"}, {"api_name": "raiv_libraries.rgb_cnn.RgbCnn.load_ckpt_model_file", "line_number": 55, "usage_type": "call"}, {"api_name": "raiv_libraries.rgb_cnn.RgbCnn", "line_number": 55, "usage_type": "name"}, {"api_name": "raiv_research.msg.ListOfPredictions", "line_number": 67, "usage_type": "call"}, {"api_name": "raiv_libraries.get_coord_node.InBoxCoord.PICK", "line_number": 73, "usage_type": "attribute"}, {"api_name": "raiv_libraries.get_coord_node.InBoxCoord", "line_number": 73, "usage_type": "name"}, {"api_name": "raiv_libraries.get_coord_node.InBoxCoord.ON_OBJECT", "line_number": 73, "usage_type": "attribute"}, {"api_name": "raiv_libraries.image_tools.ImageTools.CROP_WIDTH", "line_number": 73, "usage_type": "attribute"}, {"api_name": "raiv_libraries.image_tools.ImageTools", "line_number": 73, "usage_type": "name"}, {"api_name": "raiv_libraries.image_tools.ImageTools.CROP_HEIGHT", "line_number": 73, "usage_type": "attribute"}, {"api_name": "raiv_research.msg.Prediction", "line_number": 75, "usage_type": "call"}, {"api_name": "raiv_libraries.image_tools.ImageTools.ros_msg_to_pil", "line_number": 78, "usage_type": "call"}, {"api_name": "raiv_libraries.image_tools.ImageTools", "line_number": 78, "usage_type": "name"}, {"api_name": "raiv_libraries.rgb_cnn.RgbCnn.predict_from_pil_rgb_image", "line_number": 80, "usage_type": "call"}, {"api_name": "raiv_libraries.rgb_cnn.RgbCnn", "line_number": 80, "usage_type": "name"}, {"api_name": "raiv_libraries.cnn.Cnn.compute_prob_and_class", "line_number": 81, "usage_type": "call"}, {"api_name": "raiv_libraries.cnn.Cnn", "line_number": 81, "usage_type": "name"}, {"api_name": "rospy.sleep", "line_number": 91, "usage_type": "call"}, {"api_name": "rospy.wait_for_message", "line_number": 101, "usage_type": "call"}, {"api_name": "sensor_msgs.msg.Image", "line_number": 101, "usage_type": "argument"}, {"api_name": "rospy.wait_for_message", "line_number": 102, "usage_type": "call"}, {"api_name": "sensor_msgs.msg.Image", "line_number": 102, "usage_type": "argument"}, {"api_name": "raiv_research.msg.RgbAndDepthImages", "line_number": 103, "usage_type": "call"}, {"api_name": "raiv_research.srv.ProcessNewImageResponse", "line_number": 109, "usage_type": "call"}, {"api_name": "rospy.ServiceException", "line_number": 117, "usage_type": "call"}, {"api_name": "raiv_research.srv.GetBestPredictionResponse", "line_number": 122, "usage_type": "call"}, {"api_name": "math.dist", "line_number": 141, "usage_type": "call"}, {"api_name": "math.dist", "line_number": 148, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 155, "usage_type": "call"}, {"api_name": "rospy.ROSInterruptException", "line_number": 163, "usage_type": "attribute"}]} +{"seq_id": "32888182485", "text": "# Script to filter dependency information from Kanzi engine source codes.\nimport os\nimport sys\nimport re\nimport xml.etree.ElementTree as ET\nfrom dot import *\n\noutputPath = os.path.normpath(\"../../output/dependencies\")\n\nindividualClusterLinkNodes = False\n\n\n# Dependency XML -> DOT XML\n\n# All dependencies\n\ndef processFolderDependencies(sourceFolder, targetFolder):\n processedClusters = set()\n topLevelLinks = []\n processedLinks = set()\n clusters = set()\n links = []\n for folder in sourceFolder.findall(\"folder\"):\n clusterId = folder.get(\"path\")\n if clusterId in processedClusters:\n raise RuntimeError(\"Duplicate folders encountered\")\n else:\n processedClusters.add(clusterId)\n clusterName = folder.get(\"name\")\n subFolder = ET.SubElement(targetFolder, \"cluster\", {\"id\" : clusterId, \"name\" : clusterName})\n clusters.add(clusterId)\n if not individualClusterLinkNodes:\n ET.SubElement(subFolder, \"node\", {\"id\" : clusterId, \"name\" : \"\", \"shape\" : \"point\", \"style\" : \"invis\"})\n collectedLinks = processFolderDependencies(folder, subFolder)\n \n for link in collectedLinks:\n parentId = sourceFolder.get(\"path\")\n if parentId != \"\":\n parentId = parentId + \"/\"\n if link.find(parentId) == 0:\n targetId = parentId + re.search(\"([^/]*).*\", link[len(parentId):]).group(1)\n sourceId = clusterId\n linkId = sourceId + \"&\" + targetId\n if linkId not in processedLinks:\n processedLinks.add(linkId)\n links.append([sourceId, targetId])\n else:\n topLevelLinks.append(link)\n \n processedNodes = {}\n for file in sourceFolder.findall(\"file\"):\n nodeId = file.get(\"path\")\n if nodeId in processedNodes:\n node = processedNodes[nodeId]\n else:\n nodeName = file.get(\"name\")\n node = ET.SubElement(targetFolder, \"node\", {\"id\" : nodeId, \"name\" : nodeName, \"shape\" : \"box\"})\n processedNodes[nodeId] = node\n \n for reference in file.findall(\"reference\"):\n target = reference.get(\"target\")\n parentId = sourceFolder.get(\"path\")\n if parentId != \"\":\n parentId = parentId + \"/\"\n if target.find(parentId) == 0:\n targetId = parentId + re.search(\"([^/]*).*\", target[len(parentId):]).group(1)\n if nodeId != targetId:\n linkId = nodeId + \"&\" + targetId\n if linkId not in processedLinks:\n processedLinks.add(linkId)\n links.append([nodeId, targetId])\n else:\n topLevelLinks.append(target)\n \n for link in links:\n sourceId = link[0]\n targetId = link[1]\n linkNode = ET.SubElement(targetFolder, \"link\", {\"source-id\" : sourceId, \"target-id\" : targetId})\n if individualClusterLinkNodes:\n for sourceIdFolder in targetFolder.findall(\"cluster\"):\n if sourceIdFolder.get(\"id\") == sourceId:\n ET.SubElement(sourceIdFolder, \"node\", {\"id\" : \"out_\" + sourceId + \"_\" + targetId, \"name\" : \"\", \"shape\" : \"point\", \"style\" : \"invis\"})\n for targetIdFolder in targetFolder.findall(\"cluster\"):\n if targetIdFolder.get(\"id\") == targetId:\n ET.SubElement(targetIdFolder, \"node\", {\"id\" : \"in_\" + sourceId + \"_\" + targetId, \"name\" : \"\", \"shape\" : \"point\", \"style\" : \"invis\"})\n if targetId in clusters:\n linkNode.set(\"lhead\", targetId)\n linkNode.set(\"target-id\", \"in_\" + sourceId + \"_\" + targetId)\n if sourceId in clusters:\n linkNode.set(\"ltail\", sourceId)\n linkNode.set(\"source-id\", \"out_\" + sourceId + \"_\" + targetId)\n else:\n if targetId in clusters:\n linkNode.set(\"lhead\", targetId)\n linkNode.set(\"target-id\", targetId)\n if sourceId in clusters:\n linkNode.set(\"ltail\", sourceId)\n linkNode.set(\"source-id\", sourceId)\n if targetId in clusters or sourceId in clusters:\n linkNode.set(\"weight\", \"100\")\n \n return topLevelLinks\n\ndef processFolderDetailedDependencies(sourceFolder, targetFolder):\n links = []\n for folder in sourceFolder.findall(\"folder\"):\n clusterId = folder.get(\"path\")\n clusterName = folder.get(\"name\")\n subFolder = ET.SubElement(targetFolder, \"cluster\", {\"id\" : clusterId, \"name\" : clusterName})\n links.extend(processFolderDetailedDependencies(folder, subFolder))\n \n processedNodes = {}\n for file in sourceFolder.findall(\"file\"):\n nodeId = file.get(\"path\")\n nodeName = file.get(\"name\")\n node = ET.SubElement(targetFolder, \"node\", {\"id\" : nodeId, \"name\" : nodeName, \"shape\" : \"box\"})\n for reference in file.findall(\"reference\"):\n target = reference.get(\"target\")\n links.append([nodeId, target])\n \n parentId = sourceFolder.get(\"path\")\n if parentId != \"\":\n parentId = parentId + \"/\"\n topLevelLinks = []\n for link in links:\n sourceId = link[0]\n targetId = link[1]\n if targetId.find(parentId) == 0:\n linkNode = ET.SubElement(targetFolder, \"link\", {\"source-id\" : sourceId, \"target-id\" : targetId})\n else:\n topLevelLinks.append(link)\n \n return topLevelLinks\n\ndef createDependencies(root):\n newRoot = ET.Element(\"singleDependencies\", {\"rankdir\" : \"LR\", \"compound\" : \"true\", \"concentrate\" : \"true\", \"remincross\" : \"true\", \"searchsize\" : \"1000\"})\n # Create dependencies from all dependencies\n processFolderDependencies(root, newRoot)\n return newRoot\n\n# Internal dependencies\n\ndef gatherTargets(cluster, filterString):\n keep = set()\n \n for subCluster in cluster.findall(\"cluster\"):\n keep |= (gatherTargets(subCluster, filterString))\n \n for link in cluster.findall(\"link\"):\n sourceId = link.get(\"source-id\")\n targetId = link.get(\"target-id\")\n if filterString in sourceId or filterString in targetId:\n if sourceId.count(\"/\") < filterString.count(\"/\") + 2:\n targetId = link.get(\"target-id\")\n keep.add(sourceId)\n keep.add(targetId)\n \n return keep\n \ndef filterClusterDependencies(sourceCluster, targetCluster, keep, filterString):\n retval = False\n for sourceSubCluster in sourceCluster.findall(\"cluster\"):\n targetSubCluster = ET.SubElement(targetCluster, sourceSubCluster.tag, sourceSubCluster.attrib)\n needed = filterClusterDependencies(sourceSubCluster, targetSubCluster, keep, filterString)\n if not needed:\n targetCluster.remove(targetSubCluster)\n else:\n retval = True;\n \n for node in sourceCluster.findall(\"node\"):\n nodeId = node.get(\"id\")\n if nodeId in keep:\n ET.SubElement(targetCluster, node.tag, node.attrib)\n retval = True\n \n for link in sourceCluster.findall(\"link\"):\n sourceId = link.get(\"source-id\")\n targetId = link.get(\"target-id\")\n if filterString == sourceId or filterString == targetId:\n ET.SubElement(targetCluster, link.tag, link.attrib)\n \n return retval\n\ndef filterDependencies(root, filterString):\n keep = gatherTargets(root, filterString)\n newRoot = ET.Element(root.tag, root.attrib)\n filterClusterDependencies(root, newRoot, keep, filterString)\n return newRoot\n\ndef makeDependencies(dependencies, filterString):\n filteredDependencies = filterDependencies(dependencies, filterString)\n finalize(filteredDependencies, os.path.join(outputPath, \"Components\", filterString, \"Dependencies\"))\n\ndef makeAllClusterDependencies(dependencies, cluster):\n filterString = cluster.get(\"id\")\n makeDependencies(dependencies, filterString)\n \n for subCluster in cluster.findall(\"cluster\"):\n makeAllClusterDependencies(dependencies, subCluster)\n\ndef makeAllDependencies(dependencies):\n for subCluster in dependencies.findall(\"cluster\"):\n makeAllClusterDependencies(dependencies, subCluster)\n# Program starts here\n\ndependencies = None\nif len(sys.argv) < 2 or sys.argv[1] == \"/?\":\n print(\"Usage: single_dependencies.py [filter-string]\")\n sys.exit()\n\n# Load existing XML tree\nroot = ET.parse(sys.argv[1]).getroot()\ndependencies = createDependencies(root)\n\nif len(sys.argv) == 3:\n makeDependencies(dependencies, sys.argv[2])\nelse:\n makeAllDependencies(dependencies)", "repo_name": "NickTompkins123/perf_tester", "sub_path": "app/jobs/basemarkcl/bench/basemarkcl_gold_source/source_package/source/Kanzi/Engine/scripts/dependencies/single_dependencies.py", "file_name": "single_dependencies.py", "file_ext": "py", "file_size_in_byte": 8712, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "os.path.normpath", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "xml.etree.ElementTree.SubElement", "line_number": 30, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 30, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.SubElement", "line_number": 33, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 33, "usage_type": "name"}, {"api_name": "re.search", "line_number": 41, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.SubElement", "line_number": 57, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 57, "usage_type": "name"}, {"api_name": "re.search", "line_number": 66, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.SubElement", "line_number": 78, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 78, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.SubElement", "line_number": 82, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 82, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.SubElement", "line_number": 85, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 85, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.SubElement", "line_number": 109, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 109, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.SubElement", "line_number": 116, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 116, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.SubElement", "line_number": 129, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 129, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 136, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 136, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.SubElement", "line_number": 163, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 163, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.SubElement", "line_number": 173, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 173, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.SubElement", "line_number": 180, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 180, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.Element", "line_number": 186, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 186, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 192, "usage_type": "call"}, {"api_name": "os.path", "line_number": 192, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 207, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 209, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 212, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 212, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 212, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 215, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 216, "usage_type": "attribute"}]} +{"seq_id": "17642198520", "text": "import logging\nimport os\nimport threading\nimport time\n\nfrom autotest_lib.client.cros.audio import audio_test_data\nfrom autotest_lib.client.cros.chameleon import audio_test_utils\nfrom autotest_lib.client.cros.chameleon import chameleon_audio_helper\nfrom autotest_lib.client.cros.chameleon import chameleon_audio_ids\nfrom autotest_lib.server.cros.audio import audio_test\nfrom autotest_lib.server.cros.multimedia import remote_facade_factory\n\n\nclass audio_AudioBasicHDMI(audio_test.AudioTest):\n \"\"\"Server side HDMI audio test.\n\n This test talks to a Chameleon board and a Cros device to verify\n HDMI audio function of the Cros device.\n\n \"\"\"\n version = 2\n DELAY_BEFORE_PLAYBACK = 2\n DELAY_AFTER_PLAYBACK = 2\n CONNECT_TIMEOUT_SEC = 30\n SUSPEND_SEC = 15\n WAIT_TO_REBIND_SEC = 15\n WEB_PLAYBACK_SEC = 15\n\n def cleanup(self):\n \"\"\"Restore the CPU scaling governor mode.\"\"\"\n self._system_facade.set_scaling_governor_mode(0, self._original_mode)\n logging.debug('Set CPU0 mode to %s', self._original_mode)\n\n\n def set_high_performance_mode(self):\n \"\"\"Set the CPU scaling governor mode to performance mode.\"\"\"\n self._original_mode = self._system_facade.set_scaling_governor_mode(\n 0, 'performance')\n logging.debug('Set CPU0 scaling governor mode to performance, '\n 'original_mode: %s', self._original_mode)\n\n\n def playback_and_suspend(self, audio_facade, while_playback):\n \"\"\" Does playback and suspend-resume.\n\n @param audio_facade: audio facade to check nodes.\n @param while_playback: whether to play when suspending.\n \"\"\"\n if while_playback:\n logging.info('Playing audio served on the web...')\n web_file = audio_test_data.HEADPHONE_10MIN_TEST_FILE\n file_url = getattr(web_file, 'url', None)\n browser_facade = self.factory.create_browser_facade()\n tab_descriptor = browser_facade.new_tab(file_url)\n time.sleep(self.WEB_PLAYBACK_SEC)\n logging.info('Suspending...')\n boot_id = self.host.get_boot_id()\n self.host.suspend(suspend_time=self.SUSPEND_SEC)\n self.host.test_wait_for_resume(boot_id, self.CONNECT_TIMEOUT_SEC)\n logging.info('Resumed and back online.')\n time.sleep(self.WAIT_TO_REBIND_SEC)\n\n # Stop audio playback by closing the browser tab.\n if while_playback:\n browser_facade.close_tab(tab_descriptor)\n audio_test_utils.check_audio_nodes(audio_facade,\n (['HDMI'], None))\n\n\n def run_once(self, host, suspend=False, while_playback=False,\n check_quality=False):\n \"\"\"Running basic HDMI audio tests.\n\n @param host: device under test host\n @param suspend: whether to suspend\n @param while_playback: whether to suspend while audio playback\n @param check_quality: True to check quality.\n\n \"\"\"\n golden_file = audio_test_data.FREQUENCY_TEST_FILE\n self.host = host\n\n # Dump audio diagnostics data for debugging.\n chameleon_board = host.chameleon\n self.factory = remote_facade_factory.RemoteFacadeFactory(\n host, results_dir=self.resultsdir)\n\n # For DUTs with permanently connected audio jack cable\n # connecting HDMI won't switch automatically the node. Adding\n # audio_jack_plugged flag to select HDMI node after binding.\n audio_facade = self.factory.create_audio_facade()\n output_nodes, _ = audio_facade.get_selected_node_types()\n audio_jack_plugged = False\n if output_nodes == ['HEADPHONE'] or output_nodes == ['LINEOUT']:\n audio_jack_plugged = True\n logging.debug('Found audio jack plugged!')\n\n self._system_facade = self.factory.create_system_facade()\n self.set_high_performance_mode()\n\n chameleon_board.setup_and_reset(self.outputdir)\n\n widget_factory = chameleon_audio_helper.AudioWidgetFactory(\n self.factory, host)\n\n source = widget_factory.create_widget(\n chameleon_audio_ids.CrosIds.HDMI)\n recorder = widget_factory.create_widget(\n chameleon_audio_ids.ChameleonIds.HDMI)\n binder = widget_factory.create_binder(source, recorder)\n\n with chameleon_audio_helper.bind_widgets(binder):\n audio_test_utils.dump_cros_audio_logs(\n host, audio_facade, self.resultsdir, 'after_binding')\n\n # HDMI node needs to be selected, when audio jack is plugged\n if audio_jack_plugged:\n audio_facade.set_chrome_active_node_type('HDMI', None)\n audio_test_utils.check_audio_nodes(audio_facade,\n (['HDMI'], None))\n\n # Suspend after playing audio (if directed) and resume\n # before the HDMI audio test.\n if suspend:\n self.playback_and_suspend(audio_facade, while_playback)\n\n source.set_playback_data(golden_file)\n\n logging.info('Start recording from Chameleon.')\n recorder.start_recording()\n\n time.sleep(self.DELAY_BEFORE_PLAYBACK)\n\n logging.info('Start playing %s on Cros device',\n golden_file.path)\n source.start_playback(blocking=True)\n\n logging.info('Stopped playing %s on Cros device',\n golden_file.path)\n time.sleep(self.DELAY_AFTER_PLAYBACK)\n\n audio_test_utils.dump_cros_audio_logs(\n host, audio_facade, self.resultsdir, 'after_recording')\n\n recorder.stop_recording()\n logging.info('Stopped recording from Chameleon.')\n recorder.read_recorded_binary()\n\n recorded_file = os.path.join(self.resultsdir, \"recorded.raw\")\n logging.info('Saving recorded data to %s', recorded_file)\n recorder.save_file(recorded_file)\n\n audio_test_utils.check_recorded_frequency(\n golden_file, recorder, check_artifacts=check_quality)\n", "repo_name": "kindle4jerry/honor-play-kernel-9.0-kindle4jerry", "sub_path": "external/autotest/server/site_tests/audio_AudioBasicHDMI/audio_AudioBasicHDMI.py", "file_name": "audio_AudioBasicHDMI.py", "file_ext": "py", "file_size_in_byte": 6126, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "20", "api": [{"api_name": "autotest_lib.server.cros.audio.audio_test.AudioTest", "line_number": 14, "usage_type": "attribute"}, {"api_name": "autotest_lib.server.cros.audio.audio_test", "line_number": 14, "usage_type": "name"}, {"api_name": "logging.debug", "line_number": 32, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 39, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 50, "usage_type": "call"}, {"api_name": "autotest_lib.client.cros.audio.audio_test_data.HEADPHONE_10MIN_TEST_FILE", "line_number": 51, "usage_type": "attribute"}, {"api_name": "autotest_lib.client.cros.audio.audio_test_data", "line_number": 51, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 55, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 56, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 60, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 61, "usage_type": "call"}, {"api_name": "autotest_lib.client.cros.chameleon.audio_test_utils.check_audio_nodes", "line_number": 66, "usage_type": "call"}, {"api_name": "autotest_lib.client.cros.chameleon.audio_test_utils", "line_number": 66, "usage_type": "name"}, {"api_name": "autotest_lib.client.cros.audio.audio_test_data.FREQUENCY_TEST_FILE", "line_number": 80, "usage_type": "attribute"}, {"api_name": "autotest_lib.client.cros.audio.audio_test_data", "line_number": 80, "usage_type": "name"}, {"api_name": "autotest_lib.server.cros.multimedia.remote_facade_factory.RemoteFacadeFactory", "line_number": 85, "usage_type": "call"}, {"api_name": "autotest_lib.server.cros.multimedia.remote_facade_factory", "line_number": 85, "usage_type": "name"}, {"api_name": "logging.debug", "line_number": 96, "usage_type": "call"}, {"api_name": "autotest_lib.client.cros.chameleon.chameleon_audio_helper.AudioWidgetFactory", "line_number": 103, "usage_type": "call"}, {"api_name": "autotest_lib.client.cros.chameleon.chameleon_audio_helper", "line_number": 103, "usage_type": "name"}, {"api_name": "autotest_lib.client.cros.chameleon.chameleon_audio_ids.CrosIds", "line_number": 107, "usage_type": "attribute"}, {"api_name": "autotest_lib.client.cros.chameleon.chameleon_audio_ids", "line_number": 107, "usage_type": "name"}, {"api_name": "autotest_lib.client.cros.chameleon.chameleon_audio_ids.ChameleonIds", "line_number": 109, "usage_type": "attribute"}, {"api_name": "autotest_lib.client.cros.chameleon.chameleon_audio_ids", "line_number": 109, "usage_type": "name"}, {"api_name": "autotest_lib.client.cros.chameleon.chameleon_audio_helper.bind_widgets", "line_number": 112, "usage_type": "call"}, {"api_name": "autotest_lib.client.cros.chameleon.chameleon_audio_helper", "line_number": 112, "usage_type": "name"}, {"api_name": "autotest_lib.client.cros.chameleon.audio_test_utils.dump_cros_audio_logs", "line_number": 113, "usage_type": "call"}, {"api_name": "autotest_lib.client.cros.chameleon.audio_test_utils", "line_number": 113, "usage_type": "name"}, {"api_name": "autotest_lib.client.cros.chameleon.audio_test_utils.check_audio_nodes", "line_number": 119, "usage_type": "call"}, {"api_name": "autotest_lib.client.cros.chameleon.audio_test_utils", "line_number": 119, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 129, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 132, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 134, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 138, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 140, "usage_type": "call"}, {"api_name": "autotest_lib.client.cros.chameleon.audio_test_utils.dump_cros_audio_logs", "line_number": 142, "usage_type": "call"}, {"api_name": "autotest_lib.client.cros.chameleon.audio_test_utils", "line_number": 142, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 146, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 149, "usage_type": "call"}, {"api_name": "os.path", "line_number": 149, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 150, "usage_type": "call"}, {"api_name": "autotest_lib.client.cros.chameleon.audio_test_utils.check_recorded_frequency", "line_number": 153, "usage_type": "call"}, {"api_name": "autotest_lib.client.cros.chameleon.audio_test_utils", "line_number": 153, "usage_type": "name"}]} +{"seq_id": "43704086062", "text": "from __future__ import print_function\nfrom __future__ import division\n# ------------------------------------------------------------------------------------------------\n# Copyright (c) 2016 Microsoft Corporation\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and\n# associated documentation files (the \"Software\"), to deal in the Software without restriction,\n# including without limitation the rights to use, copy, modify, merge, publish, distribute,\n# sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all copies or\n# substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n# NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n# ------------------------------------------------------------------------------------------------\n\n# Test multi-agent visibility issues (see https://github.com/Microsoft/malmo/issues/443)\n# Launches a multi-agent mission where each agent is positioned in a circle, facing the centre.\n# If the number of agents is small enough (eg 3 or 4), each agent should be able to see every other agent.\n# Some basic image processing is applied in order to test this.\n\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import range\nfrom past.utils import old_div\nWIDTH=860\nHEIGHT=480\n\nimport MalmoPython\nimport logging\nimport math\nimport os\nimport random\nimport sys\nimport time\nimport uuid\nimport errno\n\nif sys.version_info[0] == 2:\n sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # flush print output immediately\nelse:\n import functools\n print = functools.partial(print, flush=True)\n\n# Create somewhere to store any failed frames:\nFAILED_FRAME_DIR = \"VisibilityTest_FailedFrames\"\ntry:\n os.makedirs(FAILED_FRAME_DIR)\nexcept OSError as exception:\n if exception.errno != errno.EEXIST: # ignore error if already existed\n raise\n\n# Create the first agent host - needed to process command-line options:\nagent_hosts = [MalmoPython.AgentHost()]\n\n# Parse the command-line options:\nagent_hosts[0].addOptionalFlag(\"debug,d\", \"Display mission start debug information.\")\nagent_hosts[0].addOptionalFlag(\"gui,g\", \"Display image processing steps in a gui window.\")\nagent_hosts[0].addOptionalIntArgument(\"agents,n\", \"Number of agents to use.\", 4)\ntry:\n agent_hosts[0].parse( sys.argv )\nexcept RuntimeError as e:\n print('ERROR:',e)\n print(agent_hosts[0].getUsage())\n exit(1)\nif agent_hosts[0].receivedArgument(\"help\"):\n print(agent_hosts[0].getUsage())\n exit(0)\n\nDEBUG = agent_hosts[0].receivedArgument(\"debug\")\nSHOW_GUI = agent_hosts[0].receivedArgument(\"gui\")\nINTEGRATION_TEST_MODE = agent_hosts[0].receivedArgument(\"test\")\nagents_requested = agent_hosts[0].getIntArgument(\"agents\")\nNUM_AGENTS = max(2,min(agents_requested,4))\nif NUM_AGENTS != agents_requested:\n print(\"WARNING: using\", NUM_AGENTS, \"agents, rather than\", agents_requested)\n\n# Create the rest of the agents:\nagent_hosts += [MalmoPython.AgentHost() for x in range(1, NUM_AGENTS) ]\n# Set debug flag:\nfor ah in agent_hosts:\n ah.setDebugOutput(DEBUG) # Turn client-pool connection messages on/off.\n\nfailed_frame_count = 0\n\n# Dependencies for gui:\nif SHOW_GUI:\n if sys.version_info[0] == 2:\n # Workaround for https://github.com/PythonCharmers/python-future/issues/262\n from Tkinter import *\n else:\n from tkinter import *\n from PIL import Image\n from PIL import ImageTk\n\n root = Tk()\n root.wm_title(\"Visibility Test\")\n root_frame = Frame(root)\n Label(root_frame, text=\"Original image; greyscale image; thresholded image\").pack(padx=5, pady=5)\n canvas = Canvas(root_frame, borderwidth=0, highlightthickness=0, width=640, height=480, bg=\"#dd88aa\")\n canvas.config( width=WIDTH, height=NUM_AGENTS * 4 * (5 + HEIGHT * 0.05) )\n canvas.pack(padx=5, pady=5)\n root_frame.pack()\nelse:\n from PIL import Image\n\n# Used by the gui:\nbmp_original = 0\nbmp_luminance = 1\nbmp_thresholded = 2\nbitmaps = [[(-1, None) for bmp_type in [bmp_original, bmp_luminance, bmp_thresholded]] for x in range(NUM_AGENTS)]\n\ndef safeStartMission(agent_host, my_mission, my_client_pool, my_mission_record, role, expId):\n used_attempts = 0\n max_attempts = 5\n print(\"Calling startMission for role\", role)\n while True:\n try:\n # Attempt start:\n agent_host.startMission(my_mission, my_client_pool, my_mission_record, role, expId)\n break\n except MalmoPython.MissionException as e:\n errorCode = e.details.errorCode\n if errorCode == MalmoPython.MissionErrorCode.MISSION_SERVER_WARMING_UP:\n print(\"Server not quite ready yet - waiting...\")\n waitWhileUpdatingGui(2)\n elif errorCode == MalmoPython.MissionErrorCode.MISSION_INSUFFICIENT_CLIENTS_AVAILABLE:\n print(\"Not enough available Minecraft instances running.\")\n used_attempts += 1\n if used_attempts < max_attempts:\n print(\"Will wait in case they are starting up.\", max_attempts - used_attempts, \"attempts left.\")\n waitWhileUpdatingGui(2)\n elif errorCode == MalmoPython.MissionErrorCode.MISSION_SERVER_NOT_FOUND:\n print(\"Server not found - has the mission with role 0 been started yet?\")\n used_attempts += 1\n if used_attempts < max_attempts:\n print(\"Will wait and retry.\", max_attempts - used_attempts, \"attempts left.\")\n waitWhileUpdatingGui(2)\n else:\n print(\"Other error:\", e.message)\n print(\"Waiting will not help here - bailing immediately.\")\n exit(1)\n if used_attempts == max_attempts:\n print(\"All chances used up - bailing now.\")\n exit(1)\n print(\"startMission called okay.\")\n\ndef waitWhileUpdatingGui(pause):\n while pause > 0:\n time.sleep(0.1)\n pause -= 0.1\n if SHOW_GUI:\n root.update()\n\ndef safeWaitForStart(agent_hosts):\n print(\"Waiting for the mission to start\", end=' ')\n start_flags = [False for a in agent_hosts]\n start_time = time.time()\n time_out = 120 # Allow two minutes for mission to begin.\n while not all(start_flags) and time.time() - start_time < time_out:\n states = [a.peekWorldState() for a in agent_hosts]\n start_flags = [w.has_mission_begun for w in states]\n errors = [e for w in states for e in w.errors]\n if len(errors) > 0:\n print(\"Errors waiting for mission start:\")\n for e in errors:\n print(e.text)\n print(\"Bailing now.\")\n exit(1)\n time.sleep(0.1)\n if SHOW_GUI:\n root.update()\n print(\".\", end=' ')\n if time.time() - start_time >= time_out:\n print(\"Timed out while waiting for mission to begin running - bailing.\")\n exit(1)\n print()\n print(\"Mission has started.\")\n\ndef getPlacementString(i):\n # Place agents at equal points around a circle, facing inwards.\n radius = 5\n accuracy = 1000.\n angle = 2*i*math.pi/NUM_AGENTS\n x = old_div(int(accuracy * radius * math.cos(angle)), accuracy)\n z = old_div(int(accuracy * radius * math.sin(angle)), accuracy)\n yaw = 90 + angle*180.0/math.pi\n return 'x=\"' + str(x) + '\" y=\"227\" z=\"' + str(z) + '\" pitch=\"0\" yaw=\"' + str(yaw) + '\"'\n\ndef processFrame(width, height, pixels, agent, mission_count):\n # Attempt some fairly simple image processing in order to determine how many agents the current agent can \"see\".\n # We rely on the fact that the other agents jut above the horizon line, which is at the mid-point of the image.\n # With the time set to morning, and the weather set to clear, there should always be a good distinction between\n # background (sky) pixels, and foreground (agent) pixels. A bit of thresholding should suffice to provide a\n # fairly reliable way of counting the visible agents.\n global root, bitmaps, failed_frame_count\n channels = 3 # Following code assumes this to be true.\n \n # 1. Extract a narrow strip of the middle from the middle up:\n y1 = int(height * 0.45)\n y2 = int(height * 0.5)\n if y2 == y1:\n y1 -= 1\n num_rows = y2 - y1\n middle_strip = pixels[y1*width*channels:y2*width*channels]\n\n if SHOW_GUI:\n image_original = Image.frombytes('RGB', (width, num_rows), str(middle_strip))\n photo_original = ImageTk.PhotoImage(image_original)\n if bitmaps[agent][bmp_original][1] != None:\n canvas.delete(bitmaps[agent][bmp_original][0])\n handle = canvas.create_image(old_div(width,2), ((4*agent)+0.5)*(num_rows+5), image=photo_original)\n bitmaps[agent][bmp_original] = (handle, photo_original)\n\n # 2. Convert RGB to luminance. Build up a histogram as we go - this will be useful for finding a threshold point.\n hist = [0 for x in range(256)]\n for col in range(0, width*channels, channels):\n for row in range(0, num_rows):\n pix = col + row * width * channels\n lum = int(0.2126 * middle_strip[pix] + 0.7152 * middle_strip[pix + 1] + 0.0722 * middle_strip[pix + 2])\n hist[lum] += 1\n middle_strip[pix] = middle_strip[pix+1] = middle_strip[pix+2] = lum # assuming channels == 3\n\n if SHOW_GUI:\n image_greyscale = Image.frombytes('RGB', (width, num_rows), str(middle_strip))\n photo_greyscale = ImageTk.PhotoImage(image_greyscale)\n if bitmaps[agent][bmp_luminance][1] != None:\n canvas.delete(bitmaps[agent][bmp_luminance][0])\n handle = canvas.create_image(old_div(width,2), ((4*agent+1)+0.5)*(num_rows+5), image=photo_greyscale)\n bitmaps[agent][bmp_luminance] = (handle, photo_greyscale)\n\n # 3. Calculate a suitable threshold, using the Otsu method\n total_pixels = width * num_rows\n total_sum = 0.\n for t in range(256):\n total_sum += t * hist[t]\n sum_background = 0.\n weight_background = 0.\n weight_foreground = 0.\n max_variation = 0.\n threshold = 0\n for t in range(256):\n weight_background += hist[t]\n if weight_background == 0:\n continue\n weight_foreground = total_pixels - weight_background\n if weight_foreground == 0:\n break\n sum_background += t * hist[t]\n mean_background = old_div(sum_background, weight_background)\n mean_foreground = old_div((total_sum - sum_background), weight_foreground)\n # Between class variance:\n var = weight_background * weight_foreground * (mean_background - mean_foreground) * (mean_background - mean_foreground)\n if var > max_variation:\n max_variation = var\n threshold = t\n\n # 4. Apply this threshold\n for pix in range(len(middle_strip)):\n if middle_strip[pix] <= threshold:\n middle_strip[pix] = 255\n else:\n middle_strip[pix] = 0\n\n # 5. OR together all the rows. This helps to de-noise the image.\n # At the same time, we count the number of changes (from foreground to background, or background to foreground)\n # that occur across the scanline. Assuming that there are no partial agents at the sides of the view - ie the scanline\n # starts and ends with background - this count should result in two changes per visible agent.\n pixelvalue = lambda col: sum(middle_strip[x] for x in range(col, len(middle_strip), width * channels))\n lastval = 255\n changes = 0\n for col in range(0, width * channels, channels):\n val = 0 if pixelvalue(col) > 0 else 255\n if lastval != val:\n changes += 1\n lastval = val\n if SHOW_GUI:\n # Update the bitmap so the user can see what we see.\n for row in range(num_rows):\n middle_strip[col + row*width*channels] = val\n middle_strip[1 + col + row*width*channels] = val\n middle_strip[2 + col + row*width*channels] = 0 # blue channel always 0 (will simplify recolouring later)\n\n # 6. Perform the actual test.\n agents_detected = old_div(changes, 2)\n test_passed = agents_detected == NUM_AGENTS - 1\n\n # 7. If we're displaying the gui, recolour the final image - turn the background red for error or green for success.\n # (At the moment all background pixels have both red and green values set to 255, so all we need to do is remove\n # the relevant channel.)\n if SHOW_GUI:\n channel_mask = 0 if test_passed else 1 # Remove red channel for success, remove green for failure\n for pixel in range(channel_mask, len(middle_strip), channels):\n middle_strip[pixel] = 0\n # And add this to the GUI:\n image_threshold = Image.frombytes('RGB', (width, num_rows), str(middle_strip))\n photo_threshold = ImageTk.PhotoImage(image_threshold)\n if bitmaps[agent][bmp_thresholded][1] != None:\n canvas.delete(bitmaps[agent][bmp_thresholded][0])\n handle = canvas.create_image(old_div(width,2), ((4*agent+2)+0.5)*(num_rows+5), image=photo_threshold)\n bitmaps[agent][bmp_thresholded] = (handle, photo_threshold)\n # Update the canvas:\n root.update()\n \n if not test_passed:\n # The threshold is not entirely bullet-proof - sometimes there are drawing artifacts that can result in\n # false negatives.\n # So we save a copy of the failing frames for manual inspection:\n image_failed = Image.frombytes('RGB', (width, height), str(pixels))\n image_failed.save(FAILED_FRAME_DIR + \"/failed_frame_agent_\" + str(agent) + \"_mission_\" + str(mission_count) + \"_\" + str(failed_frame_count) + \".png\")\n failed_frame_count += 1\n return test_passed\n\ndef createMissionXML(num_agents, width, height, reset):\n # Set up the Mission XML.\n # First, the server section.\n # Weather MUST be set to clear, since the dark thundery sky plays havoc with the image thresholding.\n xml = '''\n \n \n \n \n \n \n \n clear\n \n \n \n \n \n \n '''\n\n # Add an agent section for each watcher.\n # We put them in a leather helmet because it makes the image processing slightly easier.\n for i in range(num_agents):\n placement = getPlacementString(i)\n xml += '''\n Watcher#''' + str(i) + '''\n \n \n \n \n \n \n \n \n ''' + str(width) + '''\n ''' + str(height) + '''\n \n \n '''\n\n xml += ''\n return xml\n\n# Set up a client pool.\n# IMPORTANT: If ANY of the clients will be on a different machine, then you MUST\n# make sure that any client which can be the server has an IP address that is\n# reachable from other machines - ie DO NOT SIMPLY USE 127.0.0.1!!!!\n# The IP address used in the client pool will be broadcast to other agents who\n# are attempting to find the server - so this will fail for any agents on a\n# different machine.\nclient_pool = MalmoPython.ClientPool()\nfor x in range(10000, 10000 + NUM_AGENTS):\n client_pool.add( MalmoPython.ClientInfo('127.0.0.1', x) )\n\nfailed_frames = [0 for x in range(NUM_AGENTS)] # keep a count of the frames that failed for each agent.\n\n# If we're running as part of the integration tests, just do ten iterations. Otherwise keep going.\nmissions_to_run = 10 if INTEGRATION_TEST_MODE else 30000\n\nfor mission_no in range(1,missions_to_run+1):\n # Create the mission. Force reset for the first mission, to ensure a clean world. No need for subsequent missions.\n my_mission = MalmoPython.MissionSpec(createMissionXML(NUM_AGENTS, WIDTH, HEIGHT, \"true\" if mission_no == 1 else \"false\"), True)\n print(\"Running mission #\" + str(mission_no))\n # Generate an experiment ID for this mission.\n # This is used to make sure the right clients join the right servers -\n # if the experiment IDs don't match, the startMission request will be rejected.\n # In practice, if the client pool is only being used by one researcher, there\n # should be little danger of clients joining the wrong experiments, so a static\n # ID would probably suffice, though changing the ID on each mission also catches\n # potential problems with clients and servers getting out of step.\n\n # Note that, in this sample, the same process is responsible for all calls to startMission,\n # so passing the experiment ID like this is a simple matter. If the agentHosts are distributed\n # across different threads, processes, or machines, a different approach will be required.\n # (Eg generate the IDs procedurally, in a way that is guaranteed to produce the same results\n # for each agentHost independently.)\n experimentID = str(uuid.uuid4())\n\n for i in range(len(agent_hosts)):\n safeStartMission(agent_hosts[i], my_mission, client_pool, MalmoPython.MissionRecordSpec(), i, experimentID)\n\n safeWaitForStart(agent_hosts)\n time.sleep(2)\t# Wait a short while for things to stabilise\n\n running = True\n timed_out = False\n # Main mission loop.\n # In this test, all we do is stand still and process our frames.\n while not timed_out:\n for i in range(NUM_AGENTS):\n ah = agent_hosts[i]\n world_state = ah.getWorldState()\n if world_state.is_mission_running == False:\n timed_out = True\n if world_state.is_mission_running and world_state.number_of_video_frames_since_last_state > 0:\n frame = world_state.video_frames[-1]\n can_see_agent = processFrame(frame.width, frame.height, frame.pixels, i, mission_no)\n if not can_see_agent:\n failed_frames[i] += 1\n print()\n\n if SHOW_GUI:\n canvas.delete(\"all\") # Clear the gui window in between each mission.\n\n print(\"Waiting for mission to end \", end=' ')\n hasEnded = False\n while not hasEnded:\n print(\".\", end=\"\")\n time.sleep(0.1)\n for ah in agent_hosts:\n world_state = ah.getWorldState()\n if not world_state.is_mission_running:\n hasEnded = True\n print()\n print(\"Failed frames: \", failed_frames)\n if INTEGRATION_TEST_MODE and sum(failed_frames):\n exit(1) # Test failed - quit.\n time.sleep(2)\n", "repo_name": "microsoft/malmo", "sub_path": "Malmo/samples/Python_examples/agent_visibility_test.py", "file_name": "agent_visibility_test.py", "file_ext": "py", "file_size_in_byte": 19698, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3952, "dataset": "github-code", "pt": "20", "api": [{"api_name": "future.standard_library.install_aliases", "line_number": 28, "usage_type": "call"}, {"api_name": "future.standard_library", "line_number": 28, "usage_type": "name"}, {"api_name": "sys.version_info", "line_number": 44, "usage_type": "attribute"}, {"api_name": "sys.stdout", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.fdopen", "line_number": 45, "usage_type": "call"}, {"api_name": "sys.stdout.fileno", "line_number": 45, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 48, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 53, "usage_type": "call"}, {"api_name": "errno.EEXIST", "line_number": 55, "usage_type": "attribute"}, {"api_name": "MalmoPython.AgentHost", "line_number": 59, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 66, "usage_type": "attribute"}, {"api_name": "MalmoPython.AgentHost", "line_number": 84, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 84, "usage_type": "call"}, {"api_name": "sys.version_info", "line_number": 93, "usage_type": "attribute"}, {"api_name": "builtins.range", "line_number": 116, "usage_type": "call"}, {"api_name": "MalmoPython.MissionException", "line_number": 127, "usage_type": "attribute"}, {"api_name": "MalmoPython.MissionErrorCode", "line_number": 129, "usage_type": "attribute"}, {"api_name": "MalmoPython.MissionErrorCode", "line_number": 132, "usage_type": "attribute"}, {"api_name": "MalmoPython.MissionErrorCode", "line_number": 138, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 155, "usage_type": "call"}, {"api_name": "time.time", "line_number": 163, "usage_type": "call"}, {"api_name": "time.time", "line_number": 165, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 175, "usage_type": "call"}, {"api_name": "time.time", "line_number": 179, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 189, "usage_type": "attribute"}, {"api_name": "past.utils.old_div", "line_number": 190, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 190, "usage_type": "call"}, {"api_name": "past.utils.old_div", "line_number": 191, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 191, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 192, "usage_type": "attribute"}, {"api_name": "PIL.Image.frombytes", "line_number": 213, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 213, "usage_type": "name"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 214, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 214, "usage_type": "name"}, {"api_name": "past.utils.old_div", "line_number": 217, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 221, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 222, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 223, "usage_type": "call"}, {"api_name": "PIL.Image.frombytes", "line_number": 230, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 230, "usage_type": "name"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 231, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 231, "usage_type": "name"}, {"api_name": "past.utils.old_div", "line_number": 234, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 240, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 247, "usage_type": "call"}, {"api_name": "past.utils.old_div", "line_number": 255, "usage_type": "call"}, {"api_name": "past.utils.old_div", "line_number": 256, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 264, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 274, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 277, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 284, "usage_type": "call"}, {"api_name": "past.utils.old_div", "line_number": 290, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 298, "usage_type": "call"}, {"api_name": "PIL.Image.frombytes", "line_number": 301, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 301, "usage_type": "name"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 302, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 302, "usage_type": "name"}, {"api_name": "past.utils.old_div", "line_number": 305, "usage_type": "call"}, {"api_name": "PIL.Image.frombytes", "line_number": 314, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 314, "usage_type": "name"}, {"api_name": "builtins.range", "line_number": 344, "usage_type": "call"}, {"api_name": "MalmoPython.ClientPool", "line_number": 372, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 373, "usage_type": "call"}, {"api_name": "MalmoPython.ClientInfo", "line_number": 374, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 376, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 381, "usage_type": "call"}, {"api_name": "MalmoPython.MissionSpec", "line_number": 383, "usage_type": "call"}, {"api_name": "uuid.uuid4", "line_number": 398, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 400, "usage_type": "call"}, {"api_name": "MalmoPython.MissionRecordSpec", "line_number": 401, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 404, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 411, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 430, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 439, "usage_type": "call"}]} +{"seq_id": "40020203612", "text": "import re\nimport requests\nimport datetime\nfrom collections import deque\nimport youtube_dl\n\nclass Q():\n guild = dict()\n que = deque()\n index = dict()\n entry = dict()\n\n ydl_opts = {\n 'format': 'bestaudio/best',\n 'postprocessor_args': ['-ar', '16000'],\n 'keepvideo': True,\n 'default_search': 'auto',\n }\n def __init__(self):\n return\n\n def get_yt_code(self, search_term):\n return\n\n\n def add_entry(self, ctx, search_term):\n # entry = dict()\n html_content = requests.get(\"https://www.youtube.com/results?search_query=\" + search_term)\n self.yt_code = re.findall(r'\"videoId\":\"(.{11})\"', html_content.text) #Find song ID on Youtube\n\n with youtube_dl.YoutubeDL(self.ydl_opts) as ydl:\n self.song_info = ydl.extract_info(\"https://www.youtube.com/watch?v=\" + self.yt_code[0], download=False)\n # get_yt_code(search_term)\n\n self.entry = {\n \"url\" : self.song_info[\"url\"],\n \"name\" : self.song_info[\"title\"],\n \"user\" : ctx.author,\n \"channel\" : ctx.author.voice.channel,\n \"guild\" : ctx.guild,\n \"time\" : datetime.datetime.now()\n }\n self.que.append(self.entry)\n\n if ctx.guild not in self.guild:\n self.guild[ctx.guild] = []\n self.index[ctx.guild] = 0\n self.guild[ctx.guild] = self.que\n else: \n self.guild[ctx.guild] = self.que\n return self.entry\n\n\n def delete_entry(self, ctx, num):\n de = self.guild[ctx.guild]\n del de[num]\n \n def next_track(self, ctx):\n self.index[ctx.guild] += 1\n return self.index[ctx.guild]\n \n def prev_track(self, ctx):\n self.index[ctx.guild] -= 1\n\n\n return self.index[ctx.guild]\n\n def clear_que(self, ctx, save = \"n\"):\n self.guild[ctx.guild].clear()\n self.index[ctx.guild] = 0\n\n def url(self):\n return\n\n def nowplaying(self, ctx, arg = \"name\"):\n index = self.index[ctx.guild]\n return self.que[index][arg]\n\n def my_que(self, ctx):\n formattedQ = []\n count = 1\n\n for entry in self.guild[ctx.guild]:\n string = f\"{count}. {entry['name']} added by {entry['user']}\"\n formattedQ.append(string)\n count += 1\n \n formattedQ = \"\\n\".join(formattedQ)\n\n return formattedQ\n\n\n\n# l = \"this is a sentence\".split()\n# d = dict()\n# dl = dict()\n# nameasvar = \"name\"\n# d[nameasvar] = l \n# print(d)\n# dl[nameasvar] = (\"another sentence\".split())\n# l.append(dl)\n# d[nameasvar] = l\n# print(d[\"name\"])\n\n# que = Q()\n# print(que.que_entry())", "repo_name": "neu-ma-tic/test9475", "sub_path": "a02e6b89-10e0-47a2-9157-b73da36cdb21/music_q.py", "file_name": "music_q.py", "file_ext": "py", "file_size_in_byte": 2423, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "collections.deque", "line_number": 9, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 28, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 29, "usage_type": "call"}, {"api_name": "youtube_dl.YoutubeDL", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 41, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 41, "usage_type": "attribute"}]} +{"seq_id": "31118918462", "text": "\"\"\"\nlag_transformer\n~~~~~~~~~~~~~~~~\nCustom scikit-learn transformer to create lags of time series data\n\"\"\"\n\nimport sys\n\nimport pandas as pd\n\nfrom getlags import get_lags\nfrom sklearn.base import TransformerMixin\n\n\n_DAYS_IN_WEEK = 7\n_MIN_TRAIN_SIZE = _DAYS_IN_WEEK * 16\n_NA_VAL = 0.0\n\n\nclass LagTransformer(TransformerMixin):\n \"\"\"scikit-learn custom transformer to create lagged time series\n\n Parameters\n ----------\n x_cols: List of dataframe colums to create lags\n y_col: The target value to be predicted\n lags: List to specify how much to how much to lag\n the x_cols by. (ie [1, 7, 28])\n\n Returns\n -------\n A Pandas dataframe containing lagged versions of the spcified\n columns along with the target renamed as ('y').\n \"\"\"\n\n def __init__(self, x_cols=None, y_col=None, lags=1):\n self.x_cols = x_cols\n self.y_col = y_col\n self.lags = lags\n\n def fit(self, *args, **kwargs):\n pass\n\n def transform(self, X, **transform_params):\n df_lag = get_lags(X, self.x_cols, self.y_col, self.lags)\n return df_lag\n\n def fit_transform(self, X, **transform_params):\n return self.transform(X, **transform_params)\n\n\ndef main(args):\n\n if len(args) != 1:\n print('Usage: lag_transformer source_file')\n return\n else:\n source = args[0]\n\n df_in = pd.read_excel(source, index_col='date', parse_dates=True)\n\n trans = LagTransformer(x_cols=['sales'], y_col='sales', lags=[1, 7])\n df_lags = trans.transform(df_in)\n\n print(df_lags.tail(30))\n print(df_lags.info())\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n", "repo_name": "dzereski/data-science", "sub_path": "small-box-sales-fcst/models/lag_transformer.py", "file_name": "lag_transformer.py", "file_ext": "py", "file_size_in_byte": 1626, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "sklearn.base.TransformerMixin", "line_number": 20, "usage_type": "name"}, {"api_name": "getlags.get_lags", "line_number": 45, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 60, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 70, "usage_type": "attribute"}]} +{"seq_id": "39975474291", "text": "from django.urls import path, include\n\n# Rest Framework\nfrom rest_framework.routers import DefaultRouter\n\n# Core Views\nfrom .views import EntryView, EventsView, MarkEntryView, EntryListView, EntryCSVView, CodeViewSet, AccountActiveCode\n\ncode_router = DefaultRouter()\ncode_router.register('', CodeViewSet, basename='code-viewset')\n\nurlpatterns = [\n path('entry/', EntryListView.as_view()),\n path('entry/register/', EntryView.as_view()),\n path('entry//', MarkEntryView.as_view()),\n path('events/', EventsView.as_view()),\n path('logs/', EntryCSVView.as_view()),\n path('codes/', include(code_router.urls)),\n path('mycode/', AccountActiveCode.as_view())\n]\n", "repo_name": "prathameshramane/event-portal-backend-public", "sub_path": "core/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 680, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "rest_framework.routers.DefaultRouter", "line_number": 9, "usage_type": "call"}, {"api_name": "views.CodeViewSet", "line_number": 10, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "views.EntryListView.as_view", "line_number": 13, "usage_type": "call"}, {"api_name": "views.EntryListView", "line_number": 13, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 14, "usage_type": "call"}, {"api_name": "views.EntryView.as_view", "line_number": 14, "usage_type": "call"}, {"api_name": "views.EntryView", "line_number": 14, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "views.MarkEntryView.as_view", "line_number": 15, "usage_type": "call"}, {"api_name": "views.MarkEntryView", "line_number": 15, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 16, "usage_type": "call"}, {"api_name": "views.EventsView.as_view", "line_number": 16, "usage_type": "call"}, {"api_name": "views.EventsView", "line_number": 16, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 17, "usage_type": "call"}, {"api_name": "views.EntryCSVView.as_view", "line_number": 17, "usage_type": "call"}, {"api_name": "views.EntryCSVView", "line_number": 17, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 18, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 18, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 19, "usage_type": "call"}, {"api_name": "views.AccountActiveCode.as_view", "line_number": 19, "usage_type": "call"}, {"api_name": "views.AccountActiveCode", "line_number": 19, "usage_type": "name"}]} +{"seq_id": "6147236899", "text": "from interface_framework.libs.base_request import BaseCaseRequest\nfrom interface_framework.libs.my_mysql import My_Pymysql\nimport unittest\nimport logging\n\nclass PayChannelCodeUnittest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n # main()\n cls.data = My_Pymysql()\n\n @staticmethod\n def get_test_data_calss(self):\n pass\n\n def setUp(self):\n pass\n\n def test_get_payChannelCode_CL(self):\n case_data = BaseCaseRequest(\"test_get_payChannelCode_CL\")\n res = case_data.send_requests()\n res_data = res.json().get(\"result\")\n logging.info(res_data)\n self.assertTrue(res_data)\n\n def test_get_payChannelCode_RF(self):\n case_data = BaseCaseRequest(\"test_get_payChannelCode_RF\")\n res = case_data.send_requests()\n res_data = res.json().get(\"result\")\n logging.info(res_data)\n self.assertTrue(res_data)\n\n def test_payChannelCode_is_not_exists(self):\n case_data = BaseCaseRequest(\"test_payChannelCode_is_not_exists\")\n res = case_data.send_requests()\n res_data = res.json().get(\"result\")\n logging.info(res_data)\n expect_res = case_data.expect_res\n self.assertEqual(expect_res, res_data)\n\n def test_payChannelCode_is_NULL(self):\n case_data = BaseCaseRequest(\"test_payChannelCode_is_NULL\")\n res = case_data.send_requests()\n res_data = res.json().get(\"result\")\n logging.info(res_data)\n self.assertTrue(res_data)\n\n def test_payChannelCode_is_error(self):\n case_data = BaseCaseRequest(\"test_payChannelCode_is_error\")\n res = case_data.send_requests()\n res_data = res.json().get(\"result\")\n expect_res = case_data.expect_res\n logging.info(res_data)\n self.assertEqual(expect_res, res_data)\n\nif __name__ == '__main__':\n unittest.main()", "repo_name": "zhangrui90158/interface_framework", "sub_path": "test/case/test_payChannelCode.py", "file_name": "test_payChannelCode.py", "file_ext": "py", "file_size_in_byte": 1865, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "unittest.TestCase", "line_number": 6, "usage_type": "attribute"}, {"api_name": "interface_framework.libs.my_mysql.My_Pymysql", "line_number": 11, "usage_type": "call"}, {"api_name": "interface_framework.libs.base_request.BaseCaseRequest", "line_number": 21, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 24, "usage_type": "call"}, {"api_name": "interface_framework.libs.base_request.BaseCaseRequest", "line_number": 28, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 31, "usage_type": "call"}, {"api_name": "interface_framework.libs.base_request.BaseCaseRequest", "line_number": 35, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 38, "usage_type": "call"}, {"api_name": "interface_framework.libs.base_request.BaseCaseRequest", "line_number": 43, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 46, "usage_type": "call"}, {"api_name": "interface_framework.libs.base_request.BaseCaseRequest", "line_number": 50, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 54, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 58, "usage_type": "call"}]} +{"seq_id": "10322221713", "text": "import csv\nfrom Classes.stationClass import Station\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom PythonFunctions.helpers import CalculateScore\nimport re\nimport os\n\nclass Graph(object):\n \"\"\"Graph with station with locations, destinations and some functions.\"\"\"\n def __init__(self):\n self.graph = {}\n self.allRoutes = []\n self.allStations = {}\n self.allConnections = []\n self.criticalConnections = []\n self.stationNames = []\n\n\n def load_data(self, stationsCsvFile, connectiesCsvFile, allCritical = False):\n \"\"\"Function to load stations and connections into the graph.\"\"\"\n\n # File with railwaystations and coordinates.\n stationsfile = open(stationsCsvFile, 'rt')\n stations = csv.reader(stationsfile)\n for station in stations:\n\n # Add railwaystation to allStations.\n self.stationNames.append(station[0])\n if allCritical:\n newStation = Station(station[0], float(station[1]), float(station[2]), 'Kritiek')\n else:\n newStation = Station(station[0], float(station[1]), float(station[2]), station[3])\n self.allStations[station[0]] = newStation\n self.graph[station[0]] = []\n\n stationsfile.close()\n\n # File with connections between stations.\n connecties = open(connectiesCsvFile, 'rt')\n directions = csv.reader(connecties)\n\n # Add connections to the object.\n for direction in directions:\n\n # Add connection to allConnections.\n self.allConnections.append([[direction[0], direction[1]], int(float(direction[2]))])\n\n # Add direction to the graph.\n self.graph[direction[0]].append([direction[1], int(float(direction[2]))])\n self.graph[direction[1]].append([direction[0], int(float(direction[2]))])\n\n self.allStations[direction[0]].addDestination(self.allStations[direction[1]])\n self.allStations[direction[1]].addDestination(self.allStations[direction[0]])\n\n if self.allStations[direction[0]].isCritical or self.allStations[direction[1]].isCritical:\n self.criticalConnections.append([direction[0], direction[1]])\n\n connecties.close()\n\n\n def makeAllRoutes(self, minutes):\n \"\"\"Function to make all possible routes in a timescheme.\"\"\"\n allNewRoutes = []\n for i in range(len(self.allStations)):\n for j in range(i + 1, len(self.stationNames)):\n\n # Put all routes in a list with corresponding time.\n allNewRoutes.extend(self.addPaths(self.stationNames[i], self.stationNames[j], minutes))\n self.allRoutes = allNewRoutes\n\n\n def addPaths(self, start, end, minutes, route=[], time=0):\n \"\"\"Function to get all routes between two stations, within 2 hours.\"\"\"\n\n # Add start to route.\n route = route + [start]\n\n # At the end, return the route.\n if start == end:\n return [[route, time]]\n\n # If the route doesn't exist, return nothing.\n elif not self.graph[start]:\n return []\n routes = []\n\n # Check the route for every destination.\n for destination in self.graph[start]:\n\n # Do not pass the same station twice.\n if destination[0] not in route:\n\n # Ensure the route doesn't take longer than the given timeframe.\n duration = time + int(float(destination[1]))\n if duration < minutes:\n\n # Make the new routes for the further stations.\n new_routes = self.addPaths(destination[0], end, minutes, route, duration)\n for new_route in new_routes:\n routes.append(new_route)\n return routes\n\n\n def ScorePathsPruning(self, n):\n \"\"\"Function to determine the best n trajectories based on the score.\"\"\"\n bestpaths = []\n bestscores = []\n connections_made = []\n\n # Add path, calculate score and keep track of the best score and trajectories.\n for path in self.allRoutes:\n score = CalculateScore([path], self.criticalConnections)\n if bestscores == [] or min(bestscores) < score:\n\n # If the begin or the end of a path is already chosen in another trajectory, do not choose that path.\n if (len(bestpaths) < n) and (([path[0], path[1]]) not in connections_made) and (([path[-2], path[-1]]) not in connections_made):\n bestpaths.append(path)\n bestscores.append(score)\n for i in range(len(path)-1):\n if [path[i], path[i+1]] not in connections_made:\n connections_made.append([[path[i], path[i+1]]])\n\n else:\n index = bestscores.index(min(bestscores))\n bestpaths[index] = path\n bestscores[index] = score\n\n return bestpaths, bestscores\n\n def draw(self):\n \"\"\"Function to draw the graph\"\"\"\n\n # Make new graph.\n G = nx.Graph()\n\n # Initiate dictionaries and lists for labels and colors.\n labels = {}\n node_labels = {}\n node_color = []\n\n # Add node, make node blue if station is non critical and red if station\n # is critical.\n for station in self.allStations:\n thisStation = self.allStations[station]\n if thisStation.isCritical == True:\n node_color.append(\"r\")\n else:\n node_color.append(\"b\")\n G.add_node(\"\" + thisStation.name, pos = (thisStation.latitude, thisStation.longitude))\n\n # Add abbreviation of station name as label for node.\n name = re.split('\\s|-|/', thisStation.name)\n afk = \"\"\n for word in name:\n afk += word[0]\n node_labels[thisStation.name] = afk\n\n # Add edge for every connection, make edge blue if neither of the stations\n # is critical and red if at least one of them is critical.\n # Add the time between the stations as a label for the edge.\n for connection in self.allConnections:\n if [connection[0][0], connection[0][1]] in self.criticalConnections or [connection[0][1], connection[0][0]] in self.criticalConnections:\n G.add_edge(\"\" + connection[0][0], \"\" + connection[0][1], color = 'r')\n else:\n G.add_edge(\"\" + connection[0][0], \"\" + connection[0][1], color = 'b')\n labels.update({(connection[0][0], connection[0][1]): int(connection[1])})\n\n edges = G.edges()\n edge_color = [G[u][v]['color'] for u,v in edges]\n\n # Change position of node label.\n pos = nx.get_node_attributes(G,'pos')\n pos_higher = {}\n y_off = 0.03\n x_off = 0.01\n\n for k, v in pos.items():\n pos_higher[k] = (v[0]+x_off, v[1]+y_off)\n\n # Plot the figure and save it in Results.\n plt.figure(1, figsize = (10,10))\n nx.draw(G, pos, node_color=node_color, edge_color = edge_color, node_size=70)\n nx.draw_networkx_edge_labels(G, pos, labels)\n nx.draw_networkx_labels(G, pos_higher, node_labels)\n plt.savefig(os.path.join('Results', \"Graph.png\"))\n", "repo_name": "suitendaal/RailNL", "sub_path": "Classes/graphClass.py", "file_name": "graphClass.py", "file_ext": "py", "file_size_in_byte": 7351, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "csv.reader", "line_number": 25, "usage_type": "call"}, {"api_name": "Classes.stationClass.Station", "line_number": 31, "usage_type": "call"}, {"api_name": "Classes.stationClass.Station", "line_number": 33, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 41, "usage_type": "call"}, {"api_name": "PythonFunctions.helpers.CalculateScore", "line_number": 113, "usage_type": "call"}, {"api_name": "networkx.Graph", "line_number": 135, "usage_type": "call"}, {"api_name": "re.split", "line_number": 153, "usage_type": "call"}, {"api_name": "networkx.get_node_attributes", "line_number": 173, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 182, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 182, "usage_type": "name"}, {"api_name": "networkx.draw", "line_number": 183, "usage_type": "call"}, {"api_name": "networkx.draw_networkx_edge_labels", "line_number": 184, "usage_type": "call"}, {"api_name": "networkx.draw_networkx_labels", "line_number": 185, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 186, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 186, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 186, "usage_type": "call"}, {"api_name": "os.path", "line_number": 186, "usage_type": "attribute"}]} +{"seq_id": "71773530930", "text": "# -*- coding: UTF-8 -*-\n\"\"\"\n Author : 曹鹏鹏\n E-mail : lettger@163.com\n Date : 2017/9/7\n Desc : 微信三方平台接口\n\"\"\"\nfrom handlers import BaseHandler\nfrom config import logger as log\nfrom utilities import WechatServer\nfrom client import third, reply\nfrom module.models import Service\n\n\nclass IndexHander(BaseHandler):\n # def get(self):\n # result = Service(self.session).getWebAccessToken('wx399181b3084d12f5')\n # return self.write(str(result))\n # def get(self):\n # a = Service(self.session).save(\"cccccccc\",\"xxxx\",\"aaaaa\")\n # return self.write(str(a))\n # def get(self):\n # res = Service(self.session).getAuthorizerInfoByAppId(\"wx399181b3084d12f5\")\n # return self.write(str(res))\n def get(self):\n # res = Service(self.session).getUserInfoByAid(\"905284997085265930\")\n res = Service(self.session).getUserInfoByOpenIdAndAid(2, 905284997085265930)\n return self.write(res)\n # def get(self):\n # res = Service(self.session).saveUserInfo(905284997085265930, '2', '2', False, False, 2, 2, 2, 2)\n # print res\n # return self.write(\"ok\")\n# 服务号授权控制器\nclass WechatHander(BaseHandler):\n def get(self):\n auth_code = self.get_argument('auth_code', '')\n expires_in = self.get_argument('expires_in', '')\n if len(auth_code) > 10 and int(expires_in) > 60:\n return self.write('License success!')\n url = third.auth_page()\n log.Logger().getLogger().info('>>>>>>>>>>>>>url %s' % url)\n self.render(\"auth.html\", page=str(url))\n\n def post(self):\n msg_signature = self.get_argument('msg_signature')\n timestamp = self.get_argument('timestamp')\n nonce = self.get_argument('nonce')\n log.Logger().getLogger().info('event get msg_signature: %s, timestamp: %s, nonce: %s' % (msg_signature, timestamp, nonce))\n encrypt_xml = self.request.body\n log.Logger().getLogger().info('encrypt_xml is : %s' % encrypt_xml)\n if encrypt_xml.find('ToUserName') == -1:\n encrypt_xml = encrypt_xml.replace('AppId', 'ToUserName')\n decrypt_xml = WechatServer.XmlUtils().get_decrypt_xml(encrypt_xml, msg_signature, timestamp, nonce)\n log.Logger().getLogger().info('get the ticket decryp_xml: %s' % decrypt_xml)\n if decrypt_xml.find('error') == -1:\n third.ticket(self.session, decrypt_xml)\n self.write('success')\n\n\n# 公众号消息与事件接收URL\nclass AuthHander(BaseHandler):\n def post(self, appid):\n if appid.find('wx') != 0:\n return self.write('request not appid')\n log.Logger().getLogger().info(\"request appid is :%s \" % appid)\n msg_signature = self.get_argument('msg_signature')\n timestamp = self.get_argument('timestamp')\n nonce = self.get_argument('nonce')\n log.Logger().getLogger().info('message event get msg_signature: %s, timestamp: %s, nonce: %s' % (msg_signature, timestamp, nonce))\n encrypt_xml = self.request.body.decode('utf-8')\n decrypt_xml = WechatServer.XmlUtils().get_decrypt_xml(encrypt_xml, msg_signature, timestamp, nonce)\n log.Logger().getLogger().info('get the message decryp_xml: %s' % decrypt_xml)\n if decrypt_xml.find('error') == -1:\n if appid == 'wx570bc396a51b8ff8':\n return third.whole(decrypt_xml, nonce, self)\n result = reply.reply(decrypt_xml, nonce, appid,self)\n self.write(str(result))\n", "repo_name": "lettgers/three-party-wechat", "sub_path": "handlers/Wechat.py", "file_name": "Wechat.py", "file_ext": "py", "file_size_in_byte": 3510, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "handlers.BaseHandler", "line_number": 15, "usage_type": "name"}, {"api_name": "module.models.Service", "line_number": 27, "usage_type": "call"}, {"api_name": "handlers.BaseHandler", "line_number": 34, "usage_type": "name"}, {"api_name": "client.third.auth_page", "line_number": 40, "usage_type": "call"}, {"api_name": "client.third", "line_number": 40, "usage_type": "name"}, {"api_name": "config.logger.Logger", "line_number": 41, "usage_type": "call"}, {"api_name": "config.logger", "line_number": 41, "usage_type": "name"}, {"api_name": "config.logger.Logger", "line_number": 48, "usage_type": "call"}, {"api_name": "config.logger", "line_number": 48, "usage_type": "name"}, {"api_name": "config.logger.Logger", "line_number": 50, "usage_type": "call"}, {"api_name": "config.logger", "line_number": 50, "usage_type": "name"}, {"api_name": "utilities.WechatServer.XmlUtils", "line_number": 53, "usage_type": "call"}, {"api_name": "utilities.WechatServer", "line_number": 53, "usage_type": "name"}, {"api_name": "config.logger.Logger", "line_number": 54, "usage_type": "call"}, {"api_name": "config.logger", "line_number": 54, "usage_type": "name"}, {"api_name": "client.third.ticket", "line_number": 56, "usage_type": "call"}, {"api_name": "client.third", "line_number": 56, "usage_type": "name"}, {"api_name": "handlers.BaseHandler", "line_number": 61, "usage_type": "name"}, {"api_name": "config.logger.Logger", "line_number": 65, "usage_type": "call"}, {"api_name": "config.logger", "line_number": 65, "usage_type": "name"}, {"api_name": "config.logger.Logger", "line_number": 69, "usage_type": "call"}, {"api_name": "config.logger", "line_number": 69, "usage_type": "name"}, {"api_name": "utilities.WechatServer.XmlUtils", "line_number": 71, "usage_type": "call"}, {"api_name": "utilities.WechatServer", "line_number": 71, "usage_type": "name"}, {"api_name": "config.logger.Logger", "line_number": 72, "usage_type": "call"}, {"api_name": "config.logger", "line_number": 72, "usage_type": "name"}, {"api_name": "client.third.whole", "line_number": 75, "usage_type": "call"}, {"api_name": "client.third", "line_number": 75, "usage_type": "name"}, {"api_name": "client.reply.reply", "line_number": 76, "usage_type": "call"}, {"api_name": "client.reply", "line_number": 76, "usage_type": "name"}]} +{"seq_id": "12537778261", "text": "from timm.models.xcit import XCiT\n\nfrom ._check import check_encoder\n\nERROR_NOT_XCIT = \"Expected encoder to be XCiT model, got {}.\"\nERROR_DECAY = \"Learning rate decay should be in range (0, 1], got {}.\"\nNO_DECAY = 1.0\nLR_SCALE_INDEX_ZERO = (\"cls_token\", \"patch_embed\", \"pos_embed\")\n\n\ndef freeze_encoder(\n encoder: XCiT,\n num_liquid: int = 0,\n *,\n freeze_cls_token: bool = True,\n freeze_patch_embed: bool = True,\n freeze_pos_embed: bool = True,\n freeze_layer_norm: bool = True,\n freeze_last_mlp_layer: bool = False,\n) -> None:\n \"\"\"Freeze XCiT encoder parameters.\n\n Args:\n encoder: XCiT encoder model.\n num_liquid: Number of liquid attention blocks. Defaults to 0.\n freeze_cls_token: Freeze cls_token parameters. Defaults to True.\n freeze_patch_embed: Freeze patch_embed parameters. Defaults to True.\n freeze_pos_embed: Freeze pos_embed parameters. Defaults to True.\n freeze_layer_norm: Freeze layer_norm parameters. Defaults to True.\n freeze_last_mlp_layer: Freeze the last mlp-layer in the last cls attention\n block. Defaults to False.\n\n Raises:\n TypeError: Encoder model is not `XCiT`.\n \"\"\"\n encoder = check_encoder(encoder)\n # Calculate number of blocks.\n num_cls_blocks = len(encoder.cls_attn_blocks)\n num_liquid_cls_blocks = min(num_cls_blocks, num_liquid)\n num_blocks = len(encoder.blocks)\n num_liquid_blocks = max(0, num_liquid - num_liquid_cls_blocks)\n # Check if we're not freezing anything.\n if num_blocks + num_cls_blocks <= num_liquid:\n return\n # Define liquid block indices.\n liquid_cls_block_idx = list(reversed(range(num_cls_blocks)))[:num_liquid_cls_blocks]\n liquid_block_idx = list(reversed(range(num_blocks)))[:num_liquid_blocks]\n # Freeze encoder layers.\n for name, param in encoder.named_parameters():\n if name.startswith(\"cls_attn_blocks\"):\n block_idx = int(name.split(\".\")[1])\n if block_idx in liquid_cls_block_idx or (\n not freeze_last_mlp_layer\n and block_idx == num_cls_blocks - 1\n and \"mlp\" in name\n ):\n param.requires_grad = True\n else:\n param.requires_grad = False\n elif name.startswith(\"blocks\"):\n block_idx = int(name.split(\".\")[1])\n if block_idx in liquid_block_idx:\n param.requires_grad = True\n else:\n param.requires_grad = False\n elif (\n name.startswith(\"head\") # Head is always liquid\n or (not freeze_cls_token and name.startswith(\"cls_token\"))\n or (not freeze_patch_embed and name.startswith(\"patch_embed\"))\n or (not freeze_pos_embed and name.startswith(\"pos_embed\"))\n or (not freeze_layer_norm and name.startswith(\"norm\"))\n ):\n param.requires_grad = True\n else:\n param.requires_grad = False\n", "repo_name": "jopo666/HistoEncoder", "sub_path": "histoencoder/functional/_freeze.py", "file_name": "_freeze.py", "file_ext": "py", "file_size_in_byte": 2970, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 20, "dataset": "github-code", "pt": "20", "api": [{"api_name": "timm.models.xcit.XCiT", "line_number": 12, "usage_type": "name"}, {"api_name": "_check.check_encoder", "line_number": 36, "usage_type": "call"}]} +{"seq_id": "30227842336", "text": "# -- code: utf-8 --\nfrom __future__ import absolute_import\n\nfrom django.test import TestCase\nfrom django.test.client import Client\nfrom django.test.client import RequestFactory\nfrom django.test.utils import override_settings\nfrom django.contrib.auth.models import User, AnonymousUser\nfrom django.contrib.auth import authenticate\nfrom django.core.urlresolvers import reverse\nfrom django.conf import settings\n\nfrom .models import X509UserMapping\nfrom .auth_backend import is_X509_authenticated\n\n\nclass X509UserMappingTest(TestCase):\n\n def setUp(self):\n self.user = User.objects.create(username=\"test\", password=\"test\")\n self.notuser = User.objects.create(username=\"nottest\")\n self.dn = \"AwesomeDN\"\n self.mapping = X509UserMapping.objects.create(\n user=self.user,\n cert_dn=self.dn)\n self.notmapping = X509UserMapping.objects.create(\n user=self.notuser,\n cert_dn='not'+self.dn)\n self.c = Client()\n\n def test_programmatic_auth(self):\n \"\"\"\n Test programmatic authentication. Exercises the authentication\n backend directly.\n \"\"\"\n\n user = authenticate(dn=self.dn, verified='SUCCESS')\n self.assertEqual(user, self.user)\n\n def test_programmatic_bad_auth(self):\n \"\"\"\n Test programmatic authentication. Exercises the authentication\n backend directly. Should be None.\n \"\"\"\n\n user = authenticate(dn=self.dn)\n self.assertEqual(user, None)\n\n def test_no_auth_views(self):\n \"\"\"\n Test going to a location that requires authentication.\n \"\"\"\n\n # @login_required, so 302 (not logged in)\n response = self.c.get(reverse('x509_auth_list'),\n HTTP_X_SSL_USER_DN=self.dn,\n HTTP_X_SSL_AUTHENTICATED='SUCCESS')\n self.assertEqual(response.status_code, 302)\n\n def test_auth_baddn_views(self):\n \"\"\"\n Test sending an unmapped X.509 Subject (DN).\n \"\"\"\n\n self.c.get(reverse('x509_auth_auth'),\n {'next': reverse('x509_auth_list')},\n HTTP_X_SSL_USER_DN=self.dn+'X',\n HTTP_X_SSL_AUTHENTICATED='SUCCESS',\n follow=True)\n\n # @login_required, so 302 (not logged in)\n response = self.c.get(reverse('x509_auth_list'),\n HTTP_X_SSL_USER_DN=self.dn+'X',\n HTTP_X_SSL_AUTHENTICATED='SUCCESS')\n self.assertEqual(response.status_code, 302)\n\n def test_auth_invalid_ssl_views(self):\n \"\"\"\n Test sending an invalid cert (even if the Subject is good).\n \"\"\"\n\n self.c.get(reverse('x509_auth_auth'),\n {'next': reverse('x509_auth_list')},\n HTTP_X_SSL_USER_DN=self.dn,\n HTTP_X_SSL_AUTHENTICATED='ANYTHING_NOT_SUCCESS',\n follow=True)\n\n # @login_required, so 302 (not logged in)\n response = self.c.get(reverse('x509_auth_list'),\n HTTP_X_SSL_USER_DN=self.dn,\n HTTP_X_SSL_AUTHENTICATED='ANYTHING_NOT_SUCCESS')\n self.assertEqual(response.status_code, 302)\n\n def test_auth_success_views(self):\n \"\"\"\n Test actually working.\n \"\"\"\n\n response = self.c.get(reverse('x509_auth_auth'),\n {'next': reverse('x509_auth_list')},\n HTTP_X_SSL_USER_DN=self.dn,\n HTTP_X_SSL_AUTHENTICATED='SUCCESS')\n self.assertEqual(response.status_code, 302)\n self.assertEqual(response.url.endswith(reverse('x509_auth_list')),\n True)\n\n # If logged in, will be 200\n response = self.c.get(reverse('x509_auth_list'),\n HTTP_X_SSL_USER_DN=self.dn,\n HTTP_X_SSL_AUTHENTICATED='SUCCESS')\n self.assertEqual(response.status_code, 200)\n self.assertNotIn('You are using this new certificate:',\n response.content)\n\n def test_auth_success_views_no_next(self):\n \"\"\"\n Test actually working, but with out next parameter.\n \"\"\"\n\n response = self.c.get(reverse('x509_auth_auth'),\n HTTP_X_SSL_USER_DN=self.dn,\n HTTP_X_SSL_AUTHENTICATED='SUCCESS')\n self.assertEqual(response.status_code, 302)\n self.assertEqual(response.url.endswith(reverse('x509_auth_list')),\n False)\n\n # If logged in, will be 200\n response = self.c.get(reverse('x509_auth_list'),\n HTTP_X_SSL_USER_DN=self.dn,\n HTTP_X_SSL_AUTHENTICATED='SUCCESS')\n self.assertEqual(response.status_code, 200)\n\n def test_auth_views_missing_header(self):\n \"\"\"\n Test trying to auth while missing a header.\n \"\"\"\n\n # Unsuccessful login will NOT redirect, ergo, 200\n response = self.c.get(reverse('x509_auth_auth'),\n {'next': reverse('x509_auth_list')},\n HTTP_X_SSL_AUTHENTICATED='SUCCESS')\n self.assertEqual(response.status_code, 200)\n\n def test_list_view_new_cert(self):\n \"\"\"\n Test actually working, but then send new cert (prompts to add).\n \"\"\"\n\n self.test_auth_success_views()\n\n # If logged in, will be 200\n response = self.c.get(reverse('x509_auth_list'),\n HTTP_X_SSL_USER_DN=self.dn+'X',\n HTTP_X_SSL_AUTHENTICATED='SUCCESS')\n self.assertEqual(response.status_code, 200)\n self.assertIn('You are using this new certificate:', response.content)\n\n def test_delete_mapping(self):\n \"\"\"\n Test deleting a mapping.\n \"\"\"\n\n self.test_auth_success_views()\n response = self.c.get(reverse('x509_auth_delete', kwargs={'pk': 1}),\n HTTP_X_SSL_USER_DN=self.dn,\n HTTP_X_SSL_AUTHENTICATED='SUCCESS')\n self.assertEqual(response.status_code, 200)\n self.assertIn(\n 'Are you sure you want to delete \"{0}\"'.format(str(self.mapping)),\n response.content)\n\n def test_delete_mapping_not_you(self):\n \"\"\"\n Test deleting a mapping of another users.\n \"\"\"\n\n self.test_auth_success_views()\n response = self.c.get(reverse('x509_auth_delete', kwargs={'pk': 2}),\n HTTP_X_SSL_USER_DN=self.dn,\n HTTP_X_SSL_AUTHENTICATED='SUCCESS')\n self.assertEqual(response.status_code, 404)\n self.assertNotIn(\n 'Are you sure you want to delete',\n response.content)\n\n def test_create_form_bad(self):\n \"\"\"\n Test posting to the create form, bad input.\n \"\"\"\n\n self.test_auth_success_views()\n response = self.c.post(reverse('x509_auth_map'),\n {'NOTcert_dn': 'OtherCern'})\n self.assertEqual(response.status_code, 200)\n self.assertIn('This field is required.', response.content)\n\n def test_create_form_non_unique(self):\n \"\"\"\n Test posting to the create form, but with non-unique DN.\n \"\"\"\n\n self.test_auth_success_views()\n response = self.c.post(reverse('x509_auth_map'),\n {'cert_dn': self.mapping.cert_dn})\n self.assertEqual(response.status_code, 200)\n self.assertIn('X509 user mapping with this Cert dn already exists.',\n response.content)\n\n def test_create_form_good(self):\n \"\"\"\n Test posting to the create form, good input.\n \"\"\"\n\n self.test_auth_success_views()\n response = self.c.post(reverse('x509_auth_map'),\n {'cert_dn': 'OtherCern'})\n self.assertEqual(response.status_code, 302)\n\n def test_is_auth_backend(self):\n \"\"\"\n Test our decorator function and auth test utility function.\n \"\"\"\n factory = RequestFactory()\n request = factory.get('/x509/list')\n request.user = self.user\n self.assertEqual(request.user.is_authenticated, True)\n\n # Jam a session in here. Dictionaries are close enough to sessions.\n # Only your hair dresser knows for sure.\n request.session = {}\n request.session['_auth_user_backend'] = (\n 'x509_auth.auth_backend.AuthenticationBackend')\n\n self.assertEqual(is_X509_authenticated(request), True)\n\n def test_is_auth_backend_wrong_backend(self):\n \"\"\"\n Test our decorator function and auth test utility function, when\n someone is NOT using our backend.\n \"\"\"\n factory = RequestFactory()\n request = factory.get('/x509/list')\n request.user = self.user\n self.assertEqual(request.user.is_authenticated, True)\n\n # Jam a session in here. Dictionaries are close enough to sessions.\n # Only your hair dresser knows for sure.\n request.session = {}\n request.session['_auth_user_backend'] = 'some.other.Backend'\n\n self.assertEqual(is_X509_authenticated(request), False)\n\n def test_is_auth_backend_unauthed(self):\n \"\"\"\n Test our decorator function and auth test utility function when someone\n is not logged in.\n \"\"\"\n factory = RequestFactory()\n request = factory.get('/x509/list')\n request.user = AnonymousUser()\n\n self.assertEqual(request.user.is_authenticated, False)\n\n self.assertEqual(is_X509_authenticated(request), False)\n\n def test_is_auth_backend_key_error(self):\n \"\"\"\n Test our decorator function and auth test utility function. Don't\n include the required session key. This should never happen.\n \"\"\"\n factory = RequestFactory()\n request = factory.get('/x509/list')\n request.user = self.user\n self.assertEqual(request.user.is_authenticated, True)\n\n # Jam a session in here. Dictionaries are close enough to sessions.\n # Only your hair dresser knows for sure.\n request.session = {}\n self.assertEqual(is_X509_authenticated(request), False)\n\n def test_auth_success_template_tag(self):\n \"\"\"\n Test template tag.\n \"\"\"\n\n self.test_auth_success_views()\n response = self.c.get(reverse('x509_auth_map'))\n self.assertIn(\"TEST: True\", response.content)\n\n # sans django.core.context_processors.request\n @override_settings(TEMPLATES=settings.BAD_TEMPLATES_SETTING)\n def test_auth_fail_template_tag(self):\n \"\"\"\n Test template tag, but with out the needed context processor.\n \"\"\"\n\n self.test_auth_success_views()\n response = self.c.get(reverse('x509_auth_map'))\n self.assertIn(\"TEST: False\", response.content)\n", "repo_name": "nimbis/django-x509-auth", "sub_path": "x509_auth/tests.py", "file_name": "tests.py", "file_ext": "py", "file_size_in_byte": 10992, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "django.test.TestCase", "line_number": 17, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.create", "line_number": 20, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 20, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 20, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.create", "line_number": 21, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 21, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 21, "usage_type": "name"}, {"api_name": "models.X509UserMapping.objects.create", "line_number": 23, "usage_type": "call"}, {"api_name": "models.X509UserMapping.objects", "line_number": 23, "usage_type": "attribute"}, {"api_name": "models.X509UserMapping", "line_number": 23, "usage_type": "name"}, {"api_name": "models.X509UserMapping.objects.create", "line_number": 26, "usage_type": "call"}, {"api_name": "models.X509UserMapping.objects", "line_number": 26, "usage_type": "attribute"}, {"api_name": "models.X509UserMapping", "line_number": 26, "usage_type": "name"}, {"api_name": "django.test.client.Client", "line_number": 29, "usage_type": "call"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 37, "usage_type": "call"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 46, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 55, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 65, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 66, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 72, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 82, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 83, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 89, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 99, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 100, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 104, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 108, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 120, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 124, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 128, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 139, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 140, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 152, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 164, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 178, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 192, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 203, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 215, "usage_type": "call"}, {"api_name": "django.test.client.RequestFactory", "line_number": 223, "usage_type": "call"}, {"api_name": "auth_backend.is_X509_authenticated", "line_number": 234, "usage_type": "call"}, {"api_name": "django.test.client.RequestFactory", "line_number": 241, "usage_type": "call"}, {"api_name": "auth_backend.is_X509_authenticated", "line_number": 251, "usage_type": "call"}, {"api_name": "django.test.client.RequestFactory", "line_number": 258, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.AnonymousUser", "line_number": 260, "usage_type": "call"}, {"api_name": "auth_backend.is_X509_authenticated", "line_number": 264, "usage_type": "call"}, {"api_name": "django.test.client.RequestFactory", "line_number": 271, "usage_type": "call"}, {"api_name": "auth_backend.is_X509_authenticated", "line_number": 279, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 287, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.reverse", "line_number": 298, "usage_type": "call"}, {"api_name": "django.test.utils.override_settings", "line_number": 291, "usage_type": "call"}, {"api_name": "django.conf.settings.BAD_TEMPLATES_SETTING", "line_number": 291, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 291, "usage_type": "name"}]} +{"seq_id": "6469584979", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Project : ADER\n# @File : util.py\n\nfrom typing import Union, Iterable, Tuple\nimport tensorflow.compat.v1 as tf\nimport random\nimport os\nimport numpy as np\nimport math\nfrom collections import defaultdict\nfrom tqdm import tqdm\nfrom ADER import Ader\n\n\nclass DataLoader:\n \"\"\" DataLoader object to load train, valid and test data from dataset.\n Args:\n dataset (str): Name of the dataset.\n \"\"\"\n\n def __init__(self,\n dataset: str,\n ) -> None:\n\n self.item_set = set()\n self.path = os.path.join('..', '..', 'data', dataset)\n # remove item in testing data that not appeared in training data\n self.is_remove_item = True\n\n def train_loader(self,\n period: int\n ) -> (list, str):\n \"\"\" Load train data of specific period.\n Args:\n period (int): The period which load training data from.\n Returns:\n sessions (list): Training item sequences (session) of selected periods.\n info (str): Information of training data.\n \"\"\"\n Sessions = defaultdict(list)\n file_name = '/period_%d.txt' % period\n with open(self.path + file_name, 'r') as f:\n for line in f:\n sessId, itemId = line.rstrip().split(' ')\n sessId = int(sessId)\n itemId = int(itemId)\n self.item_set.add(itemId)\n Sessions[sessId].append(itemId)\n\n sessions = list(Sessions.values())\n del Sessions\n info = 'Train set information: total number of action: %d.' \\\n % sum(list(map(lambda session: len(session), sessions)))\n print(info)\n\n return sessions, info\n\n def evaluate_loader(self,\n period: int,\n ) -> (list, str):\n \"\"\" This method loads test data of specific period.\n Args:\n period (int): The period which load testing data from.\n Returns:\n sessions (list): Testing item sequences (session) of selected periods.\n info (str): Information of testing data.\n \"\"\"\n Sessions = defaultdict(list)\n removed_num = 0\n total_num = 0\n file_name = '/period_%d.txt' % period\n with open(self.path + file_name, 'r') as f:\n for line in f:\n total_num += 1\n sessId, itemId = line.rstrip().split(' ')\n sessId = int(sessId)\n itemId = int(itemId)\n # remove new items in test or validation set that not appear in train set\n if self.is_remove_item and (itemId not in self.item_set):\n removed_num += 1\n continue\n else:\n self.item_set.add(itemId)\n Sessions[sessId].append(itemId)\n\n if self.is_remove_item:\n delete_keys = []\n for sessId in Sessions:\n if len(Sessions[sessId]) == 1:\n removed_num += 1\n delete_keys.append(sessId)\n for delete_key in delete_keys:\n del Sessions[delete_key]\n\n info = 'Test set information: original total number of action: %d, removed number of action: %d.' \\\n % (total_num, removed_num)\n sessions = list(Sessions.values())\n del Sessions\n\n return sessions, info\n\n def max_item(self) -> int:\n \"\"\" This method returns the number of accumulative items until current cycle training data.\n \"\"\"\n return max(self.item_set)\n\n\nclass Sampler:\n \"\"\" This object samples data and generates positive labels for train, valid and test data,\n as well as negative sample for training data.\n Args:\n data (list): Original data needs to be sampled.\n maxlen (int): The input length of each sequence for the model.\n batch_size (int): The number of data in one batch.\n is_subseq (bool): If True, the given data is sub-sequence. If False, the given data is full\n original data.\n \"\"\"\n\n def __init__(self,\n data: list,\n maxlen: int,\n batch_size: int,\n is_subseq: bool = False\n ) -> None:\n\n self.maxlen = maxlen\n self.batch_size = batch_size\n\n self.dataset_size = 0\n self.batch_counter = 0\n self.data_indices = []\n self.logits = []\n\n self.prepared_data = []\n if not is_subseq:\n for session in data:\n self.prepared_data.append(session)\n length = len(session)\n if length > 2:\n for t in range(1, length - 1):\n self.prepared_data.append(session[:-t])\n else:\n for session in data:\n self.prepared_data.append(session)\n\n self.data_indices = list(range(len(self.prepared_data)))\n random.shuffle(self.data_indices)\n\n def label_generator(self,\n session: list,\n ) -> (list, int):\n \"\"\" This method split sessions into input sequence and labels.\n Args:\n session (list): Original sub-sequence of different length.\n Return:\n seq (list): The input sequence with fixed length set by maxlen.\n pos (int): Label (item number).\n \"\"\"\n seq = np.zeros([self.maxlen], dtype=np.int32)\n pos = np.array(session[-1], dtype=np.int32)\n idx = self.maxlen - 1\n\n for itemId in reversed(session[:-1]):\n seq[idx] = itemId\n idx -= 1\n if idx == -1:\n break\n\n return seq, pos\n\n def add_exemplar(self,\n exemplar: list\n ) -> None:\n \"\"\" Add exemplar data and logits from previous cycle model\n Args:\n exemplar (list): Exemplar data and corresponding logits.\n \"\"\"\n self.logits = []\n for session, logits in exemplar:\n self.prepared_data.append(session)\n self.logits.append(logits)\n\n self.data_indices = list(range(len(self.prepared_data)))\n random.shuffle(self.data_indices)\n\n def split_data(self,\n valid_portion: float,\n return_train: bool = False\n ) -> Union[list, tuple]:\n \"\"\" Split data into valid and train dataset and remove validation data from original training data.\n Args:\n valid_portion (float): The portion of validation dataset w.r.t entire dataset.\n return_train: If True, return validation data and train data, else only return validation data.\n Returns:\n valid_data (list): Validation sub-sequence.\n train_data (list): Training sub-sequence.\n \"\"\"\n\n data_size = len(self.prepared_data)\n sidx = np.arange(data_size, dtype='int32')\n np.random.shuffle(sidx)\n\n n_train = int(np.round(data_size * (1. - valid_portion)))\n valid_data = [self.prepared_data[s] for s in sidx[n_train:]]\n train_data = [self.prepared_data[s] for s in sidx[:n_train]]\n self.prepared_data = train_data\n\n self.data_indices = list(range(len(self.prepared_data)))\n random.shuffle(self.data_indices)\n\n if return_train:\n return valid_data, train_data\n else:\n return valid_data\n\n def sampler(self) -> Union[Iterable[Tuple[list, int]]]:\n \"\"\" This method returns a batch of sample: N * (sequence, label).\n Returns:\n one_batch (list): One batch of data in the size of N * (sequence length, 1).\n \"\"\"\n one_batch = []\n for i in range(self.batch_size):\n if (i + self.batch_counter * self.batch_size) < len(self.prepared_data):\n index = self.data_indices[i + self.batch_counter * self.batch_size]\n session = self.prepared_data[index]\n if len(session) <= 1:\n continue\n one_batch.append(self.label_generator(session))\n else:\n break\n\n self.batch_counter += 1\n if self.batch_counter == self.batch_num():\n self.batch_counter = 0\n random.shuffle(self.data_indices)\n\n return zip(*one_batch)\n\n def exemplar_sampler(self) -> Iterable[Tuple[list, int, list]]:\n \"\"\" This method returns a batch of exemplar data: N * (exemplar, logits).\n Return:\n one_batch (list): One batch of data in the size of N * (sequence length, previous item number).\n \"\"\"\n one_batch = []\n for i in range(self.batch_size):\n if (i + self.batch_counter * self.batch_size) < len(self.prepared_data):\n index = self.data_indices[i + self.batch_counter * self.batch_size]\n session = self.prepared_data[index]\n if len(session) <= 1:\n continue\n seq, pos = self.label_generator(session)\n one_batch.append((seq, pos, self.logits[index]))\n else:\n break\n\n self.batch_counter += 1\n if self.batch_counter == self.batch_num():\n self.batch_counter = 0\n random.shuffle(self.data_indices)\n\n return zip(*one_batch)\n\n def data_size(self) -> int:\n \"\"\" Returns the number of sub-sequences in the data set.\n \"\"\"\n return len(self.prepared_data)\n\n def batch_num(self) -> int:\n \"\"\" Returns the number of batches according to dataset size and batch size.\n \"\"\"\n return math.ceil(len(self.prepared_data) * 1.0 / self.batch_size)\n\n\nclass Evaluator:\n \"\"\" This object evaluates performance on valid or test data.\n Args:\n data (list): Data to evaluate, valid data or test data.\n is_subseq (bool): If true, the data to evaluate is sub-sequence, else is full sequence.\n maxlen (int): The input length of each sequence for the model.\n batch_size (int): Batch size for test.\n max_item (int): The number of accumulative items until current cycle.\n mode (str): ['valid', 'test'] for display.\n model (Ader): Trained model for evaluate.\n sess (tf.Session): Tensorflow session.\n \"\"\"\n\n def __init__(self,\n data: list,\n is_subseq: bool,\n maxlen: int,\n batch_size: int,\n max_item: int,\n mode: str,\n model: Union[Ader],\n sess: tf.Session\n ) -> None:\n\n self.max_item = max_item\n self.model = model\n self.sess = sess\n\n self.ranks = []\n self.mode = mode\n self.desc = 'Validating epoch ' if mode == 'valid' else 'Testing epoch '\n self.evaluate_sampler = Sampler(data, maxlen, batch_size, is_subseq=is_subseq)\n\n def evaluate(self,\n epoch: int\n ) -> str:\n \"\"\" This method evaluates performance of predicted last item among all existing item.\n Args:\n epoch (int): Current epoch number for display.\n Returns:\n (str): Evaluation results information.\n \"\"\"\n self.ranks = []\n batch_num = self.evaluate_sampler.batch_num()\n for _ in tqdm(range(batch_num), total=batch_num, ncols=70, leave=False, unit='b',\n desc=self.desc + str(epoch)):\n seq, pos = self.evaluate_sampler.sampler()\n predictions = self.model.predict(self.sess, seq, list(range(1, self.max_item + 1)))\n ground_truth = pos\n rank = [pred[index - 1] for pred, index in zip(predictions, ground_truth)]\n self.ranks.extend(rank)\n return self.display(epoch)\n\n def results(self) -> (float, float, float, float):\n \"\"\" This method returns evaluation results (MRR@20, RECALL@20, MRR@10, RECALL@10).\n \"\"\"\n valid_user = len(self.ranks)\n valid_ranks_20 = list(filter(lambda x: x < 20, self.ranks))\n valid_ranks_10 = list(filter(lambda x: x < 10, self.ranks))\n RECALL_20 = len(valid_ranks_20)\n MRR_20 = sum(map(lambda x: 1.0 / (x + 1), valid_ranks_20))\n RECALL_10 = len(valid_ranks_10)\n MRR_10 = sum(map(lambda x: 1.0 / (x + 1), valid_ranks_10))\n return MRR_20 / valid_user, RECALL_20 / valid_user, MRR_10 / valid_user, RECALL_10 / valid_user\n\n def display(self, epoch) -> str:\n \"\"\" This method display and save evaluation metrics (MRR@20, RECALL@20, MRR@10, RECALL@10).\n Returns:\n info (str): Evaluation results information.\n \"\"\"\n results = self.results()\n info = 'epoch:%d, %s (MRR@20: %.4f, RECALL@20: %.4f, MRR@10: %.4f, RECALL@10: %.4f)' \\\n % (epoch, self.mode, results[0], results[1], results[2], results[3])\n print(info)\n return info\n\n\nclass ExemplarGenerator:\n \"\"\" This object select exemplars from given data.\n Args:\n data (list): Training data and valid data at current cycle and exemplar data from previous cycle\n in the from of sub-sequence.\n exemplar size (int): The number of exemplars saved for each cycle.\n disable_m (bool): If true, save the same number of exemplars for each item.\n batch_size (int): Batch size to select exemplars.\n maxlen (int): The number of accumulative items until current cycle.\n dropout_rate (float): Dropout rate in trained model.\n max_item (int): The number of accumulative items until current cycle.\n \"\"\"\n\n def __init__(self,\n data: list,\n exemplar_size: int,\n disable_m: bool,\n batch_size: int,\n maxlen: int,\n dropout_rate: float,\n max_item: int,\n ) -> None:\n\n self.exemplars = defaultdict(list)\n self.m = exemplar_size\n self.max_item = max_item\n self.item_count = np.zeros(max_item)\n self.dropout_rate = dropout_rate\n\n self.sess_by_item = defaultdict(list)\n exemplar_sampler = Sampler(data, maxlen, batch_size, is_subseq=True)\n batch_num = exemplar_sampler.batch_num()\n\n for _ in tqdm(range(batch_num), total=batch_num, ncols=70, leave=False, unit='b',\n desc='Sorting exemplars'):\n seq, pos = exemplar_sampler.sampler()\n pos = np.array(pos)\n for s, item in zip(seq, pos):\n session = np.append(s, item)\n self.sess_by_item[item].append(session)\n self.item_count[item - 1] += 1\n\n if disable_m:\n self.item_count = np.ones_like(self.item_count)\n item_prob = self.item_count / self.item_count.sum()\n item_count = np.random.multinomial(n=self.m, pvals=item_prob, size=1)[0]\n self.item_count = np.int32(item_count)\n\n def herding(self,\n rep: np.ndarray,\n logits: np.ndarray,\n seq: np.ndarray,\n item: int,\n m: int\n ) -> int:\n \"\"\" Herding algorithm for exemplar selection.\n Args:\n rep (numpy.ndarray): Calculated representations by trained model.\n logits (numpy.ndarray): Calculated logits by trained model.\n seq (numpy.ndarray): Input sessions.\n item (int): The index of item (lable) which the function selects exemplars for.\n m (int): The number of exemplar per label\n Returns:\n counter (int): The number of exemplars saved for the given item or label.\n \"\"\"\n # Initialize mean and selected ids\n D = rep.T / np.linalg.norm(rep.T, axis=0)\n mu = D.mean(axis=1)\n w_t = mu\n step_t = 0\n selected_ids = []\n counter = 0\n while not (len(selected_ids) == m) and step_t < 1.1 * m:\n tmp_t = np.dot(w_t, D)\n ind_max = np.argmax(tmp_t)\n w_t = w_t + mu - D[:, ind_max]\n step_t += 1\n if ind_max not in selected_ids:\n selected_ids.append(ind_max)\n counter += 1\n self.exemplars[item] = [[seq[i][seq[i] != 0].tolist(), logits[i].tolist()] for i in selected_ids]\n return counter\n\n def herding_selection(self,\n sess: tf.Session,\n model: Union[Ader]):\n \"\"\" This method selects exemplars using herding and selects exemplars.\n Args:\n sess (tf.Session): Tensorflow session.\n model (object): Trained model for evaluate.\n Returns:\n saved_num (int): Total number of exemplars saved for all items at current cycle.\n \"\"\"\n saved_num = 0\n for item in tqdm(self.sess_by_item, ncols=70, leave=False, unit='b', desc='Selecting exemplar'):\n m = self.item_count[item - 1]\n seq = self.sess_by_item[item]\n seq = np.array(seq)\n input_seq = seq[:, :-1]\n rep, logits = sess.run([model.rep, model.logits], {model.input_seq: input_seq,\n model.dropout_rate: self.dropout_rate,\n model.max_item: self.max_item,\n model.is_training: False})\n rep = np.array(rep)\n logits = np.array(logits)\n saved = self.herding(rep, logits, seq, item, min(m, len(seq)))\n saved_num += saved\n\n return saved_num\n\n def loss_selection(self,\n sess: tf.Session,\n model: Union[Ader]\n ) -> int:\n \"\"\" This method selects exemplars by ranking loss.\n Args:\n sess (tf.Session): Tensorflow session.\n model (object): Trained model for evaluate.\n Returns:\n saved_num (int): Total number of exemplars saved for all items at current cycle.\n \"\"\"\n saved_num = 0\n for item in tqdm(self.sess_by_item, ncols=70, leave=False, unit='b', desc='Selecting exemplar'):\n m = self.item_count[item - 1]\n if m < 0.5:\n continue\n seq = self.sess_by_item[item]\n seq_num = len(seq)\n seq = np.array(seq)\n loss, logits = sess.run([model.loss, model.logits], {model.input_seq: seq[:, :-1],\n model.pos: seq[:, -1],\n model.dropout_rate: self.dropout_rate,\n model.max_item: self.max_item,\n model.is_training: False})\n loss = np.array(loss)\n logits = np.array(logits)\n selected_ids = loss.argsort()[:int(min(m, seq_num))]\n self.exemplars[item] = [[seq[i][seq[i] != 0].tolist(), logits[i].tolist()] for i in selected_ids]\n saved_num += len(selected_ids)\n return saved_num\n\n def randomly_selection(self,\n sess: tf.Session,\n model: Union[Ader]\n ) -> int:\n \"\"\" This method randomly selects exemplars.\n Args:\n sess (tf.Session): Tensorflow session.\n model (object): Trained model for evaluate.\n Returns:\n saved_num (int): Total number of exemplars saved for all items at current cycle.\n \"\"\"\n saved_num = 0\n for item in tqdm(self.sess_by_item, ncols=70, leave=False, unit='b', desc='Selecting exemplar'):\n seq = self.sess_by_item[item]\n seq = np.array(seq)\n seq_num = len(seq)\n m = self.item_count[item - 1]\n if m > 0:\n selected_ids = np.random.choice(seq_num, min(m, seq_num), replace=False)\n selected_seq = seq[selected_ids]\n logits = sess.run(model.logits, {model.input_seq: selected_seq[:, :-1],\n model.dropout_rate: self.dropout_rate,\n model.max_item: self.max_item,\n model.is_training: False})\n logits = np.array(logits)\n for s, l in zip(selected_seq, logits):\n self.exemplars[item].append([s[s != 0].tolist(), l.tolist()])\n saved_num += 1\n return saved_num\n", "repo_name": "doublemul/ADER", "sub_path": "util.py", "file_name": "util.py", "file_ext": "py", "file_size_in_byte": 21053, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 31, "dataset": "github-code", "pt": "20", "api": [{"api_name": "os.path.join", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 42, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 70, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 161, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 161, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 162, "usage_type": "attribute"}, {"api_name": "random.shuffle", "line_number": 186, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.random.shuffle", "line_number": 203, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 203, "usage_type": "attribute"}, {"api_name": "numpy.round", "line_number": 205, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 211, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 191, "usage_type": "name"}, {"api_name": "random.shuffle", "line_number": 237, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 218, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 218, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 218, "usage_type": "name"}, {"api_name": "random.shuffle", "line_number": 261, "usage_type": "call"}, {"api_name": "typing.Iterable", "line_number": 241, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 241, "usage_type": "name"}, {"api_name": "math.ceil", "line_number": 273, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 296, "usage_type": "name"}, {"api_name": "ADER.Ader", "line_number": 296, "usage_type": "name"}, {"api_name": "tensorflow.compat.v1.Session", "line_number": 297, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v1", "line_number": 297, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 320, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 376, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 379, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 382, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 386, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 389, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 391, "usage_type": "call"}, {"api_name": "numpy.ones_like", "line_number": 396, "usage_type": "call"}, {"api_name": "numpy.random.multinomial", "line_number": 398, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 398, "usage_type": "attribute"}, {"api_name": "numpy.int32", "line_number": 399, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 402, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 403, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 404, "usage_type": "attribute"}, {"api_name": "numpy.linalg.norm", "line_number": 419, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 419, "usage_type": "attribute"}, {"api_name": "numpy.dot", "line_number": 426, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 427, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1.Session", "line_number": 437, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v1", "line_number": 437, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 438, "usage_type": "name"}, {"api_name": "ADER.Ader", "line_number": 438, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 447, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 450, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 456, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 457, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1.Session", "line_number": 464, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v1", "line_number": 464, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 465, "usage_type": "name"}, {"api_name": "ADER.Ader", "line_number": 465, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 475, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 481, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 487, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 488, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1.Session", "line_number": 495, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v1", "line_number": 495, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 496, "usage_type": "name"}, {"api_name": "ADER.Ader", "line_number": 496, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 506, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 508, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 512, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 512, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 518, "usage_type": "call"}]} +{"seq_id": "5310267426", "text": "import os\nimport sys\nimport json\nimport re\nimport importlib\n\n#region\n# import re\n\n\"\"\"\ndescrib: match nest regex\nexample: \nmatch_nest(\"123(((())))456\", '(', ')') return 2, (3, 11)\nmatch_nest(\"(()\", '(', ')') return 1, (0, 1)\nmatch_nest(\"))\", '(', ')') return 0, None\n\nsp: 为了配合 noting,对较标准的 match_nest 做了一些对应的修改\n\"\"\"\ndef sp_match_nest(pattern_beg, pattern_end, string, sp_pattern_beg=None):\n\tif(sp_pattern_beg==None):\n\t\tsp_pattern_beg = pattern_beg\n\t# match pattern_beg\n\tmatch = re.search(sp_pattern_beg, string)\n\tif(not match):\n\t\treturn 0, None\n\tpos_beg = match.start()\n\tpos_end = match.end()\n\t# match pattern_end\n\tpattern_beg_or_end = '(' + pattern_beg + ')|(' + pattern_end + ')'\n\tpos = pos_end\n\twhile(True):\n\t\tmatch = re.search(pattern_beg_or_end, string[pos:])\n\t\tif(match == None): # 意味着没有 end\n\t\t\tsign = 1\n\t\t\tbreak\n\t\ttemp = match.string[match.start():match.end()]\n\t\tif(re.match(pattern_beg, temp)): # 意味着遇到了嵌套结构\n\t\t\tnu, pos_temp = sp_match_nest(pattern_beg, pattern_end, string[pos:]) # nu 只是占位用\n\t\t\tpos += pos_temp[1]\n\t\telse: # 意味找到了 end\n\t\t\tassert re.match(pattern_end, temp)\n\t\t\tpos_end = pos + match.end()\n\t\t\tsign = 2\n\t\t\tbreak\n\treturn sign, (pos_beg, pos_end)\n\n\n\ndef printInColor(text, color):\n\tcolorDict = {\n\t\t'black'\t\t: '30',\n\t\t'red'\t\t: '31',\n\t\t'green'\t\t: '32',\n\t\t'yellow'\t: '33',\n\t\t'blue'\t\t: '34',\n\t\t'purple'\t: '35',\n\t\t'white'\t\t: '37',\n\t\t'default'\t: '38'\n\t}\n\tprint(\"\\033[\" + colorDict[color] + \"m\" + text + \"\\033[0m\")\n\ndef writeSecure(text, filepath, backupload=\"noting\\\\temp\\\\\"):\n\twith open(filepath, 'rb') as f:\n\t\tdata = f.read()\n\twith open(backupload + filepath.split('\\\\')[-1], 'wb') as f:\n\t\tf.write(data)\n\twith open(filepath, 'w', encoding='utf-8') as f:\n\t\tf.write(text)\n#endregion\n\nCOMMAND_DICT = \"noting\\\\modedict.json\"\n\nsp_pattern_beg = \"\\n #(.*) (!{1,2})(.*)\"\npattern_beg = \"\\n\"\nstring_end = \"\\n\"\n\n# get args of where you are when launch\nassert len(sys.argv) == 13\nargs = {\n\t\"workspaceFolder\"\t\t\t: sys.argv[1],\t#\t/home/your-username/your-project\n\t\"workspaceFolderBasename\"\t: sys.argv[2],\t#\tyour-project\n\t\"file\"\t\t\t\t\t\t: sys.argv[3],\t#\t/home/your-username/your-project/folder/file.ext\n\t\"fileWorkspaceFolder\"\t\t: sys.argv[4],\t#\t/home/your-username/your-project\n\t\"relativeFile\"\t\t\t\t: sys.argv[5],\t#\tfolder/file.ext\n\t\"relativeFileDirname\"\t\t: sys.argv[6],\t#\tfolder\n\t\"fileBasename\"\t\t\t\t: sys.argv[7],\t#\tfile.ext\n\t\"fileBasenameNoExtension\"\t: sys.argv[8],\t#\tfile\n\t\"fileDirname\"\t\t\t\t: sys.argv[9],\t#\t/home/your-username/your-project/folder\n\t\"fileExtname\"\t\t\t\t: sys.argv[10],\t#\t.ext\n\t\"lineNumber\"\t\t\t\t: int(sys.argv[11]),\n\t\"pathSeparator\"\t\t\t\t: sys.argv[12]\t#\t/ on macOS or linux, \\\\ on Windows\n}\n\n# get modedict from COMMAND_DICT\nwith open(COMMAND_DICT, 'r', encoding='utf-8') as f:\n\tmodedict = json.load(f)\n\n\ndef exec_block(block, sign=2):\n\tassert re.match(sp_pattern_beg, block)\n\t# get mode, command, iscontinued\n\tmatch = re.search(sp_pattern_beg, block)\n\tmode, iscontinued, command = match.groups()\n\tif(iscontinued=='!'):\n\t\tiscontinued = False\n\telse:\n\t\tassert iscontinued == '!!'\n\t\tiscontinued = True\n\t# get context\n\tcontext = block[match.end():-len(string_end)]\n\tif(context[0]=='\\n'):\n\t\tcontext = context[:-1]\n\t# get attributes\n\tattr = {}\n\tif(sign==2): # block 中有参数\n\t\tpos = match.end() + 1\n\t\tpattern_attr = \"^@([^\\n:]*):([^\\n]*)\\n\"\n\t\twhile(True):\n\t\t\tmatch = re.search(pattern_attr, block[pos:])\n\t\t\tif(match==None):\n\t\t\t\tbreak\n\t\t\tattr[match.groups()[0]] = match.groups()[1]\n\t\t\tpos += match.end()\n\t# traverse mode->command\n\tif(mode not in modedict.keys()):\n\t\ttext = 'Error: \"' + mode + '\" isnot a mode in modedict.json'\n\t\tprintInColor(text, \"red\")\n\t\texit(1)\n\tcmddict = modedict[mode]\n\tisrun = False\n\tfor key in cmddict.keys():\n\t\tif(re.match(key, command)):\n\t\t\tfile = cmddict[key][\"file\"]\n\t\t\tfunc_name = cmddict[key][\"func\"]\n\t\t\tlib = importlib.import_module(file)\n\t\t\tfunc = getattr(lib, func_name)\n\t\t\tcontext_new = func(command, context, attr)\n\t\t\tisrun = True\n\t\t\tbreak\n\tif(not isrun):\n\t\tif(\"default\" in cmddict.keys()):\n\t\t\tlib = importlib.import_module(cmddict[\"default\"][\"file\"])\n\t\t\tfunc = getattr(lib, cmddict[\"default\"][\"func\"])\n\t\t\tcontext_new = func(command, context, attr)\n\t\telse:\n\t\t\ttext = 'Error: \"' + command + '\" is not a command in \"' + mode + '\" mode'\n\t\t\tprintInColor(text, \"red\")\n\t\t\texit(1)\n\t# turn context into block\n\tblock_new = \"\\n #\" + mode + \" \"\n\tif(iscontinued):\n\t\tblock_new += '!!'\n\tblock_new += command\n\tfor key in attr.keys():\n\t\tblock_new += \"\\n@\" + key + \": \" + attr[key]\n\tblock_new += '\\n' + context_new + string_end\n\treturn block_new\n\n\nif(__name__==\"__main__\"):\n\twith open(\"main.md\", \"r\", encoding='utf-8') as f:\n\t\tdata_new = \"\"\n\t\tdata_old = f.read()\n\t\n\twhile(True):\n\t\tsign, pos = sp_match_nest(pattern_beg, string_end, data_old, sp_pattern_beg=sp_pattern_beg)\n\t\tif(sign==0): # 没有需要执行的命令了\n\t\t\tdata_new += data_old\n\t\t\tbreak\n\t\telse:\n\t\t\t# run exec_block\n\t\t\tblock_new = exec_block(data_old[pos[0]:pos[1]], sign=1)\n\t\t\t# 这里虽然 block 大部分还在 data_old 中,但开头的 '\\n' 给 data_new 了,开头的 block 也就不会再被匹配了\n\t\t\tdata_new += data_old[:pos[0]] + '\\n'\n\t\t\tdata_old = block_new[1:] + data_old[pos[1]:]\n\t\n\t# 修改 main.md,并打开到 line_current 行\n\twriteSecure(data_new, \"main.md\")\n\twith open(\"main.md\", 'w', encoding='utf-8') as f:\n\t\tf.write(data_new)\n\tos.system(\"code main.md\")\n", "repo_name": "ds6ga6/noting", "sub_path": "noting.py", "file_name": "noting.py", "file_ext": "py", "file_size_in_byte": 5420, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "re.search", "line_number": 23, "usage_type": "call"}, {"api_name": "re.search", "line_number": 32, "usage_type": "call"}, {"api_name": "re.match", "line_number": 37, "usage_type": "call"}, {"api_name": "re.match", "line_number": 41, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 78, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 80, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 81, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 82, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 83, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 84, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 85, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 86, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 87, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 88, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 89, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 90, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 91, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 96, "usage_type": "call"}, {"api_name": "re.match", "line_number": 100, "usage_type": "call"}, {"api_name": "re.search", "line_number": 102, "usage_type": "call"}, {"api_name": "re.search", "line_number": 119, "usage_type": "call"}, {"api_name": "re.match", "line_number": 132, "usage_type": "call"}, {"api_name": "importlib.import_module", "line_number": 135, "usage_type": "call"}, {"api_name": "importlib.import_module", "line_number": 142, "usage_type": "call"}, {"api_name": "os.system", "line_number": 181, "usage_type": "call"}]} +{"seq_id": "36140021262", "text": "import openpyxl as xl\r\nfrom openpyxl.chart import BarChart,Reference\r\ndef sheet_process(filename):\r\n wb=xl.load_workbook(filename)\r\n sheet=wb['Sheet1']\r\n cell1=sheet['a1']# alternative is\r\n cell=sheet.cell(1,1)\r\n cell2=sheet['b1']\r\n # cell=sheet.cell(1,1)\r\n print(cell1.value+\"\\t\"+cell2.value)\r\n print(sheet.max_row)#---Prints max no of rows in excel sheet\r\n cell3=sheet.cell(1,4)\r\n cell3.value='Corrected Price'\r\n print(sheet.cell(1,4).value)\r\n for row in range(2,sheet.max_row+1):\r\n cell=sheet.cell(row,3)\r\n print(cell.value)\r\n corrected_values=cell.value*0.9\r\n corrected_values_cells=sheet.cell(row,4)\r\n corrected_values_cells.value=corrected_values\r\n val=Reference(sheet,min_row=2,max_row=sheet.max_row,min_col=4,max_col=4)\r\n chart=BarChart()\r\n chart.add_data(val)\r\n sheet.add_chart(chart,'E2')\r\n wb.save(filename)\r\nsheet_process('transactions.xlsx')", "repo_name": "bhargavvummadi/ML", "sub_path": "xellig.py", "file_name": "xellig.py", "file_ext": "py", "file_size_in_byte": 940, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "openpyxl.load_workbook", "line_number": 4, "usage_type": "call"}, {"api_name": "openpyxl.chart.Reference", "line_number": 21, "usage_type": "call"}, {"api_name": "openpyxl.chart.BarChart", "line_number": 22, "usage_type": "call"}]} +{"seq_id": "1144552433", "text": "\"\"\"empty message\n\nRevision ID: c1197f8a206e\nRevises: ad8acfc66ca2\nCreate Date: 2021-04-04 16:14:57.821793\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c1197f8a206e'\ndown_revision = 'ad8acfc66ca2'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('batches', sa.Column('identifier_field', sa.String(length=10), nullable=True))\n op.add_column('batches', sa.Column('namespaces', sa.Boolean(), nullable=True))\n op.add_column('sessions', sa.Column('notes', sa.Text(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('sessions', 'notes')\n op.drop_column('batches', 'namespaces')\n op.drop_column('batches', 'identifier_field')\n # ### end Alembic commands ###\n", "repo_name": "mcampos-quinn/marcompare", "sub_path": "migrations/versions/c1197f8a206e_.py", "file_name": "c1197f8a206e_.py", "file_ext": "py", "file_size_in_byte": 925, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "alembic.op.add_column", "line_number": 21, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 21, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 21, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 21, "usage_type": "call"}, {"api_name": "alembic.op.add_column", "line_number": 22, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 22, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.Boolean", "line_number": 22, "usage_type": "call"}, {"api_name": "alembic.op.add_column", "line_number": 23, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 23, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.Text", "line_number": 23, "usage_type": "call"}, {"api_name": "alembic.op.drop_column", "line_number": 29, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 29, "usage_type": "name"}, {"api_name": "alembic.op.drop_column", "line_number": 30, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 30, "usage_type": "name"}, {"api_name": "alembic.op.drop_column", "line_number": 31, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 31, "usage_type": "name"}]} +{"seq_id": "9844515466", "text": "#-*- coding: utf-8 -*-\nimport os\nimport pandas as pd\nimport config\nimport pandas\nimport re\nimport math\nfrom modules.valuations.valuation import Valuation\n\n\n# 피터린치- 상수값 1.5 이상\n# = EPS성장율(3~5년 평균)+배당수익율(3~5년평균) / PER\n# 0.5 미만 투자우수\n# 0.5~1 투자긍정\n# 1이상 투자부적격\nclass PEG(Valuation):\n def __init__(self, valuation):\n data = valuation.get_data()\n json = valuation.get_json()\n\n Valuation.__init__(self, data, json)\n self.set_json('PEG', self.valuate())\n\n def valuate(self):\n try:\n data = self.get_data()\n json = self.get_json()\n\n bps = json['BPS']\n eps_5_growth = json['EPS_5_GROWTH']\n\n value = ((eps_5_growth * 100) + data['DIVIDEND_RATE'].dropna()[:1][0]\n ) / json['PER']\n\n return float(value)\n except:\n return None", "repo_name": "jongha/stock-ai", "sub_path": "modules/valuations/peg.py", "file_name": "peg.py", "file_ext": "py", "file_size_in_byte": 856, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "20", "api": [{"api_name": "modules.valuations.valuation.Valuation", "line_number": 16, "usage_type": "name"}, {"api_name": "modules.valuations.valuation.Valuation.__init__", "line_number": 21, "usage_type": "call"}, {"api_name": "modules.valuations.valuation.Valuation", "line_number": 21, "usage_type": "name"}]} +{"seq_id": "33987502184", "text": "import numpy as np\nfrom .gixd_pp import get_powder_data, get_gixd_data, angle_dist\nfrom .gixd_pp import read_param, data_gixd\nimport matplotlib as mpl\nfrom . import data_path, img_path\nimport os.path\nfrom os.path import join, exists, abspath, dirname\nfrom matplotlib.colors import Normalize\nfrom helper import gridplots\n\nmpl.use(\"Agg\")\nmpl.rcParams[\"text.usetex\"] = False\nmpl.rcParams[\"svg.fonttype\"] = \"none\"\n\n# plt.style.use(\"science\")\n\n\n# plt.figure(figsize=(6, 3))\n# qq, ii = get_powder_data(width=0.02)\n# plt.plot(qq, ii / max(ii))\n# plt.savefig(join(img_path, \"xrd_q.png\"))\n\nmaters = dict()\ndate_old = \"0625\"\ndate_new = \"0726\"\ndate_new2 = \"1008\"\ndate_old1 = \"1008-old\"\ndate_new1 = \"1008-new\"\ngr = \"graphene\"\nnogr = \"no-graphene\"\n\nmaters = {}\n# maters[\"Plasma_gr_old\"] = dict(name=\"Plasma\", date=date_old, condition=gr)\n# maters[\"OTS_gr_old\"] = dict(name=\"OTS\", date=date_old, condition=gr)\n# maters[\"Au_gr_old\"] = dict(name=\"Au\", date=date_old, condition=gr)\n# maters[\"Plasma_gr_new\"] = dict(name=\"Plasma\", date=date_new, condition=gr)\n# maters[\"OTS_gr_new\"] = dict(name=\"OTS\", date=date_new, condition=gr)\n# maters[\"Au_gr_new\"] = dict(name=\"Au\", date=date_new, condition=gr)\n# maters[\"Plasma_nogr_new\"] = dict(name=\"Plasma\", date=date_new, condition=nogr)\n# maters[\"OTS_nogr_new\"] = dict(name=\"OTS\", date=date_new, condition=nogr)\n# maters[\"Au_nogr_new\"] = dict(name=\"Au\", date=date_new, condition=nogr)\n\n# maters[\"Au_gr_new2\"] = dict(name=\"Au\", date=date_new2, condition=gr)\n# maters[\"Plasma_gr_new2\"] = dict(name=\"Plasma\", date=date_new2, condition=gr)\n\nmaters[\"Plasma_gr_old1\"] = dict(name=\"Plasma\", date=date_old1, condition=gr)\n# maters[\"OTS_gr_old\"] = dict(name=\"OTS\", date=date_old1, condition=gr)\nmaters[\"Au_gr_old1\"] = dict(name=\"Au\", date=date_old1, condition=gr)\nmaters[\"Plasma_gr_new1\"] = dict(name=\"Plasma\", date=date_new1, condition=gr)\n# maters[\"OTS_gr_old\"] = dict(name=\"OTS\", date=date_old1, condition=gr)\nmaters[\"Au_gr_new1\"] = dict(name=\"Au\", date=date_new1, condition=gr)\n\nshort_names = (\"Plasma\", \"OTS\", \"Au\")\n\n\ndef show_gixd(ax, mater_name,\n v_minmax=None,\n q_range=(8, -0.1, 12, 20)):\n X, Y, data = get_gixd_data(**maters[mater_name], q_range=q_range)\n if v_minmax is None:\n param = read_param(join(data_gixd, \"scaling.json\"),\n **maters[mater_name])\n v_min, v_max = param[\"vminmax\"]\n else:\n v_min, v_max = v_minmax\n if \"new2\" in mater_name:\n data = 255 - data\n # norm=None\n ax.imshow(data,\n vmin=v_min, vmax=v_max,\n extent=q_range,\n rasterized=True,\n # norm=Normalize(vmin=v_min, vmax=v_max),\n cmap=\"inferno\")\n ax.set_xlabel(\"$q_{xy}$ (nm$^{-1}$)\")\n ax.set_ylabel(\"$q_{z}$ (nm$^{-1}$)\")\n return\n\n\ndef show_large():\n for mater_name in maters.keys():\n fig, ax = gridplots(r=0.5, ratio=1)\n ax.set_aspect('equal')\n # fig = plt.figure(figsize=(3, 5))\n show_gixd(ax, mater_name, q_range=(15, -0.1, -0.1, 20))\n fig.tight_layout()\n fig.savefig(img_path / \"2D_{0}_large.svg\".format(mater_name))\n fig.savefig(img_path / \"2D_{0}_large.png\".format(mater_name))\n\ndef show_small():\n for mater_name in maters.keys():\n fig, ax = gridplots(r=0.5, ratio=1)\n ax.set_aspect('equal')\n show_gixd(ax, mater_name, q_range=(8, -0.1, 14, 20))\n fig.tight_layout()\n fig.savefig(img_path / \"2D_{0}_small.svg\".format(mater_name))\n fig.savefig(img_path / \"2D_{0}_small.png\".format(mater_name))\n\ndef show_nobg():\n for mater_name in maters.keys():\n fig, ax = gridplots(r=0.5, ratio=1)\n ax.set_aspect('equal')\n # fig = plt.figure(figsize=(3, 5))\n show_gixd(ax, mater_name, q_range=(6, -2, 2, 10))\n fig.tight_layout()\n fig.savefig(img_path / \"2D_{0}_nobg.svg\".format(mater_name))\n fig.savefig(img_path / \"2D_{0}_nobg.png\".format(mater_name))\n\n\nif __name__ == \"__main__\":\n show_large()\n show_small()\n # show_nobg()\n", "repo_name": "alchem0x2A/ETH_PHD_thesis", "sub_path": "scripts/vdw/exp/plot_2D_gixd.py", "file_name": "plot_2D_gixd.py", "file_ext": "py", "file_size_in_byte": 4043, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "matplotlib.use", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.rcParams", "line_number": 12, "usage_type": "attribute"}, {"api_name": "matplotlib.rcParams", "line_number": 13, "usage_type": "attribute"}, {"api_name": "gixd_pp.get_gixd_data", "line_number": 59, "usage_type": "call"}, {"api_name": "gixd_pp.read_param", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 61, "usage_type": "call"}, {"api_name": "gixd_pp.data_gixd", "line_number": 61, "usage_type": "argument"}, {"api_name": "helper.gridplots", "line_number": 82, "usage_type": "call"}, {"api_name": "helper.gridplots", "line_number": 92, "usage_type": "call"}, {"api_name": "helper.gridplots", "line_number": 101, "usage_type": "call"}]} +{"seq_id": "12645862637", "text": "import logging\n\nfrom django.http import Http404\nfrom rest_framework.exceptions import APIException\nfrom rest_framework.generics import RetrieveAPIView\n\nfrom api.models import Resource, ResourceMetadata\nfrom api.serializers.resource_metadata import ResourceMetadataSerializer, \\\n ResourceMetadataObservationsSerializer, \\\n ResourceMetadataFeaturesSerializer, \\\n ResourceMetadataParentOperationSerializer\n\nlogger = logging.getLogger(__name__)\n\n\nclass ResourceMetadataView(RetrieveAPIView):\n\n serializer_class = ResourceMetadataSerializer\n\n def get_queryset(self):\n resource_uuid = self.kwargs['pk']\n try:\n resource = Resource.objects.get(pk=resource_uuid)\n except Resource.DoesNotExist:\n raise Http404\n if resource.is_active:\n return ResourceMetadata.objects.filter(resource=resource)\n else:\n logger.info('Resource associated with the requested metadata'\n ' is inactive.')\n return []\n\n def get_object(self):\n queryset = self.get_queryset()\n if len(queryset) == 0:\n raise Http404\n elif len(queryset) == 1:\n return queryset[0]\n else:\n logger.error('Database constraint violated.'\n ' There were >1 metadata instances associated with'\n f' a Resource ({self.kwargs[\"pk\"]})')\n raise APIException()\n\n\nclass ResourceMetadataObservationsView(ResourceMetadataView):\n serializer_class = ResourceMetadataObservationsSerializer\n\n\nclass ResourceMetadataFeaturesView(ResourceMetadataView):\n serializer_class = ResourceMetadataFeaturesSerializer\n\n\nclass ResourceMetadataParentOperationView(ResourceMetadataView):\n serializer_class = ResourceMetadataParentOperationSerializer", "repo_name": "web-mev/mev-backend", "sub_path": "mev/api/views/resource_metadata.py", "file_name": "resource_metadata.py", "file_ext": "py", "file_size_in_byte": 1790, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "logging.getLogger", "line_number": 13, "usage_type": "call"}, {"api_name": "rest_framework.generics.RetrieveAPIView", "line_number": 16, "usage_type": "name"}, {"api_name": "api.serializers.resource_metadata.ResourceMetadataSerializer", "line_number": 18, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.get", "line_number": 23, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 23, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 23, "usage_type": "name"}, {"api_name": "api.models.Resource.DoesNotExist", "line_number": 24, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 24, "usage_type": "name"}, {"api_name": "django.http.Http404", "line_number": 25, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 27, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 27, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 27, "usage_type": "name"}, {"api_name": "django.http.Http404", "line_number": 36, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.APIException", "line_number": 43, "usage_type": "call"}, {"api_name": "api.serializers.resource_metadata.ResourceMetadataObservationsSerializer", "line_number": 47, "usage_type": "name"}, {"api_name": "api.serializers.resource_metadata.ResourceMetadataFeaturesSerializer", "line_number": 51, "usage_type": "name"}, {"api_name": "api.serializers.resource_metadata.ResourceMetadataParentOperationSerializer", "line_number": 55, "usage_type": "name"}]} +{"seq_id": "19450776978", "text": "from datetime import timedelta, datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport csv\n\nfrom data_handler.data_importer.helios_data import HeliosData\nfrom magnetic_reconnection_dir.finder.base_finder import BaseFinder\nfrom magnetic_reconnection_dir.finder.correlation_finder import CorrelationFinder\nfrom magnetic_reconnection_dir.lmn_coordinates import test_reconnection_lmn\n\n# lists [event, probe, number of reconnection events]\nevent_list = [[datetime(1974, 12, 15, 14, 0, 0), 1, 1], [datetime(1974, 12, 15, 20, 0, 0), 1, 1],\n [datetime(1975, 1, 18, 13, 0, 0), 1, 1], [datetime(1975, 2, 7, 1, 0, 0), 1, 1],\n [datetime(1975, 9, 22, 3, 30, 0), 1, 1], [datetime(1975, 12, 19, 21, 0, 0), 1, 1],\n [datetime(1976, 1, 19, 6, 0, 0), 2, 1], [datetime(1976, 1, 27, 7, 0, 0), 2, 1],\n [datetime(1976, 1, 30, 2, 0, 0), 2, 2], [datetime(1976, 3, 4, 9, 0, 0), 2, 1],\n [datetime(1976, 12, 15, 1, 0, 0), 2, 1], [datetime(1977, 4, 5, 22, 0, 0), 2, 1],\n [datetime(1978, 1, 25, 7, 0, 0), 2, 1], [datetime(1978, 2, 26, 4, 0, 0), 2, 1],\n [datetime(1977, 4, 23, 3, 0, 0), 2, 1], [datetime(1977, 12, 17, 1, 0, 0), 1, 1],\n [datetime(1978, 3, 17, 16, 0, 0), 1, 1], [datetime(1979, 6, 21, 2, 0, 0), 1, 1],\n [datetime(1980, 1, 3, 20, 0, 0), 1, 1], [datetime(1980, 1, 16, 14, 0, 0), 1, 1],\n\n [datetime(1976, 1, 18, 6, 0, 0), 2, 0], [datetime(1976, 2, 2, 7, 0, 0), 2, 0],\n [datetime(1977, 4, 22, 3, 0, 0), 2, 0], [datetime(1976, 2, 4, 7, 0, 0), 2, 0],\n [datetime(1976, 3, 5, 9, 0, 0), 2, 0], [datetime(1976, 12, 16, 1, 0, 0), 2, 0],\n [datetime(1977, 4, 6, 22, 0, 0), 2, 0], [datetime(1977, 12, 19, 1, 0, 0), 2, 0],\n [datetime(1978, 1, 5, 10, 0, 0), 2, 0], [datetime(1974, 12, 17, 14, 0, 0), 1, 0],\n [datetime(1974, 12, 17, 20, 0, 0), 1, 0], [datetime(1975, 1, 19, 13, 0, 0), 1, 0],\n [datetime(1975, 2, 8, 1, 0, 0), 1, 0], [datetime(1975, 9, 24, 3, 30, 0), 1, 0],\n [datetime(1975, 12, 20, 21, 0, 0), 1, 0], [datetime(1977, 12, 18, 1, 0, 0), 1, 0],\n [datetime(1978, 3, 22, 16, 0, 0), 1, 0], [datetime(1976, 12, 1, 2, 0, 0), 1, 0],\n [datetime(1980, 1, 4, 20, 0, 0), 1, 0], [datetime(1980, 1, 18, 14, 0, 0), 1, 0]\n ]\n\ntest_data = [] # try best elements on test data too to avoid over-fitting\n\nDEFAULT_GENES = [[1, 4], [1, 4], [3, 8], [0.5, 0.95], [1.05, 1.5]]\n\n\ndef evolution_algorithm(genes_dict: dict, first_population_size: int = 10, best_samples_size: int = 3,\n randomly_chosen_sample_size: int = 3, number_of_descendants: int = 2,\n mutation_probability: float = 0.1, event_list_split: int = 30, iterations: int = 40,\n finder: BaseFinder = CorrelationFinder()):\n genes_keys = list(genes_dict.keys())\n genes = [genes_dict[key] for key in genes_keys]\n\n population = generate_first_population(first_population_size, genes)\n performances = []\n for loop in range(iterations):\n print('GENERATION', loop)\n np.random.shuffle(event_list)\n sorted_by_performance = performance_per_gene(population, event_list_split, finder)\n performances.append(sorted_by_performance[0])\n print('performance', sorted_by_performance)\n next_generation = selection(sorted_by_performance, best_samples=best_samples_size,\n randomly_chosen_samples=randomly_chosen_sample_size)\n descendants = crossover(next_generation, descendants_number=number_of_descendants, best_genes=best_samples_size)\n population = mutation(descendants, mutation_probability)\n\n def get_key(item):\n return item[0]\n\n best_mcc = [performance[0] for performance in performances]\n plt.plot(best_mcc)\n plt.show()\n\n # puts nans at the end of the performance list\n performances_no_nans = [perf for perf in performances if not np.isnan(perf[0])]\n performances_nans = [perf for perf in performances if np.isnan(perf[0])]\n sorted_performances = sorted(performances_no_nans, key=get_key, reverse=True) + performances_nans\n print('SORTED PERFORMANCES')\n print(sorted_performances)\n send_perf_to_csv(sorted_performances, keys=genes_keys, name='performances_genalg_culling')\n return sorted_performances\n\n\ndef fitness(gene: list, event_list_split: int, finder: BaseFinder):\n \"\"\"\n Calculates the mcc for a given gene\n :param gene: gene of a given population\n :param event_list_split: number of events that are considered in the mcc calculation\n :param finder: finder to be used in the fitness calculation\n :return: mcc\n \"\"\"\n # test on random part of the data (avoid over-fitting and allow more iterations of the algorithm in less time)\n events = event_list[:event_list_split]\n f_n, t_n, t_p, f_p = 0, 0, 0, 0\n gene_split = len(gene) - 2 # split between the finder test and the lmn test (which takes two arguments)\n for event, probe, reconnection_number in events:\n interval = 3\n start_time = event - timedelta(hours=interval / 2)\n start_hour = event.hour\n data = HeliosData(start_date=start_time.strftime('%d/%m/%Y'), start_hour=start_hour,\n duration=interval, probe=probe)\n reconnection_corr = finder.find_magnetic_reconnections(data, *gene[:gene_split])\n reconnection = test_reconnection_lmn(reconnection_corr, probe, *gene[gene_split:])\n\n if reconnection_number == 0:\n if len(reconnection) == 0:\n t_n += 1\n else:\n f_p += len(reconnection)\n else:\n if len(reconnection) < reconnection_number:\n f_n += reconnection_number - len(reconnection)\n t_p += len(reconnection)\n elif len(reconnection) == reconnection_number:\n t_p += len(reconnection)\n else: # more detected than real\n f_p += len(reconnection) - reconnection_number\n t_p += reconnection_number\n mcc = (t_p * t_n + f_n * f_p) / np.sqrt((t_p + f_p) * (t_p + f_n) * (t_n + f_p) * (t_n + f_n))\n return mcc\n\n\ndef gene_generation(genes: list):\n dna_strand = []\n for n in range(len(genes)):\n chromosome = (np.max(genes[n]) - np.min(genes[n])) * np.random.random_sample() + np.min(genes[n])\n dna_strand.append(chromosome)\n return dna_strand\n\n\n# for now, the following code follows the reasoning of the genetic algorithm tutorial available at\n# https://blog.sicara.com/getting-started-genetic-algorithms-python-tutorial-81ffa1dd72f9\n# but adapted for this particular use\ndef generate_first_population(population_size: int, genes: list):\n population = []\n for n in range(population_size):\n population.append(gene_generation(genes))\n print('POPULATION', population)\n return population\n\n\ndef performance_per_gene(population: list, event_list_split: int, finder: BaseFinder):\n \"\"\"\n Finds the mcc performance of the given gens\n :param population: all the genes that are being considered\n :param event_list_split: number of events to test in the events list\n :param finder: finder to be used in the fitness calculation\n :return: list of list of mcc and genes\n \"\"\"\n performance = []\n for gene in population:\n print('GENE', gene)\n performance.append([fitness(gene, event_list_split, finder), gene])\n\n def get_key(item):\n return item[0]\n\n # puts nans at the end of the performance list\n performance_no_nans = [perf for perf in performance if not np.isnan(perf[0])]\n performance_nans = [perf for perf in performance if np.isnan(perf[0])]\n return sorted(performance_no_nans, key=get_key, reverse=True) + performance_nans\n\n\ndef selection(sorted_population: list, best_samples: int, randomly_chosen_samples: int) ->list:\n \"\"\"\n Takes the best performing individuals as well as some randomly chosen individuals\n :param sorted_population: list of mcc performance and genes, sorted by best performance\n :param best_samples: number of best performing samples we want to take\n :param randomly_chosen_samples: number of random samples we want to choose\n :return: list of parents of genes that are going to be tested in the next generation\n \"\"\"\n next_generation = []\n for n in range(best_samples):\n next_generation.append(sorted_population[n][1])\n for n in range(randomly_chosen_samples):\n next_generation.append(sorted_population[np.random.randint(best_samples, len(sorted_population) - 1)][1])\n return next_generation\n\n\ndef create_descendant(gene1: list, gene2: list):\n \"\"\"\n :param gene1: parent gene\n :param gene2: parent gene\n :return: child gene\n \"\"\"\n descendant = []\n for n in range(len(gene1)):\n if np.random.rand() < 0.5:\n descendant.append(gene1[n])\n else:\n descendant.append(gene2[n])\n return descendant\n\n\ndef crossover(genes: list, descendants_number: int, best_genes: int):\n \"\"\"\n :param genes: parent genes (chosen from the previous population)\n :param descendants_number: number of children we want to create for parent genes\n :param best_genes: number of best genes to keep in\n :return:\n \"\"\"\n next_population = []\n for n in range(best_genes):\n next_population.append(genes[n]) # elitism\n genes = genes[0:len(genes) - best_genes] # remove worse ones\n\n np.random.shuffle(genes)\n # can do in len(genes) and have random parents but might take longer\n for n in range(len(genes)):\n # for n in range(int(len(genes) / 2)):\n for m in range(descendants_number):\n next_population.append(\n create_descendant(genes[n], genes[len(genes) - 1 - np.random.randint(0, len(genes))]))\n # create_descendant(genes[n], genes[len(genes) - 1 - n]))\n # culling - remove similar genes and add a few random ones\n _next_population = []\n for n in range(len(next_population)):\n if next_population[n] not in _next_population:\n _next_population.append(next_population[n])\n culling_number = len(next_population) - len(_next_population)\n next_population = _next_population\n\n for n in range(best_genes + culling_number): # add random ones\n next_population.append(gene_generation(DEFAULT_GENES))\n return next_population\n\n\ndef mutate_gene(gene: list) ->list:\n \"\"\"\n :param gene: gene that we want to change\n :return: mutated gene\n \"\"\"\n modification = np.int(np.random.rand() * len(gene))\n if modification == 0:\n gene = gene\n else:\n if np.random.rand() < 0.5:\n gene[modification] = gene[modification] + np.random.rand()\n else:\n gene[modification] = gene[modification] - np.random.rand()\n return gene\n\n\ndef mutation(genes: list, probability: float) ->list:\n \"\"\"\n :param genes: this generation's genes, that might be mutated\n :param probability: probability that the genes will be mutated\n :return: mutated population\n \"\"\"\n for n in range(len(genes) - 2): # to avoid getting weird values for the walen test\n if np.random.rand() < probability:\n genes[n] = mutate_gene(genes[n])\n return genes\n\n\ndef send_perf_to_csv(performance_list: list, keys: list, name: str = 'performances_genalg'):\n with open(name + '.csv', 'w', newline='') as csv_file:\n fieldnames = ['mcc'] + keys\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writeheader()\n for mcc, gene in performance_list:\n mcc_info = {'mcc': mcc}\n for n in range(len(gene)):\n mcc_info[keys[n]] = gene[n]\n writer.writerow(mcc_info)\n\n\nif __name__ == '__main__':\n sigma_sum = [1, 3]\n sigma_diff = [1, 3]\n minutes_b = [3, 4, 5, 6, 7, 8]\n minutes = [3, 4, 5, 6, 7, 8]\n maximum_walen_fraction = [1.05, 1.5]\n minimum_walen_fraction = [0.5, 0.95]\n # be careful, fitness is defined to take only two lmn arguments so far\n genes_dictionary = {'sigma sum': sigma_sum, 'sigma diff': sigma_diff, 'minutes b': minutes_b, minutes: 'minutes',\n 'minimum walen': minimum_walen_fraction, 'maximum walen': maximum_walen_fraction}\n evolution_algorithm(genes_dictionary)\n", "repo_name": "THanae/MagRec", "sub_path": "magnetic_reconnection_dir/finder/parameter_optimisation/evolutionary_optimisation.py", "file_name": "evolutionary_optimisation.py", "file_ext": "py", "file_size_in_byte": 12378, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "datetime.datetime", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 17, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 20, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 21, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 24, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 25, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 26, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 28, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 29, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 30, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 32, "usage_type": "call"}, {"api_name": "magnetic_reconnection_dir.finder.base_finder.BaseFinder", "line_number": 43, "usage_type": "name"}, {"api_name": "magnetic_reconnection_dir.finder.correlation_finder.CorrelationFinder", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.random.shuffle", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 51, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "numpy.isnan", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 69, "usage_type": "call"}, {"api_name": "magnetic_reconnection_dir.finder.base_finder.BaseFinder", "line_number": 77, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 91, "usage_type": "call"}, {"api_name": "data_handler.data_importer.helios_data.HeliosData", "line_number": 93, "usage_type": "call"}, {"api_name": "magnetic_reconnection_dir.lmn_coordinates.test_reconnection_lmn", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.random.random_sample", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 119, "usage_type": "attribute"}, {"api_name": "magnetic_reconnection_dir.finder.base_finder.BaseFinder", "line_number": 135, "usage_type": "name"}, {"api_name": "numpy.isnan", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 153, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 169, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 169, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 181, "usage_type": "attribute"}, {"api_name": "numpy.random.shuffle", "line_number": 200, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 200, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 206, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 206, "usage_type": "attribute"}, {"api_name": "numpy.int", "line_number": 226, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 226, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 226, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 230, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 230, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 231, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 231, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 233, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 233, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 244, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 244, "usage_type": "attribute"}, {"api_name": "csv.DictWriter", "line_number": 252, "usage_type": "call"}]} +{"seq_id": "37469854963", "text": "from django.db import models\nfrom django.contrib.auth.models import Group, User\nfrom django.core.exceptions import FieldError\nfrom django.utils import timezone\n\ndef user_directory_path(instance, filename):\n \"\"\"\n Profile pictures are stored in a folder that is denoted by\n the user's ID, this function takes in an instance of a saved\n profile picture, renames the file and puts it in the right place.\n\n - parameter instance: The instance of a user saving a profile picture.\n - parameter filename: The name of the file sent to the server.\n \"\"\"\n # Find the filetype by splitting the filename into a list of\n # strings, with the separator being '.'\n split_file_name = filename.split(sep='.')\n\n # Retrieve the second to last string, which will be the file\n # extension. \n filetype = split_file_name[len(split_file_name) - 1]\n\n # Find the current date.\n now = timezone.now()\n\n # File will be uploaded to \n # MEDIA_ROOT/employee_profile/pictures/user_/\n\n # File name will be\n # __.\n return 'employee_profile/pictures/user_{0}/{1}_{2}_{3}.'.format(\n instance.user.id, now.year, now.month, now.day) + filetype\n\nclass EmployeeProfile(models.Model):\n \"\"\"\n An extension of the User class, adding a profile picture and job position.\n\n Fields:\n user -- A one-to-one relationship with the Django User class,\n giving every user one employee profile.\n job_position -- A string detailing the job of the user.\n profile_picture -- A user-submitted (or pre-defined) photo assigned to a \n user.\n \"\"\"\n user = models.OneToOneField(User, related_name='employee_profile', on_delete=models.CASCADE)\n job_position = models.CharField(max_length=100, blank=True)\n profile_picture = models.ImageField(upload_to=user_directory_path, \n blank=True)\n\n def __str__(self):\n return \"%s %s | %s\" % (self.user.first_name, self.user.last_name, \n self.job_position)\n \"\"\"\n Used in the admin portal in the employee group list page.\n \"\"\"\n # Example __str__: \"Joe Bloggs | Research and development\"\n return \"%s %s | %s\" % (self.user.first_name, self.user.last_name, \n self.job_position)\n\n @property\n def admin_of(self):\n # An empty list that will be populated with the correct groups.\n groups = []\n # Find every membership object for this user where they are an admin.\n admin_memberships = self.memberships.filter(admin_privileges=True)\n # For each membership object\n for membership in admin_memberships:\n # Add the corresponding group to the group list.\n groups.append(membership.group)\n # Return the group list.\n return groups\n\n#Ref: 1.2\nclass EmployeeGroup(models.Model):\n \"\"\"\n Creates groups of Employees and gives them a to-do list and schedule \n via the todolist and schedule apps.\n \n Fields:\n name -- The name of the group.\n members -- Many-to-many field going through membership linking \n users to their respective groups.\n parent_group -- Optional foreign key relationship linking a group to \n another group as its parent.\n\n Methods:\n group_traceback -- Returns a full trace of the group's parents to the \n root group and returns as an array of EmployeeGroup \n objects.\n\n Properties:\n admins -- Returns a QuerySet of the group's administrators.\n root_group -- If the group has a parent, this will return the first \n level group.\n \"\"\"\n name = models.CharField(max_length=100)\n members = models.ManyToManyField('groups.EmployeeProfile', \n related_name='employee_groups', \n through='GroupMembership')\n parent_group = models.ForeignKey('self', \n related_name='children', \n blank=True, null=True, on_delete=models.CASCADE) \n\n #Ref: 1.2.A\n def group_traceback(self):\n # Create an empty list that the group_traceback list will \n # be built from\n traceback_list = [] \n # Set the current group to the group that called this method.\n current_group = self\n # Code will stop looping when the top of the group heirarchy \n # is reached \n while current_group != None:\n # Add group to the traceback list. \n traceback_list.insert(0, current_group)\n # Move one group up the group heirarchy.\n current_group = current_group.parent_group \n # Once the root group has been reached, return the traceback list.\n return traceback_list \n\n def __str__(self):\n return self.name\n\n @property \n def admins(self):\n \"\"\"returns a QuerySet of the admins of the group\"\"\"\n return self.members.filter(memberships__admin_privileges=True)\n\n @property\n def root_group(self):\n # The first check that needs to be done is that this group is not a\n # root group itself.\n p = self.parent_group \n # If the group has no parent, return None to show there isn't a root\n # group.\n if p == None:\n return None\n\n #Keep running until told to stop.\n while True:\n # If the group has a parent group\n if p.parent_group != None:\n # Set the current group to the parent group.\n p = p.parent_group\n else:\n # Stop the loop if there is no more parents.\n break\n # Return the root group.\n return p\n\n def save(self, *args, **kwargs):\n \"\"\"\n Saving a group requires some checking before it can be done, to ensure\n that an infinite parent group relationship has been created, in order \n to prevent this, this algorithm moves its way up the group heirarchy \n tree checking that a circular relationship is not present.\n \"\"\"\n # An empty list that will track whether there is a non-tree like\n # relationship created.\n tracker_list = []\n # Start searching at the saved group.\n current_group = self \n # While there is a parent group present\n while current_group != None:\n # If a group is referenced already in the heirarchy tree:\n if tracker_list.count(current_group) > 0:\n # This is not a validated group relationship, so raise an error.\n raise FieldError('Infinite parent_group relationship detected.')\n else:\n # Now that this group has been validated, move one group up the\n # tree and start the loop over again.\n tracker_list.append(current_group)\n current_group = current_group.parent_group\n\n # If this loop completes without raising an error. The group\n # relationship is validated, so it is safe to save it to the database.\n super(EmployeeGroup, self).save(*args, **kwargs)\n\nclass GroupMembership(models.Model):\n \"\"\"\n The intermediary table that links Users with Groups, and determines whether \n they can edit the group.\n\n Fields:\n user -- The user the membership is for.\n group -- What group the user is to be a member of.\n admin_privileges -- A boolean value determining whether the user is an \n administrator of the group. \n \"\"\"\n employee = models.ForeignKey(EmployeeProfile, on_delete=models.CASCADE, \n related_name=\"memberships\")\n group = models.ForeignKey(EmployeeGroup, on_delete=models.CASCADE)\n admin_privileges = models.BooleanField()\n\n def __str__(self):\n return self.employee.user.first_name + \" > \" + self.group.name\n", "repo_name": "JordanField/Bizzorg-Server", "sub_path": "groups/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 8133, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "django.utils.timezone.now", "line_number": 24, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 24, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 34, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 34, "usage_type": "name"}, {"api_name": "django.db.models.OneToOneField", "line_number": 45, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User", "line_number": 45, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 45, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 45, "usage_type": "attribute"}, {"api_name": "django.db.models.CharField", "line_number": 46, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 46, "usage_type": "name"}, {"api_name": "django.db.models.ImageField", "line_number": 47, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 47, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 74, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 74, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 96, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 96, "usage_type": "name"}, {"api_name": "django.db.models.ManyToManyField", "line_number": 97, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 97, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 100, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 100, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 102, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 102, "usage_type": "name"}, {"api_name": "django.core.exceptions.FieldError", "line_number": 168, "usage_type": "call"}, {"api_name": "django.db.models.Model", "line_number": 179, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 179, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 190, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 190, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 190, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 192, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 192, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 192, "usage_type": "attribute"}, {"api_name": "django.db.models.BooleanField", "line_number": 193, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 193, "usage_type": "name"}]} +{"seq_id": "28848916239", "text": "from collections import defaultdict\n\nblock = [(0, 1), (1, 0), (1, 1)]\n\n\ndef solution(m, n, board):\n global M, N, answer\n tmp_board = [list(row) for row in board]\n answer = 0\n M, N = m, n\n\n candidates = defaultdict(set) # { column1 : [row1, row2, ...], column2 : [row1, row2, ... ], } # pop을 할 대상\n\n while True:\n\n marked = [ [True for i in range(N)] for i in range(M) ]\n for r in range(m - 1):\n for c in range(n - 1):\n if find_four_blocks(r, c, tmp_board):\n marked[r][c] = False\n marked[r][c + 1] = False\n marked[r + 1][c] = False\n marked[r + 1][c + 1] = False\n\n # pop if False in marked array\n pop_num = pop_board(tmp_board, marked)\n if pop_num == 0:\n break\n\n answer += pop_num\n\n for col in range(N):\n move_board(col, tmp_board)\n\n return answer\n\n\ndef find_four_blocks(row, col, board):\n target = board[row][col]\n\n if row >= M - 1 or col >= N - 1 or not target: # cannot check 2 * 2 blocks\n return False\n\n for dx, dy in block:\n if board[row + dx][col + dy] != target:\n return False\n return True\n\ndef pop_board(tmp_board, marked):\n counter = 0\n for i in range(M):\n for j in range(N):\n if not marked[i][j]:\n tmp_board[i][j] = None\n counter += 1\n return counter\n\ndef move_board(col, board):\n for idx in range(M - 1, 1, -1):\n if not board[idx][col]:\n for target in range(idx - 1, -1, -1):\n if board[target][col]:\n board[idx][col], board[target][col] = board[target][col], board[idx][col]\n break\n\ndef print_board(board):\n for row in board:\n print(row)\n print()\n\n\nprint(solution(4, 5, [\"CCBDE\", \"AAADE\", \"AAABF\", \"CCBBF\"]))\n", "repo_name": "jihye-woo/algorithm-practice", "sub_path": "kakao/프랜즈4블록.py", "file_name": "프랜즈4블록.py", "file_ext": "py", "file_size_in_byte": 1898, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "collections.defaultdict", "line_number": 12, "usage_type": "call"}]} +{"seq_id": "1028920099", "text": "\nimport sys\nimport argparse\nimport re\nfrom multiprocessing import cpu_count\n\nfrom .submodules import MSParser, UniProt, Alignments, fasta, parent_parser\n\nPROG_VERSION = 2.1\nSEQ_PATH = 'sequences.fasta'\nFXN_SEP = '!'\nRESIDUE_SEP = '|'\n\ndef read_input(args):\n\n if args.file_type == 'cimage':\n ret = MSParser.Cimage_file()\n elif args.file_type == 'tsv':\n ret = MSParser.Tsv_file(id_col=args.id_col, seq_col=args.seq_col)\n elif args.file_type == 'dtaselect':\n ret = MSParser.Dtaselect()\n else:\n raise RuntimeError('{} is an unknown input file_type'.format(args.file_type))\n\n ret.read(args.input_file, args.defined_organism)\n return ret\n\n\ndef main():\n parser = argparse.ArgumentParser(prog='cimage_annotation', parents=[parent_parser.PARENT_PARSER],\n description='Annotate functional cysteine residues in cimage output.',\n epilog='cimage_annotation was written by Dan Bak and Aaron Maurais.\\n')\n\n parser.add_argument('-p', '--parallel', choices=[0, 1], type=int, default=1,\n help='Choose whether internet queries and protein alignments should be performed in parallel.'\n ' Parallel processing is performed on up to the number of logical cores on your system. '\n '1 is the default.')\n\n parser.add_argument('-t', '--nThread', type=int, default=None,\n help='Chose how many threads to use for parllel processing.'\n 'This option overrides the --parallel option.')\n\n parser.add_argument('--debug', choices=['none', 'pdb', 'pudb'], default='none',\n help='Start the main method in the selected debugger.')\n\n args = parser.parse_args()\n\n if args.debug != 'none':\n assert(args.debug in ['pdb', 'pudb'])\n if args.debug == 'pdb':\n import pdb as db\n elif args.debug == 'pudb':\n try:\n import pudb as db\n except ModuleNotFoundError as e:\n sys.stderr.write('pudb is not installed.')\n return -1\n db.set_trace()\n\n sys.stdout.write('\\ncimage_annotation v{}\\n'.format(PROG_VERSION))\n\n # Manually check args.\n if args.align and args.database_dir is None:\n sys.stderr.write('--database_dir must be specified when --align 1 is set\\n')\n return -1\n _nThread = args.nThread\n if args.parallel and args.nThread is None:\n _nThread = cpu_count()\n elif not args.parallel and args.nThread is None:\n _nThread=1\n\n\n # Open input file\n input_file = read_input(args)\n\n if len(input_file) == 0:\n sys.stderr.write('ERROR: No peptides found in {}!\\n\\tExiting...\\n'.format(args.input_file))\n return -1\n\n sys.stdout.write('\\nRetreiving protein Uniprot records...\\n')\n record_dict = UniProt.get_uniprot_records(input_file.unique_ids, _nThread, verbose=args.verbose,\n show_bar = not(args.verbose and args.parallel == 0))\n\n sequences = dict()\n seq_written = False\n for i, p in input_file.iterpeptides():\n # Get and Parse Uniprot entry for protein\n try:\n seq_temp = re.match(r'.?\\.?([A-z\\*]+)\\.?/?', p[args.seq_col]).group(1)\n except AttributeError as e:\n sys.stdout.write('Error parsing sequence: {}'.format(p[args.seq_col]))\n continue\n\n UniProt_data = UniProt.ExPasy(seq_temp, record_dict[p[args.id_col]],\n all_features=args.all_features, res_sep=RESIDUE_SEP, fxn_sep=FXN_SEP)\n\n input_file.set_peptide_value(i, 'position', UniProt_data[1]) # cysteine position\n input_file.set_peptide_value(i, 'res_function', UniProt_data[2]) # cysteine function (if known)\n input_file.set_peptide_value(i, 'domains', UniProt_data[3]) # Domain at position (if known)\n input_file.set_peptide_value(i, 'protein_location', UniProt_data[5]) # protein subcellular localization (if known)\n\n if args.write_seq:\n if p[args.id_col] not in sequences: #only write sequence if it is not currently in file\n fasta.write_fasta_entry(SEQ_PATH,\n p[args.id_col],\n UniProt_data[3],\n description=p['description'],\n append=seq_written)\n seq_written = True\n sequences[p[args.id_col]] = ('' if args.description_col not in p else p[args.description_col], UniProt_data[4])\n\n # Replace alignment files with empty string so they won't be continuously appended to.\n if args.write_alignment_data and args.align:\n # blast protein sequence against each fasta database and parse those alignments to determine cysteine conservation\n sys.stdout.write('\\nAlligning protein sequences to determine cysteine conservation...\\n')\n for organism in Alignments.organism_list:\n align_fname = '{}_alignments.{}'.format(organism, args.align_format)\n sys.stdout.write('\\tCreating {}...'.format(align_fname))\n with open(align_fname, 'w') as outF:\n outF.write('')\n sys.stdout.write('Done!\\n')\n\n if args.align:\n alignment_data = Alignments.align_all(input_file.unique_ids, sequences, args.database_dir, Alignments.organism_list,\n nThread=_nThread, verbose=args.verbose,\n show_bar=not(args.verbose and args.parallel == 0))\n \n for o in Alignments.organism_list:\n input_file.add_column('{}_conserved'.format(o))\n\n if args.defined_organism != 'none':\n \n for o in MSParser.ALLIGNMENT_COLUMNS:\n input_file.add_column('{}_{}'.format(args.defined_organism, o))\n\n org_ids = set()\n for a in alignment_data.values():\n org_ids.add(a[args.defined_organism].get_best_id())\n\n sys.stdout.write('\\nRetreiving Uniprot records for {} alignments...\\n'.format(args.defined_organism))\n org_record_dict = UniProt.get_uniprot_records(org_ids, _nThread, verbose=args.verbose,\n show_bar=not(args.verbose and args.parallel==0))\n\n seen=set() # Keep track of seen protein IDs\n for i, p in input_file.iterpeptides():\n for organism in Alignments.organism_list:\n if p[args.id_col] in seen and args.write_alignment_data:\n alignment_data[p[args.id_col]][organism].write('{}_alignments.{}'.format(organism, args.align_format),\n file_format=args.align_format, mode='a')\n seen.add(p[args.id_col])\n\n evalue = alignment_data[p[args.id_col]][organism].get_best_evalue()\n conserved_temp = list()\n for pos in p['position'].split(RESIDUE_SEP):\n cp_temp = '--'\n if pos in ('BAD_ID', 'RESIDUE_NOT_FOUND'):\n cp_temp = 'Error'\n else:\n assert(pos.isdigit())\n if evalue is None:\n cp_temp == '--'\n elif evalue <= args.evalue_co:\n cp_temp = 'Yes' if alignment_data[p[args.id_col]][organism].conserved_at_position(int(pos)) else 'No'\n conserved_temp.append(cp_temp)\n\n input_file.set_peptide_value(i, '{}_conserved'.format(str(organism)), RESIDUE_SEP.join(conserved_temp))\n\n # for comparative organism analyze Uniprot entry of best blast hit\n if organism == args.defined_organism.lower():\n org_dict_temp = {x: '' for x in MSParser.ALLIGNMENT_COLUMNS}\n\n id_temp = alignment_data[p[args.id_col]][organism].get_best_id()\n org_dict_temp['id'] = id_temp\n org_dict_temp['description'] = alignment_data[p[args.id_col]][organism].get_best_description()\n if id_temp != '':\n org_dict_temp['evalue'] = alignment_data[p[args.id_col]][organism].get_best_evalue()\n if org_dict_temp['evalue'] <= args.evalue_co:\n\n positions_temp = list()\n functions_temp = list()\n for pos in p['position'].split(RESIDUE_SEP):\n homolog_position = None if not pos.isdigit() else alignment_data[p[args.id_col]][organism].alignment_at_position(int(pos))[1]\n if homolog_position is None:\n homolog_position = 0\n positions_temp.append(str(homolog_position))\n if org_record_dict[id_temp] is None:\n functions_temp.append('')\n else:\n functions_temp.append(UniProt.res_features(org_record_dict[id_temp],\n homolog_position - 1,\n all_features=args.all_features)[0])\n\n org_dict_temp['position'] = RESIDUE_SEP.join(positions_temp)\n if ''.join(functions_temp):\n if len(functions_temp) == 1:\n org_dict_temp['function'] = functions_temp[0]\n else:\n org_dict_temp['function'] = FXN_SEP.join(['{}:{}'.format(p, s) for p, s in zip(positions_temp,\n functions_temp)])\n\n # add alignment data to peptides\n for k, v in org_dict_temp.items():\n key_temp = '{}_{}'.format(args.defined_organism, k)\n input_file.set_peptide_value(i, key_temp, v)\n\n # file output\n input_file.write(args.ofname)\n sys.stdout.write('\\nResults written to {}\\n\\n'.format(args.ofname))\n\n\nif __name__ == '__main__':\n main()\n\n", "repo_name": "ajmaurais/cimage_annotation", "sub_path": "src/cimage_annotation/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 10402, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "submodules.MSParser.Cimage_file", "line_number": 17, "usage_type": "call"}, {"api_name": "submodules.MSParser", "line_number": 17, "usage_type": "name"}, {"api_name": "submodules.MSParser.Tsv_file", "line_number": 19, "usage_type": "call"}, {"api_name": "submodules.MSParser", "line_number": 19, "usage_type": "name"}, {"api_name": "submodules.MSParser.Dtaselect", "line_number": 21, "usage_type": "call"}, {"api_name": "submodules.MSParser", "line_number": 21, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 30, "usage_type": "call"}, {"api_name": "submodules.parent_parser.PARENT_PARSER", "line_number": 30, "usage_type": "attribute"}, {"api_name": "submodules.parent_parser", "line_number": 30, "usage_type": "name"}, {"api_name": "sys.stderr.write", "line_number": 56, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 56, "usage_type": "attribute"}, {"api_name": "pudb.set_trace", "line_number": 58, "usage_type": "call"}, {"api_name": "sys.stdout.write", "line_number": 60, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 60, "usage_type": "attribute"}, {"api_name": "sys.stderr.write", "line_number": 64, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 64, "usage_type": "attribute"}, {"api_name": "multiprocessing.cpu_count", "line_number": 68, "usage_type": "call"}, {"api_name": "sys.stderr.write", "line_number": 77, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 77, "usage_type": "attribute"}, {"api_name": "sys.stdout.write", "line_number": 80, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 80, "usage_type": "attribute"}, {"api_name": "submodules.UniProt.get_uniprot_records", "line_number": 81, "usage_type": "call"}, {"api_name": "submodules.UniProt", "line_number": 81, "usage_type": "name"}, {"api_name": "re.match", "line_number": 89, "usage_type": "call"}, {"api_name": "sys.stdout.write", "line_number": 91, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 91, "usage_type": "attribute"}, {"api_name": "submodules.UniProt.ExPasy", "line_number": 94, "usage_type": "call"}, {"api_name": "submodules.UniProt", "line_number": 94, "usage_type": "name"}, {"api_name": "submodules.fasta.write_fasta_entry", "line_number": 104, "usage_type": "call"}, {"api_name": "submodules.fasta", "line_number": 104, "usage_type": "name"}, {"api_name": "sys.stdout.write", "line_number": 115, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 115, "usage_type": "attribute"}, {"api_name": "submodules.Alignments.organism_list", "line_number": 116, "usage_type": "attribute"}, {"api_name": "submodules.Alignments", "line_number": 116, "usage_type": "name"}, {"api_name": "sys.stdout.write", "line_number": 118, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 118, "usage_type": "attribute"}, {"api_name": "sys.stdout.write", "line_number": 121, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 121, "usage_type": "attribute"}, {"api_name": "submodules.Alignments.align_all", "line_number": 124, "usage_type": "call"}, {"api_name": "submodules.Alignments", "line_number": 124, "usage_type": "name"}, {"api_name": "submodules.Alignments.organism_list", "line_number": 124, "usage_type": "attribute"}, {"api_name": "submodules.Alignments.organism_list", "line_number": 128, "usage_type": "attribute"}, {"api_name": "submodules.Alignments", "line_number": 128, "usage_type": "name"}, {"api_name": "submodules.MSParser.ALLIGNMENT_COLUMNS", "line_number": 133, "usage_type": "attribute"}, {"api_name": "submodules.MSParser", "line_number": 133, "usage_type": "name"}, {"api_name": "sys.stdout.write", "line_number": 140, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 140, "usage_type": "attribute"}, {"api_name": "submodules.UniProt.get_uniprot_records", "line_number": 141, "usage_type": "call"}, {"api_name": "submodules.UniProt", "line_number": 141, "usage_type": "name"}, {"api_name": "submodules.Alignments.organism_list", "line_number": 146, "usage_type": "attribute"}, {"api_name": "submodules.Alignments", "line_number": 146, "usage_type": "name"}, {"api_name": "submodules.MSParser.ALLIGNMENT_COLUMNS", "line_number": 170, "usage_type": "attribute"}, {"api_name": "submodules.MSParser", "line_number": 170, "usage_type": "name"}, {"api_name": "submodules.UniProt.res_features", "line_number": 189, "usage_type": "call"}, {"api_name": "submodules.UniProt", "line_number": 189, "usage_type": "name"}, {"api_name": "sys.stdout.write", "line_number": 208, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 208, "usage_type": "attribute"}]} +{"seq_id": "23009033664", "text": "import datetime\nimport json\nimport os\nimport shutil\nimport stat\nimport zipfile\nfrom django.core.files.storage import FileSystemStorage\nfrom distutils.dir_util import copy_tree\nimport tempfile\n\n\ndef timestamp_to_str(timestamp, format_str='%Y-%m-%d %I:%M:%S'):\n date = datetime.datetime.fromtimestamp(timestamp)\n return date.strftime(format_str)\n\n\ndef filemode(mode):\n is_dir = 'd' if stat.S_ISDIR(mode) else '-'\n dic = {'7': 'rwx', '6': 'rw-', '5': 'r-x', '4': 'r--', '0': '---'}\n perm = str(oct(mode)[-3:])\n return is_dir + ''.join(dic.get(x, x) for x in perm)\n\n\ndef compress_zip(base_name, folders):\n with zipfile.ZipFile(base_name + '.zip',\n \"w\",\n zipfile.ZIP_DEFLATED,\n allowZip64=True) as zf:\n for f in folders:\n if os.path.isfile(f):\n zf.write(f,os.path.basename(f))\n continue\n os.chdir(os.path.dirname(f))\n for root, _, filenames in os.walk(os.path.basename(f)):\n for name in filenames:\n name = os.path.join(root, name)\n name = os.path.normpath(name)\n zf.write(name, name)\n\n\ndef get_file_information(path):\n fstat = os.stat(path)\n if stat.S_ISDIR(fstat.st_mode):\n ftype = 'dir'\n else:\n ftype = 'file'\n fsize = fstat.st_size\n ftime = timestamp_to_str(fstat.st_mtime)\n fmode = filemode(fstat.st_mode)\n return ftype, fsize, ftime, fmode\n\n\ndef change_permissions_recursive(path, mode):\n for root, dirs, files in os.walk(path, topdown=False):\n for d in [os.path.join(root, d) for d in dirs]:\n os.chmod(d, mode)\n for f in [os.path.join(root, f) for f in files]:\n os.chmod(f, mode)\n\n\nclass FileManager:\n def __init__(self, root='/', show_dotfiles=True):\n self.root = os.path.abspath(root)\n self.show_dotfiles = show_dotfiles\n\n def list(self, request):\n path = os.path.abspath(self.root + request['path'])\n if not os.path.exists(path) or not path.startswith(self.root):\n return {'result': ''}\n\n files = []\n for fname in sorted(os.listdir(path)):\n if fname.startswith('.') and not self.show_dotfiles:\n continue\n fpath = os.path.join(path, fname)\n try:\n ftype, fsize, ftime, fmode = get_file_information(fpath)\n except Exception as e:\n continue\n files.append({\n 'name': fname,\n 'rights': fmode,\n 'size': fsize,\n 'date': ftime,\n 'type': ftype,\n })\n\n return {'result': files}\n\n def rename(self, request):\n try:\n src = os.path.abspath(self.root + request['item'])\n dst = os.path.abspath(self.root + request['newItemPath'])\n if not (os.path.exists(src) and src.startswith(self.root) and dst.startswith(self.root)):\n return {'result': {'success': 'false', 'error': 'Invalid path'}}\n shutil.move(src, dst)\n except Exception as e:\n return {'result': {'success': 'false', 'error': e.message}}\n return {'result': {'success': 'true', 'error': ''}}\n\n def copy(self, request):\n try:\n items = request['items']\n if len(items) == 1 and 'singleFilename' in request:\n src = os.path.abspath(self.root + items[0])\n dst = os.path.abspath(self.root + request['newPath'] + '/' + request['singleFilename'])\n if not (os.path.exists(src) and src.startswith(self.root) and dst.startswith(self.root)):\n return {'result': {'success': 'false', 'error': 'File not found'}}\n shutil.copyfile(src, dst)\n else:\n path = os.path.abspath(self.root + request['newPath'])\n for item in items:\n src = os.path.abspath(self.root + item)\n if not (os.path.exists(src) and src.startswith(self.root) and path.startswith(self.root)):\n return {'result': {'success': 'false', 'error': 'Invalid path'}}\n shutil.copyfile(src, path)\n except Exception as e:\n return {'result': {'success': 'false', 'error': e.message}}\n return {'result': {'success': 'true', 'error': ''}}\n\n def remove(self, request):\n try:\n items = request['items']\n for item in items:\n path = os.path.abspath(self.root + item)\n if not (os.path.exists(path) and path.startswith(self.root)):\n return {'result': {'success': 'false', 'error': 'Invalid path'}}\n if os.path.isdir(path):\n shutil.rmtree(path)\n else:\n os.remove(path)\n except Exception as e:\n return {'result': {'success': 'false', 'error': e.message}}\n return {'result': {'success': 'true', 'error': ''}}\n\n def edit(self, request):\n try:\n path = os.path.abspath(self.root + request['item'])\n if not path.startswith(self.root):\n return {'result': {'success': 'false', 'error': 'Invalid path'}}\n content = request['content']\n with open(path, 'w') as f:\n f.write(content)\n except Exception as e:\n return {'result': {'success': 'false', 'error': e.message}}\n return {'result': {'success': 'true', 'error': ''}}\n\n def getContent(self, request):\n try:\n path = os.path.abspath(self.root + request['item'])\n if not path.startswith(self.root):\n return {'result': {'success': 'false', 'error': 'Invalid path'}}\n with open(path, 'r') as f:\n content = f.read()\n except Exception as e:\n content = e.message\n return {'result': content}\n\n def createFolder(self, request):\n try:\n path = os.path.abspath(self.root + request['newPath'])\n if not path.startswith(self.root):\n return {'result': {'success': 'false', 'error': 'Invalid path'}}\n os.makedirs(path)\n except Exception as e:\n return {'result': {'success': 'false', 'error': e.message}}\n return {'result': {'success': 'true', 'error': ''}}\n\n def move(self, request):\n try:\n dst = os.path.abspath(self.root + request['newPath'])\n if not dst.startswith(self.root):\n return {'result': {'success': 'false', 'error': 'Invalid path'}}\n for item in request['items']:\n src = os.path.abspath(self.root + item)\n if not (os.path.exists(src) and src.startswith(self.root) and dst.startswith(self.root)):\n return {'result': {'success': 'false', 'error': 'Invalid path'}}\n shutil.move(src, dst)\n except Exception as e:\n return {'result': {'success': 'false', 'error': e.message}}\n return {'result': {'success': 'true', 'error': ''}}\n\n def changePermissions(self, request):\n try:\n items = request['items']\n permissions = int(request['permsCode'], 8)\n recursive = request['recursive']\n for item in items:\n path = os.path.abspath(self.root + item)\n if not (os.path.exists(path) and path.startswith(self.root)):\n return {'result': {'success': 'false', 'error': 'Invalid path'}}\n if recursive:\n change_permissions_recursive(path, permissions)\n else:\n os.chmod(path, permissions)\n except Exception as e:\n return {'result': {'success': 'false', 'error': e.message}}\n return {'result': {'success': 'true', 'error': ''}}\n\n def compress(self, request):\n try:\n items = request['items']\n path = os.path.abspath(os.path.join(self.root + request['destination'], request['compressedFilename']))\n if not path.startswith(self.root):\n return {'result': {'success': 'false', 'error': 'Invalid path'}}\n folders = []\n for item in items:\n _path = os.path.abspath(self.root + item)\n if not (os.path.exists(_path) and _path.startswith(self.root)):\n continue\n folders.append(_path)\n compress_zip(path, folders)\n except Exception as e:\n return {'result': {'success': 'false', 'error': e.message}}\n return {'result': {'success': 'true', 'error': ''}}\n\n def extract(self, request):\n try:\n src = os.path.abspath(self.root + request['item'])\n dst = os.path.abspath(self.root + request['destination'] + '/' + request['folderName'])\n if not (os.path.isfile(src) and src.startswith(self.root) and dst.startswith(self.root)):\n return {'result': {'success': 'false', 'error': 'Invalid path'}}\n zip_file = zipfile.ZipFile(src, 'r')\n zip_file.extractall(dst)\n zip_file.close()\n except Exception as e:\n return {'result': {'success': 'false', 'error': e.message}}\n return {'result': {'success': 'true', 'error': ''}}\n\n def upload(self, files, dest):\n try:\n for _file in list(files):\n path = os.path.join(self.root, dest.replace('/', '', 1))\n if not path.startswith(self.root):\n return {'result': {'success': 'false', 'error': 'Invalid path'}}\n fs = FileSystemStorage(location=path)\n fs.save(files.get(_file).name, files.get(_file))\n except Exception as e:\n return {'result': {'success': 'false', 'error': e.message}}\n return {'result': {'success': 'true', 'error': ''}}\n\n def download(self, path, HttpResponse):\n path = os.path.abspath(self.root + path)\n response = ''\n if path.startswith(self.root) and os.path.isfile(path):\n try:\n with open(path, 'rb') as f:\n response = HttpResponse(f.read(), content_type=\"application/octet-stream\")\n response['Content-Disposition'] = 'inline; filename=' + os.path.basename(path)\n except Exception as e:\n raise Http404\n return response\n\n def downloadMultiple(self, request, HttpResponse):\n items = dict(request.iterlists())\n folders = []\n for item in items['items[]']:\n _path = os.path.join(self.root + os.path.expanduser(item))\n if not ( (os.path.exists(_path) or os.path.isfile(_path))and _path.startswith(self.root)):\n continue\n folders.append(_path)\n tmpdir = tempfile.mkdtemp()\n filename = items['toFilename'][0].replace('.zip', '',1)\n saved_umask = os.umask(77)\n path = os.path.join(tmpdir, filename)\n try:\n compress_zip(path, folders)\n with open(path+\".zip\", 'rb') as f:\n response = HttpResponse(f.read(), content_type=\"application/octet-stream\")\n response['Content-Disposition'] = 'inline; filename=' + os.path.basename(path)+'.zip'\n return [response, saved_umask, tmpdir]\n except IOError as e:\n print(\"IOError\")\n else:\n shutil.rmtree(tmpdir, ignore_errors=True)\n", "repo_name": "joni2back/angular-filemanager", "sub_path": "bridges/python/django/filemanager_app/filemanager.py", "file_name": "filemanager.py", "file_ext": "py", "file_size_in_byte": 11538, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1750, "dataset": "github-code", "pt": "20", "api": [{"api_name": "datetime.datetime.fromtimestamp", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 13, "usage_type": "attribute"}, {"api_name": "stat.S_ISDIR", "line_number": 18, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 25, "usage_type": "call"}, {"api_name": "zipfile.ZIP_DEFLATED", "line_number": 27, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path", "line_number": 30, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "os.chdir", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "os.walk", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path", "line_number": 36, "usage_type": "attribute"}, {"api_name": "os.path.normpath", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "os.stat", "line_number": 42, "usage_type": "call"}, {"api_name": "stat.S_ISDIR", "line_number": 43, "usage_type": "call"}, {"api_name": "os.walk", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path", "line_number": 55, "usage_type": "attribute"}, {"api_name": "os.chmod", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path", "line_number": 57, "usage_type": "attribute"}, {"api_name": "os.chmod", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path", "line_number": 63, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 67, "usage_type": "call"}, {"api_name": "os.path", "line_number": 67, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path", "line_number": 68, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path", "line_number": 75, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 92, "usage_type": "call"}, {"api_name": "os.path", "line_number": 92, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 93, "usage_type": "call"}, {"api_name": "os.path", "line_number": 93, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 94, "usage_type": "call"}, {"api_name": "os.path", "line_number": 94, "usage_type": "attribute"}, {"api_name": "shutil.move", "line_number": 96, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 105, "usage_type": "call"}, {"api_name": "os.path", "line_number": 105, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path", "line_number": 106, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 107, "usage_type": "call"}, {"api_name": "os.path", "line_number": 107, "usage_type": "attribute"}, {"api_name": "shutil.copyfile", "line_number": 109, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 111, "usage_type": "call"}, {"api_name": "os.path", "line_number": 111, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 113, "usage_type": "call"}, {"api_name": "os.path", "line_number": 113, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 114, "usage_type": "call"}, {"api_name": "os.path", "line_number": 114, "usage_type": "attribute"}, {"api_name": "shutil.copyfile", "line_number": 116, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 125, "usage_type": "call"}, {"api_name": "os.path", "line_number": 125, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 126, "usage_type": "call"}, {"api_name": "os.path", "line_number": 126, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 128, "usage_type": "call"}, {"api_name": "os.path", "line_number": 128, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 129, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 131, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 138, "usage_type": "call"}, {"api_name": "os.path", "line_number": 138, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 150, "usage_type": "call"}, {"api_name": "os.path", "line_number": 150, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 161, "usage_type": "call"}, {"api_name": "os.path", "line_number": 161, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 164, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 171, "usage_type": "call"}, {"api_name": "os.path", "line_number": 171, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 175, "usage_type": "call"}, {"api_name": "os.path", "line_number": 175, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 176, "usage_type": "call"}, {"api_name": "os.path", "line_number": 176, "usage_type": "attribute"}, {"api_name": "shutil.move", "line_number": 178, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 189, "usage_type": "call"}, {"api_name": "os.path", "line_number": 189, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 190, "usage_type": "call"}, {"api_name": "os.path", "line_number": 190, "usage_type": "attribute"}, {"api_name": "os.chmod", "line_number": 195, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 203, "usage_type": "call"}, {"api_name": "os.path", "line_number": 203, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 203, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 208, "usage_type": "call"}, {"api_name": "os.path", "line_number": 208, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 209, "usage_type": "call"}, {"api_name": "os.path", "line_number": 209, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 219, "usage_type": "call"}, {"api_name": "os.path", "line_number": 219, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 220, "usage_type": "call"}, {"api_name": "os.path", "line_number": 220, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 221, "usage_type": "call"}, {"api_name": "os.path", "line_number": 221, "usage_type": "attribute"}, {"api_name": "zipfile.ZipFile", "line_number": 223, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 233, "usage_type": "call"}, {"api_name": "os.path", "line_number": 233, "usage_type": "attribute"}, {"api_name": "django.core.files.storage.FileSystemStorage", "line_number": 236, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 243, "usage_type": "call"}, {"api_name": "os.path", "line_number": 243, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 245, "usage_type": "call"}, {"api_name": "os.path", "line_number": 245, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 249, "usage_type": "call"}, {"api_name": "os.path", "line_number": 249, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 258, "usage_type": "call"}, {"api_name": "os.path", "line_number": 258, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 258, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 259, "usage_type": "call"}, {"api_name": "os.path", "line_number": 259, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 259, "usage_type": "call"}, {"api_name": "tempfile.mkdtemp", "line_number": 262, "usage_type": "call"}, {"api_name": "os.umask", "line_number": 264, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 265, "usage_type": "call"}, {"api_name": "os.path", "line_number": 265, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 270, "usage_type": "call"}, {"api_name": "os.path", "line_number": 270, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 275, "usage_type": "call"}]} +{"seq_id": "6062292078", "text": "'''\nCreated on 2018年7月6日\n\n@author: Administrator\n'''\nfrom PyQt5.QtWidgets import QTableWidget, QHBoxLayout, QWidget, QAbstractItemView, QHeaderView, QPushButton, \\\n QTableWidgetItem, QComboBox, QApplication, QMessageBox\n\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtCore import QAbstractTableModel,Qt,pyqtSignal\nfrom ToolTest_Q.DataManger import MangerData\nfrom ToolTest_Q.GlobalConfig import *\nfrom PyQt5.QtGui import QIcon\nimport re\nimport sys\nfrom ToolTest_Q.CaseData import CaseData\nfrom ToolTest_Q.ImageComparison import Photoshop\nfrom ToolTest_Q.ProcessCalls import Runexe\nimport time\nimport sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom ToolTest_Q.UnitTests import wrapper\nfrom ToolTest_Q.LoggingConfig import logger\n\n\nclass CentralView(QTableWidget):\n cunt = 0\n Screenshotsignalhide=pyqtSignal()\n Screenshotsignalshow=pyqtSignal()\n def __init__(self):\n super(CentralView, self).__init__()\n self.id=None\n self.updatetemp={}\n self.reportdict={}\n self.updatetemp1={}\n self.idlist = []\n self.datalist = []\n self.templist = []\n self.table_widget = QTableWidget()\n self.ExcleView()\n self.ExtensionButton()\n self.table_widget.removeRow(0)\n self.shortcut_init()\n hhbox = QHBoxLayout()\n tab = QtWidgets.QTabWidget()\n tab.addTab(self.table_widget, QIcon(\"Res/open.png\"), \"测试用例\")\n hhbox.addWidget(tab)\n self.setLayout(hhbox)\n\n def shortcut_init(self):\n self.shortcut = QShortcut(QKeySequence(\"Ctrl+h\"), self)\n self.shortcut.activated.connect(self.shortcutprintscreen)\n self.shortcut1 = QShortcut(QKeySequence(\"Ctrl+t\"), self)\n self.shortcut1.activated.connect(self.click_btn)\n def ExcleView(self):\n\n self.exdatalist = []\n model = MyModel()\n self.data = model.data\n self.exdatalist = self.data\n self.row = model.row()\n self.colum = model.colum()\n\n self.table_widget.setRowCount(self.row + 1)\n self.table_widget.setColumnCount(self.colum + 2)\n self.table_widget.setHorizontalHeaderLabels(\n [\"用例编号\", \"用例标题\", \"用例步骤\", \"期望结果\", \"测试人员\", \"备注\", \"状态\", \"附件\"])\n # self.table_widget.setVerticalHeaderLabels(\n # [\"用例编号\", \"用例标题\", \"用例步骤\", \"期望结果\"])\n self.table_widget.setSelectionBehavior(QAbstractItemView.SelectRows)\n self.table_widget.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.table_widget.setMouseTracking(True)\n self.table_widget.setStyleSheet(\"selection-background-color:red\")\n self.table_widget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n self.table_widget.removeRow(self.row - 1)\n\n\n\n for i in range(0, len(self.data), 3):\n b = self.data[i:i + 3]\n self.table_widget.setItem(b[0], b[1],\n QTableWidgetItem(b[2]))\n for i in range(self.row):\n self.idlist.append(\n self.table_widget.item(i, 0).text())\n del self.idlist[0]\n self.templist.extend(self.exdatalist)\n self.datalist = self.templist\n\n return self.idlist\n\n\n def buttonForRow(self):\n\n widget = QWidget()\n RunBtn = QPushButton('运行')\n RunBtn.setStyleSheet(''' text-align : center;\n background-color : NavajoWhite;\n height : 30px;\n border-style: outset;\n font : 13px ''')\n\n RunBtn.clicked.connect(self.SingleRun)\n ScreenBtn = QPushButton('截图')\n ScreenBtn.setStyleSheet(''' text-align : center;\n background-color : DarkSeaGreen;\n height : 30px;\n border-style: outset;\n font : 13px; ''')\n ScreenBtn.clicked.connect(self.printscreen)\n LocationScreenBtn = QPushButton(\"条件截图\",self)\n LocationScreenBtn.setShortcut('Ctrl+L')\n LocationScreenBtn.setStyleSheet(''' text-align : center;\n background-color : LightCoral;\n height : 30px;\n border-style: outset;\n font : 13px; ''')\n LocationScreenBtn.clicked.connect(self.shortcutprintscreen)\n hLayout = QHBoxLayout()\n\n hLayout.addWidget(ScreenBtn)\n hLayout.addWidget(RunBtn)\n hLayout.addWidget(LocationScreenBtn)\n hLayout.setContentsMargins(5, 2, 5, 2)\n widget.setLayout(hLayout)\n\n return widget\n def __translate(self, send,n):\n keyvalue = {}\n list1 = []\n for index, x in enumerate(self.tempid):\n z = re.split(r\", \", x)\n list1.append(z[n])\n del list1[-1]\n Z = dict(zip(list1, self.idlist))\n\n return Z\n @pyqtSlot()\n @wrapper(\"5\")\n def SingleRun(self):\n try:\n _id = set(self.idlist)\n _casedata=CaseData(PATHDATA.get(\"data\"))\n _dir =_casedata._dirset()\n extension=_casedata.key_value()[1]\n report = _casedata.key_value()[2]\n _cha = _id - (_id & _dir)\n if CentralView.cunt == 0:\n if _cha:\n reply = QMessageBox.warning(self, '当前路径下缺失用例名称为:%s' % _cha.pop(),\n \"当前测试用例数据不完整将无法批量执行是否不再提示?\", QMessageBox.Yes |\n QMessageBox.No, QMessageBox.No)\n\n if reply == QMessageBox.Yes:\n CentralView.cunt = 1\n else:\n CentralView.cunt = 0\n else:\n pass\n else:\n pass\n send = self.sender()\n run_idcase = self.__translate(send,2).get(str(send), str(send))\n if str(send) == run_idcase:\n logger.error(\"当前是异常数据项:%s\" % run_idcase)\n else:\n PS=Photoshop(PATHDATA.get(\"data\"))\n time.sleep(0.5)\n self.exe = Runexe(run_idcase)\n self.exe.start()\n time.sleep(3)\n logger.debug(\"正在准备截图存放路径为:%s\"%report.get(run_idcase))\n if report.get(run_idcase)is None:\n logger.error(\"无法在对该测试用例进行截图:%s\"%report.get(run_idcase))\n else:\n PS.Conditions_for_screenshots(address=report.get(run_idcase),box=CASEDATA.get(run_idcase))\n # PS.grab(report.get(run_idcase))\n RT=PS.alignment_section(extension.get(run_idcase),report.get(run_idcase))\n if RT:\n self.reportdict[run_idcase] = \"通过\"\n else:\n self.reportdict[run_idcase] = \"不通过\"\n self.id=run_idcase\n # self.shortcutpng.connect(self.shortcutprintscreen)\n return self.id\n except:\n logger.warning(\"数据无效无法启动\")\n finally:\n listi=[]\n for x in self.idlist:\n self.updatetemp[x][2]=self.reportdict[x]\n listi=listi+self.updatetemp[x]\n self.datalist=self.templist + listi\n\n def printscreen(self):\n try:\n send = self.sender()\n extension_idcase1 = self.__translate(send, 3).get((str(send) + \"]\"), str(send))\n if extension_idcase1 == str(send):\n logger.warning(\"当前是异常数据项:%s\" % extension_idcase1)\n else:\n _casedata = CaseData(PATHDATA.get(\"data\"))\n extension = _casedata.key_value()[1]\n # self.Screenshotsignalhide.emit()\n self.screenshot = Photoshop(PATHDATA.get(\"data\"),address=extension.get(extension_idcase1),\n id=extension_idcase1)\n self.screenshot.showFullScreen()\n logger.info(\"截图完毕,路径下已存在:%s\" % extension.get(extension_idcase1))\n\n except:\n logger.error(\"无法截图\")\n finally:\n # self.Screenshotsignalshow.emit()\n pass\n @pyqtSlot()\n def shortcutprintscreen(self):\n try:\n if type(self.id)is str:\n logger.info(\"正在使用快捷键对运行程序截图:名称为%s的测试用例\"%self.id)\n address=\"%s/%s.extension.png\" % (PATHDATA.get(\"data\"), self.id)\n PS= Photoshop(PATHDATA.get(\"data\"),address=address)\n PS.grab(address)\n except:\n logger.warning(\"目标未启动无法截图\")\n # if self.table_widget.selectedItems()\n # print(self.table_widget.selectedItems()[0].text())\n # print(self.table_widget.itemClicked(self.table_widget.currentItem()))\n def ExtensionButton(self):\n\n self.Defaultlistdata = []\n self.tempid = []\n self.duixiang = {}\n for i in range(self.row):\n self.combox = QComboBox()\n self.combox.addItems([\"通过\", \"不通过\"])\n self.Defaultlistdata.append(i)\n self.Defaultlistdata.append(self.colum)\n self.Defaultlistdata.append(\"通过\")\n self.combox.setStyleSheet(''' text-align : center;\n background-color : green;\n height : 30px;\n border-style: outset;\n font : 13px; ''')\n\n self.table_widget.setCellWidget(i, self.colum, self.combox)\n self.duixiang[self.combox] = \"通过\"\n self.reportdict[self.idlist[i - 1]] = \"通过\"\n self.updatetemp[self.idlist[i - 1]] = [i, self.colum, \"通过\"]\n\n\n self.table_widget.setCellWidget(\n i, self.colum + 1, self.buttonForRow())\n # self.tempid.append(self.buttonForRow().children())\n self.tempid.append(self.buttonForRow().children().__repr__())\n self.combox.currentTextChanged.connect(self.onActivated)\n\n return self.Defaultlistdata\n\n def onActivated(self, x):\n self.listobjx = []\n send = self.sender()\n self.duixiang[send] = x\n xlist = list(self.duixiang.values())\n for i in range(self.row):\n if i == 0:\n pass\n else:\n self.listobjx.append(i)\n self.listobjx.append(self.colum)\n self.listobjx.append(xlist[i])\n self.updatetemp[self.idlist[i - 1]] = [i, self.colum, xlist[i]]\n self.temp = tuple(self.listobjx)\n self.datalist = self.templist + self.listobjx\n return self.datalist\n def idr(self):\n if hasattr(self,\"listobjx\"):\n self.datalist = self.templist + self.listobjx\n for x in self.idlist:\n self.updatetemp[x][2]=self.reportdict[x]\n\n def save_table(self, path):\n logger.info(path)\n try:\n s = MangerData()\n s.SetExcel(location=path, datalist=self.datalist)\n except:\n logger.warning(\"数据异常无法保存\")\n def click_btn(self):\n self.screenshot = Photoshop(\"Res/RE\")\n self.screenshot.showFullScreen()\n\nclass MyModel(QAbstractTableModel):\n def __init__(self):\n super().__init__()\n list1 = []\n list2 = []\n\n\n dizhi = PATHDATA[\"TestCase\"]\n self.data = MangerData().GetExcel(location=dizhi)\n if self.data is None:\n self.data = [\"1\", \"1\", \"\"]\n else:\n for i in range(0, len(self.data), 3):\n b = self.data[i:i + 3]\n list1.append(b[0])\n list2.append(b[1])\n #这里的路径是Excel路基,路径未进行判断\n self.rownew = max(list1)+1\n self.columnew = max(list2) + 1\n\n def row(self):\n return self.rownew\n\n def colum(self):\n return self.columnew\n\n def data(self):\n return self.data\n\n\nif __name__ == '__main__':\n a = QApplication(sys.argv)\n tableView = CentralView()\n\n tableView.show()\n\n a.exec_()\n", "repo_name": "reynold2/testtool", "sub_path": "ToolTest_Q/CentralView.py", "file_name": "CentralView.py", "file_ext": "py", "file_size_in_byte": 12569, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "PyQt5.QtWidgets.QTableWidget", "line_number": 28, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.pyqtSignal", "line_number": 30, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.pyqtSignal", "line_number": 31, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTableWidget", "line_number": 41, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QHBoxLayout", "line_number": 46, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QTabWidget", "line_number": 47, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 47, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 48, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAbstractItemView.SelectRows", "line_number": 72, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QAbstractItemView", "line_number": 72, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QAbstractItemView.NoEditTriggers", "line_number": 73, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QAbstractItemView", "line_number": 73, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QHeaderView.Stretch", "line_number": 76, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QHeaderView", "line_number": 76, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QTableWidgetItem", "line_number": 84, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 97, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 98, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 106, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 113, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QHBoxLayout", "line_number": 121, "usage_type": "call"}, {"api_name": "re.split", "line_number": 134, "usage_type": "call"}, {"api_name": "ToolTest_Q.CaseData.CaseData", "line_number": 145, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.warning", "line_number": 152, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 152, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Yes", "line_number": 153, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 153, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.No", "line_number": 154, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 154, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Yes", "line_number": 156, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 156, "usage_type": "name"}, {"api_name": "ToolTest_Q.LoggingConfig.logger.error", "line_number": 167, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger", "line_number": 167, "usage_type": "name"}, {"api_name": "ToolTest_Q.ImageComparison.Photoshop", "line_number": 169, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 170, "usage_type": "call"}, {"api_name": "ToolTest_Q.ProcessCalls.Runexe", "line_number": 171, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 173, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger.debug", "line_number": 174, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger", "line_number": 174, "usage_type": "name"}, {"api_name": "ToolTest_Q.LoggingConfig.logger.error", "line_number": 176, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger", "line_number": 176, "usage_type": "name"}, {"api_name": "ToolTest_Q.LoggingConfig.logger.warning", "line_number": 189, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger", "line_number": 189, "usage_type": "name"}, {"api_name": "ToolTest_Q.UnitTests.wrapper", "line_number": 141, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger.warning", "line_number": 202, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger", "line_number": 202, "usage_type": "name"}, {"api_name": "ToolTest_Q.CaseData.CaseData", "line_number": 204, "usage_type": "call"}, {"api_name": "ToolTest_Q.ImageComparison.Photoshop", "line_number": 207, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger.info", "line_number": 210, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger", "line_number": 210, "usage_type": "name"}, {"api_name": "ToolTest_Q.LoggingConfig.logger.error", "line_number": 213, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger", "line_number": 213, "usage_type": "name"}, {"api_name": "ToolTest_Q.LoggingConfig.logger.info", "line_number": 221, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger", "line_number": 221, "usage_type": "name"}, {"api_name": "ToolTest_Q.ImageComparison.Photoshop", "line_number": 223, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger.warning", "line_number": 226, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger", "line_number": 226, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QComboBox", "line_number": 236, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger.info", "line_number": 284, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger", "line_number": 284, "usage_type": "name"}, {"api_name": "ToolTest_Q.DataManger.MangerData", "line_number": 286, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger.warning", "line_number": 289, "usage_type": "call"}, {"api_name": "ToolTest_Q.LoggingConfig.logger", "line_number": 289, "usage_type": "name"}, {"api_name": "ToolTest_Q.ImageComparison.Photoshop", "line_number": 291, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QAbstractTableModel", "line_number": 294, "usage_type": "name"}, {"api_name": "ToolTest_Q.DataManger.MangerData", "line_number": 302, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 325, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 325, "usage_type": "attribute"}]} +{"seq_id": "30804605321", "text": "from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.template import RequestContext\nfrom django.template.loader import get_template\nfrom django.views.generic import FormView\n\nfrom weasyprint import HTML\n\nfrom main.forms import SongBookForm, SongBookFormSet\n\n\nfrom django.forms import formset_factory\n\n\nclass SongBookView(FormView):\n \"\"\"Show songbook form.\"\"\"\n\n template_name = 'main/songbook_form.html'\n form_class = SongBookFormSet\n success_url = '/'\n\n def form_valid(self, form):\n html_template = get_template('main/pdf.html')\n context = {}\n context['title'] = form.data['title'] \\\n if 'title' in form.data else None\n context['songs'] = [\n single_form.cleaned_data['song'] for single_form in form\n if 'song' in single_form.cleaned_data]\n rendered_html = html_template.render(\n RequestContext(self.request, context)).encode(encoding=\"UTF-8\")\n pdf_file = HTML(string=rendered_html).write_pdf()\n http_response = HttpResponse(pdf_file, content_type='application/pdf')\n filename = 'songbook.pdf'\n http_response['Content-Disposition'] = 'inline; filename=\"{}\"'.format(\n filename)\n return http_response\n", "repo_name": "Kasilnia/songbook", "sub_path": "main/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1270, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "django.views.generic.FormView", "line_number": 15, "usage_type": "name"}, {"api_name": "main.forms.SongBookFormSet", "line_number": 19, "usage_type": "name"}, {"api_name": "django.template.loader.get_template", "line_number": 23, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 31, "usage_type": "call"}, {"api_name": "weasyprint.HTML", "line_number": 32, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 33, "usage_type": "call"}]} +{"seq_id": "2948278134", "text": "# -*- coding: utf-8 -*-\nfrom scrapy import Spider\n\nfrom ..items import ProxyItemLoader, Proxy\n\n\nclass GouBanJiaSpider(Spider):\n name = 'goubanjia'\n allowed_domains = ['goubanjia.com']\n start_urls = ['http://www.goubanjia.com/index%d.shtml' % i for i in range(1, 11)]\n\n def parse(self, response):\n rows = response.css('div#list > table > tbody > tr')\n proxies = []\n for row in rows:\n loader = ProxyItemLoader(item=Proxy(), selector=row)\n ip_port_texts = row.css('td:nth-child(1) > *:not([style*=\"display: none;\"])::text').extract()\n loader.add_value('ip_address', ''.join(ip_port_texts[:-1]))\n loader.add_value('port', ip_port_texts[-1])\n proxy_type = row.css('td:nth-child(4)::text').extract()\n loader.add_value('proxy_type', proxy_type)\n proxies.append(loader.load_item())\n return proxies\n", "repo_name": "ezirmusitua/pmp", "sub_path": "spider/proxy_crawler/spiders/goubanjia.py", "file_name": "goubanjia.py", "file_ext": "py", "file_size_in_byte": 907, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "scrapy.Spider", "line_number": 7, "usage_type": "name"}, {"api_name": "items.ProxyItemLoader", "line_number": 16, "usage_type": "call"}, {"api_name": "items.Proxy", "line_number": 16, "usage_type": "call"}]} +{"seq_id": "3403719345", "text": "from django.shortcuts import render, redirect\nfrom .models import EmployeeData\n\n\n# Create your views here.\n\n\n\ndef IndexView(request):\n if request.method=='POST':\n model = EmployeeData()\n model.emp_name = request.POST['emp_name']\n model.emp_address = request.POST['emp_address']\n model.emp_salary = request.POST['emp_salary']\n model.save() \n return redirect('index') \n else:\n data = EmployeeData.objects.all()\n context = {\n 'data' : data\n }\n return render(request,'index.html', context)\n\ndef DeleteView(request, id):\n data = EmployeeData.objects.get(id = id)\n data.delete()\n return redirect('index')\n\ndef EditView(request, id):\n data = EmployeeData.objects.get(id = id)\n if request.method=='POST':\n data.emp_name = request.POST['emp_name']\n data.emp_address = request.POST['emp_address']\n data.emp_salary = request.POST['emp_salary']\n data.save() \n return redirect('index') \n context = {\n 'data' : data\n }\n return render(request, 'edit.html', context)\n\n", "repo_name": "krupalatitude/CRUD-", "sub_path": "app1/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1109, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "models.EmployeeData", "line_number": 11, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 16, "usage_type": "call"}, {"api_name": "models.EmployeeData.objects.all", "line_number": 18, "usage_type": "call"}, {"api_name": "models.EmployeeData.objects", "line_number": 18, "usage_type": "attribute"}, {"api_name": "models.EmployeeData", "line_number": 18, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 22, "usage_type": "call"}, {"api_name": "models.EmployeeData.objects.get", "line_number": 25, "usage_type": "call"}, {"api_name": "models.EmployeeData.objects", "line_number": 25, "usage_type": "attribute"}, {"api_name": "models.EmployeeData", "line_number": 25, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 27, "usage_type": "call"}, {"api_name": "models.EmployeeData.objects.get", "line_number": 30, "usage_type": "call"}, {"api_name": "models.EmployeeData.objects", "line_number": 30, "usage_type": "attribute"}, {"api_name": "models.EmployeeData", "line_number": 30, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 36, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 40, "usage_type": "call"}]} +{"seq_id": "40432521609", "text": "from torch.nn import Module\nimport torch\nfrom helper.utils import mkdirs\nfrom helper.utils import pathjoin\nimport time\n\n\nclass ModelSaver(object):\n\n def __init__(self,save_interval,save_dir_path=None,save_base_name:str ='model'):\n self.__timer = 0\n self.__save_interval = save_interval\n self.__save_dir_path = save_dir_path\n if self.__save_dir_path is None:\n self.__save_dir_path = pathjoin(\n '../',\n time.strftime(\"%F %H-%M-%S\",time.localtime())\n )\n mkdirs(self.__save_dir_path)\n self.__base_model_name = save_base_name\n self.__interval_timer = 0\n\n\n def __call__(self, model:Module, isFinal:bool = False,save_base_name = None,is_add=True):\n if is_add:\n self.__timer += 1\n if self.__timer % self.__save_interval == 0 or isFinal:\n self.__interval_timer += 1\n model_ext_name = 'final' if isFinal else str(self.__interval_timer)\n if save_base_name is None:\n save_base_name = self.__base_model_name\n model_save_path = pathjoin(\n self.__save_dir_path,\n save_base_name+'-'+model_ext_name+'.pth'\n )\n torch.save(model.state_dict(),model_save_path)\n\n", "repo_name": "hb-stone/FC-SOD", "sub_path": "helper/model_saver.py", "file_name": "model_saver.py", "file_ext": "py", "file_size_in_byte": 1284, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 16, "dataset": "github-code", "pt": "20", "api": [{"api_name": "helper.utils.pathjoin", "line_number": 15, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 17, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 17, "usage_type": "call"}, {"api_name": "helper.utils.mkdirs", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 24, "usage_type": "name"}, {"api_name": "helper.utils.pathjoin", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 36, "usage_type": "call"}]} +{"seq_id": "12917157032", "text": "# %%\nimport numpy as np\nimport torch \nfrom torch import nn\n\n# %%\n\nclass Conv_Block(nn.Module):\n def __init__(self, in_channel, output_channel, ksize, stride, padding, upsample=False):\n super(Conv_Block, self).__init__()\n\n if upsample :\n layers = [nn.ConvTranspose2d(in_channel, output_channel, ksize, stride, padding)]\n else :\n layers = [nn.Conv2d(in_channel, output_channel, ksize, stride, padding)]\n \n layers.append(nn.InstanceNorm2d(output_channel, affine=True, track_running_stats=True))\n layers.append(nn.ReLU(True))\n \n self.Block = nn.Sequential(*layers)\n \n def forward(self, x):\n return self.Block(x)\n\nclass Residual_block(nn.Module):\n def __init__(self, in_channel, output_channel):\n super(Residual_block, self).__init__()\n\n self.block = nn.Sequential(\n nn.Conv2d(in_channel, output_channel, 1, 1),\n nn.InstanceNorm2d(output_channel, affine=True, track_running_stats=True),\n nn.ReLU(True),\n nn.Conv2d(output_channel, output_channel, 3, 1, 1),\n nn.InstanceNorm2d(output_channel, affine=True, track_running_stats=True) \n )\n\n def forward(self, x):\n out = x + self.branch1(block)\n return out\n\nclass Generator(nn.Module):\n def __init__(self, in_channel=3, n_domains=3, repeat_num=6):\n super(Generator, self).__init__()\n layers = [\n Conv_Block(in_channel, 64, 7, 1, 3),\n Conv_Block(64, 128, 4, 2, 1),\n Conv_Block(128, 256, 4, 2, 1)\n ]\n\n for _ in range(repeat_num):\n layers.append(Residual_block(256, 256))\n \n layers.append(Conv_Block(256, 128, 4, 2, 1, True))\n layers.append(Conv_Block(128, 64, 4, 2, 1, True))\n \n layers.append(nn.Conv2d(64, in_channel, 7, 1, 3))\n layers.append(nn.Tanh())\n \n self.net = nn.Sequential(*layers)\n\n def forward(self, x):\n out = self.net(x)\n return out\n\nclass Discriminator(nn.Module):\n def __init__(self, img_size=256, in_channel=3, n_domains=3, repeat_num=6):\n super(Discriminator, self).__init__()\n\n layers = []\n\n curr_f, next_f = in_channel, 64\n for _ in range(repeat_num):\n layers.append(nn.Conv2d(curr_f, next_f, 4, 2, 1))\n layers.append(nn.LeakyReLU(0.01, True))\n curr_f, next_f = next_f, next_f*2\n \n k_size = int(img_size / (2**repeat_num))\n self.Stem = nn.Sequential(*layers)\n self.Src = nn.Conv2d(2048, 1, 3, 1, 1)\n self.Cls = nn.Conv2d(2048, n_domains, k_size)\n\n def forward(self, x):\n out = self.Stem(x)\n out_src = self.Src(out)\n out_cls = self.Cls(out)\n return out_src, out_cls.reshape(out_cls.shape[0], out_cls.shape[1])", "repo_name": "jjerry-k/StarGAN_Collection", "sub_path": "V1/model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 2855, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "torch.nn.Module", "line_number": 8, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 8, "usage_type": "name"}, {"api_name": "torch.nn.ConvTranspose2d", "line_number": 13, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 13, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 15, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 15, "usage_type": "name"}, {"api_name": "torch.nn.InstanceNorm2d", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 17, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 18, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 18, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 25, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 25, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 29, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 30, "usage_type": "name"}, {"api_name": "torch.nn.InstanceNorm2d", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 31, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 33, "usage_type": "name"}, {"api_name": "torch.nn.InstanceNorm2d", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 34, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 41, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 41, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 56, "usage_type": "name"}, {"api_name": "torch.nn.Tanh", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 57, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 59, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 65, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 65, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 73, "usage_type": "name"}, {"api_name": "torch.nn.LeakyReLU", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 74, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 78, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 79, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 79, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 80, "usage_type": "name"}]} +{"seq_id": "29968136287", "text": "from django.shortcuts import render, get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom .models import OrderProduct, ShoppingCart\nfrom .decorators import check_group\n# Create your views here.\n\n\n@login_required\ndef index(request):\n context = {}\n return render(request, 'eshop/index.html', context)\n\n\n@login_required\ndef customerProductDetail(request):\n\n user = request.user\n shopping_cart = get_object_or_404(\n ShoppingCart, buyer=user, completed=False)\n\n context = {'shoppingCartID': shopping_cart.id}\n\n return render(request, 'eshop/customerproductdetail.html', context)\n\n\n@login_required\ndef customerShoppingCart(request):\n user = request.user\n shopping_cart = get_object_or_404(\n ShoppingCart, buyer=user, completed=False)\n\n context = {'shoppingCartID': shopping_cart.id}\n\n return render(request, 'eshop/shopping-cart.html', context)\n\n\n@login_required\ndef checkout(request):\n user = request.user\n shopping_cart = get_object_or_404(\n ShoppingCart, buyer=user, completed=False)\n\n context = {'shoppingCartID': shopping_cart.id}\n\n return render(request, 'eshop/checkout.html', context)\n\n\n#### Seller views ####\n@login_required\n# @check_group(\"seller\")\ndef add_product(request):\n context = {}\n return render(request, 'eshop/create-product.html', context)\n\n\n@login_required\n@check_group(\"seller\")\ndef update_product(request):\n pass\n\n\n@login_required\n@check_group(\"seller\")\ndef delete_product(request):\n pass\n", "repo_name": "otoxiep95/django-exam-ebay", "sub_path": "eshop/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1510, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "django.shortcuts.render", "line_number": 11, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 8, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 18, "usage_type": "call"}, {"api_name": "models.ShoppingCart", "line_number": 19, "usage_type": "argument"}, {"api_name": "django.shortcuts.render", "line_number": 23, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 14, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 29, "usage_type": "call"}, {"api_name": "models.ShoppingCart", "line_number": 30, "usage_type": "argument"}, {"api_name": "django.shortcuts.render", "line_number": 34, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 26, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 40, "usage_type": "call"}, {"api_name": "models.ShoppingCart", "line_number": 41, "usage_type": "argument"}, {"api_name": "django.shortcuts.render", "line_number": 45, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 37, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 53, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 49, "usage_type": "name"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 56, "usage_type": "name"}, {"api_name": "decorators.check_group", "line_number": 57, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 62, "usage_type": "name"}, {"api_name": "decorators.check_group", "line_number": 63, "usage_type": "call"}]} +{"seq_id": "17240065037", "text": "#!/usr/bin/env python\n#\n# Server that will accept connections from a Vim channel.\n# Used by test_channel.vim to test LSP functionality.\n#\n# This requires Python 2.6 or later.\n\nfrom __future__ import print_function\nimport json\nimport socket\nimport sys\nimport time\nimport threading\n\ntry:\n # Python 3\n import socketserver\nexcept ImportError:\n # Python 2\n import SocketServer as socketserver\n\nclass ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):\n\n def setup(self):\n self.request.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)\n\n def debuglog(self, msg):\n if self.debug:\n with open(\"Xlspserver.log\", \"a\") as myfile:\n myfile.write(msg)\n\n def send_lsp_req(self, msgid, method, params):\n v = {'jsonrpc': '2.0', 'id': msgid, 'method': method}\n if len(params) != 0:\n v['params'] = params\n s = json.dumps(v)\n req = \"Content-Length: \" + str(len(s)) + \"\\r\\n\"\n req += \"Content-Type: application/vscode-jsonrpc; charset=utf-8\\r\\n\"\n req += \"\\r\\n\"\n req += s\n if self.debug:\n self.debuglog(\"SEND: ({0} bytes) '{1}'\\n\".format(len(req), req))\n self.request.sendall(req.encode('utf-8'))\n\n def send_lsp_resp(self, msgid, resp_dict):\n v = {'jsonrpc': '2.0', 'result': resp_dict}\n if msgid != -1:\n v['id'] = msgid\n s = json.dumps(v)\n resp = \"Content-Length: \" + str(len(s)) + \"\\r\\n\"\n resp += \"Content-Type: application/vscode-jsonrpc; charset=utf-8\\r\\n\"\n resp += \"\\r\\n\"\n resp += s\n if self.debug:\n self.debuglog(\"SEND: ({0} bytes) '{1}'\\n\".format(len(resp), resp))\n self.request.sendall(resp.encode('utf-8'))\n\n def send_wrong_payload(self):\n v = 'wrong-payload'\n s = json.dumps(v)\n resp = \"Content-Length: \" + str(len(s)) + \"\\r\\n\"\n resp += \"Content-Type: application/vscode-jsonrpc; charset=utf-8\\r\\n\"\n resp += \"\\r\\n\"\n resp += s\n self.request.sendall(resp.encode('utf-8'))\n\n def send_empty_header(self, msgid, resp_dict):\n v = {'jsonrpc': '2.0', 'id': msgid, 'result': resp_dict}\n s = json.dumps(v)\n resp = \"\\r\\n\"\n resp += s\n self.request.sendall(resp.encode('utf-8'))\n\n def send_empty_payload(self):\n resp = \"Content-Length: 0\\r\\n\"\n resp += \"Content-Type: application/vscode-jsonrpc; charset=utf-8\\r\\n\"\n resp += \"\\r\\n\"\n self.request.sendall(resp.encode('utf-8'))\n\n def send_extra_hdr_fields(self, msgid, resp_dict):\n # test for sending extra fields in the http header\n v = {'jsonrpc': '2.0', 'id': msgid, 'result': resp_dict}\n s = json.dumps(v)\n resp = \"Host: abc.vim.org\\r\\n\"\n resp += \"User-Agent: Python\\r\\n\"\n resp += \"Accept-Language: en-US,en\\r\\n\"\n resp += \"Content-Type: application/vscode-jsonrpc; charset=utf-8\\r\\n\"\n resp += \"Content-Length: \" + str(len(s)) + \"\\r\\n\"\n resp += \"\\r\\n\"\n resp += s\n self.request.sendall(resp.encode('utf-8'))\n\n def send_delayed_payload(self, msgid, resp_dict):\n # test for sending the hdr first and then after some delay, send the\n # payload\n v = {'jsonrpc': '2.0', 'id': msgid, 'result': resp_dict}\n s = json.dumps(v)\n resp = \"Content-Length: \" + str(len(s)) + \"\\r\\n\"\n resp += \"\\r\\n\"\n self.request.sendall(resp.encode('utf-8'))\n time.sleep(0.05)\n resp = s\n self.request.sendall(resp.encode('utf-8'))\n\n def send_hdr_without_len(self, msgid, resp_dict):\n # test for sending the http header without length\n v = {'jsonrpc': '2.0', 'id': msgid, 'result': resp_dict}\n s = json.dumps(v)\n resp = \"Content-Type: application/vscode-jsonrpc; charset=utf-8\\r\\n\"\n resp += \"\\r\\n\"\n resp += s\n self.request.sendall(resp.encode('utf-8'))\n\n def send_hdr_with_wrong_len(self, msgid, resp_dict):\n # test for sending the http header with wrong length\n v = {'jsonrpc': '2.0', 'id': msgid, 'result': resp_dict}\n s = json.dumps(v)\n resp = \"Content-Length: 1000\\r\\n\"\n resp += \"\\r\\n\"\n resp += s\n self.request.sendall(resp.encode('utf-8'))\n\n def send_hdr_with_negative_len(self, msgid, resp_dict):\n # test for sending the http header with negative length\n v = {'jsonrpc': '2.0', 'id': msgid, 'result': resp_dict}\n s = json.dumps(v)\n resp = \"Content-Length: -1\\r\\n\"\n resp += \"\\r\\n\"\n resp += s\n self.request.sendall(resp.encode('utf-8'))\n\n def do_ping(self, payload):\n time.sleep(0.2)\n self.send_lsp_resp(payload['id'], 'alive')\n\n def do_echo(self, payload):\n self.send_lsp_resp(-1, payload)\n\n def do_simple_rpc(self, payload):\n # test for a simple RPC request\n self.send_lsp_resp(payload['id'], 'simple-rpc')\n\n def do_rpc_with_notif(self, payload):\n # test for sending a notification before replying to a request message\n self.send_lsp_resp(-1, 'rpc-with-notif-notif')\n # sleep for some time to make sure the notification is delivered\n time.sleep(0.2)\n self.send_lsp_resp(payload['id'], 'rpc-with-notif-resp')\n\n def do_wrong_payload(self, payload):\n # test for sending a non dict payload\n self.send_wrong_payload()\n time.sleep(0.2)\n self.send_lsp_resp(-1, 'wrong-payload')\n\n def do_large_payload(self, payload):\n # test for sending a large (> 64K) payload\n self.send_lsp_resp(payload['id'], payload)\n\n def do_rpc_resp_incorrect_id(self, payload):\n self.send_lsp_resp(-1, 'rpc-resp-incorrect-id-1')\n self.send_lsp_resp(-1, 'rpc-resp-incorrect-id-2')\n self.send_lsp_resp(1, 'rpc-resp-incorrect-id-3')\n time.sleep(0.2)\n self.send_lsp_resp(payload['id'], 'rpc-resp-incorrect-id-4')\n\n def do_simple_notif(self, payload):\n # notification message test\n self.send_lsp_resp(-1, 'simple-notif')\n\n def do_multi_notif(self, payload):\n # send multiple notifications\n self.send_lsp_resp(-1, 'multi-notif1')\n self.send_lsp_resp(-1, 'multi-notif2')\n\n def do_msg_with_id(self, payload):\n self.send_lsp_resp(payload['id'], 'msg-with-id')\n\n def do_msg_specific_cb(self, payload):\n self.send_lsp_resp(payload['id'], 'msg-specific-cb')\n\n def do_server_req(self, payload):\n self.send_lsp_resp(201, {'method': 'checkhealth', 'params': {'a': 20}})\n\n def do_extra_hdr_fields(self, payload):\n self.send_extra_hdr_fields(payload['id'], 'extra-hdr-fields')\n\n def do_delayed_payload(self, payload):\n self.send_delayed_payload(payload['id'], 'delayed-payload')\n\n def do_hdr_without_len(self, payload):\n self.send_hdr_without_len(payload['id'], 'hdr-without-len')\n\n def do_hdr_with_wrong_len(self, payload):\n self.send_hdr_with_wrong_len(payload['id'], 'hdr-with-wrong-len')\n\n def do_hdr_with_negative_len(self, payload):\n self.send_hdr_with_negative_len(payload['id'], 'hdr-with-negative-len')\n\n def do_empty_header(self, payload):\n self.send_empty_header(payload['id'], 'empty-header')\n\n def do_empty_payload(self, payload):\n self.send_empty_payload()\n\n def do_server_req_in_middle(self, payload):\n # Send a notification message to the client in the middle of processing\n # a request message from the client\n self.send_lsp_req(-1, 'server-req-in-middle', {'text': 'server-notif'})\n # Send a request message to the client in the middle of processing a\n # request message from the client.\n self.send_lsp_req(payload['id'], 'server-req-in-middle', {'text': 'server-req'})\n\n def do_server_req_in_middle_resp(self, payload):\n # After receiving a response from the client send the response to the\n # client request.\n self.send_lsp_resp(payload['id'], {'text': 'server-resp'})\n\n def process_msg(self, msg):\n try:\n decoded = json.loads(msg)\n if 'method' in decoded:\n test_map = {\n 'ping': self.do_ping,\n 'echo': self.do_echo,\n 'simple-rpc': self.do_simple_rpc,\n 'rpc-with-notif': self.do_rpc_with_notif,\n 'wrong-payload': self.do_wrong_payload,\n 'large-payload': self.do_large_payload,\n 'rpc-resp-incorrect-id': self.do_rpc_resp_incorrect_id,\n 'simple-notif': self.do_simple_notif,\n 'multi-notif': self.do_multi_notif,\n 'msg-with-id': self.do_msg_with_id,\n 'msg-specific-cb': self.do_msg_specific_cb,\n 'server-req': self.do_server_req,\n 'extra-hdr-fields': self.do_extra_hdr_fields,\n 'delayed-payload': self.do_delayed_payload,\n 'hdr-without-len': self.do_hdr_without_len,\n 'hdr-with-wrong-len': self.do_hdr_with_wrong_len,\n 'hdr-with-negative-len': self.do_hdr_with_negative_len,\n 'empty-header': self.do_empty_header,\n 'empty-payload': self.do_empty_payload,\n 'server-req-in-middle': self.do_server_req_in_middle,\n 'server-req-in-middle-resp': self.do_server_req_in_middle_resp,\n }\n if decoded['method'] in test_map:\n test_map[decoded['method']](decoded)\n else:\n self.debuglog(\"Error: Unsupported method - \" + decoded['method'] + \"\\n\")\n else:\n self.debuglog(\"Error: 'method' field is not found\\n\")\n\n except ValueError:\n self.debuglog(\"Error: json decoding failed\\n\")\n\n def process_msgs(self, msgbuf):\n while True:\n sidx = msgbuf.find('Content-Length: ')\n if sidx == -1:\n # partial message received\n return msgbuf\n sidx += 16\n eidx = msgbuf.find('\\r\\n')\n if eidx == -1:\n # partial message received\n return msgbuf\n msglen = int(msgbuf[sidx:eidx])\n\n hdrend = msgbuf.find('\\r\\n\\r\\n')\n if hdrend == -1:\n # partial message received\n return msgbuf\n\n if msglen > len(msgbuf[hdrend + 4:]):\n if self.debug:\n self.debuglog(\"Partial message ({0} bytes)\\n\".format(len(msgbuf)))\n # partial message received\n return msgbuf\n\n if self.debug:\n self.debuglog(\"Complete message ({0} bytes) received\\n\".format(msglen))\n\n # Remove the header\n msgbuf = msgbuf[hdrend + 4:]\n payload = msgbuf[:msglen]\n\n self.process_msg(payload)\n\n # Remove the processed message\n msgbuf = msgbuf[msglen:]\n\n def handle(self):\n self.debug = False\n self.debuglog(\"=== socket opened ===\\n\")\n msgbuf = ''\n while True:\n try:\n received = self.request.recv(4096).decode('utf-8')\n except socket.error:\n self.debuglog(\"=== socket error ===\\n\")\n break\n except IOError:\n self.debuglog(\"=== socket closed ===\\n\")\n break\n if received == '':\n self.debuglog(\"=== socket closed ===\\n\")\n break\n\n # Write the received lines into the file for debugging\n if self.debug:\n self.debuglog(\"RECV: ({0} bytes) '{1}'\\n\".format(len(received), received))\n\n # Can receive more than one line in a response or a partial line.\n # Accumulate all the received characters and process one line at\n # a time.\n msgbuf += received\n msgbuf = self.process_msgs(msgbuf)\n\nclass ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):\n pass\n\ndef writePortInFile(port):\n # Write the port number in Xportnr, so that the test knows it.\n f = open(\"Xportnr\", \"w\")\n f.write(\"{0}\".format(port))\n f.close()\n\ndef main(host, port, server_class=ThreadedTCPServer):\n # Wait half a second before opening the port to test waittime in ch_open().\n # We do want to get the port number, get that first. We cannot open the\n # socket, guess a port is free.\n if len(sys.argv) >= 2 and sys.argv[1] == 'delay':\n port = 13684\n writePortInFile(port)\n time.sleep(0.5)\n\n addrs = socket.getaddrinfo(host, port, 0, 0, socket.IPPROTO_TCP)\n # Each addr is a (family, type, proto, canonname, sockaddr) tuple\n sockaddr = addrs[0][4]\n server_class.address_family = addrs[0][0]\n\n server = server_class(sockaddr[0:2], ThreadedTCPRequestHandler)\n ip, port = server.server_address[0:2]\n\n # Start a thread with the server. That thread will then start a new thread\n # for each connection.\n server_thread = threading.Thread(target=server.serve_forever)\n server_thread.start()\n\n writePortInFile(port)\n\n # Main thread terminates, but the server continues running\n # until server.shutdown() is called.\n try:\n while server_thread.is_alive():\n server_thread.join(1)\n except (KeyboardInterrupt, SystemExit):\n server.shutdown()\n\nif __name__ == \"__main__\":\n main(\"localhost\", 0)\n", "repo_name": "vim/vim", "sub_path": "src/testdir/test_channel_lsp.py", "file_name": "test_channel_lsp.py", "file_ext": "py", "file_size_in_byte": 13586, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 33476, "dataset": "github-code", "pt": "20", "api": [{"api_name": "SocketServer.BaseRequestHandler", "line_number": 22, "usage_type": "attribute"}, {"api_name": "socket.IPPROTO_TCP", "line_number": 25, "usage_type": "attribute"}, {"api_name": "socket.TCP_NODELAY", "line_number": 25, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 36, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 49, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 60, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 69, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 83, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 97, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 101, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 108, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 117, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 126, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 133, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 147, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 153, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 164, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 221, "usage_type": "call"}, {"api_name": "socket.error", "line_number": 299, "usage_type": "attribute"}, {"api_name": "SocketServer.ThreadingMixIn", "line_number": 319, "usage_type": "attribute"}, {"api_name": "SocketServer.TCPServer", "line_number": 319, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 332, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 335, "usage_type": "call"}, {"api_name": "socket.getaddrinfo", "line_number": 337, "usage_type": "call"}, {"api_name": "socket.IPPROTO_TCP", "line_number": 337, "usage_type": "attribute"}, {"api_name": "threading.Thread", "line_number": 347, "usage_type": "call"}]} +{"seq_id": "37518143153", "text": "from django.db import models\nfrom django.contrib.auth.models import AbstractUser, BaseUserManager\n\n# Create your models here.\n# m > a > f > v > u\n\nclass User(AbstractUser):\n name = models.CharField(max_length=200, null=True, unique=True)\n email = models.EmailField(unique=True, null=True)\n bio = models.TextField(null=True, blank=True)\n\n avatar = models.ImageField(null=True, default=\"avatar.jpg\")\n\n USERNAME_FIELD = 'name'\n REQUIRED_FIELDS = ['username']\n\n\nclass Genre(models.Model):\n name = models.CharField(max_length=200)\n\n def __str__(self):\n return self.name\n\n\nclass Picture(models.Model):\n host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)\n genre = models.ForeignKey(Genre, on_delete=models.SET_NULL, null=True)\n name = models.CharField(max_length=200)\n image = models.ImageField(upload_to='post_images/', null=True, blank=False)\n description = models.TextField(null=True, blank=True)\n # participant\n likes = models.ManyToManyField(User, related_name='liked_posts', blank=True)\n updated = models.DateTimeField(auto_now=True)\n created = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n ordering = ['-updated', '-created']\n \n def __str__(self):\n return self.name\n \n\nclass Like(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n picture = models.ForeignKey(Picture, on_delete=models.CASCADE)\n\n def __str__(self):\n return f\"{self.user.name} likes {self.picture.name}\"\n\n\nclass Comment(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n picture = models.ForeignKey(Picture, on_delete=models.CASCADE)\n body = models.TextField()\n updated = models.DateTimeField(auto_now=True)\n created = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n ordering = ['-updated', '-created']\n\n def __str__(self):\n return self.body", "repo_name": "phamminh12/ArtOne", "sub_path": "base/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 1921, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "django.contrib.auth.models.AbstractUser", "line_number": 7, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 8, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 8, "usage_type": "name"}, {"api_name": "django.db.models.EmailField", "line_number": 9, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 9, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 10, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 10, "usage_type": "name"}, {"api_name": "django.db.models.ImageField", "line_number": 12, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 12, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 18, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 18, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 19, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 25, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 25, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 26, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 26, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 26, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 27, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 27, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 27, "usage_type": "attribute"}, {"api_name": "django.db.models.CharField", "line_number": 28, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 28, "usage_type": "name"}, {"api_name": "django.db.models.ImageField", "line_number": 29, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 29, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 30, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 30, "usage_type": "name"}, {"api_name": "django.db.models.ManyToManyField", "line_number": 32, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 32, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 33, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 33, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 34, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 34, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 43, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 43, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 44, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 44, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 44, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 45, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 45, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 45, "usage_type": "attribute"}, {"api_name": "django.db.models.Model", "line_number": 51, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 51, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 52, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 52, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 52, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 53, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 53, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 53, "usage_type": "attribute"}, {"api_name": "django.db.models.TextField", "line_number": 54, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 54, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 55, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 55, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 56, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 56, "usage_type": "name"}]} +{"seq_id": "21824599932", "text": "import os\nimport folium\nimport confuse\nimport numpy as np\nfrom math import isnan\nimport geopandas as gpd\nfrom shapely.geometry import Point\nfrom PIL import Image\nfrom tqdm import tqdm\n\n# Initialzie custom basemaps for folium\nbasemaps = {\n 'Google Maps': folium.TileLayer(\n tiles = 'https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',\n attr = 'Google',\n name = 'Google Maps',\n overlay = True,\n control = True\n ),\n 'Google Satellite': folium.TileLayer(\n tiles = 'https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',\n attr = 'Google',\n name = 'Google Satellite',\n overlay = True,\n control = True\n ),\n 'Google Terrain': folium.TileLayer(\n tiles = 'https://mt1.google.com/vt/lyrs=p&x={x}&y={y}&z={z}',\n attr = 'Google',\n name = 'Google Terrain',\n overlay = True,\n control = True\n ),\n 'Google Satellite Hybrid': folium.TileLayer(\n tiles = 'https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}',\n attr = 'Google',\n name = 'Google Satellite',\n overlay = True,\n control = True\n ),\n 'Esri Satellite': folium.TileLayer(\n tiles = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',\n attr = 'Esri',\n name = 'Esri Satellite',\n overlay = True,\n control = True\n ),\n 'openstreetmap': folium.TileLayer('openstreetmap'),\n 'cartodbdark_matter': folium.TileLayer('cartodbdark_matter')\n}\n\n\n# Dictionary of JavaScript files (More Readable)\nscripts_dir = './scripts/'\nscripts_files = [f for f in os.listdir(scripts_dir) if f.endswith('.js')]\nScripts = {}\nfor f in scripts_files:\n key = f.split('.')[0].upper()\n with open(scripts_dir + f) as f:\n Scripts[key] = f.read()\n\ndef calculate_bbox(df, field):\n '''\n Calculate the bounding box of a specfic field ID in a given data frame\n '''\n field = int(field)\n bbox = df.loc[df['Field_Id'] == field].bounds\n r = bbox.iloc[0]\n return [r.minx, r.miny, r.maxx, r.maxy]\n\ndef tiff_to_geodataframe(im, metric, date, crs):\n '''\n Convert a tiff image to a geodataframe\n '''\n x_cords = im.coords['x'].values\n y_cords = im.coords['y'].values\n vals = im.values\n dims = vals.shape\n points = []\n v_s = []\n for lat in range(dims[1]):\n y = y_cords[lat]\n for lon in range(dims[2]):\n x = x_cords[lon]\n v = vals[:,lat,lon]\n if isnan(v[0]):\n continue\n points.append(Point(x,y))\n v_s.append(v.item()) \n d = {f'{metric}_{date}': v_s, 'geometry': points} \n df = gpd.GeoDataFrame(d, crs = crs)\n return df\n\ndef get_bearer_token_headers(bearer_token):\n '''\n Get the bearer token headers to be used in the request to the SentinelHub API\n '''\n headers = {\n 'Content-Type': 'application/json',\n 'Authorization': 'Bearer '+ bearer_token,\n }\n return headers\n\ndef get_downloaded_location_img_path(clientName, metric, date, field, extension='tiff'):\n '''\n Get the path of the downloaded image in TIFF based on the:\n '''\n date_dir = f'./{clientName}/raw/{metric}/{date}/field_{field}/'\n print(f'True Color Date Dir: {date_dir}')\n os.makedirs(date_dir, exist_ok=True)\n intermediate_dirs = os.listdir(date_dir)\n print(f'Intermediate Dirs: {intermediate_dirs}')\n if len(intermediate_dirs) == 0:\n return None\n imagePath = f'{date_dir}{os.listdir(date_dir)[0]}/response.{extension}'\n print(f'Image Path: {imagePath}')\n if not os.path.exists(imagePath):\n return None\n print(f'Image Path: {imagePath}')\n return imagePath\n\ndef get_masked_location_img_path(clientName, metric, date, field):\n '''\n Get the path of the downloaded image after applying the mask in TIFF based on the:\n '''\n date_dir = f'./{clientName}/processed/{metric}/{date}/field_{field}/'\n imagePath = date_dir + 'masked.tiff'\n return imagePath\n\ndef get_curated_location_img_path(clientName, metric, date, field):\n '''\n Get the path of the downloaded image after applying the mask and converting it to geojson formay based on the:\n '''\n date_dir = f'./{clientName}/curated/{metric}/{date}/field_{field}/'\n imagePath = date_dir + 'masked.geojson'\n\n if os.path.exists(imagePath):\n return imagePath\n else:\n return None\n\ndef parse_app_config(path=r'config-fgm-dev.yaml'):\n config = confuse.Configuration('CropHealth', __name__)\n config.set_file(path)\n return config\n\n\ndef fix_image(img):\n def normalize(band):\n band_min, band_max = (band.min(), band.max())\n return ((band-band_min)/((band_max - band_min)))\n def brighten(band):\n alpha=3\n beta=0\n return np.clip(alpha*band+beta, 0,255)\n def gammacorr(band):\n gamma=0.9\n return np.power(band, 1/gamma)\n red = img[:, :, 0]\n green = img[:, :, 1]\n blue = img[:, :, 2]\n red_b=brighten(red)\n blue_b=brighten(blue)\n green_b=brighten(green)\n red_bg=gammacorr(red_b)\n blue_bg=gammacorr(blue_b)\n green_bg=gammacorr(green_b)\n red_bgn = normalize(red_bg)\n green_bgn = normalize(green_bg)\n blue_bgn = normalize(blue_bg)\n rgb_composite_bgn= np.dstack((red_b, green_b, blue_b))\n return rgb_composite_bgn\n\n\ndef creat_gif(dataset, gif_name, duration=50):\n '''\n Create a gif from a list of images\n '''\n imgs = [Image.fromarray((255*img).astype(np.uint8)) for img in dataset]\n # duration is the number of milliseconds between frames; this is 40 frames per second\n imgs[0].save(gif_name, save_all=True, append_images=imgs[1:], duration=duration, loop=1)\n\n\ndef add_lat_lon_to_gdf_from_geometry(gdf):\n gdf['Lat'] = gdf['geometry'].apply(lambda p: p.x)\n gdf['Lon'] = gdf['geometry'].apply(lambda p: p.y)\n return gdf\n\ndef gdf_column_to_one_band_array(gdf, column_name):\n gdf = gdf.sort_values(by=['Lat', 'Lon'])\n gdf = gdf.reset_index(drop=True)\n unique_lats_count = gdf['Lat'].nunique()\n unique_lons_count = gdf['Lon'].nunique()\n rows_arr = [[] for i in range(unique_lats_count)]\n column_values = gdf[column_name].values\n for i in tqdm(range(len(column_values))):\n row_index = i // unique_lons_count\n rows_arr[row_index].append(column_values[i])\n\n max_row_length = max([len(row) for row in rows_arr])\n for row in rows_arr:\n while len(row) < max_row_length:\n row.append(0)\n\n rows_arr = np.array(rows_arr)\n return rows_arr", "repo_name": "ammarnasr/satellite-crop-monitoring", "sub_path": "utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 6539, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "folium.TileLayer", "line_number": 13, "usage_type": "call"}, {"api_name": "folium.TileLayer", "line_number": 20, "usage_type": "call"}, {"api_name": "folium.TileLayer", "line_number": 27, "usage_type": "call"}, {"api_name": "folium.TileLayer", "line_number": 34, "usage_type": "call"}, {"api_name": "folium.TileLayer", "line_number": 41, "usage_type": "call"}, {"api_name": "folium.TileLayer", "line_number": 48, "usage_type": "call"}, {"api_name": "folium.TileLayer", "line_number": 49, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 55, "usage_type": "call"}, {"api_name": "math.isnan", "line_number": 86, "usage_type": "call"}, {"api_name": "shapely.geometry.Point", "line_number": 88, "usage_type": "call"}, {"api_name": "geopandas.GeoDataFrame", "line_number": 91, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 110, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 111, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 115, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 117, "usage_type": "call"}, {"api_name": "os.path", "line_number": 117, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 137, "usage_type": "call"}, {"api_name": "os.path", "line_number": 137, "usage_type": "attribute"}, {"api_name": "confuse.Configuration", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 158, "usage_type": "call"}, {"api_name": "numpy.dstack", "line_number": 171, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 179, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 179, "usage_type": "name"}, {"api_name": "numpy.uint8", "line_number": 179, "usage_type": "attribute"}, {"api_name": "tqdm.tqdm", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 205, "usage_type": "call"}]} +{"seq_id": "38240542826", "text": "# -*- coding: utf-8 -*-\n\n\"\"\"\n CREATED BY FYMAO,\n email: fymao@zju.edu.cn\n Any question please contact me!\n 2022.6.1, Zhejiang University.\n \"\"\"\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nimport sys\nfrom PyQt5.QtWidgets import *\nfrom OCCAM1D import Ui_OCCAM1D\nfrom OCCAM1DMTpy import Ui_OCCAM1DMTpy\nimport os\n\n\nclass Ui_MainWindow(QWidget):\n def __init__(self):\n super().__init__()\n self.setObjectName(\"MainWindow\")\n self.resize(389, 404)\n self.labelwelcome = QtWidgets.QLabel(self)\n self.labelwelcome.setGeometry(QtCore.QRect(90, 10, 201, 141))\n font = QtGui.QFont()\n font.setPointSize(30)\n self.labelwelcome.setFont(font)\n self.labelwelcome.setFrameShape(QtWidgets.QFrame.NoFrame)\n self.labelwelcome.setTextFormat(QtCore.Qt.AutoText)\n self.labelwelcome.setScaledContents(False)\n self.labelwelcome.setAlignment(QtCore.Qt.AlignCenter)\n self.labelwelcome.setWordWrap(False)\n self.labelwelcome.setOpenExternalLinks(False)\n self.labelwelcome.setObjectName(\"labelwelcome\")\n self.label = QtWidgets.QLabel(self)\n self.label.setGeometry(QtCore.QRect(110, 320, 181, 51))\n self.label.setObjectName(\"label\")\n self.Buttonoccam = QtWidgets.QPushButton(self)\n self.Buttonoccam.setGeometry(QtCore.QRect(80, 160, 231, 31))\n self.Buttonoccam.setObjectName(\"Buttonoccam\")\n self.ButtonMtpy = QtWidgets.QPushButton(self)\n self.ButtonMtpy.setGeometry(QtCore.QRect(80, 210, 231, 31))\n self.ButtonMtpy.setObjectName(\"ButtonMtpy\")\n self.Buttonreadme = QtWidgets.QPushButton(self)\n self.Buttonreadme.setGeometry(QtCore.QRect(80, 260, 231, 31))\n self.Buttonreadme.setObjectName(\"Buttonreadme\")\n\n self.retranslateUi()\n QtCore.QMetaObject.connectSlotsByName(self)\n \n os.chdir(os.path.split(os.path.abspath(sys.argv[0]))[0])\n \"\"\"Button\n \"\"\"\n self.Buttonoccam.clicked.connect(self.occaminv)\n self.Buttonreadme.clicked.connect(self.readme)\n self.ButtonMtpy.clicked.connect(self.occamMtpy)\n\n def retranslateUi(self):\n _translate = QtCore.QCoreApplication.translate\n self.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n self.labelwelcome.setText(_translate(\"MainWindow\", \"MT Series\"))\n self.label.setText(_translate(\"MainWindow\", \"Copyright@MaoFangyuan\"))\n self.Buttonoccam.setText(_translate(\"MainWindow\", \"Occam1D Inversion\"))\n self.ButtonMtpy.setText(_translate(\"MainWindow\", \"MTpy\"))\n self.Buttonreadme.setText(_translate(\"MainWindow\", \"Introduction\"))\n \n def occaminv(self):\n self.uioccam1d = Ui_OCCAM1D()\n self.uioccam1d.show()\n \n def occamMtpy(self):\n self.uioccam1dmtpy = Ui_OCCAM1DMTpy()\n self.uioccam1dmtpy.show()\n \n def readme(self):\n introduction = \"\\\n 请阅读文件夹中的readme !\\n\\\n 有问题请联系 fymao@zju.edu.cn\\n\\\n :)\\\n \"\n QMessageBox.information(\n self, \"提醒\", introduction, \n QMessageBox.Yes, QMessageBox.Yes\n )\n\n\n\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n uimainwindow = Ui_MainWindow()\n uimainwindow.show()\n sys.exit(app.exec_())", "repo_name": "Ferris-geek/OCCAM1D-GUI", "sub_path": "code/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 3335, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 23, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 23, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 24, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 24, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 25, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 25, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFrame", "line_number": 28, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets", "line_number": 28, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 29, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 29, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 31, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 31, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 35, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 35, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 36, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 36, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 38, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 38, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 39, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 39, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 41, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 41, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 42, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 42, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 44, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 44, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QRect", "line_number": 45, "usage_type": "call"}, {"api_name": "PyQt5.QtCore", "line_number": 45, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QMetaObject.connectSlotsByName", "line_number": 49, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QMetaObject", "line_number": 49, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 49, "usage_type": "name"}, {"api_name": "os.chdir", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path.split", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path", "line_number": 51, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 51, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 51, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.QCoreApplication", "line_number": 59, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 59, "usage_type": "name"}, {"api_name": "OCCAM1D.Ui_OCCAM1D", "line_number": 68, "usage_type": "call"}, {"api_name": "OCCAM1DMTpy.Ui_OCCAM1DMTpy", "line_number": 72, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 89, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 89, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 89, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 92, "usage_type": "call"}]} +{"seq_id": "35846585302", "text": "from matplotlib import pyplot as plt\nfrom Tkinter import *\nimport time\nimport math\nimport sys\nmode=int(sys.argv[1])\ntoWrite = False\nif(sys.argv[2] is not None):\n\ttoWrite = sys.argv[2] is \"1\"\ntau=2*math.pi\nnumber=100\nradPerNumber=tau/number\nplt.ion()\nplt.axis('off')\nplt.gca().get_xaxis().set_visible(False)\nplt.gca().get_yaxis().set_visible(False)\n\nif mode==0:\n\troot = Tk()\n\troot.geometry(\"100x100\")\n\te=Entry(root)\n\te.pack()\n\t\n\tdef run():\n\t\tplt.cla()\n\t\tmultiplier=float(e.get())\n\t\tfor i in range(0,number):\n\t\t\tplt.plot([math.cos((radPerNumber*i)),math.cos((radPerNumber*i*multiplier))],[math.sin((radPerNumber*i)),math.sin((radPerNumber*i*multiplier))], color=\"#ea4d13\")\n\t\tplt.show()\n\tdef p1():\n\t\ttmp = float(e.get())\n\t\te.delete(0,len(e.get()))\n\t\te.insert(0, tmp+1)\n\t\trun()\n\tdef m1():\n\t\ttmp = float(e.get())\n\t\te.delete(0,len(e.get()))\n\t\te.insert(0, tmp-1)\n\t\trun()\n\t\n\tbutton=Button(root, text=\"submit\", command=run)\n\tbutton2 = Button(root, text='+1', command=p1)\n\tbutton3 = Button(root, text='-1', command=m1)\n\tbutton.pack()\n\tbutton2.pack()\n\tbutton3.pack()\n\troot.mainloop()\n\nif mode==1:\n\tdef run(multiplier):\n\t\tplt.cla()\n\t\tfor i in range(0,number):\n\t\t\tplt.plot([math.cos((radPerNumber*i)),math.cos((radPerNumber*i*multiplier))],[math.sin((radPerNumber*i)),math.sin((radPerNumber*i*multiplier))], color=\"#ea4d13\")\n\t\tplt.show()\n\t\tif toWrite:\n\t\t\tplt.savefig(\"images/{}.png\".format(multiplier), dpi = 'figure', bbox_inches='tight')\n\n\n\ti=0\n\twhile(i<=100):\n\t\trun(i)\n\t\tprint(i)\n\t\ti+=.1\n\t\tplt.pause(.01)\n\t\tif i == 100:\n\t\t\ti = 0\nelse:\n\tprint(\"use 0 to choose the input and 1 for continuious multiplier\")\n\n", "repo_name": "drkspace/Matplotlib-programs-", "sub_path": "cardiod.py", "file_name": "cardiod.py", "file_ext": "py", "file_size_in_byte": 1595, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "sys.argv", "line_number": 6, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 8, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 9, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 10, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.ion", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 14, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 15, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 16, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.cla", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "math.cos", "line_number": 28, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.cla", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 53, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 53, "usage_type": "name"}, {"api_name": "math.cos", "line_number": 53, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 53, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 56, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.pause", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}]} +{"seq_id": "14534282813", "text": "import datetime\nfrom datetime import datetime as dt, timezone, timedelta, date\nimport time\nimport numpy as np\nimport pandas as pd\nimport pymongo\n\ntry:\n import QUANTAXIS as QA\nexcept:\n print('PLEASE run \"pip install QUANTAXIS\" before call GolemQ.fetch.StockCN_realtime modules')\n pass\n\ntry:\n from GolemQ.utils.parameter import (\n AKA, \n INDICATOR_FIELD as FLD, \n TREND_STATUS as ST\n )\nexcept:\n class AKA():\n \"\"\"\n 常量,专有名称指标,定义成常量可以避免直接打字符串造成的拼写错误。\n \"\"\"\n\n # 蜡烛线指标\n CODE = 'code'\n NAME = 'name'\n OPEN = 'open'\n HIGH = 'high'\n LOW = 'low'\n CLOSE = 'close'\n VOLUME = 'volume'\n VOL = 'vol'\n DATETIME = 'datetime'\n LAST_CLOSE = 'last_close'\n PRE_CLOSE = 'pre_close'\n\n def __setattr__(self, name, value):\n raise Exception(u'Const Class can\\'t allow to change property\\' value.')\n return super().__setattr__(name, value)\n\nfrom QUANTAXIS.QAUtil import (\n QASETTING,\n )\nclient = QASETTING.client['QAREALTIME']\nfrom GolemQ.utils.symbol import (\n normalize_code\n)\n\ndef GQ_fetch_stock_realtime_adv(code=None,\n num=1,\n collections=client.get_collection('realtime_{}'.format(date.today())),\n verbose=True,\n suffix=False,):\n '''\n 返回当日的上下五档, code可以是股票可以是list, num是每个股票获取的数量\n :param code:\n :param num:\n :param collections: realtime_XXXX-XX-XX 每天实时时间\n :param suffix: 股票代码是否带沪深交易所后缀\n :return: DataFrame\n '''\n if code is not None:\n # code 必须转换成list 去查询数据库,因为五档数据用一个collection保存了股票,指数及基金,所以强制必须使用标准化代码\n if isinstance(code, str):\n code = [normalize_code(code)]\n elif isinstance(code, list):\n code = [normalize_code(symbol) for symbol in code]\n pass\n else:\n print(\"QA Error GQ_fetch_stock_realtime_adv parameter code is not List type or String type\")\n #print(verbose, code)\n items_from_collections = [\n item for item in collections.find({'code': {\n '$in': code\n }},\n limit=num * len(code),\n sort=[('datetime',\n pymongo.DESCENDING)])\n ]\n if (items_from_collections is None) or \\\n (len(items_from_collections) == 0):\n if verbose:\n print(\"QA Error GQ_fetch_stock_realtime_adv find parameter code={} num={} collection={} return NOne\"\n .format(code,\n num,\n collections))\n return\n data = pd.DataFrame(items_from_collections)\n if (suffix == False):\n # 返回代码数据中是否包含交易所代码\n data['code'] = data.apply(lambda x: x.at['code'][:6], axis=1)\n data_set_index = data.set_index(['datetime',\n 'code'],\n drop=False).drop(['_id'],\n axis=1)\n\n return data_set_index\n else:\n print(\"QA Error GQ_fetch_stock_realtime_adv parameter code is None\")\n\n\ndef GQ_fetch_stock_day_realtime_adv(codelist, \n data_day, \n verbose=True):\n \"\"\"\n 查询日线实盘数据,支持多股查询\n \"\"\"\n if codelist is not None:\n # codelist 必须转换成list 去查询数据库\n if isinstance(codelist, str):\n codelist = [codelist]\n elif isinstance(codelist, list):\n pass\n else:\n print(\"QA Error GQ_fetch_stock_day_realtime_adv parameter codelist is not List type or String type\")\n start_time = dt.strptime(str(dt.now().date()) + ' 09:15', '%Y-%m-%d %H:%M')\n if ((dt.now() > start_time) and ((dt.now() - data_day.data.index.get_level_values(level=0)[-1].to_pydatetime()) > timedelta(hours=10))) or \\\n ((dt.now() < start_time) and ((dt.now() - data_day.data.index.get_level_values(level=0)[-1].to_pydatetime()) > timedelta(hours=40))):\n if (verbose == True):\n print('时间戳差距超过:', dt.now() - data_day.data.index.get_level_values(level=0)[-1].to_pydatetime(),\n '尝试查找实盘数据....', codelist)\n #print(codelist, verbose)\n try:\n if (dt.now() > start_time):\n collections = client.get_collection('realtime_{}'.format(date.today()))\n else:\n collections = client.get_collection('realtime_{}'.format(date.today() - timedelta(hours=24)))\n data_realtime = GQ_fetch_stock_realtime_adv(codelist, num=8000, verbose=verbose, suffix=False, collections=collections)\n except: \n data_realtime = QA.QA_fetch_stock_realtime_adv(codelist, num=8000, verbose=verbose)\n if (data_realtime is not None) and \\\n (len(data_realtime) > 0):\n # 合并实盘实时数据\n data_realtime = data_realtime.drop_duplicates(([\"datetime\",\n 'code'])).set_index([\"datetime\",\n 'code'],\n drop=False)\n data_realtime = data_realtime.reset_index(level=[1], drop=True)\n data_realtime['date'] = pd.to_datetime(data_realtime['datetime']).dt.strftime('%Y-%m-%d')\n data_realtime['datetime'] = pd.to_datetime(data_realtime['datetime'])\n for code in codelist:\n # 顺便检查股票行情长度,发现低于30天直接砍掉。\n if (len(data_day.select_code(code[:6])) < 30):\n print(u'{} 行情只有{}天数据,新股或者数据不足,不进行择时分析。'.format(code, \n len(data_day.select_code(code))))\n data_day.data.drop(data_day.select_code(code), inplace=True)\n continue\n\n # *** 注意,QA_data_tick_resample_1min 函数不支持多标的 *** 需要循环处理\n data_realtime_code = data_realtime[data_realtime['code'].eq(code)]\n if (len(data_realtime_code) > 0):\n data_realtime_code = data_realtime_code.set_index(['datetime']).sort_index()\n if ('volume' in data_realtime_code.columns) and \\\n ('vol' not in data_realtime_code.columns):\n # 我也不知道为什么要这样转来���去,但是各家(新浪,pytdx)l1数据就是那么不统一\n data_realtime_code.rename(columns={\"volume\": \"vol\"}, \n inplace = True)\n elif ('volume' in data_realtime_code.columns):\n data_realtime_code['vol'] = np.where(np.isnan(data_realtime_code['vol']), \n data_realtime_code['volume'], \n data_realtime_code['vol'])\n\n # 一分钟数据转出来了\n #data_realtime_1min =\n #QA.QA_data_tick_resample_1min(data_realtime_code,\n # type_='1min')\n try:\n data_realtime_1min = QA.QA_data_tick_resample_1min(data_realtime_code, \n type_='1min')\n except:\n print('fooo1', code)\n print(data_realtime_code)\n raise('foooo1{}'.format(code))\n data_realtime_1day = QA.QA_data_min_to_day(data_realtime_1min)\n if (len(data_realtime_1day) > 0):\n # 转成日线数据\n data_realtime_1day.rename(columns={\"vol\": \"volume\"}, \n inplace = True)\n\n # 假装复了权,我建议复权那几天直接量化处理,复权几天内对策略买卖点影响很大\n data_realtime_1day['adj'] = 1.0 \n data_realtime_1day['datetime'] = pd.to_datetime(data_realtime_1day.index)\n data_realtime_1day = data_realtime_1day.set_index(['datetime', 'code'], \n drop=True).sort_index()\n\n # issue:成交量计算不正确,成交量计算差距较大,这里尝试处理方法,但是貌似不对\n data_realtime_1day[AKA.VOLUME] = data_realtime_1min[AKA.VOLUME][-1] / data_realtime_1min[AKA.CLOSE][-1]\n # if (len(data_realtime_1day) > 0):\n # print(u'日线 status:',\n # data_day.data.index.get_level_values(level=0)[-1]\n # ==\n # data_realtime_1day.index.get_level_values(level=0)[-1],\n # '时间戳差距超过:', dt.now() -\n # data_day.data.index.get_level_values(level=0)[-1].to_pydatetime(),\n #'尝试查找实盘数据....', codelist)\n # print(data_day.data.tail(3), data_realtime_1day)\n if (data_day.data.index.get_level_values(level=0)[-1] != data_realtime_1day.index.get_level_values(level=0)[-1]):\n if (verbose == True):\n print(u'追加实时实盘数据,股票代码:{} 时间:{} 价格:{}'.format(data_realtime_1day.index[0][1],\n data_realtime_1day.index[-1][0],\n data_realtime_1day[AKA.CLOSE][-1]))\n data_day.data = data_day.data.append(data_realtime_1day, \n sort=True)\n\n return data_day\n\n\ndef GQ_fetch_stock_min_realtime_adv(codelist,\n data_min,\n frequency, \n verbose=True):\n \"\"\"\n 查询A股的指定小时/分钟线线实盘数据\n \"\"\"\n if codelist is not None:\n # codelist 必须转换成list 去查询数据库\n if isinstance(codelist, str):\n codelist = [codelist]\n elif isinstance(codelist, list):\n pass\n else:\n if verbose:\n print(\"QA Error GQ_fetch_stock_min_realtime_adv parameter codelist is not List type or String type\")\n\n if data_min is None:\n if verbose:\n print(u'代码:{} 今天停牌或者已经退市*'.format(codelist)) \n return None\n\n try:\n foo = (dt.now() - data_min.data.index.get_level_values(level=0)[-1].to_pydatetime())\n except:\n if verbose:\n print(u'代码:{} 今天停牌或者已经退市**'.format(codelist)) \n return None\n start_time = dt.strptime(str(dt.now().date()) + ' 09:15', '%Y-%m-%d %H:%M')\n if ((dt.now() > start_time) and ((dt.now() - data_min.data.index.get_level_values(level=0)[-1].to_pydatetime()) > timedelta(hours=10))) or \\\n ((dt.now() < start_time) and ((dt.now() - data_min.data.index.get_level_values(level=0)[-1].to_pydatetime()) > timedelta(hours=24))):\n if (verbose == True):\n print('时间戳差距超过:', dt.now() - data_min.data.index.get_level_values(level=0)[-1].to_pydatetime(),\n '尝试查找实盘数据....', codelist)\n #print(codelist, verbose)\n try:\n if (dt.now() > start_time):\n collections = client.get_collection('realtime_{}'.format(date.today()))\n else:\n collections = client.get_collection('realtime_{}'.format(date.today() - timedelta(hours=24)))\n data_realtime = GQ_fetch_stock_realtime_adv(codelist, num=8000, verbose=verbose, suffix=False, collections=collections)\n except: \n data_realtime = QA.QA_fetch_stock_realtime_adv(codelist, num=8000, verbose=verbose)\n if (data_realtime is not None) and \\\n (len(data_realtime) > 0):\n # 合并实盘实时数据\n data_realtime = data_realtime.drop_duplicates(([\"datetime\",\n 'code'])).set_index([\"datetime\",\n 'code'],\n drop=False)\n\n data_realtime = data_realtime.reset_index(level=[1], drop=True)\n data_realtime['date'] = pd.to_datetime(data_realtime['datetime']).dt.strftime('%Y-%m-%d')\n data_realtime['datetime'] = pd.to_datetime(data_realtime['datetime'])\n for code in codelist:\n # 顺便检查股票行情长度,发现低于30天直接砍掉。\n try:\n if (len(data_min.select_code(code[:6])) < 30):\n if verbose:\n print(u'{} 行情只有{}天数据,新股或者数据不足,不进行择时分析。新股买不买卖不卖,建议掷骰子。'.format(code, \n len(data_min.select_code(code))))\n data_min.data.drop(data_min.select_code(code), inplace=True)\n continue\n except:\n if verbose:\n print(u'代码:{} 今天停牌或者已经退市***'.format(code)) \n continue\n\n # *** 注意,QA_data_tick_resample_1min 函数不支持多标的 *** 需要循环处理\n # 可能出现8位六位股票代码兼容问题\n data_realtime_code = data_realtime[data_realtime['code'].eq(code[:6])]\n if (len(data_realtime_code) > 0):\n data_realtime_code = data_realtime_code.set_index(['datetime']).sort_index()\n if ('volume' in data_realtime_code.columns) and \\\n ('vol' not in data_realtime_code.columns):\n # 我也不知道为什么要这样转来转去,但是各家(新浪,pytdx)l1数据就是那么不统一\n data_realtime_code.rename(columns={\"volume\": \"vol\"}, \n inplace = True)\n elif ('volume' in data_realtime_code.columns):\n data_realtime_code['vol'] = np.where(np.isnan(data_realtime_code['vol']), \n data_realtime_code['volume'], \n data_realtime_code['vol'])\n\n # 将l1 Tick数据重采样为1分钟\n try:\n data_realtime_1min = QA.QA_data_tick_resample_1min(data_realtime_code, \n type_='1min')\n except:\n if verbose:\n print('fooo1', code)\n print(data_realtime_code)\n pass\n #raise('foooo1{}'.format(code))\n\n if (len(data_realtime_1min) == 0):\n # 没有数据或者数据缺失,尝试获取腾讯财经的1分钟数据\n #import easyquotation\n #quotation = easyquotation.use(\"timekline\")\n #data = quotation.real(codelist, prefix=False)\n #if verbose:\n # print(data)\n pass\n return data_min\n\n # 一分钟数据转出来了,重采样为指定小时/分钟线数据\n data_realtime_1min = data_realtime_1min.reset_index([1], drop=False)\n data_realtime_mins = QA.QA_data_min_resample(data_realtime_1min, \n type_=frequency)\n\n if (len(data_realtime_mins) > 0):\n # 转成指定分钟线数据\n data_realtime_mins.rename(columns={\"vol\": \"volume\"}, \n inplace = True)\n\n\n # 假装复了权,我建议复权那几天直接量化处理,复权几天内对策略买卖点影响很大\n data_realtime_mins['adj'] = 1.0 \n #data_realtime_mins['datetime'] =\n #pd.to_datetime(data_realtime_mins.index)\n #data_realtime_mins =\n #data_realtime_mins.set_index(['datetime', 'code'],\n # drop=True).sort_index()\n # if (len(data_realtime_mins) > 0):\n # print(u'分钟线 status:', (dt.now() < start_time), '时间戳差距超过:', dt.now() - data_min.data.index.get_level_values(level=0)[-1].to_pydatetime(),\n #'尝试查找实盘数据....', codelist)\n # print(data_min.data.tail(3), data_realtime_mins)\n if (data_min.data.index.get_level_values(level=0)[-1] != data_realtime_mins.index.get_level_values(level=0)[-1]):\n if (verbose == True):\n #print(data_min.data.tail(3), data_realtime_mins)\n print(u'追加实时实盘数据,股票代码:{} 时间:{} 价格:{}'.format(data_realtime_mins.index[0][1],\n data_realtime_mins.index[-1][0],\n data_realtime_mins[AKA.CLOSE][-1]))\n data_min.data = data_min.data.append(data_realtime_mins, \n sort=True)\n\n # Amount, Volume 计算不对\n else:\n if (verbose == True):\n print(u'没有时间差', dt.now() - data_min.data.index.get_level_values(level=0)[-1].to_pydatetime())\n\n return data_min\n\n #\n #data_realtime_1min = data_realtime_1min.reset_index(level=[1], drop=False)\n\n #data_realtime_5min = QA.QA_data_min_resample(data_realtime_1min,\n # type_='5min')\n #print(data_realtime_5min)\n\n #data_realtime_15min = QA.QA_data_min_resample(data_realtime_1min,\n # type_='15min')\n #print(data_realtime_15min)\n\n #data_realtime_30min = QA.QA_data_min_resample(data_realtime_1min,\n # type_='30min')\n #print(data_realtime_30min)\n #data_realtime_1hour = QA.QA_data_min_resample(data_realtime_1min,\n # type_='60min')\n #print(data_realtime_1hour)\n #return data_min\ndef GQ_fetch_index_min_realtime_adv(codelist,\n data_min,\n frequency, \n verbose=True):\n \"\"\"\n 查询指数和ETF的分钟线实盘数据\n \"\"\"\n # 将l1 Tick数据重采样为1分钟\n data_realtime_1min = data_realtime_1min.reset_index(level=[1], drop=False)\n\n # 检查 1min数据是否完整,如果不完整,需要从腾讯财经获取1min K线\n #if ():\n\n\n data_realtime_5min = QA.QA_data_min_resample(data_realtime_1min, \n type_='5min')\n print(data_realtime_5min)\n\n data_realtime_15min = QA.QA_data_min_resample(data_realtime_1min, \n type_='15min')\n print(data_realtime_15min)\n\n data_realtime_30min = QA.QA_data_min_resample(data_realtime_1min, \n type_='30min')\n print(data_realtime_30min)\n data_realtime_1hour = QA.QA_data_min_resample(data_realtime_1min,\n type_='60min')\n print(data_realtime_1hour)\n return data_min\n\n\nif __name__ == '__main__':\n \"\"\"\n 用法示范\n \"\"\"\n codelist = ['600157', '300263']\n data_min = QA.QA_fetch_stock_day_adv(codelist,\n '2008-01-01',\n '{}'.format(date.today(),)).to_qfq()\n\n data_min = GQ_fetch_stock_day_realtime_adv(codelist, data_min)", "repo_name": "Rgveda/GolemQ", "sub_path": "fetch/StockCN_realtime.py", "file_name": "StockCN_realtime.py", "file_ext": "py", "file_size_in_byte": 21066, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 83, "dataset": "github-code", "pt": "20", "api": [{"api_name": "QUANTAXIS.QAUtil.QASETTING.client", "line_number": 46, "usage_type": "attribute"}, {"api_name": "QUANTAXIS.QAUtil.QASETTING", "line_number": 46, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 53, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 53, "usage_type": "name"}, {"api_name": "GolemQ.utils.symbol.normalize_code", "line_number": 67, "usage_type": "call"}, {"api_name": "GolemQ.utils.symbol.normalize_code", "line_number": 69, "usage_type": "call"}, {"api_name": "pymongo.DESCENDING", "line_number": 80, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 90, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 118, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 118, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 118, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 119, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 119, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 119, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 120, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 120, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 120, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 122, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 122, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 126, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 126, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 127, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 127, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 129, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 129, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 129, "usage_type": "call"}, {"api_name": "QUANTAXIS.QA_fetch_stock_realtime_adv", "line_number": 132, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 141, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 161, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 161, "usage_type": "call"}, {"api_name": "QUANTAXIS.QA_data_tick_resample_1min", "line_number": 170, "usage_type": "call"}, {"api_name": "QUANTAXIS.QA_data_min_to_day", "line_number": 176, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 184, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 233, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 233, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 238, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 238, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 238, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 239, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 239, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 239, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 240, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 240, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 240, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 242, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 242, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 246, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 246, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 247, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 247, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 249, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 249, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 249, "usage_type": "call"}, {"api_name": "QUANTAXIS.QA_fetch_stock_realtime_adv", "line_number": 252, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 262, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 263, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 289, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 289, "usage_type": "call"}, {"api_name": "QUANTAXIS.QA_data_tick_resample_1min", "line_number": 295, "usage_type": "call"}, {"api_name": "QUANTAXIS.QA_data_min_resample", "line_number": 316, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 348, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 348, "usage_type": "name"}, {"api_name": "QUANTAXIS.QA_data_min_resample", "line_number": 384, "usage_type": "call"}, {"api_name": "QUANTAXIS.QA_data_min_resample", "line_number": 388, "usage_type": "call"}, {"api_name": "QUANTAXIS.QA_data_min_resample", "line_number": 392, "usage_type": "call"}, {"api_name": "QUANTAXIS.QA_data_min_resample", "line_number": 395, "usage_type": "call"}, {"api_name": "QUANTAXIS.QA_fetch_stock_day_adv", "line_number": 406, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 408, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 408, "usage_type": "name"}]} +{"seq_id": "71021150451", "text": "import cv2\nimport tensorflow as tf\nfrom vision_function import *\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n\n#set up \nmlpc = get_model_mlpc() \nmrc = get_model_mrc()\nmrp = get_model_mpc()\nmrp_IN = get_model_mpc_IN()\nvid = cv2.VideoCapture(0, cv2.CAP_DSHOW) #define capture obj\n\nwhile (True):\n ret,frame = vid.read()\n result,frame = read_lisense_plate(frame,mrc,mrp_IN,mlpc,show_result= True)\n print(result)\n cv2.imshow('frame', frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\nvid.release()\ncv2.destroyAllWindows()", "repo_name": "punsiwoot/Simple_TH_lisense_plate_recognition", "sub_path": "demo/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 559, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "tensorflow.compat.v1.logging.set_verbosity", "line_number": 4, "usage_type": "call"}, {"api_name": "tensorflow.compat", "line_number": 4, "usage_type": "attribute"}, {"api_name": "cv2.VideoCapture", "line_number": 11, "usage_type": "call"}, {"api_name": "cv2.CAP_DSHOW", "line_number": 11, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 17, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 18, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 21, "usage_type": "call"}]} +{"seq_id": "43949995192", "text": "from copy import deepcopy\nfrom typing import Set\n\nimport tensorflow as tf\n\nfrom nncf import NNCFConfig\nfrom nncf.api.compression import CompressionLoss\nfrom nncf.api.compression import CompressionScheduler\nfrom nncf.api.compression import CompressionStage\nfrom nncf.common.accuracy_aware_training.training_loop import ADAPTIVE_COMPRESSION_CONTROLLERS\nfrom nncf.common.graph.operator_metatypes import OUTPUT_NOOP_METATYPES\nfrom nncf.common.graph.transformations.commands import TransformationPriority\nfrom nncf.common.initialization.batchnorm_adaptation import BatchnormAdaptationAlgorithm\nfrom nncf.common.schedulers import StubCompressionScheduler\nfrom nncf.common.scopes import check_scopes_in_graph\nfrom nncf.common.scopes import should_consider_scope\nfrom nncf.common.sparsity.schedulers import SPARSITY_SCHEDULERS\nfrom nncf.common.sparsity.statistics import LayerThreshold\nfrom nncf.common.sparsity.statistics import MagnitudeSparsityStatistics\nfrom nncf.common.statistics import NNCFStatistics\nfrom nncf.common.utils.api_marker import api\nfrom nncf.config.extractors import extract_algo_specific_config\nfrom nncf.config.extractors import extract_bn_adaptation_init_params\nfrom nncf.config.schemata.defaults import MAGNITUDE_SPARSITY_WEIGHT_IMPORTANCE\nfrom nncf.config.schemata.defaults import SPARSITY_INIT\nfrom nncf.tensorflow.algorithm_selector import TF_COMPRESSION_ALGORITHMS\nfrom nncf.tensorflow.api.compression import TFCompressionAlgorithmBuilder\nfrom nncf.tensorflow.graph.converter import TFModelConverterFactory\nfrom nncf.tensorflow.graph.metatypes.tf_ops import WEIGHTABLE_TF_OP_METATYPES\nfrom nncf.tensorflow.graph.transformations.commands import TFInsertionCommand\nfrom nncf.tensorflow.graph.transformations.commands import TFLayerWeight\nfrom nncf.tensorflow.graph.transformations.layout import TFTransformationLayout\nfrom nncf.tensorflow.graph.utils import collect_wrapped_layers\nfrom nncf.tensorflow.graph.utils import get_original_name_and_instance_idx\nfrom nncf.tensorflow.loss import TFZeroCompressionLoss\nfrom nncf.tensorflow.sparsity.base_algorithm import SPARSITY_LAYER_METATYPES\nfrom nncf.tensorflow.sparsity.base_algorithm import BaseSparsityController\nfrom nncf.tensorflow.sparsity.collector import TFSparseModelStatisticsCollector\nfrom nncf.tensorflow.sparsity.magnitude.functions import WEIGHT_IMPORTANCE_FUNCTIONS\nfrom nncf.tensorflow.sparsity.magnitude.functions import calc_magnitude_binary_mask\nfrom nncf.tensorflow.sparsity.magnitude.operation import BinaryMask\nfrom nncf.tensorflow.sparsity.magnitude.operation import BinaryMaskWithWeightsBackup\n\n\n@TF_COMPRESSION_ALGORITHMS.register(\"magnitude_sparsity\")\nclass MagnitudeSparsityBuilder(TFCompressionAlgorithmBuilder):\n def __init__(self, config: NNCFConfig, should_init: bool = True):\n super().__init__(config, should_init)\n self.ignored_scopes = self._algo_config.get(\"ignored_scopes\", [])\n self._op_names = []\n\n def get_transformation_layout(self, model: tf.keras.Model) -> TFTransformationLayout:\n converter = TFModelConverterFactory.create(model)\n nncf_graph = converter.convert()\n\n check_scopes_in_graph(nncf_graph, self.ignored_scopes, self.target_scopes, self.validate_scopes)\n\n transformations = TFTransformationLayout()\n\n processed_shared_layer_names: Set[str] = set()\n\n for node in nncf_graph.get_all_nodes():\n if node.is_shared():\n target_layer_name, _ = get_original_name_and_instance_idx(node.node_name)\n if target_layer_name in processed_shared_layer_names:\n continue\n processed_shared_layer_names.add(target_layer_name)\n\n if not should_consider_scope(node.node_name, ignored_scopes=self.ignored_scopes):\n continue\n\n if node.metatype in OUTPUT_NOOP_METATYPES:\n continue\n\n is_custom, layer_info = converter.get_layer_info_for_node(node.node_name)\n if node.metatype in SPARSITY_LAYER_METATYPES:\n # Processing a regular weighted node\n for weight_def in node.metatype.weight_definitions:\n op_name = self._get_sparsity_operation_name(node.node_name, weight_def.weight_attr_name)\n self._op_names.append(op_name)\n\n transformations.register(\n TFInsertionCommand(\n target_point=TFLayerWeight(layer_info.layer_name, weight_def.weight_attr_name),\n callable_object=BinaryMask(op_name),\n priority=TransformationPriority.SPARSIFICATION_PRIORITY,\n )\n )\n elif node.metatype in WEIGHTABLE_TF_OP_METATYPES:\n assert is_custom\n # Processing a custom layer weighted node\n # Caution: here layer_name will refer to the weight itself, not to the op\n weight_attr_name = node.layer_name\n op_name = self._get_sparsity_operation_name(node.node_name, weight_attr_name)\n self._op_names.append(op_name)\n\n transformations.register(\n TFInsertionCommand(\n target_point=TFLayerWeight(layer_info.layer_name, weight_attr_name),\n callable_object=BinaryMaskWithWeightsBackup(op_name, weight_attr_name),\n priority=TransformationPriority.SPARSIFICATION_PRIORITY,\n )\n )\n\n return transformations\n\n def _get_sparsity_operation_name(self, layer_name: str, weight_attr_name: str) -> str:\n return f\"{layer_name}_{weight_attr_name}_sparsity_binary_mask\"\n\n def _build_controller(self, model: tf.keras.Model) -> \"MagnitudeSparsityController\":\n \"\"\"\n Simple implementation of building controller without setting builder state and loading controller's one.\n Should be called once the compressed model target_model is fully constructed.\n\n :param model: The model with additional modifications necessary to enable\n algorithm-specific compression during fine-tuning.\n :return: The instance of the `MagnitudeSparsityController`.\n \"\"\"\n return MagnitudeSparsityController(model, self.config, self._op_names)\n\n def initialize(self, model: tf.keras.Model) -> None:\n pass\n\n\n@api()\n@ADAPTIVE_COMPRESSION_CONTROLLERS.register(\"tf_magnitude_sparsity\")\nclass MagnitudeSparsityController(BaseSparsityController):\n \"\"\"\n Controller class for magnitude sparsity in TF.\n \"\"\"\n\n def __init__(self, target_model, config: NNCFConfig, op_names):\n super().__init__(target_model, op_names)\n algo_config = extract_algo_specific_config(config, \"magnitude_sparsity\")\n params = deepcopy(algo_config.get(\"params\", {}))\n self._threshold = 0\n self._frozen = False\n self._weight_importance_fn = WEIGHT_IMPORTANCE_FUNCTIONS[\n params.get(\"weight_importance\", MAGNITUDE_SPARSITY_WEIGHT_IMPORTANCE)\n ]\n\n sparsity_init = algo_config.get(\"sparsity_init\", SPARSITY_INIT)\n params[\"sparsity_init\"] = sparsity_init\n scheduler_type = params.get(\"schedule\", \"polynomial\")\n\n if scheduler_type == \"adaptive\":\n raise ValueError(\"Magnitude sparsity algorithm do not support adaptive scheduler\")\n\n scheduler_cls = SPARSITY_SCHEDULERS.get(scheduler_type)\n self._scheduler = scheduler_cls(self, params)\n self._loss = TFZeroCompressionLoss()\n self._bn_adaptation = None\n self._config = config\n self.set_sparsity_level(sparsity_init)\n\n @property\n def scheduler(self) -> CompressionScheduler:\n return self._scheduler\n\n @property\n def loss(self) -> CompressionLoss:\n return self._loss\n\n def freeze(self, freeze: bool = True):\n self._frozen = freeze\n\n def set_sparsity_level(self, sparsity_level, run_batchnorm_adaptation: bool = False):\n \"\"\"\n Sets the sparsity level that should be applied to the model's weights.\n\n :param sparsity_level: Sparsity level that should be applied to the model's weights.\n :param run_batchnorm_adaptation: Whether to run batchnorm adaptation after setting the sparsity level.\n \"\"\"\n if not self._frozen:\n if sparsity_level >= 1 or sparsity_level < 0:\n raise AttributeError(\n \"Sparsity level should be within interval [0,1), actual value to set is: {}\".format(sparsity_level)\n )\n\n self._threshold = self._select_threshold(sparsity_level)\n self._set_masks_for_threshold(self._threshold)\n\n if run_batchnorm_adaptation:\n self._run_batchnorm_adaptation()\n\n def _select_threshold(self, sparsity_level):\n all_weights = self._collect_all_weights()\n if not all_weights:\n return 0.0\n all_weights_tensor = tf.sort(tf.concat(all_weights, 0))\n index = int(tf.cast(tf.size(all_weights_tensor) - 1, all_weights_tensor.dtype) * sparsity_level)\n threshold = all_weights_tensor[index].numpy()\n return threshold\n\n def _set_masks_for_threshold(self, threshold_val):\n for wrapped_layer in collect_wrapped_layers(self._model):\n for weight_attr, ops in wrapped_layer.weights_attr_ops.items():\n weight = wrapped_layer.layer_weights[weight_attr]\n\n for op_name in ops:\n if op_name in self._op_names:\n wrapped_layer.ops_weights[op_name][\"mask\"].assign(\n calc_magnitude_binary_mask(weight, self._weight_importance_fn, threshold_val)\n )\n\n def _collect_all_weights(self):\n all_weights = []\n for wrapped_layer in collect_wrapped_layers(self._model):\n for weight_attr, ops in wrapped_layer.weights_attr_ops.items():\n for op_name in ops:\n if op_name in self._op_names:\n all_weights.append(\n tf.reshape(self._weight_importance_fn(wrapped_layer.layer_weights[weight_attr]), [-1])\n )\n return all_weights\n\n @property\n def compression_rate(self) -> float:\n return self.statistics().magnitude_sparsity.model_statistics.sparsity_level\n\n @compression_rate.setter\n def compression_rate(self, compression_rate: float) -> None:\n self.freeze(False)\n self.set_sparsity_level(compression_rate)\n self.freeze(True)\n\n def disable_scheduler(self):\n self._scheduler = StubCompressionScheduler()\n self._scheduler.target_level = 0.0\n self._scheduler.current_sparsity_level = 0.0\n\n def statistics(self, quickly_collected_only: bool = False) -> NNCFStatistics:\n collector = TFSparseModelStatisticsCollector(self.model, self._op_names)\n model_stats = collector.collect()\n\n threshold_stats = []\n threshold = self._select_threshold(model_stats.sparsity_level)\n for s in model_stats.sparsified_layers_summary:\n threshold_stats.append(LayerThreshold(s.name, threshold))\n\n target_sparsity_level = self.scheduler.current_sparsity_level\n\n stats = MagnitudeSparsityStatistics(model_stats, threshold_stats, target_sparsity_level)\n\n nncf_stats = NNCFStatistics()\n nncf_stats.register(\"magnitude_sparsity\", stats)\n return nncf_stats\n\n def compression_stage(self) -> CompressionStage:\n if self.scheduler.current_sparsity_level >= self.scheduler.target_level:\n return CompressionStage.FULLY_COMPRESSED\n if self.scheduler.current_sparsity_level == 0:\n return CompressionStage.UNCOMPRESSED\n return CompressionStage.PARTIALLY_COMPRESSED\n\n def _run_batchnorm_adaptation(self):\n if self._bn_adaptation is None:\n self._bn_adaptation = BatchnormAdaptationAlgorithm(\n **extract_bn_adaptation_init_params(self._config, self.name)\n )\n self._bn_adaptation.run(self.model)\n", "repo_name": "openvinotoolkit/nncf", "sub_path": "nncf/tensorflow/sparsity/magnitude/algorithm.py", "file_name": "algorithm.py", "file_ext": "py", "file_size_in_byte": 12115, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 702, "dataset": "github-code", "pt": "20", "api": [{"api_name": "nncf.tensorflow.api.compression.TFCompressionAlgorithmBuilder", "line_number": 46, "usage_type": "name"}, {"api_name": "nncf.NNCFConfig", "line_number": 47, "usage_type": "name"}, {"api_name": "tensorflow.keras", "line_number": 52, "usage_type": "attribute"}, {"api_name": "nncf.tensorflow.graph.converter.TFModelConverterFactory.create", "line_number": 53, "usage_type": "call"}, {"api_name": "nncf.tensorflow.graph.converter.TFModelConverterFactory", "line_number": 53, "usage_type": "name"}, {"api_name": "nncf.common.scopes.check_scopes_in_graph", "line_number": 56, "usage_type": "call"}, {"api_name": "nncf.tensorflow.graph.transformations.layout.TFTransformationLayout", "line_number": 58, "usage_type": "call"}, {"api_name": "typing.Set", "line_number": 60, "usage_type": "name"}, {"api_name": "nncf.tensorflow.graph.utils.get_original_name_and_instance_idx", "line_number": 64, "usage_type": "call"}, {"api_name": "nncf.common.scopes.should_consider_scope", "line_number": 69, "usage_type": "call"}, {"api_name": "nncf.common.graph.operator_metatypes.OUTPUT_NOOP_METATYPES", "line_number": 72, "usage_type": "name"}, {"api_name": "nncf.tensorflow.sparsity.base_algorithm.SPARSITY_LAYER_METATYPES", "line_number": 76, "usage_type": "name"}, {"api_name": "nncf.tensorflow.graph.transformations.commands.TFInsertionCommand", "line_number": 83, "usage_type": "call"}, {"api_name": "nncf.tensorflow.graph.transformations.commands.TFLayerWeight", "line_number": 84, "usage_type": "call"}, {"api_name": "nncf.tensorflow.sparsity.magnitude.operation.BinaryMask", "line_number": 85, "usage_type": "call"}, {"api_name": "nncf.common.graph.transformations.commands.TransformationPriority.SPARSIFICATION_PRIORITY", "line_number": 86, "usage_type": "attribute"}, {"api_name": "nncf.common.graph.transformations.commands.TransformationPriority", "line_number": 86, "usage_type": "name"}, {"api_name": "nncf.tensorflow.graph.metatypes.tf_ops.WEIGHTABLE_TF_OP_METATYPES", "line_number": 89, "usage_type": "name"}, {"api_name": "nncf.tensorflow.graph.transformations.commands.TFInsertionCommand", "line_number": 98, "usage_type": "call"}, {"api_name": "nncf.tensorflow.graph.transformations.commands.TFLayerWeight", "line_number": 99, "usage_type": "call"}, {"api_name": "nncf.tensorflow.sparsity.magnitude.operation.BinaryMaskWithWeightsBackup", "line_number": 100, "usage_type": "call"}, {"api_name": "nncf.common.graph.transformations.commands.TransformationPriority.SPARSIFICATION_PRIORITY", "line_number": 101, "usage_type": "attribute"}, {"api_name": "nncf.common.graph.transformations.commands.TransformationPriority", "line_number": 101, "usage_type": "name"}, {"api_name": "nncf.tensorflow.graph.transformations.layout.TFTransformationLayout", "line_number": 52, "usage_type": "name"}, {"api_name": "tensorflow.keras", "line_number": 110, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 121, "usage_type": "attribute"}, {"api_name": "nncf.tensorflow.algorithm_selector.TF_COMPRESSION_ALGORITHMS.register", "line_number": 45, "usage_type": "call"}, {"api_name": "nncf.tensorflow.algorithm_selector.TF_COMPRESSION_ALGORITHMS", "line_number": 45, "usage_type": "name"}, {"api_name": "nncf.tensorflow.sparsity.base_algorithm.BaseSparsityController", "line_number": 127, "usage_type": "name"}, {"api_name": "nncf.NNCFConfig", "line_number": 132, "usage_type": "name"}, {"api_name": "nncf.config.extractors.extract_algo_specific_config", "line_number": 134, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 135, "usage_type": "call"}, {"api_name": "nncf.tensorflow.sparsity.magnitude.functions.WEIGHT_IMPORTANCE_FUNCTIONS", "line_number": 138, "usage_type": "name"}, {"api_name": "nncf.config.schemata.defaults.MAGNITUDE_SPARSITY_WEIGHT_IMPORTANCE", "line_number": 139, "usage_type": "argument"}, {"api_name": "nncf.config.schemata.defaults.SPARSITY_INIT", "line_number": 142, "usage_type": "argument"}, {"api_name": "nncf.common.sparsity.schedulers.SPARSITY_SCHEDULERS.get", "line_number": 149, "usage_type": "call"}, {"api_name": "nncf.common.sparsity.schedulers.SPARSITY_SCHEDULERS", "line_number": 149, "usage_type": "name"}, {"api_name": "nncf.tensorflow.loss.TFZeroCompressionLoss", "line_number": 151, "usage_type": "call"}, {"api_name": "nncf.api.compression.CompressionScheduler", "line_number": 157, "usage_type": "name"}, {"api_name": "nncf.api.compression.CompressionLoss", "line_number": 161, "usage_type": "name"}, {"api_name": "tensorflow.sort", "line_number": 190, "usage_type": "call"}, {"api_name": "tensorflow.concat", "line_number": 190, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 191, "usage_type": "call"}, {"api_name": "tensorflow.size", "line_number": 191, "usage_type": "call"}, {"api_name": "nncf.tensorflow.graph.utils.collect_wrapped_layers", "line_number": 196, "usage_type": "call"}, {"api_name": "nncf.tensorflow.sparsity.magnitude.functions.calc_magnitude_binary_mask", "line_number": 203, "usage_type": "call"}, {"api_name": "nncf.tensorflow.graph.utils.collect_wrapped_layers", "line_number": 208, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 213, "usage_type": "call"}, {"api_name": "nncf.common.schedulers.StubCompressionScheduler", "line_number": 228, "usage_type": "call"}, {"api_name": "nncf.tensorflow.sparsity.collector.TFSparseModelStatisticsCollector", "line_number": 233, "usage_type": "call"}, {"api_name": "nncf.common.sparsity.statistics.LayerThreshold", "line_number": 239, "usage_type": "call"}, {"api_name": "nncf.common.sparsity.statistics.MagnitudeSparsityStatistics", "line_number": 243, "usage_type": "call"}, {"api_name": "nncf.common.statistics.NNCFStatistics", "line_number": 245, "usage_type": "call"}, {"api_name": "nncf.common.statistics.NNCFStatistics", "line_number": 232, "usage_type": "name"}, {"api_name": "nncf.api.compression.CompressionStage.FULLY_COMPRESSED", "line_number": 251, "usage_type": "attribute"}, {"api_name": "nncf.api.compression.CompressionStage", "line_number": 251, "usage_type": "name"}, {"api_name": "nncf.api.compression.CompressionStage.UNCOMPRESSED", "line_number": 253, "usage_type": "attribute"}, {"api_name": "nncf.api.compression.CompressionStage", "line_number": 253, "usage_type": "name"}, {"api_name": "nncf.api.compression.CompressionStage.PARTIALLY_COMPRESSED", "line_number": 254, "usage_type": "attribute"}, {"api_name": "nncf.api.compression.CompressionStage", "line_number": 254, "usage_type": "name"}, {"api_name": "nncf.api.compression.CompressionStage", "line_number": 249, "usage_type": "name"}, {"api_name": "nncf.common.initialization.batchnorm_adaptation.BatchnormAdaptationAlgorithm", "line_number": 258, "usage_type": "call"}, {"api_name": "nncf.config.extractors.extract_bn_adaptation_init_params", "line_number": 259, "usage_type": "call"}, {"api_name": "nncf.common.utils.api_marker.api", "line_number": 125, "usage_type": "call"}, {"api_name": "nncf.common.accuracy_aware_training.training_loop.ADAPTIVE_COMPRESSION_CONTROLLERS.register", "line_number": 126, "usage_type": "call"}, {"api_name": "nncf.common.accuracy_aware_training.training_loop.ADAPTIVE_COMPRESSION_CONTROLLERS", "line_number": 126, "usage_type": "name"}]} +{"seq_id": "22477766904", "text": "import csv \nimport usaddress\nimport scourgify\nfrom pycountry import countries\nimport re\nimport copy\nfrom typing import Tuple, Dict, List\n\ncountry_re = re.compile('|'.join(c.name.upper() for c in countries)) \nAPN, CAREOF, DBA, STREET, CITY, STATE, ZIP, ADDRESS1, ADDRESS2, ADDRESS3, ADDRESS4, REFINEINFO = (0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15 )\n\ndef getLabelsRecords(filename):\n with open(filename) as f:\n table = [ r for r in csv.reader(f) ]\n for r in table:\n r.append( '' )\n return ( table[0], table[1:] )\n\ndef usAddressGet( usadd: List[ Tuple[ str, str ] ], addType: str ) -> bool:\n matchedAddType = ''\n for pair in usadd:\n if pair[1] == addType:\n matchedAddType += pair[0]\n if matchedAddType:\n return matchedAddType\n return False \n\ndef refine( record: List[ str ] ):\n filtered = False \n usadd = usaddress.parse( formattedColumns( record ) )\n #if the address is foreign do nothing \n if not usAddressGet( usadd, 'ZipCode') and record[STATE] == '':\n return filtered\n filtered = refinePO( record )\n filtered |= refineCityStateZip( record, usadd )\n filtered |= refineStreet( record )\n filtered |= refineRecipient( record, usadd )\n if hasNullAddressVal( record ) and hasFormattedVal( record ):\n record[REFINEINFO] += ' NULLVALUES'\n filtered = True \n return filtered\n\ndef refinePO( record ):\n for col in record[ ADDRESS1 : ADDRESS4 + 1 ]:\n if record[STREET] == '' and 'PO BOX' in col:\n record[REFINEINFO] += ' PO'\n record[STREET] = record[ADDRESS3] \n return True \n return False \n\ndef refineCityStateZip( record, usadd ):\n city, state, zipcode = ( usAddressGet( usadd, 'PlaceName' ), usAddressGet( usadd, 'StateName' ),\n usAddressGet( usadd, 'ZipCode' ) )\n filtered = False \n if city and record[CITY] == '':\n record[REFINEINFO] += ' CITY'\n record[CITY] = city\n filtered = True \n if state and record[STATE] == '':\n record[REFINEINFO] += ' STATE' \n record[STATE] = state\n filtered = True \n if zipcode and record[ZIP] == '':\n record[REFINEINFO] += ' ZIPCODE'\n record[ZIP] = zipcode\n filtered = True\n return filtered\n\ndef refineStreet( record ):\n for i in range( ADDRESS1, ADDRESS4 + 1 ):\n try:\n street = scourgify.normalize_address_record( record[i] )['address_line_1'] \n if record[STREET] == '':\n record[REFINEINFO] += ' STREET'\n record[STREET] = street \n return True \n except:\n pass\n return False\n\ndef refineRecipient( record, recipient ):\n filtered = False\n recipRecord = getRecipient( recipient )\n if recipRecord:\n if recipRecord[0] == 'DBA' and record[DBA] == '':\n record[DBA] = ' '.join( recipRecord )\n record[REFINEINFO] += ' DBA'\n filtered = True \n elif recipRecord[0] == 'C/O' and record[CAREOF] == '':\n record[CAREOF] = ' '.join( recipRecord )\n record[REFINEINFO] += ' C/O'\n filtered = True \n \n return filtered\n\n\ndef formattedColumns( record ):\n return ( record[ADDRESS1] + ' ' + record[ADDRESS2] + ' ' + \n record[ADDRESS3] + ' ' + record[ADDRESS4] )\n\n\ndef getRecipient( recipient ):\n filterRecip = filter( lambda record: record[1] == 'Recipient', recipient )\n return [ recipient[0] for recipient in filterRecip ]\n\ndef hasNullAddressVal( record ):\n return ( record[CITY] == '' or record[STATE] == '' or\n record[STREET] == '' or record[ZIP] == '')\n\ndef hasFormattedVal( record ):\n return ( record[ADDRESS1] != '' and record[ADDRESS2] != '' and \n record[ADDRESS3] != '' and record[ADDRESS4] )\n\n''' \n updatedRecords.sort( )\n preUpdateRecords.sort( )\n updatedRecords = labels + updatedRecords\n preUpdateRecords = labels + preUpdateRecords\n \n import sys\n aw = csv.writer( sys.stdout, dialect='excel' )\n for r in records:\n if ( r[REFINEINFO] == 'C/O' or r[REFINEINFO] == 'DBA' ):\n aw.writerow( r )\n'''\n\n\n'''\nwith open( 'interestingbits','w') as f:\n for r in records:\n if ( r[REFINEINFO] == 'NULLVALUES' or r[REFINEINFO] == 'C/O' or \n r[REFINEINFO] == 'DBA' or r[REFINEINFO] == 'FOREGIN' ):\n \n f.write(\n ( l[3] + '-->' + printR(r[3]) + ' : ' +l[4] + '-->' + printR(r[4]) + '\\n'\n + l[5] + '-->' + printR(r[5]) ) \n )\n f.write(\n ( l[6] + '-->' + printR(r[6]) + ' : ' + l[7] + '-->' + printR(r[7]) + '\\n'\n + l[8] + '-->' + printR(r[8]) + ' : ' + l[9] + '-->' + printR(r[9]) )\n )\n f.write(\n ('#####################################')\n )\n f.write(\n ( l[10] + '-->' + printR(r[10]) + ' : ' + l[11] + '-->' + printR(r[11]) )\n )\n f.write(\n ( l[12] + '-->' + printR(r[12]) + ' : ' + l[13] + '--> ' +printR(r[13]) )\n )\n\n\n\n co = [ r for r in records if r[REFINEINFO] == 'C/O' ]\n dba = [ r for r in records if r[REFINEINFO] == 'DBA' ]\n foreign = [ r for r in records if r[REFINEINFO] == 'FOREIGN']\n nullvalues = [ r for r in records if r[REFINEINFO] == 'NULLVALUES']\n failedparse = [ r for r in records if r[REFINEINFO] == 'FAILEDPARSE']\n'''\n", "repo_name": "devinbrownworks/python-table-cleaner-", "sub_path": "tableToolz.py", "file_name": "tableToolz.py", "file_ext": "py", "file_size_in_byte": 5602, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "re.compile", "line_number": 9, "usage_type": "call"}, {"api_name": "pycountry.countries", "line_number": 9, "usage_type": "name"}, {"api_name": "csv.reader", "line_number": 14, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 19, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 19, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 28, "usage_type": "name"}, {"api_name": "usaddress.parse", "line_number": 30, "usage_type": "call"}, {"api_name": "scourgify.normalize_address_record", "line_number": 72, "usage_type": "call"}]} +{"seq_id": "23133209616", "text": "# Solving-TSP-with-Evolutionary-Genetic-Algorithm-Heuristic-Python\n# by mohammad asadolahi\n# Mohammad.E.Asadolahi@gmail.com\nimport math\nimport random\nimport matplotlib.pyplot as plt\n\nclass Draw:\n def DrawSolutionPlot(self, cities, path: list, info):\n if info != \"\":\n plt.title(f'Best Path untill Generation:{info}')\n x = []\n y = []\n for point in cities:\n x.append(cities[point]['x'])\n y.append(cities[point]['y'])\n plt.plot(x, y, 'co')\n for route in range(1, len(path)):\n source = path[route - 1]\n destination = path[route]\n plt.arrow(cities[source]['x'], cities[source]['y'], cities[destination]['x'] - cities[source]['x'] , cities[destination]['y'] - cities[source]['y'], color='r',\n length_includes_head=True)\n plt.xlim(0, max(x) * 1.1)\n plt.ylim(0, max(y) * 1.1)\n plt.show()\n\nclass Chromosome:\n def __init__(self, solution,cost):\n self.solution = solution\n self.cost = cost\n def __lt__(self, other):\n return self.cost < other.cost\n\n\nclass GeneticSolver:\n def __init__(self, populationSize, generationCount, mutationRate, cities,citycCount):\n self.draw=Draw()\n self.populationSize = populationSize\n self.generationCount = generationCount\n self.mutationRate = mutationRate\n self.cityCount = citycCount\n self.cities=cities\n self.population = []\n self.elitePopulation = []\n self.generationAverage = []\n self.initialPopulation()\n # self.printPopulation()\n\n def drawChromosome(self,chromosome,generation):\n self.draw.DrawSolutionPlot(self.cities, chromosome.solution,\n f\"{generation} with cost: {chromosome.cost}\")\n\n def getDistance(self, city1: int, city2: int):\n return math.sqrt((self.cities[city1]['x'] - self.cities[city2]['x']) ** 2 + (self.cities[city1]['y'] - self.cities[city2]['y']) ** 2)\n\n def getRouteCost(self, route: list):\n totalRouteCost = 0\n for case in range(1, len(route)):\n source = route[case - 1]\n destination = route[case]\n totalRouteCost += self.getDistance(source,destination)\n return totalRouteCost\n\n def initialPopulation(self):\n index = 0\n while index < self.populationSize:\n solution = [i for i in range(1,self.cityCount+1)]\n while self.isSolutionExists(self.population, solution):\n random.shuffle(solution)\n self.population.append(Chromosome(solution,self.getRouteCost(solution)))\n index+=1\n self.population.sort(key=lambda route: route.cost)\n self.elitePopulation.append(self.population[0])\n self.generationAverage.append((sum(x.cost for x in self.population)) / self.populationSize)\n\n def isSolutionExists(self, population, route):\n for gene in population:\n if gene.solution == route:\n return True\n return False\n\n def printPopulation(self):\n for route in self.population:\n print(f\"Route: {route.solution} with Cost of: {route.cost} \")\n\n def applyMutation(self, population, chromosome):\n tmpChromosome = Chromosome(chromosome.solution[::],chromosome.cost)\n while self.isSolutionExists(population, tmpChromosome.solution):\n mutationIndex1 = random.randint(0, len(tmpChromosome.solution) - 1)\n mutationIndex2 = random.randint(0, len(tmpChromosome.solution) - 1)\n if(mutationIndex1!=mutationIndex2):\n temp=tmpChromosome.solution[mutationIndex1]\n tmpChromosome.solution[mutationIndex1]=tmpChromosome.solution[mutationIndex2]\n tmpChromosome.solution[mutationIndex2]=temp\n chromosome.solution = tmpChromosome.solution[::]\n chromosome.cost=self.getRouteCost(chromosome.solution)\n \n def validateChromosome(self,chromosome):\n citiesList=[i for i in range(1,self.cityCount+1)]\n toReplace=[]\n for i in citiesList:\n if i not in chromosome.solution:\n toReplace.append(i)\n validRoute=[]\n for i in chromosome.solution:\n if i not in validRoute:\n validRoute.append(i)\n else:\n validRoute.append(toReplace.pop())\n return Chromosome(validRoute,self.getRouteCost(validRoute))\n\n\n def crossOver(self,firstChromosome,secondChromosome):\n index=random.randint(0,len(firstChromosome.solution))\n firstRoute=firstChromosome.solution[0:index]+secondChromosome.solution[index:len(firstChromosome.solution)]\n secondRoute = secondChromosome.solution[0:index] + firstChromosome.solution[index:len(firstChromosome.solution)]\n firstChild=Chromosome(firstRoute,self.getRouteCost(firstRoute))\n secondChild = Chromosome(secondRoute, self.getRouteCost(secondRoute))\n if (self.mutationRate > random.random()):\n self.applyMutation(self.population, firstChild)\n if (self.mutationRate > random.random()):\n self.applyMutation(self.population, secondChild)\n return self.validateChromosome(firstChild),self.validateChromosome(secondChild)\n\n def solve(self):\n self.lunchEvolution()\n plt.plot([x.cost for x in self.elitePopulation], label=\"Elites\")\n plt.xlabel('x - Generations')\n plt.ylabel('y - Cost ')\n plt.title('Evolution of elite chromosomes')\n plt.show()\n plt.plot([x for x in self.generationAverage], label=\"Average Cost\")\n plt.title('Averge Cost of each generatins')\n plt.xlabel('x - Generations')\n plt.ylabel('y - Cost ')\n plt.show()\n\n def lunchEvolution(self):\n self.drawChromosome(self.population[0],0)\n generation = 0\n while generation < self.generationCount:\n newPopulation=self.population[::]\n for index in range(0,self.populationSize,2):\n firstChild,secondChild=self.crossOver(self.population[index],self.population[index+1])\n newPopulation.append(firstChild)\n newPopulation.append(secondChild)\n newPopulation.sort(key=lambda chromosome: chromosome.cost)\n self.population.clear()\n self.population = newPopulation[0:self.populationSize]\n self.elitePopulation.append(self.population[0])\n self.generationAverage.append((sum(x.cost for x in self.population)) / self.populationSize)\n generation += 1\n if ((generation + 1) % 20) == 0:\n self.drawChromosome(self.population[0],generation+1)\n print(self.population[0].solution,self.population[0].cost)\n # self.printPopulation()\n\ncities = {}\ncityCount = 0\nwith open('./Cities List.txt') as f:\n for line in f.readlines():\n city = line.split(' ')\n cities[int(city[0])]={}\n cities[int(city[0])]['x']=int(city[1])\n cities[int(city[0])]['y']=int(city[2])\n cityCount += 1\n\n\n# populationSize, generationCount, mutationRate in %, cities ,cityCount\ngeneticSolver = GeneticSolver(50,200, 0.3,cities,cityCount)\ngeneticSolver.solve()\n", "repo_name": "MohammadAsadolahi/Solving-TSP-with-Evolutionary-Genetic-Algorithm-Heuristic-Python", "sub_path": "TSP Genetic solver.py", "file_name": "TSP Genetic solver.py", "file_ext": "py", "file_size_in_byte": 7251, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "matplotlib.pyplot.title", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.arrow", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "math.sqrt", "line_number": 54, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 69, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 89, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 90, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 114, "usage_type": "call"}, {"api_name": "random.random", "line_number": 119, "usage_type": "call"}, {"api_name": "random.random", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 129, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 129, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 130, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 131, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 131, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 132, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 132, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 133, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 134, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 134, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 135, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 135, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 136, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 136, "usage_type": "name"}]} +{"seq_id": "73799794928", "text": "\nimport operator\nimport bayes\nfrom cytoolz.curried import sorted\n\n\nlistPosts, listClasses = bayes.loadDataSet()\nmyVocabList = bayes.createVocabList(listPosts)\nmyVocabList = sorted(myVocabList)\nprint(myVocabList)\n\nretVal = bayes.setOfWords2Vec(myVocabList, listPosts[0])\nprint(retVal)\n\ntrainMat = []\nfor postingDoc in listPosts:\n print(postingDoc)\n\n # 返回 myVocabList 中的word是否在 postingDoc中出现过?\n trainMat.append( bayes.setOfWords2Vec(myVocabList, postingDoc) )\n\np0V, p1V, pAbusive = bayes.trainNB0(trainMat, listClasses)\n#print(\"p0V: %f, p1V: %f, pAbusive: %f\" %p0V %p1V %pAbusive )\nprint(p0V)\nprint(p1V)\nprint(pAbusive)", "repo_name": "bylikai/CodeDemo", "sub_path": "PythonDemo/MachineLearningInAction/chapter04/bayesTest.py", "file_name": "bayesTest.py", "file_ext": "py", "file_size_in_byte": 648, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "bayes.loadDataSet", "line_number": 7, "usage_type": "call"}, {"api_name": "bayes.createVocabList", "line_number": 8, "usage_type": "call"}, {"api_name": "cytoolz.curried.sorted", "line_number": 9, "usage_type": "call"}, {"api_name": "bayes.setOfWords2Vec", "line_number": 12, "usage_type": "call"}, {"api_name": "bayes.setOfWords2Vec", "line_number": 20, "usage_type": "call"}, {"api_name": "bayes.trainNB0", "line_number": 22, "usage_type": "call"}]} +{"seq_id": "36946620373", "text": "\"\"\"\nAuxilliary classes to facilitate testing.\n\nMembers\n=======\n\n``unittest``: Points to the ``unittest`` module in Python >= 2.7,\nand ``unittest2`` in Python <= 2.6.\nThis aids in creating version-agnostic test cases.\n\n\"\"\"\nfrom __future__ import print_function\nimport difflib\nimport json\nimport os as _os\nimport sys as _sys\nimport time as _time\nimport xml.etree.ElementTree as _elementtree\n\nimport mock as _mock\n\nfrom . import (\n compat as _compat,\n dochelpers as _dochelpers,\n itertoolsext as _itertoolsext,\n osutils as _osutils,\n pyobjcomparer as _pyobjcomparer,\n zipfileutils as _zipfileutils)\n\nif _sys.version_info < (2, 7):\n try:\n # noinspection PyUnresolvedReferences,PyPackageRequirements\n import unittest2 as unittest\n except ImportError:\n raise ImportError('unittest2 required for use in <= python2.6')\nelse:\n # noinspection PyUnresolvedReferences\n import unittest\n\n\nassertPyObjEqual = _pyobjcomparer.assert_compare\n\n\nclass FakeTestCase(unittest.TestCase):\n \"\"\"\n Sometimes, you want to use one of the assertion methods in this module,\n but don't have a testcase.\n You can just use an instance of this.\n \"\"\"\n def __init__(self):\n unittest.TestCase.__init__(self, '_ignoreme')\n\n def _ignoreme(self):\n pass\n\n\ndef assertBetween(tc, a, b, c, eq=False):\n \"\"\"\n Asserts that::\n\n if eq:\n a <= b <= c\n else:\n a < b < c\n \"\"\"\n le = tc.assertLessEqual if eq else tc.assertLess\n le(a, b)\n le(b, c)\n\n\ndef assertNumbersEqual(testcase, a, b, tolerance=0, msg=None):\n \"\"\"Asserts if the sizes are not within ``tolerance``.\"\"\"\n if abs(a - b) <= tolerance:\n return\n testcase.assertEqual(a, b, msg=msg)\n\n\ndef assertNumberSequencesEqual(testcase, a, b, tolerance=0):\n \"\"\"Assert that for an element in sequence ``a`` the\n corresponding element in ``b`` is equal within ``tolerance``.\n\n Also assert if the two sequences are not the same length.\n \"\"\"\n msg = 'Sequence length mismatch, a: %s, b: %s' % (a, b)\n testcase.assertEqual(len(a), len(b), msg)\n for i, pair in enumerate(zip(a, b)):\n element_a, element_b = pair\n try:\n assertNumbersEqual(testcase, element_a, element_b, tolerance)\n except AssertionError:\n raise AssertionError(\"%s != %s (element %s)\" % (a, b, i))\n\n\ndef assertStartsWith(s, start):\n if not s.startswith(start):\n raise AssertionError('%r must start with %r' % (s, start))\n\n\ndef assertEndsWith(s, end):\n if not s.endswith(end):\n raise AssertionError('%r must end with %r' % (s, end))\n\n\ndef assertEqualPretty(testcase, calculated, ideal, msg=None):\n \"\"\"Prints ideal and calculated on two lines, for easier analysis of\n what's different. Useful for sequences.\n\n :param testcase: An instance of unittest.TestCase\n :param ideal: The value that should have been calculated.\n :param calculated: the value that was calculated.\n \"\"\"\n try:\n testcase.assertEqual(ideal, calculated, msg)\n except AssertionError: # pragma: no cover\n print('ideal:', ideal)\n print('calc: ', calculated)\n raise\n\n\ndef assertCrcEqual(testcase, calcpath, idealpath, asLib=False):\n \"\"\"Asserts if crcs of paths are not equal.\n If ``DIFF_FILES_ON_CRC_FAIL`` is True, launch P4MERGE to\n diff the files.\n\n :param asLib: If True, do not print or show diff (function is being\n used as part of another assert function and not as a standalone).\n \"\"\"\n crc1 = _osutils.crc_from_filename(calcpath)\n crc2 = _osutils.crc_from_filename(idealpath)\n testcase.assertEqual(crc1, crc2,\n 'ideal: %(idealpath)s (%(crc2)s) !='\n ' calc: %(calcpath)s (%(crc1)s)' % locals())\n\n\ndef assertTextFilesEqual(testcase, calcpath, idealpath, compareLines=None):\n \"\"\"Asserts if the files are not equal. It first compares crcs, and if\n that fails, it compares the file contents as text (ie, mode 'r' and not\n 'rb'). The reason for this is that there can be discrepancies between\n newlines.\n\n :param compareLines: Callable that takes (calculated line, ideal line)\n and should assert if they are not equal. Defaults to\n ``testcase.assertEqual(calc line, ideal line)``.\n \"\"\"\n if compareLines is None:\n def compareLines(linecalc_, lineideal_):\n testcase.assertEqual(linecalc_.rstrip(), lineideal_.rstrip())\n try:\n assertCrcEqual(testcase, calcpath, idealpath, asLib=True)\n return\n except AssertionError:\n pass\n with open(calcpath) as fcalc:\n with open(idealpath) as fideal:\n for linecalc, lineideal in _itertoolsext.izip_longest(\n fcalc, fideal, fillvalue=''):\n compareLines(linecalc, lineideal)\n\n\ndef compareXml(x1, x2, reporter=_dochelpers.identity):\n \"\"\"Compares two xml elements.\n If they are equal, return True. If not, return False.\n Differences are reported by calling the ``reporter`` parameter,\n such as ::\n\n reporter('Tags do not match: Foo and Bar')\n\n :type x1: xml.etree.ElementTree.Element\n \"\"\"\n if x1.tag != x2.tag:\n reporter('Tags do not match: %s and %s' % (x1.tag, x2.tag))\n return False\n for name, value in x1.attrib.items():\n if x2.attrib.get(name) != value:\n reporter('Attributes do not match: %s=%r, %s=%r'\n % (name, value, name, x2.attrib.get(name)))\n return False\n for name in x2.attrib.keys():\n if name not in x1.attrib:\n reporter('x2 has an attribute x1 is missing: %s'\n % name)\n return False\n if not _compareXmlText(x1.text, x2.text):\n reporter('text: %r != %r' % (x1.text, x2.text))\n return False\n if not _compareXmlText(x1.tail, x2.tail):\n reporter('tail: %r != %r' % (x1.tail, x2.tail))\n return False\n # noinspection PyDeprecation\n cl1 = x1.getchildren()\n cl2 = x2.getchildren()\n if len(cl1) != len(cl2):\n reporter('children length differs, %i != %i'\n % (len(cl1), len(cl2)))\n return False\n i = 0\n for c1, c2 in zip(cl1, cl2):\n i += 1\n if not compareXml(c1, c2, reporter=reporter):\n reporter('children %i do not match: %s'\n % (i, c1.tag))\n return False\n return True\n\n\ndef _compareXmlText(t1, t2):\n if not t1 and not t2:\n return True\n if t1 == '*' or t2 == '*':\n return True\n return (t1 or '').strip() == (t2 or '').strip()\n\n\ndef assertXmlEqual(a, b):\n \"\"\"Asserts two xml documents are equal.\n\n :type a: str, unicode, xml.etree.ElementTree.Element\n :type b: str, unicode, xml.etree.ElementTree.Element\n \"\"\"\n if isinstance(a, _compat.StringTypes):\n a = _elementtree.fromstring(a)\n if isinstance(b, _compat.StringTypes):\n b = _elementtree.fromstring(b)\n diffs = []\n if not compareXml(a, b, diffs.append):\n print('XMLs not equal.')\n print('Diffs:', '\\n'.join(diffs))\n print('a:', a)\n print('b:', b)\n raise AssertionError('XMLs not equal.')\n\n\ndef assertZipEqual(calcpath, idealpath):\n try:\n _zipfileutils.compare_zip_files(calcpath, idealpath)\n return\n except _zipfileutils.FileComparisonError as ex:\n print('%s != %s' % (calcpath, idealpath))\n raise AssertionError(ex.args[0])\n\n\ndef assertJsonEqual(calc, ideal, out=_sys.stderr):\n \"\"\"Asserts if ``calc != ideal``.\n Will print the diff between the json dump of ``calc`` and ``ideal``\n to ``out`` before asserting,\n as a debugging aid.\n \"\"\"\n if calc == ideal:\n return\n gotstr = json.dumps(calc, indent=4).splitlines()\n idealstr = json.dumps(ideal, indent=4).splitlines()\n for d in difflib.unified_diff(gotstr, idealstr, 'calculated', 'ideal'):\n print(d, file=out)\n raise AssertionError('Objects differ. See stderr output.')\n\n\ndef assertFoldersEqual(\n testcase, calcfolder, idealfolder,\n compare=_dochelpers.pretty_func(assertCrcEqual, 'assertCrcEqual')):\n \"\"\"Asserts if any differences are found between two folders.\n\n :param compare: Assertion method to use.\n Pass in a custom function that switches off of extensions if you want.\n \"\"\"\n def getfiles(folder):\n allfiles = list(_osutils.iter_files(folder))\n cleanfiles = map(lambda f: f.replace(folder, '').lower(), allfiles)\n return sorted(cleanfiles), allfiles\n\n calcClean, calcAll = getfiles(calcfolder)\n idealClean, idealAll = getfiles(idealfolder)\n\n try:\n assertEqualPretty(testcase, calcClean, idealClean)\n for f1, f2 in zip(calcAll, idealAll):\n compare(testcase, f1, f2)\n except AssertionError: # pragma: no cover\n print('Compared Folders:')\n print('ideal:', idealfolder)\n print('calc: ', calcfolder)\n raise\n\n\ndef assertPermissionbitsEqual(\n testcase, calcpath, idealpath,\n bitgetter=_dochelpers.pretty_func(lambda p: _os.stat(p)[0], 'os.stat()[0]')):\n \"\"\"Asserts if permission bits are not equal.\"\"\"\n stat1 = bitgetter(calcpath)\n stat2 = bitgetter(idealpath)\n testcase.assertEqual(stat1, stat2)\n\n\nclass Patcher(object):\n \"\"\"Context manager that stores ``getattr(obj, attrname)``, sets it\n to ``newvalue`` on enter, and restores it on exit.\n\n :param newvalue: If _undefined, use a new Mock.\n \"\"\"\n def __init__(self, obj, attrname, newvalue=_dochelpers.default):\n self.obj = obj\n self.attrname = attrname\n if newvalue is _dochelpers.default:\n newvalue = _mock.Mock()\n self.newvalue = newvalue\n self.oldvalue = _dochelpers.default\n self._entered = False\n\n def __enter__(self):\n if self._entered:\n raise RuntimeError(\n 'Can only enter once, or havoc would occur '\n '(setting oldvalue to the currently mocked value)')\n self._entered = True\n self.oldvalue = getattr(self.obj, self.attrname)\n setattr(self.obj, self.attrname, self.newvalue)\n return self\n\n def __exit__(self, *_):\n if self.oldvalue != _dochelpers.default:\n setattr(self.obj, self.attrname, self.oldvalue)\n\n\ndef patch(testcase, *args):\n \"\"\"\n Create and enter :class:`Patcher` that will be exited\n on ``testcase`` teardown.\n\n :param args: Passed to the ``Patcher``.\n :return: The monkey patcher's newvalue.\n \"\"\"\n mp = Patcher(*args)\n testcase.addCleanup(mp.__enter__().__exit__)\n return mp.newvalue\n\n\nclass patch_time(object):\n\n ATTRS = ['clock', 'time', 'sleep']\n\n def __init__(self, starttime=0):\n self.starttime = starttime\n self.old = None\n self._now = 0\n\n def __enter__(self):\n self.old = [(a, getattr(_time, a)) for a in self.ATTRS]\n [setattr(_time, a, getattr(self, a)) for a in self.ATTRS]\n return self\n\n def __exit__(self, *_):\n [setattr(_time, a, attr) for (a, attr) in self.old]\n\n def clock(self):\n return self._now\n\n def time(self):\n return self._now + self.starttime\n\n def sleep(self, sec):\n self._now += sec\n\n\nclass CallCounter(object):\n \"\"\"\n Counts the number of times the instance is called.\n Available via the ``count`` attribute.\n\n Generally you should not create this class directly,\n and use the ``no_params`` and ``all_params`` class methods.\n Use the former when calling this should take no arguments,\n and the latter when it should take any arguments.\n \"\"\"\n def __init__(self, call):\n self.count = 0\n self._call = call\n\n def incr(self):\n self.count += 1\n return self.count\n\n def __call__(self, *args, **kwargs):\n return self._call(self, *args, **kwargs)\n\n @classmethod\n def no_params(cls):\n return CallCounter(lambda c: c.incr())\n\n @classmethod\n def all_params(cls):\n return CallCounter(lambda c, *args, **kwargs: c.incr())\n", "repo_name": "rgalanakis/brennivin", "sub_path": "brennivin/testhelpers.py", "file_name": "testhelpers.py", "file_ext": "py", "file_size_in_byte": 12055, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "20", "api": [{"api_name": "sys.version_info", "line_number": 30, "usage_type": "attribute"}, {"api_name": "unittest.TestCase", "line_number": 44, "usage_type": "attribute"}, {"api_name": "unittest.TestCase.__init__", "line_number": 51, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 51, "usage_type": "attribute"}, {"api_name": "xml.etree.ElementTree.fromstring", "line_number": 221, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 221, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.fromstring", "line_number": 223, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 223, "usage_type": "name"}, {"api_name": "sys.stderr", "line_number": 242, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 250, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 251, "usage_type": "call"}, {"api_name": "difflib.unified_diff", "line_number": 252, "usage_type": "call"}, {"api_name": "os.stat", "line_number": 286, "usage_type": "call"}, {"api_name": "mock.Mock", "line_number": 303, "usage_type": "call"}]} +{"seq_id": "27417782341", "text": "from setuptools import setup, find_packages\nimport os\n\n\nwith open('src/__init__.py', 'r') as f:\n for line in f:\n if line.startswith('__version__'):\n version = line.strip().split('=')[1].strip(' \\'\"')\n break\n else:\n version = '0.0.1'\n\n\nwith open('README.md', 'r', encoding='utf-8') as f:\n readme = f.read()\n\nwith open(os.path.join(os.path.dirname(__file__), 'requirements.txt'), \"r\", encoding=\"utf-8\") as f:\n REQUIRES = [ln.strip() for ln in f.readlines() if ln.strip()]\n\nPACKAGES = find_packages(exclude=('tests', 'tests.*'))\n\n\nkwargs = {\n 'name': 'audioset_downloader',\n 'version': version,\n 'description': 'cli to download examples of a specific class from google AudioSet',\n 'author': 'Antoine Daurat',\n 'author_email': 'ktonalberlin@gmail.com',\n 'url': 'https://github.com/ktonal/audioset-downloader',\n 'download_url': 'https://github.com/ktonal/audioset-downloader',\n 'license': 'MIT',\n \"keywords\": \"audioset dataset sound deep-learning\",\n 'python_requires': '>=3.6',\n 'install_requires': REQUIRES,\n 'package_data': {\"src\": [\"ontology.json\", \"class_names.txt\", \"csv/eval_segments.csv\",\n \"csv/balanced_train_segments.csv\", \"csv/unbalanced_train_segments.csv\"]},\n 'packages': PACKAGES,\n \"entry_points\": {\n 'console_scripts': [\n 'audioset-dl=src.main:download_cli',\n 'audioset-classes=src.main:print_classes',\n ]}\n\n}\n\nsetup(**kwargs)\n", "repo_name": "ktonal/audioset-downloader", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 1490, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "20", "api": [{"api_name": "os.path.join", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 17, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 20, "usage_type": "call"}, {"api_name": "setuptools.setup", "line_number": 46, "usage_type": "call"}]} +{"seq_id": "6100455011", "text": "import warnings\nimport numpy as np\n\nimport torch\nfrom torch import nn\n\n\ndef auto_pad(k, pad=None):\n # Pad to 'same'\n if pad is None:\n p = k // 2 if isinstance(k, int) else [x // 2 for x in k]\n return p\n\n\nclass Conv(nn.Module):\n # Standard convolution\n def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):\n super(Conv, self).__init__()\n self.conv = nn.Conv2d(c1, c2, k, s, auto_pad(k, p), groups=g, bias=False)\n self.bn = nn.BatchNorm2d(c2)\n self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())\n\n def forward(self, x):\n return self.act(self.bn(self.conv(x)))\n\n def forward_fuse(self, x):\n return self.act(self.conv(x))\n\n\nclass DWConv(Conv):\n def __init__(self, c1, c2, k=1, s=1, act=True):\n # np.gcd -> 最大公约数\n super(DWConv, self).__init__(c1, c2, k, s, g=np.gcd(c1, c2), act=act)\n\n\nclass Bottleneck(nn.Module):\n # Standard bottleneck\n def __init__(self, c1, c2, shortcut=True, g=1, e=0.5):\n super(Bottleneck, self).__init__()\n c_ = int(c2 * e)\n self.cv1 = Conv(c1, c_, 1, 1)\n self.cv2 = Conv(c_, c2, 3, 1, g=g)\n self.add = shortcut and c1 == c2\n\n def forward(self, x):\n return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))\n\n\nclass SPP(nn.Module):\n # Spatial pyramid pooling layer\n def __init__(self, c1, c2, k=(5, 9, 13)):\n super(SPP, self).__init__()\n c_ = int(c1 / 2)\n self.cv1 = Conv(c1, c_, 1, 1)\n self.cv2 = Conv(int(c_ * (len(k) + 1)), c2, 1, 1)\n self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])\n\n def forward(self, x):\n x = self.cv1(x)\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n return self.cv2(torch.cat([x] + [m(x) for m in self.m], dim=1))\n\n\nclass BottleneckCSP(nn.Module):\n # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks\n def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):\n super(BottleneckCSP, self).__init__()\n c_ = int(c1 * e)\n self.cv_a = nn.Conv2d(c1, c_, 1, 1, bias=False)\n self.cv_b = nn.Conv2d(c1, c_, 1, 1, bias=False)\n self.cv1 = nn.Conv2d(c_, c_, 1, 1, bias=False)\n self.bottlenecks = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])\n\n self.bn = nn.BatchNorm2d(2 * c_)\n self.act = nn.LeakyReLU(0.1, inplace=True)\n self.cv2 = Conv(c_ * 2, c2, 1, 1)\n\n def forward(self, x):\n a = self.cv_a(x)\n yb = self.cv1(self.bottlenecks(self.cv_b(x)))\n return self.cv2(self.act(self.bn(torch.cat((a, yb), dim=1))))\n\n\nclass Focus(nn.Module):\n def __init__(self, c1, c2, k1=1, s=1, p=None, g=1, act=True):\n super(Focus, self).__init__()\n self.conv = Conv(c1 * 4, c2, k1, s, p, g, act)\n\n def forward(self, x):\n return self.conv(torch.cat([\n x[..., ::2, ::2],\n x[..., 1::2, ::2],\n x[..., ::2, 1::2],\n x[..., 1::2, 1::2],\n ], dim=1))\n\n\nclass UpSample(nn.Module):\n # conv > up-sample > concat > c3\n def __init__(self, c1, c3, c2, scale=2, mode='nearest', n=1, shortcut=True, g=1):\n super(UpSample, self).__init__()\n self.cv1 = Conv(c1, c2)\n self.m = nn.Sequential(*[BottleneckCSP(c3, c2, shortcut, g, e=1.0) for _ in range(n)])\n self.up_sample_ = nn.Upsample(scale_factor=scale, mode=mode)\n\n def forward(self, x):\n if isinstance(x, list):\n x[0] = self.up_sample_(self.cv1(x[0]))\n if len(x) > 1:\n x = torch.cat(x, dim=1)\n else:\n x = x[0]\n return self.m(x)\n", "repo_name": "weixianwei0129/DBNet", "sub_path": "models/common.py", "file_name": "common.py", "file_ext": "py", "file_size_in_byte": 3765, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "torch.nn.Module", "line_number": 15, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 15, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.SiLU", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 21, "usage_type": "attribute"}, {"api_name": "torch.nn.Identity", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.gcd", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 36, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 49, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 49, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 56, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 56, "usage_type": "call"}, {"api_name": "warnings.catch_warnings", "line_number": 60, "usage_type": "call"}, {"api_name": "warnings.simplefilter", "line_number": 61, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 65, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 65, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 70, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 71, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 72, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 72, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 73, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 75, "usage_type": "name"}, {"api_name": "torch.nn.LeakyReLU", "line_number": 76, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 76, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 82, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 85, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 85, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 99, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 99, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 104, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 104, "usage_type": "name"}, {"api_name": "torch.nn.Upsample", "line_number": 105, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 105, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 111, "usage_type": "call"}]} +{"seq_id": "40287823818", "text": "from typing import List\n\nclass Solution:\n\tdef numSubmat(self, mat: List[List[int]]) -> int:\n\t\tm, n, res = len(mat), len(mat[0]), 0\n\t\thistogram = [0] * (n + 1)\n\t\tfor i in range(m):\n\t\t\tstack, dp = [-1], [0] * (n + 1)\n\t\t\tfor j in range(n):\n\t\t\t\thistogram[j] = 0 if mat[i][j] == 0 else histogram[j] + 1\n\t\t\t\twhile histogram[j] < histogram[stack[-1]]:\n\t\t\t\t\tstack.pop()\n\t\t\t\tdp[j] = dp[stack[-1]] + histogram[j] * (j - stack[-1])\n\t\t\t\tstack.append(j)\n\t\t\t\tprint(i, j, histogram, stack, dp)\n\t\t\tres += sum(dp)\n\t\t\tprint(i, res)\n\t\n\t\treturn res\n\t\t\t\t\n\t\t\t\t\t\t\n#mat = [[1,0,1],[1,1,0],[1,1,0]]\t\t\nmat = [[0,1,0],[0,1,1],[1,1,1], [1, 1, 1]]\t\t\na = Solution()\nprint(a.numSubmat(mat))\n", "repo_name": "Mvitimin/Python_algorithms", "sub_path": "DynamicProgramming/count-submatrices-with-all-ones.py", "file_name": "count-submatrices-with-all-ones.py", "file_ext": "py", "file_size_in_byte": 660, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "typing.List", "line_number": 4, "usage_type": "name"}]} +{"seq_id": "26451649931", "text": "from __future__ import absolute_import\nimport tornado.ioloop\nimport tornado.web\n\nfrom parsely import Parsely\nfrom parsely.secret import secrets\n\nAPI_KEY = \"samplesite.com\"\n\n\nclass TestSyncHandler(tornado.web.RequestHandler):\n def get(self):\n \"\"\"\n Demonstrates synchronous use of the Parsely client library\n \"\"\"\n p = Parsely(API_KEY, secrets[API_KEY])\n res = p.analytics(aspect=\"authors\")\n self.write(res)\n self.finish()\n\n\nclass TestCallbackHandler(tornado.web.RequestHandler):\n @tornado.web.asynchronous\n def get(self):\n \"\"\"\n Demonstrates asynchronous use of the Parsely client via a callback function\n\n Caller must be wrapped in @tornado.web.asynchronous\n Call to client method must include the _callback kwarg\n \"\"\"\n\n def callback(result):\n self.write(result)\n self.finish()\n\n p = Parsely(API_KEY, secrets[API_KEY])\n p.analytics(aspect=\"authors\", _callback=callback)\n\n\ndef get_app():\n application = tornado.web.Application(\n [(r\"/test_sync\", TestSyncHandler), (r\"/test_callback\", TestCallbackHandler)]\n )\n return application\n\n\nif __name__ == \"__main__\":\n application = get_app()\n application.listen(5000)\n tornado.ioloop.IOLoop.instance().start()\n", "repo_name": "Parsely/python-parsely", "sub_path": "server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 1309, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "20", "api": [{"api_name": "tornado.ioloop.web", "line_number": 11, "usage_type": "attribute"}, {"api_name": "tornado.ioloop", "line_number": 11, "usage_type": "name"}, {"api_name": "parsely.Parsely", "line_number": 16, "usage_type": "call"}, {"api_name": "parsely.secret.secrets", "line_number": 16, "usage_type": "name"}, {"api_name": "tornado.ioloop.web", "line_number": 22, "usage_type": "attribute"}, {"api_name": "tornado.ioloop", "line_number": 22, "usage_type": "name"}, {"api_name": "parsely.Parsely", "line_number": 36, "usage_type": "call"}, {"api_name": "parsely.secret.secrets", "line_number": 36, "usage_type": "name"}, {"api_name": "tornado.ioloop.web", "line_number": 23, "usage_type": "attribute"}, {"api_name": "tornado.ioloop", "line_number": 23, "usage_type": "name"}, {"api_name": "tornado.ioloop.web.Application", "line_number": 41, "usage_type": "call"}, {"api_name": "tornado.ioloop.web", "line_number": 41, "usage_type": "attribute"}, {"api_name": "tornado.ioloop", "line_number": 41, "usage_type": "name"}, {"api_name": "tornado.ioloop.ioloop.IOLoop.instance", "line_number": 50, "usage_type": "call"}, {"api_name": "tornado.ioloop.ioloop", "line_number": 50, "usage_type": "attribute"}, {"api_name": "tornado.ioloop", "line_number": 50, "usage_type": "name"}]} +{"seq_id": "72824798131", "text": "import xlrd, xlwt\nfrom xlrd import open_workbook\nfrom xlutils.copy import copy\n\nprint(\"print xls-file name for save\")\nname_xls = str(input())\nrb = open_workbook(name_xls)\ndb = open_workbook('General.xls')\nwb = copy(db)\n\nread = rb.sheet_by_index(0)\nread_db = db.sheet_by_index(0)\nsheet = wb.get_sheet(0)\n\nfor i in range(read.nrows - 1):\n for j in range(5):\n sheet.write(read_db.nrows + i, j, read.row_values(i+1)[0])\n\nwb.save('General.xls')\n\n", "repo_name": "FastGall/summerStats", "sub_path": "General_add.py", "file_name": "General_add.py", "file_ext": "py", "file_size_in_byte": 451, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "xlrd.open_workbook", "line_number": 7, "usage_type": "call"}, {"api_name": "xlrd.open_workbook", "line_number": 8, "usage_type": "call"}, {"api_name": "xlutils.copy.copy", "line_number": 9, "usage_type": "call"}]} +{"seq_id": "36846119281", "text": "import torch\nimport torchvision\nfrom torchvision import transforms, models, datasets\nfrom torch.utils.data import DataLoader, Dataset\nfrom torch import nn\nfrom torch import optim\nfrom torch.autograd import Variable\nimport helper\nfrom StratifiedSampler import StratifiedSampler\nimport numpy as np\n\nFOOD_PATH = \"/home/data/food-101\"\nIMG_PATH = FOOD_PATH+\"/images\"\nMETA_PATH = FOOD_PATH+\"/meta\"\n#TRAIN_PATH = FOOD_PATH+\"/train\"\n#VALID_PATH = FOOD_PATH+\"/valid\"\nMODEL_PATH = 'model_data/'\n\nimagenet_stats = [(0.485, 0.456, 0.406), (0.229, 0.224, 0.225)]\n\n# Return only images of certain classes\n# not sure if labels are continuous\ndef get_range_indices(target, label):\n label_indices = []\n\n for i in range(len(target)):\n if target[i] in label:\n label_indices.append(i)\n\n return label_indices\n\nclass MyDataset(torchvision.datasets.ImageFolder):\n def __init__(self, subset, transform=None):\n self.subset = subset\n self.transform = transform\n \n def __getitem__(self, index):\n x, y = self.subset[index]\n if self.transform:\n x = self.transform(x)\n return x, y\n \n def __len__(self):\n return len(self.subset)\n\nclass FOOD101():\n def __init__(self):\n self.train_ds, self.valid_ds, self.train_cls, self.valid_cls = [None]*4\n self.imgenet_mean = imagenet_stats[0]\n self.imgenet_std = imagenet_stats[1]\n \n def _get_tfms(self):\n train_tfms = transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(), \n transforms.ToTensor(),\n transforms.Normalize(self.imgenet_mean, self.imgenet_std)])\n \n valid_tfms = transforms.Compose([\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(self.imgenet_mean, self.imgenet_std)]) \n return train_tfms, valid_tfms \n \n def get_dataset(self,root_dir='home/data/food-101'):\n train_tfms, valid_tfms = self._get_tfms() # transformations\n whole_ds = datasets.ImageFolder(root=IMG_PATH)\n lengths = [int(len(whole_ds)*0.8), int(len(whole_ds)*0.2)]\n subsetTrain, subsetTest = torch.utils.data.dataset.random_split(whole_ds, lengths)\n subsetTrain.dataset.transform = train_tfms\n subsetTest.dataset.transform = valid_tfms\n #self.train_ds = MyDataset(subsetA, transform=train_tfms)\n #self.valid_ds = MyDataset(subsetB, transform=valid_tfms) \n #self.train_ds = datasets.ImageFolder(root=TRAIN_PATH, transform=train_tfms)\n #self.valid_ds = datasets.ImageFolder(root=VALID_PATH, transform=valid_tfms) \n self.train_classes = self.train_ds.classes\n self.valid_classes = self.valid_ds.classes\n\n assert self.train_classes==self.valid_classes\n return self.train_ds, self.valid_ds, self.train_classes\n\n \n def get_dls(self, train_ds, valid_ds, bs, n = 0, **kwargs):\n label_dataset = self.train_classes[1:n]\n train_indices = get_range_indices(self.train_ds.classes, label_dataset)\n bs = len(self.train_ds/bs)\n return (DataLoader(train_ds, batch_size=bs, sampler = torch.utils.data.sampler.SubsetRandomSampler(train_indices), shuffle=True, **kwargs),\n DataLoader(valid_ds, batch_size=bs, shuffle=False, **kwargs)) ", "repo_name": "shyamnathp/Deep-Learning", "sub_path": "Food_Project/food101.py", "file_name": "food101.py", "file_ext": "py", "file_size_in_byte": 3391, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "torchvision.datasets", "line_number": 32, "usage_type": "attribute"}, {"api_name": "torchvision.transforms.Compose", "line_number": 53, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 53, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomResizedCrop", "line_number": 54, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 54, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomHorizontalFlip", "line_number": 55, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 55, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 56, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 56, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 57, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 57, "usage_type": "name"}, {"api_name": "torchvision.transforms.Compose", "line_number": 59, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 59, "usage_type": "name"}, {"api_name": "torchvision.transforms.CenterCrop", "line_number": 60, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 60, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 61, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 61, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 62, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 62, "usage_type": "name"}, {"api_name": "torchvision.datasets.ImageFolder", "line_number": 67, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 67, "usage_type": "name"}, {"api_name": "torch.utils.data.dataset.random_split", "line_number": 69, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 69, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.utils.data.sampler.SubsetRandomSampler", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 87, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 88, "usage_type": "call"}]} +{"seq_id": "32441755376", "text": "__author__ = 'Jonny Lamb'\n__copyright__ = 'Copyright © 2008 Jonny Lamb'\n__license__ = 'MIT'\n\nimport logging\nimport hashlib\nimport os\n\nfrom pylons import config\n\nlog = logging.getLogger(__name__)\n\ndef parse_section(section):\n \"\"\"\n Works out the component and section from the \"Section\" field.\n Sections like `python` or `libdevel` are in main.\n Sections with a prefix, separated with a forward-slash also show the component.\n It returns a list of strings in the form [component, section].\n\n For example, `non-free/python` has component `non-free` and section `python`.\n\n ``section``\n Section name to parse.\n \"\"\"\n if '/' in section:\n return section.split('/')\n else:\n return ['main', section]\n\ndef get_package_dir(source):\n \"\"\"\n Returns the directory name where the package with name supplied as the first argument\n should be installed.\n\n ``source``\n Source package name to use to work out directory name.\n \"\"\"\n if source.startswith('lib'):\n return os.path.join(source[:4], source)\n else:\n return os.path.join(source[0], source)\n\ndef md5sum(filename):\n \"\"\"\n Returns the md5sum of a file specified.\n\n ``filename``\n File name of the file to md5sum.\n \"\"\"\n try:\n f = file(filename, 'rb')\n except:\n raise AttributeError('Failed to open file %s.' % filename)\n\n sum = hashlib.md5()\n while True:\n chunk = f.read(10240)\n if not chunk:\n break\n sum.update(chunk)\n\n f.close()\n\n return sum.hexdigest()\n\ndef random_hash():\n s = os.urandom(20)\n return hash_it(s)\n\ndef hash_it(s):\n if type(s) == unicode:\n s = s.encode('utf-8')\n return hashlib.md5(s).hexdigest()\n", "repo_name": "nxvipin/Debexpo", "sub_path": "debexpo/lib/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 1741, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "logging.getLogger", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path", "line_number": 39, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "attribute"}, {"api_name": "hashlib.md5", "line_number": 55, "usage_type": "call"}, {"api_name": "os.urandom", "line_number": 67, "usage_type": "call"}, {"api_name": "hashlib.md5", "line_number": 73, "usage_type": "call"}]} +{"seq_id": "34361853345", "text": "from datetime import datetime\nfrom datetime import date\nfrom pprint import pformat\nfrom six import iteritems\nimport re\nimport json\n\nfrom ..utils import sanitize_for_serialization\n\n# type hinting support\nfrom typing import TYPE_CHECKING\nfrom typing import List\nfrom typing import Dict\n\nif TYPE_CHECKING:\n from . import KnowledgeGroupStatistics\n from . import UnansweredGroupSuggestedDocument\n from . import UnansweredPhraseGroup\n\nclass UnansweredGroup(object):\n \"\"\"\n NOTE: This class is auto generated by the swagger code generator program.\n Do not edit the class manually.\n \"\"\"\n def __init__(self) -> None:\n \"\"\"\n UnansweredGroup - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n and the value is json key in definition.\n \"\"\"\n self.swagger_types = {\n 'id': 'str',\n 'label': 'str',\n 'phrase_groups': 'list[UnansweredPhraseGroup]',\n 'suggested_documents': 'list[UnansweredGroupSuggestedDocument]',\n 'statistics': 'KnowledgeGroupStatistics',\n 'self_uri': 'str'\n }\n\n self.attribute_map = {\n 'id': 'id',\n 'label': 'label',\n 'phrase_groups': 'phraseGroups',\n 'suggested_documents': 'suggestedDocuments',\n 'statistics': 'statistics',\n 'self_uri': 'selfUri'\n }\n\n self._id = None\n self._label = None\n self._phrase_groups = None\n self._suggested_documents = None\n self._statistics = None\n self._self_uri = None\n\n @property\n def id(self) -> str:\n \"\"\"\n Gets the id of this UnansweredGroup.\n The globally unique identifier for the object.\n\n :return: The id of this UnansweredGroup.\n :rtype: str\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id: str) -> None:\n \"\"\"\n Sets the id of this UnansweredGroup.\n The globally unique identifier for the object.\n\n :param id: The id of this UnansweredGroup.\n :type: str\n \"\"\"\n \n\n self._id = id\n\n @property\n def label(self) -> str:\n \"\"\"\n Gets the label of this UnansweredGroup.\n Knowledge base unanswered group label\n\n :return: The label of this UnansweredGroup.\n :rtype: str\n \"\"\"\n return self._label\n\n @label.setter\n def label(self, label: str) -> None:\n \"\"\"\n Sets the label of this UnansweredGroup.\n Knowledge base unanswered group label\n\n :param label: The label of this UnansweredGroup.\n :type: str\n \"\"\"\n \n\n self._label = label\n\n @property\n def phrase_groups(self) -> List['UnansweredPhraseGroup']:\n \"\"\"\n Gets the phrase_groups of this UnansweredGroup.\n Represents a list of phrase groups inside an unanswered group\n\n :return: The phrase_groups of this UnansweredGroup.\n :rtype: list[UnansweredPhraseGroup]\n \"\"\"\n return self._phrase_groups\n\n @phrase_groups.setter\n def phrase_groups(self, phrase_groups: List['UnansweredPhraseGroup']) -> None:\n \"\"\"\n Sets the phrase_groups of this UnansweredGroup.\n Represents a list of phrase groups inside an unanswered group\n\n :param phrase_groups: The phrase_groups of this UnansweredGroup.\n :type: list[UnansweredPhraseGroup]\n \"\"\"\n \n\n self._phrase_groups = phrase_groups\n\n @property\n def suggested_documents(self) -> List['UnansweredGroupSuggestedDocument']:\n \"\"\"\n Gets the suggested_documents of this UnansweredGroup.\n Represents a list of documents that may be linked to an unanswered group\n\n :return: The suggested_documents of this UnansweredGroup.\n :rtype: list[UnansweredGroupSuggestedDocument]\n \"\"\"\n return self._suggested_documents\n\n @suggested_documents.setter\n def suggested_documents(self, suggested_documents: List['UnansweredGroupSuggestedDocument']) -> None:\n \"\"\"\n Sets the suggested_documents of this UnansweredGroup.\n Represents a list of documents that may be linked to an unanswered group\n\n :param suggested_documents: The suggested_documents of this UnansweredGroup.\n :type: list[UnansweredGroupSuggestedDocument]\n \"\"\"\n \n\n self._suggested_documents = suggested_documents\n\n @property\n def statistics(self) -> 'KnowledgeGroupStatistics':\n \"\"\"\n Gets the statistics of this UnansweredGroup.\n Statistics object containing the various hit counts for an unanswered group\n\n :return: The statistics of this UnansweredGroup.\n :rtype: KnowledgeGroupStatistics\n \"\"\"\n return self._statistics\n\n @statistics.setter\n def statistics(self, statistics: 'KnowledgeGroupStatistics') -> None:\n \"\"\"\n Sets the statistics of this UnansweredGroup.\n Statistics object containing the various hit counts for an unanswered group\n\n :param statistics: The statistics of this UnansweredGroup.\n :type: KnowledgeGroupStatistics\n \"\"\"\n \n\n self._statistics = statistics\n\n @property\n def self_uri(self) -> str:\n \"\"\"\n Gets the self_uri of this UnansweredGroup.\n The URI for this object\n\n :return: The self_uri of this UnansweredGroup.\n :rtype: str\n \"\"\"\n return self._self_uri\n\n @self_uri.setter\n def self_uri(self, self_uri: str) -> None:\n \"\"\"\n Sets the self_uri of this UnansweredGroup.\n The URI for this object\n\n :param self_uri: The self_uri of this UnansweredGroup.\n :type: str\n \"\"\"\n \n\n self._self_uri = self_uri\n\n def to_dict(self):\n \"\"\"\n Returns the model properties as a dict\n \"\"\"\n result = {}\n\n for attr, _ in iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_json(self):\n \"\"\"\n Returns the model as raw JSON\n \"\"\"\n return json.dumps(sanitize_for_serialization(self.to_dict()))\n\n def to_str(self):\n \"\"\"\n Returns the string representation of the model\n \"\"\"\n return pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"\n For `print` and `pprint`\n \"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"\n Returns true if both objects are equal\n \"\"\"\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"\n Returns true if both objects are not equal\n \"\"\"\n return not self == other\n\n", "repo_name": "MyPureCloud/platform-client-sdk-python", "sub_path": "build/PureCloudPlatformClientV2/models/unanswered_group.py", "file_name": "unanswered_group.py", "file_ext": "py", "file_size_in_byte": 7447, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 16, "dataset": "github-code", "pt": "20", "api": [{"api_name": "typing.TYPE_CHECKING", "line_number": 15, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 108, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 119, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 132, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 143, "usage_type": "name"}, {"api_name": "six.iteritems", "line_number": 209, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 233, "usage_type": "call"}, {"api_name": "utils.sanitize_for_serialization", "line_number": 233, "usage_type": "call"}, {"api_name": "pprint.pformat", "line_number": 239, "usage_type": "call"}]} +{"seq_id": "26122604069", "text": "from django.urls import path\nfrom myapp1 import views\n\napp_name = 'myapp1'\n\nurlpatterns = [\n\n path('', views.MyIndexView.as_view(), name=\"my_index_view\"),\n path('dashboard/', views.DashboardView.as_view(), name=\"dashboard_view\"),\n # To replace \"success page\" and default the index page with '' (blank).\n path('index/', views.MyIndexView.as_view(), name=\"my_index_view\"), #Specifies the path for index.html\n # Name the attribute of the path the same as the class but with underscores: \"my_index_view\"\n # MyIndexView is the name of the class from views.py\n # Create/Specify one path for everytime you want to render/view a html file in a browser\n path('features/', views.FeaturesView.as_view(), name=\"features_view\"),\n path('aboutus/', views.AboutView.as_view(), name=\"aboutus_view\"),\n path('contactus/', views.ContactView.as_view(), name=\"contactus_view\"),\n path('signup/', views.SignUpView.as_view(), name=\"signup_view\"),\n path('signin/', views.SignInView.as_view(), name=\"signin_view\"),\n path('createPatient/', views.CreatePatientView.as_view(), name=\"createpatient_view\"),\n path('createPhlebotomist/', views.CreatePhlebotomistView.as_view(), name=\"createphlebotomist_view\"),\n path('createLocation/', views.CreateLocationView.as_view(), name=\"createlocation_view\"),\n path('rolefinalization/', views.RoleFinalizationView.as_view(), name=\"rolefinalization_view\"),\n path('addDonor/', views.AddDonorView.as_view(), name=\"addDonor_view\"),\n path('addDonation/', views.AddDonationView.as_view(), name=\"addDonation_view\"),\n path('addTransaction/', views.AddTransactionView.as_view(), name=\"addTransaction_view\"),\n path('logout/', views.logout, name='logout')\n]", "repo_name": "NietzscheArboladura/Blood-bank", "sub_path": "mydbprojectponce/myapp1/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 1713, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "myapp1.views.MyIndexView.as_view", "line_number": 8, "usage_type": "call"}, {"api_name": "myapp1.views.MyIndexView", "line_number": 8, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 8, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "myapp1.views.DashboardView.as_view", "line_number": 9, "usage_type": "call"}, {"api_name": "myapp1.views.DashboardView", "line_number": 9, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 9, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "myapp1.views.MyIndexView.as_view", "line_number": 11, "usage_type": "call"}, {"api_name": "myapp1.views.MyIndexView", "line_number": 11, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 11, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "myapp1.views.FeaturesView.as_view", "line_number": 15, "usage_type": "call"}, {"api_name": "myapp1.views.FeaturesView", "line_number": 15, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 15, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 16, "usage_type": "call"}, {"api_name": "myapp1.views.AboutView.as_view", "line_number": 16, "usage_type": "call"}, {"api_name": "myapp1.views.AboutView", "line_number": 16, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 16, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 17, "usage_type": "call"}, {"api_name": "myapp1.views.ContactView.as_view", "line_number": 17, "usage_type": "call"}, {"api_name": "myapp1.views.ContactView", "line_number": 17, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 17, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 18, "usage_type": "call"}, {"api_name": "myapp1.views.SignUpView.as_view", "line_number": 18, "usage_type": "call"}, {"api_name": "myapp1.views.SignUpView", "line_number": 18, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 18, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 19, "usage_type": "call"}, {"api_name": "myapp1.views.SignInView.as_view", "line_number": 19, "usage_type": "call"}, {"api_name": "myapp1.views.SignInView", "line_number": 19, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 19, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 20, "usage_type": "call"}, {"api_name": "myapp1.views.CreatePatientView.as_view", "line_number": 20, "usage_type": "call"}, {"api_name": "myapp1.views.CreatePatientView", "line_number": 20, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 20, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 21, "usage_type": "call"}, {"api_name": "myapp1.views.CreatePhlebotomistView.as_view", "line_number": 21, "usage_type": "call"}, {"api_name": "myapp1.views.CreatePhlebotomistView", "line_number": 21, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 21, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 22, "usage_type": "call"}, {"api_name": "myapp1.views.CreateLocationView.as_view", "line_number": 22, "usage_type": "call"}, {"api_name": "myapp1.views.CreateLocationView", "line_number": 22, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 22, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 23, "usage_type": "call"}, {"api_name": "myapp1.views.RoleFinalizationView.as_view", "line_number": 23, "usage_type": "call"}, {"api_name": "myapp1.views.RoleFinalizationView", "line_number": 23, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 23, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 24, "usage_type": "call"}, {"api_name": "myapp1.views.AddDonorView.as_view", "line_number": 24, "usage_type": "call"}, {"api_name": "myapp1.views.AddDonorView", "line_number": 24, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 24, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 25, "usage_type": "call"}, {"api_name": "myapp1.views.AddDonationView.as_view", "line_number": 25, "usage_type": "call"}, {"api_name": "myapp1.views.AddDonationView", "line_number": 25, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 25, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 26, "usage_type": "call"}, {"api_name": "myapp1.views.AddTransactionView.as_view", "line_number": 26, "usage_type": "call"}, {"api_name": "myapp1.views.AddTransactionView", "line_number": 26, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 26, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 27, "usage_type": "call"}, {"api_name": "myapp1.views.logout", "line_number": 27, "usage_type": "attribute"}, {"api_name": "myapp1.views", "line_number": 27, "usage_type": "name"}]} +{"seq_id": "2734334604", "text": "import numpy as np\nimport pandas as pd\nimport requests\nimport seaborn as sb\n#from collections import namedtuple\nfrom datetime import datetime, timedelta #,date\nfrom dateutil.relativedelta import relativedelta\nimport matplotlib.pyplot as plt\n\nimport pickle\nimport cx_Oracle\nfrom pandas.io import sql\n\nimport json\nfrom bs4 import BeautifulSoup\nimport xml.etree.ElementTree as etree\nimport sys\nimport os\n#import wget\nimport re\n\nimport logging\nlogger = logging.getLogger('stormers')\n\nfrom flask import redirect,session\n# cur_dir = os.path.dirname(__file__)\n\n'''need this variable declaration here for scripts that refer\n to data files stored here '''\n\n# cur_dir = '/home/accounts/vinorda/sr-ask-11966/data/'\n# cur_dir = '/home/accounts/vinorda/data/'\n# cur_dir = '/home/bou/windows-shared/data/'\n\n\n# taf lists for individidual ARFOR areas.\narea40 = ['YBBN', 'YBAF', 'YAMB', 'YBSU', 'YBCG', 'YTWB','YBOK','YBWW',\\\n 'YHBA','YMYB','YBUD','YGLA','YBRK','YKRY','YTNG','YSMH' ]\narea41 = ['YROM', 'YSGE','YBCV', 'YLRE','YBDV', 'YLLE', 'YWDH','YTGM']\narea43 = ['YBMA', 'YCCY', 'YJLC', 'YRMD', 'YHUG', 'YTMO', 'YTEE', 'YWTN']\narea44 = ['YBTL', 'YBMK', 'MKY', 'YBPN','YBHM', 'YEML', 'YMRB', 'YCMT' ]\narea45 = ['YBCS','YBWP','YHID','YLHR','YCKN','YGTN','YIFL',\\\n 'YMBA','YCOE','YNTN','YBKT','YCNY','YMTI','YKOW','YBSG','YLZI']\n\nqld = area40+area41+area43+area44+area45\nnt = ['YBAS','YAYE', 'YBTI', 'YSNB','YJVN','YBYU', 'YPDN', 'WPDL', 'YELD', 'YPGV', 'YGTE', 'YHOO',\\\n 'YJAB', 'YMGD', 'YMGB','YMHU','YNGU','YPKT','YPTN','YTNK','YTGT','YYND','YGLS','YKNT']\nwa = ['YARG','YBRY','YBWX','YBGD','YBRM','YCHK','YPXM','YPCC','YCWA','YDBY','YFTZ','YTST'\\\n 'YFDF','YHLC','YPKA','YPKU','YWYM','YLBD','YTTI','YNWN','YOLW','YPBO','YPPD','YCIN',\\\n 'YPLM','YSOL','YTEF','YANG',\\\n 'YBLW','YGEL','YPJT','YMOG','YPEA','YPPH','YRTI','YFRT','YABA','YBUN','YBLN','YESP','YCAR','YSHK']\nnsw=['YARM','YBNA','YSBK','YBTH','YSCN','YCNK','YCFS','YCBB','YSDU','YGLI','YGFN','YKMP','YLIS',\\\n 'YLHI','YMND','YMOR','YMDG','YNBR','YSNF','YSNW','YORG','YPKS','YPMQ','YSRI','YSCO','YSSY','YSTW',\\\n 'YTRE','YWLM','YSCB','YCOM','YGLB','YSHW','YSHL','YMER','YMRY','YSWG','YYNG']\nvic=['YMAY','YMAV','YBNS','YBLT','YBDG','YMES','YMEN','YFLI','YHML','YHSM','YKII','YLTV','YMNG','YMML',\\\n 'YMIA','YMMB','YMTG','YPOD','YREN','YSHT','YSWH','YWGT','YWBL']\nsa=['YPAD','YPED','YKSC','YMTG','YPPF','YPAG','YPLC','YWHA','YBHI','YCBP','YLEC','YMIA','YOLD','YPWR',\\\n 'YOOM','YCDU','YFRT','YWUD']\n\ndefence = ['YPCC', 'YPXM', 'YPDN', 'YPTN', 'YCIN', 'YPLM', 'YBSG', 'YBTL', 'YBOK', 'YAMB',\\\n 'YWLM', 'YSRI', 'YSCB', 'YSNW', 'YMES', 'YMPC', 'YPED', 'YPWR', 'YPEA','YSHW',\\\n 'YSBK','YARM','YCNK','YSCO','YSTW','YCOM','YSWG']\n\n#https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/\n#import json\n#preci_metadata_file = 'precis_metadata.json'\n#taf_metadata_file = 'taf_metadata.json'\n#with open(filename, 'r') as f:\n# datastore = json.load(f)\n# for sta in nt:\n# print(sta, ' Name: ' + datastore[sta]['NAME'])\n# for sta in nt+wa:\n# print(sta, ':', datastore[sta]['WMO_NUM'] )\n# print(sta, ':', datastore[sta]['BOM_ID'] )\n\n\n'''pdl 97390 'YYND':94324 - only 9am synops-> use Territory Grape Farm TGFM 94328,'YTGT':use Rabbit Flats 95322\nBathurst Is YBTI uses Point Fawcett 94122 which is actually on the far west coast of the island and gets NW to SW seabreeze\nYBTI is almost near Wurrumiyanga (the preci location) - this is on the far east coast so gets SE seabreeze no vi/ceilo here!\nYBYU':99126\nBAYU UNDAN (LIBERDADE SHIP) 401476\nhttp://sdbweb.bom.gov.au:8891/sitesdb/plsql/SDB_SD_details.p?NstnNum=401476&stnsysID=\n'''\n\n#avid to wmo number mappings\navid_wmo_dict = \\\n {'YBBN':94578,'YBAF':94575,'YAMB':94568,'YBSU':94569,'YBCG':94592,\\\n 'YTWB':95551,'YBOK':94552,'YBWW':99435,'YHBA':95565,'YMYB':94567,'YBUD':94387,\\\n 'YGLA':94381,'YBRK':94374,'YSMH':94370,'YKRY':94549,'YTNG':94376,\\\n 'YROM':94515,'YBCV':94510,'YLRE':94346,'YWTN':94342,'YBDV':95482, 'YLLE':95487, \\\n 'YWDH':94489,'YTGM':95492,'YSGE':94517,'YBMA':94332,'YCCY':94335,'YJLC':94337,\\\n 'YRMD':94341,'YHUG':94343,'YTMO':94336,'YTEE':94338,\\\n 'YBTL':94294,'YBMK':95367,'MKY':94367,'YBPN':94365,'YBHM':94368,\\\n 'YEML':94363,'YMRB':94397,'YCMT':94395,'YBCS':94287,'YBWP':94170,\\\n 'YHID':94174,'YLHR':94186,'YCKN':95283,'YGTN':94274,'YIFL':94280,'YMBA':95286,\\\n 'YCOE':94183,'YNTN':94266,\\\n 'YBKT':94260,'YCNY':94261,'YMTI':94254,'YKOW':94268,'YBSG':94171, 'YLZI':94188, \\\n 'YGLS':94461,'YKNT':94321,'YBAS':94326,'YAYE':94462,'YBYU':401476,'YJVN':401476, 'YPDN':94120,'YBTI':94122,'YSNB':94119,\\\n 'WPDL':99055,'YELD':95146,'YPGV':94150,'YGTE':94153, 'YTTI':94102,'YTST':95101,\\\n 'YHOO':94231,'YJAB':94137,'YMGD':95142,'YMGB':94140,'YMHU':94239,'YNGU':94106,\\\n 'YPKT':95111,'YPTN':94131,'YTNK':94238,'YYND':94328,'YTGT':95322,\\\n 'YARG':94217,'YBRY':99313,'YBWX':95304,'YBGD':94316,'YBRM':94203,'YCHK':99737,\\\n 'YPXM':96995,'YPCC':96996,'YCWA':99312,\\\n 'YDBY':95205,'YFTZ':94206,'YFDF':99736,'YHLC':94212,'YPKA':95307,'YPKU':94216,\\\n 'YWYM':95214,'YLBD':99206,'YTTI':95101,'YNWN':94317,\\\n 'YOLW':95305,'YPBO':94316,'YPPD':94312,'YCIN':94204,'YPLM':94302,'YSOL':99217,\\\n 'YTEF':94319,'YANG':99314,\n 'YSSY':94767,'YSBK':95765,'YSRI':95753,'YSCN':94755,'YSHW':95761,'YSHL':95748,'YWLM':94776,\n 'YPAD':94672,'YSCB':94926, 'YPPH':94610}\n\n# Use Cape Flattery Sta Id 031213, WMO 94188 for Lizard Is\n\n\n# avid to climate statistics file numbers on climate data online servers BOM_ID in Callums FIle\navid_adams = \\\n {'YBBN':'040842','YBAF':'040211','YAMB':'040004','YBSU':'040861', 'YBCG':'040717',\\\n 'YTWB':'041529','YBOK':'041359','YBWW':'041359',\\\n 'YKRY':'040922','YTNG':'039089','YGLA':'039326','YBRK':'039083',\\\n 'YBUD':'039128','YHBA':'040405','YMYB':'040126',\\\n 'YROM':'043091','YBCV':'044021','YLRE':'036031', 'YWTN':'4136',\\\n 'YBDV':'038026','YLLE':'045009','YWDH':'4135','YTGM':'045025','YSGE':'4110',\\\n 'YBMA':'029127','YCCY':'029141','YJLC':'029058', 'YRMD':'4100', 'YHUG':'030022',\\\n 'YTMO':'037034', 'YTEE':'037036',\\\n 'YBTL':'032040', 'YBMK':'033045', 'MKY':'033119', 'YBPN':'033247','YBHM':'033106',\\\n 'YEML':'4042', 'YMRB':'034038', 'YCMT':'4147','YBAS':'15590','YAYE':'15635',\\\n 'YPDN':'14015','YGLS':'13017',\\\n\t\t 'YPGV':'14508','YGTE':'14518','YHOO':'14829','YJAB':'14198','YMGD':'14405','YMGB':'14404','YMHU':'14704','YKNT':15664,\\\n\t\t 'YPKT':'14948','YPTN':'14932','YTNK':'15135','YARG':'2064','YBRY':'505053','YBWX':'5094',\\\n\t\t 'YBGD':'505052','YBRM':'3003','YCHK':'505049','YPXM':'200790','YPCC':'200284','YCWA':'505051',\\\n\t\t 'YDBY':'3032','YFTZ':'3093','YFDF':'505056','YHLC':'2012','YPKA':'4083','YPKU':'2056','YLBD':'503016',\\\n\t\t 'YTST':'1020','YTTI':'1007','YNWN':'7176','YOLW':'5017','YPBO':'7185','YPPD':'4032','YCIN':'3080','YPLM':'5007',\\\n\t\t 'YSOL':'505060','YTEF':'13030','YANG':'507501','YPCC':'200284','YPXM':'200790',\\\n 'YSSY':'066037','YSBK':'066137','YSRI':'067105','YSCN':'068192','YSHL':'068241'}\n\n\n# avid to preci/town location mappings\n\navid_preci = \\\n {'YBBN':'Brisbane','YBAF':'Oxley', 'YAMB':'Ipswich', 'YBSU':'Maroochydore', 'YBCG':'Coolangatta',\\\n 'YTWB':'Toowoomba','YBOK':'Oakey','YBWW':'Toowoomba',\\\n 'YKRY':'Kingaroy', 'YTNG':'Biloela', 'YGLA':'Gladstone','YBRK':'Rockhampton','YSMH':'Samuel Hill',\\\n 'YBUD':'Bundaberg','YHBA':'Hervey Bay','YMYB':'Maryborough',\\\n 'YROM':'Roma', 'YBCV':'Charleville', 'YLRE':'Longreach', 'YWTN':'Winton',\\\n 'YBDV':'Birdsville', 'YLLE':'Thargomindah', 'YWDH':'Windorah','YTGM':'Thargomindah','YSGE':'St George',\\\n 'YBMA':'Mount Isa', 'YCCY':'Cloncurry', 'YJLC':'Julia Creek', 'YRMD':'Richmond', 'YHUG':'Hughenden',\\\n 'YTMO':'Urandangi', 'YTEE':'Urandangi',\\\n 'YBTL':'Townsville', 'YBMK':'Mackay','YBPN':'Proserpine','YBHM':'Hamilton Island',\\\n 'YEML':'Emerald', 'YMRB':'Moranbah', 'YCMT':'Clermont',\\\n 'YBCS':'Cairns','YBWP':'Weipa','YHID':'Thursday Island','YLHR':'Lockhart River',\\\n 'YCKN':'Cooktown','YGTN':'Georgetown','YIFL':'Innisfail',\\\n 'YMBA':'Mareeba','YCOE':'Coen','YNTN':'Normanton','YBKT':'Burketown',\\\n 'YCNY':'Doomadgee','YMTI':'Mornington Island','YKOW':'Kowanyama' ,\\\n\t 'YBAS':'Alice Springs','YAYE':'Yulara','YPDN':'Darwin','YBTI':'Wurrumiyanga','YSNB':'Pirlangimpi',\\\n 'YELD':'Ngayawili','YPGV':'Nhulunbuy Airport','YGTE':'Alyangula', 'YTGT':'Rabbit Flat',\\\n 'YHOO':'Lajamanu','YJAB':'Jabiru','YMGD':'Maningrida','YMGB':'Milingimbi','YMHU':'Borroloola','YNGU':'Ngukurr','YPKT':'Wadeye',\\\n 'YPTN':'Katherine','YTNK':'Tennant Creek','YYND':'Yuendumu','YGLS':'Docker River','YKNT':'Wulungurru',\\\n 'YARG':'Argyle','YBRY':'Barimunya','YBWX':'Barrow Island','YBGD': 'Paraburdoo', 'YWYM':'Wyndham', \\\n 'YBRM':'Broome','YCHK':'Paraburdoo','YPXM':'Christmas Island','YPCC':'Cocos Island','YCWA':'Paraburdoo',\\\n 'YDBY':'Derby','YFTZ':'Fitzroy Crossing','YFDF':'Paraburdoo',\\\n 'YHLC':'Halls Creek','YPKA':'Karratha','YPKU':'Kununurra','YLBD':'Lombadina',\\\n 'YTTI':'Kalumburu','YTST':'Kalumburu','YNWN':'Newman',\\\n 'YOLW':'Onslow','YPBO':'Paraburdoo','YPPD':'Port Hedland','YCIN':'Derby','YPLM':'Exmouth',\\\n 'YSOL':'Tom Price','YTEF':'Telfer','YANG':'Newman',\\\n 'YSSY':'Mascot','YSBK':'Liverpool','YSRI':'Richmond','YSCN':'Camden','YSHW':'Liverpool',\\\n 'YSHL':'Albion Park','YWLM':'Raymond Terrace',\\\n 'YSCB':'Canberra','YMML':'Melbourne','YPAD':'Adelaide','YPPH':'Perth'}\n\n\n# avid to climate station numbers\n# to read from Daily Weather Observations located at\n# http://www.bom.gov.au/climate/dwo/YYYYMM/html/IDCJDWxxxx.YYYYMM.shtml\n# e.g http://www.bom.gov.au/climate/dwo/201603/html/IDCJDW4003.201603.shtml <--Archerfield April 2017\navid_climate = {'YBBN':'4020','YBAF':'4003', 'YAMB':'4002', 'YBSU':'4081', 'YBCG':'4036',\\\n 'YTWB':'4126','YBOK':'4093','YBWW':'4093',\\\n 'YKRY':'4069', 'YTNG':'4120', 'YGLA':'4049','YBRK':'4102',\\\n 'YBUD':'4021','YHBA':'4056','YMYB':'4082',\\\n 'YROM':'4104', 'YBCV':'4028', 'YLRE':'4074', 'YWTN':'4136',\\\n 'YBDV':'4011', 'YLLE':'4006', 'YWDH':'4135','YTGM':'4121','YSGE':'4110',\\\n 'YBMA':'4089', 'YCCY':'4031', 'YJLC':'4067', 'YRMD':'4100', 'YHUG':'4060',\\\n 'YTMO':'4123', 'YTEE':'4129',\\\n 'YBTL':'4128', 'YBMK':'4077', 'MKY':'4078', 'YBPN':'4096','YBHM':'4054',\\\n 'YEML':'4042', 'YMRB':'4087', 'YCMT':'4147' }\n\n\n\nradarCoords = [{'locn':'Bowen','lat':19.88, 'long':148.08,'url':'http://www.bom.gov.au/products/IDR242.loop.shtml'},\n\t{'locn':'Brisbane (Mt Stapylton)','lat':27.72, 'long':153.24, 'url':'http://www.bom.gov.au/products/IDR662.loop.shtml'},\n\t{'locn':'Cairns','lat':-16.82, 'long':145.68, 'url':'http://www.bom.gov.au/products/IDR192.loop.shtml'},\n {'locn':'Emerald','lat':-23.55,'long':148.24, 'url':'http://www.bom.gov.au/products/IDR722.loop.shtml'},\n\t{'locn':'Mackay' ,'lat':-21.12,'long':149.22, 'url':'http://www.bom.gov.au/products/IDR222.loop.shtml'},\n\t{'locn':'Gladstone','lat':-23.86,'long':151.26, 'url':'http://www.bom.gov.au/products/IDR232.loop.shtml'},\n\t{'locn':'Gympie (Mt Kanigan)','lat':-25.96,'long':152.58, 'url':'http://www.bom.gov.au/products/IDR082.loop.shtml'},\n\t{'locn':'Longreach','lat':-23.43,'long':144.29, 'url':'http://www.bom.gov.au/products/IDR562.loop.shtml'},\n\t{'locn':'Marburg','lat':-27.61,'long':152.54, 'url':'http://www.bom.gov.au/products/IDR502.loop.shtml'},\n\t{'locn':'Mornington Island (Gulf of Carpentaria)','lat':-16.67,'long':139.17, 'url':'http://www.bom.gov.au/products/IDR362.loop.shtml'},\n\t{'locn':'Mount Isa','lat':-20.71,'long':139.56, 'url':'http://www.bom.gov.au/products/IDR752.loop.shtml'},\n\t{'locn':'Townsville (Hervey Range)','lat':-19.42,'long':146.55, 'url':'http://www.bom.gov.au/products/IDR732.loop.shtml'},\n\t{'locn':'Warrego','lat':-26.44,'long':147.35, 'url':'http://www.bom.gov.au/products/IDR672.loop.shtml'},\n\t{'locn':'Moree','lat':-29.5,'long':149.85, 'url':'http://www.bom.gov.au/products/IDR532.loop.shtml'},\n\t{'locn':'Grafton','lat':-29.62,'long':152.97, 'url':'http://www.bom.gov.au/products/IDR282.loop.shtml'},\n\t{'locn':'Weipa','lat':-12.67,'long':141.92, 'url':'http://www.bom.gov.au/products/IDR782.loop.shtml'},\n\t{'locn':'Willis Island','lat':16.29,'long':149.97, 'url':'http://www.bom.gov.au/products/IDR412.loop.shtml'},\n\t{'locn':'Broome','lat':-17.95,'long':122.23, 'url':'http://www.bom.gov.au/products/IDR172.loop.shtml'},\n\t{'locn':'Dampier','lat':-20.65,'long':116.69, 'url':'http://www.bom.gov.au/products/IDR152.loop.shtml'},\n\t{'locn':'Port Hedland','lat':-20.37,'long':118.63, 'url':'http://www.bom.gov.au/products/IDR162.loop.shtml'},\n\t{'locn':'Learmonth','lat':-22.10,'long':114.00, 'url':'http://www.bom.gov.au/products/IDR292.loop.shtml'},\n\t{'locn':'Carnarvon','lat':-24.88,'long':113.67, 'url':'http://www.bom.gov.au/products/IDR052.loop.shtml'},\n\t{'locn':'Giles','lat':-25.03,'long':128.30, 'url':'http://www.bom.gov.au/products/IDR442.loop.shtml'},\n\t{'locn':'Alice Springs','lat':-23.82,'long':133.90, 'url':'http://www.bom.gov.au/products/IDR252.loop.shtml'},\n\t{'locn':'Halls Creek','lat':-18.23,'long':127.66, 'url':'http://www.bom.gov.au/products/IDR392.loop.shtml'},\n\t{'locn':'Wyndham','lat':-15.45,'long':128.12, 'url':'http://www.bom.gov.au/products/IDR072.loop.shtml'},\n\t{'locn':'Katherine (Tindal)','lat':-14.51,'long':132.45, 'url':'http://www.bom.gov.au/products/IDR422.loop.shtml'},\n\t{'locn':'Darwin (Berrimah)','lat':-12.46,'long':130.93, 'url':'http://www.bom.gov.au/products/IDR632.loop.shtml'},\n\t{'locn':'Warruwi','lat':-11.65,'long':133.38, 'url':'http://www.bom.gov.au/products/IDR772.loop.shtml'},\n\t{'locn':'Sydney (Terry Hills)','lat':-33.40,'long':151.14, 'url':'http://www.bom.gov.au/products/IDR712.loop.shtml'},\n {'locn':'Canberra (Captains Flat)','lat':-35.5,'long':149.5, 'url':'http://www.bom.gov.au/products/IDR402.loop.shtml'},\n {'locn':'Melbourne','lat':-37.5,'long':144.5, 'url':'http://www.bom.gov.au/products/IDR022.loop.shtml'},\n {'locn':'Adelaide (Buckland Park) ','lat':-34.5,'long':138.5, 'url':'http://www.bom.gov.au/products/IDR642.loop.shtml'},\n {'locn':'Perth (Serpentine) ','lat':-32.2,'long':115.5, 'url':'http://www.bom.gov.au/products/IDR702.loop.shtml'}]\n\n\n# These locations get a fully worded town forecast as well - can have more info than precis\ntowns_list = ['YBCS','YROM', 'YBCV','YBDV','YEML','YBRK', 'YGLA','YGDI','YHBA','YAMB','YLRE','YBMK',\\\n 'YBUD', 'YMYB','YBMA','YTWB','YBTL']\n\n\n# weather columns in climate zone data files\nwx_cols = ['PW',\n 'PW1_int', 'PW1_desc', 'PW1_type',\n 'PW2_int', 'PW2_desc', 'PW2_type',\n 'PW3_int', 'PW3_desc', 'PW3_type',\n 'RW1_desc', 'RW1_type',\n 'RW2_desc', 'RW2_type',\n 'RW3_desc', 'RW3_type']\n# 'AWS_PW', 'AWS_PW15min', 'AWS_PW60min', <-- these not avlble for brissy\n\n'''\n'PW1_int', 'PW1_desc', 'PW1_type',\n'''\n# Weather intensity (Light, mod, hvy) or proximity VC\n# these are represeneted by integers 0 to 3\nintensity = {0:'LT', 1:'MD', 2:'HV', 3:'VC'}\n\n## two letter codes that form the prefix\n## e.g in TSRA, 'TS' is the prefix/wx descriptor,\n## 'RA' is suffix/weather type\nwx_desc = {'MI':'shallow', 'BC':'patches', 'DR':'drifting',\n 'BL':'blowing', 'SH':'showers', 'TS':'thunderstorm',\n 'FZ':'freezing', 'PR':'partial'}\n\nwx_type = {'DZ':'drizzle', 'RA':'rain','SN':'snow','SG':'snow grains',\n'IC':'ice crystals','PL':'ice pellets','GR':'hail','GS':'small hail',\n'BR':'mist','FG':'fog','FU':'smoke','VA':'vocanic ash','DU':'widespread dust',\n'SA':'sand','HZ':'haze','PO':'dust devil','SQ':'squalls',\n'FC':'funnel cloud','SS':'sandstorm','DS':'duststorm'}\n\n\n# column names used to replace original climate-zone data file columns\ncols =['hm', 'StNum', 'StName', 'Lat', 'Long', 'WMO_Num', 'AvID', 'Elevation_m', \\\n 'LST', 'UTC', 'M_type', 'pptn10min', 'pptn9am', 'T', 'Twb', 'Td', 'RH', \\\n 'VP', 'SVP', 'WS', 'WDir', 'MaxGust10min', 'CL1_amnt', 'CL1_type', 'CL1_ht',\\\n 'CL2_amnt', 'CL2_type', 'CL2_ht', 'CL3_amnt', 'CL3_type', 'CL3_ht', 'CL4_amnt',\\\n 'CL4_type', 'CL4_ht', 'Ceil1_amnt', 'Ceil1_ht', 'Ceil2_amnt', 'Ceil2_ht',\\\n 'Ceil3_amnt', 'Ceil3_ht','CeilSKCflag', 'vis', 'vis_min_dir', 'vis_aws', 'PW', 'PW1_int',\\\n 'PW1_desc', 'PW1_type', 'PW2_int', 'PW2_desc', 'PW2_type', 'PW3_int', 'PW3_desc', \\\n 'PW3_type', 'RW1_desc', 'RW1_type', 'RW2_desc', 'RW2_type', 'RW3_desc', 'RW3_type',\\\n 'AWS_PW', 'AWS_PW15min', 'AWS_PW60min', 'MSL', 'SLP', 'QNH', 'AWS_Flag', 'MSG',\\\n 'RMK', 'CAVOK_SKC_flag', 'RWY_ws_shear_flag', 'END']\n\n# data column subset that we can treat as NUMERIC\ncols_num = ['StNum', 'Lat', 'Long', 'WMO_Num',\n 'Elevation_m', 'pptn10min', 'pptn9am', 'T', 'Twb',\n 'Td', 'RH', 'VP', 'SVP', 'WS', 'WDir', 'MaxGust10min',\n 'CL1_amnt', 'CL1_type', 'CL1_ht', 'CL2_amnt', 'CL2_type', 'CL2_ht',\n 'CL3_amnt', 'CL3_type', 'CL3_ht', 'CL4_amnt', 'CL4_type', 'CL4_ht',\n 'Ceil1_ht', 'Ceil2_ht', 'Ceil3_ht','CeilSKCflag',\n 'vis', 'vis_min_dir', 'vis_aws',\n 'PW', 'PW1_int','PW2_int', 'PW3_int', 'MSL', 'SLP', 'QNH',\n 'AWS_Flag', 'CAVOK_SKC_flag', 'RWY_ws_shear_flag']\n\n# data columns that we can safely treat as TEXT/STRINGS\ncols_str = ['hm', 'StName','AvID','M_type','Ceil1_amnt','Ceil2_amnt', 'Ceil3_amnt',\n 'PW1_desc', 'PW1_type','PW2_desc', 'PW2_type', 'PW3_desc','PW3_type',\n 'RW1_desc', 'RW1_type', 'RW2_desc', 'RW2_type', 'RW3_desc','RW3_type',\n 'AWS_PW', 'AWS_PW15min', 'AWS_PW60min','MSG', 'RMK']\n\ncols_2_keep_auto_aws = \\\n['AvID','M_type','pptn10min', 'pptn9am', 'T', 'Twb',\n'Td', 'RH', 'VP', 'SVP', 'WS', 'WDir', 'MaxGust10min','QNH',\n'Ceil1_amnt','Ceil2_amnt', 'Ceil3_amnt',\n'Ceil1_ht', 'Ceil2_ht', 'Ceil3_ht', 'CeilSKCflag','vis_aws',\n'AWS_PW', 'AWS_PW15min', 'AWS_PW60min',\n'AWS_Flag', 'CAVOK_SKC_flag', 'RWY_ws_shear_flag']\n#'CL1_amnt', 'CL1_type', 'CL1_ht', 'CL2_amnt', 'CL2_type', 'CL2_ht',\n#'CL3_amnt', 'CL3_type', 'CL3_ht', 'CL4_amnt', 'CL4_type', 'CL4_ht',\n#'vis', 'vis_min_dir','PW',\n#'PW1_int','PW2_int', 'PW3_int',\n#'PW1_desc', 'PW1_type','PW2_desc', 'PW2_type', 'PW3_desc','PW3_type',\n#'RW1_desc', 'RW1_type', 'RW2_desc', 'RW2_type', 'RW3_desc','RW3_type',\n#'MSG', 'RMK']\n\ncols_2_keep_manual_aws = \\\n['AvID','M_type','pptn10min', 'pptn9am', 'T', 'Twb',\n'Td', 'RH', 'VP', 'SVP', 'WS', 'WDir', 'MaxGust10min','QNH',\n'CL1_amnt', 'CL1_type', 'CL1_ht', 'CL2_amnt', 'CL2_type', 'CL2_ht',\n'vis', 'vis_min_dir', 'PW',\n'PW1_int','PW1_desc', 'PW1_type',\n'PW2_int','PW2_desc', 'PW2_type',\n'AWS_Flag', 'CAVOK_SKC_flag', 'RWY_ws_shear_flag']\n#'Ceil1_amnt','Ceil2_amnt', 'Ceil3_amnt',\n#'Ceil1_ht', 'Ceil2_ht', 'Ceil3_ht', 'CeilSKCflag','vis_aws',\n#'AWS_PW', 'AWS_PW15min', 'AWS_PW60min',\n#'CL3_amnt', 'CL3_type', 'CL3_ht', 'CL4_amnt', 'CL4_type', 'CL4_ht',\n#'PW3_int', 'PW3_desc','PW3_type',\n#'RW1_desc', 'RW1_type', 'RW2_desc', 'RW2_type', 'RW3_desc','RW3_type',\n#'MSG', 'RMK']\n\n# cols we want to keep, NB UTC datetime wud be in index, not in columns\ncols_2_keep = \\\n['AvID', 'M_type', 'pptn10min', 'pptnSince9', 'T',\n 'Td', 'RH', 'WS', 'WDir', 'MaxGust10min', 'QNH',\n 'CL1_amnt', 'CL1_ht', 'CL2_amnt', 'CL2_ht', 'CL3_amnt', 'CL3_ht',\n 'Ceil1_amnt','Ceil1_ht','Ceil2_amnt','Ceil2_ht', 'Ceil3_amnt', 'Ceil3_ht',\n 'CeilSKCflag', 'vis', 'vis_min_dir','vis_aws',\n 'PW', 'PW1_desc', 'PW1_type','PW2_desc', 'PW2_type','PW3_desc','PW3_type',\n 'AWS_PW', 'AWS_PW15min', 'AWS_PW60min', 'AWS_Flag', 'CeilSKCflag']\n\n'''\n tcz_col_names = ['AvID', 'date', 'M_type', 'pptn10min', 'pptnSince9', 'T', 'Td',\n 'RH', 'WS', 'WDir', 'MaxGust10min', 'CL1_amnt', 'CL1_ht',\n 'CL2_amnt', 'CL2_ht', 'CL3_amnt', 'CL3_ht', 'Ceil1_amnt',\n 'Ceil1_ht', 'Ceil2_amnt', 'Ceil2_ht', 'Ceil3_amnt', 'Ceil3_ht',\n 'CeilSKCflag', 'vis', 'vis_min_dir', 'vis_aws', 'PW', 'PW1_desc',\n 'PW1_type', 'PW2_desc', 'PW2_type', 'PW3_desc', 'PW3_type',\n 'AWS_PW', 'AWS_PW15min', 'AWS_PW60min', 'QNH', 'AWS_Flag']\n\n### script to find/replace potential false matches in observations\n\n(**already ran on the data files - repeat if grab new data**)\n\n```\n#!/bin/bash\n\n#http://www.grymoire.com/unix/Sed.html#uh-10a\n#- ignore case using '/I', be greedy 'g'\n#- multiple find replace patterns using '-e'\n#- sed -e 's/a/A/' -e 's/b/B/' new\n\nsuffix=\"_new.txt\"\nfor file_name in \"$@\"\ndo\n\nname=`echo $file_name | cut -f1 -d'.'`\n\nsed -e 's/knots/kt/Ig' \\\n -e 's/kts/kt/Ig' \\\n -e 's/gusts/gust/Ig' \\\n -e 's/reports/report/Ig' \\\n -e 's/remnants/remnant/Ig' \\\n -e 's/quadrants/quadrant/Ig' < $file_name > $name$suffix\n\ndone\n\n\nUsage\n%cd 'folder holding data files'\n\n# find replace potential false matches in original datafiles\n!sh replace_false_ts_matches.sh HM01X_Data_040842.txt HM01X_Data_040223.txt\n'''\n\n#############################################################\n## Function to get read data from individual\n## ClimateZone files and return properly formatted dataframe\n#############################################################\ndef process_climate_zone_csv():\n\n df = pd.read_csv(file,\n parse_dates=[8,9], # col 8,9 datetime like\n dayfirst=True, # format like '31/10/2012 23:30' in file\n infer_datetime_format = True, # faster parsing 5-10x\n names=cols, # rename climatezone columns using cols list\n index_col=[9], # make UTC datetime index\n low_memory=False,\n skiprows=1, # skip 1 line(s) at the start of the file.\n header=None ) # don't use headers - we skipped header row!\n\n\n # convert these cols expected to be float/int to numeric\n # df[cols_num] = df[cols_num].astype(float, 'ignore')\n # too many errors with above vectorized approach\n\n for col in cols_num:\n df[col] = pd.to_numeric(df[col], errors='coerce')\n\n # convert text data to string\n df[cols_str] = df[cols_str].astype(str)\n\n return (df)\n\ntcz_file_map = {'YBBN':'040842', 'YBAF':'040211', 'YAMB':'040004',\n 'YBSU':'040861', 'YBCG':'040717', 'YTWB':'041529',\n 'YBOK':'041359', 'YBRK':'039083',\n 'YPCC':'200284','YPXM':'200790',\n 'YSSY':'066037','YSBK':'066137','YSRI':'067105',\n 'YSCN':'068192','YSHL':'068241'}\n\ndef process_climate_zone_csv_2020(station:str='YBBN'):\n\n '''\n\n http://tcz.bom.gov.au:8889/tcz/anon/HM01X_D.HM01X_page\n Use this saved query: half_hourly_metar_data_extract\n @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n userid:vinorda\n pwd:usual\n ,40004,40211,40842,40717,40861,41359,41529,39083\n @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n '''\n\n #cur_dir=\"/home/bou/shared/stats-R/fog-project/tcz_data/HM01X_99999999_9852610\"\n cur_dir = \"/home/accounts/qdisplay/avguide/tmp/\"\n #cur_dir='/home/bou/shared/stats-R/flask_projects/avguide/app/data'\n '''In the app, cur_dir will come from environment config'''\n # data_file = f'HM01X_Data_{tcz_file_map[station]}.txt'\n data_file = os.path.join(cur_dir, f'HM01X_Data_{station}.txt')\n #file = os.path.join(cur_dir,'app','data',data_file)\n #file = os.path.join(cur_dir,data_file)\n\n print(f'\\nProcessing aviation location {station}, file={data_file}')\n use_tcz_cols =[ 5, 7, 8, 9, 10, 11, 13, 14, 17, 18, 19, 20, 22, 23, 25, 26, 28,\n 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 44, 45, 47, 48, 50, 51,\n 58, 59, 60, 63, 64]\n\n tcz_col_names = ['AvID', 'date', 'M_type', 'pptn10min', 'pptnSince9', 'T', 'Td',\n 'RH', 'WS', 'WDir', 'MaxGust10min', 'CL1_amnt', 'CL1_ht',\n 'CL2_amnt', 'CL2_ht', 'CL3_amnt', 'CL3_ht', 'Ceil1_amnt',\n 'Ceil1_ht', 'Ceil2_amnt', 'Ceil2_ht', 'Ceil3_amnt', 'Ceil3_ht',\n 'CeilSKCflag', 'vis', 'vis_min_dir', 'vis_aws', 'PW', 'PW1_desc',\n 'PW1_type', 'PW2_desc', 'PW2_type', 'PW3_desc', 'PW3_type',\n 'AWS_PW', 'AWS_PW15min', 'AWS_PW60min', 'QNH', 'AWS_Flag']\n\n cols_num = ['pptn10min', 'pptnSince9', 'T','Td', 'RH','WS', 'WDir', 'MaxGust10min',\n 'CL1_amnt', 'CL1_ht', 'CL2_amnt', 'CL2_ht','CL3_amnt','CL3_ht','Ceil1_ht', 'Ceil2_ht',\n 'Ceil3_ht','vis', 'vis_min_dir', 'vis_aws','PW', 'QNH', 'AWS_Flag',\n 'CeilSKCflag']\n\n cols_str = ['AvID','M_type','Ceil1_amnt','Ceil2_amnt', 'Ceil3_amnt',\n 'PW1_desc', 'PW1_type','PW2_desc', 'PW2_type', 'PW3_desc','PW3_type',\n 'AWS_PW', 'AWS_PW15min', 'AWS_PW60min','CeilSKCflag']\n\n df = pd.read_csv(data_file,\n parse_dates=[7], # col 8,9 datetime like\n dayfirst=True, # format like '31/10/2012 23:30' in file\n infer_datetime_format = True, # faster parsing 5-10x\n usecols=use_tcz_cols,\n names=tcz_col_names, # rename climatezone columns using cols list\n index_col=['date'], # make UTC datetime index\n low_memory=False,\n skiprows=1, # skip 1 line(s) at the start of the file.\n header=None ) # don't use headers - we skipped header row!\n\n # convert these cols expected to be float/int to numeric\n # df[cols_num] = df[cols_num].astype(float, 'ignore')\n # too many errors with above vectorized approach\n\n for col in cols_num:\n df[col] = pd.to_numeric(df[col], errors='coerce')\n\n # convert text data to string\n df[cols_str] = df[cols_str].astype(str)\n\n df.index = pd.to_datetime(df.index)\n\n ''' Created new aws data Sept 2020\n We now do not write data file until merged with gpats\n cur_dir = '/home/bou/shared/stats-R/flask_projects/avguide'\n\n with open(\n os.path.join(cur_dir,'app','data',station+'_aws.pkl') , 'wb') as f:\n pickle.dump(df, f)\n '''\n return (df)\n\n'''\n#Run again if update data\n>>> import utility_functions_sep2018 as bous\n>>> import pandas as pd\n>>> tcz_file_map = {'YBBN':'040842', 'YBAF':'040211', 'YAMB':'040004',\n... 'YBSU':'040861', 'YBCG':'040717', 'YTWB':'041529',\n... 'YBOK':'041359', 'YBRK':'039083',\n... 'YPCC':'200284','YPXM':'200790',\n... 'YSSY':'066037','YSBK':'066137','YSRI':'067105',\n... 'YSCN':'068192','YSHL':'068241'}\n\n# read csv, extract relevant columns, do appropriate processing and then store picklised data on system\n>>> for station,file in tcz_file_map.items():\n... print(station,file)\n... bous.process_climate_zone_csv_2020(station)\n\nYSBK 066137\n\nProcessing aviation location YSBK, file=/home/bou/shared/stats-R/fog-project/tcz_data/HM01X_99999999_9852610/HM01X_Data_066137.txt\nProcessing aviation location YSCN, file=/home/bou/shared/stats-R/fog-project/tcz_data/HM01X_99999999_9852610/HM01X_Data_068192.txt\n...\n\nHandling old aws site data for YBBN\n-------------------------------------\nybbn_old = process_climate_zone_csv('~/data/HM01X_Data_040223_new.txt')\nybbn_new = process_climate_zone_csv('~/data/HM01X_Data_040842_new.txt')\n\n# Grab data from both old and new YBBN sites\n# Merge old and new site data into single file\n\nybbn_old['WS'] = ybbn_old['WS']/1.85198479488\nybbn_old['MaxGust10min'] = ybbn_old['MaxGust10min']/1.85198479488\n\n\nybbn_old = ybbn_old\\\n .loc[:'2000-02-14 02:30:00',cols_2_keep]\nybbn_new = ybbn_new\\\n .loc['2000-02-14 03:00:00':,cols_2_keep]\n\ndf = pd.concat(\n [ybbn_old, ybbn_new],\n axis=0,\n join='outer',\n ignore_index=False )\n\ndf.to_csv('tmp/data/Brisbane_aws_Jan1985-Jan2018.csv')\n\nimport pickle\nwith open('~/data/Brisbane_aws_Jan1985-Jan2018.pkl', 'wb') as f:\n pickle.dump(df, f)\n\n'''\n\n####################################################\n############ READ GPATS DATA FILE #################\n####################################################\n'''\n>>> cur_dir='/home/bou/shared/stats-R/flask_projects/avguide/app/data/'\n>>> g = bous.get_gpats_data(cur_dir,'YSSY')\nReading YSSY gpats file /home/bou/shared/stats-R/flask_projects/avguide/gpats/YSSY_10NM.csv\n>>> g.tail()\n LATITUDE LONGITUDE AMP\nTM \n2020-09-25 11:50:00 -27.549110 153.173250 1\n2020-09-25 11:57:00 -27.529860 153.190630 1\n2020-09-25 12:20:00 -27.305605 153.025925 2\n\n\n# gpats datetime stamps have miscrosecond precisions\n 2008-03-28 04:37:06.546000\n YYYY-MM-DD HH:MM:SS.uuuuuu\n# This is NOT COMPATIBLE WITH AWS DATA datetime stamps\n# which has HH:MM resolution\n# so we drop it right after read.csv()\n# NB We could have also resampled to seconds\n'''\n\ndef get_gpats_data(cur_dir:str=\"./gpats_data/\",sta:str=\"YBBN\")->pd.DataFrame:\n \"\"\"[summary]\n Args:\n cur_dir (str, optional): [FOlder that stores gpat data]. Defaults to \"./gpats_data/\".\n sta (str, optional): [Aviation location]. Defaults to \"YBBN\".\n Returns:\n pd.DataFrame: [description]\n \"\"\"\n # join is smart so cur_dir can be like ./gpats or ./gpats/\n gpats_file = os.path.join(cur_dir, f'gpats_{sta}_10NM.csv')\n print(\"Reading {} gpats file {}\".format(sta, gpats_file))\n\n gpats = pd.read_csv(gpats_file,parse_dates=True, index_col='TM').\\\n resample('1min').\\\n agg(dict(LATITUDE='mean', LONGITUDE='mean', AMP='count')).\\\n dropna()\n ''' PREVIOUS VER of CODE\n gpats = pd.read_csv(gpats_file,parse_dates=True, index_col='TM')\n has HH:MM:SS resolution, mostly HH:MM so we trim it\n We have non-standard datetime, use pd.to_datetime after pd.read_csv\n apply custom string format to drops higher precision microseconds'''\n # gpats_new_index = gpats.index.strftime('%Y:%m:%d %H:%M:%S')\n '''\n convert string/object dateime back to datetime type\n and use that as new index for gpats df'''\n # gpats.index = pd.to_datetime(gpats_new_index,\n # format='%Y:%m:%d %H:%M:%S',\n # errors='coerce')\n\n return (gpats)\n\n\n###################################################################\n''' Simple way to get storm dates for location with observer\n check present weather groups reported by observer\n input - original climate zone aws data file\n - gpats file for aws station\n out - list of days we had storms at station '''\n\ndef get_storm_dates(gpats:pd.DataFrame,df:pd.DataFrame):\n \"\"\"[summary]\n\n Args:\n gpats (pd.DataFrame): [description]\n df (pd.DataFrame): [description]\n\n Returns:\n [pd.Datetime]: [List of dates when we had storms at station]\n \"\"\"\n\n #storm_dates = []\n storm_dates_pw = []\n storm_dates_gpats=[]\n\n sta = str(df.iloc[-1]['AvID']).strip()\n print(\"Getting storm dates for:\", sta,\"from aws metar/speci and gpats data.\")\n\n #gpats = get_gpats_data(cur_dir + 'gpats/', sta)\n #print(\"Reading gpats file:\",(cur_dir + 'gpats/', sta))\n\n gpats_ts_stats = get_gpats_start_end_duration(gpats)\n storm_dates_gpats = gpats_ts_stats.index.unique()\n print(\"Storm dates derived from gpats data for {} = {}\"\\\n .format(sta, len(storm_dates_gpats)))\n\n #storm_dates = storm_dates_gpats\n '''\n If manual station, check observers Present Weather groups\n AWS (Automatic Weather Station) flag\n 0 Manned 1 Automatic 2 Hybrid '''\n # if (df.iloc[-1]['AWS_Flag'] == 2): #tis wud not alwys work!!\n hybrid_sta_list = ['YBBN','YAMB','YBOK','YBRK','YTBL','YBCS','YSSY','YWLM','YPDN','YPTN','YBTL','YPCC','YPXM']\n if sta in hybrid_sta_list:\n # build dict key:val, where key is wx-codes and value is wx-desc\n pw = {91: 'TS', 92: 'TS', 93: 'TS', 94: 'TS', 95: 'TS', \\\n 96: 'TSGS', 99: 'TSGR', 97: '+TS', 98: 'TSDU', \\\n 17: 'Thunder', 13: 'Lightning', 29: 'Recent TS', \\\n 27: 'GSGR', 89: 'SHGS', 90: 'SHGR'}\n\n '''NB: Hail falls as SH from CB only, generally with TS activity\n Hail GR >=5mm diameter (GS<=5mm- small hail/snow pellets) '''\n\n dat = df.copy() # make copy so as not to corrupt orignal df\n\n # for the other reported present weatqher groups\n dat['pw1'] = str_join(dat, '', 'PW1_desc', 'PW1_type')\n dat['pw2'] = str_join(dat, '', 'PW2_desc', 'PW2_type')\n dat['pw3'] = str_join(dat, '', 'PW3_desc', 'PW3_type')\n # We no longer processing RW grops !!!\n #dat['rw1'] = str_join(dat, '', 'RW1_desc', 'RW1_type')\n #dat['rw2'] = str_join(dat, '', 'RW2_desc', 'RW2_type')\n #dat['rw3'] = str_join(dat, '', 'RW3_desc', 'RW3_type')\n\n # join groups using ':'\n dat['pw1to3'] = str_join(dat, ':', 'pw1', 'pw2', 'pw3')\n #dat['rw1to3'] = str_join(dat, ':', 'rw1', 'rw2', 'rw3')\n\n # join PWs to RWs using '|'\n dat['pw_rw'] = str_join(dat, '|', 'pw1to3') #, 'rw1to3')\n\n # get TS start and end times and duration\n #wx_cols = ['T', 'Td', 'RH', 'WS', 'WDIR', 'vis', 'vis_aws',\n # 'PW', 'MaxGust10min', 'pptn10min', 'QNH']\n\n pw_ts_mask = dat['PW'].isin(list(pw.keys()))\n pwrw_ts_mask = dat['pw_rw'].str.contains(r'TS')\n wx_ts_mask = pw_ts_mask | pwrw_ts_mask\n\n wx_ts_specials = dat.loc[wx_ts_mask]\n ts_start_end = get_ts_start_end_duration(wx_ts_specials)\n storm_dates_pw = ts_start_end.index.unique()\n print(\"Storm dates derived from observer reported PW groups for {} = {}\" \\\n .format(sta, len(storm_dates_pw)))\n\n # WE could also do fog same way\n # pwrw_fg_mask = dat['pw_rw'].str.contains(r'FG')\n '''# get FOG stats -> start and end times and duration\n wx_fg_specials = dat.loc[pwrw_fg_mask,wx_cols]\n fg_start_end = get_ts_start_end_duration(wx_fg_specials)\n fg_vis1km = fg_start_end[fg_start_end.min_vis < 1]'''\n\n print(\"Total TS dates found for {} = {}\" \\\n .format(sta,\n len(set(storm_dates_pw).union(set(storm_dates_gpats))), # union two sets\n len(np.unique(list(set().union(storm_dates_pw,storm_dates_gpats)))))) # union two lists\n\n '''A python set is a dictionary that contains only keys (and no values).\n Dictionary keys are, by definition, unique. Duplicate items are weeded out automatically'''\n return list(set(storm_dates_pw).union(set(storm_dates_gpats)))\n # return (np.unique(storm_dates_pw.union(storm_dates_gpats)))\n\n\n\n####################################################\n########## TS START/END/DURATION FM GPATS###########\n####################################################\n\ndef get_gpats_start_end_duration(gpat:pd.DataFrame)->pd.DataFrame:\n\n import numpy as np\n\n '''define multiple aggregations per group\n use the 'AMP' column for counting strikes\n use 'Time' col to grab first and last gpats for a given day\n '''\n gpats = gpat.copy()\n gpats['Time'] = gpats.index\n\n aggregator = {'AMP' : {'gpats_cnt':'count'}, 'Time' : ['first','last']}\n daily = gpats.resample('D').apply(aggregator).dropna()\n # NB using a dict with renaming is deprecated\n # and will be removed in a future version!!\n\n tmp = daily['Time']\n daily.loc[:, ('Time','duration')] = round(\\\n (tmp['last'] - tmp['first'])/np.timedelta64(1, 'h') , 1)\n\n # drop outer-most column index level 0 ['CNT','Time']\n daily.columns = daily.columns.droplevel(0)\n\n # get rid of zero duration events\n # daily = daily[daily['duration'] > '00:00:00']\n daily = daily[daily['duration'] > 0]\n\n return( daily[['gpats_cnt','duration','first','last']])\n\n\n\n################################################################\n'''Load climcate zone data file for station and combine\nwith 1min resampled gpats counts for same station.\nadds any_ts flag to aws data for dates when had TS\nsaves the merged aws/gpats data file as pickled obj\n\nfor stations without manual obs, unless TS has caused a SPECI\n(vis/ceil reductions or wind gust),no SPECI will be generated.\nIn this case we use gpats observation and flag the aws obs closest\n(in time) to the gpats record with gpats['AMP'] count.\nnon zero values of this count would indicate presence of lightning.\n\nWe could resample gpats to 30min to make it better align\nwith 1/2 hrly aws, but this will miss a lot of non-routine\nspecies\nresample to 1min alighns better to non-routine species\nleft merge to retain all non-routine SPECI aws\n\ninput: sta - aviation id of station e.g 'YBBN'\n aws_file e.g 'HM01X_Data_040211_YBAF.txt'\n\n'''\n###############################################################\n\ndef merge_aws_gpats_data(sta):\n\n cur_dir = \"/home/accounts/qdisplay/avguide/tmp/\"\n #cur_dir='/home/bou/shared/stats-R/flask_projects/avguide/app/data/'\n '''In the app, cur_dir will come from environment config\n gpats fil ename like --> gpats_YPXM_10NM.csv\n tcz climate zone data file --> HM01X_Data_YPXM.txt'''\n # gpats_file = f'gpats_{sta}_10NM.csv'\n # file = os.path.join(cur_dir,'app','data',data_file)\n gpats_file = os.path.join(cur_dir, f'gpats_{sta}_10NM.csv')\n tcz_file = os.path.join(cur_dir, f'HM01X_Data_{sta}.txt')\n\n print(f'\\nProcessing sta={sta},\\nClimate Zone data file:{tcz_file}\",\\\n \\nGpats file: {gpats_file}')\n\n # load climate zone data file, except for Brisbane\n #if sta is 'YBBN':\n # df = pickle.load(open(os.path.join(cur_dir,'tcz', aws_file), 'rb'))\n #else:\n #df = process_climate_zone_csv(cur_dir+'tcz/'+aws_file)\n df = process_climate_zone_csv_2020(sta)\n #print(df.head(1))\n #print(df.tail(1))\n\n # we check both aws metar/speci and gpats for ts days now\n # this not just checks fo gpats lightning but also observer PW groups\n gpats = get_gpats_data(cur_dir, sta)\n #print(gpats.head(1))\n #print(gpats.tail(1))\n\n ts_dates = get_storm_dates(gpats,df)\n\n # print(len(ts_dates), ts_dates)\n df = df[cols_2_keep]\n\n # FLAG AWS OBS WITH TS FLAG IF TS ON THAT DATE\n df['date'] = pd.to_datetime(df.index.date)\n df['any_ts'] = df['date'].isin(ts_dates)\n\n '''for stations without manual obs, unless TS has caused a SPECI\n (vis/ceil reductions or wind gust),no SPECI will be generated.\n In this case we use gpats observation and flag the aws obs closest\n (in time) to the gpats record with gpats['AMP'] count.\n non zero values of this count would indicate presence of lightning.\n\n fn get_gpats_data() expects gpats folder and station avID\n def get_gpats_data(gpats_dir,sta):\n gpats_file = gpats_dir+sta+'_gpats_10NM.csv'\n\n # gpats.resample('D')['AMP'].count() <- daily lightning counts\n '''\n # RESAMPLE GPATS TO 1MIN LIGHTNING COUNTS AND MERGE WITH CLOSEST AWS OBS\n # gpats = get_gpats_data(cur_dir, sta)\n df = pd.merge( left=df,\n right=gpats.resample('30min')['AMP'].count(),\n left_index=True, right_index=True,how='left')\n df['AMP'] = df['AMP'].fillna(value=0) # replace NaNs with 0\n\n '''potential data redundancy 'any_ts' flags all obs for day with TS status\n 'AMP' lightning count assigned to aws obs if gpats around time of obs'''\n file = os.path.join(cur_dir, f'{sta}_aws.pkl')\n with open(file, 'wb') as f:\n pickle.dump(df, f)\n\n\n##################################################################\n'''\nGet fog dates from SFC_DAYS table in ADAMS\n\nAdd fog flag in AWS obs from climate_zone\n\nSELECT TO_CHAR(LSD, 'yyyy-mm-dd') AS Day, count(distinct decode(fog_flag,'Y',lsd))\nFROM SFC_DAYS WHERE\nLSD > TO_DATE('{start}', 'yyyy-mm-dd') AND LSD <= TO_DATE('{end}', 'yyyy-mm-dd')\nAND STN_NUM={station}\nGROUP BY TO_CHAR(LSD, 'yyyy-mm-dd')\n'''\n\n\ndef update_aws_fog_flag(sta):\n\n # get fog dates from sfc_days table in ADAMS\n fg_dates = get_fog_dates(sta)\n\n # FLAG AWS OBS WITH TS FLAG IF TS ON THAT DATE\n df = pickle.load(\n open(os.path.join('app','data',sta+'_aws.pkl'), 'rb'))\n print(\"update_aws_fog_flag- Brisbane data b4 add fog flag\\n\", df.tail())\n df['date'] = pd.to_datetime(df.index.date)\n df['fogflag'] = df['date'].isin(fg_dates)\n print(\"update_aws_fog_flag- Brisbane data after add fog flag\\n\", df.tail())\n '''potential data redundancy 'fogflag' flags all obs with FG status'''\n\n with open(os.path.join('app','data',sta+'_aws1.pkl'), 'wb') as f:\n pickle.dump(df, f)\n\n\n\n# Function to concatenate, join many cols together\n# to joing 2 cols we could just do\n# df[col1].str.cat(df[col2])\n# but col1 or col2 could be numeric, so need .astype(str) on the fly conversion\n# else get errors\n\n# https://stackoverflow.com/questions/19377969/combine-two-columns-of-text-in-dataframe-in-pandas-python\ndef str_join(df, sep, *cols):\n from functools import reduce\n return reduce(\n lambda x, y: x.astype(str).str.cat(y.astype(str), sep=sep),\\\n [df[col] for col in cols]\n )\n\n\n###################################################################\n\n################################################################\n'''Extract daily 23Z F160 sonde files for given station from\naifsa-sa archives and save as individual text files for each day\nUses Hanks extract_skewt_from_adam.pl interface\nDownloads daily 2300Z Brisbane sonde as text files\n\nIndividual sonde files have this form\n---------------------------------------\n[Header]\naifstime[18]=\"201802122300\"\nstationname[30]=\"Brisbane Ap\"\nstationnumber=040842\nlevels=76\nfields=5\nw_units=1\n[$]\n\n[Trace]\nPres,Geop,Temp,Dewp,Dir,Spd,AbsHum\n1010.0,-9999.0,27.0,24.0,40.0,15.4,-9999.0\n1000.0,-9999.0,25.9,23.4,50.0,23.0,-9999.0\n979.0,-9999.0,24.9,22.8,65.0,18.0,-9999.0\n978.0,-9999.0,-9999.0,-9999.0,65.0,17.4,-9999.0\n958.0,-9999.0,25.8,19.9,55.0,13.2,-9999.0\n950.0,-9999.0,25.3,19.3,40.0,11.8,-9999.0\n--------------------------------------------\n# len(pd.date_range(start='2000-Feb-01', end='2018-Feb-13', freq='D'))\n# 6588 days of 23 sonde data '''\n###############################################################\n\ndef batch_download_F160_hanks(station:str=\"040842\",start_date='None',end_date='None',hour='1700',exact='on'):\n\n # print(\"Start date\",start_date)\n # if no date supplied grab todays sonde file\n if start_date == 'None':\n start_date = pd.datetime.today().strftime(\"%Y-%m-%d\")\n end_date = start_date\n\n\n cur_dir = \"/home/accounts/vinorda/Downloads/\"\n f160_url = 'http://aifs-sa.bom.gov.au/cgi-bin/extract_skewt_from_adam.pl'\n #dates = pd.date_range(start='2000-Feb-01', end='2018-Feb-13', freq='D')\n dates = pd.date_range(start=start_date, end=end_date, freq='D')\n print(\"Fetching sonde data for {} from {} to {}\"\\\n .format(station,start_date, end_date))\n\n for day in dates:\n day, month, year = day.day,day.month,day.year\n payload = {'d':day,'m':month,'y':year,'h':hour,'stn': station,'exact':exact,\\\n 'plot':'go','prev':'None','ascii':'on','ascii2':'off','reverse':'','crap':9558}\n # print(payload['stn'])\n # print(day.day,day.month,day.year)\n '''?plot=go&d=1&m=1&y=2010&h=2300&stn=040842&prev=None&exact=&ascii=on&ascii2=off&reverse=&crap=9558'''\n\n f160_response = requests.get(f160_url, params=payload)\n\n print (f160_response.url) #check if url formed correctly\n\n if (f160_response.status_code == requests.codes.ok):\n '''\n print (\"Found file resource\")\n print (f160_response.headers.get('content-type'),\"\\n\")'''\n\n '''build file name as string then save response file '''\n f160_file = cur_dir+'f160_'+str(hour)+'/stn'+str(payload['stn'])+'_'+\\\n str(year)+'-'+str(month)+'-'+str(day)+'.txt'\n with open(f160_file, 'wb') as f:\n f.write(f160_response.content)\n\n # print(f160_response.content)\n\n\n#########################################################################\n## Approximate 500hpa data when no standard level 500hpa\n'''\nNot all daily sonde data have Pressure level exactly == 500,\n99% have, 1% that don't cause lotta issues..\n\nThis makes it difficult to extract 500 level using simple\n### `feb_2018.loc[feb_2018['Pres'] == 500].sort_index()`\nQueries like this\n### `feb_2018[(feb_2018['Pres'] > 499) & (feb_2018['Pres'] < 501)]`\n### `pandas.Series.between(left, right, inclusive=True)`\n### ` feb_2018.loc[feb_2018['Pres'].between(499,501,True)].sort_index()`\nreturn too many rows\n\nHow do we only filter row that has Pressure value closest to 500.0 if not 500.0\n\nhttps://www.science-emergence.com/Articles/Find-nearest-value-\n and-the-index-in-array-with-python-and-numpy/\nhttps://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array\n\nIf you want the index of the element of array (array)\nnearest to the the given number (num)\n\n### `nearest_idx = n.where(abs(array-num)==abs(array-num).min())[0] `\n\nAccess the element of array(array) nearest to the given number (num)\n### `nearest_val = array[abs(array-num)==abs(array-num).min()] `\n\nfor each days sonde data we want to pick out row where the\npressure value is closest to 500.0\n\nwe want row where we have smallest difference between pressure value and 500\nwe don't want row index but actual pressure value, so we can then search\nusing this value in the daily data and grab just ONE row cloest to 500 hpa\n\nwhere p_hPa = dat['Pres'] (series containing pressure levels)\n- `np.abs(p_hPa-500.0)` finds dist from 500.0 for all p values\n- `np.abs(p_hPa-500.0).min()` is lowest when p_hPa almost 500.0\n- `np.abs(p_hPa-500.0) == np.abs(p_hPa-500.0).min()`\n is False for all rows except row with pressure value closest to 500.0\n Guranteed to have True for at most one row. WHAT ABOUT TIES??\n- `p_hPa[boolean series]` where boolean series has one True value\n- `p_hPa[np.abs(p_hPa-500.0) == np.abs(p_hPa-500.0).min()]`\n filters using boolean indexing the pressure value clost to 500.0\n\n'''\n\n\ndef closest_900h(dat):\n if dat.empty:\n print('DataFrame is empty!')\n return # exit function\n else:\n p_hPa = dat['Pres']\n p_level = \\\n p_hPa[np.abs(p_hPa-910.0) == (np.abs(p_hPa-910.0).min())][0]\n return (dat[dat['Pres'] == float(p_level)])\n\n\n\ndef closest_850h(dat):\n if dat.empty:\n print('DataFrame is empty!')\n return # exit function\n else:\n p_hPa = dat['Pres']\n p_level = \\\n p_hPa[np.abs(p_hPa-850.0) == (np.abs(p_hPa-850.0).min())][0]\n return (dat[dat['Pres'] == float(p_level)])\n\n\ndef closest_700h(dat):\n if dat.empty:\n print('DataFrame is empty!')\n return # exit function\n else:\n p_hPa = dat['Pres']\n p_level = \\\n p_hPa[np.abs(p_hPa-700.0) == (np.abs(p_hPa-700.0).min())][0]\n return (dat[dat['Pres'] == float(p_level)])\n\n\ndef closest_500h(dat):\n if dat.empty:\n print('DataFrame is empty!')\n return # exit function\n else:\n p_hPa = dat['Pres']\n p_level = \\\n p_hPa[np.abs(p_hPa-500.0) == (np.abs(p_hPa-500.0).min())][0]\n return (dat[dat['Pres'] == float(p_level)])\n\n\n'''\n## Approximate 900hpa data when no standard level 500hpa\ndef closest_level(dat):\n if dat.empty:\n print('DataFrame is empty!')\n return # exit function\n else:\n p_hPa = dat['Pres']\n p_900 = p_hPa[np.abs(p_hPa - 900.0) == np.abs(p_hPa - 900.0).min()]\n p_850 = p_hPa[np.abs(p_hPa - 850.0) == np.abs(p_hPa - 850.0).min()]\n p_700 = p_hPa[np.abs(p_hPa - 700.0) == np.abs(p_hPa - 700.0).min()]\n p_500 = p_hPa[np.abs(p_hPa - 500.0) == np.abs(p_hPa - 500.0).min()]\n\n return (pd.concat([p_900,p_850,p_700,p_500], axis=1))\n'''\n######################################################\n## Batch process sonde txt files\n## downloaded using Hanks extract_skewt_from_adam.pl\n'''some files don't have any data\n files > 215KB are OK THRU trial/error\n\n# largest 2 files - see pipe to head\n# grep -v '^d' <--exclude directories grep '^-' only shows regular files\n# -k 5 means sort using values in 5th column - this lists file sizes\n# -rn\n# -n, --numeric-sort: compare according to string numerical value\n# -r, --reverse: reverse the result of comparisons\n\n!ls -lR /home/bou/windows-shared/data/f160 | grep '^-' | sort -k 5 -rn | head -n 2\n\n# smallest files - se pipe to tail\n!ls -lR /home/bou/windows-shared/data/f160 | grep '^-' | sort -k 5 -rn | tail -n 14\n\n# To get full pat of filenames pipe output of find to sort\n# Note we sort on colum k=7 now\n!find /home/bou/windows-shared/data/f160 -type f -ls | sort -rn -k7 | tail -n 1\n\n'''\n\n#####################################################\n## WARNING : IF U CHANGE f160 FOLDER - FEW THINGS BREAK!!!\n\ndef batch_process_F160_hanks(station:str='YBBN',time:str='0500'):\n \"\"\"[Read daily sonde data .txt files from a manually specified folder\n and assemble data for main standard levels and some derived quantities\n like 85 to 500 lapse rates, CAPE, LI, TOTA, DLM Steering etc]\n\n Args:\n station (str, optional): [F160 Radio-sonde station - 4 chars wide]. Defaults to 'YBBN'.\n time (str, optional): [Sonde release time]. Defaults to '0500'.\n \"\"\"\n import os\n from glob import glob\n import pickle\n\n cur_dir = \"/home/accounts/vinorda/Downloads/\" # ONLY FOR STANDALONE CALLS\n print(\"f160 data dir = \", cur_dir+station+'_f160_'+time+'/')\n filenames = glob(cur_dir+station+'_f160_'+time+'/stn*txt')\n print(len(filenames), filenames[-5:])\n dataframes = []\n f_dates=[]\n\n # dataframes = [pd.read_csv(f) for f in filenames]\n\n for f in filenames:\n '''some files don't have any data\n files > 215KB are OK THRU trial/error\n '''\n\n # print('file size',os.path.getsize(f))\n\n try:\n if os.path.getsize(f) > 215:\n\n # Non empty file exists, extract date from file name\n # NB IF U CHANGE f160 FOLDER - CAN'T GET DATES!!!\n # cur_dir = '/home/accounts/vinorda/sr-ask-11966/data/' split(7)!!\n\n print(f.split('/')[6].split('.')[0][10:])\n f_dates.append(f.split('/')[6].split('.')[0][10:])\n dat = pd.read_csv(f, skiprows=10, skip_blank_lines=True)\n\n # drop these 2 cols - have no actual data\n dat.drop(['Geop', 'AbsHum'], axis=1,inplace=True)\n\n # drop rows with 2 or more NAN/missing\n # dat.dropna(axis=0, thresh=2,inplace=True)\n\n # force convert all data to numeric\n for col in dat.columns:\n dat[col] = pd.to_numeric(dat[col], errors='coerce')\n\n dataframes.append(dat)\n\n else:\n # If file is empty - skip\n print(\"Empty file {}!!\".format(f))\n continue # go to next file\n except OSError as e:\n # File does not exists or is non accessible\n print(\"What da ..Empty file {}\".format(f))\n finally:\n print(\"Processing file {}\".format(f))\n\n # concat/join all daily data into 1 big file\n df = pd.concat(dataframes,axis=0, keys=f_dates)\n\n # find replace all missing values indicated by -9999 to NaN\n # https://machinelearningmastery.com/handle-missing-data-python/\n df.replace(-9999,np.NaN, inplace=True)\n\n # drop integer row ids that form inner index\n # n make index datetime index\n df.index = df.index.droplevel(1)\n df.index = pd.DatetimeIndex(df.index)\n\n # read sonde data and use 1st row as proxy for sfc conditions\n # and 850/500 data to get env lapse rates and upper temps\n\n sfc_proxy = df.resample('D').first()\n\n lev500 = df.resample('D')\\\n .apply(closest_500h)\\\n .reset_index(level=0,drop=True).sort_index()\n lev700 = df.resample('D') \\\n .apply(closest_700h) \\\n .reset_index(level=0, drop=True).sort_index()\n lev850 = df.resample('D')\\\n .apply(closest_850h)\\\n .reset_index(level=0,drop=True).sort_index()\n lev900 = df.resample('D') \\\n .apply(closest_900h) \\\n .reset_index(level=0, drop=True).sort_index()\n\n sfc_500_sonde = pd.concat([sfc_proxy, lev900,lev850,lev700,lev500], axis=1)\n '''\n p_levels = df.resample('D')\\\n .apply(closest_level)\\\n .reset_index(level=0,drop=True).sort_index()\n sfc_500_sonde = pd.concat([sfc_proxy, p_levels], axis=1) '''\n # sfc_500_sonde.to_csv(cur_dir+'f160/sonde_data_hanks_2000to2018_june10.csv')\n col_names=['sfc_P','sfc_T','sfc_Td','sfc_wdir','sfc_wspd',\n 'P910','T910','Td910','900_wdir','900_WS',\n 'P850','T850','Td850','850_wdir','850_WS',\n 'P700','T700','Td700','700_wdir','700_WS',\n 'P500','T500','Td500','500_wdir','500_WS']\n sfc_500_sonde.columns = col_names #rename col names\n sfc_500_sonde['tmp_rate850_500'] = sfc_500_sonde['T850']-sfc_500_sonde['T500'] # get lapse rates\n\n #cur_dir = '/home/bou/shared/stats-R/flask_projects/avguide'\n #with open(\n # os.path.join(cur_dir,'app','data',station+'_sonde_'+time+'_aws.pkl') , 'wb') as f:\n # pickle.dump(df, f)\n with open(\n os.path.join(cur_dir+station+'_sonde_'+time+'_aws.pkl') , 'wb') as f:\n pickle.dump(sfc_500_sonde, f)\n\n # sfc_500_sonde.to_csv(cur_dir+'f160_0300/YSSY_sonde03z_2000to2020.csv')\n return(sfc_500_sonde)\n\n\ndef get_sounding_data(station:str='YBBN',time:str='2300',level:str=None)->pd.DataFrame:\n \"\"\"\n [Grab sounding data for station - obseleted #############]\n Args:\n station (str, optional): [description]. Defaults to 'YBBN'.\n level (str, optional): [description]. Defaults to None.\n Returns:\n pd.DataFrame: [description]\n \"\"\"\n # cur_dir = '/home/bou/Downloads/'\n cur_dir = '/home/bou/shared/stats-R/flask_projects/avguide/app/data'\n # cur_dir = \"/home/accounts/qdisplay/avguide/app/data\"\n col_names=['sfc_P','sfc_T','sfc_Td','sfc_wdir','sfc_wspd',\n 'P910','T910','Td910','900_wdir','900_WS',\n 'P850','T850','Td850','850_wdir','850_WS',\n 'P700','T700','Td700','700_wdir','700_WS',\n 'P500','T500','Td500','500_wdir','500_WS']\n\n #file = f'{cur_dir}/{station}_sonde{time}z_2000to2020.csv'\n file = f'{station}_sonde{time}z_2000to2020.csv'\n\n ''' Use picklised one - faster and data is already formatted \n sonde = pd.read_csv(\n open(os.path.join('app','data',file),'rb'),\n parse_dates=[0],\n index_col=[0],\n names=col_names,\n skiprows=1,\n header=None)\n '''\n sonde = pickle.load(\n open(os.path.join(cur_dir,'app','data',station+'_sonde_'+time+'_aws.pkl'), 'rb'))\n '''\n # for 17 and 23Z use the UTC date of sonde flight as index\n if time:\n if int(time) in [14,15,16,17,18,19,20,21,22,23]:\n\n sonde.set_index(\n keys=(sonde.index.date),drop=False,inplace=bool(1))\n else: # int(time) == 0:\n sonde.set_index(\n keys=(sonde.index.date - pd.Timedelta(str(1) + ' days')),\n drop=False,inplace=bool(1))\n # we loose datetime type of index in conversion above - restore BLW\n sonde.index = pd.to_datetime(sonde.index)\n\n file stn066037_2006-7-1.txt\n aifstime[18]=\"200607011900\" <-- 1900UTC on 1st July\n For FG matching we would be using mostly using either 02, 05, 06, 08 or 11UTC obs\n and sonde from following day (although same UTC day) so when matching we\n get all 0500 UTC obs for station and merge with 1900 or 2300 sonde data - for SAME UTC date\n we could even merge the 05Z METARs with 05Z sonde and use that for synoptic matching as well\n so no problem with fog synop matching.\n\n For TS matching if we are using 23Z sonde data and 0200Z or 0500Z METARs\n then we need to correct the index for sonde data i.e 2300 UTC sonde date from Nov 1st\n is actually 9am Nov 2nd - the day we need to match for METARs is Nov 2nd and we need to\n change sonde index from Nov 1st to Nov 2nd so that correct sonde data is used for matching.\n We probably need to do same for fog matching if we want to use current days 9am obs together\n with current days 3pm/0500 or 6pm/0800 METARS\n Given this usage depends on context - fog/ or TS matching and whether we want to use observed\n sonde 2300 or 0500 vs forecast 2300Z/0500Z sonde for matching \n So we leave this reindexing out of the code here.\n\n file stn066037_2010-11-1.txt\n aifstime[18]=\"201011010300\" <-- 0300UTC on 1st Nov\n Why do we want to say this data is for 31st Oct by subtracting 1day BELOW?????\n This will stuff up storm day matching at obs wud be from Nov 1st and wrong day sonde!!\n\n\n sonde['tmp_rate850_500'] = sonde['T850']-sonde['T500']\n # if only request data at level, return only that level , else return full sonde\n '''\n # this filtering could be easily implemented in client\n if level:\n return sonde[[level+'_wdir', level+'_WS']].astype(float, 'ignore')\n else:\n return sonde\n\n################################################################\n'''Extract daily 23Z F160 sonde files for given station\nfor single day\nUses Hanks extract_skewt_from_adam.pl interface\nDownloads daily 2300Z Brisbane sonde as text files '''\n###############################################################\ndef getf160_hanks(station=\"040842\",day='None'):\n\n # if no date given, retrieve todays sonde data\n if day == 'None':\n day = pd.datetime.today() #.strftime(\"%Y-%m-%d\")\n else:\n '''our day is in this string format \"2018-06-05\"\n Need to Convert the string to datetime format, else get\n AttributeError: 'str' object has no attribute 'day' '''\n day = pd.to_datetime(day) # this also works\n # day = datetime.strptime(day, '%Y-%m-%d')\n\n print(\"\\n\\nGetting f160 sonde from Hanks interface for\",day,\"\\n\")\n\n\n ''' Convert the other way datetime to string format\n days = [datetime.strptime(d, '%Y%m%d') for d in dates]\n huge issues with dates formats - Nice tutorial/examples\n see https://www.guru99.com/date-time-and-datetime-classes-in-python.html\n\n dates = pd.date_range(start=day, end=day, freq='D')\n print(\"Getting sonde station:{}, day {} or {}\".format(station,day,dates[0]))\n print(\"day:\",day,\"type\",type(day),\n \"\\npd.to_datetime(day)\", type(pd.to_datetime(day)),\n \"\\nfrom pd.date_range()\", type(dates[0]),\n \"\\ndates\",dates)\n\n '''\n\n f160_url = 'http://aifs-sa.bom.gov.au/cgi-bin/extract_skewt_from_adam.pl'\n day, month, year = day.day,day.month,day.year\n payload = {'plot':'go', 'd':day,'m':month,'y':year,\\\n 'stn': station,\\\n 'prev':'None','exact':'', \\\n 'ascii':'on','ascii2':'off','reverse':'','crap':9558}\n\n '''?plot=go&d=1&m=1&y=2010&h=2300&stn=040842&prev=None&exact=&ascii=on&ascii2=off&reverse=&crap=9558'''\n\n f160_response = requests.get(f160_url, params=payload)\n\n print (f160_response.url) #check if url formed correctly\n\n if (f160_response.status_code == requests.codes.ok):\n\n print (\"Found file resource\")\n print (f160_response.headers.get('content-type'),\"\\n\")\n\n # save response file\n f160_file = cur_dir+'f160/stn'+str(payload['stn'])+'_'+\\\n str(year)+'-'+str(month)+'-'+str(day)+'.txt'\n\n\n with open(f160_file, 'wb') as f:\n f.write(f160_response.content)\n\n dat = pd.read_csv(f160_file,skiprows=10, skip_blank_lines=True)\n\n # drop these 2 cols - have no actual data\n dat.drop(['Geop', 'AbsHum'], axis=1,inplace=True)\n\n # drop rows with 2 or more NAN/missing\n dat.dropna(axis=0, thresh=2,inplace=True)\n\n # force convert all data to numeric\n for col in dat.columns:\n dat[col] = pd.to_numeric(dat[col], errors='coerce')\n\n # find replace all missing values indicated by -9999 to NaN\n # https://machinelearningmastery.com/handle-missing-data-python/\n dat.replace(-9999,np.NaN, inplace=True)\n #print(dat)\n\n # drop integer row ids that form inner index\n # n make index datetime index\n # df.index = df.index.droplevel(1)\n # dat.index = pd.DatetimeIndex(day)\n\n sfc_proxy = dat.iloc[0,:]\n #print(sfc_proxy)\n\n p_hPa = dat.iloc[:,0] # get pressure levels as Series\n\n closest900 = \\\n p_hPa[np.abs(p_hPa-900.0) == np.abs(p_hPa-900.0).min()]\n nine100 = dat.iloc[closest900.index.values[0]]\n\n closest850 = \\\n p_hPa[np.abs(p_hPa-850.0) == np.abs(p_hPa-850.0).min()]\n eight50 = dat.iloc[closest850.index.values[0]]\n\n closest700 = \\\n p_hPa[np.abs(p_hPa-700.0) == np.abs(p_hPa-700.0).min()]\n seven100 = dat.iloc[closest700.index.values[0]]\n\n closest500 = \\\n p_hPa[np.abs(p_hPa-500.0) == np.abs(p_hPa-500.0).min()]\n five100 = dat.iloc[closest500.index.values[0]]\n\n\n dato = pd.concat(\n [sfc_proxy, nine100,eight50,seven100,five100], axis=0)\n\n #set index for Series object\n dato.index = ['P','T','Td','wdir','wspd',\n 'P900', 'T900','Td900','wdir900','wspd900',\n 'P850', 'T850','Td850','wdir850','wspd850',\n 'P700', 'T700','Td700','wdir700','wspd700',\n 'P500', 'T500','Td500','wdir500','wspd500']\n\n dato['tmp_rate850_500'] = dato['T850']-dato['T500']\n print(dato)\n\n return(dato)\n\n\n\n#########################################################\n''' For some reason\n http://aifs-sa.bom.gov.au/cgi-bin/extract_skewt_from_adam.pl\n archves has missing data at some of the levels\n\n However aifs-qld.bom.gov.au has those levels\n This function is to get data from this site although there\n is some difference in number of fields availale\n\n http://aifs-qld.bom.gov.au/local/qld/rfc/pages/digi.php?id=ybbn&wind=raw\n see aifs-qld-f160-data-format.txt for format '''\n##########################################################\ndef getStation_f160_aifs_qld(station=\"YBBN\"):\n print(\"\\n\\nGetting f160 sonde from aifs-qld interface\\n\")\n\n day = pd.datetime.today() #.strftime(\"%Y-%m-%d\")\n day, month, year = day.day,day.month,day.year\n\n f160_url = 'http://aifs-qld.bom.gov.au/local/qld/rfc/pages/digi.php'\n payload = {'id': station, 'wind': 'raw'}\n\n f160_response = requests.get(f160_url, params=payload)\n\n print (f160_response.url) # check if url formed correctly\n\n if (f160_response.status_code == requests.codes.ok):\n\n print (\"Found file resource\")\n print (f160_response.headers.get('content-type'), \"\\n\")\n\n # save response file\n f160_file = \\\n '/tmp/f160/stn' + str(payload['id']) + '_' + \\\n str(year) + '-' + str(month) + '-' + str(day) + '.txt'\n\n with open(f160_file, 'wb') as f:\n f.write(f160_response.content)\n\n dat = pd.read_csv(f160_file, skiprows=10, skip_blank_lines=True)\n\n # drop rows with 2 or more NAN/missing\n dat.dropna(axis=0, thresh=2, inplace=True)\n\n # force convert all data to numeric\n for col in dat.columns:\n dat[col] = pd.to_numeric(dat[col], errors='coerce')\n\n # find replace all missing values indicated by -9999 to NaN\n # https://machinelearningmastery.com/handle-missing-data-python/\n dat.replace(-9999, np.NaN, inplace=True)\n print(dat)\n\n # drop integer row ids that form inner index\n # n make index datetime index\n # df.index = df.index.droplevel(1)\n # dat.index = pd.DatetimeIndex(day)\n\n sfc_proxy = dat.iloc[0, :]\n print(sfc_proxy)\n\n # five100_proxy = dat.apply(closest_to_500)\n p_hPa = dat.iloc[:, 0]\n print(p_hPa)\n\n closest500 = \\\n p_hPa[np.abs(p_hPa - 500.0) == np.abs(p_hPa - 500.0).min()]\n print(closest500)\n print(closest500.index.values[0])\n\n five100_proxy = dat.iloc[closest500.index.values[0]]\n print(five100_proxy)\n\n dato = pd.concat([sfc_proxy, five100_proxy], axis=0)\n # set index for Series object\n dato.index = ['P', 'Z', 'wdir', 'wspd', 'P500', 'T500', 'Td500', 'wdir500', 'wspd500']\n # print(dato)\n\n return (dato)\n\n\n\n####################################################################\n'''\nGet f160 data files using sql query direct from adamprd\n[vinorda@qld-rfc-ws38 ~]$ sqlplus anonymous/anonymous@adamprd\nSQL*Plus: Release 11.2.0.1.0 Production on Wed May 16 19:01:52 2018\nCopyright (c) 1982, 2009, Oracle. All rights reserved.\nConnected to:\nOracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production\nWith the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,\nData Mining and Real Application Testing options\n\nSQL> desc uas\n Name Null? Type\n ----------------------------------------- -------- ----------------------------\n STN_NUM NOT NULL NUMBER(6)\n TM NOT NULL DATE\n PRES NOT NULL NUMBER(7,1)\n PRES_QUAL NUMBER(2)\n LEVEL_TYPE NUMBER(1)\n GEOP_HT NUMBER(8,1)\n GEOP_HT_QUAL NUMBER(2)\n AIR_TEMP NUMBER(7,1)\n AIR_TEMP_QUAL NUMBER(2)\n DWPT NUMBER(7,1)\n DWPT_QUAL NUMBER(2)\n WND_DIR NUMBER(5,1)\n WND_DIR_QUAL NUMBER(2)\n WND_SPD NUMBER(5,1)\n WND_SPD_QUAL NUMBER(2)\n OB_QUAL_FLAG NUMBER(2)\n MSG_ID NUMBER(38)\n CMT VARCHAR2(240)\n\n\"tm\" is in UTC.\n\nMessage from Hank\nUntil they either fix the TTAA messages or change the decoder to accept them\nthe standard levels won't get into ADAM.\n\nThe upper temp messages (TTAA/BB/etc) are all archived to the one structure in ADAM,\nwhich is the one I query for the SkewT plotting web page.\n\nMy SQL queries are:\n\n\n $query =\n \" select tm,pres,air_temp,dwpt,geop_ht from uas where stn_num=$stn\n and tm between '$start_date' and '$end_date'\n and air_temp is not null\n and pres>=100\n order by tm,-1*pres;\n select tm,pres,wnd_dir,wnd_spd*2 from uas where stn_num=$stn\n and tm between '$start_date' and '$end_date'\n and wnd_dir is not null\n and pres>=$min_pressure\n order by tm,-1*pres;\n \";\n\n'''\n##########################################################################\n# Requires import cx_Oracle\n# from pandas.io import sql\n# for batch process/download specify both start and end dates\n# and comment return statement and uncomment 2 lines above return\n\ndef getf160_adams(station_number=40842, start_date='None',end_date='None'):\n\n print(\"\\n\\nGetting f160 sonde from ADAMS interface\\n\")\n\n conn = cx_Oracle.connect(user='anonymous', password='anonymous', dsn='adamprd')\n # cursor = conn.cursor()\n hr = datetime.utcnow().hour # pd.datetime.today().hour\n\n '''Note: seems we can't get current days sonde data from ADAMS\n not until a few hours after sonde launch\n Quality assurance issues maybe - so set back one day and get\n yesterdays sonde\n Other option is use Bretts interface on aifs-qld\n http://aifs-qld.bom.gov.au/local/qld/rfc/pages/digi.php '''\n\n df=pd.DataFrame()\n\n # if (start_date is 'None'): # | (end_date is 'None'):\n if (hr >= 14): # after midnight local to 24Z/10am get the morning trace - anytime 14Z till 23Z\n '''we have to set start date one day earlier since its new calendar day!!\n we have to set start calendar date by 2 days to grab 23Z issue\n say its 16Z on the 20th. The latest sonde \n '''\n start_date = (pd.datetime.today() - pd.Timedelta('1 days')).strftime(\"%Y-%m-%d\")\n end_date = pd.datetime.today().strftime(\"%Y-%m-%d\")\n print(f\"\\nCurrent hour = {hr}. Sonde data from {start_date} to {end_date}\\\n Trying sonde from 00Z to 06Z\")\n query = (\n \"SELECT stn_num,tm,pres,geop_ht,air_temp,dwpt,wnd_dir,round(wnd_spd*1.943) as wnd_spd FROM UAS \"\n \"WHERE STN_NUM={station_number} \"\n \"AND TM between TO_DATE('{start_date}', 'yyyy-mm-dd') \"\n \"AND TO_DATE('{end_date}', 'yyyy-mm-dd') \"\n \"AND TO_CHAR(tm,'hh24') in (00,01,02,03,04,05,06) \"\n \"ORDER by tm,-1*pres\"\n ).format(\n start_date=start_date, end_date=end_date, station_number=station_number\n )\n print(query)\n\n\n df = sql.read_sql(query, conn, parse_dates=['TM'], index_col='TM')\n print(df)\n\n if df.empty: # try get 23Z sonde from previous calendar day\n '''\n This situation arises when say its anytime 14Z but no afternoon sonde \n from same UTC date - so say 20th 1600Z, we try get sonde from 20th between 00 to 06Z\n if we can't then we go back further to 19th and get 23Z sonde from there\n '''\n start_date = (pd.datetime.today() - pd.Timedelta('2 days')).strftime(\"%Y-%m-%d\")\n end_date = pd.datetime.today().strftime(\"%Y-%m-%d\")\n\n print(f\"\\nNo 00Z to 06Z sonde current UTC date. Try sonde data from {start_date} to {end_date} to grab yesterdays 23Z sonde\\n\")\n\n query = (\n \"SELECT stn_num,tm,pres,geop_ht,air_temp,dwpt,wnd_dir,round(wnd_spd*1.943) as wnd_spd FROM UAS \"\n \"WHERE STN_NUM={station_number} \"\n \"AND TM between TO_DATE('{start_date}', 'yyyy-mm-dd') \"\n \"AND TO_DATE('{end_date}', 'yyyy-mm-dd') \"\n \"AND TO_CHAR(tm,'hh24') in (22,23) \"\n \"ORDER by tm,-1*pres\"\n ).format(\n start_date=start_date, end_date=end_date, station_number=station_number\n )\n\n print(query)\n\n\n df = sql.read_sql(query, conn, parse_dates=['TM'], index_col='TM')\n\n elif (hr <= 14): # 00Z to 14Z get afternoon sonde anytime after 00Z upto 06Z\n # Note we increment end_date by 1 day to provide a range\n start_date = pd.datetime.today().strftime(\"%Y-%m-%d\")\n end_date = (pd.datetime.today() + pd.Timedelta('1 days')).strftime(\"%Y-%m-%d\")\n print(f\"\\nCurrent hour = {hr}. Sonde data from {start_date} to {end_date}\\\n Trying sonde from 00Z to 06Z\")\n query = (\n \"SELECT stn_num,tm,pres,geop_ht,air_temp,dwpt,wnd_dir,round(wnd_spd*1.943) as wnd_spd FROM UAS \"\n \"WHERE STN_NUM={station_number} \"\n \"AND TM between TO_DATE('{start_date}', 'yyyy-mm-dd') \"\n \"AND TO_DATE('{end_date}', 'yyyy-mm-dd') \"\n \"AND TO_CHAR(tm,'hh24') in (00,01,02,03,04,05,06) \"\n \"ORDER by tm,-1*pres\"\n ).format(\n start_date=start_date, end_date=end_date, station_number=station_number\n )\n\n print(query)\n\n\n df = sql.read_sql(query, conn, parse_dates=['TM'], index_col='TM')\n\n if df.empty: # try get 23Z sonde from previous calendar day\n '''\n This situation arises when say its anytime 00 to 06Z but no afternoon sonde\n so we try get 23Z sonde from previous calendar date for todays afternoon storm assessement\n '''\n start_date = (pd.datetime.today() - pd.Timedelta('1 days')).strftime(\"%Y-%m-%d\")\n end_date = (pd.datetime.today() + pd.Timedelta('1 days')).strftime(\"%Y-%m-%d\")\n\n print(f\"\\nNo 00Z to 06Z sonde today. Try sonde data from {start_date} to {end_date} to grab yesterdays 23Z sonde\\n\")\n query = (\n \"SELECT stn_num,tm,pres,geop_ht,air_temp,dwpt,wnd_dir,round(wnd_spd*1.943) as wnd_spd FROM UAS \"\n \"WHERE STN_NUM={station_number} \"\n \"AND TM between TO_DATE('{start_date}', 'yyyy-mm-dd') \"\n \"AND TO_DATE('{end_date}', 'yyyy-mm-dd') \"\n \"AND TO_CHAR(tm,'hh24') in (22,23) \"\n \"ORDER by tm,-1*pres\"\n ).format(\n start_date=start_date, end_date=end_date, station_number=station_number\n )\n\n print(query)\n\n\n df = sql.read_sql(query, conn, parse_dates=['TM'], index_col='TM')\n\n if ~df.empty:\n print(df)\n\n return (df)\n\n\n#############################################################\n'''Process data downloaded in batch mode using above fn\n getf160_adams(station_number=40842,\n start_date='2000-01-01',end_date='2018-05-24')\n\n\n data file was saved as cur_dir/'f160/sonde_data_adam_2000to2018.csv'\n\n USAGE fom main()\n\n sonde_data_adams = pd.read_csv(cur_dir+'f160/sonde_data_adam_2000to2018.csv',\n parse_dates=[0], index_col=0)\n\n for col in sonde_data_adams.columns[1:]:\n sonde_data_adams[col] = pd.to_numeric(sonde_data_adams[col], errors='coerce')\n\n sonde_data_final = sonde_data_adams.resample('D').apply(bous.process_adams_f160)\n\n sonde_data_final['LTM']= pd.to_datetime(sonde_data_final['LTM'])\n # if hour is 22 or 23 increment date by 1, if 00Z no date change\n sonde_data_final['dates'] = [ (x+pd.Timedelta('1 days')).date() \\\n if ((x.hour == 22)|(x.hour == 23)) else x.date() \\\n for x in sonde_data_final['LTM']]\n\n sonde_data_final['dates'] = pd.to_datetime(sonde_data_final['dates'])\n sonde_data_final.set_index('dates', inplace=True)\n'''\n\ndef get_std_levels_adams(x):\n fields = ['STN_NUM', 'P', 'Z', 'T', 'Td', 'wdir', 'wspd',\n 'STN_NUM', 'P900', 'Z900', 'T900', 'Td900', 'wdir900', 'wspd900',\n 'STN_NUM', 'P850', 'Z850', 'T850', 'Td850', 'wdir850', 'wspd850',\n 'STN_NUM', 'P500', 'Z500', 'T500', 'Td500', 'wdir500', 'wspd500',\n 'tmp_rate850_500', 'gpt_rate', 'lr850_500', 'LTM']\n\n # if no data for this date\n if x.empty:\n # print(\"No sonde data for this day - not even have date!\", x.index.time[:1])\n return (pd.Series(index=fields, data=np.nan))\n\n #21# x['WND_SPD'] = round(1.942 * x['WND_SPD'], 1)\n\n try:\n p_hpa = x.iloc[:, 1] # Series pressure values in 2nd col, 1st col STN_NUM\n except:\n print(\"Something went wrong this day, no pressure values - DISCARD\", x.index[:1])\n # print(p_hpa)\n # return (pd.Series(index=fields, data=np.nan))\n # print(p_hpa)\n\n # fix winds - convert to knots - round to 1 dp\n # we do this on whole dataset before calling this function\n # x['WND_SPD'] = round(1.942 * x['WND_SPD'], 1)\n\n '''\n Most of the time this will work\n lv850 = x.loc[x['PRES'] == 850].iloc[0] # a series of 850 params\n lv500 = x.loc[x['PRES'] == 500].iloc[0] #\n but if we have missing standard levels need to find level closest'''\n\n lv900 = x.loc[ \\\n np.abs(p_hpa - 900.0) == np.abs(p_hpa - 900.0).min()].iloc[0] \\\n .squeeze()\n\n\n lv850 = x.loc[ \\\n np.abs(p_hpa - 850.0) == np.abs(p_hpa - 850.0).min()].iloc[0] \\\n .squeeze()\n '''need .iloc[0] as sometimes more than 1 row may match '''\n\n lv500 = x.loc[ \\\n np.abs(p_hpa - 500.0) == np.abs(p_hpa - 500.0).min()].iloc[0] \\\n .squeeze()\n\n '''\n # if no data at 850, 500 or levels closest return NaNs 4 this day\n p_850 = lv850['PRES']\n p_500 = lv500['PRES']\n\n if (~(p_850 == 850)) | (~(p_500 == 500)):\n print(\"Missing standard levels for this day\", x.index[:1])\n print(\"So we used these closest levels instead\")\n print (\"p_850\", p_850, \"p_500\", p_500)\n '''\n # many ways to check if any field is missing in std level\n # lv850[lv850.isin([np.nan])].empty\n # lv850.index[lv850==\"\"] # if missing value is just a blank\n\n # lv850.index[lv850.isnull()] gives indices list for missing values\n # if len list non zero - we have missing data\n\n # SOME SETS REMARKED SO AS NOT TO THOW AWAY DATA WE DO HAVE\n # each level has 7 data values including STN_NUM\n # if 5 or more values for level missing than we discard day\n if np.logical_and(\n lv850.isnull().sum() > 5,\n lv500.isnull().sum() > 5):\n print(\"Had 5 or more missing values at 850 and 500-DISCARD\", x.index[:1])\n return (pd.Series(index=fields, data=np.nan))\n\n '''\n if (len(lv850.index[lv850.isnull()]) > 5) &\\\n (len(lv500.index[lv500.isnull()]) > 5):\n print(\"we had missing values\")\n return(pd.Series(index=fields, data=np.nan))\n\n\n # since we only care about missing 'AIR_TEMP' and 'GEOP_HT'\n if ( lv850.index[lv850.isnull()].isin(['AIR_TEMP','GEOP_HT'])) |\n ( lv500.index[lv500.isnull()].isin(['AIR_TEMP','GEOP_HT'])):\n print(\"we had missing values\")\n return(pd.Series(index=fields, data=np.nan))\n '''\n\n '''\n if x.loc[x['PRES'] == p_850].empty :\n print(\"Missing 850 data for this day\",x.index[:1])\n return(pd.Series(index=fields, data=np.nan))\n if x.loc[x['PRES'] == p_500].empty :\n print(\"Missing 500 data for this day\",x.index[:1])\n return(pd.Series(index=fields, data=np.nan))\n '''\n\n # grab sfc values - lowest sonde level shud be 1st record\n lvsfc = x.iloc[0, :]\n\n dat = pd.concat([lvsfc, lv900, lv850, lv500], axis=0)\n\n tmp_rate = lv850['AIR_TEMP'] - lv500['AIR_TEMP']\n gpt_rate = lv500['GEOP_HT'] - lv850['GEOP_HT']\n dat['tmp_rate850_500'] = tmp_rate\n dat['gpt_rate'] = gpt_rate\n dat['lr850_500'] = round(dat['tmp_rate850_500'] / dat['gpt_rate'] * 1000, 1)\n\n # for date use datetime for 1st sonde record for this day\n dat['LTM'] = pd.to_datetime(x.index, format='%Y-%m-%d %H:%M:S', errors='coerce')[0]\n dat['LTM'] = pd.to_datetime(x.index, infer_datetime_format=True)[0]\n\n dat.index = fields\n\n return (dat)\n\n\n\n################################################################\n'''Sonde data downloaded using direct SQL query to ADAM has\n datetime with 22Z or 23Z\n Such dates should be incremented to next/following calendar day\n When batch processing sonde using .resample('D')\n sonde_data_final = sonde_data_adams.resample('D')\\\n .apply(bous.process_adams_f160)\n\n resample('D') only uses the date portion as index\n truncates/ignores the time bit 22Z/23Z etc\n Here we use the saved time info to save record with\n next days timestamp if time was like 22Z or 23Z\n'''\n################################################################\n\ndef process_adams_sonde(dat):\n\n # 1st modify 'LTM' the field with both date and time\n # to be datetime aware/datetime like!!\n dat['LTM'] = pd.to_datetime(dat['LTM'])\n\n # if hour is 22 or 23 increment date by 1 else no change\n dat['dates'] = [ (x+pd.Timedelta('1 days')).date() \\\n if ((x.hour == 22)|(x.hour == 23)) else x.date() \\\n for x in dat['LTM']]\n\n # dats not datetime like - force it\n dat['dates'] = pd.to_datetime(dat['dates'])\n # now set as index\n dat.set_index('dates', inplace=True)\n # this wud by default drop curent index 'TM'\n # drop 'STN_NUM' from columns\n dat.drop(labels=['STN_NUM'], axis=1, inplace=True)\n # Drop records/rows where ALL cell values in that row is missing NaN\n dat.dropna(how='all', inplace=True)\n\n\n '''add calendar day to serve as numeric equivalent of month-day combination'''\n dat['day'] = dat.index.dayofyear\n\n '''To trully be able to capture seasonal variations\n we have to convert calendar day to a categorical variable.\n We can bin months like this '''\n # DJF 'summer',MAM 'autumn', JJA 'winter', SON 'spring'\n seasons = {'summer': [12, 1, 2], 'autumn': [3, 4, 5],\n 'winter': [6, 7, 8], 'spring': [9, 10, 11]}\n\n dat['season'] = ''\n for k, v in enumerate(seasons):\n # print (v,seasons[v])\n # print(obs.index.month.isin(seasons[v]))\n dat.loc[dat.index.month.isin(seasons[v]), 'season'] = v\n\n ''' dat['TS'] = .... We don't know it tis daate had storms yet!!! '''\n\n '''Best solution so far when deciding which record to remove\n for records with same date; remove rowwith more missing data'''\n\n dat = dat.reset_index()\n # this is very clever!!!\n dat = dat.loc[dat.notnull().sum(axis=1).groupby(dat['dates']).idxmax()]\n # now put dates back as index\n dat = dat.set_index(['dates'])\n\n return(dat)\n\n\n############################################################\n## Functions for basic time and timedelta conversions\n## TS stats start,end times and duration\n## conversion to decimal representation for ease of plotting\n## plotting routines etc\n#############################################################\n\n## Convert time HH:MM format to decimal HH.mm\n'''60 minutes make an hour - each minute is one-sixtieth (1/60) of an hour.\n Basis for converting number of minutes into fractions of an hour.\n To this for ease of plotting time as floats on y-axis\n 1/60 = 0.016666666666666666\n'''\ndef conversion(x):\n h,m,s = x.split(':')\n return (int(h) + int(m)/60 + int(m)/60/60)\n\n\n'''\nHelper function to convert timedelta object\nto 'HH:MM:SS' format (DON'T REALLY Need them!!)\n'''\ndef convert_timedelta(duration):\n #days, seconds = duration.days, duration.seconds\n seconds=duration.seconds\n hrs = seconds // 3600\n mins = (seconds % 3600) // 60\n secs = (seconds % 60)\n ret = '{}:{}:{}'.format(hrs,mins,secs)\n # ret = '%s:%s:%s' % (hrs,mins,secs)\n return (ret)\n\n'''\nfunction takes in the duration string \"%H:%M:%S\" format\nand uses datetime.strptime(date_string,format)\n\nReturn a datetime corresponding to date_string,parsed according to format.\nassert(t.hour*60*60+t.minute*60+t.second == delta.total_seconds())\n'''\n\ndef duration_to_timedelta(dt):\n t = datetime.strptime(dt,\"%H:%M:%S\")\n delta = timedelta(hours=t.hour,minutes=t.minute,seconds=t.second)\n return (delta)\n\n'''\nTwo datetime64 cols ('first','last')\nfirst 703 non-null datetime64[ns]\nlast 703 non-null datetime64[ns]\nduration 703 non-null timedelta64[ns]\n\n'duration' col is timedelta64\n\nUTC first last duration\n1985-01-06 1985-01-06 06:35:00 1985-01-06 12:30:00 05:55:00\n\nTo plot PDF's of these we need continous numeric so need to convert these to floats\n(actually not really need to do this)\n\nHere we first have to strip the date out from the datetime64 cols\n('first' and 'last')\nthen convert the remaining time data to decimal representation - unnecessary...\n'''\n\ndef format_datetimes(df):\n\n dataf = df.copy() # we don't want to modify passed df\n\n # dataf[['first','last']].apply(lambda x: datetime.strftime(x,'%H:%M:%S')).apply(conversion)\n # TypeError: (\"descriptor 'strftime' requires a 'datetime.date' object but received a 'Series'\", 'occurred at index first')\n\n '''applying for each series in turn works though'''\n dataf['first']= dataf['first']\\\n .apply(lambda x: datetime.strftime(x,'%H:%M:%S'))\\\n .apply(conversion)\n dataf['last'] = dataf['last']\\\n .apply(lambda x: datetime.strftime(x,'%H:%M:%S'))\\\n .apply(conversion)\n\n # Convert hh:mm:ss to minutes\n # daily['duration'] = daily['duration'].apply(lambda x :duration_to_timedelta(str(x)))\n '''\n fixed in get_ts_start_end_duration(dat)\n duration = pd.DatetimeIndex(dataf['duration'])\n dataf['duration'] = \\\n (duration.hour*60*60 + duration.minute*60 + duration.second)/(60*60.0)\n '''\n # dataf['duration'] = dataf['duration'].apply(conversion)\n '''AttributeError: 'Timedelta' object has no attribute 'split'''\n\n # dataf['duration'] = dataf['duration'].apply(lambda x: datetime.strftime(x,'%H:%M:%S')).apply(conversion)\n '''TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a \"Timedelta\"'''\n\n return(dataf)\n\n\n\n#### Function to plot TS start/end/duration stats\n#### Same function used for aws obs and gpats data\n\ndef plot_ts_stats(ts_df):\n\n #import matplotlib.pyplot as plt\n #import seaborn as sns\n import format_datetimes\n\n # convert datetime/deltatime to equivalent float representation\n dat = format_datetimes(ts_df)\n # dat = ts_df.copy()\n\n (fig, axes) = plt.subplots(figsize=(14,18) , nrows=4, ncols=1 )\n\n # get num of ts days by month for bar chart\n ts_days_by_month = \\\n dat.groupby(dat.index.month).size()\n\n\n ts_days_by_month.plot( kind='bar', ax=axes[0])\n axes[0].set_title(\"Total Num of Thunderstorm Days per month\", color='b',fontsize=15)\n axes[0].set_ylabel('Num of Thunder Days', color='g', fontsize=20)\n axes[0].tick_params(labelsize=10)\n\n # box plots for median and pdf of onset/end/duration\n sb.boxplot(data=dat, x=dat.index.month, y=\"first\", linewidth=2, ax=axes[1])\n axes[1].set_title(\"Thunderstorm Onset\", color='b',fontsize=15)\n axes[1].set_ylabel('TS Onset Time (UTC)', color='g', fontsize=20)\n axes[1].tick_params(labelsize=10)\n\n sb.boxplot(data=dat, x=dat.index.month, y=\"last\", linewidth=2, ax=axes[2])\n axes[2].set_title(\"Thunderstorm Finish\", color='b',fontsize=15)\n axes[2].set_ylabel('TS End Time (UTC)', color='g', fontsize=20)\n axes[2].tick_params(labelsize=10)\n\n sb.boxplot(data=dat, x=dat.index.month, y=\"duration\", linewidth=2, ax=axes[3])\n axes[3].set_title(\"Thunderstorm Duration Hours\", color='b',fontsize=15)\n axes[3].set_ylabel('TS Duration (hours)', color='g', fontsize=20)\n axes[3].set_xlabel('MONTHS OF THE YEAR', color='r', fontsize=15)\n axes[3].tick_params(labelsize=10)\n\n\n\n\n### No longer require tis #############\ndef gpats_format_datetimes(gpats):\n\n gpats_ts_stats = gpats.copy()\n\n duration=gpats_ts_stats['duration'].apply(lambda x:convert_timedelta(x) )\n # get back datetime from duration string - no more micro-sec!!!\n duration = duration.apply(lambda x: datetime.strptime(x, \"%H:%M:%S\"))\n # nb duration ow longer timedelta but shud not matter\n\n # datetime to string so we can strip microseconds\n first = gpats_ts_stats['first'].dt.strftime(\"%Y/%m/%d %H:%M:%S\")\n # get back datetime from new datetime string - no more micro-sec!!!\n first = first.apply(lambda x: datetime.strptime(x, \"%Y/%m/%d %H:%M:%S\"))\n\n last = gpats_ts_stats['last'].dt.strftime(\"%Y/%m/%d %H:%M:%S\")\n last = last.apply(lambda x: datetime.strptime(x, \"%Y/%m/%d %H:%M:%S\"))\n\n gpats_ts_stats['duration'] = duration\n gpats_ts_stats['first'] = first\n gpats_ts_stats['last'] = last\n\n return(gpats_ts_stats)\n\n\n\n\n############################################################\n#### TS DATES / STATS FROM ORIG MSG COL ####################\n'''\norig_msg_only = df.iloc[:,[0,54]].copy()\n\n# Find and replace/delete trend/TTF part from all raw messages\nno_trend = orig_msg_only['MSG'].str.\\\n replace(r'TTF|FM\\d{4}|TEMPO|INTER.*', '', case=False)\n\n# add as new series to df\n# no_trend field is original message text stripped of TTF\norig_msg_only.loc[:,'no_trend'] = no_trend\n\norig_msg_only['no_trend_RMK'] = \\\n orig_msg_only['no_trend'].str.cat(df['RMK'])\n\nmsg_ts_mask = orig_msg_only['no_trend_RMK'].str.\\\n contains(r'[vc|re|ra|+|-]?TS\\w*|Thunder|Lightning',case=False)\n\nmsg_ts_mask.fillna(False, limit=1,inplace=True)\n\n#---------------------------------------------------\n# save mask for later use\nimport pickle\nwith open('~/data/msg_ts_mask.pkl', 'wb') as f:\n pickle.dump(msg_ts_mask, f)\n\nmsg_ts_stats = get_ts_start_end_duration(\\\n\t\t\t\t\t\tdf.loc[msg_ts_mask].copy())\n# Filter zero duration TS events\nmsg_ts_stats = \\\n msg_ts_stats[msg_ts_stats['duration'] > 0]\n\nts_dates_from_msg = msg_ts_stats.index\n\n'''\n#########################################################\n###### MERGE AWS DATA WITH NETCDF DATA ##################\n'''\ndf_final = df.merge(\n sta_df500_about_YBBN,\n how='left',\n left_index=True, right_index=True)\n\nwith open('~/data/obs_ec_reanal_merge.pkl', 'wb') as f:\n pickle.dump(df_final[keep], f)\n\n\nwith open('~/data/obs_ec_reanal_merge.pkl', 'wb') as f:\n df_final = pickle.load(f)\n'''\n\n'''Most netcdf data are 3D [TIME,X,Y]\ne.g times slices of a variable for a given lat/lon box\n'''\n\ndef get_dimensions(nc_data):\n\n import netCDF4 as nc # netcdf module\n\n print ('Dimensions of nc data file')\n dim_keys = nc_data.dimensions.keys()\n print(dim_keys)\n\n print('Read latitide and longitude')\n x = nc_data.variables['longitude'][:] # read longitude variable\n y = nc_data.variables['latitude'][:] # read latitutde variable\n\n print(\"Longitude:len=\",len(x),x)\n print(\"Latitude: len=\",len(y),y)\n\n print('Read time and do conversion')\n # read the 'units' attributes from the variable time\n time_unit = nc_data.variables[\"time\"].getncattr('units')\n print(time_unit)\n # 'calendar' type attributes from the variable time\n time_cal = nc_data.variables[\"time\"].getncattr('calendar')\n print(time_cal)\n # convert time\n time = nc_data.variables['time'][:]\n print(\"Time:len=\",len(time))\n local_time = nc.num2date(nc_data.variables['time'][:],units=time_unit, calendar=time_cal)\n\n print(\"First data point time %s ->\\t\\t: %s\"\n % (time[0], local_time[0])) # check conversion\n print(\"Last data point time %s ->\\t: %s\"\n % (time[-1], local_time[-1])) # check conversion\n\n '''Data usually 3D [TIME, LONG (X), LAT (Y)]\n Some netcdf have extra 4th dimension, multiple pressure levels'''\n if ('level' in list(dim_keys)):\n levels = nc_data.variables['level'][:] # read longitude variable\n print(\"Pressure Levels: len=\",len(levels),levels)\n return (local_time,levels,x,y)\n else:\n return (local_time,x,y)\n\n\n\n# read airport lat long coordinates from given AV_ID\n# from avlocs database\ndef get_sta_latlon(sta):\n\n # avlocs_url = 'http://web.bom.gov.au/cosb/dms/mgdu/avloc/avloc.csv'\n avlocs_url = '~/data/avloc.csv'\n avlocs = pd.read_csv(avlocs_url, header=0, sep=';', comment='#',index_col='av_id')\n # sta_name = 'Gold coast'\n # name_mask = avlocs['name'].str.contains(sta_name.upper(), case=False)\n # Lots of locations with same name - useless!\n\n sta = sta.upper()\n lat_lon = avlocs[avlocs['type'] == 'AD'].loc[sta][['latitude','longitude']].values\n return lat_lon\n\n\n'''\nFind closest grid point to station.\nThis grid point is then used to extract\nrelevant variables for this location from netcdf file\n\nECMWF have a Python interface to ecCodes that does this\nfor us. Not sure they have one for netcdf.\nhttp://download.ecmwf.int/test-data/eccodes/html/namespaceec_codes.html\nhttps://software.ecmwf.int/wiki/display/ECC/grib_nearest\ncodes_grib_find_nearest() '''\n\n'''\nParameters\nsta_id : station aviation id like YBBN or YTWB\nnc_id : netcdf data file handle\ngrid_size: grid spacing in degrees, 0.25, 0.5 etc\n\nReturn\n(x_index, y_index): the integer indices\ncorresponding to grid point location closest to station\n'''\n\ndef nearest_grid_point(sta_id,nc_id,grid_size=0.5):\n\n # To create lat/lon grids manually\n # latitude = np.arange(lat_min, lat_max, grid_size)\n # longitude = np.arange(lon_min, lon_max, grid_size)\n\n latitude = nc_id.variables['latitude'][:]\n longitude = nc_id.variables['longitude'][:]\n lat_min=np.min(latitude)\n lat_max=np.max(latitude)\n lon_min=np.min(longitude)\n lon_max=np.max(longitude)\n\n print (\"min lat:%s\\tmax lat:%s\\tmin long:%s\\tmax long:%s\" %(lat_min,lat_max, lon_min,lon_max))\n\n (stn_lat, stn_lon) = get_sta_latlon(sta_id)\n\n '''Create 2D array mesh grid of our area\n for which we had extracted model data'''\n\n # Use meshgrid to make 2D arrays of the lat/lon data above\n lats, lons = np.meshgrid(latitude, longitude)\n\n '''\n Now find the absolute value of the difference between\n the station's lat/lon with every point in the grid.\n This tells us how close a point is to the particular\n latitude and longitude.'''\n\n abslat = np.abs(lats-stn_lat)\n abslon = np.abs(lons-stn_lon)\n\n '''\n Now we need to combine these two results.\n We will use numpy.maximum,\n which takes two arrays and finds the local maximum.'''\n\n c = np.maximum(abslon, abslat)\n\n '''find the index location on the grid of this\n by using the min function.'''\n\n latlon_idx = np.argmin(c)\n\n '''Now, this latitude/longitude index value is the index\n for a flattened array, so when you look for that same index value in,\n say, your temperature array,\n you should flatten the array to pluck out the value at that point.\n '''\n # grid_temp = data.flat[latlon_idx]\n '''\n If you don't like flattened arrays,\n you can also get the row/column index like this '''\n x, y = np.where(c == np.min(c))\n #grid_data = data[x[0], y[0]]\n grid_lat = lats[x[0], y[0]]\n grid_lon = lons[x[0], y[0]]\n\n print (\"Station %s coordinates are %s,%s\\\n \\nNearest grid point location is %s,%s\" \\\n %(sta_id,stn_lat,stn_lon,grid_lat, grid_lon ))\n\n # get longitude x-index and lat y-index\n x_index = int(np.abs(grid_lon - lon_min)/grid_size)\n y_index = int(np.abs(grid_lat - lat_min)/grid_size)\n\n\n return (x_index, y_index)\n\n\n'''\nNote http://james.hiebert.name/blog/work/2015/04/18/NetCDF-Scale-Factors/\n\nPacking floating point numbers into smaller data types\nhas the potential to half or quarter the data input or\noutput requirements for an application.\n\nTo scale grid date before writing to netcdf format - need to apply\ncorrect scale factor and offset\n\npacking/unpacking function requires three parameters:\nthe max and min of the data, and n, the number of bits\ninto which you wish to pack (8 or 16)\n\nSEE ALSO\nhttps://www.unidata.ucar.edu/software/netcdf/workshops/2010/bestpractices/Packing.html\n'''\n\ndef compute_scale_and_offset(min, max, n):\n # stretch/compress data to the available packed range\n scale_factor = (max - min) / (2 ** n - 1)\n # translate the range to be symmetric about zero\n add_offset = min + 2 ** (n - 1) * scale_factor\n return (scale_factor, add_offset)\n\n\n# simple packing and unpacking function:\n\ndef pack_value(unpacked_value, scale_factor, add_offset):\n return np.floor((unpacked_value - add_offset) / scale_factor)\n\ndef unpack_value(packed_value, scale_factor, add_offset):\n return packed_value * scale_factor + add_offset\n\n## get wind direction given U and V vectors\n## courtesy G.Buis\ndef get_wind_dir(u,v):\n rad2deg = 57.2957795\n temp = 270.0 - (rad2deg * np.arctan2(v, u))\n wdir = [(d-360) if (d>=360) else d for d in temp]\n return(wdir)\n\n## get wind speed given U and V vectors\ndef get_wind_spd(u,v):\n return(np.sqrt(u**2 + v**2))\n\n'''\nhttps://software.ecmwf.int/wiki/display/CKB/ERA-Interim%3A+compute+geopotential+on+model+levels\n'''\n# Geopotential z:units = \"m**2 s**-2\"\n# divide geopotential by the gravity of Earth\n# (9.80665 m s**-2 about 9.8 m\n\n\n\n##################################################################\n'''Get list of months spanning the time period for which\n analogues are sought\n https://stackoverflow.com/questions/34898525/generate-list-of-months-between-interval-in-python/34899127\n'''\ndef get_month_list(my_date,period):\n\n '''VERY SILLY HACK TO GET MONTHS IN DATA WINDOW\n we want to look at all aws data for months between\n start month and end month inclusive\n For e..g if start mon is 11 and end month is 3\n we want all month in between so [11,12,1,2,3] i.e.\n grab data for 5 month period centered on January '''\n\n start = pd.to_datetime(my_date) - pd.Timedelta(str(period)+' days')\n end = pd.to_datetime(my_date) + pd.Timedelta(str(period) + ' days')\n\n daterange = pd.date_range(start=start, end=end,freq='1M')\n daterange = daterange.union([daterange[-1] + 1])\n return([int(d.strftime('%m')) for d in daterange])\n\n\n'''\n#####################################################\nFUNCTION to grab data for a time period centered\non the day for which TS forecast is sought.\n\nLook for historical analogues for period 6 weeks wide period\nspanning 21 days (3 weeks) either side of date specified\nor today() if no date parameter passed\n\nIdeally we would like to filter by calendar days\nbut for time being we grab data for current month\nplus 1 month either side of curr month\n########################################################\n'''\n\n# http://cryptroix.com/2016/10/09/hello/\n# http://blog.thedigitalcatonline.com/blog/2015/02/11/default-arguments-in-python/\n'''we can use both standard and default arguments in a function,\nbut the order in which they appear in the function prototype is fixed:\nall standard arguments first, then the default ones OK\n'''\n\n# Dates = namedtuple('Dates', ('cur_day', 'period', 'start', 'end'))\ndef grab_data_period_centered_day_aws(df_final,period=21, day=None):\n\n print('Processing {}: Data grab window is {} X 2 (days) wide'.format(day,period))\n\n '''\n month_map = pd.Series(\n index=list(range(1,13)),\\\n data=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'])\n '''\n # get dates for start/end of 6 week period centered on given date\n if (day):\n cur_mon = day.month\n start = pd.to_datetime(day) - pd.Timedelta(str(period)+ ' days')\n end = pd.to_datetime(day) + pd.Timedelta(str(period)+ ' days')\n elif (day is None):\n # no date supplied, build period centered on today()\n cur_mon = int(pd.datetime.today().strftime(\"%m\"))\n # print(\"Day is None, Use Current Month\", cur_mon)\n start = pd.datetime.today() - pd.Timedelta(str(period)+ ' days')\n end = pd.datetime.today() + pd.Timedelta(str(period)+ ' days')\n else:\n print(\"This can never happen - ever !!!\")\n\n '''\n # df_final_Jan = df_final.loc[df_final.index.month==cur_mon, keep]\n\n num_days = len(pd.date_range(start,end))\n\n start_mon,start_day = int(start.strftime(\"%m\")),int(start.strftime(\"%d\"))\n end_mon,end_day = int(end.strftime(\"%m\")),int(start.strftime(\"%d\"))\n '''\n month_list = get_month_list(day,period)\n\n print (\"start = {}, end = {}\".format(start,end))\n print (\"Analogue months wud be {}\".format(month_list))\n '''\n print (\"Looking for analogues through months between {} {} and {} {}\\\n centered on {}\"\\\n .format(month_map.loc[start_mon], start_day,\\\n month_map.loc[end_mon], end_day,\\\n day.strftime(\"%Y:%m:%d\"))) # pd.datetime.today().strftime(\"%Y:%m:%d\")))\n '''\n return (df_final\\\n .loc[df_final.index.month.isin(month_list)]\\\n .between_time(start_time='00:00',\n end_time='00:05',include_start=True,\n include_end=False)\\\n .resample('H').first().dropna(how='all'))\n\n\n'''\n########################################################\nFUNCTION to build envelopes for synoptic parameters T,Td,etc\nthen create a mask using the envelope to extract matching\ndays from data set.\nReturns num of matching days found and how many of those\nmatching days actually had TS\n#########################################################\n'''\n# Params = namedtuple('Params', ('uwdir1', 'uwdir2', 'uwspd1', 'uwspd1'))\n# https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/\n\ncols_display = ['any_ts','T','Td','QNH','WS', 'WDir', 'MaxGust10min','vis',\n 'vis_min_dir', 'vis_aws', 'PW', 'PW1_desc', 'PW2_desc', 'WDIR_DLM','WSPD_DLM','T500','date']\n\ndef calculate_percent_chance_ts_aws(df_period, obs_4day):\n\n print(\"Obs for day\", obs_4day)\n\n # 60 deg upper 500 wind dir window\n UDL = obs_4day['wdir_500']-30\n UDR = obs_4day['wdir_500']+30\n\n steering_dir_mask = \\\n (df_period['WDIR_DLM'] >= UDL) & \\\n (df_period['WDIR_DLM'] <= UDR)\n\n\n # TWO special cases\n # Cases r exclusive - only one can happen at a time\n\n # CASE 1: UDL NEGATIVE WHEN obs_4day['wdir_500'] < 30\n # a negative wind direction\n # e.g. if wdir=10 ---> UDL=10-30=-20\n if (UDL < 0):\n print(\"500 dir = \", obs_4day['wdir_500'])\n UDL = 360 - abs(UDL)\n print(\"New UDL: {} UDR: {}\".format(UDL,UDR))\n steering_dir_mask = \\\n (df_period['WDIR_DLM'] >= UDL) | \\\n (df_period['WDIR_DLM'] <= UDR)\n\n # CASE 2: UDR GTR THAN 360 if obs_4day['wdir_500'] > 330\n # will give a wind direction > 360\n # say if wdir=350 ---> UDR=350+30=380\n if (UDR > 360):\n print(\"500 dir = \", obs_4day['wdir_500'])\n UDR = 30 - (360 - obs_4day['wdir_500'])\n print(\"New UDL: {} UDR: {}\".format(UDL,UDR))\n steering_dir_mask = \\\n (df_period['WDIR_DLM'] >= UDL) | \\\n (df_period['WDIR_DLM'] <= UDR)\n\n #print(\"UDL: {} UDR: {} USL: {} USR: {} UTL: {} UTR: {} SPL: {} SPR: {} STdL: {} STdR: {} \"\\\n # .format(UDL,UDR,USL,USR,UTL,UTR,SPL,SPR,STdL, STdR))\n\n USL = obs_4day['wspd_500']-10\n USR = obs_4day['wspd_500']+10\n steering_spd_mask = (df_period['WSPD_DLM'] > USL) & \\\n (df_period['WSPD_DLM'] < USR)\n\n UTL = obs_4day['T500']-5\n UTR = obs_4day['T500']+5\n upper_500T_mask = (df_period['T500'] > UTL) & \\\n (df_period['T500'] < UTR)\n\n SPL = obs_4day['P']-5\n SPR = obs_4day['P']+5\n qnh_mask = (df_period['QNH'] > SPL) & \\\n (df_period['QNH'] < SPR)\n\n STdL = obs_4day['Td']-5\n STdR = obs_4day['Td']+5\n td_mask = (df_period['Td'] > STdL) & \\\n (df_period['Td'] < STdR)\n\n mask = steering_dir_mask&steering_spd_mask&upper_500T_mask&qnh_mask&td_mask\n\n num_of_TS_days = df_period.loc[mask,'any_ts'].sum()\n num_of_days_match_synop_pattern = \\\n df_period.loc[mask].shape[0]\n\n if (num_of_days_match_synop_pattern > 0):\n\n if (num_of_TS_days > 0):\n duh = df_period.loc[mask,cols_display]\n # print(duh.sort_index())\n return (mask,duh,num_of_days_match_synop_pattern,num_of_TS_days)\n #return(num_of_TS_days/num_of_days_match_synop_pattern*100)\n else:\n # print(\"No matching TS days found\")\n # calling function expects a tuple, can't help!!\n return (mask,None,num_of_days_match_synop_pattern,0)\n else:\n # print(\"No matching synoptic pattern in dataset\")\n # calling function expects a tuple, can't help!!\n return (mask,None,-1,-1)\n\n\n\n################################################################\n'''MODIFY ABV FUNCTIONS to use sonde data upper air parameters\nT500, Td500, wdir_500, wspd_500 for synoptic pattern matching\nWe can use EC Reanal or AR Reanal as well for upper data.\nFor those avlocs that have sonde flight, use that instead.\n\npandas.Series.dt.dayofyear grabs us The ordinal day of the year\ndf['date'].dt.dayofyear\npandas.DatetimeIndex.dayofyear\nDatetimeIndex.dayofyear\nstorm_dates_ybbn_area.dayofyear\n\nUse the calendar day of year to grab data across ALL years\nfor SAME period/season\n\ninput:\n sonde_date = this is DAILY 00Z data (merged AWS and sonde)\n AWS is aws_data.resample('D')['AvID','Td','QNH','any_ts','AMP'].first(),\n sonde=sonde_data[['wdir500','wspd500','T500', 'lr850_500']],\n .rename(columns={'QNH': 'P','any_ts':'TS'})\nperiod: default 6 weeks either side of given date\nday : date for which forecast is sought '''\n#################################################################\n\n\ndef grab_data_period_centered_day_sonde(sonde_data,period=42, day=None):\n\n '''\n print('\\nExtracting aws/sonde data for same seasonality or\\\n \\ncalendar days window:{} days either side of {}'\\\n .format(period,period))\n '''\n # get dates for start/end of X weeks period centered on given date\n if (day): # IF\n start = pd.to_datetime(day) - pd.Timedelta(str(period) + ' days')\n end = pd.to_datetime(day) + pd.Timedelta(str(period) + ' days')\n else: #no date suppiled - use todays date\n start = pd.datetime.today() - pd.Timedelta(str(period) + ' days')\n end = pd.datetime.today() + pd.Timedelta(str(period) + ' days')\n\n # print (\"start = {}, end = {}\".format(start, end))\n\n # convert time period to day of year range\n day_range = pd.date_range(start=start,end=end,freq='D').dayofyear\n\n # grab sonde samples for specified calendar days/day of year only\n return (sonde_data.loc[sonde_data.index.dayofyear.isin(day_range)])\n\n################################################################\n'''Extract days with matching synop pattern and find how\nmany had TS. Fraction of matching synop days with storms\nis proxy for storm potential.\ninputs:\n obb_win: this is DAILY 00Z data (merged AWS and sonde)\n for a given calendar day period across several years\n obs_4day: observations close to 00Z for station\n for date for which TS forecast is sought\n For current day, grab the 00Z sonde and station 00Z sfc obs\n For future date, grab these fields from NWP. (Not yet coded!)'''\n###################################################################\ndef calculate_percent_chance_ts_sonde(obb_win, obs_4day):\n\n\n print('\\nSearching matched season records/days for synoptic condition matches....')\n\n # convert obs to series for dict like indexing\n # obs_4day = obs_4day.T.squeeze()\n\n '''\n Wind directions need special attention\n Normal Case:\n DIR between 30 and 330, can do normal +30/-30\n\n TWO special cases\n CASE 1: wdir between 330 and 360\n say if wdir=350, wdir+30=380!!\n so here wdir=wdir+30-360 to get correct dir\n\n CASE 2: wdir between 0 and 30\n e.g. if wdir=10, wdir-30 = -20,-ve wind directiom\n so here wdir=wdir-30+360 to get correct dir'''\n\n if (obs_4day['wdir500'] >= 31) & (obs_4day['wdir500'] <= 329):\n UDL = obs_4day['wdir500']-30\n UDR = obs_4day['wdir500']+30\n steering_dir_mask = \\\n (obb_win['wdir500'] >= UDL) & \\\n (obb_win['wdir500'] <= UDR)\n\n elif (obs_4day['wdir500'] >= 330) & (obs_4day['wdir500'] <= 360):\n UDL = obs_4day['wdir500']-30\n UDR = obs_4day['wdir500']+30-360\n steering_dir_mask = \\\n (obb_win['wdir500'] >= UDL) | \\\n (obb_win['wdir500'] <= UDR)\n\n elif (obs_4day['wdir500'] >= 0) & (obs_4day['wdir500'] <= 30):\n UDL = obs_4day['wdir500']-30+360\n UDR = obs_4day['wdir500']+30\n steering_dir_mask = \\\n (obb_win['wdir500'] >= UDL) | \\\n (obb_win['wdir500'] <= UDR)\n else:\n print(\"No shit wind\", obs_4day['wdir500'] )\n\n\n USL = obs_4day['wspd500']-10\n USR = obs_4day['wspd500']+10\n steering_spd_mask = (obb_win['wspd500'] > USL) & \\\n (obb_win['wspd500'] < USR)\n\n UTL = obs_4day['T500']-5\n UTR = obs_4day['T500']+5\n upper_500T_mask = (obb_win['T500'] > UTL) & \\\n (obb_win['T500'] < UTR)\n\n SPL = obs_4day['P']-5\n SPR = obs_4day['P']+5\n qnh_mask = (obb_win['P'] > SPL) & \\\n (obb_win['P'] < SPR)\n\n STdL = obs_4day['Td']-5\n STdR = obs_4day['Td']+5\n td_mask = (obb_win['Td'] > STdL) & \\\n (obb_win['Td'] < STdR)\n\n # middle 50% 5.5 to 6.5 for TS days, 5.0 to 6.0 for TS-free days\n # middle 50% 24 to 28 for TS days, 20 to 24 for non- TS days\n '''Better ability to discriminate than real lapse rate - we use this'''\n lr_mask = (obb_win['tmp_rate850_500'] > (obs_4day['tmp_rate850_500']-5)) & \\\n (obb_win['tmp_rate850_500'] < (obs_4day['tmp_rate850_500']+5))\n\n # for pure temperature difference between 850 and 500\n #lr_mask = (obb_win['tmp_rate'] > (obs_4day['tmp_rate'] - 10)) & \\\n # (obb_win['tmp_rate'] < (obs_4day['tmp_rate'] + 10))\n\n print(\"Synop parameter thresholds\\n500hPa wind DIR:\\t{} and {} degrees\\\n \\n500hP wind SPD:\\t\\t{} to {} knots\\n500hP Temp:\\t\\t{} to {} deg C\\\n \\nSLP:\\t\\t{} to {} hPa, \\nsfc Td:\\t\\t{} to {} deg C\\\n \\nLapse Rate:\\t\\t{} to {} degC/km\"\n .format(UDL, UDR, round(USL,1), round(USR,1),\n round(UTL,1), round(UTR,1), SPL, SPR,\n round(STdL,1),round(STdR,1),\n round(obs_4day['tmp_rate850_500']-5,1),\n round(obs_4day['tmp_rate850_500']+5),1))\n\n mask = steering_dir_mask & steering_spd_mask & \\\n upper_500T_mask & qnh_mask & td_mask & lr_mask\n\n\n matching_synops = pd.DataFrame() # empty df\n num_of_days_match_synop_pattern = np.nan\n num_of_TS_days = np.nan\n\n try:\n matching_synops = obb_win.loc[mask]\n '''num of days matching conditions is just number of\n days satisfying synop condition envelopes above'''\n #this can fail if no matchs\n num_of_days_match_synop_pattern = \\\n matching_synops.shape[0]\n except:\n print(\"No matching synoptic days found in dataset\")\n # exit - calling fn expected to deal with situation\n return (mask,matching_synops, # all NaNs except mask\n num_of_days_match_synop_pattern,num_of_TS_days)\n\n\n ''' for days satisfying synop conditions,count how many had TS\n 'TS' is either True/1 or False/0 '''\n try:\n num_of_TS_days = matching_synops['TS'].sum()\n except:\n print(\"No TS days found in matching synops\")\n return (mask,matching_synops,\n num_of_days_match_synop_pattern,num_of_TS_days)\n # only num_of_TS_days will be NaN\n\n # we get to here if no errors above, so no NaNs in return\n return (mask,matching_synops,\n num_of_days_match_synop_pattern,num_of_TS_days)\n\n\n############################################################\ndef calculate_percent_chance_fg_sonde(obb_win:pd.DataFrame, obs_4day:pd.Series):\n\n # print(f'\\nSearching matched season records/days for fog like conditions using these parameters\\n{obs_4day}')\n '''\n obb_win is data we are searching through - columns are\n ['AvID', 'T', 'Td','WS','WDir','QNH','fogflag','Station', 'level','900_wdir','900_WS']\n\n obs_4day is data we use for current day 00Z or 06Z data\n\n obs_4day['P'] = float(list(request.form.items())[0][1])\n obs_4day['T'] = float(list(request.form.items())[1][1])\n obs_4day['Td'] = float(list(request.form.items())[2][1])\n obs_4day['900Dir'] = float(list(request.form.items())[3][1])\n obs_4day['900spd'] = float(list(request.form.items())[4][1])\n '''\n\n if (obs_4day['900Dir'] >= 31) & (obs_4day['900Dir'] <= 329):\n UDL = obs_4day['900Dir']-30\n UDR = obs_4day['900Dir']+30\n\n steering_dir_mask = \\\n (obb_win['900_wdir'] >= UDL) & \\\n (obb_win['900_wdir'] <= UDR)\n print(f'900Hpa wind direction envelop:\\t{obs_4day[\"900Dir\"]} -->{UDL} to {UDR}')\n\n elif (obs_4day['900Dir'] >= 330) & (obs_4day['900Dir'] <= 360):\n UDL = obs_4day['900Dir']-30\n UDR = obs_4day['900Dir']+30-360\n\n steering_dir_mask = \\\n (obb_win['900_wdir'] >= UDL) | \\\n (obb_win['900_wdir'] <= UDR)\n print(f'900Hpa wind direction envelop:\\t{obs_4day[\"900Dir\"]} -->{UDL} to {UDR}')\n\n elif (obs_4day['900Dir'] >= 0) & (obs_4day['900Dir'] <= 30):\n UDL = obs_4day['900Dir']-30+360\n UDR = obs_4day['900Dir']+30\n\n steering_dir_mask = \\\n (obb_win['900_wdir'] >= UDL) | \\\n (obb_win['900_wdir'] <= UDR)\n print(f'900Hpa wind direction envelop:\\t{obs_4day[\"900Dir\"]} -->{UDL} to {UDR}')\n else:\n print(\"No shit wind\", obs_4day['900Dir'] )\n # better set it to False - so match will fail - else will crash!!\n steering_dir_mask=False\n\n '''\n For fog - wind speeds does not look like strong discriminator\n # Percentage or Frequency of wind speeds bins\n 33% of fog cases had 3000ft winds 0-10 knots\n 50% of fog cases had 3000ft winds 10-20 knots\n 14% of fog cases had 3000ft winds 20-30 knots, only 3% 30-40, 0% 40+\n > 83% of fog cases wind below 20 knots\n > 97% of fog cases wind below 30 knots\n For no fog cases\n 29% of fog cases had 3000ft winds 0-10 knots\n 47% of fog cases had 3000ft winds 10-20 knots\n 20% of fog cases had 3000ft winds 20-30 knots, only 4% 30-40, <1% 40+\n > 85% of fog cases wind below 20 knots\n > 97% of fog cases wind below 30 knots '''\n\n USL = obs_4day['900spd']-10 # we changed range from +-10 to +-8\n USR = obs_4day['900spd']+10\n steering_spd_mask = (obb_win['900_WS'] > USL) & \\\n (obb_win['900_WS'] < USR)\n print(f'900Hpa wind speed envelope:\\t{obs_4day[\"900spd\"]:.1f} --> {USL:.1f} to {USR:.1f}')\n\n ''' SFC P not good at all to discriminate fog/no-fog days - allow larger range '''\n SPL = obs_4day['P']-4 # we change range from +-5 to +-2\n SPR = obs_4day['P']+4\n qnh_mask = (obb_win['QNH'] > SPL) & \\\n (obb_win['QNH'] < SPR)\n print(f'QNH envelope:\\t\\t\\t{obs_4day[\"P\"]} --> {SPL:.1f} to {SPR:.1f}')\n\n ''' SFC T not good at all to discriminate fog/no-fog days - allow larger range\n STL = obs_4day['T']-4\n STR = obs_4day['T']+4\n t_mask = (obb_win['T'] > STL) & (obb_win['T'] < STR)\n print(\"SFC T: \", obs_4day['T'], STL,STR) '''\n\n\n STdL = obs_4day['Td']-3 # we change range from +-5 to +-2\n STdR = obs_4day['Td']+3\n td_mask = (obb_win['Td'] > STdL) & (obb_win['Td'] < STdR)\n print(f'SFC TD:\\t\\t\\t\\t{obs_4day[\"Td\"]} --> {STdL:.1f} to {STdR:.1f}')\n\n #Need to check for low to mid moisture RH contribution\n #eg. k-index K index = (T850 - T500) + Td850 - (T700 - Td700)\n obb_win_TmTd = obb_win['T'] - obb_win['Td']\n obs_TmTd = (obs_4day['T'] - obs_4day['Td'])\n TmTd_mask = (obb_win_TmTd > (obs_TmTd-3)) & (obb_win_TmTd < (obs_TmTd+3))\n print(f'SFC TmTd (+/- 3):\\t\\t{obs_TmTd:.1f} --> {(obs_TmTd-3):.1f} to {(obs_TmTd+3):.1f}')\n '''\n # middle 50% 6 to 8 for FG days, 8 to 12 for FGTS-free days\n # Better ability to discriminate than real lapse rate - we use this\n lr_low = obs_4day['lr_sfc_850']-3\n lr_up = obs_4day['lr_sfc_850']+3\n lr_mask = (obb_win['lr_sfc_850'] > lr_low) & (obb_win['lr_sfc_850'] < lr_up)\n print(f'Lapse Rate:\\t\\t\\t{obs_4day[\"lr_sfc_850\"]:.1f} --> {lr_low:.1f} to {lr_up:.1f}')\n '''\n mask = steering_dir_mask & steering_spd_mask & qnh_mask & td_mask & TmTd_mask #& lr_mask #& t_mask\n matching_synops = pd.DataFrame() # empty df\n num_of_days_match_synop_pattern = np.nan\n num_of_FG_days = np.nan\n\n try:\n matching_synops = obb_win.loc[mask]\n '''num of days matching conditions is just number of\n days satisfying synop condition envelopes above'''\n # print(matching_synops.index)\n # this can fail if no matchs\n num_of_days_match_synop_pattern = \\\n matching_synops.shape[0]\n print(f'Num days matching synop pattern={num_of_days_match_synop_pattern}')\n except:\n print(\"No matching synoptic days found in dataset\")\n # exit - calling fn expected to deal with situation\n return (mask,matching_synops, # all NaNs except mask\n num_of_days_match_synop_pattern,num_of_FG_days)\n\n\n ''' for days satisfying synop conditions,count how many had TS\n 'TS' is either True/1 or False/0 '''\n try:\n print(matching_synops['fogflag'])\n print(matching_synops[\"fogflag\"].value_counts())\n # num_of_FG_days = matching_synops.loc[matching_synops['fogflag']].sum() FAILS due NAN in fogflag\n # below ones work - so manage to get num fog days but for some reasons bombs so print never executes!!\n num_of_FG_days = matching_synops[\"fogflag\"].value_counts()[1]\n num_of_FG_days = matching_synops.loc[matching_synops['fogflag']==True].shape[0]\n print(f'Num FG days found in matching synops={num_of_fog_days}')\n except:\n print(\"Did not find any FG days found in matching synops\")\n return (mask,matching_synops,\n num_of_days_match_synop_pattern,num_of_FG_days)\n # only num_of_FG_days will be NaN\n\n # we get to here if no errors above, so no NaNs in return\n return (mask,matching_synops,\n num_of_days_match_synop_pattern,num_of_FG_days)\n\n\n#############################################################\n## Function to get TS start and end times for each day\n'''\ndef get_ts_predictions() calls\n--> def ts_stats_based_on_aws(aws_df, matched_ts_dates)\nwith a list of dates/days that had TS in matched synop days\nwhich in turn calls this fn with aws observations\nfor days when had TS '''\n#############################################################\ndef get_ts_start_end_duration(dat):\n\n '''Parameters:\n dataframe containing all observations that were classified\n as being \"TS like\"\n dataframe can even be all fog observations - all this fn does\n is for each day find the 1st obs, last obs and use that for simple\n duration calculation.\n returns: daily data with start, end and duration info for storms'''\n\n\n df=dat.copy() #make copy as default is pass by reference\n\n ''' agg() NEEDs a column to work on!\n\n while resample('D') works on the datetime index\n built-in fn first/last need datetime like column,\n add 'time' col for easy aggregation\n .agg({'X':['sum','mean'],'Y':'max','Z':['min','std']})'''\n\n df['time'] = df.index\n '''\n print(\"\\nFunction --> get_ts_start_end_duration(dat)\\n\",\n df[['WDir','WS','T','Td','QNH','date','any_ts','AMP']].head(1))\n '''\n df1 = df.resample('D')['time']\\\n .aggregate(['first', 'last']).dropna()\n\n\n # calculate duration for TS each calendar day\n # taking diff of two datetimes yield timedelta obj\n df1['duration'] = round(\\\n (df1['last'] - df1['first'] )/np.timedelta64(1, 'h'), 1)\n\n # get some other TAF forcast parameters\n # lowest vis and longest duration between 1 speci and next\n\n '''AWS (Automatic Weather Station) flag\n 0 Manned 1 Automatic 2 Hybrid\n\n Note stations such as YAMB will be code 2 when manned\n and 1 when on AUTO - maybe we need list of stations\n like ['YAMB','YBOK','YTBL'] shud be treated as 2-hybrid\n even when flag is 1.'''\n #hybrid_sta_list = ['YBBN','YAMB','YBOK','YTBL','YBCS']\n #if sta in hybrid_sta_list:\n '''\n if (df.iloc[-1]['AWS_Flag'] == 2):\n df1['min_vis'] = df.resample('D')['vis']\\\n .aggregate('min').dropna()\n elif (df.iloc[-1]['AWS_Flag'] == 1):\n df1['min_vis'] = df.resample('D')['vis_aws']\\\n .aggregate('min').dropna()\n else:\n df1['min_vis'] = df.resample('D')['vis']\\\n .aggregate('min').dropna()\n '''\n\n # hybrid stations cause issues from time to time\n # better use try except - so ensures at least one successful block\n try:\n # allways try with default vis first - if that fails tey vis_aws\n df1['min_vis'] = df.resample('D')['vis']\\\n .aggregate('min').dropna()\n except:\n print(\"KeyError: Column not found: vis\")\n df1['min_vis'] = df.resample('D')['vis_aws']\\\n .aggregate('min').dropna()\n\n df1['max_gust'] = df.resample('D')['MaxGust10min']\\\n .aggregate('max').dropna()\n\n df1['ttl_rain'] = df.resample('D')['pptn10min'] \\\n .aggregate('sum').dropna()\n\n ''' THIS BIT NOT REALLY WORK WELL AT THE MOMENT\n # duration of each speci, min,max,mean\n # diff does val(n+1) - val(n), where n index\n df['time_diff'] = df['time'].diff()\n\n df2 = df.resample('D')['time_diff']\\\n .aggregate(['min', 'max']).dropna()\n\n #df2['min'] = pd.datetime(df2['min'],\"%H:%M\")\n # df2['min'] = df2['min'].dt.get_total_hours()\n\n df2['min'] = df2['min']\\\n .apply(lambda x: round(x / np.timedelta64(1, 'h')) )\n df2['max'] = df2['max']\\\n .apply(lambda x: round(x / np.timedelta64(1, 'h')) )\n #df2['intervals'] = df.resample('D')['time_diff'].tolist()\n '''\n\n '''\n df2['min'] =df2['min']\\\n .apply(lambda x: round(pd.Timedelta(x).total_seconds() \\\n % 86400.0 / 3600.0) )\n df2['min'] =df2['min']\\\n .apply(lambda x: round(pd.Timedelta(x).total_seconds() \\\n % 86400.0 / 3600.0) )\n '''\n '''\n https://stackoverflow.com/questions/44864655/pandas-difference-between-apply-and-aggregate-functions\n https://stackoverflow.com/questions/21828398/what-is-the-difference-between-pandas-agg-and-apply-function\n '''\n # da = pd.concat([df1,df2],axis=1)\n # return (da)\n return(df1)\n\n\n\n###############################################################\n'''\nLook up original AWS datafile with MATHCHNG synop days/dates that had TS\nThis should grab grab ALL (1/2 hourly) obs for matching synop days that had TS\n\nNote\n\ndf.loc[(df.index.isin(new_dates)),:] # doesn't quite cut it !!!\nREF\nhttps://stackoverflow.com/questions/48152584/how-to-filter-a-dataframe-of-dates-and-hours-by-a-list-of-dates\n\n\nNote we can't do TS start and end times using this new subset dataframe\nsince get_ts_start_end_duration just grabs 1st and last obs from each day by default\nW have to identify/label the TS obs/speci so it will then pick the 1st and last SPECI\nfor start and end times\naws['M-type'] is 'M' for routine Metar, 'S' for all SPECIS\n'''\n###############################################################\n\ndef ts_stats_based_on_aws(aws_df, matched_ts_dates):\n\n if len(matched_ts_dates) == 0:\n print(\"No TS days found in matching synops - so no stats\")\n return (pd.DataFrame())\n\n # extract aws obs, ONLY for days in matching synop that had TS\n aws_4_ts_days = \\\n aws_df.loc[(aws_df.index.floor('D').isin(matched_ts_dates))]\n # NB since index floored to day, Time data in index is dropped\n '''\n print(\"\\nFunction --> ts_stats_based_on_aws(aws_df, matched_ts_dates)\",\n aws_4_ts_days.shape,\"\\n\", \\\n aws_4_ts_days[['WDir','WS','T','Td','QNH','date','any_ts','AMP']].head(1))\n # mask using aws 'specis'/ or gpats count\n '''\n mask = (aws_4_ts_days['M_type'].str.contains('s')) | \\\n (aws_4_ts_days['AMP'] > 0)\n\n if np.sum(mask) > 0: # mask sum will show how many True!!\n ts_days_stats = get_ts_start_end_duration(aws_4_ts_days.loc[mask])\n ts_days_stats.index.name = 'Date'\n # ts_days_stats.reset_index().set_index(['Date','source'])\n return (ts_days_stats)\n else:\n print(\"No SPECI or lightning detected for TS days found - WIERDOOO.\\\n \\nInsufficient samples to generate statistics\\\n \\nThen how come found TS days in matched days!!!!\")\n return (pd.DataFrame()) #empty dataframe\n\n\n###############################################################\n'''\nFind percentage of matching synop days that had storms\n\ninput:\naws: aws data file from merge_aws_gpats_data(sta,aws_file)\nIndex(['AvID', 'M_type', 'pptn10min', 'pptn9am', 'T', 'Twb', 'Td', 'RH', 'VP',\n 'SVP', 'WS', 'WDir', 'MaxGust10min', 'QNH', 'Ceil1_amnt', 'Ceil2_amnt',\n 'Ceil3_amnt', 'Ceil1_ht', 'Ceil2_ht', 'Ceil3_ht', 'CeilSKCflag',\n 'vis_aws', 'AWS_PW', 'AWS_PW15min', 'AWS_PW60min', 'AWS_Flag',\n 'CAVOK_SKC_flag', 'RWY_ws_shear_flag', 'date', 'any_ts', 'AMP']\n\nsonde: Brisbane sonde data, T,Td,wdir,wsp values at sfc, 850 and 500\nIndex(['P', 'Z', 'T', 'Td', 'wdir', 'wspd', 'P850', 'Z850', 'T850', 'Td850',\n 'wdir850', 'wspd850', 'P500', 'Z500', 'T500', 'Td500', 'wdir500',\n 'wspd500', 'tmp_rate', 'gpt_rate', 'lr850_500', 'LTM', 'day', 'season',\n 'TS'],\n\nperiod: how wide so seasonality match\n14 days - 2 weeks wide, 28 is 4 weeks , 42 days is 6 weeks\nmy_date: date for which forecast is sought\n\nmakes these fn calls\n\nsearch_window_obs =\n grab_data_period_centered_day_sonde(sonde,42,day)\n\nmask,synop_match_obs,num_matches,ts_day_cnt =\n calculate_percent_chance_ts_sonde(search_window_obs, obs_4day)\n\n\nmatched = ts_stats_based_on_aws(aws,matched_ts_dates)\n--> call made by abv fn\nts_days_stats = get_ts_start_end_duration(aws_4_ts_days.loc[mask])\n'''\n###############################################################\n\n\n\ndef get_ts_prediction(aws_sonde_daily,aws_data, period, my_date=None,obs_4day=None):\n\n matched = pd.DataFrame() # empty dataframe-no TS found in matches\n\n station = aws_data.iloc[-1]['AvID']\n print(\"Searching archive for matching synop days for {}\".format(station))\n print(\"Station aws Td, QNH merge with Brisbane sonde data\\n\",aws_sonde_daily.tail())\n\n if my_date:\n '''If date supplied - get prediction for that day'''\n print(\"Trying prediction for \",my_date)\n day = pd.to_datetime(my_date) #my_date ='2018-02-13'\n obs_4day = aws_sonde_daily.loc[my_date].T.squeeze()\n else:\n '''If no date supplied - get prediction for today'''\n print(\"No date given - will try predictions for today()\")\n day = pd.datetime.today()\n obs_4day = obs_4day\n\n print(\"\\nObs for day\\n\",obs_4day)\n\n # we can't have any missing values in search parameters\n if obs_4day[['wdir500','wspd500','T500', 'P','Td','tmp_rate850_500']].isnull().any():\n print(\"Fix Missing parameters First\")\n return (pd.DataFrame())\n\n search_window_obs = \\\n grab_data_period_centered_day_sonde(aws_sonde_daily,42,day)\n\n mask,synop_match_obs,num_matches,ts_day_cnt = \\\n calculate_percent_chance_ts_sonde(search_window_obs, obs_4day)\n\n #print(\"num_matches,ts_day_cnt\",num_matches,ts_day_cnt)\n\n if num_matches > 0:\n print('\\nSearch window is:', len(search_window_obs),\"days wide\"\\\n '\\nNum days matching synop pattern in search window:',\\\n len(synop_match_obs),mask.sum(),num_matches,\\\n '\\nNum days with TS in matching synop days:',ts_day_cnt)\n #mask,synop_match_obs\n #num_matches,ts_day_cnt\n # print(synop_match_obs.tail(1))\n else:\n print('\\nlen(synop_match_obs) > 0:ELSE\\\n \\nNo matching days found from {} historical days.\\\n \\nMust have very unusual conditions!!!'\\\n .format(len(search_window_obs)))\n return (matched)\n\n if (ts_day_cnt >= 0):\n print(\"\\nOut of {} days with matching synop pattern or environment\\n\\\n {} days had storms at {} airport.\\nChance TS at {} = {}%\"\\\n .format(len(synop_match_obs),\n synop_match_obs['TS'].sum(),station,\n station,(synop_match_obs['TS'].sum()/len(synop_match_obs))*100))\n\n print('Num days with TS: ',synop_match_obs['TS'].sum(),\n 'From matching synops:',synop_match_obs['TS'].shape[0])\n\n matched_ts_dates=(synop_match_obs[synop_match_obs['TS']>0].index)\n # print(\"1st method\",matched_ts_dates)\n # 1st method DatetimeIndex(['2008-06-20'], dtype='datetime64[ns]', name='UTC', freq=None)\n print(\"\\nMatching dates:\", matched_ts_dates)\n\n matched = ts_stats_based_on_aws(aws_data,matched_ts_dates)\n return(matched)\n\n else:\n print('\\nif (ts_day_cnt > 0):ELSE\\nNo matching days found \\\n \\nfrom {} historical days. Must have very unusual conditions!!!'\\\n .format(len(search_window_obs)))\n return (matched)\n\n\ndef get_ts_predictions_stations(stations,sonde2day=None,my_date=None):\n\n sonde_from_adams = ''\n print(\"\\n\\nProcessing TS prediction for station:{}\".format(stations))\n import math\n\n '''on nginx server cur_dir causes issue !!!\n replacing it with app works with data direcroty moved under avguide/app/\n # cur_dir = os.path.dirname(__file__)\n # os.path.join(cur_dir,'data','sonde_hank_final.pkl'), 'rb'))\n '''\n day = None\n obs_4day=None\n predictions = []\n data = pd.DataFrame()\n\n # check set membership of stations - for brisbane stations load Brisbane sonde\n # Empty containers are \"false\" (so empty set would be null/false) as are numeric values equivalent to zero\n # you can emplicityl test empty set using if len(myset) <-- cardinality of the set\n if set(stations).intersection(set(['YBBN','YBAF','YAMB','YBSU','YBCG','YBOK','YTWB','YKRY'])):\n # load Brisbane sonde data file\n sonde_data = pickle.load( open(\n os.path.join('app','data','YBBN_sonde_2300_aws.pkl'), 'rb'))\n #os.path.join('app','data','sonde_hank_final.pkl'), 'rb'))\n #sonde_data = get_sounding_data('YBBN','2300')\n print(\"BEGIN PROCESSING TS FORECASTS FOR SEQ STATIONS\\n\",sonde_data.tail())\n elif set(stations).intersection(set(['YBRK','YGLA','YTNG','YBUD','YHBA','YMYB','YEML','YCMT','YMRB','YBMK','YBPN','YBHM'])):\n # load Rockhampton sonde data file\n sonde_data = pickle.load( open(\n os.path.join('app','data','YBRK_sonde_2300_aws.pkl'), 'rb'))\n #sonde_data = get_sounding_data('YBRK','2300')\n print(\"BEGIN PROCESSING TS FORECASTS FOR CAPRICORN/CENTRAL HIGHLANDN COAST\\n\",sonde_data.tail())\n elif set(stations).intersection(set(['YSSY','YSRI','YWLM','YSBK','YSCN','YSHW','YSHL'])):\n sonde_data = pickle.load( open(\n os.path.join('app','data','YSSY_sonde_0300_aws.pkl'), 'rb'))\n print(\"\\n\\n\\n\\nBEGIN PROCESSING TS FORECASTS FOR SYDNEY BASIN\\n\",sonde_data.tail())\n\n '''\n We are matching storms based on 2300Z sonde data\n 2300Z sonde data is actually data for following/next calendar day\n so we need to reindex the sonde data so we merge METAR 00Z data with correct days sonde data\n No such problems using sonde data after 2300Z - as in SYd case when sonde is 02 or 03Z\n as then METAR day 00Z and Sonde day both fall on the same date/day\n '''\n if set(stations).intersection(set(['YBBN','YBAF','YAMB','YBSU','YBCG','YBOK','YTWB','YKRY'])):\n sonde_data.set_index(\n keys=(sonde_data.index.date + pd.Timedelta(str(1) + ' days')),\n drop=False,inplace=bool(1))\n # we loose datetime type of index in conversion above - restore BLW\n sonde_data.index = pd.to_datetime(sonde_data.index)\n\n # If date supplied - get TS predictions for that day\n # operationally - we wud always want predictions for today so my_date=''\n if my_date:\n day = pd.to_datetime(my_date) # my_date is string like '2018-02-13'\n else:\n # If no date supplied - get prediction for TODAY\n day = pd.datetime.today()\n print(\"def get_ts_predictions_stations:\\nNo date supplied-will try predictions for today\", day)\n\n # CHECK 1ST TO SEE IF WE HAVE SONDE DATA\n # IF NONE - CAN'T DO PREDICTIONS\n if 'sonde_item' in session:\n # we need this default flag False - cause most of the time\n # manual entry is best - esp on python anywhere.com\n # DON'T REMARK ELSE\n # if sonde_from_adams==0 : CODE BELOW FAILS !!!!\n sonde_from_adams = False\n # on BOM LAN sonde data is retrieved from adams - so not always the case\n # print(\"Houston - we have sonde data from adams\", sonde_from_adams == True)\n else:\n # TRY GET SONDE DATA FROM ADAMS IN 1ST INSTANCE\n try:\n sonde = getf160_adams(40842)\n sonde = sonde.resample('D').apply(get_std_levels_adams)\n # sonde = getf160_hanks(\"040842\") # dont need to do std levels for hanks\n # hanks works but runs into except clause!!!\n\n '''further post processing -\n - adjust date (23Z issue!), drop extra STN_NUM columns\n - add day of year , season, drop duplicate rows for same date'''\n sonde = process_adams_sonde(sonde).squeeze()\n print(\"Todays sonde flight for Brisbane:\", sonde)\n #logger.debug(\"Todays sonde flight:\", sonde2day)\n sonde_from_adams = True\n sonde2day = sonde\n print(\"\\n\\nSonde flight from adams \", sonde_from_adams, \" Sonde status \", sonde_from_adams==True)\n except:\n print(\"\\n\\nHaving trouble getting radionsonde for\",\\\n day, \"PLEASE ENTER SONDE DATA MANUALLY \", sonde2day)\n # FORCE USER TO ENTER SONDE DATA !!!!!!!!!!!!\n return redirect(url_for('sonde_update'))\n\n # WE DON'T PROCEED BELOW THIS LINE UNLESS HAVE SONDE DATA\n\n # now do predictions for all stations\n for station in stations:\n print(\"\\n\\nProcessing TS prediction for station:{} for {}\"\\\n .format(station,day.strftime(\"%Y-%m-%d\")))\n # get station aws archive data\n df = pickle.load(\n open(\n os.path.join('app','data', station+'_aws.pkl'), 'rb'))\n print(df[['AvID', 'WDir', 'WS', 'T', 'Td', 'QNH', 'any_ts', 'AMP']].tail(5))\n #print(df.index)\n #print(df.columns)\n #print(df.info)\n # merge with closest radiosonde upper data archive\n '''\n File \"./app/__init__.py\", line 1605, in storm_predict\n storm_predictions = bous.get_ts_predictions_stations(stations,sonde_data)\n File \"./utility_functions_sep2018.py\", line 3047, in get_ts_predictions_stations\n left = df.resample('D')[['AvID','Td','QNH','any_ts','AMP']].first(),\n ValueError: cannot reindex from a duplicate axis\n\n df.loc['2000-01-01':'2000-01-05'].between_time('00:00','00:30')\n can give more than one row for given date\n BUT if we resample to ('D') and rturn first() then gurantee only one row \n and likely 00Z as well\n df.loc['2000-01-01':'2000-01-05'].between_time('00:00','00:30').resample('D').first()\n '''\n '''\n df_temp = None\n if utc == 0:\n df_temp = df.between_time('23:45', '00:15').resample('D').first()\n print(\"Matching using 10am data\\n\", df[['T', 'Td', 'QNH']].between_time('23:45', '00:15').tail(5))\n if utc == 2:\n df_temp = df.between_time('01:45', '02:15').resample('D').first()\n print(\"Matching using 12pm data\\n\", df[['T', 'Td', 'QNH']].between_time('01:45', '02:15').tail(5))\n if utc == 4:\n df_temp = df.between_time('03:45', '04:15').resample('D').first()\n print(\"Matching using 2pm data\\n\", df[['T', 'Td', 'QNH']].between_time('03:45', '04:15').tail(5))\n df_temp = df_temp.loc[:df.index.date[-1]] # resample introduces days for rest of days in year!!\n # df_temp['fogflag'] = df_temp['fogflag'].astype(bool) # force to be boolean converts NaN to False\n # Now this would work to filter fog days only ==> df_temp[df_temp['fogflag']]\n '''\n # when we process all stations at once - assume match sought for 02Z/12pm 0bs\n # we may in future put a input for time n main page\n df_temp = df.between_time('01:45', '02:15').resample('D').first()\n aws_sonde_daily = pd.merge(\n # left = df.resample('D')[['AvID','Td','QNH','any_ts','AMP']].first(),\n left=df_temp[['AvID', 'WDir', 'WS', 'T', 'Td', 'QNH', 'any_ts', 'AMP']],\n right=sonde_data[['500_wdir', '500_WS', 'T500', 'tmp_rate850_500']],\n left_index=True, right_index=True, how='left') \\\n .rename(columns={'QNH': 'P', 'any_ts': 'TS', '500_wdir': 'wdir500', '500_WS': 'wspd500'})\n print(\"\\n\\nMerged Sonde/AWS data is:\\n\", \\\n aws_sonde_daily[['AvID', 'WDir', 'WS', 'T', 'Td', 'P','wdir500','wspd500']].tail(5))\n ''' get date input from main 'thunderstorm_predict.html' '''\n\n obs_4day = None\n\n if my_date:\n #If date supplied - get prediction for that day\n day = pd.to_datetime(my_date) #my_date is string like '2018-02-13'\n # get obs from station/sonde merged data for this date\n obs_4day = aws_sonde_daily.loc[my_date] #.T.squeeze()\n print(\"\\n\\nObservations for given date {} is \\n{}\"\\\n .format(day.strftime(\"%Y-%m-%d\"), obs_4day))\n else:\n #If no date supplied - get prediction for today\n day = pd.datetime.today()\n obs_4day = sonde2day # initialise todays obs with todays sonde\n #print(\"Radio sonde for {} :\\n{}\"\\\n # .format(day.strftime(\"%Y-%m-%d\"), obs_4day.to_frame()))\n try:\n '''Now we have already got todays sonde flight data,\n upper winds and temps and lapse rate info\n NEED to get station surface parameters from station obs'''\n\n wx_obs = get_wx_obs_www([station]).squeeze() #expects a list\n print(\"\\n\\nObservations for 00Z on {} for {} :\\n{}\"\\\n .format(day.strftime(\"%Y-%m-%d\"), station, wx_obs.to_frame()))\n # extra work if call like this\n # wx_obs = get_wx_obs_www(stations)\n # sta_ob = wx_obs[wx_obs['name'].str.contains(station)]\n\n # update surface parameters from station aws data\n obs_4day['P'] = wx_obs['P']\n obs_4day['T'] = wx_obs['T']\n obs_4day['Td'] = wx_obs['Td']\n obs_4day['wdir'] = wx_obs['wdir']\n obs_4day['wspd'] = wx_obs['wspd']\n\n\n # when sonde data manually entered - we set these manually\n if sonde_from_adams==0 :\n print(\"\\n\\nSonde flight from adams\", sonde_from_adams)\n obs_4day['T500'] = float(sonde2day['t500'])\n obs_4day['wdir500'] = float(sonde2day['wdir500'])\n obs_4day['wspd500'] = float(sonde2day['wspd500'])\n obs_4day['tmp_rate850_500'] = \\\n float(sonde2day['tmp_rate850_500'])\n else:\n print(\"\\n\\nSonde flight data from adams will be used\", sonde_from_adams)\n\n obs_4day['TS'] = None # we don't know if curr day had TS - silly!!\n\n logger.debug(\"Observations for today {} :\\n{}\"\\\n .format(day.strftime(\"%Y-%m-%d\"), obs_4day))\n except:\n print(\"\\n\\nResults.html Having trouble getting station data for today\\\n \\nTry predict TS using last obs in database\")\n # obs_4day = aws_sonde_daily.loc[aws_sonde_daily.iloc[-1].index]\n continue\n\n if obs_4day[['wdir500','wspd500','T500', 'P','Td','tmp_rate850_500']].isnull().any():\n print(\"Fix Missing parameters First\")\n\n ts_obs = obs_4day['TS'] #True class label for past dates\n num_days_synop = None\n search_window_obs = None\n synop_match_obs = None\n num_matches = None\n ts_day_cnt= None\n\n search_window_obs = \\\n grab_data_period_centered_day_sonde(aws_sonde_daily,42,day)\n\n try:\n num_days_synop = len(search_window_obs)\n except:\n print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\\n No data in season windows: VERY RARE EVENT HAS HAPPENED\")\n num_days_synop = 0\n\n\n mask,synop_match_obs,num_matches,ts_day_cnt = \\\n calculate_percent_chance_ts_sonde(search_window_obs, obs_4day)\n\n print(\"num_matches,ts_day_cnt\",num_matches,ts_day_cnt)\n\n if math.isnan(num_matches):\n proba = -1\n print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\\n No matching synop days found from {} historical days.\\\n \\nMust have very unusual conditions!!!\"\\\n .format(len(search_window_obs)))\n\n\n if math.isnan(ts_day_cnt):\n proba = -1\n print(\"No TS days found in matching synops.\"\\\n .format(len(search_window_obs)))\n\n\n if (ts_day_cnt > 0):\n num_matching_days = len(synop_match_obs)\n proba = ts_day_cnt*1.0/num_matching_days\n elif (ts_day_cnt == 0): # no matching day had storms\n print(\"no matching day had storms\")\n num_matching_days = len(synop_match_obs)\n proba = 0.0\n elif (ts_day_cnt == -1): # no matching days found - very unusual!!!!\n print(\"no matching days found - very unusual!!!!\")\n ts_day_cnt = 0\n num_matching_days = 0\n proba = -1\n '''\n if (proba == -1):\n y = \"thunderstorm prediction inconclusive\"\n elif (proba >= .30):\n y = \"thunderstorms almost certain\"\n elif (proba >= .10):\n y = \"thunderstorms likely\"\n elif (proba < .04):\n y = \"thunderstorms very unlikely\"\n else:\n y = 'thunderstorms possible - 4 to 9% chance'\n '''\n\n pred = 'POSSIBLE' if ((proba >= 0.04) & (proba <= 0.1)) else ('LIKELY' if proba >= 0.10 else 'NO CHANCE ')\n\n if my_date:\n predictions.append([station, my_date,num_days_synop,\n num_matching_days, ts_day_cnt,\n round(proba * 100, 2),pred, ts_obs==1.0])\n data = pd.DataFrame(predictions)\n data.columns = \\\n ['sta','date','synop_days','matches','ts_cnt','prob','pred','obs']\n else:\n predictions.append([station, day.strftime(\"%Y-%m-%d\"),num_days_synop,\n num_matching_days, ts_day_cnt,\n round(proba * 100, 2),pred])\n data = pd.DataFrame(predictions)\n data.columns = \\\n ['sta','date','synop_days','matches','ts_cnt','prob','pred']\n\n '''TS status will not be known for today!!!!'''\n return(data)\n\n\ndef get_fog_dates_adams(av_id = 'YBBN',get_dates_only=None):\n\n print(\"\\n\\nGetting fog days from ADAMS interface\\n\")\n\n conn = cx_Oracle.connect(user='anonymous', password='anonymous', dsn='adamprd')\n\n station = avid_adams[av_id] # get adams station number\n '''To update fog dates need to get it from ADAMs'''\n start_date = '1900-01-01'\n end_date = pd.datetime.today().strftime(\"%Y-%m-%d\")\n # station = 40842\n\n query = (\n \"SELECT TO_CHAR(LSD, 'yyyy-mm-dd') AS Day, count(distinct decode(fog_flag,'Y',lsd))\"\n \"FROM SFC_DAYS WHERE \"\n \"LSD > TO_DATE('{start}', 'yyyy-mm-dd') AND LSD <= TO_DATE('{end}', 'yyyy-mm-dd') \"\n \" AND STN_NUM={station}\"\n \"GROUP BY TO_CHAR(LSD, 'yyyy-mm-dd')\"\n ).format(\n start=start_date, end=end_date, station=station\n )\n\n df = sql.read_sql(query, conn, parse_dates=['DAY'], index_col='DAY')\n df.columns = ['fog_flag']\n df.sort_index(inplace=True, ascending=True)\n print(df.tail(20))\n\n # UTC fog date will be previous calender day\n fog_dates = df.index - pd.Timedelta('1 days')\n df.set_index(fog_dates, inplace=True)\n print(df.tail(20))\n\n # get only dates when had fog, so fog_flag is 1, 0 for no fog\n df = df.loc[df['fog_flag'] == 1]\n\n '''\n fog_data = pd.read_csv(\n open(os.path.join('app','data', 'fog_days_ybbn_since1980.csv'), 'rb'),\n parse_dates=['DAY'], index_col=['DAY'])\n\n # UTC fog date will be previous day\n fog_dates = fog_data.index - pd.Timedelta('1 days')\n fog_data.set_index(fog_dates,inplace=True)\n\n # get only dates when had fog\n fog_data = fog_data.loc[fog_data['fog_flag']==1]\n\n return (fog_data.index)'''\n\n return (df.index)\n\n# https://stackoverflow.com/questions/40632750/whats-the-difference-between-enum-and-namedtuple\n'''named tuples here are immutable sets - so the values for each of the tuple is\nset of dates e.g. common fog dates in two different methods, set of disjoint dates etc\nWe can look up these dates in original tcz files for closer look\n'''\nfrom collections import namedtuple\nvins_aut_vs_man = namedtuple(\n typename='vins_aut_vs_man',\n field_names='all_dates common_dates not_common auto_only man_only')\nvins_vs_rob = namedtuple(\n typename='vins_vs_rob',\n field_names='all_dates common_dates not_common vins_only robs_only')\n\n\n# https://stackoverflow.com/questions/27841823/enum-vs-string-as-a-parameter-in-a-function\n\nfrom enum import Enum\nclass compare_dates(Enum):\n auto_with_man = 1\n rob_with_vin = 2\n\n'''\nPython UDF User Defined FUnctions data type hints for arguments and return data types\nsee e-mail\n'''\ndef compare_fog_dates(station:str='YBBN',how=compare_dates) -> namedtuple:\n \"\"\"\n compare fog dates for same station from different source data sets\n performs various set algebra with found fog dates in the two data sources\n such as union/intersection/disjoint etc beween the set of fg_dates\n\n returns the various sets as a named tuple where each tuple value is a set of dates\n for given test - say dates common to both sets for set intersection\n\n Interesting that the manual and auto obs finds similar fog days\n set union = unique days from combined sets <-- associative\n set intersection - dates in common i.e in both sets <-- associative\n set of dates which are common to all/both sets.\n\n set symmetric_difference - dates which are not common to both sets (associative)\n dates which appear in either one of the sets - not in both or intersection\n is like ( set_a.union(set_b) ).intersection(set_b)\n\n The set difference of A and B is a set of dates that exists only in set A but not in B\n This is not --> associative A.difference(B) not same as B.difference(A)\n\n Two sets are said to be disjoint sets if they have no common elements\n No reason to test for this! `set_a.isdisjoint(set_b)`\n\n Set A is said to be the subset of set B if all elements of A are in B\n A.issubset(B)\n\n print(f'how = {how}, compare_dates={compare_dates}, ,compare_dates.auto_with_man={compare_dates.auto_with_man},compare_dates.rob_with_vin={compare_dates.rob_with_vin}')\n \"\"\"\n\n #if (how == compare_dates.auto_with_man):\n if (how.name=='auto_with_man'):\n fg_aut = get_fog_data_vins(station=station,auto_obs='Yep',get_dates_only=\"Yep\")\n fg_man = get_fog_data_vins(station=station,auto_obs=None, get_dates_only=\"Yep\")\n\n return vins_aut_vs_man(\n set(fg_aut).union(set(fg_man)),\n set(fg_aut).intersection(set(fg_man)),\n set(fg_aut).symmetric_difference(set(fg_man)),\n set(fg_aut).difference(set(fg_man)),\n set(fg_man).difference(set(fg_aut)))\n elif (how.name=='rob_with_vin'):\n # elif (how == compare_dates.rob_with_vin):\n # default case (how == compare_dates.rob_with_vin)\n fg_aut = get_fog_data_vins(station = station,auto_obs='Yep',get_dates_only=None)\n rob_dates = get_fog_data_robs_FCT(station=station,get_dates_only=\"Yep\")\n # align my fog dates (first and last only) with Robs\n aut_dates = fg_aut.loc[fg_aut['fogflag']].loc[rob_dates[0]:rob_dates[-1]].index.date\n\n return vins_vs_rob(\n set(aut_dates).union(set(rob_dates)),\n set(aut_dates).intersection(set(rob_dates)),\n set(aut_dates).symmetric_difference(set(rob_dates)),\n set(aut_dates).difference(set(rob_dates)),\n set(rob_dates).difference(set(aut_dates)))\n\n\ndef get_fog_data_robs_FCT(station:str = 'YBBN',get_dates_only=None) ->namedtuple:\n \"\"\"\n [Look up Roberts station fog summry files\n and get dates we had fog at the station. If get_dates_only is not None\n return the dates only, else return the fog data file]\n\n Keyword Arguments:\n station {str} -- [Aviation ID for station] (default: {'YBBN'})\n get_dates_only {[datetime]} -- [List of dates we had fog at Station] (default: {None})\n\n\n Returns:\n fg data {pandas dataframe} - if get_dates_only is None\n dates {datetime.date} - list of dates we had fog at station\n \"\"\"\n '''\n Now get fog info from Roberts QLD fog summary file\n We have option of generating these files on the fly as/if needed\n which would require calls to \"sys\" or \"subprocess\"\n\n Easiest fix for time being is have a script generate these files before hand\n in the app/data folder\n\n head -n 1 app/data/FogSummaryUnfiltered_QLD.csv > app/data/YBBN_fog_days_rob.csv\n awk -F',' 'BEGIN {IGNORECASE = 1} $2 ~ /ybbn/' app/data/FogSummaryUnfiltered_QLD.csv \\\n | awk -F',' 'BEGIN {IGNORECASE = 1} $6 ~ /rain/' >> app/data/YBBN_fog_days_rob.csv\n '''\n\n print('Getting fog data for '+station+' derived using ROBS FCT')\n df_fg = pd.read_csv(os.path.join('app','data', station+'_fog_days_rob.csv'), parse_dates=[2,6,7,8,9])\n\n '''To get only YBBN 900 winds at 06Z\n head -n 1 UpperWinds_QLD.csv > ybbn_900_winds_06Z.csv ; awk -F',' 'BEGIN {IGNORECASE = 1} $1 ~ /ybbn/' UpperWinds_QLD.csv | awk -F',' '$4 ~ /900/'\\\n | awk -F',' '$6 ~ /06:00:00/' >> ybbn_900_winds_06Z.csv\n\n df_winds = pd.read_csv(\n os.path.join('app','data', station+'_900_winds_06Z.csv',\n parse_dates=[5,10], index_col=[5] )\n '''\n # set fg onset dates as fog date\n # we dont need to correct fog dates as FG.onset date is UTC date on which 1st fog signal detected\n df_fg.index = df_fg['FG.onset'].dt.date # - pd.Timedelta(str(1) + ' days')\n #check #type(df_fg.index), type(df_fg.index[0])\n\n #df_fg.head(1)\n if get_dates_only:\n return df_fg.index\n else:\n return df_fg\n\ndef get_fog_data_vins(station:str='YBBN',auto_obs:str='Yes',get_dates_only:str=None)->pd.Index:\n \"\"\"\n [Look up Vins station fog summary files\n and get dates we had fog at the station. If get_dates is not None\n return the dates only, else return the fog data file]\n\n Keyword Arguments:\n station {str} -- [Aviation ID for station] (default: {'YBBN'})\n get_dates_only {[datetime]} -- [List of dates we had fog at Station] (default: {None})\n\n Returns:\n {pandas.DataFrame} - Dataframe if get_dates_only is None\n {pandas.Series} - pd.Index.date, list of dates we had fog at station\n\n \"\"\"\n # for fog stats derived using automatic observations data\n if auto_obs:\n fg = pd.read_csv(os.path.join('app','data', station+'2auto.csv'))\n print('Getting fog data for '+station+' derived using VINS auto obs matching')\n\n '''\n see perl script --> ./aws_format_v6.5_2020.pl\n if ( ($wind_SPD <= 10) && # to stop elevated spots like YTWB dropping fogs!!\n \t (($vis_obs <= 6)||($vis_aws <= 6)) && # ROB uses Vis<8km bigger NET!\n \t (($T-$Td) < 2) &&\n \t (($pptn10min < 0.1) && ($pptn_last < 0.1)) &&\n ((trim($aws_CL1A.$aws_CL1H) =~ /^(SCT|BKN|OVC)\\s*[1-2]00$/)) )# NB fogs missed if no cld near gnd\n '''\n else:\n fg = pd.read_csv(os.path.join('app','data', station+'2manual.csv'))\n print('Getting fog data for '+station+' derived using VINS manual obs matching')\n '''\n if ( (($PW =~ /4[0-9]/) ||\n \t (trim($PW1) =~ /(PR|BC|VC|BL|DR)\\s*FG/i) ||\n \t (trim($PW2) =~ /(PR|BC|VC|BL|DR)\\s*FG/i) ||\n \t ($PW =~ /10/))\n # && (trim($aws_CL1A.$aws_CL1H) =~ /^(SCT|BKN|OVC)\\s*[1-2]00$/)) # cld on gnd reqd condition\n && (($PW !~ /12/) && (trim($PW1) !~ /MI\\s*FG/i)) # make sure no MIST(10) or MIFG(12)\n && ($pptn10min < 0.1) # just sanity check - silly observer fog report rain 0.4mm 11/10/2019 20:00\n && (($T-$Td) < 2)\n && (($vis_obs < 10)||($vis_aws < 10))) #sanity check - observer saying fog 13/06/2014 00:30 vis>10km\n '''\n fg.index = pd.to_datetime(\n fg['year'].astype(str) + fg['mon'].astype(str).str.zfill(2)+ \\\n fg['day'].astype(str).str.zfill(2),format='%Y%m%d')\n\n fg.drop(['year', 'mon', 'day'], axis=1, inplace=bool(1)) # drop these for now\n # fg['fogflag'].values has spaces [' NO', ' YES', ' NO', ...] > fix BLW\n fg['fogflag']= fg['fogflag'].str.replace(' ', '')\n fg['fogflag']=np.where(fg[\"fogflag\"] == \"YES\", True, False) # make it boolean for easy filtering\n numeric_cols = ['rain24hr','min_vis', 'fg_onset', 'fg_finish','fg_duration',\\\n 'Td5', 'Td8', 'Td11', 'Td14','QNH5', 'QNH8', 'QNH11', 'QNH14']\n fg[numeric_cols] = fg[numeric_cols].apply(pd.to_numeric, errors='coerce')\n # fg['rain_flag'] = fg['rain24hr'] > 0.0 #same as below!\n fg['rain_flag'] = np.where(fg[\"rain24hr\"]>0.0, True, False)\n # fg['fogflag'].groupby(fg['rain_flag']).value_counts() # group data by rain/no rain days and fog outcomes in each set\n # fg['fogflag'].groupby(fg['rain_flag']).value_counts(normalize=True) # get relative frequencies for each group\n\n fg_dates = pd.to_datetime(fg[fg['fogflag']].index.date)\n # fg[fg['fogflag']].index.isin(fg_dates).sum() #should return 287 fog days for YBBN\n if get_dates_only: # default is None:\n return (fg_dates) # return only the fog dates for station\n else:\n return (fg) # return only actual fog stats dataframe\n\n\ndef get_climatological_fog_probability(station:str='YBBN',dates:[pd.datetime]=None,aws_sonde_daily=None):\n\n \"\"\"[summary]\n\n Args:\n station (str, optional): [description]. Defaults to 'YBBN'.\n dates ([type], optional): dates = pd.date_range(start='2019-06-03' , end='2019-06-10', freq='D')\n aws_sonde_daily ([type], optional): [description]. Defaults to None.\n \"\"\"\n stats = list()\n from collections import namedtuple\n matches = namedtuple(\n typename='matches',\n field_names='date num_of_fog_days num_of_days_match_synop_pattern')\n\n for date in dates:\n # date = date.strftime(\"%Y-%m-%d\") # no need!\n print(f'\\nProcessing date:{date}')\n win=None\n win=grab_data_period_centered_day_sonde(aws_sonde_daily,35,date)\n if win is None:\n print(\"Empty window grab_data_period_centered_day_sonde()\")\n next\n obs_4day = aws_sonde_daily.loc[date]\n # 'T','Td','900_wdir','900_WS','QNH'\n # if obs_4day.isnull().any()\n if (obs_4day.isnull()['T'] or obs_4day.isnull()['Td'] #or obs_4day.isnull()['lr_sfc_850']\n or obs_4day.isnull()['QNH'] or obs_4day.isnull()['900_wdir']\n or obs_4day.isnull()['900_WS']):\n print(\"Missing values for synop search parameters\")\n next\n # just match columns names expected in called function - silly\n obs_4day = obs_4day.rename({'900_wdir':'900Dir','900_WS':'900spd','QNH': 'P'})\n mask,matching_synops,num_of_days_match_synop_pattern,num_of_FG_days=\\\n calculate_percent_chance_fg_sonde(win,obs_4day)\n # print(f'num_of_FG_days={num_of_FG_days},num_of_days_match_synop_pattern={num_of_days_match_synop_pattern},chance={100*num_of_FG_days/num_of_days_match_synop_pattern}')\n #tmp = matches(date,num_of_FG_days,num_of_days_match_synop_pattern)\n stats.append(matches(date,num_of_FG_days,num_of_days_match_synop_pattern))\n return stats\n\n\n###################################################################\ndef get_fg_predictions_stations_new(stations,sonde2day=None,my_date=None):\n \"\"\"[summary]\n\n Arguments:\n stations {[list of strings]} -- [Stations/AviationIds for which TS predictionss are sought]\n\n Keyword Arguments:\n sonde2day {[pd.Series]} -- [Sounding data including 850 T/Td, 500 temps] (default: {None})\n my_date {[datetime]} -- [Date for which forecast is sough] (default: {None})\n \"\"\"\n\n day = pd.datetime.today()\n print(\"\\n\\nProcessing FOG prediction for station:{}\".format(stations))\n import math\n # cur_dir = os.path.dirname(__file__)\n\n # 1800Z data for airports - currently read from a csv file, index is airport ID like YBBN\n #['YBBN','YBAF','YAMB','YBSU','YBCG','YBOK','YTWB']:\n data_18Z = pd.read_csv(os.path.join('app','data', 'station_data_18Z.csv'), index_col=[1])\n predictions = []\n data = pd.DataFrame()\n\n # check set membership of stations - for brisbane stations load Brisbane sonde\n # Empty containers are \"false\" (so empty set would be null/false) as are numeric values equivalent to zero\n # you can emplicityl test empty set using if len(myset) <-- cardinality of the set\n if set(stations).intersection(set(['YBBN','YBAF','YAMB','YBSU','YBCG','YBOK','YTWB','YKRY'])):\n # load Brisbane sonde data file\n sonde_data = pickle.load( open(\n os.path.join('app','data','YBBN_sonde_2300_aws.pkl'), 'rb'))\n #os.path.join('app','data','sonde_hank_final.pkl'), 'rb'))\n #sonde_data = get_sounding_data('YBBN','2300')\n print(\"BEGIN PROCESSING TS FORECASTS FOR SEQ STATIONS\\n\",sonde_data.tail())\n elif set(stations).intersection(set(['YBRK','YGLA','YTNG','YBUD','YHBA','YMYB','YEML','YCMT','YMRB','YBMK','YBPN','YBHM'])):\n # load Rockhampton sonde data file\n sonde_data = pickle.load( open(\n os.path.join('app','data','YBRK_sonde_2300_aws.pkl'), 'rb'))\n #sonde_data = get_sounding_data('YBRK','2300')\n print(\"BEGIN PROCESSING TS FORECASTS FOR CAPRICORN/CENTRAL HIGHLANDN COAST\\n\",sonde_data.tail())\n elif set(stations).intersection(set(['YSSY','YSRI','YWLM','YSBK','YSCN','YSHW','YSHL'])):\n sonde_data = pickle.load( open(\n os.path.join('app','data','YSSY_sonde_0300_aws.pkl'), 'rb'))\n print(\"\\n\\n\\n\\nBEGIN PROCESSING TS FORECASTS FOR SYDNEY BASIN\\n\",sonde_data.tail())\n\n # sonde_data = sonde_data.loc[:,['900_wdir', '900_WS','lr_sfc_850']].rename(columns={'900_wdir':'direction','900_WS':'speed'})\n sonde_data['lr_sfc_850'] = sonde_data['sfc_T']-sonde_data['T850']\n\n # now do predictions for all stations\n for station in stations:\n print(\"\\n\\nProcessing FG prediction for station:{}\"\\\n .format(station))\n # get station aws archive data for station\n df = pickle.load(\n open(\n os.path.join('app','data', station+'_aws.pkl'), 'rb'))\n\n fg_aut=get_fog_data_vins(station=station,auto_obs='Yes')\n fg_dates = fg_aut.index.date\n sonde_data = pd.merge(left=sonde_data, right=fg_aut[['fogflag']],how='left',\\\n left_index=True,right_index=True)\n #fg_dates = get_fog_data_vins(station = station,get_dates_only='Yes')\n # add fog flag columm to station aws data file\n #if station == 'YBBN':\n # df.drop(['fogflag'], axis=1, inplace=bool(1))\n #df['date'] = df.index.date\n #df['fogflag'] = df['date'].isin(fg_dates)\n #print(stations, df['fogflag'].value_counts())\n\n # WE ONLY NEED TO MERGE THE 23Z WINDS ( 17Z flight woulf be better) WITH STATION DATA FILE\n\n # df_temp = df.loc[df.index.hour == 18] # filter out 18Z obs from stations AWS obs data b4 merging in\n # df_temp = df.loc[np.logical_and(df.index.hour == 6, df.index.minute == 0)]\n # df_temp = df_temp.resample('D').first() # gets only one 06XX UTC obs from each day\n df_temp = df.between_time('16:45','17:15').resample('D').first()\n df_temp = df_temp.loc[:df.index.date[-1]] # resample introduces days for rest of 2020!!\n # note the above keeps 'fogflag' as bool but introduces some NaN which can make filtering paninful\n # df_temp['fogflag'] = df_temp['fogflag'].astype(bool) # force to be boolean converts NaN to False\n # Now this would work to filter fog days only ==> df_temp[df_temp['fogflag']]\n\n aws_sonde_daily = pd.merge(\n left=df_temp[['AvID', 'T', 'Td', 'WS', 'WDir', 'QNH']], \\\n right=sonde_data[['900_wdir', '900_WS','lr_sfc_850','fogflag']], \\\n # right=df_winds[['Station', 'level','900_wdir','900_WS']],\\ #if using EC data file\n left_index=True, right_index=True, how='left')\n\n print(\"\\n\", aws_sonde_daily.tail(5))\n\n obs_4day = data_18Z.loc[station].copy() # get station 1800/4am data\n print(obs_4day)\n # need to spilt 900 winds into dir and speed\n # SFC T, TD, and QNH good to go - obs_4day['P'], obs_4day['T'], obs_4day['Td']\n obs_4day['900Dir'] = int(obs_4day['WIND_900'].split('/')[0])\n obs_4day['900spd'] = int(obs_4day['WIND_900'].split('/')[1])\n # obs_4day['lr_sfc_850'] = int(obs_4day['lr_sfc_850'])\n\n print(obs_4day)\n\n ''' GET 18Z OBS FROM WEB SCRAPPING - DOES NOT WORK atm!\n wx_obs = get_wx_obs_www([station],18).squeeze() # expects a list\n print(\"\\nObservations for 18Z on {} for {} :\\n{}\" \\\n .format(day.strftime(\"%Y-%m-%d\"), station, wx_obs))\n # extra work if call like this\n # wx_obs = get_wx_obs_www(stations)\n # sta_ob = wx_obs[wx_obs['name'].str.contains(station)]\n\n # update surface parameters from station aws data\n obs_4day['P'] = wx_obs['P']\n obs_4day['T'] = wx_obs['T']\n obs_4day['Td'] = wx_obs['Td']\n obs_4day['wdir'] = wx_obs['wdir']\n obs_4day['wspd'] = wx_obs['wspd']\n\n print(\"\\n18:00UTC obs from get_wx_obs\\n\", obs_4day)\n '''\n\n #fg_obs = obs_4day['FG'] #True class label for past dates\n num_days_synop = None\n search_window_obs = None\n synop_match_obs = None\n num_matches = None\n num_matching_days = None\n fg_day_cnt= None\n\n search_window_obs = \\\n grab_data_period_centered_day_sonde(aws_sonde_daily,35,day)\n\n try:\n num_days_synop = len(search_window_obs)\n except:\n print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\\n No data in season windows: VERY RARE EVENT HAS HAPPENED\")\n num_days_synop = 0\n\n\n mask,synop_match_obs,num_matches,fg_day_cnt = \\\n calculate_percent_chance_fg_sonde(search_window_obs.copy(), obs_4day)\n\n print(\"num_matches,fg_day_cnt\",num_matches,fg_day_cnt)\n\n if math.isnan(num_matches):\n proba = -1\n print(f'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\\n No matching synop days found from {len(search_window_obs)} historical days.\\\n \\nMust have very unusual conditions!!!')\n\n if math.isnan(fg_day_cnt):\n proba = -1\n print(f'No FG days found in {len(search_window_obs)} matching synops')\n\n if (fg_day_cnt > 0):\n num_matching_days = len(synop_match_obs)\n proba = fg_day_cnt*1.0/num_matching_days\n elif (fg_day_cnt == 0): # no matching day had storms\n print(\"no matching day had fog\")\n num_matching_days = len(synop_match_obs)\n proba = 0.0\n elif (fg_day_cnt == -1): # no matching days found - very unusual!!!!\n print(\"no matching days found - very unusual!!!!\")\n fg_day_cnt = 0\n num_matching_days = 0\n proba = -1\n\n if (proba == -1):\n pred = \"inconclusive\"\n elif (proba >= .20):\n pred = \"highly likely (PROB40 or ALT)\"\n elif (proba >= .10):\n pred = \"fog possible (PROB10 to PROB30)\"\n elif (proba >= .05):\n pred = \"slight chance fog (5% to 10% chance)\"\n else:\n pred = 'fog unlikely'\n\n #pred = True if proba >= 0.15 else False\n predictions.append([station, day.strftime(\"%Y-%m-%d\"),num_days_synop,\n num_matching_days, fg_day_cnt,\n round(proba * 100, 2),pred])\n data = pd.DataFrame(predictions)\n data.columns = \\\n ['sta','date','synop_days','matches','fog_cnt','prob','pred']\n\n return(data)\n\n\ndef get_fg_predictions_stations(stations,sonde2day=None,my_date=None):\n \"\"\"[summary]\n\n Arguments:\n stations {[list of strings]} -- [Stations/AviationIds for which TS predictionss are sought]\n\n Keyword Arguments:\n sonde2day {[pd.Series]} -- [Sounding data including 850 T/Td, 500 temps] (default: {None})\n my_date {[datetime]} -- [Date for which forecast is sough] (default: {None})\n \"\"\"\n\n day = pd.datetime.today()\n print(\"\\n\\nProcessing FOG prediction for station:{}\".format(stations))\n import math\n # cur_dir = os.path.dirname(__file__)\n\n # 1800Z data for airports - currently read from a csv file, index is airport ID like YBBN\n #['YBBN','YBAF','YAMB','YBSU','YBCG','YBOK','YTWB']:\n data_18Z = pd.read_csv(os.path.join('app','data', 'station_data_18Z.csv'), index_col=[1])\n\n predictions = []\n data = pd.DataFrame()\n\n # check set membership of stations - for brisbane stations load Brisbane sonde\n # Empty containers are \"false\" (so empty set would be null/false) as are numeric values equivalent to zero\n # you can emplicityl test empty set using if len(myset) <-- cardinality of the set\n if set(stations).intersection(set(['YBBN','YBAF','YAMB','YBSU','YBCG','YBOK','YTWB','YKRY'])):\n # load Brisbane sonde data file\n sonde_data = pickle.load( open(\n os.path.join('app','data','YBBN_sonde_2300_aws.pkl'), 'rb'))\n #os.path.join('app','data','sonde_hank_final.pkl'), 'rb'))\n #sonde_data = get_sounding_data('YBBN','2300')\n print(\"BEGIN PROCESSING TS FORECASTS FOR SEQ STATIONS\\n\",sonde_data.tail())\n elif set(stations).intersection(set(['YBRK','YGLA','YTNG','YBUD','YHBA','YMYB','YEML','YCMT','YMRB','YBMK','YBPN','YBHM'])):\n # load Rockhampton sonde data file\n sonde_data = pickle.load( open(\n os.path.join('app','data','YBRK_sonde_2300_aws.pkl'), 'rb'))\n #sonde_data = get_sounding_data('YBRK','2300')\n print(\"BEGIN PROCESSING TS FORECASTS FOR CAPRICORN/CENTRAL HIGHLANDN COAST\\n\",sonde_data.tail())\n elif set(stations).intersection(set(['YSSY','YSRI','YWLM','YSBK','YSCN','YSHW','YSHL'])):\n sonde_data = pickle.load( open(\n os.path.join('app','data','YSSY_sonde_0300_aws.pkl'), 'rb'))\n print(\"\\n\\n\\n\\nBEGIN PROCESSING TS FORECASTS FOR SYDNEY BASIN\\n\",sonde_data.tail())\n\n # The UTC date for sonde data is actually one less than the calendar data\n # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n # very dodgy - fix logic!!!\n # depends on sonding time 17/19/23Z versus 02Z,04Z,05Z etc\n sonde_data.set_index(sonde_data.index - pd.Timedelta(str(1) + ' days'),inplace=bool(1))\n sonde_data = sonde_data[['P900', 'wdir900', 'wspd900', 'P850', 'wdir850', 'wspd850']] #only grab these cols\n sonde_data.rename(columns={'wdir900': '900_wdir','wspd900':'900_WS',\\\n 'wdir850': '850_wdir','wspd850':'850_WS'}, inplace = True)\n\n sonde_data['lr_sfc_850'] = sonde_data['sfc_T']-sonde_data['T850']\n sonde_data = sonde_data[['lr_sfc_850','900_wdir','900_WS', 'T850','Td850','T700','Td700','T500','Td500']] #only grab these cols\n\n # now do predictions for all stations\n for station in stations:\n print(\"\\n\\nProcessing FG prediction for station:{}\"\\\n .format(station))\n # get station aws archive data for station\n df = pickle.load(\n open(\n os.path.join('app','data', station+'_aws.pkl'), 'rb'))\n\n fg_dates = get_fog_data_vins(station = station,get_dates_only='Yes')\n # fg = get_fog_data_vins(station=station, auto_obs='YES')\n # df['fogflag'] = df['date'].isin(fg_dates)\n # add fog flag columm to station aws data file\n #if station == 'YBBN':\n # df.drop(['fogflag'], axis=1, inplace=bool(1))\n\n snd = pd.merge(left=sonde_data, right=fg[['fogflag']], \\\n how='left', left_index=True, right_index=True)\n\n # WE ONLY NEED TO MERGE THE 23Z WINDS ( 17Z flight woulf be better) WITH STATION DATA FILE\n\n # df_temp = df.loc[df.index.hour == 18] # filter out 18Z obs from stations AWS obs data b4 merging in\n # df_temp = df.loc[np.logical_and(df.index.hour == 6, df.index.minute == 0)]\n # df_temp = df_temp.resample('D').first() # gets only one 06XX UTC obs from each day\n df_temp = df.between_time('07:45', '08:15').resample('D').first()\n df_temp = df_temp.loc[:df.index.date[-1]] # resample introduces days for rest of days in year!!\n # note the above keeps 'fogflag' as bool but introduces some NaN which can make filtering paninful\n # df_temp['fogflag'] = df_temp['fogflag'].astype(bool) # force to be boolean converts NaN to False\n # Now this would work to filter fog days only ==> df_temp[df_temp['fogflag']]\n\n aws_sonde_daily = pd.merge(\n left=df_temp[['AvID', 'T', 'Td', 'WS', 'WDir', 'QNH']], \\\n right=snd[['P900', '900_wdir', '900_WS', 'P850', '850_wdir', '850_WS','fogflag']], \\\n # right=df_winds[['Station', 'level','900_wdir','900_WS']],\\ #if using EC data file\n left_index=True, right_index=True, how='left')\n\n print(\"\\n\", aws_sonde_daily.tail(5))\n\n obs_4day = data_18Z.loc[station].copy() # get station 1800/4am data\n\n # need to spilt 900 winds into dir and speed\n # SFC T, TD, and QNH good to go - obs_4day['P'], obs_4day['T'], obs_4day['Td']\n obs_4day['900Dir'] = int(obs_4day['WIND_900'].split('/')[0])\n obs_4day['900spd'] = int(obs_4day['WIND_900'].split('/')[1])\n\n print(obs_4day)\n\n ''' GET 18Z OBS FROM WEB SCRAPPING - DOES NOT WORK atm!\n wx_obs = get_wx_obs_www([station],18).squeeze() # expects a list\n print(\"\\nObservations for 18Z on {} for {} :\\n{}\" \\\n .format(day.strftime(\"%Y-%m-%d\"), station, wx_obs))\n # extra work if call like this\n # wx_obs = get_wx_obs_www(stations)\n # sta_ob = wx_obs[wx_obs['name'].str.contains(station)]\n\n # update surface parameters from station aws data\n obs_4day['P'] = wx_obs['P']\n obs_4day['T'] = wx_obs['T']\n obs_4day['Td'] = wx_obs['Td']\n obs_4day['wdir'] = wx_obs['wdir']\n obs_4day['wspd'] = wx_obs['wspd']\n\n print(\"\\n18:00UTC obs from get_wx_obs\\n\", obs_4day)\n '''\n\n #fg_obs = obs_4day['FG'] #True class label for past dates\n num_days_synop = None\n search_window_obs = None\n synop_match_obs = None\n num_matches = None\n num_matching_days = None\n fg_day_cnt= None\n\n search_window_obs = \\\n grab_data_period_centered_day_sonde(aws_sonde_daily,28,day)\n\n try:\n num_days_synop = len(search_window_obs)\n except:\n print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\\n No data in season windows: VERY RARE EVENT HAS HAPPENED\")\n num_days_synop = 0\n\n\n mask,synop_match_obs,num_matches,fg_day_cnt = \\\n calculate_percent_chance_fg_sonde(search_window_obs, obs_4day)\n\n print(\"num_matches,fg_day_cnt\",num_matches,fg_day_cnt)\n\n if math.isnan(num_matches):\n proba = -1\n print(f'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\\n No matching synop days found from {len(search_window_obs)} historical days.\\\n \\nMust have very unusual conditions!!!')\n\n if math.isnan(fg_day_cnt):\n proba = -1\n print(f'No FG days found in {len(search_window_obs)} matching synops')\n\n if (fg_day_cnt > 0):\n num_matching_days = len(synop_match_obs)\n proba = fg_day_cnt*1.0/num_matching_days\n elif (fg_day_cnt == 0): # no matching day had storms\n print(\"no matching day had fog\")\n num_matching_days = len(synop_match_obs)\n proba = 0.0\n elif (fg_day_cnt == -1): # no matching days found - very unusual!!!!\n print(\"no matching days found - very unusual!!!!\")\n fg_day_cnt = 0\n num_matching_days = 0\n proba = -1\n\n if (proba == -1):\n pred = \"inconclusive\"\n elif (proba >= .20):\n pred = \"highly likely\"\n elif (proba >= .10):\n pred = \"fog possible\"\n elif (proba >= .05):\n pred = \"chance fog\"\n else:\n pred = 'fog very unlikely'\n\n # pred = True if proba >= 0.15 else False\n predictions.append([station, day.strftime(\"%Y-%m-%d\"),num_days_synop,\n num_matching_days, fg_day_cnt,\n round(proba * 100, 2),pred])\n data = pd.DataFrame(predictions)\n data.columns = \\\n ['sta','date','synop_days','matches','fog_cnt','prob','pred']\n\n return(data)\n\n\n\ndef wind_quadrants(x):\n \"\"\"\n Split winds into Quadrants\n Usage:\n df_new['wdir900_sector'] = df_new['900_wdir'].apply(wind_quadrants)\n\n :param x: wind direction series or values\n :return: quadrant direction\n \"\"\"\n if ((x >= 0) & (x < 90)):\n return 'NE'\n elif ((x >= 90) & (x < 180)):\n return 'SE'\n elif ((x >= 180) & (x < 270)):\n return 'SW'\n elif ((x >= 270) & (x < 360)):\n return 'NW'\n else:\n return (np.NaN)\n\n'''\nSplit winds into N/S or E/W semicircles\n'''\n\ndef wind_semis_NS(x):\n if ((x < 90) | (x > 275)):\n return 'Nly'\n else:\n return 'Sly'\n\ndef wind_semis_EW(x):\n if ((x >= 0) & (x <= 180)):\n return 'Ely'\n else:\n return 'Wly'\n\n\n'''\ndef classify(document):\n label = {0: 'negative', 1: 'positive'}\n X = vect.transform([document])\n y = clf.predict(X)[0]\n proba = np.max(clf.predict_proba(X))\n return label[y], proba\n\n#The train function can be used to update the classifier given that a document and a class label\nare provided.\n\ndef train(document, y):\n X = vect.transform([document])\n clf.partial_fit(X, [y])\n\n\n@app.route('/results', methods=['POST'])\ndef results():\n form = ReviewForm(request.form)\n if request.method == 'POST' and form.validate():\n review = request.form['moviereview']\n y, proba = classify(review)\n return render_template('results.html',\n content=review,\n prediction=y,\n probability=round(proba*100, 2))\n return render_template('reviewform.html', form=form)\n\n\ndef get_knn_predictions(obs_4day):\n\n\n ######## Preparing the Classifier\n cur_dir = os.path.dirname(__file__)\n clf = pickle.load(open(os.path.join(cur_dir,\n 'pkl_objects',\n 'classifier.pkl'), 'rb'))\n db = os.path.join(cur_dir, 'reviews.sqlite')\n\n #Define a classify function to return the predicted class label as well\n as the corresponding probability prediction of a given text document.\n\n\n\n #import as pkl object previously trained KNN model\n knn = KNeighborsClassifier(n_neighbors=15)\n knn.fit(X_train, y_train)\n\n Now and make prediction using this classifier\n\n print(\"Obs for day\\n\",obs_4day)\n cols = ['P','T', 'Td', 'wdir', 'wspd', 'T850', 'Td850',\n 'wdir850', 'wspd850', 'T500', 'Td500', 'wdir500',\n 'wspd500', 'tmp_rate850_500', 'day']\n obs_today = obs_4day[cols]\n print(\"Obs for prediction with KNN\", obs_today)\n X = np.array(obs_today).reshape(1, -1)\n print(\"Input sample to KNN classifier\", X)\n print(\"Prediction by KNN classifier is ---> \", knn.predict(X)[0])\n'''\n\n\n\n'''\nfind all dates where we had a positive match\nthen check whether the TS identification for given\ndays was based on gpats or aws data\nalso pick up onset, duration, end times for TS that day\n'''\n\n# find all dates where we had a positive match\n# then check whether the TS identification for given\n# days was based on gpats or aws data\n# also pick up onset, duration, end times for TS that day\n\n# matched_ts_dates = duf[duf['any_ts']].index\n'''DatetimeIndex(['2014-01-03', '2017-01-21'], dtype='datetime64[ns]', freq=None)'''\n\n'''If we use 'date' series to process '''\n# matched_ts_dates = duf.loc[duf['any_ts'],'date'].dt.strftime(\"%Y-%m-%d\")\n# print(matched_ts_dates)\n'''2014-01-03 2014-01-03\n 2017-01-21 2017-01-21\nName: date, dtype: object'''''\n\n# print(duf[duf['any_ts']].index.strftime(\"%Y-%m-%d\"))\n'''array(['2014-01-03','2017-01-21'],\n dtype='\\n\";\n\necho 'Shears
    (kts)';\n\nforeach ($wind_shear_levels as $wind_shear_level) {\n $speed1 = $wind_array['wind'][$wind_shear_level[0]][1];\n $speed2 = $wind_array['wind'][$wind_shear_level[1]][1];\n $dir1 = $wind_array['wind'][$wind_shear_level[0]][0];\n $dir2 = $wind_array['wind'][$wind_shear_level[1]][0];\n\n if($dir1 > $dir2) {\n $dir = $dir1 - $dir2;\n } else {\n $dir = $dir2 - $dir1;\n }\n\n $dir = $dir * 0.017453292519943295769236907684886; // in radians\n\n $shear = sqrt(($speed1*$speed1) + ($speed2*$speed2) - 2*($speed1)*($speed2)*cos($dir));\n $round_shear = round($shear);\n\n echo ''.$wind_shear_level[0].'-'.$wind_shear_level[1].''.$round_shear.''.\"\\n\";\n\n}\n\n$lapse_rate_levels = array(\n array(850,500),\n array(700,500)\n );\n\necho 'Lapse Rates
    (°C/km)';\nforeach ($lapse_rate_levels as $lapse_rate_level) {\n $temp1 = $temp_array[$lapse_rate_level[0]]['temp'];\n $temp2 = $temp_array[$lapse_rate_level[1]]['temp'];\n $height1 = $temp_array[$lapse_rate_level[0]]['height'];\n $height2 = $temp_array[$lapse_rate_level[1]]['height'];\n $lapse_rate = ($temp1 - $temp2)/($height2 - $height1)*1000;\n\n echo ''.$lapse_rate_level[0].'-'.$lapse_rate_level[1].''.number_format($lapse_rate,1).''.\"\\n\";\n}\n\n\nforeach ($feet_array as $feet) {\n $fzl_array[] = array($feet[1],$feet[3]);\n}\nif (is_numeric($fzl_array[2][1])) {\n\n echo 'Heights
    (ft)';\n $fzl = findTempLvl($fzl_array,0);\n $fzl = round($fzl,-2);\n $negtw = findTempLvl($fzl_array,-20);\n $negtw = round($negtw,-2);\n echo 'FZL'.round($fzl,-2).''.\"\\n\";\n echo '-20°C'.round($negtw,-2).''.\"\\n\";\n}\n\necho '';\n'''\n\n\n# convert compass direction to corresponding degrees\n# see http://codegolf.stackexchange.com/questions/54755/convert-a-point-of-the-compass-to-degrees\ndef f(s):\n if 'W'in s:\n s = s.replace('N','n')\n a=(len(s)-2)/8\n if 'b' in s:\n a = 1/8 if len(s)==3 else 1/4\n return (1-a)*f(s[:-2])+a*f(s[-1])\n else:\n if len(s)==1:\n return 'NESWn'.find(s)*90\n else:\n return (f(s[0])+f(s[1:]))/2\n\n\n'''\nend_date = datetime.now() #2017-04-04 13:56:54.789208\nstart_date = end_date - relativedelta(months=13)\ndate_range = pd.date_range(start_date, end_date, freq='M',closed=None)\n'''\n## explore http://pandas.pydata.org/pandas-docs/stable/timedeltas.html\n## to fix not able to get correct month range\n## https://chrisalbon.com/python/pandas_time_series_basics.html\n\n## Python string formatters --> https://pyformat.info/\n## http://www.diveintopython.net/native_data_types/formatting_strings.html\n\n#print ('Number of arguments:', len(sys.argv), 'arguments.')\n#print ('Argument List:', str(sys.argv))\n#location = sys.argv[1]\n#print('Weather forecasts for {}'.format(location.upper()))\n\n\ndef get_avlocs():\n import pandas as pd\n import os\n\n # \"LOC_ID\" \"Location\" \"Lat\"\t\"Long\" \"Elevation_ft\" \"Elevation\" \"HAM_Cld_ft\" \"HAM_Vis_m\" \"SAM_Cld_ft\" \"SAM_Vis_ft\" \"State\"\n\n print( \"Current directory from get_avlocs() in utility_fucntions_sept2018 is\", os.getcwd())\n # Current directory from get_avlocs() in utility_fucntions_sept2018 is . and pwd is /mnt/win_data/shared/stats-R/flask_projects/avguide\n\n minima_path = os.path.join('app', 'static', 'minima_new.xls')\n # minima_path = os.path.join('static', 'minima_new.xls')\n with open(minima_path, 'rb') as m:\n locs = pd.read_excel(m, usecols=list(range(11)), header=0, index_col=0) #nrows=313, skiprows=list(range(10)))\n\n\n # ensure numeric data is forced to be numeric\n for col in ['Lat', 'Long', 'Elevation_ft', 'HAM_Cld_ft', 'HAM_Vis_m', \\\n 'SAM_Cld_ft', 'SAM_Vis_m']:\n locs[col] = pd.to_numeric(locs[col], downcast='integer', errors='coerce')\n\n # 'AREA' shud be an int not float, NaN is compatible with float but no int\n # columns in minima.xls can't be missing - drop rows with NaNs in these cols\n # else Raises ValueError: ('cannot convert float NaN to integer')\n locs.dropna(subset=['State', 'Location', 'HAM_Cld_ft', 'HAM_Vis_m'], inplace=True)\n\n # leave area as str as http://127.0.0.1:5000/api/v1/resources/tafors?area=40 fails!!\n # locs['AREA'] = locs['AREA'].astype(int)\n # locs['AREA'] = locs['AREA'].apply(lambda x: int(x) if x == x else np.NaN)\n\n decimals = pd.Series([4, 4], index=['Lat', 'Long']) # lat/long to 4 dec plc\n locs = locs.round(decimals)\n\n # force convert text data to string\n cols_str = ['Location', 'Elevation', 'State']\n locs[cols_str] = locs[cols_str].astype(str)\n\n\n '''get PCA locs in diff states from pca file at web.bom.gov.au\n http://web.bom.gov.au/spb/adpo/aviation/LocationDatabase/pca.txt\n fixed width col format - so have to give width of each col, skips 1st and 3rd row\n only grab 1ST 2 COLS usecols=[0,1]\n \"LOC_ID\" \"AREA\" \"LOCATION_NAME\" \"Lat\" \"Long\" \"Type\" \"Reg\" \"State\"'''\n pca_path = os.path.join('app','static', 'pca.txt')\n # pca_path = os.path.join('static', 'pca.txt')\n with open(pca_path, 'r') as p:\n pca = pd.read_fwf(p, widths=[7,5,33,10,11,5,4,5], skiprows=[0,2], usecols=[0,1], index_col=0)\n\n minima = locs#.reset_index()\n '''merge the two data sets into one dataframe\n https://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.read_fwf.html\n left join ensures we keep all airport minima info\n and supplment these with extra info from pca database, lat, long etc'''\n locs = pd.merge(left=minima, right=pca, left_index=True, right_index=True, how='left')\n\n\n # 'AREA' shud be an int not float, NaN is compatible with float but no int\n # columns in minima.xls can't be missing - drop rows with NaNs in these cols\n # else Raises ValueError: ('cannot convert float NaN to integer')\n # ValueError: cannot index with vector containing NA / NaN values\n locs.dropna(subset=['State','Location','HAM_Cld_ft', 'HAM_Vis_m','AREA'],inplace=True)\n\n # leave area as str as http://127.0.0.1:5000/api/v1/resources/tafors?area=40 fails!!\n # locs['AREA'] = locs['AREA'].astype(int)\n # locs['AREA'] = locs['AREA'].apply(lambda x: int(x) if x == x else np.NaN)\n\n # (x,y) coord system x is longitude , y is latitude\n\n return locs\n\ndef get_avlocs_old():\n\n import pandas as pd\n import os\n\n '''get TAF codes for airports in diff states from minima file at web.bom.gov.au\n http://web.bom.gov.au/spb/adpo/aviation/LocationDatabase/minima.xls\n \"state\" \"Location\" \"Ident\" \"HAM (cld (ft))\" \"HAM (vis (m))\"\n \"SAM (cld (ft))\" \"SAM (vis (m))\" \"MSA (ft)\" '''\n minima_path = os.path.join(cur_dir,'static', 'minima.xls')\n with open(minima_path, 'rb') as m:\n minima = pd.read_excel(m, usecols=list(range(8)), skiprows=list(range(10)))\n\n '''get PCA locs in diff states from pca file at web.bom.gov.au\n http://web.bom.gov.au/spb/adpo/aviation/LocationDatabase/pca.txt\n fixed width col format - so have to give width of each col, skips 1st and 3rd row\n \"LOC_ID\" \"AREA\" \"LOCATION_NAME\" \"Lat\" \"Long\" \"Type\" \"Reg\" \"State\"'''\n pca_path = os.path.join(cur_dir,'static', 'pca.txt')\n with open(pca_path, 'r') as p:\n pca = pd.read_fwf(p, widths=[7,5,33,10,11,5,4,5], skiprows=[0,2])\n\n\n '''merge the two data sets into one dataframe\n left join ensures we keep all airport minima info\n and supplment these with extra info from pca database, lat, long etc'''\n locs = pd.merge(left=minima, right=pca, left_on='Ident', right_on='LOC_ID', how='left')\\\n .drop(['state','Ident','LOCATION_NAME'], axis=1)\\\n [['LOC_ID', 'AREA', 'Lat', 'Long', 'Type','Reg', 'State',\\\n 'Location','HAM (cld (ft))', 'HAM (vis (m))', \\\n 'SAM (cld (ft))','SAM (vis (m))', ' MSA (ft)']]\\\n .set_index('LOC_ID')\n\n cols_flt = ['Lat', 'Long','HAM (cld (ft))', 'HAM (vis (m))', \\\n 'SAM (cld (ft))','SAM (vis (m))', ' MSA (ft)']\n\n # ensure numeric data is forced to be numeric\n for col in ['Lat', 'Long', 'HAM (cld (ft))', 'HAM (vis (m))', \\\n 'SAM (cld (ft))','SAM (vis (m))', ' MSA (ft)']:\n locs[col] = pd.to_numeric(locs[col], downcast='integer',errors='coerce')\n\n # 'AREA' shud be an int not float, NaN is compatible with float but no int\n # columns in minima.xls can't be missing - drop rows with NaNs in these cols\n # else Raises ValueError: ('cannot convert float NaN to integer')\n locs.dropna(subset=['State','Location','HAM (cld (ft))', 'HAM (vis (m))'],inplace=True)\n\n # leave area as str as http://127.0.0.1:5000/api/v1/resources/tafors?area=40 fails!!\n # locs['AREA'] = locs['AREA'].astype(int)\n # locs['AREA'] = locs['AREA'].apply(lambda x: int(x) if x == x else np.NaN)\n\n decimals = pd.Series([4,4],index=['Lat', 'Long']) # lat/long to 4 dec plc\n locs = locs.round(decimals)\n\n # force convert text data to string\n cols_str = ['AREA','Location', 'Type', 'Reg', 'State']\n locs[cols_str] = locs[cols_str].astype(str)\n\n # (x,y) coord system x is longitude , y is latitude\n # shorten longer names\n locs.rename(columns= {\n 'HAM (cld (ft))':'HAM_cld_ft', 'HAM (vis (m))':'HAM_vis_m', \\\n 'SAM (cld (ft))':'SAM_cld_ft','SAM (vis (m))':'SAM_vis_m', ' MSA (ft)':'MSA'}, inplace=True)\n\n return locs\n\n\ndef get_wx_obs_www(stations, hist=''):\n stations_all = [] # list to store each station as they are created\n #['YAMB','YBBN','YBAF','YBSU','YBCG','YTWB','YBOK']\n print(stations)\n area = \"SE QLD\"\n for airport in stations:\n\n # avid_wmo_dict = {'YBBN':94578,'YBAF':94575,....}\n # avid to climate station numbers\n station = avid_wmo_dict[airport]\n if airport in nt:\n url = \"http://www.bom.gov.au/fwo/IDD60801/IDD60801.{}.json\".format(station)\n if airport in wa:\n url = \"http://www.bom.gov.au/fwo/IDW60801/IDW60801.{}.json\".format(station)\n if airport in nsw:\n url = \"http://www.bom.gov.au/fwo/IDN60901/IDN60901.{}.json\".format(station)\n if airport=='YSHL':\n url = \"http://www.bom.gov.au/fwo/IDN60701/IDN60701.{}.json\".format(station)\n if airport in vic :\n url = \"http://www.bom.gov.au/fwo/IDV60901/IDV60901.{}.json\".format(station)\n if airport in sa:\n url = \"http://www.bom.gov.au/fwo/IDS60901/IDS60901.{}.json\".format(station)\n if airport in qld:\n url = \"http://www.bom.gov.au/fwo/IDQ60801/IDQ60801.{}.json\".format(station)\n\n\n print (\"Fetching {} observations from {}\".format(airport,url))\n obs_response = requests.get(url)\n obs_json = json.loads(obs_response.text)\n stations_all.\\\n append( \\\n pd.DataFrame( obs_json['observations']['data'], \\\n columns = ['sort_order' , 'wmo', 'name', 'history_product', \\\n 'local_date_time', 'local_date_time_full', 'aifstime_utc', \\\n 'lat', 'lon', 'apparent_t', 'cloud', 'cloud_base_m', 'cloud_oktas', \\\n 'cloud_type', 'cloud_type_id', 'delta_t', 'gust_kmh', 'gust_kt', 'air_temp', 'dewpt', \\\n 'press', 'press_msl', 'press_qnh', 'press_tend', 'rain_trace', 'rel_hum',\\\n 'sea_state', 'swell_dir_worded', 'swell_height', 'swell_period', \\\n 'vis_km', 'weather', 'wind_dir', 'wind_spd_kmh', 'wind_spd_kt']))\n\n df = pd.concat(stations_all) # join all the stations together\n list_to_drop = ['sort_order' , 'history_product', 'local_date_time', 'local_date_time_full','lat', 'lon', 'apparent_t',\\\n 'cloud_type', 'cloud_type_id', 'delta_t', 'gust_kmh', 'press', 'press_msl', 'press_tend',\\\n 'sea_state', 'swell_dir_worded', 'swell_height', 'swell_period', 'wind_spd_kmh']\n\n df.drop( list_to_drop, axis='columns',inplace=True)\n\n # U can also drop by column int positions\n # cols_drop = [0,3,4,5,7,8,9,13,14,15,16,20,21,23,26,27,28,29,33]\n # df.drop(df.columns[cols_drop],axis=1,inplace=True)\n\n # abbreviate some of the longer column names .e.g 'air_temp' -> 'T', 'dewpt'->'Td' etc\n df.rename( columns= {'name':'av_id','cloud_base_m': 'cld_base', 'cloud_oktas': 'cld_okta', 'gust_kt':'gust',\\\n 'air_temp':'T', 'dewpt':'Td','press_qnh':'QNH', 'rel_hum':'RH',\\\n 'vis_km':'vis', 'wind_dir':'dir', 'wind_spd_kt':'spd'}, inplace=True)\n\n # df.sort_values(by='aifstime_utc', ascending=True,inplace=True)\n # we postpone this to after set_index\n\n for col in ['QNH','T', 'Td','spd','gust', 'RH','vis']:\n df[col] = pd.to_numeric(df[col], errors='coerce')\n\n # convert text data to string\n # df[cols_str] = df[cols_str].astype(str)\n\n # Convert df['aifstime_utc'] from string to datetime\n df['date'] = pd.to_datetime(df['aifstime_utc'])\n\n # Set df['date'] as the index and delete the column\n df.set_index(keys='date', drop=True, inplace=True)\n # localise UTC time to local time\n # df['date'] = df['date'].dt.tz_localize('UTC').dt.tz_convert('Australia/Brisbane')\n\n '''drop 'date' column at same time\n also need to drop column 'aifstime_utc'\n df.drop(['date', 'aifstime_utc'], axis=1, inplace=True) '''\n\n df.drop(['aifstime_utc'], axis=1, inplace=True)\n df.sort_index(axis=0,ascending=True,inplace=True) #sort index ascending\n\n\n df.cld_base = df.cld_base * 3.28084 #convert cloud base m to ft\n #df['dir'] = df['dir'].apply(f)\n\n cols_display = ['av_id','QNH','T', 'Td','dir','spd','gust', 'RH','vis']#,'cld_okta','cld_base']\n df = df[cols_display]\n\n # TypeError: Empty 'DataFrame': no numeric data to plot, when plotting\n # columns had values 'None' , if convert to NaN, plot() won't complain!!\n\n # df.isnull() --> True for many columns with values 'None'\n # for some reason these None values are not treated same as NaN\n # so replace python None with pandas NaN\n\n df.fillna(value=np.nan, inplace=True)\n\n # fix wind direction\n # df['dir'] = df['dir'].apply(f)\n\n # change station names to av IDs\n\n if (area == \"SE QLD\"):\n name_dict = {'Amberley':'YAMB', 'Archerfield':'YBAF',\n 'Brisbane Airport':'YBBN' , 'Coolangatta':'YBCG',\n 'Oakey':'YBOK' ,'Sunshine Coast Airport':'YBSU',\n 'Toowoomba':'YTWB', 'Charleville':'YBCV','Roma':'YROM',\n 'St George':'YSGE', 'Thargomindah':'YTGM','Ballera':'YLLE',\n 'Windorah':'YWDH','Birdsville':'YBDV'}\n df['av_id'] = df['av_id'].map(name_dict)\n\n\n df_hist = df\n df_today = pd.DataFrame()\n\n # dump csv to \"/tmp/area40_observations.csv\"\n # df.to_csv(\"/tmp/Oct17_2017_area40_observations.csv\", sep=',', header=True, index=True)\n\n # get todays observations - now since we use UTC time today starts from 00UTC/10am\n # try first to avoid KeyError: 'the label [2018-06-23] is not in the [index]'\n # after 14UTC, local today is day+1, so get yesterdays 00Z in that case\n\n try:\n df_today = df.loc[datetime.today().strftime('%Y-%m-%d'), cols_display]\n print(\"Todays ({}) obs for {}:\\n{}\"\\\n .format(datetime.today().strftime('%Y-%m-%d'),area, df_today.between_time('0:0', '1:0')))\n # df.iloc[np.lexsort((df.index, df.A.values))] # Sort by A.values, then by index\n # when we print(df_today.index) the indices still contain full datetime\n # we only wud like the 00Z obs\n except:\n yesterday = datetime.today() - relativedelta(days=1)\n df_today = df.loc[yesterday.strftime('%Y-%m-%d'), cols_display]\n print(\"Yesterdays ({}) obs for {}:\\n{}\" \\\n .format(yesterday.strftime('%Y-%m-%d'), area, df_today.between_time('0:0', '1:0')))\n '''We get times that are not between two times by setting start_time later than end_time\n This effectively drops all obs 01Z till 23Z\n date name QNH T Td dir spd RH vis\n 2018-06-22 00:00:00 YBBN 1026.9 17.8 8.9 SSW 9 56 10\n 2018-06-22 00:30:00 YBBN 1026.9 18.9 9.1 SSW 9 53 10\n 2018-06-22 01:00:00 YBBN 1026.6 20.2 9.2 S 8 49 10\n 2018-06-22 23:00:00 YBBN 1026.2 14.9 8.5 SSW 11 65 40\n 2018-06-22 23:30:00 YBBN 1026.2 15.4 8.2 SSW 13 62 10\n '''\n\n if hist:\n df_10am = df_hist\n else:\n df_10am = \\\n df_today.loc[\n np.logical_and(\n df_today.index.hour == 0,\n df_today.index.minute == 0)]\n\n # df_10am = df_today.loc[df_today.index.hour == 0,cols_display]\n # df_10am = df_10am.sort_values(by=['av_id'], ascending=[True])\n # print(\"Row with duplicate av IDs\", df_10am['name'].duplicated().sum())\n # print(df_10am['name'].duplicated())\n # drop duplicates\n df_10am = df_10am.loc[~df_10am['av_id'].duplicated(keep='first'), :]\n # see https://www.ritchieng.com/pandas-removing-duplicate-rows/\n # pandas.DataFrame.drop_duplicates has issues !!!!\n # df_10am.drop_duplicates(subset='Name', keep='first',inplace=True)\n\n df_10am.columns = ['av_id', 'P', 'T', 'Td', 'wdir', 'wspd', 'gust', 'RH', 'vis']\n print (\"Fetched {} observations\".format(airport))\n print(df_10am.tail())\n\n return (df_10am.sort_index(axis=0))\n\n\n\ndef get_airport_metar_speci(avid):\n\n \"\"\"\n Grab METARAWS file for given aviation location and find and SPECIS\n \"\"\"\n # now get any SPECIS\n '''\n metar_url = (\n 'http://aifs-qld.bom.gov.au/cgi-bin/uncgi-bin/metar_hist/?{}').format(avid)\n metar_response = requests.get(metar_url) '''\n\n # now get any SPECIS using WMO ids from\n # Problem with these is that obs that are SPECIS are not tagged with 'SPECI' keyword\n # Brets perl code was removing SPECI, METAR from AWS data, he has allowed that to report now - so good to use\n\n metar_url = 'http://aifs-qld.bom.gov.au/cgi-bin/local/qld/rfc/bin/metar_disp.pl'\n payload = {'WMO': avid_wmo_dict[avid]}\n metar_response = requests.get(metar_url, params=payload)\n\n print (metar_response.url) #check if url formed correctly\n\n #metar_url ='http://aifs-qld.bom.gov.au/cgi-bin/local/qld/rfc/bin/metar_disp.pl?WMO={}'\\\n # .format(avid_wmo_dict[avid])\n #metar_response = requests.get(metar_url)\n\n print (metar_response.status_code)\n if (metar_response.status_code == requests.codes.ok):\n print (\"Found file resource\")\n print (metar_response.headers.get('content-type'),\"\\n\")\n\n # print(metar_response.text) will prints entire file\n\n # save response file so we can search it later for SPECIS\n with open('/tmp/metadata.txt', 'wb') as f:\n f.write(metar_response.content)\n\n f = open('/tmp/metadata.txt', 'r')\n\n # no matches will simply return an empty list\n matches = re.findall(r'SPECIAWS', metar_response.text)\n # http://www.pitt.edu/~naraehan/python3/re.html\n\n # replace all ` ` with 1 space\n\n if (len(matches) > 0):\n print (\"\\n\\nSpecis for {}\".format(avid), \"\\n#################\")\n # now step through each metar and print out if its SPECI\n for line in f:\n if 'SPECIAWS' in line:\n print (cleanhtml(line.replace(' ',' ')))\n #if (avid == 'YBHM'): # special case YBHM - print 2nd line as well\n # print (next(f)) # as 1st line only upto RMK\n else:\n print(\"No specis for {}\".format(avid), \"\\n------------------\")\n\n'''\n end_date = datetime.now() #2017-04-04 13:56:54.789208\n start_date = end_date - relativedelta(days=2)\n #date_range = pd.date_range(start_date, end_date, freq='M',closed=None)\n\n\n # we try 3 differrent ways to call the plot method\n # plot() by default uses the dataframe index for x-axis, hence no x= ...\n df.loc[ start_date:end_date, ['spd', 'gust']]\\\n .plot(title=\"{} Airport Plots\".format(avid))\n plt.ylabel('knots')\n\n df.loc[ start_date:end_date,['T', 'Td']].plot()\n plt.ylabel('Degrees C')\n\n df.loc[ start_date:end_date].plot(y=['dir1'], style='r.')\n plt.ylabel('Degrees')\n\n df.loc[ start_date:end_date].plot(y=['QNH'])\n plt.ylabel('QNH Pressure (hPa)')\n\n df.loc[ start_date:end_date, ['cld_base', 'cld_okta']].plot(subplots=True)\n\n plt.show()\n'''\n\n\ndef get_precis(myloc=None):\n\n import pandas as pd\n import wget\n import os\n import requests\n import urllib\n from xml.dom import minidom\n import xml.etree.ElementTree as etree\n\n\n def xtoDF(link):\n xml = urllib.request.urlopen(link)\n # xml = urllib.urlopen(link)\n dom = minidom.parse(xml)\n locs = []\n\n forecasts = dom.getElementsByTagName('forecast')[0]\n for area in forecasts.getElementsByTagName('area'):\n atts = area.attributes\n if atts['type'].value == 'location':\n locs.append({\n 'name': atts['description'].value,\n 'aac': atts['aac'].value,\n })\n return pd.DataFrame(locs)\n\n\n def get_preci_forecasts(loc,tree):\n\n # get list of all element tags - some 180 to 240 preci locations!!\n lists = (tree.findall(\"forecast/area\"))\n #print(\"\\n\\n\\nlists\",lists)\n\n for item in lists:\n # find matching town or location\n if (loc.lower() in item.attrib['description'].lower()):\n try:\n time = (item.findall(\"forecast-period\"))\n #print(\"\\n\\ntime\",time)\n time = time[0].attrib['start-time-local']\n #print(\"\\n\\ntime\",time)\n except:\n pass\n\n # print (\"\\n\\n###############################################################\\n\")\n # print (\"Forecast for:\\t {} issued at:\\t {}\"(format(item.attrib['description']), format(time)))\n # print (\"\\nForecast for \", item.attrib['description'],\" issued at:\" , time,\"\\n\")\n # print(item.attrib)\n\n fcst_param_list = []\n\n for day in item.iter('forecast-period'):\n fcst_dict = {}\n # print (\"\\nForecasts for day:\\t\\t\", day.attrib['start-time-local'])\n for item in day.findall('element'):\n # print (item.get('type'),\":\\t\\t\", item.text)\n fcst_dict.update({item.get('type'): item.text})\n\n for item in day.findall('text'):\n # print (item.get('type'),\":\\t\\t\", item.text)\n fcst_dict.update({item.get('type'): item.text})\n\n fcst_dict.update({'date_time': day.attrib['start-time-local']})\n fcst_param_list.append(fcst_dict)\n\n # print(fcst_param_list)\n return (pd.DataFrame.from_dict(data=fcst_param_list, orient='columns'))\n\n else:\n # print(\"Preci loc not found\")\n # break # DONT - GO TO NEXT ITEM!!\n continue\n\n # Grab all preci XML files and parse the tree\n qld_tree=None\n nt_tree=None\n wa_tree=None\n nsw_tree=None\n vic_tree=None\n sa_tree=None\n for i,state in enumerate(['qld','nt','wa','nsw','vic','sa']):\n if i==0: # if state=='qld'\n preci_url = 'ftp://ftp.bom.gov.au/anon/gen/fwo/IDQ11295.xml'\n print('Processing ' + state)\n #preci_locations = xtoDF(preci_url)\n #print(preci_locations.head())\n xml = urllib.request.urlopen(preci_url)\n qld_tree = etree.parse(xml)\n if i==1: # if state=='nt'\n preci_url = 'ftp://ftp.bom.gov.au/anon/gen/fwo/IDD10207.xml'\n print('Processing ' + state)\n #preci_locations = xtoDF(preci_url)\n #print(preci_locations.head())\n xml = urllib.request.urlopen(preci_url)\n nt_tree = etree.parse(xml)\n if i==2: # if state=='wa'\n preci_url = 'ftp://ftp.bom.gov.au/anon/gen/fwo/IDW14199.xml'\n print('Processing ' + state)\n #preci_locations = xtoDF(preci_url)\n #print(preci_locations.head())\n xml = urllib.request.urlopen(preci_url)\n wa_tree = etree.parse(xml)\n if i==3: # if state=='nsw'\n preci_url = 'ftp://ftp.bom.gov.au/anon/gen/fwo/IDN11060.xml'\n print('Processing ' + state)\n #preci_locations = xtoDF(preci_url)\n #print(preci_locations.head())\n xml = urllib.request.urlopen(preci_url)\n nsw_tree = etree.parse(xml)\n if i==4: # if state=='vic'\n preci_url = 'ftp://ftp.bom.gov.au/anon/gen/fwo/IDV10753.xml'\n print('Processing ' + state)\n #preci_locations = xtoDF(preci_url)\n #print(preci_locations.head())\n xml = urllib.request.urlopen(preci_url)\n vic_tree = etree.parse(xml)\n if i==5: # if state=='sa'\n preci_url = 'ftp://ftp.bom.gov.au/anon/gen/fwo/IDS10044.xml'\n print('Processing ' + state)\n #preci_locations = xtoDF(preci_url)\n #print(preci_locations.head())\n xml = urllib.request.urlopen(preci_url)\n sa_tree = etree.parse(xml)\n\n # Now grab preci forecasts for all aviation locations we need precis for\n # these locations are defined in avid_preci dictionary\n preci_df_list = []\n for avid,location in avid_preci.items(): # for our specified aviation locations\n print('\\n\\nWeather forecasts for avid:{}-->{}'.format(avid,location.upper()))\n if avid in qld:\n tree = qld_tree\n elif avid in nt:\n tree = nt_tree\n elif avid in wa:\n tree = wa_tree\n elif avid in nsw:\n tree = nsw_tree\n elif avid in vic:\n tree = vic_tree\n elif avid in sa:\n tree = sa_tree\n else:\n print(\"Shit YTST-->KALUMBURU YFDF-->PARABURDOO\")\n preci_df = get_preci_forecasts(location,tree) # avid_preci[location],tree)\n\n # convert day into datetime index object - so we can index by datetime\n if preci_df is None:\n pass\n print(\"location is Nonetype - No preci found for either Christmas and Cocos and Barimunya!!!\")\n else:\n preci_df['location'] = location\n try:\n preci_df['date_time'] = \\\n preci_df['date_time'].str.extract(r'(\\d{4}-\\d{2}-\\d{2})', expand=True)\n preci_df['date_time'] = pd.to_datetime(preci_df['date_time'], errors='coerce')\n except:\n print(f'Some errors in processing {avid}:{location}')\n pass\n preci_df_list.append(preci_df)\n\n # preci_df_tmp.append(pd.concat(preci_df_list))\n\n preci_df = pd.concat(preci_df_list)\n\n # abbreviate some of the longer column names .e.g 'air_temp' -> 'T', 'dewpt'->'Td' etc\n preci_df.rename(columns=\n {'date_time': 'day', 'air_temperature_maximum': 'T_max', 'air_temperature_minimum': 'T_min',\n 'precis': 'preci', 'forecast_icon_code': 'icon',\n 'probability_of_precipitation': 'pop', 'precipitation_range': 'rainfall'}, inplace=True)\n\n preci_df.set_index(['location', 'day'], inplace=True)\n\n #with open(os.path.join(cur_dir, 'data', 'preci_file.csv'), 'wb') as f:\n # preci_df.to_csv(f)\n # preci_df.to_csv(open(os.path.join(cur_dir, 'data', 'preci_file.csv'), 'wb') as f)\n\n # if fn called with request for specific preci forecast\n if myloc:\n print(myloc,avid_preci[myloc])\n return preci_df.loc[avid_preci[myloc],]\n else:\n return preci_df # return all precis\n\n\ndef get_precis_old(myloc=None):\n import pandas as pd\n # import numpy as np\n # import requests\n import wget\n import os\n '''\n import re\n import json\n from bs4 import BeautifulSoup\n import xml.etree.ElementTree as etree\n\n from datetime import date, datetime, timedelta\n from dateutil.relativedelta import relativedelta\n '''\n '''\n +++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n FUNCTION TO READ PRECI FORECAST FOR GIVE LOCATION\n +++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n Now find preci location match for given avid by looking at\n the attribute \"description\" for the element.\n\n \n\n There are 4 attributes, get values for attributes as a Python dictionary\n e.g item.attrib['description'] would give name of preci location\n '''\n\n # http://www.bom.gov.au/qld/forecasts/map7day.shtml\n\n def get_preci_forecasts(loc,tree):\n\n # get list of all element tags - some 180 to 240 preci locations!!\n lists = (tree.findall(\"forecast/area\"))\n\n for item in lists:\n # find matching town or location\n if (loc.lower() in item.attrib['description'].lower()):\n time = (item.findall(\"forecast-period\"))\n time = time[0].attrib['start-time-local']\n\n # print (\"\\n\\n###############################################################\\n\")\n # print (\"Forecast for:\\t {} issued at:\\t {}\"(format(item.attrib['description']), format(time)))\n # print (\"\\nForecast for \", item.attrib['description'],\" issued at:\" , time,\"\\n\")\n # print(item.attrib)\n\n fcst_param_list = []\n\n for day in item.iter('forecast-period'):\n fcst_dict = {}\n # print (\"\\nForecasts for day:\\t\\t\", day.attrib['start-time-local'])\n for item in day.findall('element'):\n # print (item.get('type'),\":\\t\\t\", item.text)\n fcst_dict.update({item.get('type'): item.text})\n\n for item in day.findall('text'):\n # print (item.get('type'),\":\\t\\t\", item.text)\n fcst_dict.update({item.get('type'): item.text})\n\n fcst_dict.update({'date_time': day.attrib['start-time-local']})\n fcst_param_list.append(fcst_dict)\n\n # print(fcst_param_list)\n return (pd.DataFrame.from_dict(data=fcst_param_list, orient='columns'))\n\n else:\n # print(\"Preci loc not found\")\n # break # DONT - GO TO NEXT ITEM!!\n continue\n\n '''\n precis = ['Caloundra', 'Caboolture', 'Redcliffe', 'Nambour', 'Noosa Heads', 'Maleny', 'Maroochydore',\n 'Brisbane', 'Kenmore', 'Ferny Grove', 'Oxley', 'Mount Gravatt',\n 'Manly', 'Coolangatta', 'Robina', 'Nerang', 'Coomera', 'Surfers Paradise',\n 'Laidley', 'Beaudesert', 'Boonah', 'Esk', 'Gatton', 'Ipswich',\n 'Bundaberg', 'Maryborough', 'Hervey Bay', 'Monto', 'Gayndah', 'Gympie',\n 'Dalby', 'Chinchilla', 'Miles', 'Kingaroy', 'Toowoomba', 'Warwick', 'Goondiwindi', 'Stanthorpe',\n 'Gladstone', 'Rockhampton', 'Biloela', 'Yeppoon',\n 'Mackay', 'Bowen', 'Carmila', 'Hamilton Island', 'Proserpine',\n 'Townsville', 'Ayr', 'Ingham',\n 'Cairns', 'Atherton', 'Mareeba', 'Innisfail', 'Cardwell', 'Cooktown',\n 'Charters Towers', 'Georgetown', 'Hughenden', 'Richmond',\n 'Normanton', 'Burketown', 'Croydon', 'Doomadgee', 'Kowanyama', 'Mornington Island',\n 'Weipa', 'Aurukun', 'Coen', 'Laura', 'Lockhart River', 'Palmerville', 'Thursday Island',\n 'Charleville', 'Roma', 'St George', 'Augathella', 'Bollon', 'Cunnamulla', 'Injune', 'Surat', 'Birdsville',\n 'Bedourie', 'Boulia', 'Quilpie', 'Thargomindah', 'Windorah',\n 'Mount Isa', 'Camooweal', 'Julia Creek', 'Urandangi', 'Cloncurry',\n 'Longreach', 'Barcaldine', 'Blackall', 'Isisford', 'Tambo', 'Winton',\n 'Emerald', 'Clermont', 'Moranbah', 'Blackwater', 'Dysart',\n 'Rolleston', 'Springsure', 'Taroom']\n '''\n\n '''\n preci_url = 'http://qld-aifs-op.bom.gov.au/gfe/products/IDQ11295.xml'\n preci_response = requests.get(preci_url)\n\n with open('/tmp/preci_data.xml', 'wb') as f:\n f.write(preci_response.content)\n\n tree = etree.parse('/tmp/preci_data.xml')\n\n # requests module does not not works with ftp downloads\n # preci_url = 'ftp://ftp.bom.gov.au/anon/gen/fwo/IDQ11295.xml'\n # InvalidSchema: No connection adapters were found for 'ftp://ftp.bom.gov.au/anon/gen/fwo/IDQ11295.xml'\n # use wget instead if not on internal bom LAN\n # wget module, which doesn't require you to open the destination file\n # just give url and filename with path\n '''\n\n try:\n os.remove(os.path.join(cur_dir, 'data', 'preci_file.xml'))\n except OSError:\n pass\n\n preci_url = 'ftp://ftp.bom.gov.au/anon/gen/fwo/IDQ11295.xml'\n\n wget.download(preci_url, os.path.join(cur_dir, 'data', 'preci_file.xml'))\n with open(os.path.join(cur_dir, 'data', 'preci_file.xml'), 'r') as f:\n tree = etree.parse(f)\n\n preci_df_list = []\n\n for avid,location in avid_preci.items():\n # print('Weather forecasts for avid:{}-->{}'.format(avid,location.upper()))\n preci_df = get_preci_forecasts(location,tree) # avid_preci[location],tree)\n\n # convert day into datetime index object\n if preci_df is None:\n print(\"location is Nonetype\")\n else:\n preci_df['location'] = location\n preci_df['date_time'] = \\\n preci_df['date_time'].str.extract(r'(\\d{4}-\\d{2}-\\d{2})', expand=True)\n preci_df['date_time'] = pd.to_datetime(preci_df['date_time'], errors='coerce')\n preci_df_list.append(preci_df)\n\n preci_df = pd.concat(preci_df_list) # ,sort=True) # Only OYTHONANYWHERE.COM\n '''\n /home/vinorda/storm_predict/utility_functions_june10.py:3767: FutureWarning: Sorting because non-concatenation axis is not aligned. A future version\n 2018-07-24 10:27:44,207: of pandas will change to not sort by default.\n 2018-07-24 10:27:44,207: To accept the future behavior, pass 'sort=True'.\n 2018-07-24 10:27:44,208: To retain the current behavior and silence the warning, pass sort=False\n 2018-07-24 10:27:44,208: preci_df = pd.concat(preci_df_list\n\n 2018-07-24 10:27:44,568: /home/vinorda/storm_predict/utility_functions_june10.py:3788: PerformanceWarning: indexing past lexsort depth may impact performance.\n 2018-07-24 10:27:44,569: return preci_df.loc[avid_preci[myloc],]\n 2018-07-24 10:27:59,070: /home/vinorda/.local/lib/python3.6/site-packages/pandas/core/series.py:850: FutureWarning:\n 2018-07-24 10:27:59,070: Passing list-likes to .loc or [] with any missing label will raise\n 2018-07-24 10:27:59,070: KeyError in the future, you can use .reindex() as an alternative.\n '''\n\n '''Note that not all precis issues have same fields\n For e.g 4pm issue would not have rainfall amnt or pop or max and min T for current day\n 4am issue has no MinT to current day etc,\n Check time of day and have different column names based on time of day\n '''\n\n # abbreviate some of the longer column names .e.g 'air_temp' -> 'T', 'dewpt'->'Td' etc\n preci_df.rename(columns=\n {'date_time': 'day', 'air_temperature_maximum': 'T_max', 'air_temperature_minimum': 'T_min',\n 'precis': 'preci', 'forecast_icon_code': 'icon',\n 'probability_of_precipitation': 'pop', 'precipitation_range': 'rainfall'}, inplace=True)\n\n preci_df.set_index(['location', 'day'], inplace=True)\n\n #with open(os.path.join(cur_dir, 'data', 'preci_file.csv'), 'wb') as f:\n # preci_df.to_csv(f)\n # preci_df.to_csv(open(os.path.join(cur_dir, 'data', 'preci_file.csv'), 'wb') as f)\n\n # if fn called with request for specific preci forecast\n if myloc:\n print(myloc,avid_preci[myloc])\n return preci_df.loc[avid_preci[myloc],]\n else:\n return preci_df # return all precis\n\n\ndef get_precis_state(state='qld'):\n ## see http://fredgibbs.net/tutorials/extract-geocode-placenames-from-text-file\n ## https://pypi.org/project/geopy/\n ## https://stackoverflow.com/questions/48239455/indexerror-list-index-out-of-range\n import pandas as pd\n # import numpy as np\n import requests\n import wget\n import os\n import xml.etree.ElementTree as etree\n\n # http://www.bom.gov.au/qld/forecasts/map7day.shtml\n cur_dir = '/home/accounts/vinorda/IT_stuff/python/flask_projects/storm_predictv2'\n cur_dir = '/home/bou/stats-R/flask_projects/storm_predictv3'\n\n '''geolocate placenames (get latitude and longitude coordinates).\n send requests to the Google Geocoding API and\n process the JSON response that it returns.\n # api-endpoint '''\n url = 'http://maps.googleapis.com/maps/api/geocode/json'\n\n '''Usage\n r = requests.get(URL, params=DICTIONARY)\n the API expects us to send two bits of information:\n address (in this case our place name), and\n sensor (which the API requires to be set to true or false).\n '''\n\n if state == 'qld':\n preci_url = 'ftp://ftp.bom.gov.au/anon/gen/fwo/IDQ11295.xml'\n elif state == 'nsw':\n preci_url = 'ftp://ftp.bom.gov.au/anon/gen/fwo/IDN11060.xml'\n elif state == 'nt':\n preci_url = 'ftp://ftp.bom.gov.au/anon/gen/fwo/IDD10207.xml'\n elif state == 'sa':\n preci_url = 'ftp://ftp.bom.gov.au/anon/gen/fwo/IDS10044.xml'\n elif state == 'vic':\n preci_url = 'ftp://ftp.bom.gov.au/anon/gen/fwo/IDV10753.xml'\n elif state == 'wa':\n preci_url = 'ftp://ftp.bom.gov.au/anon/gen/fwo/IDW14199.xml'\n elif state == None:\n # get all states\n # wud need another outer loop\n # for state in ['nsw','qld',......]:\n pass\n\n try:\n # remove previous XML file\n os.remove(os.path.join(cur_dir, 'data', state + '_preci_file.xml'))\n except OSError:\n pass\n\n wget.download(preci_url, os.path.join(cur_dir, 'data', state + '_preci_file.xml'))\n\n # os.sleep(5)\n\n with open(os.path.join(cur_dir, 'data', state + '_preci_file.xml'), 'r') as f:\n tree = etree.parse(f)\n\n # get list of all element tags - some 180 to 240 preci locations!!\n lists = tree.findall(\"forecast/area\")\n print('Number of forecast/areas in ', state, \" = \", len(lists))\n precis_list = []\n location = None\n state_xml = None\n\n for item in lists:\n # print('item',item)\n if (item.attrib['type'] == 'region'):\n state_xml = item.attrib['description']\n continue\n if (item.attrib['type'] == 'public-district'):\n # district = item.attrib['description']\n continue\n\n # find matching town or location\n location = item.attrib['description']\n print('Processing preci location', location)\n\n # Defining a params dict for the parameters to be sent to the API\n payload = {'address': str(location + ',' + state_xml + ',Australia'), 'sensor': 'false'}\n\n # print ('Geolocating:', payload['address'])\n # Sending get request and saving the response as response object\n # Make sure that you had a successful request\n r = requests.get(url, params=payload)\n if r.status_code == 200:\n # Extracting data in json format\n data = r.json()\n\n '''an empty array (data['results']) will raise the exception\n IndexError : List index Out of range\n also make sure that the field results exists in the dictionary data.\n Otherwise the call to data[\"results\"] will raise a\n KeyError exception... Try dict.get(key) instead of dict[key]'''\n\n if data.get(\"results\", []):\n # Extracting latitude, longitude and formatted address\n # of the first matching location\n # print(data['results'][0]['geometry']['location'])\n lat = data['results'][0]['geometry']['location']['lat']\n lon = data['results'][0]['geometry']['location']['lng']\n # formatted_address = data['results'][0]['formatted_address']\n\n # Printing the output\n # print(\"Latitude:%s\\nLongitude:%s\\nFormatted Address:%s\"\n # %(lat, lon,formatted_address))\n\n # time = item.findall(\"forecast-period\")\n # print('time',time)\n # time = time[0].attrib['start-time-local']\n\n # print (\"\\n\\n###############################################################\\n\")\n # print (\"Forecast for:\\t {} issued at:\\t {}\".format(item.attrib['description'], format(time)))\n # print(item.attrib)\n\n # for each day - get preci day/date,and actual preci (max,min,icon etc)\n days = []\n for day in item.iter('forecast-period'):\n fcst_dict = {}\n # print (\"\\nForecasts for day:\\t\\t\", day.attrib['start-time-local'])\n for item in day.findall('element'):\n # print (item.get('type'),\":\\t\\t\", item.text)\n fcst_dict[item.get('type')] = item.text\n # fcst_dict.update({item.get('type'): item.text})\n\n for item in day.findall('text'):\n # print (item.get('type'),\":\\t\\t\", item.text)\n fcst_dict[item.get('type')] = item.text\n # fcst_dict.update({item.get('type'): item.text})\n\n # fcst_dict.update({'location': location})\n fcst_dict['location'] = location\n fcst_dict['state'] = state\n fcst_dict['lat'] = lat\n fcst_dict['lon'] = lon\n # fcst_dict.update({'date_time': day.attrib['start-time-local']})\n fcst_dict['date_time'] = day.attrib['start-time-local']\n\n # print(fcst_dict.items())\n # print(fcst_dict.keys())\n # print(fcst_dict.values())\n days.append(fcst_dict)\n\n dat = pd.DataFrame.from_dict(data=days, orient='columns')\n dat['date_time'] = \\\n dat['date_time'].str.extract(r'(\\d{4}-\\d{2}-\\d{2})', expand=True)\n dat['date_time'] = pd.to_datetime(dat['date_time'], errors='coerce')\n # print(dat)\n precis_list.append(dat)\n\n preci_df = pd.concat(precis_list)\n\n # df[df.location.str.contains('Boonah')] will give us Boonah precis only\n # abbreviate some of the longer column names .e.g 'air_temp' -> 'T', 'dewpt'->'Td' etc\n preci_df.rename(columns=\n {'date_time': 'day', 'air_temperature_maximum': 'T_max',\n 'air_temperature_minimum': 'T_min', 'precis': 'preci',\n 'forecast_icon_code': 'icon', 'probability_of_precipitation': 'pop',\n 'precipitation_range': 'rainfall'}, inplace=True)\n\n '''Note that not all precis issues have same fields\n For e.g 4pm issue would not have rainfall amnt or pop or max and min T for current day\n 4am issue has no MinT to current day etc,\n Check time of day and have different column names based on time of day\n\n preci_df.set_index(['location', 'day'], inplace=True)\n\n with open(os.path.join(cur_dir, 'data', state+'_preci_file.csv'), 'wb') as f:\n preci_df.to_csv(f)\n preci_df.to_csv(open(os.path.join(cur_dir, 'data', state+'_preci_file.csv'), 'wb') as f)\n\n # if fn called with request for specific preci forecast\n if myloc:\n print(myloc,avid_preci[myloc])\n return preci_df.loc[avid_preci[myloc],]\n else:\n return preci_df # return all precis '''\n\n # force numeric col values\n for col in ['lat', 'lon', 'T_max', 'T_min']:\n preci_df[col] = pd.to_numeric(preci_df[col], errors='coerce')\n\n # with open(os.path.join(cur_dir, 'data', state+'_preci_file.csv'), 'wb') as f:\n # preci_df.to_csv(f)\n\n if (len(preci_df.columns)) == 11: # extra col wud be rainfall !!\n preci_df = preci_df[['location', 'state', 'lat', 'lon', 'day', 'icon', \\\n 'T_max', 'T_min', 'pop', 'preci', 'rainfall']]\n elif (len(preci_df.columns)) == 10:\n preci_df = preci_df[['location', 'state', 'lat', 'lon', 'day', 'icon', \\\n 'T_max', 'T_min', 'pop', 'preci']]\n\n preci_df.to_csv(cur_dir + '/data/' + state + '_preci_file.csv', sep=',', header=True)\n\n return (preci_df)\n\n\n# Fn below is for creating sfc wind climatology based on\n# get days with similar gradient wind to Brisbane Sonde\ndef get_matching_days(grad_wnd_dir, grad_wnd_spd, SLP, sonde):\n#def get_matching_days(grad_wnd_dir, grad_wnd_spd, sonde):\n if (grad_wnd_dir >= 16) & (grad_wnd_dir <= 344):\n UDL = grad_wnd_dir - 15\n UDR = grad_wnd_dir + 15\n print(\"(grad_wnd_dir >= 16) & (grad_wnd_dir <= 344)\", UDL, UDR)\n grad_dir_mask = \\\n (sonde['wdir900'] >= UDL) & \\\n (sonde['wdir900'] <= UDR)\n\n elif (grad_wnd_dir >= 345) & (grad_wnd_dir <= 360):\n UDL = grad_wnd_dir - 15\n UDR = grad_wnd_dir + 15 - 360\n print(\"(grad_wnd_dir >= 16) & (grad_wnd_dir <= 344)\", UDL, UDR)\n grad_dir_mask = \\\n (sonde['wdir900'] >= UDL) | \\\n (sonde['wdir900'] <= UDR)\n\n elif (grad_wnd_dir >= 0) & (grad_wnd_dir <= 15):\n UDL = grad_wnd_dir - 15 + 360\n UDR = grad_wnd_dir + 15\n print(\"(grad_wnd_dir >= 16) & (grad_wnd_dir <= 344)\", UDL, UDR)\n grad_dir_mask = \\\n (sonde['wdir900'] >= UDL) | \\\n (sonde['wdir900'] <= UDR)\n else:\n print(\"No shit wind\", sonde['wdir900'])\n\n USL = grad_wnd_spd - 5\n USR = grad_wnd_spd + 5\n grad_spd_mask = (sonde['wspd900'] > USL) & \\\n (sonde['wspd900'] < USR)\n\n SPL = SLP - 5\n SPR = SLP + 5\n qnh_mask = (sonde['P'] > SPL) & (sonde['P'] < SPR)\n\n mask = grad_dir_mask & grad_spd_mask & qnh_mask\n\n try:\n match_days = sonde.loc[mask].index\n except:\n print(\"No matching synoptic days found in dataset\")\n # exit - calling fn expected to deal with situation\n\n return match_days\n\n\n\n'''\nHaversine (or Great Circle) distance formula.\nhttps://en.wikipedia.org/wiki/Haversine_formula\nCopyright\nhttps://github.com/sversh/pycon2017-optimizing-pandas\nhttps://www.youtube.com/watch?v=HN5d490_KKk\nhttps://www.superherosupplies.com/\n\nfunction takes the latitude and longitude of two points,\nadjusts for Earth’s curvature,\nand calculates the straight-line distance between them\n\nUsage: say to find dist between given point and all other\ndata points in a dataframe df\n\ndf['distance'] = df.apply(lambda row:\n haversine(40.671, -73.985, row['latitude'], row['longitude']), axis=1)\n\n# Vectorized implementation of Haversine applied on Pandas series\ndf['distance'] = haversine(40.671, -73.985, df['latitude'], df['longitude'])\n\n\n50-fold improvement over the apply() method,\nand more than a 100-fold improvement over iterrows() by\nvectorizing the function — \ndidn’t need to do anything but change the input type tp pandas Series!\n'''\n'''\n# Define a basic Haversine distance formula\ndef haversine(lat1, lon1, lat2, lon2):\n MILES = 3959 # 6367 km is the radius of the Earth\n # convert decimal degrees to radian\n lat1, lon1, lat2, lon2 = map(np.deg2rad, [lat1, lon1, lat2, lon2])\n\n # haversine formula\n dlat = lat2 - lat1\n dlon = lon2 - lon1\n a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2)**2\n c = 2 * np.arcsin(np.sqrt(a))\n total_miles = MILES * c\n return total_miles\n'''\n\ndef haversine(lon1, lat1, lon2, lat2):\n\n from math import radians, cos, sin, asin, sqrt, atan2\n \"\"\"\n Calculate the great circle distance between two points\n on the earth (specified in decimal degrees)\n \"\"\"\n # convert decimal degrees to radians\n lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])\n\n # haversine formula\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2\n #c = 2 * asin(sqrt(a))\n c = 2 * atan2(sqrt(a),sqrt(1-a))\n\n # 6367 km is the radius of the Earth\n km = 6367 * c\n return(km)", "repo_name": "launda/avguide", "sub_path": "utility_functions_sep2018.py", "file_name": "utility_functions_sep2018.py", "file_ext": "py", "file_size_in_byte": 223793, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "logging.getLogger", "line_number": 23, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 378, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 394, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 428, "usage_type": "call"}, {"api_name": "os.path", "line_number": 428, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 454, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 470, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 475, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 573, "usage_type": "call"}, {"api_name": "os.path", "line_number": 573, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 576, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 564, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 603, "usage_type": "attribute"}, {"api_name": "numpy.unique", "line_number": 688, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 701, "usage_type": "attribute"}, {"api_name": "numpy.timedelta64", "line_number": 719, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 765, "usage_type": "call"}, {"api_name": "os.path", "line_number": 765, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 766, "usage_type": "call"}, {"api_name": "os.path", "line_number": 766, "usage_type": "attribute"}, {"api_name": "pandas.to_datetime", "line_number": 792, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 809, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 816, "usage_type": "call"}, {"api_name": "os.path", "line_number": 816, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 818, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 841, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 842, "usage_type": "call"}, {"api_name": "os.path", "line_number": 842, "usage_type": "attribute"}, {"api_name": "pandas.to_datetime", "line_number": 844, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 849, "usage_type": "call"}, {"api_name": "os.path", "line_number": 849, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 850, "usage_type": "call"}, {"api_name": "functools.reduce", "line_number": 863, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 906, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 906, "usage_type": "attribute"}, {"api_name": "pandas.date_range", "line_number": 913, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 925, "usage_type": "call"}, {"api_name": "requests.codes", "line_number": 929, "usage_type": "attribute"}, {"api_name": "numpy.abs", "line_number": 998, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 1010, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 1021, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 1032, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 1093, "usage_type": "call"}, {"api_name": "os.path.getsize", "line_number": 1108, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1108, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 1116, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 1126, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 1141, "usage_type": "call"}, {"api_name": "numpy.NaN", "line_number": 1145, "usage_type": "attribute"}, {"api_name": "pandas.DatetimeIndex", "line_number": 1150, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 1170, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1190, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1190, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 1191, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 1227, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1228, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1228, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 1197, "usage_type": "attribute"}, {"api_name": "pandas.datetime.today", "line_number": 1286, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 1286, "usage_type": "attribute"}, {"api_name": "pandas.to_datetime", "line_number": 1291, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 1320, "usage_type": "call"}, {"api_name": "requests.codes", "line_number": 1324, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 1337, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 1347, "usage_type": "call"}, {"api_name": "numpy.NaN", "line_number": 1351, "usage_type": "attribute"}, {"api_name": "numpy.abs", "line_number": 1365, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 1369, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 1373, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 1377, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 1381, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 1413, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 1413, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 1419, "usage_type": "call"}, {"api_name": "requests.codes", "line_number": 1423, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 1436, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 1443, "usage_type": "call"}, {"api_name": "numpy.NaN", "line_number": 1447, "usage_type": "attribute"}, {"api_name": "numpy.abs", "line_number": 1463, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 1470, "usage_type": "call"}, {"api_name": "cx_Oracle.connect", "line_number": 1548, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 1550, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1550, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 1559, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 1567, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 1567, "usage_type": "attribute"}, {"api_name": "pandas.Timedelta", "line_number": 1567, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 1568, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 1568, "usage_type": "attribute"}, {"api_name": "pandas.io.sql.read_sql", "line_number": 1584, "usage_type": "call"}, {"api_name": "pandas.io.sql", "line_number": 1584, "usage_type": "name"}, {"api_name": "pandas.datetime.today", "line_number": 1593, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 1593, "usage_type": "attribute"}, {"api_name": "pandas.Timedelta", "line_number": 1593, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 1594, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 1594, "usage_type": "attribute"}, {"api_name": "pandas.io.sql.read_sql", "line_number": 1612, "usage_type": "call"}, {"api_name": "pandas.io.sql", "line_number": 1612, "usage_type": "name"}, {"api_name": "pandas.datetime.today", "line_number": 1616, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 1616, "usage_type": "attribute"}, {"api_name": "pandas.datetime.today", "line_number": 1617, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 1617, "usage_type": "attribute"}, {"api_name": "pandas.Timedelta", "line_number": 1617, "usage_type": "call"}, {"api_name": "pandas.io.sql.read_sql", "line_number": 1634, "usage_type": "call"}, {"api_name": "pandas.io.sql", "line_number": 1634, "usage_type": "name"}, {"api_name": "pandas.datetime.today", "line_number": 1641, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 1641, "usage_type": "attribute"}, {"api_name": "pandas.Timedelta", "line_number": 1641, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 1642, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 1642, "usage_type": "attribute"}, {"api_name": "pandas.Timedelta", "line_number": 1642, "usage_type": "call"}, {"api_name": "pandas.io.sql.read_sql", "line_number": 1659, "usage_type": "call"}, {"api_name": "pandas.io.sql", "line_number": 1659, "usage_type": "name"}, {"api_name": "pandas.Series", "line_number": 1705, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 1705, "usage_type": "attribute"}, {"api_name": "numpy.abs", "line_number": 1728, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 1733, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 1738, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 1761, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 1765, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 1765, "usage_type": "attribute"}, {"api_name": "pandas.concat", "line_number": 1793, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 1802, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 1803, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 1830, "usage_type": "call"}, {"api_name": "pandas.Timedelta", "line_number": 1833, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 1838, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 1919, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1919, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 1920, "usage_type": "call"}, {"api_name": "datetime.datetime.strftime", "line_number": 1951, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1951, "usage_type": "name"}, {"api_name": "datetime.datetime.strftime", "line_number": 1954, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1954, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 1988, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 1988, "usage_type": "name"}, {"api_name": "seaborn.boxplot", "line_number": 2001, "usage_type": "call"}, {"api_name": "seaborn.boxplot", "line_number": 2006, "usage_type": "call"}, {"api_name": "seaborn.boxplot", "line_number": 2011, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 2027, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 2027, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 2033, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 2033, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 2036, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 2036, "usage_type": "name"}, {"api_name": "netCDF4.num2date", "line_number": 2128, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 2152, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 2192, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 2193, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 2194, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 2195, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 2205, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 2213, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 2214, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 2221, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 2226, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 2237, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 2237, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 2247, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 2248, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 2283, "usage_type": "call"}, {"api_name": "numpy.arctan2", "line_number": 2292, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 2298, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 2323, "usage_type": "call"}, {"api_name": "pandas.Timedelta", "line_number": 2323, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 2324, "usage_type": "call"}, {"api_name": "pandas.Timedelta", "line_number": 2324, "usage_type": "call"}, {"api_name": "pandas.date_range", "line_number": 2326, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 2366, "usage_type": "call"}, {"api_name": "pandas.Timedelta", "line_number": 2366, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 2367, "usage_type": "call"}, {"api_name": "pandas.Timedelta", "line_number": 2367, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 2370, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 2370, "usage_type": "attribute"}, {"api_name": "pandas.datetime.today", "line_number": 2372, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 2372, "usage_type": "attribute"}, {"api_name": "pandas.Timedelta", "line_number": 2372, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 2373, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 2373, "usage_type": "attribute"}, {"api_name": "pandas.Timedelta", "line_number": 2373, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 2538, "usage_type": "call"}, {"api_name": "pandas.Timedelta", "line_number": 2538, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 2539, "usage_type": "call"}, {"api_name": "pandas.Timedelta", "line_number": 2539, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 2541, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 2541, "usage_type": "attribute"}, {"api_name": "pandas.Timedelta", "line_number": 2541, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 2542, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 2542, "usage_type": "attribute"}, {"api_name": "pandas.Timedelta", "line_number": 2542, "usage_type": "call"}, {"api_name": "pandas.date_range", "line_number": 2547, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 2654, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 2655, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 2656, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 2688, "usage_type": "attribute"}, {"api_name": "pandas.Series", "line_number": 2688, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 2790, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 2791, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 2792, "usage_type": "attribute"}, {"api_name": "numpy.timedelta64", "line_number": 2872, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 2975, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 2990, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 2999, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 3043, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 3052, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 3057, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 3057, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 3065, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 3129, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 3136, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3137, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3137, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 3143, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3144, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3144, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 3148, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3149, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3149, "usage_type": "attribute"}, {"api_name": "pandas.Timedelta", "line_number": 3161, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 3164, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 3169, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 3172, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 3172, "usage_type": "attribute"}, {"api_name": "flask.session", "line_number": 3177, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 3206, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 3215, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3217, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3217, "usage_type": "attribute"}, {"api_name": "pandas.merge", "line_number": 3254, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 3268, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 3275, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 3275, "usage_type": "attribute"}, {"api_name": "math.isnan", "line_number": 3346, "usage_type": "call"}, {"api_name": "math.isnan", "line_number": 3354, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 3391, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 3398, "usage_type": "call"}, {"api_name": "cx_Oracle.connect", "line_number": 3410, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 3415, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 3415, "usage_type": "attribute"}, {"api_name": "pandas.io.sql.read_sql", "line_number": 3428, "usage_type": "call"}, {"api_name": "pandas.io.sql", "line_number": 3428, "usage_type": "name"}, {"api_name": "pandas.Timedelta", "line_number": 3434, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 3463, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 3466, "usage_type": "call"}, {"api_name": "enum.Enum", "line_number": 3474, "usage_type": "name"}, {"api_name": "collections.namedtuple", "line_number": 3482, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 3568, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3568, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3568, "usage_type": "attribute"}, {"api_name": "collections.namedtuple", "line_number": 3539, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 3606, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3606, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3606, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 3618, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3618, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3618, "usage_type": "attribute"}, {"api_name": "pandas.to_datetime", "line_number": 3631, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 3638, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 3641, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 3643, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 3647, "usage_type": "call"}, {"api_name": "pandas.Index", "line_number": 3589, "usage_type": "attribute"}, {"api_name": "pandas.datetime", "line_number": 3655, "usage_type": "attribute"}, {"api_name": "collections.namedtuple", "line_number": 3666, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 3708, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 3708, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 3715, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3715, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3715, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 3717, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 3724, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3725, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3725, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 3731, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3732, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3732, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 3736, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3737, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3737, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 3748, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3750, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3750, "usage_type": "attribute"}, {"api_name": "pandas.merge", "line_number": 3754, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 3775, "usage_type": "call"}, {"api_name": "math.isnan", "line_number": 3835, "usage_type": "call"}, {"api_name": "math.isnan", "line_number": 3841, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 3873, "usage_type": "call"}, {"api_name": "pandas.datetime.today", "line_number": 3891, "usage_type": "call"}, {"api_name": "pandas.datetime", "line_number": 3891, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 3898, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3898, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3898, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 3901, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 3908, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3909, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3909, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 3915, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3916, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3916, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 3920, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3921, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3921, "usage_type": "attribute"}, {"api_name": "pandas.Timedelta", "line_number": 3928, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 3941, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 3943, "usage_type": "call"}, {"api_name": "os.path", "line_number": 3943, "usage_type": "attribute"}, {"api_name": "pandas.merge", "line_number": 3952, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 3966, "usage_type": "call"}, {"api_name": "math.isnan", "line_number": 4025, "usage_type": "call"}, {"api_name": "math.isnan", "line_number": 4031, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 4063, "usage_type": "call"}, {"api_name": "numpy.NaN", "line_number": 4089, "usage_type": "attribute"}, {"api_name": "numpy.log", "line_number": 4200, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 4201, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 4314, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 4317, "usage_type": "call"}, {"api_name": "os.path", "line_number": 4317, "usage_type": "attribute"}, {"api_name": "pandas.read_excel", "line_number": 4320, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 4326, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 4337, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 4350, "usage_type": "call"}, {"api_name": "os.path", "line_number": 4350, "usage_type": "attribute"}, {"api_name": "pandas.read_fwf", "line_number": 4353, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 4360, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 4386, "usage_type": "call"}, {"api_name": "os.path", "line_number": 4386, "usage_type": "attribute"}, {"api_name": "pandas.read_excel", "line_number": 4388, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 4394, "usage_type": "call"}, {"api_name": "os.path", "line_number": 4394, "usage_type": "attribute"}, {"api_name": "pandas.read_fwf", "line_number": 4396, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 4402, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 4415, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 4426, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 4469, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 4470, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 4473, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 4482, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 4502, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 4508, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 4536, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 4554, "usage_type": "call"}, {"api_name": "datetime.datetime.today", "line_number": 4564, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 4564, "usage_type": "name"}, {"api_name": "datetime.datetime.today", "line_number": 4566, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 4566, "usage_type": "name"}, {"api_name": "datetime.datetime.today", "line_number": 4571, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 4571, "usage_type": "name"}, {"api_name": "dateutil.relativedelta.relativedelta", "line_number": 4571, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 4590, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 4629, "usage_type": "call"}, {"api_name": "requests.codes", "line_number": 4638, "usage_type": "attribute"}, {"api_name": "re.findall", "line_number": 4651, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 4706, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 4706, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 4706, "usage_type": "attribute"}, {"api_name": "xml.dom.minidom.parse", "line_number": 4708, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 4708, "usage_type": "argument"}, {"api_name": "xml.dom.minidom", "line_number": 4708, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 4719, "usage_type": "call"}, {"api_name": "pandas.DataFrame.from_dict", "line_number": 4761, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 4761, "usage_type": "attribute"}, {"api_name": "xml.etree.ElementTree", "line_number": 4781, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 4781, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 4781, "usage_type": "attribute"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 4782, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 4782, "usage_type": "argument"}, {"api_name": "xml.etree.ElementTree", "line_number": 4788, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 4788, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 4788, "usage_type": "attribute"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 4789, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 4789, "usage_type": "argument"}, {"api_name": "xml.etree.ElementTree", "line_number": 4795, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 4795, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 4795, "usage_type": "attribute"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 4796, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 4796, "usage_type": "argument"}, {"api_name": "xml.etree.ElementTree", "line_number": 4802, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 4802, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 4802, "usage_type": "attribute"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 4803, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 4803, "usage_type": "argument"}, {"api_name": "xml.etree.ElementTree", "line_number": 4809, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 4809, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 4809, "usage_type": "attribute"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 4810, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 4810, "usage_type": "argument"}, {"api_name": "xml.etree.ElementTree", "line_number": 4816, "usage_type": "name"}, {"api_name": "urllib.request.urlopen", "line_number": 4816, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 4816, "usage_type": "attribute"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 4817, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 4817, "usage_type": "argument"}, {"api_name": "pandas.to_datetime", "line_number": 4849, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 4857, "usage_type": "call"}, {"api_name": "pandas.DataFrame.from_dict", "line_number": 4942, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 4942, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 4989, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 4989, "usage_type": "call"}, {"api_name": "os.path", "line_number": 4989, "usage_type": "attribute"}, {"api_name": "wget.download", "line_number": 4995, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 4995, "usage_type": "call"}, {"api_name": "os.path", "line_number": 4995, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 4996, "usage_type": "call"}, {"api_name": "os.path", "line_number": 4996, "usage_type": "attribute"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 4997, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 4997, "usage_type": "name"}, {"api_name": "pandas.to_datetime", "line_number": 5012, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 5015, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 5104, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 5104, "usage_type": "call"}, {"api_name": "os.path", "line_number": 5104, "usage_type": "attribute"}, {"api_name": "wget.download", "line_number": 5108, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 5108, "usage_type": "call"}, {"api_name": "os.path", "line_number": 5108, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 5112, "usage_type": "call"}, {"api_name": "os.path", "line_number": 5112, "usage_type": "attribute"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 5113, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 5113, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 5141, "usage_type": "call"}, {"api_name": "pandas.DataFrame.from_dict", "line_number": 5200, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 5200, "usage_type": "attribute"}, {"api_name": "pandas.to_datetime", "line_number": 5203, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 5207, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 5237, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 5356, "usage_type": "argument"}, {"api_name": "math.sin", "line_number": 5361, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 5361, "usage_type": "call"}, {"api_name": "math.atan2", "line_number": 5363, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 5363, "usage_type": "call"}]} +{"seq_id": "32216578254", "text": "#!/home/pablo/Spymovil/python/proyectos/APICOMMSV3/venv/bin/python\n'''\nApi de configuracion SQL de dataloggers y PLC para el servidor APISERVER\n\nhttps://www.gorgias.com/blog/prevent-idle-in-transaction-engineering\nhttps://4geeks.com/lesson/everything-you-need-to-start-using-sqlalchemy\n\n\nBASE DE DATOS:\npsql>CREATE DATABASE bd_unidades;\npsql>CREATE TABLE configuraciones ( pk SERIAL PRIMARY KEY, unit_id VARCHAR (20), uid VARCHAR (50), jconfig JSON);\n\npip install --upgrade wheel\napt-get install libpq-dev\npip install psycopg2\n\n-----------------------------------------------------------------------------\nR001 @ 2023-06-17 (commsv3_apiconf:1.2)\n- En el entrypoint '/apiconf/unidades' el json que devuelvo tiene una nueva\n clave 'nro_unidades'\n \n-----------------------------------------------------------------------------\nR001 @ 2023-06-14 (commsv3_apiconf:1.1)\n- Se manejan todos los parámetros por variables de entorno\n- Se agrega un entrypoint 'ping' que permite ver si la api esta operativa\n\n'''\nimport os\nimport json\nfrom sqlalchemy import create_engine, exc\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom sqlalchemy import text\nfrom sqlalchemy.pool import NullPool\nimport logging\nfrom flask import Flask, request, jsonify\nfrom flask_restful import Resource, Api, reqparse\nfrom apiconf_templates import DLG_CONF_TEMPLATE, PLC_CONF_TEMPLATE\nfrom collections.abc import MutableMapping\n\nPGSQL_HOST = os.environ.get('PGSQL_HOST', 'pgsql')\nPGSQL_PORT = os.environ.get('PGSQL_PORT','5432')\nPGSQL_USER = os.environ.get('PGSQL_USER', 'admin')\nPGSQL_PASSWD = os.environ.get('PGSQL_PASSWD', 'pexco599')\nPGSQL_BD = os.environ.get('PGSQL_BD','bd_spcomms')\n\nAPICONF_HOST = os.environ.get('APICONF_HOST','apiconf')\nAPICONF_PORT = os.environ.get('APICONF_PORT','5200')\n\nAPI_VERSION = 'R001 @ 2023-06-17'\n\napp = Flask(__name__)\napi = Api(app)\n\n'''\nERROR SQL001: Pgsql engine error\nERROR SQL002: Pgsql connection error\nERROR SQL003: Pgsql execute error\n\nWARN SQL001: No config rcd in SQL\n\n\n'''\nclass BD_SQL_BASE:\n\n def __init__(self):\n self.engine = None\n self.conn = None\n self.response = ''\n self.status_code = 0\n self.url = f'postgresql+psycopg2://{PGSQL_USER}:{PGSQL_PASSWD}@{PGSQL_HOST}:{PGSQL_PORT}/{PGSQL_BD}'\n\n def connect(self):\n # Engine\n try:\n self.engine = create_engine(url=self.url, echo=False, isolation_level=\"AUTOCOMMIT\", poolclass=NullPool, connect_args={'connect_timeout': 5})\n except SQLAlchemyError as err:\n app.logger.info( f'(100) ApiCONF_ERR001: Pgsql engine error, HOST:{PGSQL_HOST}:{PGSQL_PORT}, Err:{err}')\n return False \n # Connection\n try:\n self.conn = self.engine.connect()\n self.conn.autocommit = True\n except SQLAlchemyError as err:\n app.logger.info( f'(101) ApiCONF_ERR002: Pgsql connection error, HOST:{PGSQL_HOST}:{PGSQL_PORT}, Err:{err}')\n return False\n #\n return True\n #\n\n def close(self):\n '''\n '''\n app.logger.info( f'(DEBUG) ApiCONF_INFO: Sql close and dispose R2. HOST:{PGSQL_HOST}:{PGSQL_PORT}')\n self.conn.invalidate()\n self.conn.close() \n self.engine.dispose()\n\n def kill_idle_connections(self):\n '''\n Funcion que mata las tareas idle de la bd.\n https://linuxhint.com/kill-idle-connections-postgresql/\n select pid,state, usename,datname,datid from pg_stat_activity where state = 'idle' and datname=current_database()\n '''\n sql = '''\n select pid from pg_stat_activity where state = 'idle' and datname=current_database() order by pid asc\n '''\n query = text(sql)\n rp = self.conn.execute(query)\n # Dejo al menos 3 conexiones\n i = 0\n for row in rp.fetchall():\n pid = row[0]\n i += 1\n if i < 4:\n continue\n print(f'DEBUG: {pid}')\n sql = f\"select pg_terminate_backend({pid})\"\n query = text(sql)\n #_ = self.conn.execute(query)\n\n def remove_idle_connections(self):\n sql = '''\n WITH inactive_connections AS (\n SELECT pid, rank() over (partition by client_addr order by backend_start ASC) as rank\n ` FROM pg_stat_activity\n WHERE\n -- Exclude the thread owned connection (ie no auto-kill)\n pid <> pg_backend_pid( )\n AND\n -- Exclude known applications connections\n application_name !~ '(?:psql)|(?:pgAdmin.+)'\n AND\n -- Include connections to the same database the thread is connected to\n datname = current_database() \n AND\n -- Include connections using the same thread username connection\n usename = current_user \n AND\n -- Include inactive connections only\n state in ('idle', 'idle in transaction', 'idle in transaction (aborted)', 'disabled') \n AND\n -- Include old connections (found with the state_change field)\n current_timestamp - state_change > interval '5 minutes' \n )\n SELECT pg_terminate_backend(pid)\n FROM inactive_connections \n WHERE rank > 1\n '''\n query = text(sql)\n try:\n #print(sql)\n _ = self.conn.execute(query)\n except Exception as err:\n app.logger.info( f'(116) ApiDATOS_ERR005: Sql exec error, HOST:{PGSQL_HOST}:{PGSQL_PORT}, Err:{err}')\n #\n\n def exec_sql(self, sql):\n # Ejecuta la orden sql.\n # Retorna un resultProxy o None\n if not self.connect():\n app.logger.info( f'(102) ApiCONF_ERR002: Pgsql connection error, HOST:{PGSQL_HOST}:{PGSQL_PORT}')\n return {'res':False }\n #\n try:\n query = text(sql)\n except Exception as err:\n app.logger.info( f'(103) ApiCONF_ERR003: Sql query error, HOST:{PGSQL_HOST}:{PGSQL_PORT}, Err:{sql}')\n app.logger.info( f'(104) ApiCONF_ERR004: Sql query exception, HOST:{PGSQL_HOST}:{PGSQL_PORT}, Err:{err}')\n return {'res':False }\n #\n try:\n #print(sql)\n rp = self.conn.execute(query)\n except Exception as err:\n app.logger.info( f'(105) ApiDATOS_ERR005: Sql exec error, HOST:{PGSQL_HOST}:{PGSQL_PORT}, Err:{err}')\n return {'res':False }\n #\n return {'res':True,'rp':rp }\n\n def read_configuration(self, unit_id):\n '''\n Lee el jconfig del usuario\n '''\n sql = f\"SELECT jconfig FROM configuraciones WHERE unit_id = '{unit_id}'\" \n d_res = self.exec_sql(sql)\n if not d_res.get('res',False):\n app.logger.info( '(105) ApiCONF_ERR007: select_user FAIL')\n return d_res\n #\n\n def insert_configuration(self, unit_id, jd_config ):\n '''\n Inserta un nuevo usuario en la tabla usuarios\n Retorna True/False\n '''\n # Determino si existe el registro (UPDATE) o no (INSERT)\n sql = f\"SELECT pk FROM configuraciones WHERE unit_id = '{unit_id}'\"\n d_res = self.exec_sql(sql)\n if not d_res.get('res',False):\n app.logger.info( '(106) ApiCONF_ERR008: insert_user FAIL')\n return d_res\n #\n rp = d_res.get('rp',None)\n if rp.rowcount == 0:\n # Hago un INSERT:\n sql = f\"INSERT INTO configuraciones (unit_id, uid, jconfig ) VALUES ('{unit_id}','0','{jd_config}')\"\n else:\n row = rp.fetchone()\n pk = row[0]\n sql = f\"UPDATE configuraciones SET jconfig = '{jd_config}' WHERE pk = '{pk}'\"\n #\n d_res = self.exec_sql(sql)\n if not d_res.get('res',False):\n app.logger.info( '(107) ApiCONF_ERR008: insert_user FAIL')\n return d_res\n\n def read_uid(self, uid):\n '''\n '''\n sql = f\"SELECT id FROM recoverid WHERE uid = '{uid}'\" \n d_res = self.exec_sql(sql)\n if not d_res.get('res',False):\n app.logger.info( '(108) ApiCONF_ERR012: read_uid FAIL')\n return d_res\n\n def insert_uid(self, id, uid):\n '''\n '''\n sql = f\"DELETE FROM recoverid WHERE uid = '{uid}'\"\n d_res = self.exec_sql(sql)\n sql = f\"DELETE FROM recoverid WHERE id = '{id}'\"\n d_res = self.exec_sql(sql)\n #\n sql = f\"INSERT INTO recoverid (id, uid ) VALUES ('{id}','{uid}')\"\n d_res = self.exec_sql(sql)\n if not d_res.get('res',False):\n app.logger.info( '(109) ApiCONF_ERR011: insert_uid FAIL')\n return d_res\n #\n return d_res\n\n def read_allunits(self):\n '''\n Lee todas las unidades configuradas.\n '''\n sql = \"SELECT unit_id FROM configuraciones\"\n d_res = self.exec_sql(sql)\n if not d_res.get('res',False):\n app.logger.info( '(105) ApiCONF_ERR007: select_user FAIL')\n return d_res\n\nclass Kill(Resource):\n def get(self):\n bdsql = BD_SQL_BASE()\n bdsql.connect()\n bdsql.kill_idle_connections()\n bdsql.close()\n return {'rsp':'OK'},200 \n \nclass Test(Resource):\n '''\n Abre una conexion y la cierra.\n '''\n def get(self):\n #\n bdsql = BD_SQL_BASE()\n bdsql.connect()\n bdsql.remove_idle_connections()\n bdsql.close()\n return {'rsp':'OK'},200\n\nclass Ping(Resource):\n '''\n Prueba la conexion a la SQL\n '''\n def get(self):\n\n bdpgsl = BD_SQL_BASE()\n if bdpgsl.connect():\n print(\"Connected to PGSQL!\")\n bdpgsl.close()\n return {'rsp':'OK','version':API_VERSION,'SQL_HOST':PGSQL_HOST, 'SQL_PORT':PGSQL_PORT },200\n #\n d_rsp = {'rsp':'ERROR', 'msg':f'ApiCONF_ERR001: Pgsql connect error, HOST:{PGSQL_HOST}:{PGSQL_PORT}' }\n return d_rsp, 500\n\nclass GetTemplate(Resource):\n '''\n Retorna un json con el template de la version solicitada.\n Si esta es \"latest\" se manda la ultima version\n '''\n def get(self):\n '''\n Testing:\n req=requests.get('http://127.0.0.1:5200/apiconf/template', params={'ver':'1.1.0','type':'PLC'})\n jd_template=req.json()\n d_template=json.loads(jd_template)\n '''\n parser = reqparse.RequestParser()\n parser.add_argument('ver',type=str,location='args',required=True)\n parser.add_argument('type',type=str,location='args',required=True)\n args=parser.parse_args()\n s_version = args['ver']\n s_type = args['type']\n #\n if s_type.upper() == 'DLG':\n if s_version.upper() == 'LATEST':\n s_version = list(DLG_CONF_TEMPLATE.keys())[0]\n #\n if s_version not in list(DLG_CONF_TEMPLATE.keys()):\n return {},204\n #\n d_template = DLG_CONF_TEMPLATE[s_version]\n d_rsp = {'version': s_version, 'template': d_template}\n return d_rsp,200\n\n if s_type.upper() == 'PLC':\n if s_version.upper() == 'LATEST':\n s_version = list(PLC_CONF_TEMPLATE.keys())[0]\n\n if s_version not in list(PLC_CONF_TEMPLATE.keys()):\n return {},204\n #\n d_template = PLC_CONF_TEMPLATE[s_version]\n d_rsp = {'version': s_version, 'template': d_template}\n return d_rsp,200\n \n return {},204\n \nclass GetVersiones(Resource):\n '''\n Retorna un json con la lista de versiones disponibles.\n '''\n def get(self):\n '''\n Retorna una json con la lista de versiones disponibles\n '''\n parser = reqparse.RequestParser()\n parser.add_argument('type',type=str,location='args',required=True)\n args=parser.parse_args()\n s_type = args['type']\n #\n if s_type.upper() == 'DLG':\n l_versiones = list( DLG_CONF_TEMPLATE.keys())\n d_rsp = { 'versiones': l_versiones}\n return d_rsp,200\n\n if s_type.upper() == 'PLC':\n l_versiones = list( PLC_CONF_TEMPLATE.keys())\n d_rsp = { 'versiones': l_versiones}\n return d_rsp,200\n \n return {}, 204\n \nclass Config(Resource):\n\n def __convert_flatten__(self, d, parent_key ='', sep =':'):\n '''\n '''\n items = []\n for k, v in d.items():\n new_key = parent_key + sep + k if parent_key else k\n \n if isinstance(v, MutableMapping):\n items.extend(self.__convert_flatten__(v, new_key, sep = sep).items())\n else:\n items.append((new_key, v))\n return dict(items)\n\n def __compare_dicts__(self, d_reference, d_other):\n '''\n Compara 2 diccionarios y devuelve 2 listas con las claves\n diferentes en uno y otro.\n '''\n set_reference = set( self.__convert_flatten__(d_reference).keys())\n set_other = set( self.__convert_flatten__(d_other).keys())\n k_de_mas = list(set_other - set_reference)\n k_de_menos = list(set_reference - set_other) \n return k_de_mas, k_de_menos\n \n def get(self):\n '''\n Lee la configuracion de un equipo de la SQL\n En la BS almacenamos json.(strings)\n Retornamos un json.\n '''\n parser = reqparse.RequestParser()\n parser.add_argument('unit',type=str,location='args',required=True)\n args=parser.parse_args()\n #\n bdsql = BD_SQL_BASE()\n d_res = bdsql.read_configuration(args['unit'])\n if not d_res.get('res',False):\n bdsql.close()\n return {'rsp':'ERROR', 'msg':'Error en pgsql'},500\n #\n rp = d_res.get('rp',None)\n if rp.rowcount == 0:\n app.logger.info( f'(110) ApiCONF_WARN001: No config rcd in SQL')\n bdsql.close()\n return {},204\n\n row = rp.fetchone()\n d_config = row[0]\n bdsql.close()\n return d_config, 200\n \n def post(self):\n '''\n Crea/actualiza la configuracion de una unidad.\n Recibimos un json que almacenamos.\n No lo chequeamos !!!\n '''\n parser = reqparse.RequestParser()\n parser.add_argument('unit',type=str,location='args',required=True)\n args=parser.parse_args()\n #\n d_config = request.get_json()\n # Lo debo re-serializar para que la BD no salte.\n # https://stackoverflow.com/questions/26745519/converting-dictionary-to-json\n #\n jd_config = json.dumps(d_config)\n bdsql = BD_SQL_BASE()\n d_res = bdsql.insert_configuration(args['unit'], jd_config)\n if not d_res.get('res',False):\n bdsql.close()\n return {'rsp':'ERROR', 'msg':'Error en pgsql'},500\n # \n return {'rsp':'OK'}, 200\n\nclass GetAllUnits(Config):\n\n def get(self):\n '''\n Genera un listado de todas las uniades configuradas.\n '''\n #\n bdsql = BD_SQL_BASE()\n d_res = bdsql.read_allunits()\n if not d_res.get('res',False):\n bdsql.close()\n return {'rsp':'ERROR', 'msg':'Error en pgsql'},500\n #\n rp = d_res.get('rp',None)\n if rp.rowcount == 0:\n app.logger.info( f'(110) ApiCONF_WARN001: No config rcd in SQL')\n bdsql.close()\n return {},204\n\n l_unidades = []\n for row in rp.fetchall():\n l_unidades.append(row[0])\n\n l_unidades = sorted(l_unidades)\n nro_unidades = len(l_unidades)\n d_rsp = {'nro_unidades':nro_unidades, 'l_unidades':l_unidades}\n return d_rsp,200\n\nclass Uid2id(Resource):\n\n def get(self):\n '''\n '''\n parser = reqparse.RequestParser()\n parser.add_argument('uid',type=str,location='args',required=True)\n args=parser.parse_args()\n uid = args['uid']\n #\n bdsql = BD_SQL_BASE()\n d_res = bdsql.read_uid(uid)\n if not d_res.get('res',False):\n bdsql.close()\n return {'rsp':'ERROR', 'msg':'Error en pgsql'},500\n #\n rp = d_res.get('rp',None)\n if rp.rowcount == 0:\n app.logger.info( f'(112) ApiCONF_WARN001: No config rcd in SQL')\n bdsql.close()\n return {},204\n\n row = rp.fetchone()\n unit_id = row[0]\n bdsql.close()\n d_resp = {'uid': uid, 'id':unit_id }\n return d_resp,200\n \n def put(self):\n '''\n Crea/actualiza la configuracion de una unidad.\n Recibimos un json que almacenamos.\n No lo chequeamos !!!\n '''\n d_params = request.get_json()\n if 'uid' not in d_params:\n app.logger.info( f'(113) ApiCONF_ERR009: No UID in request_json_data')\n return {'Err':'No UID'}, 406\n #\n if 'id' not in d_params:\n app.logger.info( f'(114) ApiCONF_ERR010: No ID in request_json_data')\n return {'Err':'No ID'}, 406\n # \n if d_params['id'] == 'DEFAULT':\n app.logger.info( f'(115) ApiCONF_ERR013: No ID no puede ser DEFAULT')\n return {'Err':'ID no puede ser DEFAULT'}, 406\n \n bdsql = BD_SQL_BASE()\n d_res = bdsql.insert_uid( d_params['id'], d_params['uid'] )\n if not d_res.get('res',False):\n bdsql.close()\n return {'rsp':'ERROR', 'msg':'Error en pgsql'},500\n #\n return {'rsp':'OK'}, 200\n \nclass Help(Resource):\n\n def get(self):\n ''' Retorna la descripcion de los metodos disponibles\n '''\n d_options = {\n 'GET /apiconf/versiones':'Retorna una lista con todas las versiones que se manejan',\n 'GET /apiconf/template':'Retorna el template de la version indicada',\n 'GET /apiconf/config':' Retorna la configuracion de la unidad solicitada',\n 'POST /apiconf/config':'Crea/Actualiza la configuracion de la unidad indicada',\n 'GET /apiconf/unidades':' Retorna una lista con todas las unidades configuradas',\n }\n return d_options, 200\n\napi.add_resource( Kill, '/apiconf/kill')\napi.add_resource( Test, '/apiconf/test')\napi.add_resource( Ping, '/apiconf/ping')\napi.add_resource( Help, '/apiconf/help')\napi.add_resource( GetVersiones, '/apiconf/versiones')\napi.add_resource( GetTemplate, '/apiconf/template')\napi.add_resource( GetAllUnits, '/apiconf/unidades')\napi.add_resource( Config, '/apiconf/config')\napi.add_resource( Uid2id, '/apiconf/uid2id')\n\nif __name__ != '__main__':\n gunicorn_logger = logging.getLogger('gunicorn.error')\n app.logger.handlers = gunicorn_logger.handlers\n app.logger.setLevel(gunicorn_logger.level)\n\n app.logger.info( f'Starting APICONF: SQL_HOST={PGSQL_HOST}, SQL_PORT={PGSQL_PORT}' )\n\nif __name__ == '__main__':\n PGSQL_HOST = '127.0.0.1'\n app.run(host='0.0.0.0', port=5200, debug=True)\n\n\n\n", "repo_name": "ppeluffo/APICOMMSV3", "sub_path": "apiconf/apiconf.py", "file_name": "apiconf.py", "file_ext": "py", "file_size_in_byte": 18879, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "os.environ.get", "line_number": 40, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 40, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 41, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 41, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 42, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 42, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 43, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 43, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 44, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 44, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 46, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 46, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 47, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 47, "usage_type": "attribute"}, {"api_name": "flask.Flask", "line_number": 51, "usage_type": "call"}, {"api_name": "flask_restful.Api", "line_number": 52, "usage_type": "call"}, {"api_name": "sqlalchemy.create_engine", "line_number": 75, "usage_type": "call"}, {"api_name": "sqlalchemy.pool.NullPool", "line_number": 75, "usage_type": "name"}, {"api_name": "sqlalchemy.exc.SQLAlchemyError", "line_number": 76, "usage_type": "name"}, {"api_name": "sqlalchemy.exc.SQLAlchemyError", "line_number": 83, "usage_type": "name"}, {"api_name": "sqlalchemy.text", "line_number": 107, "usage_type": "call"}, {"api_name": "sqlalchemy.text", "line_number": 118, "usage_type": "call"}, {"api_name": "sqlalchemy.text", "line_number": 149, "usage_type": "call"}, {"api_name": "sqlalchemy.text", "line_number": 165, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 252, "usage_type": "name"}, {"api_name": "flask_restful.Resource", "line_number": 260, "usage_type": "name"}, {"api_name": "flask_restful.Resource", "line_number": 272, "usage_type": "name"}, {"api_name": "flask_restful.Resource", "line_number": 287, "usage_type": "name"}, {"api_name": "flask_restful.reqparse.RequestParser", "line_number": 299, "usage_type": "call"}, {"api_name": "flask_restful.reqparse", "line_number": 299, "usage_type": "name"}, {"api_name": "apiconf_templates.DLG_CONF_TEMPLATE.keys", "line_number": 308, "usage_type": "call"}, {"api_name": "apiconf_templates.DLG_CONF_TEMPLATE", "line_number": 308, "usage_type": "name"}, {"api_name": "apiconf_templates.DLG_CONF_TEMPLATE.keys", "line_number": 310, "usage_type": "call"}, {"api_name": "apiconf_templates.DLG_CONF_TEMPLATE", "line_number": 310, "usage_type": "name"}, {"api_name": "apiconf_templates.DLG_CONF_TEMPLATE", "line_number": 313, "usage_type": "name"}, {"api_name": "apiconf_templates.PLC_CONF_TEMPLATE.keys", "line_number": 319, "usage_type": "call"}, {"api_name": "apiconf_templates.PLC_CONF_TEMPLATE", "line_number": 319, "usage_type": "name"}, {"api_name": "apiconf_templates.PLC_CONF_TEMPLATE.keys", "line_number": 321, "usage_type": "call"}, {"api_name": "apiconf_templates.PLC_CONF_TEMPLATE", "line_number": 321, "usage_type": "name"}, {"api_name": "apiconf_templates.PLC_CONF_TEMPLATE", "line_number": 324, "usage_type": "name"}, {"api_name": "flask_restful.Resource", "line_number": 330, "usage_type": "name"}, {"api_name": "flask_restful.reqparse.RequestParser", "line_number": 338, "usage_type": "call"}, {"api_name": "flask_restful.reqparse", "line_number": 338, "usage_type": "name"}, {"api_name": "apiconf_templates.DLG_CONF_TEMPLATE.keys", "line_number": 344, "usage_type": "call"}, {"api_name": "apiconf_templates.DLG_CONF_TEMPLATE", "line_number": 344, "usage_type": "name"}, {"api_name": "apiconf_templates.PLC_CONF_TEMPLATE.keys", "line_number": 349, "usage_type": "call"}, {"api_name": "apiconf_templates.PLC_CONF_TEMPLATE", "line_number": 349, "usage_type": "name"}, {"api_name": "flask_restful.Resource", "line_number": 355, "usage_type": "name"}, {"api_name": "collections.abc.MutableMapping", "line_number": 364, "usage_type": "argument"}, {"api_name": "flask_restful.reqparse.RequestParser", "line_number": 387, "usage_type": "call"}, {"api_name": "flask_restful.reqparse", "line_number": 387, "usage_type": "name"}, {"api_name": "flask_restful.reqparse.RequestParser", "line_number": 414, "usage_type": "call"}, {"api_name": "flask_restful.reqparse", "line_number": 414, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 418, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 418, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 422, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 459, "usage_type": "name"}, {"api_name": "flask_restful.reqparse.RequestParser", "line_number": 464, "usage_type": "call"}, {"api_name": "flask_restful.reqparse", "line_number": 464, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 493, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 493, "usage_type": "name"}, {"api_name": "flask_restful.Resource", "line_number": 514, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 539, "usage_type": "call"}]} +{"seq_id": "17281934975", "text": "import boto3\nimport click\nfrom botocore.exceptions import ClientError\n\nsession = boto3.Session(profile_name ='Waqar')\ns3 = session.resource('s3')\n\n@click.group()\ndef cli():\n \"S3 all options:\"\n pass\n\n@cli.command('List_Buckets')\ndef List_Buckets():\n \"List all buckets in profile\"\n for bucket in s3.buckets.all():\n print(bucket)\n\n@cli.command('List_objects')\n@click.argument('bucket')\ndef List_objects(bucket):\n \"List objects\"\n for obj in s3.Bucket(bucket).objects.all():\n print(obj)\n\n@cli.command('Setup_bucket_static Website')\n@click.argument('bucket')\ndef Setup_bucket_static(bucket):\n \"Setup bucket(Create and configure S3)\"\n s3_bucket = None\n try: \n s3_bucket = s3.create_bucket(\n Bucket=bucket,\n CreateBucketConfiguration={\n 'LocationConstraint': session.region_name\n }\n )\n except ClientError as e:\n if e.response['Error']['Code'] == 'BucketAlreadyOwnedByYou':\n s3_bucket = s3.Bucket(bucket)\n else:\n raise e\n\n policy = \"\"\"\n {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"PublicReadGetObject\",\n \"Effect\": \"Allow\",\n \"Principal\": \"*\",\n \"Action\": [\n \"s3:GetObject\"\n ],\n \"Resource\": [\n \"arn:aws:s3:::%s/*\"\n ]\n }\n ]\n }\n \"\"\" % s3_bucket.name\n policy = policy.strip()\n pol = s3_bucket.policy()\n pol.put(Policy=policy)\n\n ws = s3_bucket.Website()\n ws.put(WebsiteConfiguration={\n 'ErrorDocument': {\n 'key': 'error.html'\n },\n 'IndexDocument': {\n 'Suffix': 'index.html'\n }\n })\n\nif __name__ == '__main__':\n cli()\n\n", "repo_name": "waqaransari03/AWS-Python-Automation-Boto3", "sub_path": "testing.py", "file_name": "testing.py", "file_ext": "py", "file_size_in_byte": 1899, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "boto3.Session", "line_number": 5, "usage_type": "call"}, {"api_name": "click.group", "line_number": 8, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 20, "usage_type": "call"}, {"api_name": "botocore.exceptions.ClientError", "line_number": 38, "usage_type": "name"}, {"api_name": "click.argument", "line_number": 27, "usage_type": "call"}]} +{"seq_id": "13340275235", "text": "from django import forms\nfrom .models import ContactProfile\n \n\nclass ContactForm(forms.ModelForm):\n class Meta:\n model = ContactProfile\n fields = ('name', 'email', 'message','subject', 'phone')\n\n name = forms.CharField(max_length=100, required=True,\n widget=forms.TextInput(attrs={\n \n 'placeholder':\"Name\",\n 'name':\"name\",\n 'id':\"name\",\n 'autocomplete':\"off\",\n 'required':'required'\n }))\n email = forms.EmailField(max_length=254, required=True, \n widget=forms.TextInput(attrs={\n \n 'id':\"emailHelp\",\n 'name':\"emailHelp\",\n 'placeholder':\"Email\",\n 'autocomplete':\"off\",\n 'required':'required',\n }))\n \n phone = forms.CharField(max_length=100, required=True,\n widget=forms.TextInput(attrs={\n \n \n \"type\":\"tel\",\n \"placeholder\":\"Phone\",\n \"name\":\"phone\",\n \"id\":\"phone\",\n 'required':'required'\n }))\n subject = forms.CharField(max_length=100, required=True,\n widget=forms.TextInput(attrs={\n \n \n \"name\":\"subject\",\n \"placeholder\":\"Subject\",\n \"id\":\"subject\"\n }))\n \n \n message = forms.CharField(max_length=1000, required=True, \n widget=forms.Textarea(attrs={\n \n 'placeholder':\"Message\",\n 'rows':\"3\",\n 'name':\"comments\",\n 'id':\"comments\"\n \n }))\n\n\n\t", "repo_name": "Mukiibi-G-J/-Portfolio", "sub_path": "main/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 1686, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.forms.ModelForm", "line_number": 5, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 5, "usage_type": "name"}, {"api_name": "models.ContactProfile", "line_number": 7, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 10, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 10, "usage_type": "name"}, {"api_name": "django.forms.TextInput", "line_number": 11, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 11, "usage_type": "name"}, {"api_name": "django.forms.EmailField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 19, "usage_type": "name"}, {"api_name": "django.forms.TextInput", "line_number": 20, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 20, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 29, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 29, "usage_type": "name"}, {"api_name": "django.forms.TextInput", "line_number": 30, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 30, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 39, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 39, "usage_type": "name"}, {"api_name": "django.forms.TextInput", "line_number": 40, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 40, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 49, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 49, "usage_type": "name"}, {"api_name": "django.forms.Textarea", "line_number": 50, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 50, "usage_type": "name"}]} +{"seq_id": "73117157181", "text": "from collections import defaultdict\nfrom typing import Any\nfrom numpy import ndarray\n\nimport numpy as np\n\n\nclass Agent:\n def __init__(self, learning_rate: float, initial_epsilon: float, epsilon_decay: float, final_epsilon: float,\n default_q_value_factory, existent_q_values: [tuple[int, int], ndarray], action_factory,\n discount_factor: float = 0.95):\n self.q_values = defaultdict(default_q_value_factory, existent_q_values)\n\n self.lr = learning_rate\n self.discount_factor = discount_factor\n\n self.epsilon = initial_epsilon\n self.epsilon_decay = epsilon_decay\n self.final_epsilon = final_epsilon\n\n self.training_error = []\n self.action_factory = action_factory\n\n def get_action(self, obs: Any) -> int:\n if np.random.random() < self.epsilon:\n return self.action_factory()\n\n return int(np.argmax(self.q_values[obs]))\n\n def update(self, obs: Any, action: int, reward: float, terminated: bool,\n next_obs: [int, int, bool]):\n future_q_value = (not terminated) * np.max(self.q_values[next_obs])\n temporal_difference = reward + self.discount_factor * future_q_value - self.q_values[obs][action]\n\n self.q_values[obs][action] = self.q_values[obs][action] + self.lr * temporal_difference\n self.training_error.append(temporal_difference)\n\n def decay_epsilon(self):\n self.epsilon = max(self.final_epsilon, self.epsilon - self.epsilon_decay)\n", "repo_name": "LerinRuss/Learning", "sub_path": "Python-Projects/Gym/src/agent.py", "file_name": "agent.py", "file_ext": "py", "file_size_in_byte": 1503, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "numpy.ndarray", "line_number": 10, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 12, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 24, "usage_type": "name"}, {"api_name": "numpy.random.random", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 25, "usage_type": "attribute"}, {"api_name": "numpy.argmax", "line_number": 28, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 30, "usage_type": "name"}, {"api_name": "numpy.max", "line_number": 32, "usage_type": "call"}]} +{"seq_id": "74370773183", "text": "#!/home/stephan/.virtualenvs/g3/bin/python\n\nimport guck3.__main__\nimport os\nimport datetime\nimport sys\nfrom setproctitle import setproctitle\n\nsetproctitle(\"g3.\" + os.path.basename(__file__))\n\n__version__ = \"3.2.4 master\"\nos.environ[\"GUCK3_VERSION\"] = __version__\n\ntry:\n startmode = sys.argv[1]\nexcept Exception:\n startmode = \"systemd\"\nif startmode not in [\"dev\", \"systemd\"]:\n startmode = \"dev\"\n\nexitcode = 3\nwhile exitcode == 3:\n exitcode = guck3.__main__.run(startmode=startmode)\n if exitcode == 3:\n trstr = str(datetime.datetime.now()) + \": RESTART - \"\n else:\n trstr = str(datetime.datetime.now()) + \": SHUTDOWN - \"\n print(trstr + \"GUCK3 exited with return code:\", exitcode)\n if exitcode == 3:\n print(trstr + \"Restarting GUCK3 ...\")\n print()\nprint(trstr + \"Exit GUCK3\")\n", "repo_name": "dermatty/GUCK3", "sub_path": "guck3.py", "file_name": "guck3.py", "file_ext": "py", "file_size_in_byte": 824, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "setproctitle.setproctitle", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 12, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 15, "usage_type": "attribute"}, {"api_name": "guck3.__main__.__main__.run", "line_number": 23, "usage_type": "call"}, {"api_name": "guck3.__main__.__main__", "line_number": 23, "usage_type": "attribute"}, {"api_name": "guck3.__main__", "line_number": 23, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 25, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 25, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 27, "usage_type": "attribute"}]} +{"seq_id": "45106625210", "text": "import re, contractions, nltk, spacy\nimport numpy as np\nimport pandas as pd\nfrom nltk.corpus import stopwords\n\ndialogs = pd.read_csv(\"data/data.csv\", names=[\"msg\"], header=None, ) #nrows=90)\n#dialogs = dialogs.iloc[0:500]\n\n# remove url\ndialogs['msg'] = dialogs['msg'].apply(lambda x: re.split('https:\\/\\/.*', str(x))[0])\n\n# remove hashtags and mentions\ndialogs['msg'] = dialogs['msg'].apply(lambda x: ' '.join(re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)\",\" \",x).split()))\n\n# Remove punctuation\ndialogs['msg'] = dialogs['msg'].map(lambda x: re.sub('[,\\.!?]', ' ', x))\n\n# removing numbers from strings of specified \ndialogs['msg'] = dialogs['msg'].str.replace('\\d+', '')\n\n# remove emoticons\nfilter_char = lambda c: ord(c) < 256\ndialogs['msg'] = dialogs['msg'].apply(lambda x: ''.join(filter(filter_char, x)))\n\n# remove contractions\ndialogs['msg'] = dialogs['msg'].apply(lambda x: contractions.fix(x))\n\n# Unique words\n#uniqueWords = list(set(' '.join(dialogs['msg']).lower().split(' ')))\n#count = len(uniqueWords)\n\n# Total words\n#dialogs['total_words'] = dialogs['msg'].str.split().str.len()\n#totalWordCount = dialogs['total_words'].sum()\n\n# Remove stopwords\nstopwords = nltk.corpus.stopwords.words('english')\ndialogs['msg'] = dialogs['msg'].apply(lambda x: ' '.join([w for w in x.split() if w.lower() not in stopwords]))\n\n# lemmatization\nnlp = spacy.load('en_core_web_sm', disable=['parser', 'ner'])\nallowed_postags=['NOUN',]\ndialogs['msg'] = dialogs['msg'].apply(lambda x: ' '.join([token.lemma_ if token.lemma_ not in ['-PRON-'] else '' for token in nlp(x) if token.pos_ in allowed_postags]))\n\n# drop empty strings\ndialogs['msg'].replace('', np.nan, inplace=True)\ndialogs.dropna(subset=['msg'], inplace=True)\n\n#store and read the data file\ndialogs.to_pickle('./data/all_docs.pkl')\n", "repo_name": "b00tss/nlp_app", "sub_path": "ml_scripts/clean_data.py", "file_name": "clean_data.py", "file_ext": "py", "file_size_in_byte": 1793, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "pandas.read_csv", "line_number": 6, "usage_type": "call"}, {"api_name": "re.split", "line_number": 10, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 13, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 16, "usage_type": "call"}, {"api_name": "contractions.fix", "line_number": 26, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 37, "usage_type": "name"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 37, "usage_type": "call"}, {"api_name": "nltk.corpus", "line_number": 37, "usage_type": "attribute"}, {"api_name": "nltk.corpus.stopwords", "line_number": 38, "usage_type": "name"}, {"api_name": "spacy.load", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 46, "usage_type": "attribute"}]} +{"seq_id": "13219133959", "text": "from django.shortcuts import render, HttpResponseRedirect\nfrom .models import Product, ProductCategory, Basket\nfrom django.contrib.auth.decorators import login_required\n\n\ndef index(request):\n return render(request, 'products/index.html')\n\n\ndef products(request):\n context = {'title': 'Store',\n 'products': Product.objects.all(),\n 'categories': ProductCategory.objects.all()}\n return render(request, 'products/products.html', context)\n\n\n@login_required\ndef basket_add(request, product_id):\n product = Product.objects.get(id=product_id)\n baskets = Basket.objects.filter(user=request.user, product=product)\n\n if not baskets.exists():\n Basket.objects.create(user=request.user, product=product, quantity=1)\n else:\n baskets = baskets.first()\n baskets.quantity += 1\n baskets.save()\n return HttpResponseRedirect(request.META['HTTP_REFERER'])\n\n\n@login_required\ndef basket_remove(request, basket_id):\n basket = Basket.objects.get(id=basket_id)\n basket.delete()\n return HttpResponseRedirect(request.META['HTTP_REFERER'])", "repo_name": "AntonPopov90/django_store", "sub_path": "store/products/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1098, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.shortcuts.render", "line_number": 7, "usage_type": "call"}, {"api_name": "models.Product.objects.all", "line_number": 12, "usage_type": "call"}, {"api_name": "models.Product.objects", "line_number": 12, "usage_type": "attribute"}, {"api_name": "models.Product", "line_number": 12, "usage_type": "name"}, {"api_name": "models.ProductCategory.objects.all", "line_number": 13, "usage_type": "call"}, {"api_name": "models.ProductCategory.objects", "line_number": 13, "usage_type": "attribute"}, {"api_name": "models.ProductCategory", "line_number": 13, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 14, "usage_type": "call"}, {"api_name": "models.Product.objects.get", "line_number": 19, "usage_type": "call"}, {"api_name": "models.Product.objects", "line_number": 19, "usage_type": "attribute"}, {"api_name": "models.Product", "line_number": 19, "usage_type": "name"}, {"api_name": "models.Basket.objects.filter", "line_number": 20, "usage_type": "call"}, {"api_name": "models.Basket.objects", "line_number": 20, "usage_type": "attribute"}, {"api_name": "models.Basket", "line_number": 20, "usage_type": "name"}, {"api_name": "models.Basket.objects.create", "line_number": 23, "usage_type": "call"}, {"api_name": "models.Basket.objects", "line_number": 23, "usage_type": "attribute"}, {"api_name": "models.Basket", "line_number": 23, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponseRedirect", "line_number": 28, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 17, "usage_type": "name"}, {"api_name": "models.Basket.objects.get", "line_number": 33, "usage_type": "call"}, {"api_name": "models.Basket.objects", "line_number": 33, "usage_type": "attribute"}, {"api_name": "models.Basket", "line_number": 33, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponseRedirect", "line_number": 35, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 31, "usage_type": "name"}]} +{"seq_id": "38380640579", "text": "from pathlib import Path\n\nimport seaborn as sns\n\nimport src\nfrom src.misc.timetables import *\nfrom src.run_sim.def_get_params import get_spotpy_params\nfrom src.sim.sim import Sim\n\n\n##################################################################################\n# parameter setting\n##################################################################################\n\n# set a state code (2 = Hamburg, 8 = Baden-Wuerttemberg, 9 = Bavaria, 10 = Saarland) \nSTATE = 9\n\n# set a NPI-timetable\n# (possible options: timetable_default, timetable_no_reduction_of_work,timetable_no_homeoffice, timetable_no_quarantine, timetable_open_kitas, timetable_open_schools, timetable_open_universities, timetable_open_schools_kitas, timetable_open_education)\nTIMETABLE = timetable_default\n\n# set the number of agents\nN = 100000\n\n# set the number of initially infected agents\nN_INITIAL_INFECTIONS = 50\n\n# set the number of replications\nN_INTERNAL_RUNS = 60\n\n# set a name for the simulation\nNAME_OF_RUN = \"baseline_scenario_bavaria\"\n\n# number of cores used for parallel computation\nN_CORES = 15\n\n##################################################################################\n# model setup and execution (do not touch)\n##################################################################################\n\nassert STATE in (2, 8, 9, 10), \"STATE has to be one of the following integers: 2, 8, 9, 10\"\n\nif STATE == 2:\n spotpy_params = get_spotpy_params(Path.joinpath(src.PATH, \"important_outputs\", \"params\", \"LHS_HH_2021_01_22.csv\"))\nelif STATE == 8:\n spotpy_params = get_spotpy_params(Path.joinpath(src.PATH, \"important_outputs\", \"params\", \"LHS_BW_2021_01_20.csv\"))\nelif STATE == 9:\n spotpy_params = get_spotpy_params(Path.joinpath(src.PATH, \"important_outputs\", \"params\", \"LHS_BY_2021_01_14.csv\"))\nelif STATE == 10:\n spotpy_params = get_spotpy_params(Path.joinpath(src.PATH, \"important_outputs\", \"params\", \"LHS_SL_2021_01_20.csv\"))\n\nINFECTION_PROB = spotpy_params[\"infection_prob\"]\nN_TICKS_TO_QUARANTINE = spotpy_params[\"ticks_to_quarantine\"]\nN_RANDOM_INFECTIONS = 0\nDISPLAY_SIMULATION = False\nSAVE_OUTPUT = True\n\nparams = [\n INFECTION_PROB,\n N_INITIAL_INFECTIONS,\n N,\n N_RANDOM_INFECTIONS,\n TIMETABLE,\n N_TICKS_TO_QUARANTINE,\n N_INTERNAL_RUNS,\n NAME_OF_RUN,\n SAVE_OUTPUT,\n DISPLAY_SIMULATION,\n ]\n\nmodel = Sim(STATE, n_cores=N_CORES)\noutput = model.run(params)", "repo_name": "mariuzka/covid19_sim", "sub_path": "src/run_sim/run_simulation.py", "file_name": "run_simulation.py", "file_ext": "py", "file_size_in_byte": 2391, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "src.run_sim.def_get_params.get_spotpy_params", "line_number": 44, "usage_type": "call"}, {"api_name": "pathlib.Path.joinpath", "line_number": 44, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 44, "usage_type": "name"}, {"api_name": "src.PATH", "line_number": 44, "usage_type": "attribute"}, {"api_name": "src.run_sim.def_get_params.get_spotpy_params", "line_number": 46, "usage_type": "call"}, {"api_name": "pathlib.Path.joinpath", "line_number": 46, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 46, "usage_type": "name"}, {"api_name": "src.PATH", "line_number": 46, "usage_type": "attribute"}, {"api_name": "src.run_sim.def_get_params.get_spotpy_params", "line_number": 48, "usage_type": "call"}, {"api_name": "pathlib.Path.joinpath", "line_number": 48, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 48, "usage_type": "name"}, {"api_name": "src.PATH", "line_number": 48, "usage_type": "attribute"}, {"api_name": "src.run_sim.def_get_params.get_spotpy_params", "line_number": 50, "usage_type": "call"}, {"api_name": "pathlib.Path.joinpath", "line_number": 50, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 50, "usage_type": "name"}, {"api_name": "src.PATH", "line_number": 50, "usage_type": "attribute"}, {"api_name": "src.sim.sim.Sim", "line_number": 71, "usage_type": "call"}]} +{"seq_id": "24947899710", "text": "#!/usr/bin/env python3\n\nimport qlat as q\nimport numpy as np\nimport functools\n\nq.begin_with_mpi()\n\nq.default_g_jk_kwargs[\"jk_type\"] = \"rjk\"\nq.default_g_jk_kwargs[\"n_rand_sample\"] = 1024\nq.default_g_jk_kwargs[\"rng_state\"] = q.RngState(\"rejk\")\n\n@functools.cache\ndef get_trajs(job_tag):\n return list(range(25))\n\nrs = q.RngState(\"seed\")\njob_tag = \"test1\"\ntrajs = get_trajs(job_tag)\n\ndata_list = np.zeros((len(trajs), 5,)) # can be list or np.array\nrs.g_rand_fill(data_list)\njk_list = q.g_jk(data_list)\njk_idx_list = [ \"avg\", ] + [ (job_tag, traj) for traj in trajs ]\njk_list = q.g_rejk(jk_list, jk_idx_list)\navg, err = q.g_jk_avg_err(jk_list)\n\nq.displayln_info(f\"CHECK: {avg}\")\nq.displayln_info(f\"CHECK: {err}\")\n\nq.displayln_info(f\"CHECK: finished successfully.\")\n\nq.end_with_mpi()\n", "repo_name": "jinluchang/Qlattice", "sub_path": "examples-py/jackknife-random.py", "file_name": "jackknife-random.py", "file_ext": "py", "file_size_in_byte": 780, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "24", "api": [{"api_name": "qlat.begin_with_mpi", "line_number": 7, "usage_type": "call"}, {"api_name": "qlat.default_g_jk_kwargs", "line_number": 9, "usage_type": "attribute"}, {"api_name": "qlat.default_g_jk_kwargs", "line_number": 10, "usage_type": "attribute"}, {"api_name": "qlat.default_g_jk_kwargs", "line_number": 11, "usage_type": "attribute"}, {"api_name": "qlat.RngState", "line_number": 11, "usage_type": "call"}, {"api_name": "functools.cache", "line_number": 13, "usage_type": "attribute"}, {"api_name": "qlat.RngState", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 21, "usage_type": "call"}, {"api_name": "qlat.g_jk", "line_number": 23, "usage_type": "call"}, {"api_name": "qlat.g_rejk", "line_number": 25, "usage_type": "call"}, {"api_name": "qlat.g_jk_avg_err", "line_number": 26, "usage_type": "call"}, {"api_name": "qlat.displayln_info", "line_number": 28, "usage_type": "call"}, {"api_name": "qlat.displayln_info", "line_number": 29, "usage_type": "call"}, {"api_name": "qlat.displayln_info", "line_number": 31, "usage_type": "call"}, {"api_name": "qlat.end_with_mpi", "line_number": 33, "usage_type": "call"}]} +{"seq_id": "15497792522", "text": "#!usr/bin/env/python \n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\nimport os \nimport tensorflow as tf\nfrom tensorflow.python.ops import rnn \nfrom matplotlib import pyplot as plt\n\n\nclass MyLSTM(object):\n def __init__(self,layers = [4,15,1],time_step = 20,lr = 0.0006,epoch = 5 ):\n super(MyLSTM,self).__init__()\n self.dir = os.path.join(os.path.dirname(__file__),'model3/')\n self.path = self.dir + 'stockModel.ckpt'\n self.time_step = 20 #时间步\n self.rnn_unit = layers[1] #hidden layer units\n self.batch_size = 60 #每一批次训练多少个样例\n self.input_size = layers[0] #输入层维度\n self.output_size = layers[2] #输出层维度\n self.lr = 0.0006 #学习率\n self.epoch = epoch #训练周期\n self.X = tf.placeholder(tf.float32, shape=[None,self.time_step,self.input_size])\n self.Y = tf.placeholder(tf.float32, shape=[None,self.time_step,self.output_size])\n\n self.weights = {\n 'in':tf.Variable(tf.truncated_normal([self.input_size,self.rnn_unit], stddev = 0.1)),\n 'out':tf.Variable(tf.truncated_normal([self.rnn_unit,self.output_size],stddev = 0.1))\n }\n\n self.biases = {\n 'in':tf.Variable(tf.constant(0.1,shape=[self.rnn_unit,])),\n 'out':tf.Variable(tf.constant(0.1,shape=[self.output_size,]))\n }\n\n\n def read_data(self,filename):\n pass\n\n def lstm_model(self,init_state_size):\n w_in = self.weights['in']\n b_in = self.biases['in'] \n # print(\"lstm X = \",X.get_shape()) \n my_input = tf.reshape(self.X,[-1,self.input_size]) #需要将tensor转成2维进行计算,计算后的结果作为隐藏层的输入\n # print(\"my_input.shape = \",my_input.get_shape())\n input_rnn = tf.nn.tanh(tf.matmul(my_input,w_in)+b_in)\n # print(\"input_rnn.shape ----1 = \",input_rnn.get_shape())\n input_rnn = tf.reshape(input_rnn,[-1,self.time_step,self.rnn_unit]) #将tensor转成3维,作为lstm cell的输入\n # print(\"input_rnn.shape ----2 = \",input_rnn.get_shape())\n cell=tf.nn.rnn_cell.BasicLSTMCell(self.rnn_unit)\n init_state = cell.zero_state(init_state_size,dtype=tf.float32)\n output_rnn,final_states = rnn.dynamic_rnn(cell, input_rnn,initial_state=init_state, dtype=tf.float32) #output_rnn是记录lstm每个输出节点的结果,final_states是最后一个cell的结果\n output = tf.reshape(output_rnn,[-1,self.rnn_unit]) #作为输出层的输入\n # print(\"output.shape = \",output.get_shape())\n w_out = self.weights['out']\n b_out = self.biases['out']\n predict = tf.matmul(output,w_out)+b_out\n # print(\"predict.shape = \",predict.get_shape())\n # print(\"-\"*30 + ' lstm ' + '-'*30)\n return predict,final_states\n\n def train(self,x_train,y_train):\n shape = x_train.shape # (1000,20,4) (1000,20,1)\n \n pred,_= self.lstm_model(init_state_size = 1)\n #损失函数\n loss = tf.reduce_mean(tf.square(tf.reshape(pred,[-1])-tf.reshape(self.Y, [-1])))\n train_op = tf.train.AdamOptimizer(self.lr).minimize(loss)\n \n with tf.Session() as sess:\n sess.run(tf.initialize_all_variables())\n saver = tf.train.Saver()\n #重复训练10000次\n try:\n saver.restore(sess,self.path)\n except Exception as ex:\n print(\"[Exception Information] \",str(ex))\n for i in range(self.epoch):\n for step in range(shape[0]):\n x_batch = x_train[step:step+1,:,:]\n y_batch = y_train[step:step+1,:,:]\n # print(\"x_batch = \",x_batch.shape,\"y_batch = \",y_batch.shape)\n sess.run(train_op,feed_dict = {self.X: x_batch,self.Y: y_batch})\n _,loss_=sess.run([train_op,loss],feed_dict={self.X:x_batch,self.Y: y_batch})\n # break\n # break\n print(\"i = \",i,\"loss_= \",loss_)\n sess.run(pred,feed_dict = {self.X: x_batch})\n saver.save(sess,self.path)\n\n\n def evaluate(self,x_test,y_test):\n shape = x_test.shape # (N,20,4) (N,20,1)\n predict_op,_ = self.lstm_model(init_state_size = 1) \n with tf.Session() as sess:\n #参数恢复\n sess.run(tf.initialize_all_variables())\n saver=tf.train.Saver()\n saver.restore(sess,self.path)\n # saver.restore(sess,'./model2/model2.ckpt')\n y_real = []\n y_pred = []\n for step in range(shape[0]):\n # print(\"step = \",step)\n x = x_test[step:step+1,:,:]\n y = y_test[step:step+1,:,:].reshape((-1))\n # print(\"x.shape = \",x.shape,y.shape)\n prob = sess.run(predict_op,feed_dict={self.X:x}) \n predict = prob.reshape((-1))\n # print(\"predict.shape = \",predict.shape)\n y_real.append(y[1])\n y_pred.append(predict[1])\n \n #以折线图表示结果\n \n plt.figure()\n plt.plot(list(range(len(y_real))),y_real,color='r',label = 'y_real')\n plt.plot(list(range(len(y_pred))),y_pred,color='b',label = 'y_pred')\n plt.legend()\n plt.grid(True)\n plt.show()\n\n def predict(self,x_test):\n predict_op,_ = self.lstm_model(init_state_size = 1) \n with tf.Session() as sess:\n #参数恢复\n sess.run(tf.initialize_all_variables())\n saver=tf.train.Saver()\n saver.restore(sess,self.path)\n # saver.restore(sess,'./model2/model2.ckpt')\n test_predict=[]\n y_predict = []\n for step in range(len(test_x)-1):\n x = x_test[step:step+1,:,:]\n y = y_test[step:step+1,:,:].reshape((-1))\n # print(\"x.shape = \",x.shape,y.shape)\n prob = sess.run(predict_op,feed_dict={self.X:x}) \n y_predict.append(prob)\n return np.array(y_predict)\n\n\nif __name__ == '__main__':\n filename = './dataset/dataset_2.csv'\n myModel = MyLSTM()\n data = myModel.read_data(filename)\n print(\"data = \",data.shape)\n batch_index,train_x,train_y = myModel.get_train_data(data)\n mean,std,test_x,test_y = myModel.get_test_data(data)\n # myModel.train(data)\n myModel.prediction(data)", "repo_name": "ChenLiangbo/DeepLearning", "sub_path": "lstm_model/lstm_stock/model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 6737, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "os.path.join", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 15, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 24, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 24, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 25, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 25, "usage_type": "attribute"}, {"api_name": "tensorflow.Variable", "line_number": 28, "usage_type": "call"}, {"api_name": "tensorflow.truncated_normal", "line_number": 28, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 29, "usage_type": "call"}, {"api_name": "tensorflow.truncated_normal", "line_number": 29, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 45, "usage_type": "call"}, {"api_name": "tensorflow.nn.tanh", "line_number": 47, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 47, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 47, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 49, "usage_type": "call"}, {"api_name": "tensorflow.nn.rnn_cell.BasicLSTMCell", "line_number": 51, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 51, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 52, "usage_type": "attribute"}, {"api_name": "tensorflow.python.ops.rnn.dynamic_rnn", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.python.ops.rnn", "line_number": 53, "usage_type": "name"}, {"api_name": "tensorflow.float32", "line_number": 53, "usage_type": "attribute"}, {"api_name": "tensorflow.reshape", "line_number": 54, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 58, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 68, "usage_type": "call"}, {"api_name": "tensorflow.square", "line_number": 68, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 68, "usage_type": "call"}, {"api_name": "tensorflow.train.AdamOptimizer", "line_number": 69, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 69, "usage_type": "attribute"}, {"api_name": "tensorflow.Session", "line_number": 71, "usage_type": "call"}, {"api_name": "tensorflow.initialize_all_variables", "line_number": 72, "usage_type": "call"}, {"api_name": "tensorflow.train.Saver", "line_number": 73, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 73, "usage_type": "attribute"}, {"api_name": "tensorflow.Session", "line_number": 96, "usage_type": "call"}, {"api_name": "tensorflow.initialize_all_variables", "line_number": 98, "usage_type": "call"}, {"api_name": "tensorflow.train.Saver", "line_number": 99, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 99, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 117, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 117, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 118, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 121, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 122, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 122, "usage_type": "name"}, {"api_name": "tensorflow.Session", "line_number": 126, "usage_type": "call"}, {"api_name": "tensorflow.initialize_all_variables", "line_number": 128, "usage_type": "call"}, {"api_name": "tensorflow.train.Saver", "line_number": 129, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 129, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 140, "usage_type": "call"}]} +{"seq_id": "30329699409", "text": "import urllib\nfrom chargebee import util, http_request\nfrom chargebee.main import ChargeBee\nfrom chargebee import compat\nimport json\n\n\ndef send_list_request(method, url, params=None, env=None, headers=None):\n serialized = {}\n\n if params is None:\n params = {}\n\n for k, v in list(params.items()):\n if isinstance(v, list):\n v = json.dumps(v)\n serialized.update({k: v})\n return send(method, url, serialized, env, headers)\n\n\ndef send(method, url, params=None, env=None, headers=None):\n if params is None:\n params = {}\n\n env = env or ChargeBee.default_env\n\n ser_params = util.serialize(params)\n\n response, response_headers = http_request.request(method, url, env, ser_params, headers)\n\n from chargebee.result import Result\n from chargebee.list_result import ListResult\n if 'list' in response:\n return ListResult(response['list'], response.get('next_offset', None), response_headers)\n return Result(response, response_headers)\n\n\ndef uri_path(*paths):\n url = \"\"\n for path in paths:\n if path is None or len(str(path).strip()) < 1:\n raise Exception(\"Id is None or empty\")\n if compat.py_major_v >= 3:\n url = url + \"/\" + urllib.parse.quote(str(path).strip())\n else:\n url = url + \"/\" + urllib.quote(str(util.get_val(path)))\n return url\n", "repo_name": "chargebee/chargebee-python", "sub_path": "chargebee/request.py", "file_name": "request.py", "file_ext": "py", "file_size_in_byte": 1368, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 37, "dataset": "github-code", "pt": "24", "api": [{"api_name": "json.dumps", "line_number": 16, "usage_type": "call"}, {"api_name": "chargebee.main.ChargeBee.default_env", "line_number": 25, "usage_type": "attribute"}, {"api_name": "chargebee.main.ChargeBee", "line_number": 25, "usage_type": "name"}, {"api_name": "chargebee.util.serialize", "line_number": 27, "usage_type": "call"}, {"api_name": "chargebee.util", "line_number": 27, "usage_type": "name"}, {"api_name": "chargebee.http_request.request", "line_number": 29, "usage_type": "call"}, {"api_name": "chargebee.http_request", "line_number": 29, "usage_type": "name"}, {"api_name": "chargebee.list_result.ListResult", "line_number": 34, "usage_type": "call"}, {"api_name": "chargebee.result.Result", "line_number": 35, "usage_type": "call"}, {"api_name": "chargebee.compat.py_major_v", "line_number": 43, "usage_type": "attribute"}, {"api_name": "chargebee.compat", "line_number": 43, "usage_type": "name"}, {"api_name": "urllib.parse.quote", "line_number": 44, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 44, "usage_type": "attribute"}, {"api_name": "urllib.quote", "line_number": 46, "usage_type": "call"}, {"api_name": "chargebee.util.get_val", "line_number": 46, "usage_type": "call"}, {"api_name": "chargebee.util", "line_number": 46, "usage_type": "name"}]} +{"seq_id": "14132819221", "text": "#!/usr/bin/env python\n\nimport sys\nimport cv2\nimport numpy as np\nfrom pathlib import Path\nfrom sensor_msgs.msg import Image\nimport rospy\nfrom cv_bridge import CvBridge\nimport math\nfrom shapely.geometry import LineString\nfrom shapely.geometry import Point\n\n\n#\n# Perform a conversion from 2D pixel to XYZ 3D coordinates expressed in the robot frame.\n# Use it AFTER a camera calibration (which provides the necessary files : newcam_mtx.npy, R_mtx.npy, S_arr.npy and translation_vector.npy)\n#\nclass PerspectiveCalibration:\n def __init__(self, savedir, depth_image=None):\n\n if depth_image is None:\n depth_image = rospy.wait_for_message('/camera/aligned_depth_to_color/image_raw', Image)\n bridge = CvBridge()\n self.depth_image = bridge.imgmsg_to_cv2(depth_image, desired_encoding = 'passthrough')\n else:\n self.depth_image = depth_image\n\n #Calculate the histogram of the depth image to get the distance value of the table by getting the most recurrent value in the image\n self.histogram = cv2.calcHist([self.depth_image], [0], None, [1000], [1,1000])\n self.background_index = self.histogram.argmax()\n\n # load camera calibration\n self.savedir = Path(savedir)\n newcam_mtx = np.load(self.savedir / 'newcam_mtx.npy')\n self.inverse_newcam_mtx = np.linalg.inv(newcam_mtx)\n R_mtx = np.load(self.savedir / 'R_mtx.npy')\n self.inverse_R_mtx = np.linalg.inv(R_mtx)\n s_arr = np.load(self.savedir / 's_arr.npy')\n self.translation_vector = np.load(self.savedir / 'translation_vector.npy')\n self.scalingfactor = s_arr[0]\n\n def from_2d_to_3d(self, image_coordinates, depth=None):\n bridge = CvBridge()\n\n # Expected this format -> np.array([(0.0, 0.0, 30)])\n u, v = image_coordinates\n\n # Solve: From Image Pixels, find World Points\n uv_1 = np.array([[u, v, 1]], dtype=np.float32)\n uv_1 = uv_1.T\n suv_1 = self.scalingfactor * uv_1\n xyz_c = self.inverse_newcam_mtx.dot(suv_1)\n xyz_c = xyz_c - self.translation_vector\n XYZ = self.inverse_R_mtx.dot(xyz_c)\n\n uv_10 = np.array([[320, 240, 1]], dtype=np.float32)\n uv_10 = uv_10.T\n suv_10 = self.scalingfactor * uv_10\n xyz_c0 = self.inverse_newcam_mtx.dot(suv_10)\n xyz_c0 = xyz_c0 - self.translation_vector\n XYZ0 = self.inverse_R_mtx.dot(xyz_c0)\n\n #self.depth_image = rospy.wait_for_message('/camera/aligned_depth_to_color/image_raw', Image)\n #self.depth_image = bridge.imgmsg_to_cv2(self.depth_image, desired_encoding = 'passthrough')\n\n #check if the value of depth is coherent with the values of heihgt we are waiting for the table, i.e between the distance of the table + 3 mm and 12 centimeters high from the table\n #if not self.background_index + 3 > self.depth_image[v][u] > self.background_index - 120:\n # XYZ = [['a'],['b'],['c']]\n # print('Value of depth is not coherent')\n # return XYZ\n\n #This value correspond to the value of the table\n #print('self background index', self.background_index)\n\n #This value correspond to the value of distance of the pixel selected with the coordinates (v,u)\n #print('Depth value of the selected pixel : ', self.depth_image[v][u])\n\n #print('coordonnée u', u)\n #print('coordonnée v', v)\n\n #The height of the object of the selected pixel is equal to the height of the table minus the height of the pixel\n if depth is None:\n h_object = (self.background_index - self.depth_image[v][u]) / 10\n else:\n h_object = (self.background_index - depth[v][u]) / 10\n #print(\"Height of the object : \", h_object)\n\n #b_prime is the coordinates of the center of the image (in robot coordinates)\n b_prime = XYZ0\n\n #a_prime is the coordinates of the selected pixel(in robot coordinates)\n a_prime = XYZ\n\n #we calculate the distance between a_prime and b_prime(in robot coordinates)\n a_prime_b_prime = math.sqrt((a_prime[0] - b_prime[0]) ** 2 + (a_prime[1] - b_prime[1]) ** 2)\n\n #b_prime_c is the distance between the camera and the point at the center of the image\n b_prime_c = self.background_index /10\n\n #print('XYZ : ', XYZ)\n #print('A prime B prime : ', a_prime_b_prime)\n #print('b_prime_c : ', b_prime_c)\n\n\n #we use the Thales Theorem to calculate the correction necessary\n correction = abs(((h_object * a_prime_b_prime) / b_prime_c))\n\n if correction > 2.5:\n print(f'Big correction in from_2d_to_3d in perspective_calibration.py = {correction:.2f}')\n\n if correction != 0 :\n #We draw a circle with the diameter of the correction with the selected pixel as the center then we draw a line from the pixel to the center of the image\n #the intersection between those two object is the point we were really aiming at the beginning\n point_1 = Point(a_prime[0], a_prime[1])\n circle = point_1.buffer(correction).boundary\n line = LineString([(a_prime[0],a_prime[1]), (b_prime[0],b_prime[1])])\n intersection = circle.intersection(line)\n\n try:\n return intersection.coords[0][0]/100, intersection.coords[0][1]/100, h_object/100\n except Exception as e:\n print(f'An error occured in from_2d_to_3d in perspective_callibration : {e}')\n print(image_coordinates)\n return self.from_2d_to_3d(self, image_coordinates)\n\n else :\n print('aucune correction nécessaire')\n #The new coordinates of the aimed point in the robot coordinates are declared to be the coords of the intersection\n try:\n return XYZ[0]/100, XYZ[1]/100, h_object/100\n except Exception as e:\n print(f'An error occured in from_2d_to_3d in perspective_callibration : {e}')\n print(image_coordinates)\n return self.from_2d_to_3d(self, image_coordinates)\n\n\nif __name__ == '__main__':\n rospy.init_node('test_perspective_calibration')\n object = PerspectiveCalibration('/common/save/calibration/camera/camera_data')\n image_coordinates = [354, 207]\n x, y, z = object.from_2d_to_3d(image_coordinates)\n print(x, y, z)\n", "repo_name": "raiv-toulouse/raiv_camera_calibration", "sub_path": "src/raiv_camera_calibration/perspective_calibration.py", "file_name": "perspective_calibration.py", "file_ext": "py", "file_size_in_byte": 6391, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "rospy.wait_for_message", "line_number": 23, "usage_type": "call"}, {"api_name": "sensor_msgs.msg.Image", "line_number": 23, "usage_type": "argument"}, {"api_name": "cv_bridge.CvBridge", "line_number": 24, "usage_type": "call"}, {"api_name": "cv2.calcHist", "line_number": 30, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 36, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 38, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 40, "usage_type": "call"}, {"api_name": "cv_bridge.CvBridge", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 50, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 57, "usage_type": "attribute"}, {"api_name": "math.sqrt", "line_number": 96, "usage_type": "call"}, {"api_name": "shapely.geometry.Point", "line_number": 115, "usage_type": "call"}, {"api_name": "shapely.geometry.LineString", "line_number": 117, "usage_type": "call"}, {"api_name": "rospy.init_node", "line_number": 139, "usage_type": "call"}]} +{"seq_id": "7136355137", "text": "import tkinter as tk\nfrom fuzzywuzzy import process\nimport requests\n\n# Get S&P500 components in JSON format\nr = requests.get('https://pkgstore.datahub.io/core/s-and-p-500-companies/constituents_json/data'\n '/87cab5b5abab6c61eafa6dfdfa068a42/constituents_json.json')\nstock_list = r.json()\nstock_list = [{k: v for k, v in sk.items() if k == \"Name\" or k == \"Symbol\"} for sk in stock_list]\n\n\ndef find_stock(partial_name):\n return process.extract(partial_name, stock_list)\n\n\nclass SearchFrame(tk.Frame):\n def __init__(self):\n super().__init__()\n self.search_string = tk.StringVar()\n self.lb_var = tk.StringVar()\n self.lb_var.set(\"\")\n self.result_string = tk.StringVar()\n self.result_string.set(\"\")\n instr_label = tk.Label(self, text=\"Enter the stock name or code\",\n padx=10, pady=10, font=('Arial', 10))\n instr_label.grid(row=0, column=0)\n self.search_box = tk.Entry(self, textvariable=self.search_string)\n self.search_box.grid(row=1, column=0)\n self.found_lb = tk.Listbox(self, listvariable=self.lb_var, bd=0, height=5)\n\n self.result_box = tk.Label(self, textvariable=self.result_string,\n padx=10, pady=10)\n self.result_box.grid(row=3, column=0)\n self.search_box.focus()\n\n self.search_string.trace_add('write', self.change_name)\n self.found_lb.bind(\"<>\", self.select_name)\n\n # Placeholder for the list of stocks matching the search criteria\n self.found_list = []\n\n def change_name(self, *args):\n search = self.search_box.get()\n if search:\n self.found_list = find_stock(search)\n found_names = [sk[0]['Name'] for sk in self.found_list]\n self.lb_var.set(found_names)\n self.found_lb.grid(row=2, column=0, padx=10, pady=(0, 10))\n self.found_lb.select_set(0)\n self.search_box.focus()\n else:\n\n self.lb_var.set(\"\")\n self.found_lb.grid_forget()\n\n def select_name(self, event):\n select_num = self.found_lb.curselection()\n if select_num:\n select_num = select_num[0]\n self.result_string.set(self.found_list[select_num][0][\"Symbol\"])\n else:\n self.result_string.set(\"\")\n\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n sf = SearchFrame()\n sf.pack()\n root.mainloop()\n\n", "repo_name": "AndrewDales/JupyterTestProject", "sub_path": "fuzzy_wuzzy_stock_search.py", "file_name": "fuzzy_wuzzy_stock_search.py", "file_ext": "py", "file_size_in_byte": 2454, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "requests.get", "line_number": 6, "usage_type": "call"}, {"api_name": "fuzzywuzzy.process.extract", "line_number": 13, "usage_type": "call"}, {"api_name": "fuzzywuzzy.process", "line_number": 13, "usage_type": "name"}, {"api_name": "tkinter.Frame", "line_number": 16, "usage_type": "attribute"}, {"api_name": "tkinter.StringVar", "line_number": 19, "usage_type": "call"}, {"api_name": "tkinter.StringVar", "line_number": 20, "usage_type": "call"}, {"api_name": "tkinter.StringVar", "line_number": 22, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 24, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 27, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 29, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 31, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 66, "usage_type": "call"}]} +{"seq_id": "13821844415", "text": "import numpy as np\nimport torch\n\n\ndef test(loader, model, verbose=False, cls_acc=False):\n \"\"\"test accuracy of the model\n\n Args:\n loader (torch.utils.data.DataLoader): _description_\n model (torch.nn.Modules): _description_\n verbose (bool, optional): If true, print the accuracy. Defaults to False.\n cls_acc (bool, optional): If true, print accuracy of each class. Defaults to False.\n\n Returns:\n float: total accuracy\n \"\"\"\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n class_correct = np.array([0 for _ in classes])\n class_total = np.array([0 for _ in classes])\n num_correct = 0\n num_samples = 0\n\n model = model.to(device=device)\n model.eval() # set model to evaluation mode\n with torch.no_grad():\n for x, y in loader:\n x = x.to(device=device)\n y = y.to(device=device)\n scores = model(x)\n _, preds = scores.max(1)\n num_correct += (preds == y).sum()\n num_samples += preds.size(0)\n\n batch_total = torch.bincount(y).cpu().numpy()\n batch_correct = torch.bincount(y[preds == y]).cpu().numpy()\n class_total += np.pad(batch_total, (0, 10 - len(batch_total)), 'constant', constant_values=(0, 0))\n class_correct += np.pad(batch_correct, (0, 10 - len(batch_correct)), 'constant', constant_values=(0, 0))\n\n acc = float(num_correct) / num_samples\n\n if verbose:\n print(\"Total Accuracy: %.2f%%\" % (100 * acc))\n if cls_acc:\n for i, value in enumerate(classes):\n print(\"%s: %.2f%%\" % (classes[i], 100 * float(class_correct[i]) / class_total[i]))\n\n return acc\n", "repo_name": "AnotherOnezjy/HUST-CV-2023", "sub_path": "lab4/tools/test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 1829, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "torch.device", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 17, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.bincount", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.bincount", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 39, "usage_type": "call"}]} +{"seq_id": "24941236489", "text": "from six import PY3, text_type as unicode\n\nimport os\nimport sys\nimport unittest\n\nfrom robot.utils.asserts import assert_equals, assert_raises, assert_true\nfrom robot.utils.etreewrapper import ETSource, ET\nfrom robot.errors import DataError\n\nIRONPYTHON = sys.platform == 'cli'\nPATH = os.path.join(os.path.dirname(__file__), 'test_etreesource.py')\nSTARTSWITH = 'from six import'\n\n\nclass TestETSource(unittest.TestCase):\n\n def test_path_to_file(self):\n source = ETSource(PATH)\n with source as src:\n if IRONPYTHON:\n assert_equals(src, PATH)\n else:\n assert_true(src.read().startswith(STARTSWITH.encode()))\n self._verify_string_representation(source, PATH)\n if IRONPYTHON:\n assert_true(source._opened is None)\n else:\n assert_true(source._opened.closed)\n\n def test_opened_file_object(self):\n source = ETSource(open(PATH))\n with source as src:\n assert_true(src.read().startswith(STARTSWITH))\n assert_true(src.closed is False)\n self._verify_string_representation(source, PATH)\n assert_true(source._opened is None)\n\n def test_byte_string(self):\n self._test_string('\\ncontent\\n'.encode())\n\n def test_unicode_string(self):\n self._test_string(u'\\nhyv\\xe4\\n')\n\n def _test_string(self, xml):\n source = ETSource(xml)\n with source as src:\n content = src.read()\n if not (IRONPYTHON or PY3):\n content = content.decode('UTF-8')\n assert_equals(content, xml)\n self._verify_string_representation(source, '')\n assert_true(source._opened.closed)\n with ETSource(xml) as src:\n assert_equals(ET.parse(src).getroot().tag, 'tag')\n\n def test_path_is_validated(self):\n def use(src):\n with src:\n pass\n assert_raises(IOError, use, ETSource('nonex.xml'))\n\n def test_non_ascii_string_repr(self):\n self._verify_string_representation(ETSource(u'\\xe4'), u'\\xe4')\n\n def _verify_string_representation(self, source, expected):\n assert_equals(unicode(source), expected)\n assert_equals('-%s-' % source, '-%s-' % expected)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "repo_name": "userzimmermann/robotframework-python3", "sub_path": "utest/utils/test_etreesource.py", "file_name": "test_etreesource.py", "file_ext": "py", "file_size_in_byte": 2313, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "24", "api": [{"api_name": "sys.platform", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 12, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 16, "usage_type": "attribute"}, {"api_name": "robot.utils.etreewrapper.ETSource", "line_number": 19, "usage_type": "call"}, {"api_name": "robot.utils.asserts.assert_equals", "line_number": 22, "usage_type": "call"}, {"api_name": "robot.utils.asserts.assert_true", "line_number": 24, "usage_type": "call"}, {"api_name": "robot.utils.asserts.assert_true", "line_number": 27, "usage_type": "call"}, {"api_name": "robot.utils.asserts.assert_true", "line_number": 29, "usage_type": "call"}, {"api_name": "robot.utils.etreewrapper.ETSource", "line_number": 32, "usage_type": "call"}, {"api_name": "robot.utils.asserts.assert_true", "line_number": 34, "usage_type": "call"}, {"api_name": "robot.utils.asserts.assert_true", "line_number": 35, "usage_type": "call"}, {"api_name": "robot.utils.asserts.assert_true", "line_number": 37, "usage_type": "call"}, {"api_name": "robot.utils.etreewrapper.ETSource", "line_number": 46, "usage_type": "call"}, {"api_name": "six.PY3", "line_number": 49, "usage_type": "name"}, {"api_name": "robot.utils.asserts.assert_equals", "line_number": 51, "usage_type": "call"}, {"api_name": "robot.utils.asserts.assert_true", "line_number": 53, "usage_type": "call"}, {"api_name": "robot.utils.etreewrapper.ETSource", "line_number": 54, "usage_type": "call"}, {"api_name": "robot.utils.asserts.assert_equals", "line_number": 55, "usage_type": "call"}, {"api_name": "robot.utils.etreewrapper.ET.parse", "line_number": 55, "usage_type": "call"}, {"api_name": "robot.utils.etreewrapper.ET", "line_number": 55, "usage_type": "name"}, {"api_name": "robot.utils.asserts.assert_raises", "line_number": 61, "usage_type": "call"}, {"api_name": "robot.utils.etreewrapper.ETSource", "line_number": 61, "usage_type": "call"}, {"api_name": "robot.utils.etreewrapper.ETSource", "line_number": 64, "usage_type": "call"}, {"api_name": "robot.utils.asserts.assert_equals", "line_number": 67, "usage_type": "call"}, {"api_name": "six.text_type", "line_number": 67, "usage_type": "call"}, {"api_name": "robot.utils.asserts.assert_equals", "line_number": 68, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 72, "usage_type": "call"}]} +{"seq_id": "41743167569", "text": "\nfrom urllib.request import *\nimport http.cookiejar, urllib.parse\nimport json\n\n'''\n 有时候,用户可能需要访问 Web 应用中的被保护的页面,如果使用浏览器则十分简单,通过系统提供的登录页面登录系统,浏览器会负责维护与服务器\n 之间的 session,如果用户登录的用户名,密码符合要求,就可以访问被保护资源了\n\n 如果使用 urllib.request 模块来访问被保护页面,则同样需要维护与服务器之间的 session,此时就需要借助于 cookie 管理器来实现。\n\n 如果程序直接使用 urlopen() 发送请求,冰球并为管理与服务器之间的 session,那么服务器就无法识别两次请求是否是同一个客服端发出的。\n 为了有效地管理 session,程序可引入 http.cookiejar 模块。\n\n 此外程序还需要使用 OpenerDirector 对象来管理发送请求。\n 为了使用 urllib.request 模块通过 cookie 来管理 session,可按如下步骤进行操作\n\n 1 创建 http.cookiejar.CookieJar 对象或其子类的对象。\n 2 以 CookieJar 对象为参数,创建 urllib.request.HTTPCookieProcessor 对象,该对象负责调用 CookieJar 来管理 cookie\n 3 以 HTTPCookieProcessor 对象为参数,调用 urllib.request.build_opener() 函数创建 OpenerDirector 对象。\n 4 使用 OpenerDirector 对象来发送请求,该对象将会通过 HTTPCookieProcessor 调用 CookieJar 来管理 cookie。\n\n'''\n\n\n# 以指定文件创建 CookieJar 对象,该对象可以把 cookie 信息保存在文件中\ncookie_jar = http.cookiejar.MozillaCookieJar('a.txt')\n# 创建 HTTPCookieProcessor 对象\ncookie_processor = HTTPCookieProcessor(cookie_jar)\n# 创建 OpenerDirector 对象\nopener = build_opener(cookie_processor)\n\n# 定义模拟 Chrome 浏览器的 User-Agent\nuser_agent = r'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'\n# 定义请求头\nheaders = {'User-Agent': user_agent, 'Connection': 'keep-alive'}\n\n# ----------------------- 下面代码发送登录的 POST 请求\n# params = {'username': '13824472562', 'password': '123456'}\nparams = {'phone': '13824472562', 'type': '1'}\npostdata = urllib.parse.urlencode(params).encode()\n\n# 创建向登录页面发送 POST 请求的 Reuest\n# request = Request('http://47.92.93.177:5566/#/login', data=postdata, headers=headers)\nrequest = Request('http://101.132.113.84:11002/userua/verify/login', data=postdata)\n# 使用 OpenerDirector 发送 POST 请求\nresponse = opener.open(request)\nresult = response.read().decode('utf-8')\n\nd = json.loads(result)\nprint(d, type(d))\n\n# 将 cookie 信息写入文件中\ncookie_jar.save(ignore_discard=True, ignore_expires=True)\n\n\n# ---------------------- 下面代码发送访问被保护资源的 GET 请求\n# 创建向被保护页面发送 GET 请求的 Request\n# request = Request('http://47.92.93.177:5566/#/login', headers=headers)\n# response = opener.open(request)\n# print(response.read().decode)\n", "repo_name": "afreeliu/CrazyPythonLearn", "sub_path": "main/Chapter/15_网络编程/15.2.4管理cookie.py", "file_name": "15.2.4管理cookie.py", "file_ext": "py", "file_size_in_byte": 3036, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "http.cookiejar.cookiejar.MozillaCookieJar", "line_number": 27, "usage_type": "call"}, {"api_name": "http.cookiejar.cookiejar", "line_number": 27, "usage_type": "attribute"}, {"api_name": "http.cookiejar", "line_number": 27, "usage_type": "name"}, {"api_name": "urllib.request.parse.urlencode", "line_number": 41, "usage_type": "call"}, {"api_name": "urllib.request.parse", "line_number": 41, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 41, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 50, "usage_type": "call"}]} +{"seq_id": "13551927126", "text": "from tkinter import *\r\nfrom translate import Translator\r\n\r\ndef trans():\r\n translator=Translator(from_lang=lan1.get(),to_lang=lan2.get())\r\n translation=translator.translate(var.get())\r\n var1.set(translation)\r\n\r\n\r\nroot=Tk()\r\nroot.title(\"Translator\")\r\n\r\nmf=Frame(root)\r\nmf.grid(column=0,row=0, sticky=(N,W,E,S))\r\nmf.columnconfigure(0,weight=1)\r\nmf.rowconfigure(0,weight=1)\r\nmf.pack(pady=100,padx=100)\r\n\r\nlan1=StringVar(root)\r\nlan2=StringVar(root)\r\n\r\nchoices={'English','Hindi','Gujarati','Spanish','German','Urdu'}\r\nlan1.set('English')\r\nlan2.set('Hindi')\r\n\r\nlan1menu=OptionMenu(mf,lan1,*choices)\r\nLabel(mf,text=\"select a language\").grid(row=0,column=1)\r\nlan1menu.grid(row=1,column=1)\r\n\r\nlan2menu=OptionMenu(mf,lan2,*choices)\r\nLabel(mf,text=\"select a language\").grid(row=0,column=2)\r\nlan2menu.grid(row=1,column=2)\r\n\r\nLabel(mf,text=\"Enter text\").grid(row=2,column=0)\r\nvar=StringVar()\r\n\r\ntextbox=Entry(mf,textvariable=var).grid(row=2,column=1)\r\n\r\nLabel(mf,text=\"Output\").grid(row=2,column=2)\r\nvar1=StringVar()\r\ntextbox=Entry(mf,textvariable=var1).grid(row=2,column=3)\r\n\r\nb=Button(mf,text=\"Translate\",command=trans).grid(row=3,column=1,columnspan=3)\r\n\r\nroot.mainloop()\r\n", "repo_name": "Amar7148/python-language-translator-", "sub_path": "translator.py", "file_name": "translator.py", "file_ext": "py", "file_size_in_byte": 1172, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "translate.Translator", "line_number": 5, "usage_type": "call"}]} +{"seq_id": "44780691272", "text": "from django.test import TestCase\n\n# Create your tests here.\n\n\nfrom catalog.models import Director\nfrom django.urls import reverse\n\n\nclass DirectorListViewTest(TestCase):\n\n @classmethod\n def setUpTestData(cls):\n # Create directors for pagination tests\n number_of_directors = 13\n for director_id in range(number_of_directors):\n Director.objects.create(name='Christian {0}'.format(director_id))\n\n def test_view_url_exists_at_desired_location(self):\n response = self.client.get('/catalog/directors/')\n self.assertEqual(response.status_code, 200)\n\n def test_view_url_accessible_by_name(self):\n response = self.client.get('/catalog/directors/')\n self.assertEqual(response.status_code, 200)\n\n def test_view_uses_correct_template(self):\n response = self.client.get('/catalog/directors/')\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'catalog/director_list.html')\n\n def test_pagination_is_ten(self):\n response = self.client.get('/catalog/directors/')\n self.assertEqual(response.status_code, 200)\n self.assertTrue('is_paginated' in response.context)\n self.assertTrue(response.context['is_paginated'] is True)\n self.assertTrue(len(response.context['director_list']) == 10)\n\n def test_lists_all_directors(self):\n # Get second page and confirm it has (exactly) the remaining 3 items\n response = self.client.get('/catalog/directors/'+'?page=2')\n self.assertEqual(response.status_code, 200)\n self.assertTrue('is_paginated' in response.context)\n self.assertTrue(response.context['is_paginated'] is True)\n self.assertTrue(len(response.context['director_list']) == 3)\n\nimport datetime\nfrom django.utils import timezone\n\nfrom catalog.models import Movie, Genre, Language\nfrom django.contrib.auth.models import User # Required to assign User as a borrower\n\nfrom django.contrib.auth.models import Permission # Required to grant the permission needed to set a movie as returned.\n\nclass DirectorCreateViewTest(TestCase):\n \"\"\"Test case for the DirectorCreate view (Created as Challenge).\"\"\"\n\n def setUp(self):\n # Create a user\n test_user1 = User.objects.create_user(username='testuser1', password='1X\", methods = ['GET', 'POST', 'DELETE'])\n@cross_origin()\ndef note_id(id_):\n if request.method == 'GET':\n try:\n note=Note.query.filter_by(id=id_).first()\n return jsonify(note.serialize())\n except Exception as e:\n return(str(e))\n if request.method == 'POST':\n try:\n note=Note.query.filter_by(id=id_).first()\n title=request.form['title']\n content=request.form['content']\n author=request.form['author']\n published=request.form['published']\n try:\n if not(len(title) is 0):\n note.title=title,\n if not(len(content) is 0):\n note.content=content,\n if not(len(author) is 0):\n note.author=author,\n if not(len(published) is 0):\n note.published=published\n db.session.commit()\n return \"Note updated. note id={}\".format(note.id)\n except Exception as e:\n return(str(e))\n except Exception as e:\n return(str(e))\n if request.method == 'DELETE':\n try:\n note=Note.query.filter_by(id=id_).first()\n db.session.delete(note)\n db.session.commit()\n return \"Note deleted. note id={}\".format(id_)\n except Exception as e:\n return(str(e))\n\nif __name__ == '__main__':\n app.run()", "repo_name": "EdisonGonzalez/GTDsystemBack", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 2668, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 6, "usage_type": "call"}, {"api_name": "flask_cors.CORS", "line_number": 8, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 10, "usage_type": "attribute"}, {"api_name": "flask_sqlalchemy.SQLAlchemy", "line_number": 12, "usage_type": "call"}, {"api_name": "flask_cors.cross_origin", "line_number": 17, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 24, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 25, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 25, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 26, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 26, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 27, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 27, "usage_type": "name"}, {"api_name": "models.Note", "line_number": 29, "usage_type": "call"}, {"api_name": "flask_cors.cross_origin", "line_number": 22, "usage_type": "call"}, {"api_name": "models.Note.query.all", "line_number": 45, "usage_type": "call"}, {"api_name": "models.Note.query", "line_number": 45, "usage_type": "attribute"}, {"api_name": "models.Note", "line_number": 45, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 46, "usage_type": "call"}, {"api_name": "flask_cors.cross_origin", "line_number": 42, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 53, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 53, "usage_type": "name"}, {"api_name": "models.Note.query.filter_by", "line_number": 55, "usage_type": "call"}, {"api_name": "models.Note.query", "line_number": 55, "usage_type": "attribute"}, {"api_name": "models.Note", "line_number": 55, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 56, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 59, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 59, "usage_type": "name"}, {"api_name": "models.Note.query.filter_by", "line_number": 61, "usage_type": "call"}, {"api_name": "models.Note.query", "line_number": 61, "usage_type": "attribute"}, {"api_name": "models.Note", "line_number": 61, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 62, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 62, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 63, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 63, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 64, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 64, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 65, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 65, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 81, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 81, "usage_type": "name"}, {"api_name": "models.Note.query.filter_by", "line_number": 83, "usage_type": "call"}, {"api_name": "models.Note.query", "line_number": 83, "usage_type": "attribute"}, {"api_name": "models.Note", "line_number": 83, "usage_type": "name"}, {"api_name": "flask_cors.cross_origin", "line_number": 51, "usage_type": "call"}]} +{"seq_id": "37547227468", "text": "import plotly.express as px\n\ndef set_pie_charts(st,data):\n col1, col2 = st.columns(2)\n with col1:\n data_types = data.groupby('type')['total_count'].sum().reset_index()\n fig = px.pie( data_types , values='total_count', names='type', title='Deliverity Tracking')\n st.plotly_chart(fig)\n\n with col2:\n data_types = data[data['type'] == 'bounce'].groupby('bounce_type')['total_count'].sum().reset_index()\n fig = px.pie(data_types, values='total_count', names='bounce_type', title='Bounce stats')\n st.plotly_chart(fig)", "repo_name": "abdelaliLaatamli/streamlit_data_dashbord", "sub_path": "sections/pie_deliverty.py", "file_name": "pie_deliverty.py", "file_ext": "py", "file_size_in_byte": 564, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "plotly.express.pie", "line_number": 7, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 7, "usage_type": "name"}, {"api_name": "plotly.express.pie", "line_number": 12, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 12, "usage_type": "name"}]} +{"seq_id": "41652888580", "text": "import pytest\nfrom model_bakery import baker\nfrom django.contrib.auth.models import User\n\n\n@pytest.fixture\ndef zuck(db):\n user = baker.make(\n User,\n username='zuck',\n first_name='Mark',\n last_name='Zuckerberg',\n email='mark.zuckerberg@facebook.com',\n profile__photo_url='http://zuck.png',\n is_superuser=True,\n is_staff=True\n )\n yield user\n user.delete()\n", "repo_name": "vidalmatheus/fsquare", "sub_path": "template/main/tests/conftest.py", "file_name": "conftest.py", "file_ext": "py", "file_size_in_byte": 422, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "27", "api": [{"api_name": "model_bakery.baker.make", "line_number": 8, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User", "line_number": 9, "usage_type": "argument"}, {"api_name": "model_bakery.baker", "line_number": 8, "usage_type": "name"}, {"api_name": "pytest.fixture", "line_number": 6, "usage_type": "attribute"}]} +{"seq_id": "19272430154", "text": "\"\"\" Module that provides the estimated waittime for a given timestamp\n The timestamp is rounded to the nearest quarter hour \"\"\"\nimport os.path\nimport pandas as pd\nimport numpy as np\nimport _pickle as pkl\nfrom datetime import datetime, timedelta, timezone\n\nclass WaitimeEHAS:\n def __init__(self, file):\n self._file = file\n self._dict = None\n self._pkl_file = \"../data/gulasch.pkl\"\n if not os.path.isfile(self._pkl_file):\n df = self._load_data(self._file)\n self._dict = self._process_data(df)\n self._pickle(self._dict, self._pkl_file)\n else:\n self._dict = self._load_pickle(self._pkl_file)\n\n def _load_data(self, file):\n \"\"\" Loads data from a file \"\"\"\n df = pd.read_csv(file, names=['DAY', 'INTERVAL', 'LANES_SECURITY', 'TRANSFERFILTER'], header=None, skiprows=1)\n return df\n\n def _process_data(self, df: pd.DataFrame):\n \"\"\" Brings the data in the correct format and aggregates information \"\"\"\n # Create Datetime from DAY and INTERVAL_15MIN\n df['DATE'] = pd.to_datetime(df['DAY'] + ' ' + df['INTERVAL'], format='%Y-%m-%d %H:%M')\n # Calculate People per Security Lane\n df[0] = df['TRANSFERFILTER'] / df['LANES_SECURITY']\n # Sort by Date ascending\n df = df.sort_values('DATE')\n\n # Add the Values for +15, +30 and +45 minutes and replace NaN with 0\n df[15] = df[0].shift(-1)\n df[30] = df[0].shift(-2)\n df[45] = df[0].shift(-3)\n df.fillna(inplace=True, value=0)\n\n # Create Timestamp from DateTime\n df['TIMESTAMP'] = df.DATE.values.astype(np.int64) // 10 ** 9\n\n df_processed = df[['TIMESTAMP', 0, 15, 30, 45]]\n df_processed.set_index('TIMESTAMP', inplace=True)\n # Select Useful Information from DataFrame\n\n result = df_processed.T.to_dict()\n return result\n\n def _pickle(self, df, file):\n \"\"\" Pickles the waittime dictionary \"\"\"\n with open(file, 'wb') as f:\n pkl.dump(df, f, -1)\n\n def get_predicted_waittime(self, ts):\n \"\"\" Gives the predicted waittimes for a given timestamp\n\n Keyword Arguments:\n\n ts -- epoch timestmap since 01.01.1970\n\n Returns Json:\n {'PEOPLE_PER_LANE': 7.333333333333333, 'PEOPLE_PLUS_15': 0.0,\n 'PEOPLE_PLUS_30': 0.33333333333333331, 'PEOPLE_PLUS_45': 51.333333333333336} \"\"\"\n dt = datetime.fromtimestamp(\n int(ts)\n )\n rounded_dt = datetime(dt.year, dt.month, dt.day, dt.hour, 15*(dt.minute // 15))\n # rounded_ts = rounded_dt.astype(np.int64) // 10 ** 9\n rounded_ts = rounded_dt.timestamp()\n return self._dict[rounded_ts]\n\n\n def _load_pickle(self, pkl_file):\n \"\"\" Loads the dictionary from file\"\"\"\n return pkl.load(open(pkl_file, \"rb\"))\n\nWAITEHAS = WaitimeEHAS('../data/EF.csv')\n\ndef get_best_timeslot(arrival_time, max_window):\n ts = (arrival_time - datetime(1970, 1, 1, tzinfo=timezone.utc)) / timedelta(seconds=1)\n\n forecast = WAITEHAS.get_predicted_waittime(ts)\n for k, v in forecast.items():\n best = None\n if k <= max_window:\n if not best or v < forecast[best]:\n best = k\n return best, 1-(forecast[best]/forecast[0])\n\nif __name__ == \"__main__\":\n from pprint import pprint\n pprint(get_best_timeslot(\"1497692825\", 99))\n", "repo_name": "swagner-de/recodingaviation_hackathon", "sub_path": "src/analysis/waittime_EHAM.py", "file_name": "waittime_EHAM.py", "file_ext": "py", "file_size_in_byte": 3398, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "os.path.path.isfile", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 14, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 23, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 26, "usage_type": "attribute"}, {"api_name": "pandas.to_datetime", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.int64", "line_number": 42, "usage_type": "attribute"}, {"api_name": "_pickle.dump", "line_number": 54, "usage_type": "call"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 66, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 66, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 69, "usage_type": "call"}, {"api_name": "_pickle.load", "line_number": 77, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 82, "usage_type": "call"}, {"api_name": "datetime.timezone.utc", "line_number": 82, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 82, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 82, "usage_type": "call"}, {"api_name": "pprint.pprint", "line_number": 94, "usage_type": "call"}]} +{"seq_id": "17603774564", "text": "from django.core.management.base import BaseCommand, CommandError\nimport pymysql\nfrom django.db import connection\nfrom django.conf import settings\nfrom collections import namedtuple\nfrom api.models import Area, Category\n\n\ndef format_fetch(cursor):\n \"\"\"Return all rows from a cursor as a namedtuple\"\"\"\n desc = cursor.description\n nt_result = namedtuple('Result', [col[0] for col in desc])\n return [nt_result(*row) for row in cursor.fetchall()]\n\n\nclass Command(BaseCommand):\n help = '初始化数据库'\n\n def handle(self, *args, **options):\n connect = pymysql.connect(\n host='127.0.0.1',\n port=3308,\n user='sharezone',\n password='1qaz#EDC',\n db='sharezone'\n )\n cursor = connect.cursor()\n cursor.execute('select * from dict where class_id=0')\n rows = format_fetch(cursor)\n # rows = cursor.fetchall()\n self.stdout.write('初始化Area...')\n area_count = 0\n for row in rows:\n existed = Area.objects.filter(name=row.c_name, identity=row.s_class_id).exists()\n if not existed:\n Area.objects.create(\n name=row.c_name,\n identity=row.s_class_id,\n pid=row.p_id\n )\n area_count += 1\n self.stdout.write(self.style.SUCCESS('初始化Area完成, 插入%s条数据' % area_count))\n\n self.stdout.write('初始化Category...')\n cursor.execute('select * from share_category')\n rows = format_fetch(cursor)\n category_count = 0\n for row in rows:\n existed = Category.objects.filter(name=row.category_name)\n if not existed:\n Category.objects.create(\n name=row.category_name,\n pid=row.p_id\n )\n category_count += 1\n self.stdout.write(self.style.SUCCESS('初始化Category完成, 插入%s条数据' % category_count))\n\n cursor.close()\n\n\n\n\n", "repo_name": "hifeiwenchao/sharezone", "sub_path": "api/management/commands/initial_db.py", "file_name": "initial_db.py", "file_ext": "py", "file_size_in_byte": 2032, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "collections.namedtuple", "line_number": 12, "usage_type": "call"}, {"api_name": "django.core.management.base.BaseCommand", "line_number": 16, "usage_type": "name"}, {"api_name": "pymysql.connect", "line_number": 20, "usage_type": "call"}, {"api_name": "api.models.Area.objects.filter", "line_number": 34, "usage_type": "call"}, {"api_name": "api.models.Area.objects", "line_number": 34, "usage_type": "attribute"}, {"api_name": "api.models.Area", "line_number": 34, "usage_type": "name"}, {"api_name": "api.models.Area.objects.create", "line_number": 36, "usage_type": "call"}, {"api_name": "api.models.Area.objects", "line_number": 36, "usage_type": "attribute"}, {"api_name": "api.models.Area", "line_number": 36, "usage_type": "name"}, {"api_name": "api.models.Category.objects.filter", "line_number": 49, "usage_type": "call"}, {"api_name": "api.models.Category.objects", "line_number": 49, "usage_type": "attribute"}, {"api_name": "api.models.Category", "line_number": 49, "usage_type": "name"}, {"api_name": "api.models.Category.objects.create", "line_number": 51, "usage_type": "call"}, {"api_name": "api.models.Category.objects", "line_number": 51, "usage_type": "attribute"}, {"api_name": "api.models.Category", "line_number": 51, "usage_type": "name"}]} +{"seq_id": "6241693599", "text": "#!/usr/bin/env python2\n# vim:fileencoding=utf-8\nfrom __future__ import (unicode_literals, division, absolute_import,\n print_function)\n\n__license__ = 'GPL v3'\n__copyright__ = '2013, Kovid Goyal '\n\nimport textwrap\nfrom io import BytesIO\n\nfrom lxml import etree\nfrom lxml.builder import ElementMaker\n\nfrom calibre import guess_type\nfrom calibre.constants import numeric_version, __appname__\nfrom calibre.ebooks.docx.names import namespaces, STYLES, WEB_SETTINGS\nfrom calibre.ebooks.metadata import authors_to_string\nfrom calibre.ebooks.metadata.opf2 import OPF as ReadOPF\nfrom calibre.ebooks.oeb.base import OPF, OPF2_NS\nfrom calibre.utils.date import utcnow\nfrom calibre.utils.localization import canonicalize_lang, lang_as_iso639_1\nfrom calibre.utils.zipfile import ZipFile\n\ndef xml2str(root, pretty_print=False, with_tail=False):\n ans = etree.tostring(root, encoding='utf-8', xml_declaration=True,\n pretty_print=pretty_print, with_tail=with_tail)\n return ans\n\ndef update_doc_props(root, mi):\n def setm(name, text=None, ns='dc'):\n ans = root.makeelement('{%s}%s' % (namespaces[ns], name))\n for child in tuple(root):\n if child.tag == ans.tag:\n root.remove(child)\n ans.text = text\n root.append(ans)\n return ans\n setm('title', mi.title)\n setm('creator', authors_to_string(mi.authors))\n if mi.tags:\n setm('keywords', ', '.join(mi.tags), ns='cp')\n if mi.comments:\n setm('description', mi.comments)\n if mi.languages:\n l = canonicalize_lang(mi.languages[0])\n setm('language', lang_as_iso639_1(l) or l)\n\n\nclass DocumentRelationships(object):\n\n def __init__(self):\n self.rmap = {}\n self.counter = 0\n for typ, target in {\n STYLES: 'styles.xml',\n WEB_SETTINGS: 'webSettings.xml',\n }.iteritems():\n self.add_relationship(target, typ)\n\n def get_relationship_id(self, target, rtype, target_mode=None):\n return self.rmap.get((target, rtype, target_mode))\n\n def add_relationship(self, target, rtype, target_mode=None):\n ans = self.get_relationship_id(target, rtype, target_mode)\n if ans is None:\n self.counter += 1\n ans = 'rId%d' % self.counter\n self.rmap[(target, rtype, target_mode)] = ans\n return ans\n\n def serialize(self):\n E = ElementMaker(namespace=namespaces['pr'], nsmap={None:namespaces['pr']})\n relationships = E.Relationships()\n for (target, rtype, target_mode), rid in self.rmap.iteritems():\n r = E.Relationship(Id=rid, Type=rtype, Target=target)\n if target_mode is not None:\n r.set('TargetMode', target_mode)\n relationships.append(r)\n return xml2str(relationships)\n\nclass DOCX(object):\n\n def __init__(self, opts, log):\n self.opts, self.log = opts, log\n self.document_relationships = DocumentRelationships()\n\n # Boilerplate {{{\n @property\n def contenttypes(self):\n E = ElementMaker(namespace=namespaces['ct'], nsmap={None:namespaces['ct']})\n types = E.Types()\n for partname, mt in {\n \"/word/footnotes.xml\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml\",\n \"/word/document.xml\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml\",\n \"/word/numbering.xml\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml\",\n \"/word/styles.xml\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml\",\n \"/word/endnotes.xml\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml\",\n \"/word/settings.xml\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml\",\n \"/word/theme/theme1.xml\": \"application/vnd.openxmlformats-officedocument.theme+xml\",\n \"/word/fontTable.xml\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml\",\n \"/word/webSettings.xml\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml\",\n \"/docProps/core.xml\": \"application/vnd.openxmlformats-package.core-properties+xml\",\n \"/docProps/app.xml\": \"application/vnd.openxmlformats-officedocument.extended-properties+xml\",\n }.iteritems():\n types.append(E.Override(PartName=partname, ContentType=mt))\n added = {'png', 'gif', 'jpeg', 'jpg', 'svg', 'xml'}\n for ext in added:\n types.append(E.Default(Extension=ext, ContentType=guess_type('a.'+ext)[0]))\n for ext, mt in {\n \"rels\": \"application/vnd.openxmlformats-package.relationships+xml\",\n \"odttf\": \"application/vnd.openxmlformats-officedocument.obfuscatedFont\",\n }.iteritems():\n added.add(ext)\n types.append(E.Default(Extension=ext, ContentType=mt))\n # TODO: Iterate over all resources and add mimetypes for any that are\n # not already added\n return xml2str(types)\n\n @property\n def appproperties(self):\n E = ElementMaker(namespace=namespaces['ep'], nsmap={None:namespaces['ep']})\n props = E.Properties(\n E.Application(__appname__),\n E.AppVersion('%02d.%04d' % numeric_version[:2]),\n E.DocSecurity('0'),\n E.HyperlinksChanged('false'),\n E.LinksUpToDate('true'),\n E.ScaleCrop('false'),\n E.SharedDoc('false'),\n )\n if self.mi.publisher:\n props.append(E.Company(self.mi.publisher))\n return xml2str(props)\n\n @property\n def containerrels(self):\n return textwrap.dedent(b'''\\\n \n \n \n \n \n ''')\n\n @property\n def websettings(self):\n E = ElementMaker(namespace=namespaces['w'], nsmap={'w':namespaces['w']})\n ws = E.webSettings(\n E.optimizeForBrowser, E.allowPNG, E.doNotSaveAsSingleFile)\n return xml2str(ws)\n\n # }}}\n\n def convert_metadata(self, oeb):\n E = ElementMaker(namespace=namespaces['cp'], nsmap={x:namespaces[x] for x in 'cp dc dcterms xsi'.split()})\n cp = E.coreProperties(E.revision(\"1\"), E.lastModifiedBy('calibre'))\n ts = utcnow().isoformat(str('T')).rpartition('.')[0] + 'Z'\n for x in 'created modified'.split():\n x = cp.makeelement('{%s}%s' % (namespaces['dcterms'], x), **{'{%s}type' % namespaces['xsi']:'dcterms:W3CDTF'})\n x.text = ts\n cp.append(x)\n package = etree.Element(OPF('package'), attrib={'version': '2.0'}, nsmap={None: OPF2_NS})\n oeb.metadata.to_opf2(package)\n self.mi = ReadOPF(BytesIO(xml2str(package)), populate_spine=False, try_to_guess_cover=False).to_book_metadata()\n update_doc_props(cp, self.mi)\n return xml2str(cp)\n\n def write(self, path_or_stream, oeb):\n with ZipFile(path_or_stream, 'w') as zf:\n zf.writestr('[Content_Types].xml', self.contenttypes)\n zf.writestr('_rels/.rels', self.containerrels)\n zf.writestr('docProps/core.xml', self.convert_metadata(oeb))\n zf.writestr('docProps/app.xml', self.appproperties)\n zf.writestr('word/webSettings.xml', self.websettings)\n zf.writestr('word/document.xml', xml2str(self.document))\n zf.writestr('word/styles.xml', xml2str(self.styles))\n zf.writestr('word/_rels/document.xml.rels', self.document_relationships.serialize())\n\nif __name__ == '__main__':\n d = DOCX(None, None)\n print (d.websettings)\n", "repo_name": "mad0c/calibre", "sub_path": "src/calibre/ebooks/docx/writer/container.py", "file_name": "container.py", "file_ext": "py", "file_size_in_byte": 8265, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "24", "api": [{"api_name": "lxml.etree.tostring", "line_number": 26, "usage_type": "call"}, {"api_name": "lxml.etree", "line_number": 26, "usage_type": "name"}, {"api_name": "calibre.ebooks.docx.names.namespaces", "line_number": 32, "usage_type": "name"}, {"api_name": "calibre.ebooks.metadata.authors_to_string", "line_number": 40, "usage_type": "call"}, {"api_name": "calibre.utils.localization.canonicalize_lang", "line_number": 46, "usage_type": "call"}, {"api_name": "calibre.utils.localization.lang_as_iso639_1", "line_number": 47, "usage_type": "call"}, {"api_name": "calibre.ebooks.docx.names.STYLES", "line_number": 56, "usage_type": "name"}, {"api_name": "calibre.ebooks.docx.names.WEB_SETTINGS", "line_number": 57, "usage_type": "name"}, {"api_name": "lxml.builder.ElementMaker", "line_number": 73, "usage_type": "call"}, {"api_name": "calibre.ebooks.docx.names.namespaces", "line_number": 73, "usage_type": "name"}, {"api_name": "lxml.builder.ElementMaker", "line_number": 91, "usage_type": "call"}, {"api_name": "calibre.ebooks.docx.names.namespaces", "line_number": 91, "usage_type": "name"}, {"api_name": "calibre.guess_type", "line_number": 109, "usage_type": "call"}, {"api_name": "lxml.builder.ElementMaker", "line_number": 122, "usage_type": "call"}, {"api_name": "calibre.ebooks.docx.names.namespaces", "line_number": 122, "usage_type": "name"}, {"api_name": "calibre.constants.__appname__", "line_number": 124, "usage_type": "argument"}, {"api_name": "calibre.constants.numeric_version", "line_number": 125, "usage_type": "name"}, {"api_name": "textwrap.dedent", "line_number": 138, "usage_type": "call"}, {"api_name": "lxml.builder.ElementMaker", "line_number": 148, "usage_type": "call"}, {"api_name": "calibre.ebooks.docx.names.namespaces", "line_number": 148, "usage_type": "name"}, {"api_name": "lxml.builder.ElementMaker", "line_number": 156, "usage_type": "call"}, {"api_name": "calibre.ebooks.docx.names.namespaces", "line_number": 156, "usage_type": "name"}, {"api_name": "calibre.utils.date.utcnow", "line_number": 158, "usage_type": "call"}, {"api_name": "calibre.ebooks.docx.names.namespaces", "line_number": 160, "usage_type": "name"}, {"api_name": "lxml.etree.Element", "line_number": 163, "usage_type": "call"}, {"api_name": "lxml.etree", "line_number": 163, "usage_type": "name"}, {"api_name": "calibre.ebooks.oeb.base.OPF", "line_number": 163, "usage_type": "call"}, {"api_name": "calibre.ebooks.oeb.base.OPF2_NS", "line_number": 163, "usage_type": "name"}, {"api_name": "calibre.ebooks.metadata.opf2.OPF", "line_number": 165, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 165, "usage_type": "call"}, {"api_name": "calibre.utils.zipfile.ZipFile", "line_number": 170, "usage_type": "call"}]} +{"seq_id": "44453367069", "text": "from django.shortcuts import render\nfrom .models import Student\nfrom .serializers import StudentSerializer\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view, authentication_classes, permission_classes\nfrom rest_framework.authentication import BasicAuthentication\nfrom rest_framework.permissions import IsAuthenticated\n\n\"\"\"\nAuthentication and Permission in Function Based View in Django REST Framework 21\n\"\"\"\n\n@api_view(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])\n@authentication_classes([BasicAuthentication])\n@permission_classes([IsAuthenticated])\ndef student_api(request, pk=None):\n if request.method == \"GET\":\n if pk is not None:\n stu = Student.objects.get(id=pk)\n serializer = StudentSerializer(stu)\n return Response(serializer.data)\n stu = Student.objects.all()\n serializer = StudentSerializer(stu, many=True)\n return Response(serializer.data)\n \n if request.method == \"POST\":\n serializer = StudentSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response({'success':'Student Added'}, status=status.HTTP_201_CREATED)\n return Response({'error':serializer.errors}, status=status.HTTP_400_BAD_REQUEST)\n\n if request.method == \"PUT\":\n stu = Student.objects.get(id=pk)\n serializer = StudentSerializer(stu, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response({'success':'Complete Student data Updated'})\n return Response({'error':serializer.errors}, status=status.HTTP_400_BAD_REQUEST)\n\n if request.method == \"PATCH\":\n stu = Student.objects.get(id=pk)\n serializer = StudentSerializer(stu, data=request.data, partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response({'success':'Partial Student data Updated'})\n return Response({'error':serializer.errors}, status=status.HTTP_400_BAD_REQUEST)\n\n if request.method == \"DELETE\":\n stu = Student.objects.get(id=pk)\n stu.delete()\n return Response({'success':'Student Deleted'})", "repo_name": "sdgoraya786/django-project", "sub_path": "DRF/sd16/api/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2219, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "models.Student.objects.get", "line_number": 20, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 20, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 20, "usage_type": "name"}, {"api_name": "serializers.StudentSerializer", "line_number": 21, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 22, "usage_type": "call"}, {"api_name": "models.Student.objects.all", "line_number": 23, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 23, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 23, "usage_type": "name"}, {"api_name": "serializers.StudentSerializer", "line_number": 24, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 25, "usage_type": "call"}, {"api_name": "serializers.StudentSerializer", "line_number": 28, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 31, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 31, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 31, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 32, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 32, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 32, "usage_type": "name"}, {"api_name": "models.Student.objects.get", "line_number": 35, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 35, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 35, "usage_type": "name"}, {"api_name": "serializers.StudentSerializer", "line_number": 36, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 39, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 40, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 40, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 40, "usage_type": "name"}, {"api_name": "models.Student.objects.get", "line_number": 43, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 43, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 43, "usage_type": "name"}, {"api_name": "serializers.StudentSerializer", "line_number": 44, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 47, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 48, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 48, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 48, "usage_type": "name"}, {"api_name": "models.Student.objects.get", "line_number": 51, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 51, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 51, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 53, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 14, "usage_type": "call"}, {"api_name": "rest_framework.decorators.authentication_classes", "line_number": 15, "usage_type": "call"}, {"api_name": "rest_framework.authentication.BasicAuthentication", "line_number": 15, "usage_type": "name"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 16, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 16, "usage_type": "name"}]} +{"seq_id": "4740845757", "text": "import copy\nimport cv2 as cv\nimport numpy as np\nimport mediapipe as mp\nfrom collections import deque\nimport json\nfrom mediapipe_zmq.utils import get_args\nfrom mediapipe_zmq.utils import emotion_recognition\nfrom mediapipe_zmq.utils import face_mesh\nfrom mediapipe_zmq.utils import left_hand\nfrom mediapipe_zmq.utils import right_hand\nfrom mediapipe_zmq.utils import pose_landmark\nimport zmq\nimport time\nimport tensorflow as tf\n\n\n\n# from keras_cv_attention_models import mobilevit\n\n#\nclass CvFpsCalc(object):\n def __init__(self, buffer_len=1):\n self._start_tick = cv.getTickCount()\n self._freq = 1000.0 / cv.getTickFrequency()\n self._difftimes = deque(maxlen=buffer_len)\n\n def get(self):\n current_tick = cv.getTickCount()\n different_time = (current_tick - self._start_tick) * self._freq\n self._start_tick = current_tick\n\n self._difftimes.append(different_time)\n\n fps = 1000.0 / (sum(self._difftimes) / len(self._difftimes))\n fps_rounded = round(fps, 2)\n\n return fps_rounded\n#\n\n\ndef main():\n # --- 설정 ---\n count = 1\n start = time.time()\n # ZMQ bind\n context = zmq.Context()\n sockets = context.socket(zmq.PUB)\n sockets.bind('tcp://127.0.0.1:10100')\n\n # --- json\n dicts = {\n 'face_mesh' : {},\n 'left_hand' : {},\n 'right_hand' : {},\n 'pose' : {},\n 'emotion' : {}\n}\n\n # --- 인수값 불러오기\n args = get_args()\n \n # 카메라\n cap_device = args.device\n cap_width = args.width\n cap_height = args.height\n \n # face detection\n model_selection = args.model_selection\n min_face_detection_confidence = args.min_face_detection_confidence\n\n # holistic\n smooth_landmarks = not args.unuse_smooth_landmarks\n enable_segmentation = args.enable_segmentation\n smooth_segmentation = args.smooth_segmentation\n model_complexity = args.model_complexity\n min_mesh_detection_confidence = args.min_mesh_detection_confidence\n min_tracking_confidence = args.min_tracking_confidence\n segmentation_score_th = args.segmentation_score_th\n\n # plot_world_landmark = args.plot_world_landmark\n use_brect = args.use_brect\n\n # --- 카메라 설정\n cap = cv.VideoCapture(cap_device)\n cap.set(cv.CAP_PROP_FRAME_WIDTH, cap_width)\n cap.set(cv.CAP_PROP_FRAME_HEIGHT, cap_height)\n\n\n # --- mobile_VIT 모델\n mobile_VIT=tf.keras.models.load_model('mobile_VIT.h5')\n\n # --- mediapipe 모델\n \n # face detection\n mp_face_detection = mp.solutions.face_detection\n face_detection = mp_face_detection.FaceDetection(\n model_selection=model_selection,\n min_detection_confidence=min_face_detection_confidence,\n )\n\n # holistic model\n mp_holistic = mp.solutions.holistic\n holistic = mp_holistic.Holistic(\n # upper_body_only=upper_body_only,\n model_complexity=model_complexity,\n smooth_landmarks=smooth_landmarks,\n enable_segmentation=enable_segmentation,\n smooth_segmentation=smooth_segmentation,\n min_detection_confidence=min_mesh_detection_confidence,\n min_tracking_confidence=min_tracking_confidence,\n )\n\n # --- 프레임 체크\n global CvFpsCalc\n a_cvFpsCalc = CvFpsCalc(buffer_len=10)\n # --- 시작 ---\n while True:\n display_fps = a_cvFpsCalc.get()\n\n # 카메라 On\n ret, image = cap.read()\n if not ret:\n break\n image = cv.flip(image, 1) \n # debug_image = cv.flip(image, 1)\n debug_image = copy.deepcopy(image)\n image = cv.cvtColor(image, cv.COLOR_BGR2RGB)\n \n\n\n # face detection result\n d_results = face_detection.process(image)\n\n # emotion\n # start = time.time()\n \n if count / 1 == 1:\n emotion = emotion_recognition(d_results, debug_image, mobile_VIT)\n dicts['emotion'] = [emotion]\n count += 1\n print(\"time :\", time.time() - start)\n\n elif count / 5 == 1:\n count = 1\n\n else:\n count += 1\n \n\n # holistic result\n image.flags.writeable = False\n h_results = holistic.process(image)\n image.flags.writeable = True\n\n # face mesh\n face_landmarks = h_results.face_landmarks\n face = face_mesh(face_landmarks, cap_width, cap_height)\n dicts['face_mesh'] = face\n\n # hand\n left_hand_landmark = h_results.left_hand_landmarks\n right_hand_landmark = h_results.right_hand_landmarks\n\n left = left_hand(left_hand_landmark, cap_width, cap_height)\n right = right_hand(right_hand_landmark, cap_width, cap_height)\n\n dicts['left_hand'] = left\n dicts['right_hand'] = right\n\n # pose\n pose_landmarks = h_results.pose_landmarks\n pose = pose_landmark(pose_landmarks, cap_width, cap_height)\n dicts['pose'] = pose\n\n dicts_json = json.dumps(dicts)\n sockets.send_json(dicts_json)\n print(display_fps)\n\n\n\n cv.imshow('MediaPipe Holistic', debug_image)\n if cv.waitKey(5) & 0xFF == 27:\n # print(dicts_json)\n # print(display_fps)\n\n break\n\n\nif __name__ == '__main__':\n main()\n print('완료')\n", "repo_name": "koga1694/lookingglassfactory-realtime-motion", "sub_path": "mediapipe_pub.py", "file_name": "mediapipe_pub.py", "file_ext": "py", "file_size_in_byte": 5222, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "cv2.getTickCount", "line_number": 24, "usage_type": "call"}, {"api_name": "cv2.getTickFrequency", "line_number": 25, "usage_type": "call"}, {"api_name": "collections.deque", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.getTickCount", "line_number": 29, "usage_type": "call"}, {"api_name": "time.time", "line_number": 45, "usage_type": "call"}, {"api_name": "zmq.Context", "line_number": 47, "usage_type": "call"}, {"api_name": "zmq.PUB", "line_number": 48, "usage_type": "attribute"}, {"api_name": "mediapipe_zmq.utils.get_args", "line_number": 61, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 85, "usage_type": "call"}, {"api_name": "cv2.CAP_PROP_FRAME_WIDTH", "line_number": 86, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FRAME_HEIGHT", "line_number": 87, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.models.load_model", "line_number": 91, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 91, "usage_type": "attribute"}, {"api_name": "mediapipe.solutions", "line_number": 96, "usage_type": "attribute"}, {"api_name": "mediapipe.solutions", "line_number": 103, "usage_type": "attribute"}, {"api_name": "cv2.flip", "line_number": 125, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 127, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 128, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 128, "usage_type": "attribute"}, {"api_name": "mediapipe_zmq.utils.emotion_recognition", "line_number": 139, "usage_type": "call"}, {"api_name": "time.time", "line_number": 142, "usage_type": "call"}, {"api_name": "mediapipe_zmq.utils.face_mesh", "line_number": 158, "usage_type": "call"}, {"api_name": "mediapipe_zmq.utils.left_hand", "line_number": 165, "usage_type": "call"}, {"api_name": "mediapipe_zmq.utils.right_hand", "line_number": 166, "usage_type": "call"}, {"api_name": "mediapipe_zmq.utils.pose_landmark", "line_number": 173, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 176, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 182, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 183, "usage_type": "call"}]} +{"seq_id": "9970380709", "text": "from sqlalchemy import Column, String, Date, Float, create_engine\nfrom sqlalchemy.orm import Session, sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\nURI = 'mssql+pyodbc://DESKTOP-M0S2O65/blop?driver=SQL+Server'\n\nclass stmt_info(Base):\n __tablename__ = \"STMT_Info\"\n\n date_ = Column(\"dated_on\", Date, primary_key = True)\n paid_to = Column(\"paid_to\", String)\n stmt_desc = Column(\"Stmt_desc\", String)\n balance_amt = Column(\"balance_amt\", Float)\n\n def __int__(self, date, paid_to, stmt_desc, balance_amt):\n date_ = self.date\n paid_to = self.paid_to\n stmt_desc = self.stmt_desc\n balance_amt = self.balance_amt\n\n# Initialize MSSQL DB connection.\nengine_ = create_engine(URI, echo = True)\nBase.metadata.create_all(bind=engine_)\n\nSession = sessionmaker(bind=engine_)\nsession = Session()\n\n# get all balance amunts\nget_all = session.query(stmt_info).all()\n\n# Get grouped balance mat, for each dates.\nget_grouped = session.query(stmt_info).select_from(stmt_info.date_).group_by(stmt_info.date_).all()\nfor i in get_grouped:\n print(i.date_)\n\nsession.close_all()", "repo_name": "Ajay-98/MePayz", "sub_path": "Src/Connectors/Execute_Plotter.py", "file_name": "Execute_Plotter.py", "file_ext": "py", "file_size_in_byte": 1145, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "sqlalchemy.ext.declarative.declarative_base", "line_number": 5, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 11, "usage_type": "call"}, {"api_name": "sqlalchemy.Date", "line_number": 11, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 12, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 12, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 13, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 13, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 14, "usage_type": "call"}, {"api_name": "sqlalchemy.Float", "line_number": 14, "usage_type": "argument"}, {"api_name": "sqlalchemy.create_engine", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 26, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.sessionmaker", "line_number": 26, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 27, "usage_type": "call"}]} +{"seq_id": "9493241956", "text": "\nimport argparse\nimport numpy\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-A', '--observations-A', type = int, default = 50, help = 'No. A observations')\n parser.add_argument('-B', '--observations-B', type = int, default = 50, help = 'No. B observations')\n parser.add_argument('--xmin', type = float, default = -1.0, help = 'Min x')\n parser.add_argument('--ymin', type = float, default = -1.0, help = 'Min y')\n parser.add_argument('--xmax', type = float, default = 1.0, help = 'Max x')\n parser.add_argument('--ymax', type = float, default = 1.0, help = 'Max y')\n\n parser.add_argument('-o', '--output', type = str, required = True, help = 'Output file')\n\n args = parser.parse_args()\n\n f = open(args.output, 'w')\n\n N = args.observations_A + args.observations_B\n \n f.write('%d\\n' % N)\n\n for i in range(args.observations_A):\n\n x = numpy.random.uniform() * (args.xmax - args.xmin) + args.xmin\n y = numpy.random.uniform() * (args.ymax - args.ymin) + args.ymin\n\n f.write('%15.9f %15.9f 0 0.0 1.0\\n' % (x, y))\n\n for i in range(args.observations_B):\n\n x = numpy.random.uniform() * (args.xmax - args.xmin) + args.xmin\n y = numpy.random.uniform() * (args.ymax - args.ymin) + args.ymin\n\n f.write('%15.9f %15.9f 1 0.0 1.0\\n' % (x, y))\n\n f.close()\n \n\n \n \n", "repo_name": "rhyshawkins/TransTessellate2D", "sub_path": "scripts/generatedualtemplatepoints.py", "file_name": "generatedualtemplatepoints.py", "file_ext": "py", "file_size_in_byte": 1384, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "27", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 7, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 28, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 29, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 35, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 36, "usage_type": "attribute"}]} +{"seq_id": "69981314944", "text": "from recognition.face_recognition import train_generator, build_model\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.neighbors import RadiusNeighborsClassifier, KNeighborsClassifier\r\nfrom sklearn.model_selection import StratifiedKFold\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.svm import LinearSVC\r\nimport glob\r\nfrom datetime import datetime\r\nimport tensorflow as tf\r\nfrom utils.split_utils import read_splitted, load_images, load_image, read_data\r\nimport numpy as np\r\nfrom sklearn.metrics import confusion_matrix, classification_report\r\nimport seaborn as sn\r\nimport csv\r\n\r\n\r\n# from mpl_toolkits.mplot3d import Axes3D\r\n\r\n\r\ndef train():\r\n generator, test_generator = train_generator(data_dir, input_shape, 8, 8)\r\n model = build_model(input_shape)\r\n tf.keras.utils.plot_model(model, to_file='model.png')\r\n logdir = \"classification_logs\\\\\" + datetime.now().strftime(\"%Y%m%d-%H%M%S\")\r\n tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=logdir)\r\n model.fit_generator(generator, steps_per_epoch=40, epochs=20, validation_data=test_generator,\r\n workers=1,\r\n validation_steps=20,\r\n callbacks=[\r\n tensorboard_callback\r\n ])\r\n model.save_weights(\"classifier.h5\")\r\n return model\r\n\r\n\r\ndef test():\r\n model = build_model(input_shape)\r\n #model.load_weights(\"./bkp/classifier_xception.h5\")\r\n model.load_weights(\"./classifier.h5\")\r\n return model\r\n\r\n\r\ndef plot_distribution():\r\n X_train, _, y_train, _ = read_splitted(data_dir, test_size=.1)\r\n train_data = load_images(X_train, y_train, input_shape)\r\n train_embeddings = model.predict(np.array(list(train_data[:, 0])), batch_size=10)\r\n pca = PCA(n_components=2)\r\n components = pca.fit_transform(train_embeddings)\r\n # colors = {label: np.random.rand(3,) for label in y_train}\r\n colors = {'Indaia': [0.85865774, 0.37650632, 0.50745684], 'Mary': [0.20140247, 0.23166685, 0.5555025],\r\n 'Bernado': [0.5573546, 0.09530458, 0.74360155], 'Carsten': [0.95897643, 0.40382865, 0.00107667],\r\n 'Barbie': [0.50138109, 0.9929755, 0.93214165], 'Bauer': [0.66824179, 0.44940505, 0.86794612],\r\n 'Shisha': [0.74865352, 0.10384365, 0.70145182], 'tedy': [0.33421823, 0.77872292, 0.29918022],\r\n 'Bob': [0.03626006, 0.80469907, 0.52052402], 'Toby': [0.66475028, 0.38716534, 0.52905105],\r\n 'Link': [0.21017388, 0.4747068, 0.559078], 'Ozzy': [0.39641091, 0.3549963, 0.97724448],\r\n 'Selke': [0.95460547, 0.90028715, 0.62342923], 'Feijao': [0.72759571, 0.50212979, 0.3407233],\r\n 'Ebel': [0.4662668, 0.18774943, 0.01507599], 'Edy': [0.45849246, 0.63398482, 0.49569488],\r\n 'Sol': [0.32354957, 0.64919097, 0.14215046], 'Monica': [0.36595567, 0.69431044, 0.77532274]}\r\n labels = colors.keys()\r\n colors = [colors[label] for label in y_train]\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111)\r\n ax.set_title('Xception', fontsize=16)\r\n ax.scatter(components[:, 0], components[:, 1], c=colors, cmap=\"Set2_r\", s=60)\r\n plt.show()\r\n fig.savefig('saved_figure_fig.png')\r\n ax.savefig('saved_figure_ax.png')\r\n\r\n\r\ndef export_tsv():\r\n X_train, _, y_train, _ = read_splitted(data_dir, test_size=.1)\r\n train_data = load_images(X_train, y_train, input_shape)\r\n train_embeddings = model.predict(np.array(list(train_data[:, 0])), batch_size=10)\r\n with open('embeddings.tsv', 'w') as writeFile:\r\n writer = csv.writer(writeFile)\r\n for embedding in train_embeddings:\r\n writer.writerow(embedding)\r\n writeFile.close()\r\n with open('labels.tsv', 'w') as writeFile:\r\n writer = csv.writer(writeFile)\r\n for label in y_train:\r\n writer.writerow([label])\r\n writeFile.close()\r\n\r\n\r\ndef test_open_data():\r\n X_train, _, y_train, _ = read_splitted(data_dir, test_size=.1)\r\n train_data = load_images(X_train, y_train, input_shape)\r\n train_embeddings = model.predict(np.array(list(train_data[:, 0])), batch_size=10)\r\n classifier = RadiusNeighborsClassifier(radius=.4, weights='distance', outlier_label='unknown')\r\n classifier.fit(train_embeddings, y_train)\r\n image, _ = load_image(\"test.jpg\", 'x', input_shape)\r\n embeddings = model.predict(np.array([image]), batch_size=1)\r\n predicted = classifier.predict(embeddings)\r\n print(predicted)\r\n dist, ind = classifier.radius_neighbors(X=embeddings)\r\n print(dist[0])\r\n print(y_train[ind])\r\n\r\n\r\ndef evaluate_classifiers():\r\n X, y = read_data(data_dir)\r\n k_fold = StratifiedKFold(n_splits=10)\r\n folds = list(k_fold.split(X, y))\r\n for classifier_index in range(5):\r\n accuracy = []\r\n for i, (train_index, test_index) in enumerate(folds):\r\n X_train, X_test, y_train, y_test = X[train_index], X[test_index], y[train_index], y[test_index]\r\n train_data, test_data = load_images(X_train, y_train, input_shape), load_images(X_test, y_test, input_shape)\r\n\r\n trainX = model.predict(np.array(list(train_data[:, 0])), batch_size=10)\r\n trainy = y_train\r\n\r\n testX = model.predict(np.array(list(test_data[:, 0])), batch_size=10)\r\n testy = y_test\r\n\r\n if classifier_index == 0:\r\n classifier = RadiusNeighborsClassifier(radius=.4, weights='distance', outlier_label='unknown')\r\n print(\"Usando r-NN 0.4\")\r\n elif classifier_index == 1:\r\n classifier = RadiusNeighborsClassifier(radius=.5, weights='distance', outlier_label='unknown')\r\n print(\"Usando r-NN 0.5\")\r\n elif classifier_index == 2:\r\n classifier = RadiusNeighborsClassifier(radius=.7, weights='distance', outlier_label='unknown')\r\n print(\"Usando r-NN 0.7\")\r\n elif classifier_index == 3:\r\n classifier = KNeighborsClassifier(n_neighbors=5, n_jobs=4, weights='distance')\r\n print(\"Usando k-NN k=5\")\r\n else:\r\n classifier = LinearSVC()\r\n print(\"Usando SVM\")\r\n classifier.fit(trainX, trainy)\r\n labels = [filename.split(\"\\\\\")[-1] for filename in glob.glob(data_dir + \"/*\")]\r\n # labels.append('unknown')\r\n predict = classifier.predict(testX)\r\n acc = classifier.score(testX, testy)\r\n accuracy.append(acc)\r\n # print('Acurácia KNN: {}'.format(100 * acc))\r\n # report = classification_report(testy, predict)\r\n # print(report)\r\n\r\n # testMatrix = confusion_matrix(testy, predict)\r\n # sn.heatmap(testMatrix, annot=True, annot_kws={\"size\": \"16\"}, xticklabels=labels, yticklabels=labels)\r\n # plt.savefig(\"heatmap_{}.jpg\".format(i))\r\n # plt.clf()\r\n\r\n print(\"{}: {}\".format(classifier_index, accuracy))\r\n\r\n\r\nif __name__ == '__main__':\r\n input_shape = (96, 96)\r\n\r\n # data_dir = \"./recognition/augmented_data\" \r\n data_dir = \"./recognition/augmented_data\"\r\n #model = train()\r\n model = test()\r\n model.summary()\r\n\r\n # evaluate_classifiers()\r\n\r\n plot_distribution()\r\n\r\n # export_tsv()\r\n\r\n # test_open_data()\r\n", "repo_name": "MaikHenrique/Teste_Repositorio", "sub_path": "face-recognition.py", "file_name": "face-recognition.py", "file_ext": "py", "file_size_in_byte": 7244, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "recognition.face_recognition.train_generator", "line_number": 21, "usage_type": "call"}, {"api_name": "recognition.face_recognition.build_model", "line_number": 22, "usage_type": "call"}, {"api_name": "tensorflow.keras.utils.plot_model", "line_number": 23, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 23, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 24, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 24, "usage_type": "name"}, {"api_name": "tensorflow.keras.callbacks.TensorBoard", "line_number": 25, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 25, "usage_type": "attribute"}, {"api_name": "recognition.face_recognition.build_model", "line_number": 37, "usage_type": "call"}, {"api_name": "utils.split_utils.read_splitted", "line_number": 44, "usage_type": "call"}, {"api_name": "utils.split_utils.load_images", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 46, "usage_type": "call"}, {"api_name": "sklearn.decomposition.PCA", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "utils.split_utils.read_splitted", "line_number": 71, "usage_type": "call"}, {"api_name": "utils.split_utils.load_images", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 73, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 75, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 80, "usage_type": "call"}, {"api_name": "utils.split_utils.read_splitted", "line_number": 87, "usage_type": "call"}, {"api_name": "utils.split_utils.load_images", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 89, "usage_type": "call"}, {"api_name": "sklearn.neighbors.RadiusNeighborsClassifier", "line_number": 90, "usage_type": "call"}, {"api_name": "utils.split_utils.load_image", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 93, "usage_type": "call"}, {"api_name": "utils.split_utils.read_data", "line_number": 102, "usage_type": "call"}, {"api_name": "sklearn.model_selection.StratifiedKFold", "line_number": 103, "usage_type": "call"}, {"api_name": "utils.split_utils.load_images", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 114, "usage_type": "call"}, {"api_name": "sklearn.neighbors.RadiusNeighborsClassifier", "line_number": 118, "usage_type": "call"}, {"api_name": "sklearn.neighbors.RadiusNeighborsClassifier", "line_number": 121, "usage_type": "call"}, {"api_name": "sklearn.neighbors.RadiusNeighborsClassifier", "line_number": 124, "usage_type": "call"}, {"api_name": "sklearn.neighbors.KNeighborsClassifier", "line_number": 127, "usage_type": "call"}, {"api_name": "sklearn.svm.LinearSVC", "line_number": 130, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 133, "usage_type": "call"}]} +{"seq_id": "24462276883", "text": "import discord\r\nfrom discord.ext import commands\r\n\r\n# Konfiguration\r\ntoken = ''\r\nprefix = '!'\r\n\r\n# Spielfeld\r\nboard = [' ' for _ in range(9)]\r\ncurrent_player = 'X'\r\nplayers = {}\r\n\r\n# Intents konfigurieren\r\nintents = discord.Intents.default()\r\nintents.message_content = True # Aktiviert das Ereignis für Nachrichteninhalte\r\n\r\n# Bot-Client erstellen\r\nbot = commands.Bot(command_prefix=prefix, intents=intents)\r\n\r\n@bot.event\r\nasync def on_error(event, *args, **kwargs):\r\n import traceback\r\n error_message = traceback.format_exc()\r\n print(f'Fehler im Event {event}: {error_message}')\r\n\r\n@bot.event\r\nasync def on_ready():\r\n print(f'Bot ist eingeloggt als {bot.user.name}')\r\n\r\n@bot.command(name='neu')\r\nasync def new_game(ctx):\r\n global board, current_player, players\r\n board = [' ' for _ in range(9)]\r\n current_player = 'X'\r\n players = {}\r\n await ctx.send('Neues Tic-Tac-Toe-Spiel gestartet!\\n' + draw_board())\r\n await ctx.send('Spieler X, gib `!beitreten` ein, um dem Spiel beizutreten!')\r\n\r\n@bot.command(name='zug')\r\nasync def make_move(ctx, position: int):\r\n global board, current_player\r\n\r\n if ctx.author.id in players and current_player == players[ctx.author.id]:\r\n if 1 <= position <= 9 and board[position - 1] == ' ':\r\n board[position - 1] = current_player\r\n\r\n if check_winner():\r\n await ctx.send(draw_board())\r\n await ctx.send(f'Spieler {current_player} gewinnt!')\r\n elif ' ' not in board:\r\n await ctx.send(draw_board())\r\n await ctx.send('Unentschieden!')\r\n else:\r\n current_player = 'O' if current_player == 'X' else 'X'\r\n await ctx.send(draw_board())\r\n await ctx.send(f'Spieler {current_player} ist am Zug.')\r\n else:\r\n await ctx.send('Ungültiger Zug! Bitte wähle eine freie Position von 1 bis 9.')\r\n else:\r\n await ctx.send('Du bist nicht am Zug!')\r\n\r\n@bot.command(name='beitreten')\r\nasync def join_game(ctx):\r\n global players\r\n\r\n if ctx.author.id not in players:\r\n players[ctx.author.id] = 'X' if len(players) % 2 == 0 else 'O'\r\n await ctx.send(f'Spieler {players[ctx.author.id]} ist beigetreten!')\r\n else:\r\n await ctx.send('Du bist bereits im Spiel!')\r\n\r\ndef draw_board():\r\n rows = [board[i:i + 3] for i in range(0, len(board), 3)]\r\n board_str = '\\n'.join([' | '.join(row) for row in rows])\r\n return f'```\\n{board_str}```'\r\n\r\ndef check_winner():\r\n winning_combinations = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]\r\n for combo in winning_combinations:\r\n if board[combo[0]] == board[combo[1]] == board[combo[2]] != ' ':\r\n return True\r\n return False\r\n\r\n@bot.event\r\nasync def on_message(message):\r\n # Prüfe, ob die Nachricht im gewünschten Kanal ist (nach Channel-ID überprüft)\r\n target_channel_id = '1151479089656504354' # Ersetze DEINE_CHANNEL_ID durch die tatsächliche Channel-ID\r\n if message.channel.id == target_channel_id:\r\n if message.content.startswith('!neu'):\r\n await new_game(message.channel)\r\n elif message.content.startswith('!zug'):\r\n try:\r\n position = int(message.content.split()[1])\r\n await make_move(message.channel, position)\r\n except ValueError:\r\n await message.channel.send('Ungültiger Zug! Verwende `!zug [Position]`, um einen Zug zu machen.')\r\n await bot.process_commands(message)\r\n\r\n\r\nbot.run(token)\r\n", "repo_name": "Martin20231/Discord-Tic-Tac-Toe", "sub_path": "tic-tac-toe.py", "file_name": "tic-tac-toe.py", "file_ext": "py", "file_size_in_byte": 3572, "program_lang": "python", "lang": "de", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "discord.Intents.default", "line_number": 14, "usage_type": "call"}, {"api_name": "discord.Intents", "line_number": 14, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.Bot", "line_number": 18, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 18, "usage_type": "name"}, {"api_name": "traceback.format_exc", "line_number": 23, "usage_type": "call"}]} +{"seq_id": "14563442830", "text": "\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.conf.urls.i18n import i18n_patterns\nfrom django.utils.translation import gettext_lazy as _\n\n# Change the header of the admin panel. \nadmin.site.site_header = 'Across Globe Admin Panel'\nadmin.site.index_title = 'Customize App'\n\nurlpatterns = i18n_patterns(\n path(_('admin/'), admin.site.urls),\n path('rosetta/', include('rosetta.urls')),\n path('', include('myblog.urls')),\n path('ckeditor/', include('ckeditor_uploader.urls')),\n path(_('account/'), include('account.urls')),\n path('social-auth/', include('social_django.urls', namespace='social')),\n path('hitcount/', include(('hitcount.urls', 'hitcount'), namespace='hitcount')),\n #path(r'^convert/', include('lazysignup.urls')),\n path('verification/', include('verify_email.urls')),\n path('ads/', include('ads.urls')),\n path(_('shop/'), include('shop.urls')),\n path(_('event/'), include('event.urls')),\n path(_('addlocation/'), include('addlocation.urls')),\n path(_('campaign/'), include('campaign.urls')),\n) \n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n", "repo_name": "bioscom/AcrossGlobe", "sub_path": "Blog/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 1347, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "django.contrib.admin.site", "line_number": 10, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 10, "usage_type": "name"}, {"api_name": "django.contrib.admin.site", "line_number": 11, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 11, "usage_type": "name"}, {"api_name": "django.conf.urls.i18n.i18n_patterns", "line_number": 13, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 14, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 14, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 14, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 14, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 15, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 16, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 16, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 17, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 17, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 18, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 18, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 18, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 19, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 19, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 20, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 20, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 22, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 22, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 23, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 23, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 24, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 24, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 24, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 25, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 25, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 25, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 26, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 26, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 26, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 27, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 27, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 27, "usage_type": "call"}, {"api_name": "django.conf.settings.DEBUG", "line_number": 30, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 30, "usage_type": "name"}, {"api_name": "django.conf.urls.static.static", "line_number": 31, "usage_type": "call"}, {"api_name": "django.conf.settings.MEDIA_URL", "line_number": 31, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 31, "usage_type": "name"}, {"api_name": "django.conf.settings.MEDIA_ROOT", "line_number": 31, "usage_type": "attribute"}, {"api_name": "django.conf.urls.static.static", "line_number": 32, "usage_type": "call"}, {"api_name": "django.conf.settings.STATIC_URL", "line_number": 32, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 32, "usage_type": "name"}, {"api_name": "django.conf.settings.STATIC_ROOT", "line_number": 32, "usage_type": "attribute"}]} +{"seq_id": "16044723224", "text": "from flask import Flask, request, jsonify, render_template\nfrom tic_tac_toe import TicTacToe\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef home():\n return render_template(\"home.html\")\n\n@app.route(\"/game\")\ndef game():\n # Pass data to the template\n data = {\"board\": game.board, \"current_player\": game.current_player}\n return render_template(\"game.html\", **data)\n\ngame = TicTacToe()\n\n@app.route(\"/make_move\", methods=[\"POST\"])\ndef make_move():\n # Get the cell from the request body\n cell = request.json[\"cell\"]\n # Parse the cell id to get the row and column\n row, col = map(int, cell.split(\"-\")[1:])\n # Make the move and check the result\n game.make_move(row, col)\n result = game.check_win()\n\n if result is None:\n # The game is still in progress\n return jsonify({\"board\": game.board, \"current_player\": game.current_player})\n elif result == \"D\":\n # The game is a draw\n game.reset()\n return jsonify({\"board\": game.board, \"result\": \"D\"})\n else:\n # A player has won the game\n game.reset()\n return jsonify({\"board\": game.board, \"result\": result})\n\nif __name__ == \"__main__\":\n app.run()\n", "repo_name": "gottagofaster236/TicTacToeChatGpt", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1176, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "24", "api": [{"api_name": "flask.Flask", "line_number": 4, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 8, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 14, "usage_type": "call"}, {"api_name": "tic_tac_toe.TicTacToe", "line_number": 16, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 21, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 21, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 30, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 34, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 38, "usage_type": "call"}]} +{"seq_id": "565494793", "text": "import requests\nfrom bs4 import BeautifulSoup as BSoup\nimport csv\nfrom time import sleep\n\ndef get_html(url):\n r = requests.get(url)\n # print(r.status_code)\n # print(r.text)\n return r.text\n\ndef get_total_pages(html):\n soup = BSoup(html, 'lxml')\n pages_ul = soup.find('div', class_=\"pager-wrap\").find('ul')\n last_page = pages_ul.find_all('li')[-1]\n total_pages = last_page.find('a').get('href').split('=')[-1]\n # print(total_pages)\n return int(total_pages)\n\ndef get_page_data (html):\n soup = BSoup(html, 'lxml')\n catalogue = soup.find('div', class_='list-view')\n phones = catalogue.find_all('div', class_='item product_listbox oh')\n # print(phones)\n for phone in phones:\n try:\n name = phone.find('div', class_='listbox_title').text.strip()\n except:\n name = 'just_phone'\n \n try:\n price = phone.find('div', class_='listbox_price').text.strip()\n except:\n price = 'Not indicated'\n\n try:\n img_link = phone.find('div', class_='listbox_img pull-left').find('img').get('src')\n if 'images/product' in img_link:\n img = 'https://www.kivano.kg' + img_link\n else:\n img = 'https:' + img_link\n except:\n img = 'https://media.istockphoto.com/photos/dog-on-the-phone-picture-id473502112?k=20&m=473502112&s=612x612&w=0&h=-XfSN-riSPMZ_ZA-5NtCPTLXtgJLdTFtQ5bBoGxguyQ='\n # print(name)\n # print(price)\n # print(img)\n\n data = {\n 'name': name,\n 'price': price,\n 'img': img}\n # print(data)\n write_to_csv(data)\n\ndef write_headers():\n with open('phones_kivano.csv', 'a') as file:\n fieldnames = ['Name', 'Price', 'Photo']\n writer = csv.DictWriter(file, fieldnames=fieldnames)\n writer.writeheader()\n\ndef write_to_csv(data):\n with open('phones_kivano.csv', 'a') as file:\n fieldnames = ['Name', 'Price', 'Photo']\n writer = csv.DictWriter(file, fieldnames=fieldnames)\n writer.writerow({'Name': data['name'], 'Price': data['price'], 'Photo': data['img']})\n\ndef main():\n with open('phones_kivano.csv', 'w') as file: pass\n write_headers()\n url_ = 'https://www.kivano.kg/mobilnye-telefony'\n # get_total_pages(get_html(url_))\n\n i = 1\n while i <= get_total_pages(get_html(url_)):\n url = f'https://www.kivano.kg/mobilnye-telefony?page={i}'\n print(url)\n html = get_html(url)\n catalogue = BSoup(html, 'lxml').find('div', class_='list-view')\n if not catalogue:\n break\n get_page_data(html)\n i += 1\n\nwhile True:\n main()\n sleep(3600)", "repo_name": "EA1127/Python_14", "sub_path": "week4/day20/parcing_1hackathon/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2704, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "requests.get", "line_number": 7, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 13, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 21, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 58, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 64, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 78, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 86, "usage_type": "call"}]} +{"seq_id": "17314083496", "text": "from pyspark.sql.types import StructType, StructField, StringType\nfrom graphframes import GraphFrame\nfrom rdflib.term import Variable\nfrom pyspark.sql.functions import udf, col, first\n\n@udf\ndef _escape_udf(s):\n return s.replace(\".\", \"_\")\n\nclass PySPARQLConstructResult:\n \"\"\"This is a class representation of the result of a `construct` query.\n In particular, it has properties that return the results as a \n :class:`pyspark.sql.DataFrame` or as a :class:`graphframes.GraphFrame`, \n depending on user needs.\n \"\"\"\n\n __SCHEMA = StructType([\n StructField(\"subject\", StringType()),\n StructField(\"predicate\", StringType()),\n StructField(\"object\", StringType())\n ])\n \n __VERTICES_QUERY = \"\"\"\n SELECT DISTINCT ?subject ?predicate ?object\n WHERE {\n ?subject ?predicate ?object\n FILTER (isLiteral(?object))\n }\n \"\"\"\n\n __EDGES_QUERY = \"\"\"\n SELECT DISTINCT ?subject ?predicate ?object\n WHERE {\n ?subject ?predicate ?object\n FILTER (!isLiteral(?object))\n }\n \"\"\"\n \n __QUERY = \"\"\"\n SELECT DISTINCT ?subject ?predicate ?object\n WHERE {\n ?subject ?predicate ?object\n }\n \"\"\"\n \n def __init__(self, spark, sparql_result):\n self.spark = spark\n self.sparql_result = sparql_result\n \n def __to_dataframe(self, sparql_result):\n \n def __term_to_string(sparql_row): \n return [\n str(sparql_row[Variable(\"subject\")]),\n str(sparql_row[Variable(\"predicate\")]),\n str(sparql_row[Variable(\"object\")])\n ]\n \n data = list(map(__term_to_string, sparql_result))\n return self.spark.createDataFrame(data, schema=self.__SCHEMA)\n \n \n @property\n def dataFrame(self):\n \"\"\"A DataFrame of triples representing the constructed graph. \n\n :type: :class:`pyspark.sql.DataFrame`\n \"\"\"\n\n sparql_result = self.sparql_result.query(self.__QUERY)\n return self.__to_dataframe(sparql_result)\n \n @property\n def verticesDataFrame(self):\n \"\"\"A DataFrame representing the vertices and literals of the \n constructed graph.\n\n :type: :class:`pyspark.sql.DataFrame`\n \"\"\"\n\n vertices_sparql_result = self.sparql_result.query(self.__VERTICES_QUERY)\n return self.__to_dataframe(vertices_sparql_result) \\\n .withColumn(\"predicate\", _escape_udf(col(\"predicate\"))) \\\n .groupby(\"subject\") \\\n .pivot(\"predicate\") \\\n .agg(first(\"object\")) \\\n .withColumnRenamed(\"subject\", \"id\")\n\n @property\n def edgesDataFrame(self):\n \"\"\"A DataFrame of triples representing the egdes of the \n constructed graph.\n\n :type: :class:`pyspark.sql.DataFrame`\n \"\"\"\n\n edges_sparql_result = self.sparql_result.query(self.__EDGES_QUERY)\n return self.__to_dataframe(edges_sparql_result) \\\n .withColumnRenamed(\"subject\", \"src\") \\\n .withColumnRenamed(\"object\", \"dst\") \\\n .withColumnRenamed(\"predicate\", \"relationship\")\n \n @property\n def graphFrame(self):\n \"\"\"A GraphFrame representation of the constructed graph.\n\n :type: :class:`graphframes.GraphFrame`\n \"\"\"\n\n return GraphFrame(\n self.verticesDataFrame, \n self.edgesDataFrame\n )", "repo_name": "chimera-suite/PySPARQL", "sub_path": "PySPARQL/ConstructResult.py", "file_name": "ConstructResult.py", "file_ext": "py", "file_size_in_byte": 3368, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "pyspark.sql.functions.udf", "line_number": 6, "usage_type": "name"}, {"api_name": "pyspark.sql.types.StructType", "line_number": 17, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 18, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StringType", "line_number": 18, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 19, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StringType", "line_number": 19, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StructField", "line_number": 20, "usage_type": "call"}, {"api_name": "pyspark.sql.types.StringType", "line_number": 20, "usage_type": "call"}, {"api_name": "rdflib.term.Variable", "line_number": 54, "usage_type": "call"}, {"api_name": "rdflib.term.Variable", "line_number": 55, "usage_type": "call"}, {"api_name": "rdflib.term.Variable", "line_number": 56, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 83, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.first", "line_number": 86, "usage_type": "call"}, {"api_name": "graphframes.GraphFrame", "line_number": 110, "usage_type": "call"}]} +{"seq_id": "509860626", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom tqdm import tqdm as tqdm\nimport matplotlib.pyplot as plt\n\nclass DataIterator(object):\n def __init__(self, X, y, batch_size, shuffle=False):\n self.X = X # X is of shape (n_bags, n_items, lengthxdim)\n self.y = y # y is of shape (n_bags, )\n self.batch_size = batch_size # batch of bags\n self.shuffle = shuffle\n self.L = self.X.shape[0] # n_bags\n\n self.d = self.X.shape[-1] # length x dim (flattened vectorial representation of a time-series)\n \n def __len__(self):\n return len(self.y)//self.batch_size\n\n def get_iterator(self, loss=0.0):\n if self.shuffle:\n rng_state = np.random.get_state()\n np.random.shuffle(self.X)\n np.random.set_state(rng_state)\n np.random.shuffle(self.y)\n np.random.set_state(rng_state)\n return self.next_batch()\n \n def next_batch(self):\n start = 0\n end = self.batch_size\n while end <= self.L:\n yield self.X[start:end], self.y[start:end] # X (batch_size , n_items, lengthxdim)\n start = end\n end += self.batch_size\n \n \nclass DataIteratorSeq(object):\n def __init__(self, X, y, shuffle=False):\n \n self.X = X # X is of shape (n_bags, n_items, length, dim)\n self.y = y # y is of shape (n_bags, )\n self.batch_size = 1 # one batch is one bag\n self.shuffle = shuffle\n self.L = self.X.shape[0] # n_bags\n \n # stack dimensions\n self.X = self.X.reshape(X.shape[0],X.shape[1],X.shape[2]*X.shape[3])\n\n self.d = self.X.shape[-1] # length x dim (flattened vectorial representation of a time-series)\n \n def __len__(self):\n return len(self.y) # each batch is one bag\n\n def get_iterator(self, loss=0.0):\n if self.shuffle: \n rng_state = np.random.get_state()\n np.random.shuffle(self.X)\n np.random.set_state(rng_state)\n np.random.shuffle(self.y)\n np.random.set_state(rng_state)\n return self.next_batch()\n \n def next_batch(self):\n start = 0\n end = self.batch_size\n while end <= self.L:\n yield self.X[start:end], self.y[start:end] # X (batch_size , n_items, lengthxdim)\n start = end\n end += self.batch_size\n \nclass Trainer(object):\n\n def __init__(self, in_dims, model, num_epochs=1000):\n \n self.model = model(in_dims) #.cuda()\n \n# self.l = nn.L1Loss()\n self.l = nn.MSELoss()\n \n \n self.optim = optim.Adadelta(self.model.parameters(), lr=1e-3)#,weight_decay=1e-2)\n# self.scheduler = optim.lr_scheduler.ReduceLROnPlateau(self.optim, factor=0.5, patience=50, verbose=True)\n \n self.num_epochs = num_epochs\n \n def fit(self, train,test=None):\n \n train_loss = 0.0\n best_mae = 1.0e3\n best_mse = 1.0e6\n losses = [] \n for j in range(self.num_epochs):\n \n train_iterator = train.get_iterator(train_loss)\n \n for X, y in train_iterator:\n self.optim.zero_grad()\n y_pred = self.model(Variable(X)).reshape(-1) #.cuda()\n \n loss = self.l(y_pred, Variable(y)) #.cuda()\n \n losses.append(loss.detach())\n loss.backward()\n \n self.optim.step()\n \n\n if j%50==0:\n print('Train loss: {0:.6f}'.format(loss.data.cpu().numpy()))\n \n #plt.plot(losses[50:])\n #plt.show() \n def evaluate(self, test, return_all=False):\n counts = 0\n sum_mae = 0.\n sum_mse = 0.\n test_iterator = test.get_iterator()\n pred = []\n true = []\n for X, y in test_iterator:\n counts += 1\n y_pred = self.model(Variable(X))#.cuda()) #\n sum_mse += self.l(y_pred, Variable(y)).data.cpu().numpy() #.cuda()\n pred.append(y_pred.detach())\n true.append(y.detach())\n if return_all:\n return {'pred':pred,'true':true}\n else:\n return np.asscalar(sum_mse/counts)\n \n def predict(self, test):\n y_preds = []\n for X, y in test.next_batch():\n y_pred = self.model(Variable(X)) #.cuda()\n y_preds.append(y_pred.data.cpu().numpy())\n return np.concatenate(y_preds)\n \ndef init_weights(m):\n if type(m) == nn.Linear:\n torch.nn.init.kaiming_normal_(m.weight) \n\nclass DeepSet(nn.Module):\n\n def __init__(self, in_features, set_features=50):\n super(DeepSet, self).__init__()\n self.in_features = in_features\n set_features = in_features\n self.out_features = set_features\n\n self.feature_extractor = nn.Sequential(\n nn.Linear(in_features, 200),\n nn.ELU(inplace=True),\n nn.Linear(200, 200),\n nn.ELU(inplace=True),\n nn.Linear(200, 100),\n nn.ELU(inplace=True),\n# nn.Dropout(0.3),\n nn.Linear(100, set_features)\n )\n #self.feature_extractor.apply(init_weights)\n\n self.regressor = nn.Sequential(\n nn.Linear(set_features, 30),\n nn.ELU(inplace=True),\n nn.Linear(30, 10),\n nn.ELU(inplace=True),\n nn.Linear(10,1)\n )\n #self.regressor.apply(init_weights)\n self.add_module('0', self.feature_extractor)\n self.add_module('1', self.regressor)\n \n \n\n def reset_parameters(self):\n for module in self.children():\n reset_op = getattr(module, \"reset_parameters\", None)\n if callable(reset_op):\n reset_op()\n \n def forward(self, inp):\n x = self.feature_extractor(inp)\n x = torch.mean(x,dim=1) # x: (batch_size, n_items, L*d) sum items # x.sum(dim=1\n x = self.regressor(x)\n return x\n \n \nclass DeepSetRNN(nn.Module):\n\n def __init__(self, in_features, set_features=50):\n super(DeepSetRNN, self).__init__()\n \n self.in_features = in_features # the dimension of the time series\n self.out_features = set_features # dim of the hidden state\n self.feature_extractor = nn.RNN(input_size=in_features, hidden_size=set_features, num_layers=1, batch_first=True)\n\n self.regressor = nn.Sequential(\n nn.Linear(set_features, 30),\n nn.ReLU(),\n nn.Linear(30, 30),\n nn.ReLU(),\n nn.Linear(30, 10),\n nn.ReLU(),\n nn.Linear(10, 1),\n )\n \n self.add_module('0', self.feature_extractor)\n self.add_module('1', self.regressor)\n \n def init_hidden(self, batch_size):\n return torch.zeros(1, batch_size, self.out_features) #.cuda()\n \n def reset_parameters(self):\n for module in self.children():\n reset_op = getattr(module, \"reset_parameters\", None)\n if callable(reset_op):\n reset_op()\n \n def forward(self, inp):\n hidden = self.init_hidden(inp.size(0))\n rnn_out, _ = self.feature_extractor(inp, hidden)\n x = rnn_out.sum(dim=1)\n x = self.regressor(x)\n return x\n \n \n \nclass DeepSetGRU(nn.Module):\n\n def __init__(self, in_features, set_features=200):\n super(DeepSetGRU, self).__init__()\n \n self.in_features = in_features\n self.out_features = set_features\n self.feature_extractor = nn.GRU(in_features, set_features, 1, batch_first=True)\n\n self.regressor = nn.Sequential(\n nn.Linear(set_features, 200),\n nn.ReLU(),\n nn.Linear(200, 100),\n nn.ReLU(),\n nn.Linear(100, 1),\n )\n \n self.add_module('0', self.feature_extractor)\n self.add_module('1', self.regressor)\n \n def init_hidden(self, batch_size):\n return torch.zeros(1, batch_size, self.out_features) #.cuda()\n \n def reset_parameters(self):\n for module in self.children():\n reset_op = getattr(module, \"reset_parameters\", None)\n if callable(reset_op):\n reset_op()\n \n def forward(self, inp):\n hidden = self.init_hidden(inp.size(0))\n rnn_out, _ = self.feature_extractor(inp, hidden)\n x = rnn_out.sum(dim=1)\n x = self.regressor(x)\n return x\n \n \n \nclass DeepSetLSTM(nn.Module):\n\n def __init__(self, in_features, set_features=200):\n super(DeepSetLSTM, self).__init__()\n \n self.in_features = in_features\n self.out_features = set_features\n self.feature_extractor = nn.LSTM(in_features, set_features, 1, batch_first=True)\n\n self.regressor = nn.Sequential(\n nn.Linear(set_features, 200),\n nn.ReLU(),\n# nn.Linear(200, 200),\n# nn.ReLU(),\n nn.Linear(200, 1),\n )\n \n self.add_module('0', self.feature_extractor)\n self.add_module('1', self.regressor)\n \n def init_hidden(self, batch_size):\n return torch.zeros(1, batch_size, self.out_features), torch.zeros(1, batch_size, self.out_features) #.cuda() #.cuda()\n \n def reset_parameters(self):\n for module in self.children():\n reset_op = getattr(module, \"reset_parameters\", None)\n if callable(reset_op):\n reset_op()\n \n def forward(self, inp):\n hidden = self.init_hidden(inp.size(0))\n rnn_out, (_,_) = self.feature_extractor(inp, hidden)\n x = rnn_out.sum(dim=1)\n x = self.regressor(x)\n return x", "repo_name": "maudl3116/Distribution_Regression_Streams", "sub_path": "src/deep_sets.py", "file_name": "deep_sets.py", "file_ext": "py", "file_size_in_byte": 9928, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "numpy.random.get_state", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 25, "usage_type": "attribute"}, {"api_name": "numpy.random.shuffle", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 26, "usage_type": "attribute"}, {"api_name": "numpy.random.set_state", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 27, "usage_type": "attribute"}, {"api_name": "numpy.random.shuffle", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 28, "usage_type": "attribute"}, {"api_name": "numpy.random.set_state", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 29, "usage_type": "attribute"}, {"api_name": "numpy.random.get_state", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 60, "usage_type": "attribute"}, {"api_name": "numpy.random.shuffle", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 61, "usage_type": "attribute"}, {"api_name": "numpy.random.set_state", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 62, "usage_type": "attribute"}, {"api_name": "numpy.random.shuffle", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 63, "usage_type": "attribute"}, {"api_name": "numpy.random.set_state", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 64, "usage_type": "attribute"}, {"api_name": "torch.nn.MSELoss", "line_number": 82, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 82, "usage_type": "name"}, {"api_name": "torch.optim.Adadelta", "line_number": 85, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 85, "usage_type": "name"}, {"api_name": "torch.autograd.Variable", "line_number": 102, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 104, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 126, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.asscalar", "line_number": 133, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 140, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 143, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 143, "usage_type": "name"}, {"api_name": "torch.nn.init.kaiming_normal_", "line_number": 144, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 144, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 146, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 146, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 154, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 154, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 155, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 155, "usage_type": "name"}, {"api_name": "torch.nn.ELU", "line_number": 156, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 156, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 157, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 157, "usage_type": "name"}, {"api_name": "torch.nn.ELU", "line_number": 158, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 158, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 159, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 159, "usage_type": "name"}, {"api_name": "torch.nn.ELU", "line_number": 160, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 160, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 162, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 166, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 166, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 167, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 167, "usage_type": "name"}, {"api_name": "torch.nn.ELU", "line_number": 168, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 168, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 169, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 169, "usage_type": "name"}, {"api_name": "torch.nn.ELU", "line_number": 170, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 170, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 171, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 171, "usage_type": "name"}, {"api_name": "torch.mean", "line_number": 187, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 192, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 192, "usage_type": "name"}, {"api_name": "torch.nn.RNN", "line_number": 199, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 199, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 201, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 201, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 202, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 202, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 203, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 203, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 204, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 204, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 205, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 205, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 206, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 206, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 207, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 207, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 208, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 208, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 215, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 232, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 232, "usage_type": "name"}, {"api_name": "torch.nn.GRU", "line_number": 239, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 239, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 241, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 241, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 242, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 242, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 243, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 243, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 244, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 244, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 245, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 245, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 246, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 246, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 253, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 270, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 270, "usage_type": "name"}, {"api_name": "torch.nn.LSTM", "line_number": 277, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 277, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 279, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 279, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 280, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 280, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 281, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 281, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 284, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 284, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 291, "usage_type": "call"}]} +{"seq_id": "33155746353", "text": "import multiprocessing\nimport time\nimport os\n\n\n# 定义一个准备作为进程任务的函数\ndef action(max):\n my_sum = 0\n for i in range(max):\n print('(%s)进程正在执行: %d' % (os.getpid(), i))\n my_sum += i\n return my_sum\n\n\nif __name__ == '__main__':\n # 创建一个包含 4 条进程的进程池\n with multiprocessing.Pool(processes=4) as pool:\n # 使用进程执行 map 计算\n # 后面元组有 3 个元素,因此程序启动 3 条进程来执行 action 函数\n results = pool.map(action, (50, 100, 150))\n print('--------------')\n for r in results:\n print(r)\n", "repo_name": "baidongbin/python", "sub_path": "疯狂Python讲义/codes/14/14.9/pool_test2.py", "file_name": "pool_test2.py", "file_ext": "py", "file_size_in_byte": 647, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "os.getpid", "line_number": 10, "usage_type": "call"}, {"api_name": "multiprocessing.Pool", "line_number": 17, "usage_type": "call"}]} +{"seq_id": "33484684835", "text": "from __future__ import annotations\n\nimport threading\nimport time\nfrom typing import TYPE_CHECKING, List\n\nif TYPE_CHECKING:\n from Events.EventLogger import EventLogger\n from Tasks.Task import Task\n\nimport importlib\nfrom pkgutil import iter_modules\nfrom inspect import isclass\nimport signal\n\nimport math\nimport atexit\nfrom typing import Type\n\nfrom GUIs import Colors\nfrom Elements.LabelElement import LabelElement\nimport pygame\n\nfrom Sources.EmptySource import EmptySource\nfrom Sources.EmptyTouchScreenSource import EmptyTouchScreenSource\nfrom Workstation.WorkstationGUI import WorkstationGUI\nimport Utilities.Exceptions as pyberror\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nimport sys\nimport os\nimport ast\nimport traceback\nfrom screeninfo import get_monitors\n\n\nclass Workstation:\n\n def __init__(self):\n self.tasks = {}\n self.event_loggers = {}\n\n # Core application details\n QCoreApplication.setOrganizationName(\"TNEL\")\n QCoreApplication.setOrganizationDomain(\"tnelab.org\")\n QCoreApplication.setApplicationName(\"Pybehav\")\n\n # Load information from settings or set defaults\n settings = QSettings()\n # Store information on the available sources\n package_dir = \"Sources/\"\n for (_, module_name, _) in iter_modules([package_dir]):\n # import the module and iterate through its attributes\n module = importlib.import_module(f\"Sources.{module_name}\")\n for attribute_name in dir(module):\n attribute = getattr(module, attribute_name)\n if isclass(attribute):\n # Add the class to this package's variables\n globals()[attribute_name] = attribute\n if settings.contains(\"sources\"):\n self.sources = eval(settings.value(\"sources\"))\n else:\n self.sources = {\"es\": EmptySource(), \"etss\": EmptyTouchScreenSource(\"(1024, 768)\")}\n settings.setValue(\"sources\", '{\"es\": EmptySource(), \"etss\": EmptyTouchScreenSource(\"(1024, 768)\")}')\n # Store the number of available chambers\n if settings.contains(\"n_chamber\"):\n self.n_chamber = int(settings.value(\"n_chamber\"))\n else:\n self.n_chamber = 1\n settings.setValue(\"n_chamber\", self.n_chamber)\n\n # Store the position of the pygame window\n if settings.contains(\"pygame/offset\"):\n offset = ast.literal_eval(settings.value(\"pygame/offset\"))\n else:\n m = get_monitors()[0]\n offset = (m.width / 6, 30)\n settings.setValue(\"pygame/offset\", str(offset))\n\n os.environ['SDL_VIDEO_WINDOW_POS'] = '%i,%i' % offset # Position the pygame window\n pygame.init()\n pygame.display.set_caption(\"Pybehav\")\n\n # Compute the arrangement of chambers in the pygame window\n if settings.contains(\"pygame/n_row\"):\n self.n_row = int(settings.value(\"pygame/n_row\"))\n self.n_col = int(settings.value(\"pygame/n_col\"))\n self.w = int(settings.value(\"pygame/w\"))\n self.h = int(settings.value(\"pygame/h\"))\n self.task_gui = pygame.display.set_mode((self.w * self.n_col, self.h * self.n_row), pygame.RESIZABLE, 32)\n else:\n self.compute_chambergui()\n\n self.ed = None\n self.guis = {}\n app = QApplication(sys.argv)\n self.wsg = WorkstationGUI(self)\n self.thread_events = {}\n self.event_notifier = threading.Event()\n self.stopping = False\n guithread = threading.Thread(target=lambda: self.gui_loop())\n guithread.start()\n taskthread = threading.Thread(target=lambda: self.loop())\n taskthread.start()\n eventthread = threading.Thread(target=lambda: self.event_loop())\n eventthread.start()\n atexit.register(lambda: self.exit_handler())\n signal.signal(signal.SIGTERM, self.exit_handler)\n signal.signal(signal.SIGINT, self.exit_handler)\n sys.exit(app.exec())\n\n def compute_chambergui(self) -> None:\n settings = QSettings()\n szo = pygame.display.get_desktop_sizes()\n szo = szo[0]\n sz = (int(szo[0] * 5 / 6), int(szo[1] - 70))\n self.n_row = 1\n self.n_col = self.n_chamber\n self.w = math.floor(sz[0] / self.n_chamber)\n self.h = math.floor(sz[0] / self.n_chamber * 2)\n if self.h > sz[1]:\n self.h = sz[1]\n self.w = math.floor(sz[1] / 2)\n while self.h < math.floor(sz[1] / (self.n_row + 1)) or self.n_col * self.w > sz[0]:\n self.n_row += 1\n self.h = math.floor(sz[1] / self.n_row)\n self.w = math.floor(self.h / 2)\n self.n_col = math.ceil(self.n_chamber / self.n_row)\n settings.setValue(\"pygame/n_row\", self.n_row)\n settings.setValue(\"pygame/n_col\", self.n_col)\n settings.setValue(\"pygame/w\", self.w)\n settings.setValue(\"pygame/h\", self.h)\n settings.setValue(\"pyqt/w\", int(szo[0] / 6))\n settings.setValue(\"pyqt/h\", int(szo[1] - 70))\n self.task_gui = pygame.display.set_mode((self.w * self.n_col, self.h * self.n_row), pygame.RESIZABLE, 32)\n\n def add_task(self, chamber: int, task_name: str, subject_name: str, address_file: str, protocol: str, task_event_loggers: List[EventLogger]) -> None:\n \"\"\"\n Creates a Task and adds it to the chamber.\n\n Parameters\n ----------\n chamber : int\n The index of the chamber where the task will be added\n task_name : string\n The name corresponding to the Task class\n address_file : string\n The file path for the Address File\n protocol : string\n The file path for the Protocol\n task_event_loggers : list\n The list of EventLoggers for the task\n \"\"\"\n # Import the selected Task\n task_module = importlib.import_module(\"Local.Tasks.\" + task_name)\n task = getattr(task_module, task_name)\n metadata = {\"chamber\": chamber, \"subject\": subject_name, \"protocol\": protocol, \"address_file\": address_file}\n try:\n self.tasks[chamber] = task(self, metadata, self.sources, address_file, protocol) # Create the task\n self.event_loggers[chamber] = task_event_loggers\n self.thread_events[chamber] = (threading.Event(), threading.Event(), threading.Event(), threading.Event(),\n threading.Event(), threading.Event())\n for logger in task_event_loggers:\n logger.set_task(self.tasks[chamber])\n # Import the Task GUI\n gui = getattr(importlib.import_module(\"Local.GUIs.\" + task_name + \"GUI\"), task_name + \"GUI\")\n # Position the GUI in pygame\n col = chamber % self.n_col\n row = math.floor(chamber / self.n_col)\n # Create the GUI\n self.guis[chamber] = gui(self.task_gui.subsurface(col * self.w, row * self.h, self.w, self.h),\n self.tasks[chamber])\n except BaseException as e:\n print(type(e).__name__)\n self.ed = QMessageBox()\n self.ed.setIcon(QMessageBox.Critical)\n self.ed.setWindowTitle(\"Error adding task\")\n if isinstance(e, pyberror.ComponentRegisterError):\n self.ed.setText(\"A Component failed to register\\n\"+traceback.format_exc())\n elif isinstance(e, pyberror.SourceUnavailableError):\n self.ed.setText(\"A requested Source is currently unavailable\")\n elif isinstance(e, pyberror.MalformedProtocolError):\n self.ed.setText(\"Error raised when parsing Protocol file\\n\"+traceback.format_exc())\n elif isinstance(e, pyberror.MalformedAddressFileError):\n self.ed.setText(\"Error raised when parsing AddressFile\\n\"+traceback.format_exc())\n elif isinstance(e, pyberror.InvalidComponentTypeError):\n self.ed.setText(\"A Component in the AddressFile is an invalid type\")\n else:\n self.ed.setText(\"Unhandled exception\\n\"+traceback.format_exc())\n self.ed.setStandardButtons(QMessageBox.Ok)\n self.ed.show()\n raise pyberror.AddTaskError\n\n def switch_task(self, task_base: Task, task_name: Type[Task], protocol: str = None) -> Task:\n \"\"\"\n Switch the active Task in a sequence.\n\n Parameters\n ----------\n task_base : Task\n The base Task of the sequence\n task_name : Class\n The next Task in the sequence\n protocol : dict\n Dictionary representing the protocol for the new Task\n \"\"\"\n # Create the new Task as part of a sequence\n new_task = task_name(task_base, task_base.components, protocol)\n gui = getattr(importlib.import_module(\"Local.GUIs.\" + task_name.__name__ + \"GUI\"), task_name.__name__ + \"GUI\")\n # Position the GUI in pygame\n col = task_base.metadata['chamber'] % self.n_col\n row = math.floor(task_base.metadata['chamber'] / self.n_col)\n # Create the GUI\n self.guis[task_base.metadata['chamber']].sub_gui = gui(\n self.task_gui.subsurface(col * self.w, row * self.h, self.w, self.h),\n new_task)\n return new_task\n\n def remove_task(self, chamber: int, del_loggers: bool = True) -> threading.Thread:\n \"\"\"\n Remove the Task from the specified chamber.\n\n Parameters\n ----------\n del_loggers\n chamber : int\n The chamber from which a Task should be removed\n \"\"\"\n remove_thread = threading.Thread(target=lambda: self.remove_task_(chamber, del_loggers))\n remove_thread.start()\n return remove_thread\n\n def remove_task_(self, chamber: int, del_loggers: bool = True) -> None:\n if chamber in self.thread_events:\n self.thread_events[chamber][0].set()\n self.event_notifier.set()\n self.thread_events[chamber][1].wait()\n self.thread_events[chamber][2].wait()\n self.thread_events[chamber][4].wait()\n if chamber in self.event_loggers.keys():\n if del_loggers:\n for el in self.event_loggers[chamber]: # Close all associated EventLoggers\n el.close_()\n del self.event_loggers[chamber]\n if chamber in self.tasks.keys():\n self.tasks[chamber].clear()\n for c in self.tasks[chamber].components:\n c.close()\n del self.tasks[chamber]\n if chamber in self.guis.keys():\n del self.guis[chamber]\n if chamber in self.thread_events.keys():\n del self.thread_events[chamber]\n\n def start_task(self, chamber: int) -> None:\n \"\"\"\n Start the Task in the specified chamber.\n\n Parameters\n ----------\n chamber : int\n The chamber corresponding to the Task that should be started\n \"\"\"\n self.tasks[chamber].start__() # Start the Task\n for el in self.event_loggers[chamber]: # Start all EventLoggers\n el.start_()\n self.thread_events[chamber][3].set()\n\n def stop_task(self, chamber: int) -> None:\n \"\"\"\n Stop the Task in the specified chamber.\n\n Parameters\n ----------\n chamber : int\n The chamber corresponding to the Task that should be stopped\n \"\"\"\n self.thread_events[chamber][3].clear()\n self.tasks[chamber].stop__() # Stop the task\n self.event_notifier.set()\n\n def event_loop(self) -> None:\n while not self.stopping:\n self.event_notifier.wait()\n self.event_notifier.clear()\n keys = list(self.thread_events.keys())\n for key in keys:\n if key in self.thread_events and not self.thread_events[key][0].is_set():\n ecopy = self.tasks[key].events.copy()\n self.tasks[key].events = []\n for el in self.event_loggers[key]:\n if el.started:\n el.log_events(ecopy)\n if not self.tasks[key].started:\n for el in self.event_loggers[key]:\n if el.started:\n el.stop_()\n elif key in self.thread_events and not self.thread_events[key][4].is_set():\n self.thread_events[key][4].set()\n time.sleep(0)\n\n def loop(self) -> None:\n \"\"\"\n Master event loop for all Tasks. Handles Task logic and Task Events.\n \"\"\"\n cps = 0\n while not self.stopping:\n cps += 1\n events = pygame.event.get() # Get mouse/keyboard events\n task_keys = list(self.tasks.keys())\n for key in task_keys: # For each Task\n keys = list(self.thread_events.keys())\n if key in keys:\n if not self.thread_events[key][0].is_set():\n if key in self.thread_events and self.thread_events[key][3].is_set() and not self.tasks[key].paused: # If the Task has been started and is not paused\n if len(self.tasks[key].events) > 0 and not self.event_notifier.is_set():\n self.event_notifier.set()\n self.tasks[key].main_loop() # Run the Task's logic loop\n self.guis[key].handle_events(events) # Handle mouse/keyboard events with the Task GUI\n if self.tasks[key].is_complete(): # Stop the Task if it is complete\n self.wsg.chambers[key].stop()\n elif key in self.thread_events and not self.thread_events[key][2].is_set():\n self.thread_events[key][2].set()\n time.sleep(0)\n\n def gui_loop(self) -> None:\n last_frame = time.perf_counter()\n while not self.stopping:\n if time.perf_counter() - last_frame > 1/30:\n self.task_gui.fill(Colors.black)\n keys = list(self.guis.keys())\n for key in keys: # For each Task\n if key in self.thread_events and not self.thread_events[key][0].is_set():\n self.guis[key].draw() # Update the GUI\n # Draw GUI border and subject name\n col = key % self.n_col\n row = math.floor(key / self.n_col)\n pygame.draw.rect(self.task_gui, Colors.white, pygame.Rect(col * self.w, row * self.h, self.w, self.h), 1)\n LabelElement(self.guis[key], 10, self.h - 30, self.w, 20,\n self.tasks[key].metadata[\"subject\"], SF=1).draw()\n elif key in self.thread_events and not self.thread_events[key][1].is_set():\n self.thread_events[key][1].set()\n pygame.display.flip() # Signal to pygame that the whole GUI has updated\n last_frame = time.perf_counter()\n time.sleep(0)\n\n def exit_handler(self, *args):\n \"\"\"\n Callback for when py-behav is closed.\n \"\"\"\n self.stopping = True\n for key in self.tasks: # Stop all Tasks\n if self.tasks[key].started:\n self.stop_task(key)\n self.remove_task(key)\n for src in self.sources: # Close all Sources\n self.sources[src].close_source()\n", "repo_name": "tne-lab/py-behav-box-v2", "sub_path": "source/Workstation/Workstation.py", "file_name": "Workstation.py", "file_ext": "py", "file_size_in_byte": 15575, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "typing.TYPE_CHECKING", "line_number": 7, "usage_type": "name"}, {"api_name": "pkgutil.iter_modules", "line_number": 53, "usage_type": "call"}, {"api_name": "importlib.import_module", "line_number": 55, "usage_type": "call"}, {"api_name": "inspect.isclass", "line_number": 58, "usage_type": "call"}, {"api_name": "Sources.EmptySource.EmptySource", "line_number": 64, "usage_type": "call"}, {"api_name": "Sources.EmptyTouchScreenSource.EmptyTouchScreenSource", "line_number": 64, "usage_type": "call"}, {"api_name": "ast.literal_eval", "line_number": 75, "usage_type": "call"}, {"api_name": "screeninfo.get_monitors", "line_number": 77, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 81, "usage_type": "attribute"}, {"api_name": "pygame.init", "line_number": 82, "usage_type": "call"}, {"api_name": "pygame.display.set_caption", "line_number": 83, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 83, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 91, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 91, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 91, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 97, "usage_type": "attribute"}, {"api_name": "Workstation.WorkstationGUI.WorkstationGUI", "line_number": 98, "usage_type": "call"}, {"api_name": "threading.Event", "line_number": 100, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 102, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 104, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 106, "usage_type": "call"}, {"api_name": "atexit.register", "line_number": 108, "usage_type": "call"}, {"api_name": "signal.signal", "line_number": 109, "usage_type": "call"}, {"api_name": "signal.SIGTERM", "line_number": 109, "usage_type": "attribute"}, {"api_name": "signal.signal", "line_number": 110, "usage_type": "call"}, {"api_name": "signal.SIGINT", "line_number": 110, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 111, "usage_type": "call"}, {"api_name": "pygame.display.get_desktop_sizes", "line_number": 115, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 115, "usage_type": "attribute"}, {"api_name": "math.floor", "line_number": 120, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 121, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 124, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 125, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 127, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 128, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 129, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 136, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 136, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 136, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 138, "usage_type": "name"}, {"api_name": "Events.EventLogger.EventLogger", "line_number": 138, "usage_type": "name"}, {"api_name": "importlib.import_module", "line_number": 156, "usage_type": "call"}, {"api_name": "threading.Event", "line_number": 162, "usage_type": "call"}, {"api_name": "threading.Event", "line_number": 163, "usage_type": "call"}, {"api_name": "importlib.import_module", "line_number": 167, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 170, "usage_type": "call"}, {"api_name": "Utilities.Exceptions.ComponentRegisterError", "line_number": 179, "usage_type": "attribute"}, {"api_name": "Utilities.Exceptions", "line_number": 179, "usage_type": "name"}, {"api_name": "traceback.format_exc", "line_number": 180, "usage_type": "call"}, {"api_name": "Utilities.Exceptions.SourceUnavailableError", "line_number": 181, "usage_type": "attribute"}, {"api_name": "Utilities.Exceptions", "line_number": 181, "usage_type": "name"}, {"api_name": "Utilities.Exceptions.MalformedProtocolError", "line_number": 183, "usage_type": "attribute"}, {"api_name": "Utilities.Exceptions", "line_number": 183, "usage_type": "name"}, {"api_name": "traceback.format_exc", "line_number": 184, "usage_type": "call"}, {"api_name": "Utilities.Exceptions.MalformedAddressFileError", "line_number": 185, "usage_type": "attribute"}, {"api_name": "Utilities.Exceptions", "line_number": 185, "usage_type": "name"}, {"api_name": "traceback.format_exc", "line_number": 186, "usage_type": "call"}, {"api_name": "Utilities.Exceptions.InvalidComponentTypeError", "line_number": 187, "usage_type": "attribute"}, {"api_name": "Utilities.Exceptions", "line_number": 187, "usage_type": "name"}, {"api_name": "traceback.format_exc", "line_number": 190, "usage_type": "call"}, {"api_name": "Utilities.Exceptions.AddTaskError", "line_number": 193, "usage_type": "attribute"}, {"api_name": "Utilities.Exceptions", "line_number": 193, "usage_type": "name"}, {"api_name": "Tasks.Task.Task", "line_number": 195, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 195, "usage_type": "name"}, {"api_name": "importlib.import_module", "line_number": 210, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 213, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 230, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 220, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 301, "usage_type": "call"}, {"api_name": "pygame.event.get", "line_number": 310, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 310, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 325, "usage_type": "call"}, {"api_name": "time.perf_counter", "line_number": 328, "usage_type": "call"}, {"api_name": "time.perf_counter", "line_number": 330, "usage_type": "call"}, {"api_name": "GUIs.Colors.black", "line_number": 331, "usage_type": "attribute"}, {"api_name": "GUIs.Colors", "line_number": 331, "usage_type": "name"}, {"api_name": "math.floor", "line_number": 338, "usage_type": "call"}, {"api_name": "pygame.draw.rect", "line_number": 339, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 339, "usage_type": "attribute"}, {"api_name": "GUIs.Colors.white", "line_number": 339, "usage_type": "attribute"}, {"api_name": "GUIs.Colors", "line_number": 339, "usage_type": "name"}, {"api_name": "pygame.Rect", "line_number": 339, "usage_type": "call"}, {"api_name": "Elements.LabelElement.LabelElement", "line_number": 340, "usage_type": "call"}, {"api_name": "pygame.display.flip", "line_number": 344, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 344, "usage_type": "attribute"}, {"api_name": "time.perf_counter", "line_number": 345, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 346, "usage_type": "call"}]} +{"seq_id": "8812967959", "text": "import unittest\nfrom unittest.mock import MagicMock, Mock, patch\nfrom freezegun import freeze_time\nimport datetime as dt\nimport pyRofex\nimport src.model.strategy as stgy\nfrom src.model.instrument_handler import FutureContract\nimport src.model.rate_calculator as rc\nimport src.model.market_apis as mapis\n\n\nclass TestStrategy(unittest.TestCase):\n\n NOW_DATE = \"2022-01-01\"\n\n def setUp(self):\n # Por simplicidad el spot price es el mismo para los dos instrumentos\n self._spot_price = 100.0\n self._yfinance_api_mock = MagicMock()\n last_prices = {\"GGAL\": self._spot_price, \"PAMP\": self._spot_price}\n self._yfinance_api_mock.last_prices.return_value = last_prices\n self._yfinance_api_mock.price.side_effect = lambda ticker: last_prices[ticker]\n\n self._pyrofex_api_mock = MagicMock()\n self._pyrofex_api_mock.bids.return_value = {\n \"GGAL/FEB22\": mapis.OrderBook(110, 10),\n \"PAMP/FEB22\": mapis.OrderBook(120, 10),\n }\n self._pyrofex_api_mock.asks.return_value = {\n \"GGAL/FEB22\": mapis.OrderBook(115, 10),\n \"PAMP/FEB22\": mapis.OrderBook(125, 10),\n }\n self._pyrofex_api_mock.place_order.return_value = {\n \"order\": {\"clientId\": \"test_order_id\"}\n }\n self._pyrofex_api_mock.order_execution_status.return_value = \"UNITTEST\"\n self._tradeable_check_mock = MagicMock()\n self._maturity_date = dt.datetime(2022, 5, 28, 0, 0, 0, 0)\n ggal_future = FutureContract(\"GGAL/FEB22\", \"GGAL\", self._maturity_date, 100.0)\n PAMP_future = FutureContract(\"PAMP/FEB22\", \"PAMP\", self._maturity_date, 100.0)\n self._tradeable_check_mock.tradeable_pyrofex_future_underlier_ticker.return_value = {\n \"GGAL\": [ggal_future],\n \"PAMP\": [PAMP_future],\n }\n self._instrument_handler_mock = MagicMock()\n self._instrument_handler_mock.rofex_instruments_by_ticker.return_value = {\n \"GGAL/FEB22\": ggal_future,\n \"PAMP/FEB22\": PAMP_future,\n }\n self._tradeable_check_mock.tradeable_ticker_maturity.return_value = {\n \"GGAL/FEB22\": \"FEB22\",\n \"PAMP/FEB22\": \"FEB22\",\n }\n self._tradeable_check_mock.tradeable_maturities.return_value = [\"FEB22\"]\n self._implicit_rate_calculator = rc.ImplicitRateCalculator(\n self._pyrofex_api_mock,\n self._yfinance_api_mock,\n self._tradeable_check_mock,\n )\n\n self._data_update_mock = MagicMock()\n self._data_update_mock.update_boolean.return_value = False\n\n self._strategy = stgy.Strategy(\n self._instrument_handler_mock,\n self._implicit_rate_calculator,\n self._pyrofex_api_mock,\n self._yfinance_api_mock,\n self._data_update_mock,\n self._tradeable_check_mock,\n )\n\n @freeze_time(NOW_DATE)\n def test_trader_when_there_is_no_arb_opportunity(self):\n self._pyrofex_api_mock.bids.return_value = {\n \"GGAL/FEB22\": mapis.OrderBook(110, 10),\n \"PAMP/FEB22\": mapis.OrderBook(115, 10),\n }\n self._pyrofex_api_mock.asks.return_value = {\n \"GGAL/FEB22\": mapis.OrderBook(120, 10),\n \"PAMP/FEB22\": mapis.OrderBook(125, 10),\n }\n self._implicit_rate_calculator.update_rates()\n self._strategy.start_trades()\n self.assertEqual(self._pyrofex_api_mock.place_order.call_count, 0)\n\n @freeze_time(NOW_DATE)\n def test_trader_when_arb_exist(self):\n self._implicit_rate_calculator.update_rates()\n self._strategy.start_trades()\n # Testea si se mandan 2 ordenes\n self.assertEqual(self._pyrofex_api_mock.place_order.call_count, 2)\n (\n buy_order_args,\n sell_order_args,\n ) = self._pyrofex_api_mock.place_order.call_args_list\n\n self.assertEqual(sell_order_args.kwargs[\"ticker\"], \"PAMP/FEB22\")\n self.assertEqual(sell_order_args.kwargs[\"side\"], pyRofex.Side.SELL)\n self.assertEqual(sell_order_args.kwargs[\"size\"], 10)\n self.assertEqual(sell_order_args.kwargs[\"price\"], 120)\n self.assertEqual(\n sell_order_args.kwargs[\"time_in_force\"],\n pyRofex.TimeInForce.ImmediateOrCancel,\n )\n self.assertEqual(sell_order_args.kwargs[\"order_type\"], pyRofex.OrderType.LIMIT)\n\n self.assertEqual(buy_order_args.kwargs[\"ticker\"], \"GGAL/FEB22\")\n self.assertEqual(buy_order_args.kwargs[\"side\"], pyRofex.Side.BUY)\n self.assertEqual(buy_order_args.kwargs[\"size\"], 10)\n self.assertEqual(buy_order_args.kwargs[\"price\"], 115)\n self.assertEqual(\n buy_order_args.kwargs[\"time_in_force\"],\n pyRofex.TimeInForce.ImmediateOrCancel,\n )\n self.assertEqual(buy_order_args.kwargs[\"order_type\"], pyRofex.OrderType.LIMIT)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "repo_name": "javkrei/Arbitraje-de-Tasas", "sub_path": "test/test_model/test_strategy.py", "file_name": "test_strategy.py", "file_ext": "py", "file_size_in_byte": 4924, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "unittest.TestCase", "line_number": 12, "usage_type": "attribute"}, {"api_name": "unittest.mock.MagicMock", "line_number": 19, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 24, "usage_type": "call"}, {"api_name": "src.model.market_apis.OrderBook", "line_number": 26, "usage_type": "call"}, {"api_name": "src.model.market_apis", "line_number": 26, "usage_type": "name"}, {"api_name": "src.model.market_apis.OrderBook", "line_number": 27, "usage_type": "call"}, {"api_name": "src.model.market_apis", "line_number": 27, "usage_type": "name"}, {"api_name": "src.model.market_apis.OrderBook", "line_number": 30, "usage_type": "call"}, {"api_name": "src.model.market_apis", "line_number": 30, "usage_type": "name"}, {"api_name": "src.model.market_apis.OrderBook", "line_number": 31, "usage_type": "call"}, {"api_name": "src.model.market_apis", "line_number": 31, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 37, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 38, "usage_type": "call"}, {"api_name": "src.model.instrument_handler.FutureContract", "line_number": 39, "usage_type": "call"}, {"api_name": "src.model.instrument_handler.FutureContract", "line_number": 40, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 45, "usage_type": "call"}, {"api_name": "src.model.rate_calculator.ImplicitRateCalculator", "line_number": 55, "usage_type": "call"}, {"api_name": "src.model.rate_calculator", "line_number": 55, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 61, "usage_type": "call"}, {"api_name": "src.model.strategy.Strategy", "line_number": 64, "usage_type": "call"}, {"api_name": "src.model.strategy", "line_number": 64, "usage_type": "name"}, {"api_name": "src.model.market_apis.OrderBook", "line_number": 76, "usage_type": "call"}, {"api_name": "src.model.market_apis", "line_number": 76, "usage_type": "name"}, {"api_name": "src.model.market_apis.OrderBook", "line_number": 77, "usage_type": "call"}, {"api_name": "src.model.market_apis", "line_number": 77, "usage_type": "name"}, {"api_name": "src.model.market_apis.OrderBook", "line_number": 80, "usage_type": "call"}, {"api_name": "src.model.market_apis", "line_number": 80, "usage_type": "name"}, {"api_name": "src.model.market_apis.OrderBook", "line_number": 81, "usage_type": "call"}, {"api_name": "src.model.market_apis", "line_number": 81, "usage_type": "name"}, {"api_name": "freezegun.freeze_time", "line_number": 73, "usage_type": "call"}, {"api_name": "pyRofex.Side", "line_number": 99, "usage_type": "attribute"}, {"api_name": "pyRofex.TimeInForce", "line_number": 104, "usage_type": "attribute"}, {"api_name": "pyRofex.OrderType", "line_number": 106, "usage_type": "attribute"}, {"api_name": "pyRofex.Side", "line_number": 109, "usage_type": "attribute"}, {"api_name": "pyRofex.TimeInForce", "line_number": 114, "usage_type": "attribute"}, {"api_name": "pyRofex.OrderType", "line_number": 116, "usage_type": "attribute"}, {"api_name": "freezegun.freeze_time", "line_number": 87, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 120, "usage_type": "call"}]} +{"seq_id": "71712365183", "text": "# encoding:utf-8\nfrom openpyxl import load_workbook\nfrom openpyxl.styles import numbers\n\n# ERROR_SHEET格式: 总表的行号, 分表的行号, 错误分类, 总表收方名称, 总表付款金额, 总表记账部门, 分表付方账号(仅在付方账号有误时记录)\n#\n# 1 从[上传模板sheet]中逐行取出不为空的数据, 记入ori_data字典中; key为: 行号, value为: [收款人, 金额, 记账部门]\n# 2 从[银行明细sheet]中逐行取出不为空的数据, 记入bank_info字典中; key为: 银行账号, value为: 记账部门\n# 3 从[银行导出sheet]中逐行取出每一行数据, '行号', '付方账号', '收款人', '金额', '记账部门'\n# 以'付方账号'为标准, 向bank_info搜索'记账部门';\n# 如果不一致, 将此条数据标记为: \"记账部门有误\"; 并计入output_data\n# 如果一致, 直接计入output_data\n# 4 遍历ori_data, 向output_data做匹配\n# 如果匹配得到, 并且output_data没有 [记账部门有误] ; pass\n# 如果匹配得到, 并且output_data有 [记账部门有误] ; 记录两边行号, 写入Error_Sheet\n# 如果匹配不到, 此条目标记为: \"未匹配成功\" ; 记录两边行号, 写入Error_Sheet\n\n\ndef payment_check(filepath):\n oriName = u'上传模板'\n bankDetail = u'银行明细'\n bankOutput = u'银行导出'\n wb = load_workbook(filepath)\n ori_sheet = wb[oriName]\n bank_detail_sheet = wb[bankDetail]\n output_sheet = wb[bankOutput]\n bank_info = {}\n output_data = {}\n\n sheet_num = len(wb.worksheets)\n err_sheet = wb.create_sheet(u'错误的数据', sheet_num + 1)\n err_sheet.cell(1, 1, '总表的行号')\n err_sheet.cell(1, 2, '分表的行号')\n err_sheet.cell(1, 3, '错误分类')\n err_sheet.cell(1, 4, '总表收方名称')\n err_sheet.cell(1, 5, '总表付款金额')\n err_sheet.cell(1, 6, '总表记账部门')\n err_sheet.cell(1, 7, '分表付方账号(仅在付方账号有误时记录)')\n err_sheet_row = 2\n\n # 遍历[银行明细sheet], 当 \"银行账号\" 和 \"记账部门\" 都不��空时, 记入bank_info字典\n for i in range(2, bank_detail_sheet.max_row + 1):\n _bank_account = bank_detail_sheet.cell(i, 3).value\n _depart_name = bank_detail_sheet.cell(i, 13).value\n\n if _depart_name is None or _bank_account is None:\n continue\n\n _bank_account = _bank_account.strip()\n _depart_name = _depart_name.strip()\n bank_info[_bank_account] = _depart_name\n\n #\n for i in range(2, output_sheet.max_row + 1):\n _op_account = output_sheet.cell(i, 4).value.split(u',')[1]\n _op_money = output_sheet.cell(i, 5).value\n _op_user = output_sheet.cell(i, 6).value\n _op_depart = output_sheet.cell(i, 9).value\n\n if _op_account is not None:\n _op_account = _op_account.strip()\n\n if _op_money is not None:\n _op_money = str(_op_money)\n\n if _op_user is not None:\n _op_user = _op_user.strip()\n\n if _op_depart is not None:\n _op_depart = _op_depart.strip()\n\n if _op_account in bank_info:\n true_depart = bank_info[_op_account]\n if true_depart != _op_depart:\n _my_key = str(i) # 如果记账部门有误, 则把字典的key值类型设置为string, 原本为int\n output_data[_my_key] = [_op_user, _op_money, true_depart]\n else:\n output_data[i] = [_op_user, _op_money, _op_depart]\n else:\n err_sheet.cell(err_sheet_row, 2, i)\n err_sheet.cell(err_sheet_row, 3, '付方账号错误')\n err_sheet.cell(err_sheet_row, 7, _op_account)\n err_sheet_row += 1\n\n # 遍历[上传模板sheet], 获取 行号, 收方名称, 付款金额, 记账部门; 并向output_data做匹配\n for i in range(2, ori_sheet.max_row + 1):\n _money = ori_sheet.cell(i, 6).value\n _depart = ori_sheet.cell(i, 1).value\n _user = ori_sheet.cell(i, 3).value\n if _money is not None and _depart is not None and _user is not None:\n _money = str(_money)\n _depart = _depart.strip()\n _user = _user.strip()\n\n _compare_data = [_user, _money, _depart]\n output_value_list = output_data.values()\n\n if _compare_data in output_value_list:\n _my_index = output_value_list.index(_compare_data)\n _my_key = output_data.keys()[_my_index]\n if type(_my_key) is str:\n err_sheet.cell(err_sheet_row, 1, i)\n err_sheet.cell(err_sheet_row, 2, int(_my_key))\n err_sheet.cell(err_sheet_row, 3, '记账部门有误')\n err_sheet.cell(err_sheet_row, 4, _user)\n err_sheet.cell(err_sheet_row, 5, float(_money)).number_format = numbers.FORMAT_NUMBER_00\n err_sheet.cell(err_sheet_row, 6, _depart)\n err_sheet_row += 1\n del output_data[_my_key]\n else:\n err_sheet.cell(err_sheet_row, 1, i)\n err_sheet.cell(err_sheet_row, 3, 'CannotMatch')\n err_sheet.cell(err_sheet_row, 4, _user)\n err_sheet.cell(err_sheet_row, 5, float(_money)).number_format = numbers.FORMAT_NUMBER_00\n err_sheet.cell(err_sheet_row, 6, _depart)\n err_sheet_row += 1\n\n if err_sheet_row == 2:\n wb.remove(wb.worksheets[sheet_num + 1])\n else:\n sheet_explain = '付方账号错误: 表示检索[银行导出表]时, \"银行账号\"没有在[银行明细]中找到\\n' \\\n '记账部门有误: 表示[银行导出表]中, \"银行账号\" 和 \"记账部门\" 匹配不一致\\n' \\\n 'CannotMatch: 表示其他无法以[上传模板]中的条目 匹配 [银行导出]的各种情况\\n' \\\n ' 包括 收款人/付款不正确、付款银行未在资金池...等'\n err_sheet.cell(err_sheet_row + 2, 1, '本表解释')\n err_sheet.cell(err_sheet_row + 3, 1, sheet_explain)\n wb.save(filepath)\n return\n", "repo_name": "ArielinIChen/ForAimee", "sub_path": "PaymentInfo/BankExcelCheck.py", "file_name": "BankExcelCheck.py", "file_ext": "py", "file_size_in_byte": 6144, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "openpyxl.load_workbook", "line_number": 23, "usage_type": "call"}, {"api_name": "openpyxl.styles.numbers.FORMAT_NUMBER_00", "line_number": 106, "usage_type": "attribute"}, {"api_name": "openpyxl.styles.numbers", "line_number": 106, "usage_type": "name"}, {"api_name": "openpyxl.styles.numbers.FORMAT_NUMBER_00", "line_number": 114, "usage_type": "attribute"}, {"api_name": "openpyxl.styles.numbers", "line_number": 114, "usage_type": "name"}]} +{"seq_id": "27458119223", "text": "#!/usr/bin/env python3.7\n\nfrom collections import defaultdict\nimport sys\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FuncFormatter\nimport math\nimport ciso8601\nimport datetime\n\n\ncolor_palette = [\n \"#ffffe5\",\n \"#fff7bc\",\n \"#fee391\",\n \"#fec44f\",\n \"#fe9929\",\n \"#ec7014\",\n \"#cc4c02\",\n \"#993404\",\n \"#662506\",\n]\n\n\nclass ConcurrencyCounter(object):\n def __init__(self, resolution=1):\n self._mult = 1 / resolution\n self.buckets = defaultdict(int)\n\n def add(self, start, end):\n start = int(start * self._mult)\n end = int(math.ceil(end * self._mult))\n if end == start:\n end += 1\n for i in range(start, end, 1):\n self.buckets[i] += 1\n\n\nTIME_BUCKET_SIZE = 1.0\n\ndrive_counters = defaultdict(lambda: ConcurrencyCounter(TIME_BUCKET_SIZE))\n\n\n@FuncFormatter\ndef time_formatter(x, pos):\n x *= TIME_BUCKET_SIZE\n dt = datetime.datetime.fromtimestamp(x)\n return dt.strftime(\"%H:%M:%S\")\n\n\nmonth_name_to_number = [\n None,\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n]\n\n\nwith open(sys.argv[1], \"rb\", buffering=10 * 2 ** 20) as fp:\n for i, raw_line in enumerate(fp):\n if not i % 500:\n print(\"\\rLines processed: %d...\" % i, end=\"\", file=sys.stderr)\n # sys.stderr.flush()\n raw_line = raw_line.strip()\n if not raw_line or raw_line[0] == b\"#\":\n continue\n\n # if i >= 500000:\n # break\n\n # early filtering for faster processing\n if b\"object-server\" not in raw_line:\n continue\n if b\"- -\" not in raw_line:\n continue\n\n line = raw_line[16:] # filter off syslog timestamp\n\n try:\n server_type, parts = line.split(b\":\", 1)\n except ValueError:\n continue\n\n server_type = server_type.strip()\n try:\n server_name, server_type = server_type.split()\n except ValueError:\n continue\n if server_type == b\"object-server\":\n parts = parts.strip().decode(\"ascii\")\n splitted = parts.split()\n\n path = splitted[6][:-1] # take off the last \" character\n drive = path.split(\"/\")[1]\n\n req_duration = float(splitted[-4])\n (datetime_first, datetime_end) = splitted[3:5]\n logged_time = datetime_first + \" \" + datetime_end\n logged_time = logged_time[1:-1] # strip the []\n\n # like \"27/Feb/2020 20:43:38 +0000\"\n iso_date = [logged_time[7:11]]\n month_num = \"%02d\" % month_name_to_number.index(logged_time[3:6])\n iso_date.append(month_num)\n iso_date.append(logged_time[0:2])\n iso_date = \"-\".join(iso_date)\n iso_date += \" \" + logged_time[12:20] + logged_time[21:]\n\n end_timestamp = ciso8601.parse_datetime(iso_date).timestamp()\n start_time = end_timestamp - req_duration\n\n drive_counters[drive].add(start_time, end_timestamp)\n\nprint(\"\\nDone\", file=sys.stderr)\n\n\nall_drives = list(drive_counters.keys())\nall_drives.sort() # so subsequent runs have the same order\nprint(len(all_drives))\n\nmpl.rcParams.update(mpl.rcParamsDefault)\nfig_height = max(len(all_drives) * 2 / 96, 4)\nfig, ax = plt.subplots(1, 1, figsize=(12, fig_height))\n\n\n# find global min and max to know how to scale colors\nglobal_min = 9999999999\nglobal_max = -1\nfor drive in all_drives:\n global_min = min(global_min, min(drive_counters[drive].buckets.values()))\n global_max = max(global_max, max(drive_counters[drive].buckets.values()))\n\nprint(global_min, global_max)\n\nlen_colors = len(color_palette)\nbucket_width = (global_max - global_min) / len_colors\n\n# plot drive counters here\n# one line per drive, 1px tall with no gaps, change color based on value\nfor i, drive in enumerate(all_drives):\n plotable_x = []\n color_vals = []\n for k in sorted(drive_counters[drive].buckets):\n plotable_x.append(k)\n color_index = (\n int(\n (drive_counters[drive].buckets[k] - global_min) // bucket_width\n )\n - 1\n )\n color_vals.append(color_palette[color_index])\n ax.scatter(\n plotable_x, [i] * len(plotable_x), s=1, c=color_vals, marker=\",\"\n )\n\nax.yaxis.set_visible(False)\nax.xaxis.set_major_formatter(time_formatter)\n# ax.legend(loc=\"best\", fancybox=True)\n\nlabels = ax.get_xticklabels()\nplt.setp(labels, rotation=45, horizontalalignment=\"right\")\n\nplt.title(\n \"Concurrent Drive Usage Over Time (%ss resolution)\" % TIME_BUCKET_SIZE\n)\n\nplt.tight_layout()\n\nplt.style.use(\"fivethirtyeight\")\nmpl.rcParams[\"font.sans-serif\"] = \"B612\"\nmpl.rcParams[\"font.family\"] = \"B612\"\nmpl.rcParams[\"axes.labelsize\"] = 10\nmpl.rcParams[\"xtick.labelsize\"] = 8\nmpl.rcParams[\"ytick.labelsize\"] = 8\nmpl.rcParams[\"text.color\"] = \"k\"\n\nfig.savefig(\"drive_usage.png\")\n", "repo_name": "notmyname/logflow", "sub_path": "per_drive.py", "file_name": "per_drive.py", "file_ext": "py", "file_size_in_byte": 4973, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "27", "api": [{"api_name": "collections.defaultdict", "line_number": 29, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 33, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 42, "usage_type": "call"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 48, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 48, "usage_type": "attribute"}, {"api_name": "matplotlib.ticker.FuncFormatter", "line_number": 45, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 69, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 72, "usage_type": "attribute"}, {"api_name": "ciso8601.parse_datetime", "line_number": 119, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 124, "usage_type": "attribute"}, {"api_name": "matplotlib.rcParams.update", "line_number": 131, "usage_type": "call"}, {"api_name": "matplotlib.rcParams", "line_number": 131, "usage_type": "attribute"}, {"api_name": "matplotlib.rcParamsDefault", "line_number": 131, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 133, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.setp", "line_number": 171, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 171, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 173, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 173, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 177, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 177, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.style.use", "line_number": 179, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 179, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 179, "usage_type": "name"}, {"api_name": "matplotlib.rcParams", "line_number": 180, "usage_type": "attribute"}, {"api_name": "matplotlib.rcParams", "line_number": 181, "usage_type": "attribute"}, {"api_name": "matplotlib.rcParams", "line_number": 182, "usage_type": "attribute"}, {"api_name": "matplotlib.rcParams", "line_number": 183, "usage_type": "attribute"}, {"api_name": "matplotlib.rcParams", "line_number": 184, "usage_type": "attribute"}, {"api_name": "matplotlib.rcParams", "line_number": 185, "usage_type": "attribute"}]} +{"seq_id": "12129073340", "text": "import copy\nimport os\nfrom threading import Event\n\nfrom opentrons import containers, drivers\nfrom opentrons.util import trace\nfrom opentrons.util.vector import Vector\nfrom opentrons.util.log import get_logger\nfrom opentrons.helpers import helpers\nfrom opentrons.util.trace import traceable\n\n\nlog = get_logger(__name__)\n\n\nclass InstrumentMosfet(object):\n \"\"\"\n Provides access to MagBead's MOSFET.\n \"\"\"\n\n def __init__(self, this_robot, mosfet_index):\n self.robot = this_robot\n self.mosfet_index = mosfet_index\n\n def engage(self):\n \"\"\"\n Engages the MOSFET.\n \"\"\"\n self.robot._driver.set_mosfet(self.mosfet_index, True)\n\n def disengage(self):\n \"\"\"\n Disengages the MOSFET.\n \"\"\"\n self.robot._driver.set_mosfet(self.mosfet_index, False)\n\n def wait(self, seconds):\n \"\"\"\n Pauses protocol execution.\n\n Parameters\n ----------\n seconds : int\n Number of seconds to pause for.\n \"\"\"\n self.robot._driver.wait(seconds)\n\n\nclass InstrumentMotor(object):\n \"\"\"\n Provides access to Robot's head motor.\n \"\"\"\n def __init__(self, this_robot, axis):\n self.robot = this_robot\n self.axis = axis\n\n def move(self, value, mode='absolute'):\n \"\"\"\n Move plunger motor.\n\n Parameters\n ----------\n value : int\n A one-dimensional coordinate to move to.\n mode : {'absolute', 'relative'}\n \"\"\"\n kwargs = {self.axis: value}\n self.robot._driver.move_plunger(\n mode=mode, **kwargs\n )\n\n def home(self):\n \"\"\"\n Home plunger motor.\n \"\"\"\n self.robot._driver.home(self.axis)\n\n def wait(self, seconds):\n \"\"\"\n Wait.\n\n Parameters\n ----------\n seconds : int\n Number of seconds to pause for.\n \"\"\"\n self.robot._driver.wait(seconds)\n\n def speed(self, rate):\n \"\"\"\n Set motor speed.\n\n Parameters\n ----------\n rate : int\n \"\"\"\n self.robot._driver.set_plunger_speed(rate, self.axis)\n return self\n\n\nclass Robot(object):\n \"\"\"\n This class is the main interface to the robot.\n\n Through this class you can can:\n * define your :class:`opentrons.Deck`\n * :meth:`connect` to Opentrons physical robot\n * :meth:`home` axis, move head (:meth:`move_to`)\n * :meth:`pause` and :func:`resume` the protocol run\n * set the :meth:`head_speed` of the robot\n\n Each Opentrons protocol is a Python script. When evaluated the script\n creates an execution plan which is stored as a list of commands in\n Robot's command queue.\n\n Here are the typical steps of writing the protocol:\n * Using a Python script and the Opentrons API load your\n containers and define instruments\n (see :class:`~opentrons.instruments.pipette.Pipette`).\n * Call :meth:`reset` to reset the robot's state and clear commands.\n * Write your instructions which will get converted\n into an execution plan.\n * Review the list of commands generated by a protocol\n :meth:`commands`.\n * :meth:`connect` to the robot and call :func:`run` it on a real robot.\n\n See :class:`Pipette` for the list of supported instructions.\n\n Examples\n --------\n >>> from opentrons import robot, instruments, containers\n >>> robot.reset() # doctest: +ELLIPSIS\n \n >>> plate = containers.load('96-flat', 'A1', 'plate')\n >>> p200 = instruments.Pipette(axis='b', max_volume=200)\n >>> p200.aspirate(200, plate[0]) # doctest: +ELLIPSIS\n \n >>> robot.commands()\n ['Aspirating 200 at ']\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initializes a robot instance.\n\n Notes\n -----\n This class is a singleton. That means every time you call\n :func:`__init__` the same instance will be returned. There's\n only once instance of a robot.\n \"\"\"\n\n self._commands = None # []\n self.INSTRUMENT_DRIVERS_CACHE = {}\n\n self.can_pop_command = Event()\n self.can_pop_command.set()\n\n self.mode = None\n self.smoothie_drivers = {\n 'live': None,\n 'simulate': drivers.get_virtual_driver(\n options={'limit_switches': False}\n ),\n 'simulate_switches': drivers.get_virtual_driver(\n options={'limit_switches': True}\n )\n }\n\n null_driver = drivers.get_virtual_driver()\n\n def _null(*args, **kwargs):\n return\n\n null_driver.move = _null\n null_driver.home = _null\n self.smoothie_drivers['null'] = null_driver\n\n self._driver = drivers.get_virtual_driver()\n self.disconnect()\n self.arc_height = 5\n self.cmds_total = None\n self.set_connection('simulate')\n self.reset()\n\n @helpers.not_app_run_safe\n def reset(self):\n \"\"\"\n Resets the state of the robot and clears:\n * Deck\n * Instruments\n * Command queue\n * Runtime warnings\n\n \"\"\"\n self._commands = []\n self._runtime_warnings = []\n\n self._previous_container = None\n\n self._deck = containers.Deck()\n self.setup_deck()\n\n self._ingredients = {} # TODO needs to be discusses/researched\n self._instruments = {}\n\n self.axis_homed = {\n 'x': False, 'y': False, 'z': False, 'a': False, 'b': False}\n\n return self\n\n def add_instrument(self, axis, instrument):\n \"\"\"\n Adds instrument to a robot.\n\n Parameters\n ----------\n axis : str\n Specifies which axis the instruments is attached to.\n instrument : Instrument\n An instance of a :class:`Pipette` to attached to the axis.\n\n Notes\n -----\n A canonical way to add to add a Pipette to a robot is:\n\n ::\n\n from opentrons.instruments.pipette import Pipette\n p200 = Pipette(axis='a')\n\n This will create a pipette and call :func:`add_instrument`\n to attach the instrument.\n \"\"\"\n axis = axis.upper()\n self._instruments[axis] = instrument\n\n def add_warning(self, warning_msg):\n \"\"\"\n Internal. Add a runtime warning to the queue.\n \"\"\"\n self._runtime_warnings.append(warning_msg)\n\n def get_warnings(self):\n \"\"\"\n Get current runtime warnings.\n\n Returns\n -------\n\n Runtime warnings accumulated since the last :func:`run`\n or :func:`simulate`.\n \"\"\"\n return list(self._runtime_warnings)\n\n def get_mosfet(self, mosfet_index):\n \"\"\"\n Get MOSFET for a MagBead (URL).\n\n Parameters\n ----------\n mosfet_index : int\n Number of a MOSFET on MagBead.\n\n Returns\n -------\n Instance of :class:`InstrumentMosfet`.\n \"\"\"\n instr_type = 'mosfet'\n key = (instr_type, mosfet_index)\n\n motor_obj = self.INSTRUMENT_DRIVERS_CACHE.get(key)\n if not motor_obj:\n motor_obj = InstrumentMosfet(self, mosfet_index)\n self.INSTRUMENT_DRIVERS_CACHE[key] = motor_obj\n return motor_obj\n\n def get_motor(self, axis):\n \"\"\"\n Get robot's head motor.\n\n Parameters\n ----------\n axis : {'a', 'b'}\n Axis name. Please check stickers on robot's gantry for the name.\n \"\"\"\n instr_type = 'instrument'\n key = (instr_type, axis)\n\n motor_obj = self.INSTRUMENT_DRIVERS_CACHE.get(key)\n if not motor_obj:\n motor_obj = InstrumentMotor(self, axis)\n self.INSTRUMENT_DRIVERS_CACHE[key] = motor_obj\n return motor_obj\n\n def flip_coordinates(self, coordinates):\n \"\"\"\n Flips between Deck and Robot coordinate systems.\n\n TODO: Add image explaining coordinate systems.\n \"\"\"\n dimensions = self._driver.get_dimensions()\n return helpers.flip_coordinates(coordinates, dimensions)\n\n @helpers.not_app_run_safe\n def connect(self, port=None, options=None):\n \"\"\"\n Connects the robot to a serial port.\n\n Parameters\n ----------\n port : str\n OS-specific port name or ``'Virtual Smoothie'``\n options : dict\n if :attr:`port` is set to ``'Virtual Smoothie'``, provide\n the list of options to be passed to :func:`get_virtual_device`\n\n Returns\n -------\n ``True`` for success, ``False`` for failure.\n \"\"\"\n device = None\n if not port or port == drivers.VIRTUAL_SMOOTHIE_PORT:\n device = drivers.get_virtual_driver(options)\n else:\n device = drivers.get_serial_driver(port)\n\n self._driver = device\n self.smoothie_drivers['live'] = device\n\n # set virtual smoothie do have same dimensions as real smoothie\n ot_v = device.ot_version\n self.smoothie_drivers['simulate'].ot_version = ot_v\n self.smoothie_drivers['simulate_switches'].ot_version = ot_v\n self.smoothie_drivers['null'].ot_version = ot_v\n\n def _update_axis_homed(self, *args):\n for a in args:\n for letter in a:\n if letter.lower() in self.axis_homed:\n self.axis_homed[letter.lower()] = True\n\n def home(self, *args, **kwargs):\n \"\"\"\n Home robot's head and plunger motors.\n\n Parameters\n ----------\n *args :\n A string with axes to home. For example ``'xyz'`` or ``'ab'``.\n\n If no arguments provided home Z-axis then X, Y, B, A\n\n Notes\n -----\n Sometimes while executing a long protocol,\n a robot might accumulate precision\n error and it is recommended to home it. In this scenario, add\n ``robot.home('xyzab')`` into your script.\n\n Examples\n --------\n >>> from opentrons import Robot\n >>> robot.connect('Virtual Smoothie')\n >>> robot.home()\n \"\"\"\n self._driver.calm_down()\n if args:\n self._update_axis_homed(*args)\n self._driver.home(*args)\n else:\n self._update_axis_homed('xyzab')\n self._driver.home('z')\n self._driver.home('x', 'y', 'b', 'a')\n\n def add_command(self, command):\n if self.mode == 'live':\n cmd_run_event = {'caller': 'ui'}\n cmd_run_event['mode'] = 'live'\n cmd_run_event['name'] = 'command-run'\n cmd_run_event.update({\n 'command_description': command,\n 'command_index': len(self._commands),\n 'commands_total': self.cmds_total\n })\n trace.EventBroker.get_instance().notify(cmd_run_event)\n self._commands.append(command)\n\n @helpers.not_app_run_safe\n def move_head(self, *args, **kwargs):\n self._driver.move_head(*args, **kwargs)\n\n @helpers.not_app_run_safe\n def move_plunger(self, *args, **kwargs):\n self._driver.move_plunger(*args, **kwargs)\n\n def head_speed(self, *args, **kwargs):\n \"\"\"\n Set the XY axis speeds of the robot, set in millimeters per minute\n\n Parameters\n ----------\n rate : int\n An integer setting the mm/minute rate of the X and Y axis.\n Speeds too fast (around 6000 and higher) will cause the robot\n to skip step, be careful when using this method\n\n Examples\n --------\n >>> from opentrons import robot\n >>> robot.connect('Virtual Smoothie')\n >>> robot.home()\n >>> robot.head_speed(4500)\n >>> robot.move_head(x=200, y=200)\n \"\"\"\n self._driver.set_speed(*args, **kwargs)\n\n @traceable('move-to')\n def move_to(self, location, instrument=None, strategy='arc', **kwargs):\n \"\"\"\n Move an instrument to a coordinate, container or a coordinate within\n a container.\n\n Parameters\n ----------\n location : one of the following:\n 1. :class:`Placeable` (i.e. Container, Deck, Slot, Well) — will\n move to the origin of a container.\n 2. :class:`Vector` move to the given coordinate in Deck coordinate\n system.\n 3. (:class:`Placeable`, :class:`Vector`) move to a given coordinate\n within object's coordinate system.\n\n instrument :\n Instrument to move relative to. If ``None``, move relative to the\n center of a gantry.\n\n strategy : {'arc', 'direct'}\n ``arc`` : move to the point using arc trajectory\n avoiding obstacles.\n\n ``direct`` : move to the point in a straight line.\n\n Examples\n --------\n >>> from opentrons import Robot\n >>> robot.reset() # doctest: +ELLIPSIS\n \n >>> robot.connect('Virtual Smoothie')\n >>> robot.home()\n >>> plate = robot.add_container('96-flat', 'A1', 'plate')\n >>> robot.move_to(plate[0])\n >>> robot.move_to(plate[0].top())\n \"\"\"\n\n placeable, coordinates = containers.unpack_location(location)\n\n if instrument:\n coordinates = instrument.calibrator.convert(\n placeable,\n coordinates)\n else:\n coordinates += placeable.coordinates(placeable.get_deck())\n\n if strategy == 'arc':\n arc_coords = self._create_arc(coordinates, placeable, instrument)\n for coord in arc_coords:\n self._driver.move_head(**coord)\n elif strategy == 'direct':\n self._driver.move_head(\n x=coordinates[0],\n y=coordinates[1],\n z=coordinates[2]\n )\n else:\n raise RuntimeError(\n 'Unknown move strategy: {}'.format(strategy))\n\n def _calibrated_max_dimension(self, container=None, instrument=None):\n \"\"\"\n Returns a Vector, each axis being the calibrated maximum\n for all instruments\n \"\"\"\n if not self._instruments or not self.containers():\n if container:\n return container.max_dimensions(self._deck)\n return self._deck.max_dimensions(self._deck)\n\n def _max_per_instrument(placeable, inst):\n \"\"\"\n Returns list of Vectors, one for each Instrument's farthest\n calibrated coordinate for the supplied placeable\n \"\"\"\n if inst:\n return [\n instrument.calibrator.convert(\n placeable,\n placeable.max_dimensions(placeable)\n )\n ]\n return [\n instrument.calibrator.convert(\n placeable,\n placeable.max_dimensions(placeable)\n )\n for instrument in self._instruments.values()\n ]\n\n container_max_coords = []\n if container:\n container_max_coords = _max_per_instrument(container, instrument)\n else:\n for c in self.containers().values():\n container_max_coords += _max_per_instrument(c, instrument)\n\n max_coords = [\n max(\n container_max_coords,\n key=lambda coordinates: coordinates[axis]\n )[axis]\n for axis in range(3)\n ]\n\n return Vector(max_coords)\n\n def _create_arc(self, destination, placeable=None, instrument=None):\n \"\"\"\n Returns a list of coordinates to arrive to the destination coordinate\n \"\"\"\n this_container = None\n if isinstance(placeable, containers.Well):\n this_container = placeable.get_parent()\n elif isinstance(placeable, containers.WellSeries):\n this_container = placeable.get_parent()\n elif isinstance(placeable, containers.Container):\n this_container = placeable\n\n ref_container = None\n if this_container and (self._previous_container == this_container):\n ref_container = this_container\n\n _, _, tallest_z = self._calibrated_max_dimension(\n ref_container, instrument)\n tallest_z += self.arc_height\n\n _, _, robot_max_z = self._driver.get_dimensions()\n arc_top = min(tallest_z, robot_max_z)\n arrival_z = min(destination[2], robot_max_z)\n\n self._previous_container = this_container\n\n return [\n {'z': arc_top},\n {'x': destination[0], 'y': destination[1]},\n {'z': arrival_z}\n ]\n\n @property\n def actions(self):\n \"\"\"\n Return a copy of a raw list of commands in the Robot's queue.\n \"\"\"\n return copy.deepcopy(self._commands)\n\n def prepare_for_run(self):\n \"\"\"\n Internal. Prepare for a Robot's run.\n \"\"\"\n if not self._driver.is_connected():\n raise RuntimeWarning('Please connect to the robot')\n\n self._runtime_warnings = []\n\n if not self._instruments:\n self.add_warning('No instruments added to robot')\n if not self._commands:\n self.add_warning('No commands added to robot')\n\n for instrument in self._instruments.values():\n instrument.reset()\n\n def set_connection(self, mode):\n self.mode = mode\n if mode not in self.smoothie_drivers:\n raise ValueError(\n 'mode expected to be \"live\", \"simulate_switches\", '\n '\"null\" or \"simulate\", {} provided'.format(mode)\n )\n\n d = self.smoothie_drivers[mode]\n\n # set VirtualSmoothie's coordinates to be the same as physical robot\n if d and d.is_simulating():\n if self._driver and self._driver.is_connected():\n d.connection.serial_port.set_position_from_arguments({\n ax.upper(): val\n for ax, val in self._driver.get_current_position().items()\n })\n\n self._driver = d\n if self._driver and not self._driver.is_connected():\n self._driver.toggle_port()\n\n @helpers.not_app_run_safe\n def disconnect(self):\n \"\"\"\n Disconnects from the robot.\n \"\"\"\n if self._driver:\n self._driver.disconnect()\n\n self.axis_homed = {\n 'x': False, 'y': False, 'z': False, 'a': False, 'b': False}\n\n def containers(self):\n \"\"\"\n Returns the dict with all of the containers on the deck.\n \"\"\"\n return self._deck.containers()\n\n def get_deck_slot_types(self):\n return 'slots'\n\n def get_slot_offsets(self):\n \"\"\"\n col_offset\n - from bottom left corner of A to bottom corner of B\n\n row_offset\n - from bottom left corner of 1 to bottom corner of 2\n\n TODO: figure out actual X and Y offsets (from origin)\n \"\"\"\n SLOT_OFFSETS = {\n 'slots': {\n 'x_offset': 10,\n 'y_offset': 10,\n 'col_offset': 91,\n 'row_offset': 134.5\n }\n }\n slot_settings = SLOT_OFFSETS.get(self.get_deck_slot_types())\n row_offset = slot_settings.get('row_offset')\n col_offset = slot_settings.get('col_offset')\n x_offset = slot_settings.get('x_offset')\n y_offset = slot_settings.get('y_offset')\n return (row_offset, col_offset, x_offset, y_offset)\n\n def get_max_robot_rows(self):\n # TODO: dynamically figure out robot rows\n return 3\n\n def setup_deck(self):\n robot_rows = self.get_max_robot_rows()\n row_offset, col_offset, x_offset, y_offset = self.get_slot_offsets()\n\n for col_index, col in enumerate('ABCDE'):\n for row_index, row in enumerate(range(1, robot_rows + 1)):\n properties = {\n 'width': col_offset,\n 'length': row_offset,\n 'height': 0\n }\n slot = containers.Slot(properties=properties)\n slot_coordinates = (\n (col_offset * col_index) + x_offset,\n (row_offset * row_index) + y_offset,\n 0 # TODO: should z always be zero?\n )\n slot_name = \"{}{}\".format(col, row)\n self._deck.add(slot, slot_name, slot_coordinates)\n\n @property\n def deck(self):\n return self._deck\n\n def get_instruments_by_name(self, name):\n res = []\n for k, v in self.get_instruments():\n if v.name == name:\n res.append((k, v))\n\n return res\n\n def get_instruments(self, name=None):\n \"\"\"\n :returns: sorted list of (axis, instrument)\n \"\"\"\n if name:\n return self.get_instruments_by_name(name)\n\n return sorted(\n self._instruments.items(), key=lambda s: s[0].lower())\n\n def get_containers(self):\n \"\"\"\n Returns the list of the containers on the deck.\n \"\"\"\n return sorted(\n self._deck.containers().items(), key=lambda s: s[0].lower())\n\n def add_container(self, container_name, slot, label=None):\n if not label:\n label = container_name\n container = containers.get_persisted_container(container_name)\n container.properties['type'] = container_name\n self._deck[slot].add(container, label)\n\n # if a container is added to Deck AFTER a Pipette, the Pipette's\n # Calibrator must update to include all children of Deck\n for _, instr in self.get_instruments():\n if hasattr(instr, 'update_calibrator'):\n instr.update_calibrator()\n return container\n\n def clear_commands(self):\n \"\"\"\n Clear Robot's command queue.\n \"\"\"\n self._previous_container = None\n self._commands = []\n\n def pause(self):\n \"\"\"\n Pauses execution of the protocol. Use :meth:`resume` to resume\n \"\"\"\n self.can_pop_command.clear()\n self._driver.pause()\n\n def stop(self):\n \"\"\"\n Stops execution of the protocol.\n \"\"\"\n self._driver.stop()\n self.can_pop_command.set()\n\n def resume(self):\n \"\"\"\n Resume execution of the protocol after :meth:`pause`\n \"\"\"\n self.can_pop_command.set()\n self._driver.resume()\n\n def halt(self):\n \"\"\"\n Stops execution of both the protocol and the Smoothie board immediately\n \"\"\"\n self._driver.halt()\n self.can_pop_command.set()\n\n def get_serial_ports_list(self):\n ports = []\n # TODO: Store these settings in config\n if os.environ.get('ENABLE_VIRTUAL_SMOOTHIE', '').lower() == 'true':\n ports = [drivers.VIRTUAL_SMOOTHIE_PORT]\n ports.extend(drivers.get_serial_ports_list())\n return ports\n\n def is_connected(self):\n if not self._driver:\n return False\n return self._driver.is_connected()\n\n def is_simulating(self):\n if not self._driver:\n return False\n return self._driver.is_simulating()\n\n def get_connected_port(self):\n return self._driver.get_connected_port()\n\n def versions(self):\n # TODO: Store these versions in config\n compatible = self._driver.versions_compatible()\n return {\n 'firmware': {\n 'version': self._driver.get_firmware_version(),\n 'compatible': compatible['firmware']\n },\n 'config': {\n 'version': self._driver.get_config_version(),\n 'compatible': compatible['config']\n },\n 'ot_version': {\n 'version': self._driver.get_ot_version(),\n 'compatible': compatible['ot_version']\n }\n }\n\n def diagnostics(self):\n \"\"\"\n Access diagnostics information for the robot.\n\n Returns\n -------\n Dictionary with the following keys:\n * ``axis_homed`` — axis that are currently in home position.\n * ``switches`` — end stop switches currently hit.\n * ``steps_per_mm`` — steps per millimeter calibration\n values for ``x`` and ``y`` axis.\n \"\"\"\n # TODO: Store these versions in config\n return {\n 'axis_homed': self.axis_homed,\n 'switches': self._driver.get_endstop_switches(),\n 'steps_per_mm': {\n 'x': self._driver.get_steps_per_mm('x'),\n 'y': self._driver.get_steps_per_mm('y')\n }\n }\n\n def commands(self):\n \"\"\"\n Access the human-readable list of commands in the robot's queue.\n\n Returns\n -------\n A list of string values for each command in the queue, for example:\n\n ``'Aspirating 200uL at ///'``\n \"\"\"\n return self._commands\n\n def comment(self, msg):\n self.add_command(msg)\n", "repo_name": "lauraespina/opentronsclone", "sub_path": "api/opentrons/robot/robot.py", "file_name": "robot.py", "file_ext": "py", "file_size_in_byte": 25294, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "opentrons.util.log.get_logger", "line_number": 13, "usage_type": "call"}, {"api_name": "threading.Event", "line_number": 156, "usage_type": "call"}, {"api_name": "opentrons.drivers.get_virtual_driver", "line_number": 162, "usage_type": "call"}, {"api_name": "opentrons.drivers", "line_number": 162, "usage_type": "name"}, {"api_name": "opentrons.drivers.get_virtual_driver", "line_number": 165, "usage_type": "call"}, {"api_name": "opentrons.drivers", "line_number": 165, "usage_type": "name"}, {"api_name": "opentrons.drivers.get_virtual_driver", "line_number": 170, "usage_type": "call"}, {"api_name": "opentrons.drivers", "line_number": 170, "usage_type": "name"}, {"api_name": "opentrons.drivers.get_virtual_driver", "line_number": 179, "usage_type": "call"}, {"api_name": "opentrons.drivers", "line_number": 179, "usage_type": "name"}, {"api_name": "opentrons.containers.Deck", "line_number": 201, "usage_type": "call"}, {"api_name": "opentrons.containers", "line_number": 201, "usage_type": "name"}, {"api_name": "opentrons.helpers.helpers.not_app_run_safe", "line_number": 186, "usage_type": "attribute"}, {"api_name": "opentrons.helpers.helpers", "line_number": 186, "usage_type": "name"}, {"api_name": "opentrons.helpers.helpers.flip_coordinates", "line_number": 303, "usage_type": "call"}, {"api_name": "opentrons.helpers.helpers", "line_number": 303, "usage_type": "name"}, {"api_name": "opentrons.drivers.VIRTUAL_SMOOTHIE_PORT", "line_number": 323, "usage_type": "attribute"}, {"api_name": "opentrons.drivers", "line_number": 323, "usage_type": "name"}, {"api_name": "opentrons.drivers.get_virtual_driver", "line_number": 324, "usage_type": "call"}, {"api_name": "opentrons.drivers", "line_number": 324, "usage_type": "name"}, {"api_name": "opentrons.drivers.get_serial_driver", "line_number": 326, "usage_type": "call"}, {"api_name": "opentrons.drivers", "line_number": 326, "usage_type": "name"}, {"api_name": "opentrons.helpers.helpers.not_app_run_safe", "line_number": 305, "usage_type": "attribute"}, {"api_name": "opentrons.helpers.helpers", "line_number": 305, "usage_type": "name"}, {"api_name": "opentrons.util.trace.EventBroker.get_instance", "line_number": 386, "usage_type": "call"}, {"api_name": "opentrons.util.trace.EventBroker", "line_number": 386, "usage_type": "attribute"}, {"api_name": "opentrons.util.trace", "line_number": 386, "usage_type": "name"}, {"api_name": "opentrons.helpers.helpers.not_app_run_safe", "line_number": 389, "usage_type": "attribute"}, {"api_name": "opentrons.helpers.helpers", "line_number": 389, "usage_type": "name"}, {"api_name": "opentrons.helpers.helpers.not_app_run_safe", "line_number": 393, "usage_type": "attribute"}, {"api_name": "opentrons.helpers.helpers", "line_number": 393, "usage_type": "name"}, {"api_name": "opentrons.containers.unpack_location", "line_number": 456, "usage_type": "call"}, {"api_name": "opentrons.containers", "line_number": 456, "usage_type": "name"}, {"api_name": "opentrons.util.trace.traceable", "line_number": 418, "usage_type": "call"}, {"api_name": "opentrons.util.vector.Vector", "line_number": 524, "usage_type": "call"}, {"api_name": "opentrons.containers.Well", "line_number": 531, "usage_type": "attribute"}, {"api_name": "opentrons.containers", "line_number": 531, "usage_type": "name"}, {"api_name": "opentrons.containers.WellSeries", "line_number": 533, "usage_type": "attribute"}, {"api_name": "opentrons.containers", "line_number": 533, "usage_type": "name"}, {"api_name": "opentrons.containers.Container", "line_number": 535, "usage_type": "attribute"}, {"api_name": "opentrons.containers", "line_number": 535, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 563, "usage_type": "call"}, {"api_name": "opentrons.helpers.helpers.not_app_run_safe", "line_number": 604, "usage_type": "attribute"}, {"api_name": "opentrons.helpers.helpers", "line_number": 604, "usage_type": "name"}, {"api_name": "opentrons.containers.Slot", "line_number": 664, "usage_type": "call"}, {"api_name": "opentrons.containers", "line_number": 664, "usage_type": "name"}, {"api_name": "opentrons.containers.get_persisted_container", "line_number": 705, "usage_type": "call"}, {"api_name": "opentrons.containers", "line_number": 705, "usage_type": "name"}, {"api_name": "os.environ.get", "line_number": 754, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 754, "usage_type": "attribute"}, {"api_name": "opentrons.drivers.VIRTUAL_SMOOTHIE_PORT", "line_number": 755, "usage_type": "attribute"}, {"api_name": "opentrons.drivers", "line_number": 755, "usage_type": "name"}, {"api_name": "opentrons.drivers.get_serial_ports_list", "line_number": 756, "usage_type": "call"}, {"api_name": "opentrons.drivers", "line_number": 756, "usage_type": "name"}]} +{"seq_id": "39703144201", "text": "import re\nimport os\nimport sys\nimport json\nimport pathlib\nimport subprocess\n\nimport xdg\n\nfrom . import pkg_dir\n\nSSR_CONF = {\n 'url': ('ssr://OjoxOjMwMDAwOm9yaWdpbjpub25lOnBsYWluOmRHVnpkQS8_b2Jmc3BhcmFtP'\n 'SZwcm90b3BhcmFtPSZyZW1hcmtzPWRHVnpkQSZncm91cD1kR1Z6ZEE'),\n 'dict': {\n 'server': '::1',\n 'server_port': 30000,\n 'protocol': 'origin',\n 'method': 'none',\n 'obfs': 'plain',\n 'password': 'test',\n 'obfs_param': '',\n 'protocol_param': '',\n 'remarks': 'test',\n 'group': 'test',\n },\n 'config_dict': {\n 'server': '::1',\n 'server_port': 30000,\n 'protocol': 'origin',\n 'method': 'none',\n 'obfs': 'plain',\n 'password': 'test',\n 'obfs_param': '',\n 'protocol_param': '',\n '_meta': {\n 'id': 1,\n 'remarks': 'test',\n 'group': 'test',\n 'sub': None,\n },\n },\n}\n\nCMD_PREFIX = ['python3', '-m', 'ssrcli']\n\n_venv_env = os.environ.copy()\nif _venv_env.get('PYTHONPATH', None):\n _venv_env['PYTHONPATH'] += ':{}'.format(str(pkg_dir))\nelse:\n _venv_env['PYTHONPATH'] = str(pkg_dir)\nVENV_ENV = _venv_env\n\nif sys.version_info[2] >= 7:\n SUBPROCESS_KWARGS = {\n 'env': VENV_ENV,\n 'check': True,\n 'universal_newlines': True,\n 'stdout': subprocess.PIPE,\n 'stderr': subprocess.PIPE,\n 'timeout': 10,\n }\nelse:\n SUBPROCESS_KWARGS = {\n 'env': VENV_ENV,\n 'check': True,\n 'text': True,\n 'capture_output': True,\n 'timeout': 10,\n }\n\nID_REGEX = re.compile(r'^id: (\\d+)$', flags=re.MULTILINE)\n\nif not pathlib.Path(xdg.XDG_CONFIG_HOME / 'ssrcli').exists():\n pathlib.Path(xdg.XDG_CONFIG_HOME / 'ssrcli').mkdir()\n\nSSRCLI_CONFIG = dict(\n update_retry=6,\n UPDATE_TIMEOUT=11,\n SSR_CONF_EXTRA_FIELDS={\n 'local_address': '127.0.0.1',\n 'local_port': 1080,\n 'timeout': 300,\n 'fast_open': True,\n },\n)\nwith open(xdg.XDG_CONFIG_HOME / 'ssrcli' / 'ssrcli-config.json', 'w') as f:\n f.write(json.dumps(SSRCLI_CONFIG))\n\nwith open(xdg.XDG_CONFIG_HOME / 'ssrcli' / 'ssr-config.json', 'w') as f:\n f.write(json.dumps({**SSR_CONF['config_dict'], **SSRCLI_CONFIG['SSR_CONF_EXTRA_FIELDS']}))\n", "repo_name": "myl7/ssrcli", "sub_path": "tests/ssrcli_test/shared.py", "file_name": "shared.py", "file_ext": "py", "file_size_in_byte": 2281, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "24", "api": [{"api_name": "os.environ.copy", "line_number": 47, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 47, "usage_type": "attribute"}, {"api_name": "sys.version_info", "line_number": 54, "usage_type": "attribute"}, {"api_name": "subprocess.PIPE", "line_number": 59, "usage_type": "attribute"}, {"api_name": "subprocess.PIPE", "line_number": 60, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 72, "usage_type": "call"}, {"api_name": "re.MULTILINE", "line_number": 72, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 74, "usage_type": "call"}, {"api_name": "xdg.XDG_CONFIG_HOME", "line_number": 74, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 75, "usage_type": "call"}, {"api_name": "xdg.XDG_CONFIG_HOME", "line_number": 75, "usage_type": "attribute"}, {"api_name": "xdg.XDG_CONFIG_HOME", "line_number": 87, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 88, "usage_type": "call"}, {"api_name": "xdg.XDG_CONFIG_HOME", "line_number": 90, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 91, "usage_type": "call"}]} +{"seq_id": "70339793031", "text": "#\n# Config setup\n#\n\nimport logging\nimport os.path\n\nfrom ConfigParser import SafeConfigParser\nfrom keystoneauth1 import loading\nfrom keystoneauth1 import session\nfrom novaclient import client as nvclient\n\nfrom reporting_pollster.common import credentials\n\n\nclass ConfigError(Exception):\n def __init__(self, msg):\n self.msg = msg\n\n\nconfig_file = \"./reporting.conf\"\n\n# defaults for testing\nremote = {\n 'user': 'reporting-test',\n 'passwd': 'Testing out the system',\n 'database': 'reporting2',\n 'host': '127.0.0.1',\n 'port': 33306,\n}\n\nlocal = {\n 'user': 'reporting-test',\n 'passwd': 'Testing out the system',\n 'database': 'reporting2',\n 'host': '127.0.0.1',\n 'port': 3306,\n}\n\n# defaults for both testing and production\ndbs = {\n 'keystone': 'keystone',\n 'nova': 'nova',\n 'cinder': 'cinder',\n 'glance': 'glance',\n 'rcshibboleth': 'rcshibboleth',\n 'dashboard': 'dashboard',\n}\n\n\ndef sanitise_db_creds(creds):\n \"\"\"Clean up certain values in the credentials to make sure that the DB driver\n doesn't get confused.\n \"\"\"\n tmp = {}\n for name, value in creds.items():\n if name == 'port':\n tmp[name] = int(value)\n elif name == 'password':\n tmp['passwd'] = value\n else:\n tmp[name] = value\n return tmp\n\n\ndef verify_nova_creds(nova_version, creds):\n client = Config.get_nova_client(nova_version, creds)\n # will return success quickly or fail quickly\n logging.debug(\"Testing nova credentials\")\n try:\n client.availability_zones.list()\n except Exception as e:\n raise ConfigError(\n \"Validating Nova credentials failed: %s\" % (e.message)\n )\n\n\nclass Config(object):\n \"\"\"Configuration wrapper class.\n \"\"\"\n remote = None\n local = None\n nova = None\n nova_api_version = '2'\n dbs = None\n config_file = None\n\n def __init__(self):\n self.load_defaults()\n\n @classmethod\n def reload_config(cls, filename):\n cls.config_file = filename\n logging.info(\"Loading configuration from %s\", filename)\n if not os.path.isfile(filename):\n raise ConfigError(\"Configuration file %s not found\" % (filename))\n cls.remote = None\n cls.local = None\n cls.nova = None\n cls.dbs = None\n # check environment first, override later\n cls.load_nova_environment()\n\n parser = SafeConfigParser()\n parser.read(filename)\n if not parser.has_section('remote'):\n raise ConfigError(\"No Remote DB Config\")\n if not parser.has_section('local'):\n raise ConfigError(\"No Local DB Config\")\n if not parser.has_section('nova') and cls.nova is None:\n raise ConfigError(\"No Nova Creds\")\n\n creds = {}\n for (name, value) in parser.items('remote'):\n creds[name] = value\n cls.remote = sanitise_db_creds(creds)\n creds = {}\n for (name, value) in parser.items('local'):\n creds[name] = value\n cls.local = sanitise_db_creds(creds)\n if parser.has_section('nova'):\n creds = {}\n for (name, value) in parser.items('nova'):\n creds[name] = value\n try:\n cls.nova = cls.extract_nova_version(creds)\n except KeyError:\n raise ConfigError(\"No Valid Nova Creds\")\n if not parser.has_section('databases'):\n logging.info(\"No database mapping defined - using default\")\n cls.dbs = dbs\n else:\n cls.dbs = {}\n for (name, value) in parser.items('databases'):\n cls.dbs[name] = value\n if dbs.keys() != cls.dbs.keys():\n raise ConfigError(\"Invalid DB Mapping\")\n verify_nova_creds(cls.nova_api_version, cls.nova)\n\n @classmethod\n def load_config(cls, filename):\n if cls.remote and cls.local and cls.nova and cls.dbs:\n return\n cls.reload_config(filename)\n\n @classmethod\n def load_defaults(cls):\n if cls.config_file and os.path.isfile(cls.config_file):\n cls.reload_config(cls.config_file)\n else:\n logging.debug(\"Loading in-build default configuration\")\n cls.remote = sanitise_db_creds(remote)\n cls.local = sanitise_db_creds(local)\n cls.dbs = dbs\n cls.load_nova_environment()\n verify_nova_creds(cls.nova_api_version, cls.nova)\n\n @classmethod\n def extract_nova_version(cls, creds):\n try:\n cls.nova_api_version = creds['version']\n del creds['version']\n return creds\n except KeyError:\n logging.debug(\"Trying to load invalid nova credentials\")\n raise\n\n @classmethod\n def load_nova_environment(cls):\n try:\n creds = credentials.get_nova_credentials()\n cls.nova = cls.extract_nova_version(creds)\n except KeyError:\n logging.info(\"Loading nova credentials from environment failed\")\n\n @classmethod\n def get_remote(cls):\n if not cls.remote:\n cls.load_defaults()\n return cls.remote\n\n @classmethod\n def get_local(cls):\n if not cls.local:\n cls.load_defaults()\n return cls.local\n\n @classmethod\n def get_nova(cls):\n if not cls.nova:\n cls.load_defaults()\n return cls.nova\n\n @classmethod\n def get_nova_api_version(cls):\n if not cls.nova:\n # is read from the nova section, so if nova is not loaded we\n # need to make sure there won't be a clash if it defines a\n # different value to the default\n cls.load_defaults()\n return cls.nova_api_version\n\n @classmethod\n def get_dbs(cls):\n if not cls.dbs:\n cls.load_defaults()\n return cls.dbs\n\n @classmethod\n def get_nova_client(cls, nova_version=None, creds=None):\n if not nova_version:\n nova_version = cls.get_nova_api_version()\n if not creds:\n creds = cls.get_nova()\n loader = loading.get_plugin_loader(\"password\")\n auth = loader.load_from_options(**creds)\n sess = session.Session(auth=auth)\n return nvclient.Client(nova_version, session=sess)\n", "repo_name": "NeCTAR-RC/reporting-pollster", "sub_path": "reporting_pollster/common/config.py", "file_name": "config.py", "file_ext": "py", "file_size_in_byte": 6278, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "logging.debug", "line_number": 69, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 94, "usage_type": "call"}, {"api_name": "os.path.path.isfile", "line_number": 95, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 95, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 95, "usage_type": "name"}, {"api_name": "ConfigParser.SafeConfigParser", "line_number": 104, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 130, "usage_type": "call"}, {"api_name": "os.path.path.isfile", "line_number": 148, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 148, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 148, "usage_type": "name"}, {"api_name": "logging.debug", "line_number": 151, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 165, "usage_type": "call"}, {"api_name": "reporting_pollster.common.credentials.get_nova_credentials", "line_number": 171, "usage_type": "call"}, {"api_name": "reporting_pollster.common.credentials", "line_number": 171, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 174, "usage_type": "call"}, {"api_name": "keystoneauth1.loading.get_plugin_loader", "line_number": 215, "usage_type": "call"}, {"api_name": "keystoneauth1.loading", "line_number": 215, "usage_type": "name"}, {"api_name": "keystoneauth1.session.Session", "line_number": 217, "usage_type": "call"}, {"api_name": "keystoneauth1.session", "line_number": 217, "usage_type": "name"}, {"api_name": "novaclient.client.Client", "line_number": 218, "usage_type": "call"}, {"api_name": "novaclient.client", "line_number": 218, "usage_type": "name"}]} +{"seq_id": "72193572851", "text": "from django.test import TestCase\nfrom unit_test.models import Animal\n\nclass AnimalTestCase(TestCase):\n def setUp(self):\n Animal.objects.create(name=\"lion\", sound=\"roar\", population=12)\n Animal.objects.create(name=\"cat\", sound=\"meow\", population=22)\n\n def test_animals_cange_number(self):\n \"\"\"Animals that can speak are correctly identified\"\"\"\n lion = Animal.objects.get(name=\"lion\")\n lion.name = \"Cat\"\n lion.sound = \"HAHA\"\n lion.population = 13\n lion.save()\n", "repo_name": "acchoblues/my-learning-saved", "sub_path": "apps/unit_test/tests.py", "file_name": "tests.py", "file_ext": "py", "file_size_in_byte": 520, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "django.test.TestCase", "line_number": 4, "usage_type": "name"}, {"api_name": "unit_test.models.Animal.objects.create", "line_number": 6, "usage_type": "call"}, {"api_name": "unit_test.models.Animal.objects", "line_number": 6, "usage_type": "attribute"}, {"api_name": "unit_test.models.Animal", "line_number": 6, "usage_type": "name"}, {"api_name": "unit_test.models.Animal.objects.create", "line_number": 7, "usage_type": "call"}, {"api_name": "unit_test.models.Animal.objects", "line_number": 7, "usage_type": "attribute"}, {"api_name": "unit_test.models.Animal", "line_number": 7, "usage_type": "name"}, {"api_name": "unit_test.models.Animal.objects.get", "line_number": 11, "usage_type": "call"}, {"api_name": "unit_test.models.Animal.objects", "line_number": 11, "usage_type": "attribute"}, {"api_name": "unit_test.models.Animal", "line_number": 11, "usage_type": "name"}]} +{"seq_id": "74004810608", "text": "from ngubot.game import Game\nimport argparse\n\nitems_both = []\n\nitems_merge = [\"4_4\", \"4_8\", \"4_9\", \"4_10\", \"4_11\", \"4_12\", \"5_5\", \"5_6\"]\n\nitems_boost = [\"4_12\", \"Head\", \"Chest\", \"5_10\", \"4_11\"]\n\n\ndef main():\n if int(args.numiters) == 0:\n iter = 1\n while True:\n game = Game(locate=False)\n game.schedule(\n int(args.interval), game.clean, (args.both, args.merge, args.boost)\n )\n game.run(int(args.starttime))\n print(\"Iteration\", iter)\n iter += 1\n else:\n for iter in range(1, int(args.numiters) + 1):\n game = Game(locate=False)\n game.schedule(\n int(args.interval), game.clean, (args.both, args.merge, args.boost)\n )\n game.run(int(args.starttime))\n print(\"Iteration\", iter)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-o\",\n \"--both\",\n nargs=\"+\",\n default=items_both,\n help=\"Items to merge then boost.\",\n )\n parser.add_argument(\n \"-m\", \"--merge\", nargs=\"+\", default=items_merge, help=\"Items to merge.\",\n )\n parser.add_argument(\n \"-b\", \"--boost\", nargs=\"+\", default=items_boost, help=\"Items to boost.\",\n )\n parser.add_argument(\n \"-r\", \"--repeat\", default=3, help=\"Number of times to boost each item.\",\n )\n parser.add_argument(\n \"-s\", \"--starttime\", default=0, help=\"The time in the run you start.\"\n )\n parser.add_argument(\n \"-i\",\n \"--interval\",\n default=300,\n help=\"How often to execute the command (-starttime).\",\n )\n parser.add_argument(\n \"-n\", \"--numiters\", default=0, help=\"The time in the run you start.\"\n )\n\n args = parser.parse_args()\n\n main()\n", "repo_name": "bvarjavand/ngubot", "sub_path": "examples/inventory.py", "file_name": "inventory.py", "file_ext": "py", "file_size_in_byte": 1816, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "ngubot.game.Game", "line_number": 15, "usage_type": "call"}, {"api_name": "ngubot.game.Game", "line_number": 24, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 33, "usage_type": "call"}]} +{"seq_id": "70946282291", "text": "# -*- coding: utf8 -*-\nfrom flask import request\nfrom wanx import app\nfrom wanx.base import util\nfrom wanx.models.credit import UserCredit, UserGemLog, UserGoldLog\nfrom wanx.models.gift import PayForGift\nfrom wanx.models.product import UserProduct\n\n\n@app.route('/credit/user', methods=['GET'])\n@util.jsonapi(login_required=True)\ndef user_credit():\n \"\"\"获取用户经济信息 (GET&LOGIN)\n\n :uri: /credit/user\n :return: {'gem': int, 'gold': int, 'gift_num': int}\n \"\"\"\n user = request.authed_user\n uc = UserCredit.get_or_create_user_credit(user_id=str(user._id))\n uproducts = UserProduct.get_user_products(str(user._id))\n gift_num = sum([up.num for up in uproducts])\n return {'gem': uc.gem, 'gold': uc.gold, 'gift_num': gift_num}\n\n\n@app.route('/credit/gem_log', methods=['GET'])\n@util.jsonapi(login_required=True)\ndef user_gem_log():\n \"\"\"获取用户游票交易记录 (GET&LOGIN)\n\n :uri: /credit/gem_log\n :param page: 页码\n :param nbr: 每页数量\n :return: {'logs': list, 'end_page': bool}\n \"\"\"\n user = request.authed_user\n page = int(request.values.get('page', 1))\n pagesize = int(request.values.get('nbr', 10))\n\n logs = UserGemLog.get_user_logs(str(user._id), page, pagesize)\n logs = [log.format() for log in logs]\n return {'logs': logs, 'end_page': len(logs) != pagesize}\n\n\n@app.route('/credit/gold_log', methods=['GET'])\n@util.jsonapi(login_required=True)\ndef user_gold_log():\n \"\"\"获取用户游米交易记录 (GET&LOGIN)\n\n :uri: /credit/gold_log\n :param page: 页码\n :param nbr: 每页数量\n :return: {'logs': list, 'end_page': bool}\n \"\"\"\n user = request.authed_user\n page = int(request.values.get('page', 1))\n pagesize = int(request.values.get('nbr', 10))\n\n logs = UserGoldLog.get_user_logs(str(user._id), page, pagesize)\n logs = [log.format() for log in logs]\n return {'logs': logs, 'end_page': len(logs) != pagesize}\n\n\n@app.route('/credit/pay_gift_log', methods=['GET'])\n@util.jsonapi(login_required=True)\ndef user_pay_gift_log():\n \"\"\"获取用户付费礼物兑换记录 (GET&LOGIN)\n\n :uri: /credit/pay_gift_log\n :param page: 页码\n :param nbr: 每页数量\n :return: {'logs': list, 'end_page': bool}\n \"\"\"\n user = request.authed_user\n page = int(request.values.get('page', 1))\n pagesize = int(request.values.get('nbr', 10))\n\n logs = PayForGift.get_user_logs(str(user._id), page, pagesize)\n logs = [log.format() for log in logs]\n return {'logs': logs, 'end_page': len(logs) != pagesize}", "repo_name": "leepood/migu_community", "sub_path": "wanx/views/credit.py", "file_name": "credit.py", "file_ext": "py", "file_size_in_byte": 2538, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "flask.request.authed_user", "line_number": 18, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 18, "usage_type": "name"}, {"api_name": "wanx.models.credit.UserCredit.get_or_create_user_credit", "line_number": 19, "usage_type": "call"}, {"api_name": "wanx.models.credit.UserCredit", "line_number": 19, "usage_type": "name"}, {"api_name": "wanx.models.product.UserProduct.get_user_products", "line_number": 20, "usage_type": "call"}, {"api_name": "wanx.models.product.UserProduct", "line_number": 20, "usage_type": "name"}, {"api_name": "wanx.app.route", "line_number": 10, "usage_type": "call"}, {"api_name": "wanx.app", "line_number": 10, "usage_type": "name"}, {"api_name": "wanx.base.util.jsonapi", "line_number": 11, "usage_type": "call"}, {"api_name": "wanx.base.util", "line_number": 11, "usage_type": "name"}, {"api_name": "flask.request.authed_user", "line_number": 35, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 35, "usage_type": "name"}, {"api_name": "flask.request.values.get", "line_number": 36, "usage_type": "call"}, {"api_name": "flask.request.values", "line_number": 36, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 36, "usage_type": "name"}, {"api_name": "flask.request.values.get", "line_number": 37, "usage_type": "call"}, {"api_name": "flask.request.values", "line_number": 37, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 37, "usage_type": "name"}, {"api_name": "wanx.models.credit.UserGemLog.get_user_logs", "line_number": 39, "usage_type": "call"}, {"api_name": "wanx.models.credit.UserGemLog", "line_number": 39, "usage_type": "name"}, {"api_name": "wanx.app.route", "line_number": 25, "usage_type": "call"}, {"api_name": "wanx.app", "line_number": 25, "usage_type": "name"}, {"api_name": "wanx.base.util.jsonapi", "line_number": 26, "usage_type": "call"}, {"api_name": "wanx.base.util", "line_number": 26, "usage_type": "name"}, {"api_name": "flask.request.authed_user", "line_number": 54, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 54, "usage_type": "name"}, {"api_name": "flask.request.values.get", "line_number": 55, "usage_type": "call"}, {"api_name": "flask.request.values", "line_number": 55, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 55, "usage_type": "name"}, {"api_name": "flask.request.values.get", "line_number": 56, "usage_type": "call"}, {"api_name": "flask.request.values", "line_number": 56, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 56, "usage_type": "name"}, {"api_name": "wanx.models.credit.UserGoldLog.get_user_logs", "line_number": 58, "usage_type": "call"}, {"api_name": "wanx.models.credit.UserGoldLog", "line_number": 58, "usage_type": "name"}, {"api_name": "wanx.app.route", "line_number": 44, "usage_type": "call"}, {"api_name": "wanx.app", "line_number": 44, "usage_type": "name"}, {"api_name": "wanx.base.util.jsonapi", "line_number": 45, "usage_type": "call"}, {"api_name": "wanx.base.util", "line_number": 45, "usage_type": "name"}, {"api_name": "flask.request.authed_user", "line_number": 73, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 73, "usage_type": "name"}, {"api_name": "flask.request.values.get", "line_number": 74, "usage_type": "call"}, {"api_name": "flask.request.values", "line_number": 74, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 74, "usage_type": "name"}, {"api_name": "flask.request.values.get", "line_number": 75, "usage_type": "call"}, {"api_name": "flask.request.values", "line_number": 75, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 75, "usage_type": "name"}, {"api_name": "wanx.models.gift.PayForGift.get_user_logs", "line_number": 77, "usage_type": "call"}, {"api_name": "wanx.models.gift.PayForGift", "line_number": 77, "usage_type": "name"}, {"api_name": "wanx.app.route", "line_number": 63, "usage_type": "call"}, {"api_name": "wanx.app", "line_number": 63, "usage_type": "name"}, {"api_name": "wanx.base.util.jsonapi", "line_number": 64, "usage_type": "call"}, {"api_name": "wanx.base.util", "line_number": 64, "usage_type": "name"}]} +{"seq_id": "243197997", "text": "import os\nimport sys\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"ms2ldaviz.settings\")\n\n\n\nimport django\ndjango.setup()\n\nfrom basicviz.models import *\nfrom django.contrib.auth.models import User\n\n\nif __name__ == '__main__':\n\tmfename = sys.argv[1]\n\tusername = sys.argv[2]\n\tuser = User.objects.get(username = username)\n\tmfe = MultiFileExperiment.objects.get(name = mfename)\n\n\tlinks= MultiLink.objects.filter(multifileexperiment = mfe)\n\tprint(\"Found {} experiments\".format(len(links)))\n\texperiments = [l.experiment for l in links]\n\tfor e in experiments:\n\t\tue,_ = UserExperiment.objects.get_or_create(user = user,experiment = e)\n\t\tue.permission = 'edit'\n\t\tue.save()\n", "repo_name": "glasgowcompbio/ms2ldaviz", "sub_path": "ms2ldaviz/add_user_to_mfe.py", "file_name": "add_user_to_mfe.py", "file_ext": "py", "file_size_in_byte": 665, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "20", "api": [{"api_name": "os.environ.setdefault", "line_number": 3, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 3, "usage_type": "attribute"}, {"api_name": "django.setup", "line_number": 8, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 15, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 16, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 17, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 17, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 17, "usage_type": "name"}]} +{"seq_id": "22794118885", "text": "\"\"\"\n-*- coding: utf-8 -*-\n========================\nRandom raster image creation with color information side by side\n========================\nContributor: Chirag Rathod (Srce Cde)\n========================\n\"\"\"\n\nfrom PIL import Image, ImageDraw, ImageFont\nimport svgwrite\n\n\ndef create_raster_e(filename: str = \"raster_e.jpeg\") -> None:\n img = Image.new(\"RGB\", (100, 100), color=\"white\")\n d = ImageDraw.Draw(img)\n # font path may differ in other operating system\n font = ImageFont.truetype(\n \"/System/Library/Fonts/Supplemental/Arial Unicode.ttf\", 100\n )\n d.text((0, -30), \"@\", fill=\"black\", font=font)\n img.save(filename)\n\n\ndef create_vector_e(filename: str = \"vector_e.svg\") -> None:\n dwg = svgwrite.Drawing(filename, profile=\"tiny\")\n dwg.add(dwg.text(\"@\", insert=(0, 100), font_size=\"100px\", font_family=\"Arial\"))\n dwg.save()\n\n\nif __name__ == \"__main__\":\n create_raster_e()\n create_vector_e()\n", "repo_name": "srcecde/srcecde-articles-codebase", "sub_path": "digital-images/raster-vs-vector/raster_vs_vector_img.py", "file_name": "raster_vs_vector_img.py", "file_ext": "py", "file_size_in_byte": 935, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "PIL.Image.new", "line_number": 15, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 15, "usage_type": "name"}, {"api_name": "PIL.ImageDraw.Draw", "line_number": 16, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 16, "usage_type": "name"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 18, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 18, "usage_type": "name"}, {"api_name": "svgwrite.Drawing", "line_number": 26, "usage_type": "call"}]} +{"seq_id": "7607654281", "text": "# import libraries\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import *\n\n# initialize spark session\nspark = SparkSession \\\n .builder \\\n .master(\"local[*]\") \\\n .appName(\"StagingToWarehouse\") \\\n .config(\"spark.executor.memory\", \"2g\") \\\n .config(\"spark.executor.cores\", '2') \\\n .config(\"spark.driver.memory\", '2g') \\\n .config(\"spark.driver.cores\", '2') \\\n .config(\"spark.cassandra.connection.host\", \"localhost\") \\\n .config(\"spark.cassandra.connection.port\", \"9042\") \\\n .config(\"spark.cassandra.auth.username\", \"root\") \\\n .config(\"spark.cassandra.auth.password\", \"admin\") \\\n .config(\"spark.hadoop.google.cloud.auth.service.account.enable\", \"true\") \\\n .config(\"spark.hadoop.google.cloud.auth.service.account.json.keyfile\", \"../../tools/bigquery/key_file.json\") \\\n .getOrCreate()\n\n# get max id of fact_records table\nfact_records_max_id = spark.read \\\n .format(\"bigquery\") \\\n .options(parentProject=\"test-373705\") \\\n .options(table=\"flight_delay.fact_records\") \\\n .load().select(\"id\") \\\n .agg(max(\"id\")) \\\n .collect()[0][0]\n# ensure max id have a value\nif fact_records_max_id is None:\n fact_records_max_id=-1\n\n# extract data from mysql table\nmysql = spark.read \\\n .format(\"org.apache.spark.sql.cassandra\") \\\n .options(keyspace=\"flight_delay\") \\\n .options(table=\"mysql\") \\\n .load() \\\n .filter(col(\"id\")>fact_records_max_id)\n\n# extract data from mongodb table\nmongodb = spark.read \\\n .format(\"org.apache.spark.sql.cassandra\") \\\n .options(keyspace=\"flight_delay\") \\\n .options(table=\"mongodb\") \\\n .load() \\\n .filter(col(\"id\")>fact_records_max_id)\n\n# integrate data, rename columns, and change datatype\nsource = mysql.union(mongodb).select(\n col(\"id\").alias(\"id\"),\n col(\"actualelapsedtime\").cast(\"bigint\").alias(\"actual_elapsed_time\"),\n col(\"airtime\").cast(\"bigint\").alias(\"air_time\"),\n col(\"arrdel15\").cast(\"bigint\").alias(\"arr_delay_15\"),\n col(\"arrdelay\").cast(\"bigint\").alias(\"arr_delay\"),\n col(\"arrdelayminutes\").cast(\"bigint\").alias(\"arr_delay_minutes\"),\n col(\"arrivaldelaygroups\").cast(\"bigint\").alias(\"arr_delay_groups\"),\n col(\"arrtime\").cast(\"bigint\").alias(\"arr_time\"),\n col(\"arrtimeblk\").alias(\"arr_time_block\"),\n col(\"cancellationcode\").alias(\"cancellation_code\"),\n col(\"cancelled\").cast(\"bigint\"),\n col(\"carrierdelay\").cast(\"bigint\").alias(\"carrier_delay\"),\n col(\"crsarrtime\").alias(\"crs_arr_time\"),\n col(\"crsdeptime\").alias(\"crs_dep_time\"),\n col(\"crselapsedtime\").cast(\"bigint\").alias(\"crs_elapsed_time\"),\n col(\"dayofmonth\").alias(\"day_of_month\"),\n col(\"dayofweek\").alias(\"day_of_week\"),\n col(\"departuredelaygroups\").cast(\"bigint\").alias(\"dep_delay_groups\"),\n col(\"depdel15\").cast(\"bigint\").alias(\"dep_delay_15\"),\n col(\"depdelay\").cast(\"bigint\").alias(\"dep_delay\"),\n col(\"depdelayminutes\").cast(\"bigint\").alias(\"dep_delay_minutes\"),\n col(\"deptime\").cast(\"bigint\").alias(\"dep_time\"),\n col(\"deptimeblk\").alias(\"dep_time_block\"),\n col(\"dest\"),\n col(\"destairportid\").alias(\"dest_airport_id\"),\n col(\"destairportseqid\").alias(\"dest_airport_seq_id\"),\n col(\"destcitymarketid\").alias(\"dest_city_market_id\"),\n col(\"destcityname\").alias(\"dest_city_name\"),\n col(\"deststate\").alias(\"dest_state\"),\n col(\"deststatefips\").alias(\"dest_state_fips\"),\n col(\"deststatename\").alias(\"dest_state_name\"),\n col(\"destwac\").alias(\"dest_wac\"),\n col(\"distance\").cast(\"bigint\"),\n col(\"distancegroup\").alias(\"distance_group\"),\n col(\"diverted\").cast(\"bigint\").alias(\"diverted\"),\n col(\"dot_id_reporting_airline\"),\n col(\"flight_number_reporting_airline\"),\n col(\"flightdate\").cast(\"date\").alias(\"flight_date\"),\n col(\"flights\").cast(\"bigint\"),\n col(\"iata_code_reporting_airline\"),\n col(\"lateaircraftdelay\").cast(\"bigint\").alias(\"late_aircraft_delay\"),\n col(\"month\"),\n col(\"nasdelay\").cast(\"bigint\").alias(\"nas_delay\"),\n col(\"origin\"),\n col(\"originairportid\").alias(\"origin_airport_id\"),\n col(\"originairportseqid\").alias(\"origin_airport_seq_id\"),\n col(\"origincitymarketid\").alias(\"origin_city_market_id\"),\n col(\"origincityname\").alias(\"origin_city_name\"),\n col(\"originstate\").alias(\"origin_state\"),\n col(\"originstatefips\").alias(\"origin_state_fips\"),\n col(\"originstatename\").alias(\"origin_state_name\"),\n col(\"originwac\").alias(\"origin_wac\"),\n col(\"quarter\"),\n col(\"reporting_airline\"),\n col(\"securitydelay\").cast(\"bigint\").alias(\"security_delay\"),\n col(\"tail_number\"),\n col(\"taxiin\").cast(\"bigint\").alias(\"taxi_in\"),\n col(\"taxiout\").cast(\"bigint\").alias(\"taxi_out\"),\n col(\"weatherdelay\").cast(\"bigint\").alias(\"weather_delay\"),\n col(\"wheelsoff\").cast(\"bigint\").alias(\"wheels_on\"),\n col(\"wheelson\").cast(\"bigint\").alias(\"wheels_off\"),\n col(\"year\")\n)\n\n## define function\n# define the function to load data to dim table\ndef to_dim_table(source_dataframe, table_name, unique_columns, table_columns):\n # get the current table from bigquery\n current_table = spark.read \\\n .format(\"bigquery\") \\\n .options(parentProject=\"test-373705\") \\\n .options(table=\"flight_delay.\" + table_name) \\\n .load().select([\"id\"] + unique_columns)\n \n # get new data from source dataframe\n new_table = source_dataframe.select(table_columns).distinct()\n \n # mapping and fill null id\n dim_table = new_table.join(current_table, on=unique_columns, how=\"full\") \\\n .orderBy(unique_columns) \\\n .withColumn(\"id\", monotonically_increasing_id())\n \n # get max_id of the current table\n max_id = current_table.agg(max(\"id\")).collect()[0][0]\n\n # ensure max_id has a value\n max_id = -1 if max_id is None else max_id\n\n # drop old data\n to_append_table = dim_table.filter(col(\"id\")>max_id)\n\n # append new data to dim table\n to_append_table.orderBy(\"id\") \\\n .write \\\n .format(\"bigquery\") \\\n .options(parentProject=\"test-373705\") \\\n .options(\"flight_delay.\" + table_name) \\\n .option(\"writeMethod\", \"direct\") \\\n .mode(\"append\") \\\n .save()\n\n # return the dim table\n return dim_table\n\n# define function add dim id to source\ndef add_dim_id(source_dataframe, dim_table, unique_columns, dim_id):\n # return a dataframe added dim id to source\n return source_dataframe.join(dim_table.selectExpr(unique_columns + [\"id as \" + dim_id]),\n on=unique_columns, how=\"left\")\n\n### load data to dim tables\n## define arguments\n# define dim_date table arguments\nunique_date_columns = [\"flight_date\"]\ndate_columns = [\"year\", \"quarter\", \"month\", \"day_of_month\", \"day_of_week\", \"flight_date\"]\n\n# define dim_airline table arguments\nunique_airline_columns = [\"reporting_airline\", \"tail_number\", \"flight_number_reporting_airline\"]\nairline_columns = [\"reporting_airline\", \"dot_id_reporting_airline\", \"iata_code_reporting_airline\",\n \"tail_number\", \"flight_number_reporting_airline\"]\n\n# define dim_origin table arguments\nunique_origin_columns = [\"origin_airport_id\"]\norigin_columns = [\"origin_airport_id\", \"origin_airport_seq_id\", \"origin_city_market_id\", \"origin\",\n \"origin_city_name\", \"origin_state\", \"origin_state_fips\", \"origin_state_name\", \"origin_wac\"]\n\n# define dim_destination table arguments\nunique_destination_columns = [\"dest_airport_id\"]\ndestination_columns = [\"dest_airport_id\", \"dest_airport_seq_id\", \"dest_city_market_id\", \"dest\",\n \"dest_city_name\", \"dest_state\", \"dest_state_fips\", \"dest_state_name\", \"dest_wac\"]\n\n# define dim_schedule table arguments\nunique_schedule_columns = [\"crs_dep_time\", \"crs_arr_time\", \"crs_elapsed_time\", \"distance\"]\nschedule_columns = [\"crs_dep_time\", \"dep_time_block\", \"crs_arr_time\", \"arr_time_block\",\n \"crs_elapsed_time\", \"distance\", \"distance_group\"]\n\n# define dim_cancellations_and_diversions table arguments\nunique_cancellations_and_diversions_columns = [\"cancelled\", \"cancellation_code\", \"diverted\"]\ncancellations_and_diversions_columns = [\"cancelled\", \"cancellation_code\", \"diverted\"]\n\n## create lists\n# create table_name list\ntable_name_list = [\"dim_date\", \"dim_airline\", \"dim_origin\", \"dim_destination\",\n \"dim_schedule\", \"dim_cancellations_and_diversions\"]\n\n# create unique_columns list\nunique_columns_list = [unique_date_columns, unique_airline_columns, unique_origin_columns, unique_destination_columns,\n unique_schedule_columns, unique_cancellations_and_diversions_columns]\n\n# create table_columns list\ntable_columns_list = [date_columns, airline_columns, origin_columns, destination_columns,\n schedule_columns, cancellations_and_diversions_columns]\n\n# create dim_table list\ndim_table_list = []\n\n# create dim_id list\ndim_id_list = [\"date_id\", \"airline_id\", \"origin_id\", \"destination_id\",\n \"schedule_id\", \"cancellations_and_diversions_id\"]\n\n# number of dim_table\nnum_dim_table = len(table_name_list)\n\n## load data\nfor i in range(num_dim_table):\n # append to list\n dim_table_list.append(to_dim_table(source_dataframe=source, table_name=table_name_list[i],\n unique_columns=unique_columns_list[i],\n table_columns=table_columns_list[i]))\n\n### load data to fact table\n# mappping dim_id\nfor i in range(num_dim_table):\n # add dim_id\n source = add_dim_id(source_dataframe=source, dim_table=dim_table_list[i],\n unique_columns=unique_columns_list[i], dim_id=dim_id_list[i])\n \n# select necessary columns for fact_records table\nfact_records = source.select(\"id\", \"date_id\", \"airline_id\", \"origin_id\", \"destination_id\", \"schedule_id\",\n \"cancellations_and_diversions_id\", \"dep_time\", \"dep_delay\", \"dep_delay_minutes\",\n \"dep_delay_15\", \"dep_delay_groups\", \"taxi_out\", \"taxi_in\", \"wheels_off\",\n \"wheels_on\", \"arr_time\", \"arr_delay\", \"arr_delay_minutes\", \"arr_delay_15\",\n \"arr_delay_groups\", \"actual_elapsed_time\", \"air_time\", \"flights\", \"carrier_delay\",\n \"weather_delay\", \"nas_delay\", \"security_delay\",\"late_aircraft_delay\")\n\n# append new data to fact_records table\nfact_records.orderBy(col(\"id\").asc()) \\\n .write \\\n .format(\"bigquery\") \\\n .options(parentProject=\"test-373705\") \\\n .options(table=\"flight_delay.fact_records\") \\\n .option(\"writeMethod\", \"direct\") \\\n .mode(\"append\") \\\n .save()\n\n# stop session\nspark.stop()", "repo_name": "nitsvutt/airline-data-platform", "sub_path": "process-data/integrate-to-warehouse.py", "file_name": "integrate-to-warehouse.py", "file_ext": "py", "file_size_in_byte": 11007, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "27", "api": [{"api_name": "pyspark.sql.SparkSession.builder.master", "line_number": 6, "usage_type": "call"}, {"api_name": "pyspark.sql.SparkSession.builder", "line_number": 6, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession", "line_number": 6, "usage_type": "name"}]} +{"seq_id": "9164768428", "text": "#!/usr/bin/env python\n#coding: utf8\n\n'''\n Create the application database from a year directory\n usage : ./import_data.py dbname.db \"/the/path/of/csvdata/directory/\"\n for instance : ./import_data_regul.py \"/home/gil/solaire/static/data/solar.db\" \"/home/gil/solaire/static/data/regul/\"\n'''\n\nimport sqlite3\nimport csv\nimport os\nimport glob\nimport sys\n\n#database name (remove if exists)\ndb = sys.argv[1]\ntry:\n os.remove(db)\nexcept OSError:\n pass\n\n#path to parse. Must contain only subpathes and csv files\nmypath = sys.argv[2]\n\nconn = sqlite3.connect(db)\nconn.text_factory = str # allows utf-8 data to be stored\ncursor = conn.cursor()\n\nfileslist = []\ndef test_dir(path_param):\n for f in os.listdir(path_param):\n if (os.path.isfile(os.path.join(path_param, f))):\n fileslist.append(os.path.join(path_param, f))\n else:\n test_dir(os.path.join(path_param, f))\n return fileslist\n\n#Create a list of csv files\ncsvfiles = test_dir(mypath)\n\n#Generate empty database\n\ncursor.execute(\"\"\"\nCREATE TABLE import_regul(\n num_Regul integer,\n date_time varchar(20),\n t1 integer,\n t2 integer,\n t3 integer,\n t4 integer,\n t5 integer,\n t6 integer,\n tds integer,\n debit integer,\n pcurrent real,\n qday integer,\n qyear integer,\n qsum integer,\n r1 integer,\n r2 integer,\n r3 integer,\n h1 integer,\n h2 integer);\n\"\"\")\nconn.commit()\n\ncursor.execute(\"\"\"\nCREATE TABLE data_regul(\n id integer primary key,\n cyear integer,\n cmonth integer,\n cday integer,\n ctime varchar(5),\n t1 integer,\n t2 integer,\n t3 integer,\n t4 integer,\n t5 integer,\n t6 integer,\n tds integer,\n debit integer,\n pcurrent real,\n qday integer,\n qyear integer,\n qsum integer,\n r1 integer,\n r2 integer,\n r3 integer,\n h1 integer,\n h2 integer);\n\"\"\")\nconn.commit()\n\nfor f in csvfiles:\n i = 0\n reader = csv.reader(open(f, 'r'), delimiter=';')\n for row in reader:\n if i > 0:\n to_db = [\n row[0], \n unicode(row[1], \"utf8\"), \n row[2],\n row[3],\n row[4],\n row[5],\n row[6],\n row[7],\n row[8],\n row[9],\n row[10],\n row[11],\n row[12],\n row[13],\n row[14],\n row[15],\n row[16],\n row[17],\n row[18],\n ]\n cursor.execute(\n \"\"\"INSERT INTO import_regul (\n num_Regul,\n date_time,\n t1,\n t2,\n t3,\n t4,\n t5,\n t6,\n tds,\n debit,\n pcurrent,\n qday,\n qyear,\n qsum,\n r1,\n r2,\n r3,\n h1,\n h2\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);\"\"\"\n , to_db\n )\n i += 1\nconn.commit()\n\ncursor.execute(\n \"\"\"INSERT INTO data_regul\n (\n cyear\n ,cmonth\n ,cday\n ,ctime\n ,t1\n ,t2\n ,t3\n ,t4\n ,t5\n ,t6\n ,tds\n ,debit\n ,pcurrent\n ,qday\n ,qyear\n ,qsum\n ,r1\n ,r2\n ,r3\n ,h1\n ,h2\n )\n SELECT \n substr(date_time,0,5)\n ,substr(date_time,6,2)\n ,substr(date_time,9,2)\n ,substr(date_time,12,5)\n ,t1\n ,t2\n ,t3\n ,t4\n ,t5\n ,t6\n ,tds\n ,debit\n ,pcurrent\n ,qday\n ,qyear\n ,qsum\n ,r1\n ,r2\n ,r3\n ,h1\n ,h2\n FROM import_regul;\n\"\"\")\nconn.commit()\n\ncursor.execute(\"DROP TABLE import_regul;\")\nconn.commit()\n\ncursor.execute(\"VACUUM;\")\nconn.commit()\n\nconn.close()\n", "repo_name": "gildeluermoz/solarview", "sub_path": "static/data/import_data_regul.py", "file_name": "import_data_regul.py", "file_ext": "py", "file_size_in_byte": 3917, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "sys.argv", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 19, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 24, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 26, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path", "line_number": 36, "usage_type": "attribute"}, {"api_name": "csv.reader", "line_number": 97, "usage_type": "call"}]} +{"seq_id": "28502183219", "text": "import scrapy\nimport json\n\nfrom AospMakefileSpider.items import AospmakefilespiderItem\n\ngit_list_urls = []\n\nwith open('repo_master.json') as json_data:\n gitList = json.load(json_data)\n for git in gitList:\n git_list_urls.append(git['url'])\n\nandroid_googlesource = 'https://android.googlesource.com'\nbaseDir = ''\n# baseUrl = android_googlesource + '/platform/system/tools/aidl/+/master'\n\nclass RepoSpider(scrapy.Spider):\n name = \"git\"\n allowed_domains = [ 'android.googlesource.com' ]\n start_urls = git_list_urls\n\n # def start_requests(self):\n # yield scrapy.Request(url=baseUrl, callback=self.parse)\n\n def parse(self, response):\n list = response.css('.FileList-itemLink')\n for item in list:\n name = item.xpath('text()').extract()[0]\n urls = item.xpath('@href').extract()\n\n if (name.endswith('.mk')) or (name.endswith('.bp')) or (name.endswith('.gradle')):\n # print('catch remote file = ' + urls[0])\n url = android_googlesource + urls[0]\n fileItem = AospmakefilespiderItem()\n fileItem['url'] = url\n # idx = len(baseUrl)\n # fileItem['path'] = baseDir + url[idx:]\n fileItem['name'] = name\n yield fileItem\n elif \".\" in name:\n # print('ignore remote file = ' + urls[0])\n continue\n else:\n # print('crawl remote dir = ' + urls[0])\n url = android_googlesource + urls[0]\n yield scrapy.Request(url=url, callback=self.parse)\n", "repo_name": "wtao901231/android-git-spider", "sub_path": "AospMakefileSpider/AospMakefileSpider/spiders/git_spider.py", "file_name": "git_spider.py", "file_ext": "py", "file_size_in_byte": 1615, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "json.load", "line_number": 9, "usage_type": "call"}, {"api_name": "scrapy.Spider", "line_number": 17, "usage_type": "attribute"}, {"api_name": "AospMakefileSpider.items.AospmakefilespiderItem", "line_number": 34, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 46, "usage_type": "call"}]} +{"seq_id": "27083065563", "text": "from utils.arcnah import arcno\nimport pandas as pd\nimport numpy as np\nfrom projects.dima.tables.lpipk import lpi_pk\nfrom projects.dima.tables.bsnepk import bsne_pk\n\ndef no_pk(tablefam:str=None,dimapath:str=None,tablename:str= None):\n \"\"\"\n\n \"\"\"\n arc = arcno()\n fam = {\n 'plantprod':['tblPlantProdDetail','tblPlantProdHeader'],\n 'soilstab':['tblSoilStabDetail','tblSoilStabHeader'],\n 'soilpit':['tblSoilPits', 'tblSoilPitHorizons']\n }\n try:\n if tablefam is not None and ('plantprod' in tablefam):\n\n header = arcno.MakeTableView(fam['plantprod'][1],dimapath)\n detail = arcno.MakeTableView(fam['plantprod'][0],dimapath)\n head_det = pd.merge(header,detail,how=\"inner\", on=\"RecKey\")\n head_det = arc.CalculateField(head_det,\"PrimaryKey\",\"PlotKey\",\"FormDate\")\n return head_det\n\n\n elif tablefam is not None and ('soilstab' in tablefam):\n header = arcno.MakeTableView(fam['soilstab'][1],dimapath)\n detail = arcno.MakeTableView(fam['soilstab'][0],dimapath)\n head_det = pd.merge(header,detail,how=\"inner\", on=\"RecKey\")\n head_det = arc.CalculateField(head_det,\"PrimaryKey\",\"PlotKey\",\"FormDate\")\n return head_det\n\n elif tablefam is not None and ('soilpit' in tablefam):\n print(\"soilpit\")\n pits = arcno.MakeTableView(fam['soilpit'][0], dimapath)\n horizons = arcno.MakeTableView(fam['soilpit'][1], dimapath)\n merge = pd.merge(pits, horizons, how=\"inner\", on=\"SoilKey\")\n\n allpks = lpi_pk(dimapath)\n iso = allpks.loc[:,[\"PrimaryKey\", \"EstablishDate\", \"FormDate\", \"DateModified\"]].copy()\n merge['FormDate2'] = pd.to_datetime(merge.DateRecorded.apply(lambda x: pd.Timestamp(x).date()))\n\n mergepk = date_column_chooser(merge,iso) if \"tetonAIM\" not in dimapath else pd.merge(merge, iso, how=\"left\", left_on=\"FormDate2\", right_on=\"FormDate\").drop_duplicates('HorizonKey')\n if \"DateModified2\" in mergepk.columns:\n mergepk.drop(['EstablishDate',\"FormDate\",'FormDate2',\"DateModified2\"], axis=1, inplace=True)\n else:\n mergepk.drop(['EstablishDate',\"FormDate\",'FormDate2'], axis=1, inplace=True)\n\n return mergepk\n\n else:\n no_pk_df = arcno.MakeTableView(tablename, dimapath)\n # print('netdima in path')\n if ('Network_DIMAs' in dimapath) and (tablefam==None):\n if ('tblPlots' in tablename) or ('tblLines' in tablename):\n print(\"lines,plots; networkdima in the path\")\n fulldf = bsne_pk(dimapath)\n iso = arc.isolateFields(fulldf,'PlotKey','PrimaryKey').copy()\n no_pk_df = pd.merge(no_pk_df,iso,how=\"inner\",on=[\"PlotKey\"]).drop_duplicates([\"LineKey\",\"PrimaryKey\"]) if \"tblLines\" in tablename else pd.merge(no_pk_df,iso,how=\"inner\",on=[\"PlotKey\"]).drop_duplicates([\"PrimaryKey\"])\n return no_pk_df\n else:\n print(\"network, but not line or plot, no pk\")\n if 'Sites' in tablename:\n no_pk_df = no_pk_df[(no_pk_df.SiteKey!='888888888') & (no_pk_df.SiteKey!='999999999')]\n return no_pk_df\n else:\n return no_pk_df\n\n elif ('Network_DIMAs' in dimapath) and ('fake' in tablefam):\n if ('tblPlots' in tablename) or ('tblLines' in tablename):\n fulldf = lpi_pk(dimapath)\n iso = arc.isolateFields(fulldf,'PlotKey','PrimaryKey').copy()\n\n no_pk_df = pd.merge(no_pk_df,iso,how=\"inner\",on=[\"PlotKey\"]).drop_duplicates([\"LineKey\",\"PrimaryKey\"]) if \"tblLines\" in tablename else pd.merge(no_pk_df,iso,how=\"inner\",on=[\"PlotKey\"]).drop_duplicates([\"PrimaryKey\"])\n return no_pk_df\n else:\n print(\"network, but not line or plot, no pk --fakebranch\")\n if 'Sites' in tablename:\n no_pk_df = no_pk_df[(no_pk_df.SiteKey!='888888888') & (no_pk_df.SiteKey!='999999999')]\n return no_pk_df\n else:\n return no_pk_df\n\n else:\n if ('tblPlots' in tablename) or ('tblLines' in tablename):\n print('not network, no tablefam')\n fulldf = lpi_pk(dimapath)\n iso = arc.isolateFields(fulldf,'PlotKey','PrimaryKey').copy()\n no_pk_df = pd.merge(no_pk_df,iso,how=\"inner\",on=[\"PlotKey\"]).drop_duplicates([\"LineKey\",\"PrimaryKey\"]) if \"tblLines\" in tablename else pd.merge(no_pk_df,iso,how=\"inner\",on=[\"PlotKey\"]).drop_duplicates([\"PrimaryKey\"])\n return no_pk_df\n else:\n print(\"not network, not line or plot, no pk\")\n if 'Sites' in tablename:\n no_pk_df = no_pk_df[(no_pk_df.SiteKey!='888888888') & (no_pk_df.SiteKey!='999999999')]\n return no_pk_df\n else:\n return no_pk_df\n # return no_pk_df\n except Exception as e:\n print(e)\n\ndef date_column_chooser(df,iso):\n df_establish = pd.merge(df, iso, how=\"left\", left_on=\"FormDate2\", right_on=\"EstablishDate\").drop_duplicates('HorizonKey')\n df_formdate = pd.merge(df, iso, how=\"left\", left_on=\"FormDate2\", right_on=\"FormDate\").drop_duplicates('HorizonKey')\n if np.nan not in [i for i in df_formdate.PrimaryKey]:\n return df_formdate\n elif np.nan not in [i for i in df_establish.PrimaryKey]:\n return df_establish\n else:\n iso[\"DateModified2\"] = pd.to_datetime(iso.DateModified.apply(lambda x: pd.Timestamp(x).date()))\n df_datemod = pd.merge(df, iso, how=\"left\", left_on=\"FormDate2\", right_on=\"DateModified2\").drop_duplicates('HorizonKey')\n return df_datemod\n", "repo_name": "krstphrrr/met_scraper_api", "sub_path": "src/dima/tables/nopk.py", "file_name": "nopk.py", "file_ext": "py", "file_size_in_byte": 5997, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "utils.arcnah.arcno", "line_number": 11, "usage_type": "call"}, {"api_name": "utils.arcnah.arcno.MakeTableView", "line_number": 20, "usage_type": "call"}, {"api_name": "utils.arcnah.arcno", "line_number": 20, "usage_type": "name"}, {"api_name": "utils.arcnah.arcno.MakeTableView", "line_number": 21, "usage_type": "call"}, {"api_name": "utils.arcnah.arcno", "line_number": 21, "usage_type": "name"}, {"api_name": "pandas.merge", "line_number": 22, "usage_type": "call"}, {"api_name": "utils.arcnah.arcno.MakeTableView", "line_number": 28, "usage_type": "call"}, {"api_name": "utils.arcnah.arcno", "line_number": 28, "usage_type": "name"}, {"api_name": "utils.arcnah.arcno.MakeTableView", "line_number": 29, "usage_type": "call"}, {"api_name": "utils.arcnah.arcno", "line_number": 29, "usage_type": "name"}, {"api_name": "pandas.merge", "line_number": 30, "usage_type": "call"}, {"api_name": "utils.arcnah.arcno.MakeTableView", "line_number": 36, "usage_type": "call"}, {"api_name": "utils.arcnah.arcno", "line_number": 36, "usage_type": "name"}, {"api_name": "utils.arcnah.arcno.MakeTableView", "line_number": 37, "usage_type": "call"}, {"api_name": "utils.arcnah.arcno", "line_number": 37, "usage_type": "name"}, {"api_name": "pandas.merge", "line_number": 38, "usage_type": "call"}, {"api_name": "projects.dima.tables.lpipk.lpi_pk", "line_number": 40, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 42, "usage_type": "call"}, {"api_name": "pandas.Timestamp", "line_number": 42, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 44, "usage_type": "call"}, {"api_name": "utils.arcnah.arcno.MakeTableView", "line_number": 53, "usage_type": "call"}, {"api_name": "utils.arcnah.arcno", "line_number": 53, "usage_type": "name"}, {"api_name": "projects.dima.tables.bsnepk.bsne_pk", "line_number": 58, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 60, "usage_type": "call"}, {"api_name": "projects.dima.tables.lpipk.lpi_pk", "line_number": 72, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 75, "usage_type": "call"}, {"api_name": "projects.dima.tables.lpipk.lpi_pk", "line_number": 88, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 90, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 104, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 106, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 108, "usage_type": "attribute"}, {"api_name": "pandas.to_datetime", "line_number": 111, "usage_type": "call"}, {"api_name": "pandas.Timestamp", "line_number": 111, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 112, "usage_type": "call"}]} +{"seq_id": "5563442157", "text": "from PIL import Image\nfrom PIL.ExifTags import TAGS, GPSTAGS\nfrom logging import info\nfrom datetime import datetime\n\ntags_skip = ['MakerNote', 'UserComment']\n\n\ndef get_exif_data(filename):\n \"\"\" Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags \"\"\"\n try:\n image = Image.open(filename)\n except OSError as e:\n info('The file ' + filename + ' can\\'t be open as image')\n return {}\n exif_data = {}\n try:\n einfo = image._getexif()\n except Exception as e:\n info(e)\n einfo = {}\n if einfo:\n for tag, value in einfo.items():\n decoded = TAGS.get(tag, tag)\n if decoded in tags_skip:\n continue\n if decoded == \"GPSInfo\":\n gps_data = {}\n for t in value:\n sub_decoded = GPSTAGS.get(t, t)\n tvalue = value[t]\n if isinstance(tvalue, bytes):\n tvalue = tvalue.decode('utf-8')\n gps_data[sub_decoded] = tvalue\n\n exif_data[decoded] = gps_data\n else:\n dvalue = value\n if isinstance(value, bytes):\n # dvalue = value.decode('utf-8')\n dvalue = \"{}\"\n formats = ['utf-8', 'ISO-8859-1', 'utf-16']\n for theFormat in formats:\n try:\n dvalue = value.decode(theFormat)\n break\n except Exception as e:\n info(e)\n info('Exception: Invalid Encoding Detected for Exif Data.')\n exif_data[decoded] = dvalue\n if decoded in ['DateTimeOriginal', 'DateTime', 'DateTimeDigitized']:\n date_portion = exif_data[decoded][0:10]\n time_portion = exif_data[decoded][11:]\n exif_data[decoded] = date_portion.replace(':', '/') + ' ' + time_portion\n # Adjusting the output\n output = dict()\n output['tags'] = exif_data\n coords = get_lat_lon(exif_data)\n output['latitude'] = coords[0]\n output['longitude'] = coords[1]\n edkeys = exif_data.keys()\n if 'DateTimeOriginal' in edkeys and ['DateTimeOriginal'] != '':\n output['date_stamp'] = datetime.strptime(exif_data['DateTimeOriginal'], '%Y/%m/%d %H:%M:%S').isoformat()\n elif 'DateTimeOriginal' in edkeys and exif_data['DateTimeDigitized'] != '':\n output['date_stamp'] = datetime.strptime(exif_data['DateTimeDigitized'], '%Y/%m/%d %H:%M:%S').isoformat()\n elif 'DateTimeOriginal' in edkeys and exif_data['DateTime'] != '':\n output['date_stamp'] = datetime.strptime(exif_data['DateTime'], '%Y/%m/%d %H:%M:%S').isoformat()\n else:\n output['date_stamp'] = None\n return output\n\n\ndef _get_if_exist(data, key):\n if key in data:\n return data[key]\n\n return None\n\n\ndef _convert_to_degress(value):\n \"\"\"Helper function to convert the GPS coordinates stored in the EXIF to degress in float format\"\"\"\n d0 = value[0][0]\n d1 = value[0][1]\n d = float(d0) / float(d1)\n\n m0 = value[1][0]\n m1 = value[1][1]\n m = float(m0) / float(m1)\n\n s0 = value[2][0]\n s1 = value[2][1]\n s = float(s0) / float(s1)\n\n return d + (m / 60.0) + (s / 3600.0)\n\n\ndef get_lat_lon(exif_data):\n \"\"\" Returns the latitude and longitude, if available, from the\n provided exif_data (obtained through get_exif_data above) \"\"\"\n lat = None\n lon = None\n\n if \"GPSInfo\" in exif_data:\n gps_info = exif_data[\"GPSInfo\"]\n\n gps_latitude = _get_if_exist(gps_info, \"GPSLatitude\")\n gps_latitude_ref = _get_if_exist(gps_info, 'GPSLatitudeRef')\n gps_longitude = _get_if_exist(gps_info, 'GPSLongitude')\n gps_longitude_ref = _get_if_exist(gps_info, 'GPSLongitudeRef')\n\n if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref:\n lat = _convert_to_degress(gps_latitude)\n if gps_latitude_ref != \"N\":\n lat = 0 - lat\n\n lon = _convert_to_degress(gps_longitude)\n if gps_longitude_ref != \"E\":\n lon = 0 - lon\n\n return lat, lon\n", "repo_name": "WildMeOrg/linc-webapp", "sub_path": "app/lib/exif.py", "file_name": "exif.py", "file_ext": "py", "file_size_in_byte": 4241, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "PIL.Image.open", "line_number": 12, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 12, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 14, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 20, "usage_type": "call"}, {"api_name": "PIL.ExifTags.TAGS.get", "line_number": 24, "usage_type": "call"}, {"api_name": "PIL.ExifTags.TAGS", "line_number": 24, "usage_type": "name"}, {"api_name": "PIL.ExifTags.GPSTAGS.get", "line_number": 30, "usage_type": "call"}, {"api_name": "PIL.ExifTags.GPSTAGS", "line_number": 30, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 48, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 49, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 63, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 63, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 65, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 65, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 67, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 67, "usage_type": "name"}]} +{"seq_id": "70082202931", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom .Res2Net_v1b import res2net50_v1b_26w_4s\n\n\nclass BasicConv2d(nn.Module):\n def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1):\n super(BasicConv2d, self).__init__()\n self.conv = nn.Conv2d(in_planes, out_planes,\n kernel_size=kernel_size, stride=stride,\n padding=padding, dilation=dilation, bias=False)\n self.bn = nn.BatchNorm2d(out_planes)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n return x\n\n\nclass RFB_modified(nn.Module):\n def __init__(self, in_channel, out_channel):\n super(RFB_modified, self).__init__()\n self.relu = nn.ReLU(True)\n self.branch0 = nn.Sequential(\n BasicConv2d(in_channel, out_channel, 1),\n )\n self.branch1 = nn.Sequential(\n BasicConv2d(in_channel, out_channel, 1),\n BasicConv2d(out_channel, out_channel, kernel_size=(1, 3), padding=(0, 1)),\n BasicConv2d(out_channel, out_channel, kernel_size=(3, 1), padding=(1, 0)),\n BasicConv2d(out_channel, out_channel, 3, padding=3, dilation=3)\n )\n self.branch2 = nn.Sequential(\n BasicConv2d(in_channel, out_channel, 1),\n BasicConv2d(out_channel, out_channel, kernel_size=(1, 5), padding=(0, 2)),\n BasicConv2d(out_channel, out_channel, kernel_size=(5, 1), padding=(2, 0)),\n BasicConv2d(out_channel, out_channel, 3, padding=5, dilation=5)\n )\n self.branch3 = nn.Sequential(\n BasicConv2d(in_channel, out_channel, 1),\n BasicConv2d(out_channel, out_channel, kernel_size=(1, 7), padding=(0, 3)),\n BasicConv2d(out_channel, out_channel, kernel_size=(7, 1), padding=(3, 0)),\n BasicConv2d(out_channel, out_channel, 3, padding=7, dilation=7)\n )\n self.conv_cat = BasicConv2d(4*out_channel, out_channel, 3, padding=1)\n self.conv_res = BasicConv2d(in_channel, out_channel, 1)\n\n def forward(self, x):\n x0 = self.branch0(x)\n x1 = self.branch1(x)\n x2 = self.branch2(x)\n x3 = self.branch3(x)\n x_cat = self.conv_cat(torch.cat((x0, x1, x2, x3), 1))\n\n x = self.relu(x_cat + self.conv_res(x))\n return x\n\n\nclass aggregation(nn.Module):\n # dense aggregation, it can be replaced by other aggregation previous, such as DSS, amulet, and so on.\n # used after MSF\n def __init__(self, channel):\n super(aggregation, self).__init__()\n self.relu = nn.ReLU(True)\n\n self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n self.conv_upsample1 = BasicConv2d(channel, channel, 3, padding=1)\n self.conv_upsample2 = BasicConv2d(channel, channel, 3, padding=1)\n self.conv_upsample3 = BasicConv2d(channel, channel, 3, padding=1)\n self.conv_upsample4 = BasicConv2d(channel, channel, 3, padding=1)\n self.conv_upsample5 = BasicConv2d(2*channel, 2*channel, 3, padding=1)\n\n self.conv_concat2 = BasicConv2d(2*channel, 2*channel, 3, padding=1)\n self.conv_concat3 = BasicConv2d(3*channel, 3*channel, 3, padding=1)\n self.conv4 = BasicConv2d(3*channel, 3*channel, 3, padding=1)\n self.conv5 = nn.Conv2d(3*channel, 1, 1)\n\n def forward(self, x1, x2, x3):\n x1_1 = x1\n x2_1 = self.conv_upsample1(self.upsample(x1)) * x2\n x3_1 = self.conv_upsample2(self.upsample(self.upsample(x1))) \\\n * self.conv_upsample3(self.upsample(x2)) * x3\n\n x2_2 = torch.cat((x2_1, self.conv_upsample4(self.upsample(x1_1))), 1)\n x2_2 = self.conv_concat2(x2_2)\n\n x3_2 = torch.cat((x3_1, self.conv_upsample5(self.upsample(x2_2))), 1)\n x3_2 = self.conv_concat3(x3_2)\n\n x = self.conv4(x3_2)\n x = self.conv5(x)\n\n return x\n\n\nclass PraNet(nn.Module):\n # res2net based encoder decoder\n def __init__(self, channel=32):\n super(PraNet, self).__init__()\n # ---- ResNet Backbone ----\n self.resnet = res2net50_v1b_26w_4s(pretrained=True)\n # ---- Receptive Field Block like module ----\n self.rfb2_1 = RFB_modified(512, channel)\n self.rfb3_1 = RFB_modified(1024, channel)\n self.rfb4_1 = RFB_modified(2048, channel)\n # ---- Partial Decoder ----\n self.agg1 = aggregation(channel)\n # ---- reverse attention branch 4 ----\n self.ra4_conv1 = BasicConv2d(2048, 256, kernel_size=1)\n self.ra4_conv2 = BasicConv2d(256, 256, kernel_size=5, padding=2)\n self.ra4_conv3 = BasicConv2d(256, 256, kernel_size=5, padding=2)\n self.ra4_conv4 = BasicConv2d(256, 256, kernel_size=5, padding=2)\n self.ra4_conv5 = BasicConv2d(256, 1, kernel_size=1)\n # ---- reverse attention branch 3 ----\n self.ra3_conv1 = BasicConv2d(1024, 64, kernel_size=1)\n self.ra3_conv2 = BasicConv2d(64, 64, kernel_size=3, padding=1)\n self.ra3_conv3 = BasicConv2d(64, 64, kernel_size=3, padding=1)\n self.ra3_conv4 = BasicConv2d(64, 1, kernel_size=3, padding=1)\n # ---- reverse attention branch 2 ----\n self.ra2_conv1 = BasicConv2d(512, 64, kernel_size=1)\n self.ra2_conv2 = BasicConv2d(64, 64, kernel_size=3, padding=1)\n self.ra2_conv3 = BasicConv2d(64, 64, kernel_size=3, padding=1)\n self.ra2_conv4 = BasicConv2d(64, 1, kernel_size=3, padding=1)\n\n def forward(self, x):\n x = self.resnet.conv1(x)\n x = self.resnet.bn1(x)\n x = self.resnet.relu(x)\n x = self.resnet.maxpool(x) # bs, 64, 88, 88\n # ---- low-level features ----\n x1 = self.resnet.layer1(x) # bs, 256, 88, 88\n x2 = self.resnet.layer2(x1) # bs, 512, 44, 44\n\n x3 = self.resnet.layer3(x2) # bs, 1024, 22, 22\n x4 = self.resnet.layer4(x3) # bs, 2048, 11, 11\n x2_rfb = self.rfb2_1(x2) # channel -> 32\n x3_rfb = self.rfb3_1(x3) # channel -> 32\n x4_rfb = self.rfb4_1(x4) # channel -> 32\n\n ra5_feat = self.agg1(x4_rfb, x3_rfb, x2_rfb)\n lateral_map_5 = F.interpolate(ra5_feat, scale_factor=8, mode='bilinear') # NOTES: Sup-1 (bs, 1, 44, 44) -> (bs, 1, 352, 352)\n\n # ---- reverse attention branch_4 ----\n crop_4 = F.interpolate(ra5_feat, scale_factor=0.25, mode='bilinear')\n x = -1*(torch.sigmoid(crop_4)) + 1\n x = x.expand(-1, 2048, -1, -1).mul(x4)\n x = self.ra4_conv1(x)\n x = F.relu(self.ra4_conv2(x))\n x = F.relu(self.ra4_conv3(x))\n x = F.relu(self.ra4_conv4(x))\n ra4_feat = self.ra4_conv5(x)\n x = ra4_feat + crop_4\n lateral_map_4 = F.interpolate(x, scale_factor=32, mode='bilinear') # NOTES: Sup-2 (bs, 1, 11, 11) -> (bs, 1, 352, 352)\n\n # ---- reverse attention branch_3 ----\n crop_3 = F.interpolate(x, scale_factor=2, mode='bilinear')\n x = -1*(torch.sigmoid(crop_3)) + 1\n x = x.expand(-1, 1024, -1, -1).mul(x3)\n x = self.ra3_conv1(x)\n x = F.relu(self.ra3_conv2(x))\n x = F.relu(self.ra3_conv3(x))\n ra3_feat = self.ra3_conv4(x)\n x = ra3_feat + crop_3\n lateral_map_3 = F.interpolate(x, scale_factor=16, mode='bilinear') # NOTES: Sup-3 (bs, 1, 22, 22) -> (bs, 1, 352, 352)\n\n # ---- reverse attention branch_2 ----\n crop_2 = F.interpolate(x, scale_factor=2, mode='bilinear')\n x = -1*(torch.sigmoid(crop_2)) + 1\n x = x.expand(-1, 512, -1, -1).mul(x2)\n x = self.ra2_conv1(x)\n x = F.relu(self.ra2_conv2(x))\n x = F.relu(self.ra2_conv3(x))\n ra2_feat = self.ra2_conv4(x)\n x = ra2_feat + crop_2\n lateral_map_2 = F.interpolate(x, scale_factor=8, mode='bilinear') # NOTES: Sup-4 (bs, 1, 44, 44) -> (bs, 1, 352, 352)\n\n return lateral_map_5, lateral_map_4, lateral_map_3, lateral_map_2\n\n\nif __name__ == '__main__':\n ras = PraNet().cuda()\n input_tensor = torch.randn(1, 3, 352, 352).cuda()\n\n out = ras(input_tensor)", "repo_name": "DengPingFan/PraNet", "sub_path": "lib/PraNet_Res2Net.py", "file_name": "PraNet_Res2Net.py", "file_ext": "py", "file_size_in_byte": 8083, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 364, "dataset": "github-code", "pt": "20", "api": [{"api_name": "torch.nn.Module", "line_number": 7, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 7, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 10, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 13, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 13, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 14, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 14, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 22, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 25, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 26, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 29, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 35, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 41, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 55, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 61, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 61, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 66, "usage_type": "name"}, {"api_name": "torch.nn.Upsample", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 68, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 78, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 86, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 89, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 98, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 98, "usage_type": "name"}, {"api_name": "Res2Net_v1b.res2net50_v1b_26w_4s", "line_number": 103, "usage_type": "call"}, {"api_name": "torch.nn.functional.interpolate", "line_number": 143, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 143, "usage_type": "name"}, {"api_name": "torch.nn.functional.interpolate", "line_number": 146, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 146, "usage_type": "name"}, {"api_name": "torch.sigmoid", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 150, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 150, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 151, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 151, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 152, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 152, "usage_type": "name"}, {"api_name": "torch.nn.functional.interpolate", "line_number": 155, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 155, "usage_type": "name"}, {"api_name": "torch.nn.functional.interpolate", "line_number": 158, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 158, "usage_type": "name"}, {"api_name": "torch.sigmoid", "line_number": 159, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 162, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 163, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 163, "usage_type": "name"}, {"api_name": "torch.nn.functional.interpolate", "line_number": 166, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 166, "usage_type": "name"}, {"api_name": "torch.nn.functional.interpolate", "line_number": 169, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 169, "usage_type": "name"}, {"api_name": "torch.sigmoid", "line_number": 170, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 173, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 173, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 174, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 174, "usage_type": "name"}, {"api_name": "torch.nn.functional.interpolate", "line_number": 177, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 177, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 184, "usage_type": "call"}]} +{"seq_id": "35759905349", "text": "import numpy as np\r\nimport tensorflow as tf\r\nfrom ConvPool_CNN_C import ConvPool_CNN\r\nfrom tensorflow.keras import datasets\r\nimport time\r\nimport matplotlib.pyplot as plt\r\n\r\n#the path name represetn different configs\r\n#save the train and test error\r\npath = 'wnmobn'\r\nwnmobn_train_err = []\r\nwnmobn_test_err = []\r\n\r\n\r\n#set random seed\r\nseed = 12345\r\n\r\n\r\nnum_epochs = 200 # toal epochs that data pass through\r\nbatch_size = 100 # mini batch size\r\n\r\n\r\n# indicators of using different normalizations\r\nuse_WN,use_BN,use_MOBN=True,False,True\r\nif (use_WN and use_BN ):\r\n print(\"Cannot use weight norm and batch norm together\")\r\n exit(0)\r\nif (use_BN and use_MOBN ):\r\n print(\"Cannot use mean-only batch norm and batch norm together\")\r\n exit(0)\r\n\r\n#print out what normalization is used\r\nprint('Use weight-normalization : ' + str(use_WN))\r\nprint('Use batch-normalization : ' + str(use_BN))\r\nprint('Use mean-only-batch-normalization: ' + str(use_MOBN))\r\n\r\n\r\nrandgen = np.random.RandomState(seed)\r\ntf.set_random_seed(seed)\r\n\r\n#get train, test data from cifar-10\r\n(X_train, y_train), (X_test, y_test) = datasets.cifar10.load_data()\r\n#apply normaliation to images\r\nX_train, X_test = X_train / 255.0, X_test / 255.0\r\n#make them 1d vector\r\ny_train = y_train.reshape(y_train.size)\r\ny_test = y_test.reshape(y_test.size)\r\n\r\n#different batch size for train and test\r\ntrain_batch_size = int(X_train.shape[0] / batch_size)\r\ntest_batch_size = int(X_test.shape[0] / batch_size)\r\n#the batchsize for initializatioon\r\ninit_batch_size = 500\r\n\r\n#our model\r\nmodel = tf.make_template('CONVPool_model', ConvPool_CNN)\r\n\r\n#x is image y is label, x_init for initializtion\r\nx = tf.placeholder(tf.float32, shape=[batch_size, 32, 32, 3])\r\ny = tf.placeholder(tf.int32, shape=[batch_size])\r\nx_initialization = tf.placeholder(tf.float32, shape=[init_batch_size, 32, 32, 3])\r\n\r\n#model initialization\r\ninitialize_model = model(x_initialization, drop_rate=0.5, is_test=False, init=True,use_WN=use_WN,use_BN=use_BN,use_MOBN=use_MOBN)\r\n#model training\r\ntrain_model = model(x, drop_rate=0.5, is_test=False, init=False,use_WN=use_WN,use_BN=use_BN,use_MOBN=use_MOBN)\r\n#train losee\r\nloss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=train_model, name='cross_entropy'))\r\n#model testing\r\ntest_model = model(x, drop_rate=0.5, is_test=True, init=False,use_WN=use_WN,use_BN=use_BN,use_MOBN=use_MOBN)\r\n#make predictions and calculate test error\r\nprediction = tf.argmax(test_model, axis=1, output_type=tf.int32)\r\nnot_eq = tf.cast(tf.not_equal(prediction, y), tf.float32)\r\ntest_error = tf.reduce_mean(not_eq)\r\n\r\n# using Adam optimizer, similar to the paper\r\noptimizer = tf.train.AdamOptimizer(0.001).minimize(loss)\r\n\r\n# save the model\r\nsaver = tf.train.Saver()\r\ninit_global_variables = tf.global_variables_initializer()\r\n\r\nstart = time.time()\r\nprint('start time: ', time.time())\r\nwith tf.Session() as sess:\r\n sess.run(init_global_variables)\r\n for epoch in range(num_epochs):\r\n print('epochs: ', epoch)\r\n #shuffle data\r\n idx = randgen.permutation(X_train.shape[0])\r\n X_train = X_train[idx]\r\n y_train = y_train[idx]\r\n\r\n #initialize the model in the first epoch\r\n if epoch == 0:\r\n sess.run(initialize_model, feed_dict={x_initialization: X_train[:init_batch_size]})\r\n # shuffle data\r\n idx =randgen.permutation(X_train.shape[0])\r\n X_train = X_train[idx]\r\n y_train = y_train[idx]\r\n #calculate train error\r\n train_err = 0.\r\n for t in range(train_batch_size):\r\n feed_dict = {x: X_train[t * batch_size:(t + 1) * batch_size],\r\n y: y_train[t * batch_size:(t + 1) * batch_size]}\r\n l, _ = sess.run([loss, optimizer], feed_dict=feed_dict)\r\n train_err += l\r\n train_err /= train_batch_size\r\n wnmobn_train_err.append(train_err)\r\n print('train error: ', train_err)\r\n\r\n #calculate test error\r\n test_err = 0.\r\n for t in range(test_batch_size):\r\n feed_dict = {x: X_test[t * batch_size:(t + 1) * batch_size], y: y_test[t * batch_size:(t + 1) * batch_size]}\r\n test_error_out = sess.run(test_error, feed_dict=feed_dict)\r\n test_err += test_error_out\r\n test_err /= test_batch_size\r\n wnmobn_test_err.append(test_err)\r\n print('test error: ', test_err)\r\n #save parameters\r\n saved_path = saver.save(sess, './' + path + '/' + path + '_saved_variable')\r\n#show the training time\r\nprint(time.time())\r\ntrain_time = time.time() - start\r\nprint('train time: ', train_time)\r\n\r\n#plot train and test error\r\nplt.plot(wnmobn_test_err, label='test error')\r\nplt.plot(wnmobn_train_err, label='train error')\r\nplt.legend()\r\nplt.show()\r\n#save traintime ,train and test error in three files, they are all numpy array\r\nnp.save('./' + path + '/' + path + '_test_err.npy', wnmobn_test_err)\r\nnp.save('./' + path + '/' + path + '_train_err.npy', wnmobn_train_err)\r\nnp.save('./' + path + '/' + path + '_train_time.npy', train_time)\r\nplt.savefig('./' + path + '/' + path + '_loss.png')", "repo_name": "kkiillee55/e4040-weight-normalization", "sub_path": "TrainModel.py", "file_name": "TrainModel.py", "file_ext": "py", "file_size_in_byte": 5111, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "numpy.random.RandomState", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 38, "usage_type": "attribute"}, {"api_name": "tensorflow.set_random_seed", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.keras.datasets.cifar10.load_data", "line_number": 42, "usage_type": "call"}, {"api_name": "tensorflow.keras.datasets.cifar10", "line_number": 42, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.datasets", "line_number": 42, "usage_type": "name"}, {"api_name": "tensorflow.make_template", "line_number": 56, "usage_type": "call"}, {"api_name": "ConvPool_CNN_C.ConvPool_CNN", "line_number": 56, "usage_type": "argument"}, {"api_name": "tensorflow.placeholder", "line_number": 59, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 59, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 60, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 60, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 61, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 61, "usage_type": "attribute"}, {"api_name": "tensorflow.reduce_mean", "line_number": 68, "usage_type": "call"}, {"api_name": "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "line_number": 68, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 68, "usage_type": "attribute"}, {"api_name": "tensorflow.argmax", "line_number": 72, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 72, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 73, "usage_type": "call"}, {"api_name": "tensorflow.not_equal", "line_number": 73, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 73, "usage_type": "attribute"}, {"api_name": "tensorflow.reduce_mean", "line_number": 74, "usage_type": "call"}, {"api_name": "tensorflow.train.AdamOptimizer", "line_number": 77, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 77, "usage_type": "attribute"}, {"api_name": "tensorflow.train.Saver", "line_number": 80, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 80, "usage_type": "attribute"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 81, "usage_type": "call"}, {"api_name": "time.time", "line_number": 83, "usage_type": "call"}, {"api_name": "time.time", "line_number": 84, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 85, "usage_type": "call"}, {"api_name": "time.time", "line_number": 124, "usage_type": "call"}, {"api_name": "time.time", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 129, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 129, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 130, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 131, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 131, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 132, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 132, "usage_type": "name"}, {"api_name": "numpy.save", "line_number": 134, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 136, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 137, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 137, "usage_type": "name"}]} +{"seq_id": "39085931777", "text": "import time\nimport random\nimport ray\n\n@ray.remote\ndef time_waster(min_delay: float = 1, max_delay: float = 10) -> float:\n delay = (max_delay - min_delay) * random.random() + min_delay\n time.sleep(delay)\n return delay\n\ndef main():\n pending = []\n for i in range(10):\n if i == 0:\n ref = time_waster.remote(min_delay=20, max_delay=30)\n else:\n ref = time_waster.remote(min_delay=2, max_delay=3)\n print(ref)\n pending.append(ref)\n print('submitted', i)\n for ref in pending:\n print(\"About to get\")\n result = ray.get(ref)\n print(\"Got!\")\n print(f\"Delay was {result} sec\")\n\nif __name__ == \"__main__\":\n start = time.time()\n main()\n print(f\"Took {time.time() - start}\")", "repo_name": "joseph-long/talk_python_performance", "sub_path": "ray_ex/ex1.py", "file_name": "ex1.py", "file_ext": "py", "file_size_in_byte": 768, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "24", "api": [{"api_name": "random.random", "line_number": 7, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 8, "usage_type": "call"}, {"api_name": "ray.remote", "line_number": 5, "usage_type": "attribute"}, {"api_name": "ray.get", "line_number": 23, "usage_type": "call"}, {"api_name": "time.time", "line_number": 28, "usage_type": "call"}, {"api_name": "time.time", "line_number": 30, "usage_type": "call"}]} +{"seq_id": "19317945003", "text": "from flask import request, make_response, Response\nfrom flask import jsonify\nfrom app import LOGGER\nfrom app.controllers import face_recognizer\nfrom app.controllers import person_controller\nimport cv2\nimport base64\nimport numpy as np\nfrom app import app\n\n\n@app.route('/api/face/recognizer', methods=['POST'])\ndef recognizer():\n if request.method == \"POST\":\n try:\n imgb64 = request.data['image']\n image = np.fromstring(base64.b64decode(imgb64), np.uint8)\n image = cv2.imdecode(image, cv2.IMREAD_COLOR)\n\n face_dict = face_recognizer.recognize(image)\n LOGGER.info(face_dict)\n\n return make_response(jsonify(face_dict), 200) if face_dict['id'] else Response(\n status=404)\n except Exception as e:\n LOGGER.error(e)\n return Response(status=500)\n\n\n@app.route('/api/face/register', methods=['POST'])\ndef add_face():\n if request.method == \"POST\":\n try:\n imgb64 = request.data['image']\n name = request.data['name']\n sex = request.data['sex'] if request.data['sex'] else None\n phone = request.data['phone'] if request.data['phone'] else None\n email = request.data['email'] if request.data['email'] else None\n image = np.fromstring(base64.b64decode(imgb64), np.uint8)\n image = cv2.imdecode(image, cv2.IMREAD_COLOR)\n\n cropped_face = face_recognizer.get_face(image)\n\n features = face_recognizer.feature_extractor(cropped_face)\n\n person = {\n \"name\": name,\n \"sex\": sex,\n \"phone\": phone,\n \"email\": email,\n \"image\": imgb64,\n \"face_attributes\": np.array(features.squeeze())\n }\n\n if person_controller.create(person):\n return Response(status=201)\n\n return Response(status=400)\n\n except Exception as e:\n LOGGER.error(e)\n return Response(status=500)\n", "repo_name": "BrWillian/face_recognition_api", "sub_path": "app/routes/default.py", "file_name": "default.py", "file_ext": "py", "file_size_in_byte": 2032, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "flask.request.method", "line_number": 14, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 14, "usage_type": "name"}, {"api_name": "flask.request.data", "line_number": 16, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 16, "usage_type": "name"}, {"api_name": "numpy.fromstring", "line_number": 17, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 17, "usage_type": "attribute"}, {"api_name": "cv2.imdecode", "line_number": 18, "usage_type": "call"}, {"api_name": "cv2.IMREAD_COLOR", "line_number": 18, "usage_type": "attribute"}, {"api_name": "app.controllers.face_recognizer.recognize", "line_number": 20, "usage_type": "call"}, {"api_name": "app.controllers.face_recognizer", "line_number": 20, "usage_type": "name"}, {"api_name": "app.LOGGER.info", "line_number": 21, "usage_type": "call"}, {"api_name": "app.LOGGER", "line_number": 21, "usage_type": "name"}, {"api_name": "flask.make_response", "line_number": 23, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 23, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 23, "usage_type": "call"}, {"api_name": "app.LOGGER.error", "line_number": 26, "usage_type": "call"}, {"api_name": "app.LOGGER", "line_number": 26, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 27, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 12, "usage_type": "call"}, {"api_name": "app.app", "line_number": 12, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 32, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 32, "usage_type": "name"}, {"api_name": "flask.request.data", "line_number": 34, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 34, "usage_type": "name"}, {"api_name": "flask.request.data", "line_number": 35, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 35, "usage_type": "name"}, {"api_name": "flask.request.data", "line_number": 36, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 36, "usage_type": "name"}, {"api_name": "flask.request.data", "line_number": 37, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 37, "usage_type": "name"}, {"api_name": "flask.request.data", "line_number": 38, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 38, "usage_type": "name"}, {"api_name": "numpy.fromstring", "line_number": 39, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 39, "usage_type": "attribute"}, {"api_name": "cv2.imdecode", "line_number": 40, "usage_type": "call"}, {"api_name": "cv2.IMREAD_COLOR", "line_number": 40, "usage_type": "attribute"}, {"api_name": "app.controllers.face_recognizer.get_face", "line_number": 42, "usage_type": "call"}, {"api_name": "app.controllers.face_recognizer", "line_number": 42, "usage_type": "name"}, {"api_name": "app.controllers.face_recognizer.feature_extractor", "line_number": 44, "usage_type": "call"}, {"api_name": "app.controllers.face_recognizer", "line_number": 44, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 52, "usage_type": "call"}, {"api_name": "app.controllers.person_controller.create", "line_number": 55, "usage_type": "call"}, {"api_name": "app.controllers.person_controller", "line_number": 55, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 56, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 58, "usage_type": "call"}, {"api_name": "app.LOGGER.error", "line_number": 61, "usage_type": "call"}, {"api_name": "app.LOGGER", "line_number": 61, "usage_type": "name"}, {"api_name": "flask.Response", "line_number": 62, "usage_type": "call"}, {"api_name": "app.app.route", "line_number": 30, "usage_type": "call"}, {"api_name": "app.app", "line_number": 30, "usage_type": "name"}]} +{"seq_id": "31241641884", "text": "# Ahmet Ali Nuhoğlu\n# 21602149\n\n# EEE482 - Computational Neuroscience Homework 3\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport h5py\nfrom scipy.stats import norm\n\nquestion = sys.argv[1]\n\ndef ahmet_ali_nuhoglu_21602149_hw2(question):\n if question == '1' :\n\n print(\"Question 1\")\n print(\"Part A\")\n\n with h5py.File('hw3_data2.mat', 'r') as file:\n Xn, Yn = list(file['Xn']), list(file['Yn'])\n\n Xn = np.array(Xn).T\n Yn = np.array(Yn).flatten()\n\n def ridge_regression(X, y, lmbd):\n return np.linalg.inv(X.T.dot(X) + lmbd * np.identity(np.shape(X)[1])).dot(X.T).dot(y)\n\n def r_squared(Y, pred):\n return (np.corrcoef(Y, pred)[0, 1]) ** 2\n\n def cross_validation(X, y, K, lmbd):\n\n part_len = int(np.size(y) / K)\n\n valid_means_d = dict()\n test_means_d = dict()\n\n for i in range(K):\n valid_data_start = i * part_len\n test_data_start = (i + 1) * part_len\n train_data_start = (i + 2) * part_len\n\n train_data_ind, test_data_ind, valid_data_ind = [], [], []\n\n for j in range(valid_data_start, test_data_start):\n valid_data_ind.append(j % np.size(y))\n\n for j in range(test_data_start, train_data_start):\n test_data_ind.append(j % np.size(y))\n\n for j in range(train_data_start, valid_data_start + np.size(y)):\n train_data_ind.append(j % np.size(y))\n\n x_valid, x_test, x_train = X[valid_data_ind], X[test_data_ind], X[train_data_ind]\n y_valid, y_test, y_train = y[valid_data_ind], y[test_data_ind], y[train_data_ind]\n\n for l in lmbd:\n weight = ridge_regression(x_train, y_train, l)\n\n valid_means_d.setdefault(l, []).append(r_squared(y_valid, x_valid.dot(weight)))\n test_means_d.setdefault(l, []).append(r_squared(y_test, x_test.dot(weight)))\n\n valid_means_d = dict((lmbd, np.mean(val)) for lmbd, val in valid_means_d.items())\n test_means_d = dict((lmbd, np.mean(val)) for lmbd, val in test_means_d.items())\n\n return valid_means_d, test_means_d\n\n lambda_values = np.logspace(0, 12, num=500, base=10)\n dict_valid, dict_test = cross_validation(Xn, Yn, 10, lambda_values)\n\n lambda_opt = max(dict_valid, key=lambda k: dict_valid[k])\n\n x_val, y_val = zip(*sorted(dict_valid.items()))\n x_tst, y_tst = zip(*sorted(dict_test.items()))\n\n plt.figure()\n plt.plot(x_tst, y_tst)\n plt.plot(x_val, y_val)\n plt.legend(['Test Data', 'Validation Data', ])\n plt.ylabel(r'$R^2$')\n plt.xlabel(r'$\\lambda$')\n plt.title(r'$R^2$'' vs ''$\\lambda$')\n plt.xscale('log')\n plt.grid()\n plt.show(block=False)\n\n print(\"Optimal Lambda Value: \", lambda_opt)\n\n print(\"Part B\")\n\n np.random.seed(3)\n\n def bootstrap(iter_num, x, y, lmbd):\n weight_new = []\n for i in range(iter_num):\n new_ind = np.random.choice(np.arange(np.size(y)), np.size(y))\n x_new, y_new = Xn[new_ind], Yn[new_ind]\n weight_r = ridge_regression(x_new, y_new, lmbd)\n weight_new.append(weight_r)\n return weight_new\n\n def find_significant_w(arr_mean, arr_std):\n p_values = 2 * (1 - norm.cdf(np.abs(arr_mean / arr_std)))\n significant_weights = np.where(p_values < 0.05)\n return significant_weights\n\n weight_new = []\n weight_new = bootstrap(500, Xn, Yn, 0)\n\n weight_new_mean = np.mean(weight_new, axis=0)\n weight_new_std = np.std(weight_new, axis=0)\n plt.figure(figsize=(20, 10))\n plt.grid()\n plt.errorbar(np.arange(1, 101), weight_new_mean, yerr=2 * weight_new_std, ecolor='r', fmt='o-k', capsize=5)\n plt.ylabel(r'Resampled Weight Values')\n plt.xlabel(r'Weight Indices')\n plt.title(r'Ridge Regression with ' r'$\\lambda = 0$''\\nand %95 CI')\n plt.show(block=False)\n print(\"Indices of the Resampled Weights which are significantly different than zero:\")\n print(find_significant_w(weight_new_mean, weight_new_std)[0])\n\n print(\"Part C\")\n\n weight_new_ridge = []\n weight_new_ridge = bootstrap(500, Xn, Yn, lambda_opt)\n weight_newR_mean = np.mean(weight_new_ridge, axis=0)\n weight_newR_std = np.std(weight_new_ridge, axis=0)\n plt.figure(figsize=(20, 10))\n plt.grid()\n plt.errorbar(np.arange(1, 101), weight_newR_mean, yerr=2 * weight_newR_std, ecolor='r', fmt='o-k', capsize=5)\n plt.ylabel(r'Resampled Weight Values')\n plt.xlabel(r'Weight Indices')\n plt.title(r'Ridge Regression with ' r'$\\lambda = \\lambda_{opt}$''\\nand %95 CI')\n plt.show(block=False)\n print(\"Indices of the Resampled Weights which are significantly different than zero:\")\n print(find_significant_w(weight_newR_mean, weight_newR_std)[0])\n\n\n elif question == '2':\n\n print(\"Question 2\")\n\n print(\"Part A\")\n\n with h5py.File('hw3_data3.mat', 'r') as file:\n pop1, pop2 = np.array(list(file['pop1'])).flatten(), np.array(list(file['pop2'])).flatten()\n\n def bootstrap(iter_num, x, seed=6):\n np.random.seed(seed)\n x_new = []\n for i in range(iter_num):\n new_ind = np.random.choice(np.arange(np.size(x)), np.size(x))\n x_sample = x[new_ind]\n x_new.append(x_sample)\n return np.array(x_new)\n\n def mean_difference(x, y, iterations):\n xy_concat = np.concatenate((x, y))\n xy_boot = bootstrap(iterations, xy_concat)\n x_boot = np.zeros((iterations, np.size(x)))\n y_boot = np.zeros((iterations, np.size(y)))\n for i in range(np.size(xy_concat)):\n if i < np.size(x):\n x_boot[:, i] = xy_boot[:, i]\n else:\n y_boot[:, i - np.size(x)] = xy_boot[:, i]\n x_means = np.mean(x_boot, axis=1)\n y_means = np.mean(y_boot, axis=1)\n mean_diff = x_means - y_means\n\n return mean_diff\n\n mean_diff = mean_difference(pop1, pop2, 10000)\n\n def find_z_and_p(x, mu):\n mu_0 = np.mean(x)\n sigma = np.std(x)\n z = np.abs((mu - mu_0) / sigma)\n p = (1 - norm.cdf(z))\n return z, p\n\n plt.figure()\n plt.title('Population Mean Difference')\n plt.xlabel('Difference of Means')\n plt.ylabel('P(x)')\n plt.yticks([])\n plt.hist(mean_diff, bins=60, density=True, edgecolor='black')\n plt.show(block=False)\n\n z, p = find_z_and_p(mean_diff, np.mean(pop1) - np.mean(pop2))\n print(\"z-score: \", z)\n print(\"two sided p-value: \", 2 * p)\n\n print(\"Part B\")\n\n with h5py.File('hw3_data3.mat', 'r') as file:\n vox1, vox2 = np.array(list(file['vox1'])).flatten(), np.array(list(file['vox2'])).flatten()\n\n vox1_boot = bootstrap(10000, vox1)\n vox2_boot = bootstrap(10000, vox2)\n\n corr_boot = np.zeros(10000)\n for i in range(10000):\n corr_boot[i] = np.corrcoef(vox1_boot[i], vox2_boot[i])[0, 1]\n\n corr_mean = np.mean(corr_boot)\n sorted_corr = np.sort(corr_boot)\n dif = np.size(sorted_corr) / 40\n corr_lower = sorted_corr[int(dif)]\n corr_upper = sorted_corr[int(np.size(sorted_corr) - dif)]\n print(\"Mean: \", corr_mean)\n print(\"%95 CI: (\", corr_lower, \", \", corr_upper, \")\")\n\n zero_corr = np.where(corr_boot < 10 ** (-2))\n print(\"Number of elements with zero correlation: \", np.size(zero_corr))\n\n print(\"Part C\")\n\n vox1_indep = bootstrap(10000, vox1, 13)\n vox2_indep = bootstrap(10000, vox2, 5)\n\n corr_boot_indep = np.zeros(10000)\n for i in range(10000):\n corr_boot_indep[i] = np.corrcoef(vox1_indep[i], vox2_indep[i])[0, 1]\n\n plt.figure()\n plt.title('Correlation between vox1 and vox2')\n plt.xlabel('Correlation (x)')\n plt.ylabel('P(x)')\n plt.yticks([])\n plt.hist(corr_boot_indep, bins=60, density=True, edgecolor='black')\n plt.show(block=False)\n\n z, p = find_z_and_p(corr_boot_indep, np.corrcoef(vox1, vox2)[0, 1])\n print(\"z-score: \", z)\n print(\"one sided p value: \", p)\n\n print(\"Part D\")\n\n with h5py.File('hw3_data3.mat', 'r') as file:\n building, face = np.array(list(file['building'])).flatten(), np.array(list(file['face'])).flatten()\n\n mean_diff_d = np.zeros(10000)\n diff_options = np.zeros(4)\n choices = np.zeros(20)\n\n for i in range(10000):\n for j in range(20):\n ind = np.random.choice(20)\n diff_options[0:1] = 0\n diff_options[2] = building[ind] - face[ind]\n diff_options[3] = -1 * diff_options[2]\n choices[j] = diff_options[np.random.choice(4)]\n mean_diff_d[i] = np.mean(choices)\n\n plt.figure()\n plt.title('Difference of Means\\nBuilding - Face\\n(Subject Population = Same)')\n plt.xlabel('Difference of Means (x)')\n plt.ylabel('P(x)')\n plt.yticks([])\n plt.hist(mean_diff_d, bins=60, density=True, edgecolor='black')\n plt.show(block=False)\n\n z, p = find_z_and_p(mean_diff_d, np.mean(building) - np.mean(face))\n print(\"z-score: \", z)\n print(\"Two sided p value: \", 2 * p)\n\n print(\"Part E\")\n\n mean_diff_e = mean_difference(building, face, 10000)\n\n plt.figure()\n plt.title('Difference of Means\\nBuilding - Face\\n(Subject Population = Different)')\n plt.xlabel('Difference of Means (x)')\n plt.ylabel('P(x)')\n plt.yticks([])\n plt.hist(mean_diff_e, bins=60, density=True, edgecolor='black')\n plt.show(block=False)\n\n z_e, p_e = find_z_and_p(mean_diff_e, np.mean(building) - np.mean(face))\n print(\"z-score: \", z_e)\n print(\"Two sided p value: \", 2 * p_e)\n\n\n\nahmet_ali_nuhoglu_21602149_hw2(question)\n", "repo_name": "ahmetalinuhoglu/Computational_Neuroscience", "sub_path": "Homework 3/ahmet_ali_nuhoglu_21602149_hw3.py", "file_name": "ahmet_ali_nuhoglu_21602149_hw3.py", "file_ext": "py", "file_size_in_byte": 10271, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "h5py.File", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 26, "usage_type": "attribute"}, {"api_name": "numpy.identity", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.shape", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.corrcoef", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.logspace", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 77, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 77, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 78, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 80, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 81, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 81, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xscale", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 83, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 84, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 85, "usage_type": "name"}, {"api_name": "numpy.random.seed", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 91, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 96, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 96, "usage_type": "call"}, {"api_name": "scipy.stats.norm.cdf", "line_number": 103, "usage_type": "call"}, {"api_name": "scipy.stats.norm", "line_number": 103, "usage_type": "name"}, {"api_name": "numpy.abs", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 112, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 112, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 113, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.errorbar", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 115, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 117, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 117, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 118, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 129, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 129, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.errorbar", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 130, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 131, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 131, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 132, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 132, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 133, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 134, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 134, "usage_type": "name"}, {"api_name": "h5py.File", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 146, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 149, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 152, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 158, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 160, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 160, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 161, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 161, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 167, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 168, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 178, "usage_type": "call"}, {"api_name": "scipy.stats.norm.cdf", "line_number": 179, "usage_type": "call"}, {"api_name": "scipy.stats.norm", "line_number": 179, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 182, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 182, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 183, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 183, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 184, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 184, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 185, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 185, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 186, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 186, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 187, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 187, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 188, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 188, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 190, "usage_type": "call"}, {"api_name": "h5py.File", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 197, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.corrcoef", "line_number": 204, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 206, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 207, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 208, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 210, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 214, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 222, "usage_type": "call"}, {"api_name": "numpy.corrcoef", "line_number": 224, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 226, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 226, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 227, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 227, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 228, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 228, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 229, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 229, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 230, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 230, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 231, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 231, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 232, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 232, "usage_type": "name"}, {"api_name": "numpy.corrcoef", "line_number": 234, "usage_type": "call"}, {"api_name": "h5py.File", "line_number": 240, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 241, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 243, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 244, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 245, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 249, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 249, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 253, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 253, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 254, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 256, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 256, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 257, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 257, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 258, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 258, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 259, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 259, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 260, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 260, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 261, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 261, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 262, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 262, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 264, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 272, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 272, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 273, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 273, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 274, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 274, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 275, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 275, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 276, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 276, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 277, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 277, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 278, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 278, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 280, "usage_type": "call"}]} +{"seq_id": "3673744060", "text": "import unittest\nimport zope.component.event\nfrom zope.testing import doctest\n\nfrom zope.app.container.contained import Contained, ObjectRemovedEvent\nfrom zope.app.container.interfaces import IContained, IObjectRemovedEvent\nfrom zope.app.container.sample import SampleContainer\nfrom zope.app.testing.placelesssetup import setUp, tearDown\nfrom zope.app.testing import ztapi\n\nclass TestObjectEventNotifications(unittest.TestCase):\n\n def setUp(self):\n self.callbackTriggered = False\n setUp()\n\n def tearDown(self):\n tearDown()\n\n def testNotify(self):\n events = []\n\n def record(*args):\n events.append(args)\n\n ztapi.subscribe([IContained, IObjectRemovedEvent], None, record)\n\n item = Contained()\n event = ObjectRemovedEvent(item)\n zope.component.event.objectEventNotify(event)\n self.assertEqual([(item, event)], events)\n\n def testNotifyNobody(self):\n # Check that notify won't raise an exception in absence of\n # of subscribers.\n events = []\n item = Contained()\n evt = ObjectRemovedEvent(item)\n zope.component.event.objectEventNotify(evt)\n self.assertEqual([], events)\n\n def testVeto(self):\n zope.component.provideHandler(zope.component.event.objectEventNotify)\n container = SampleContainer()\n item = Contained()\n\n # This will fire an event.\n container['Fred'] = item\n\n class Veto(Exception):\n pass\n \n def callback(item, event):\n self.callbackTriggered = True\n self.assertEqual(item, event.object)\n raise Veto\n\n ztapi.subscribe([IContained, IObjectRemovedEvent], None, callback)\n\n # del container['Fred'] will fire an ObjectRemovedEvent event.\n self.assertRaises(Veto, container.__delitem__, 'Fred')\n \ndef test_suite():\n return unittest.TestSuite((\n unittest.makeSuite(TestObjectEventNotifications),\n ))\n\nif __name__=='__main__':\n unittest.main(defaultTest='test_suite')\n", "repo_name": "Donkyhotay/MoonPy", "sub_path": "zope/app/event/tests/test_objectevent.py", "file_name": "test_objectevent.py", "file_ext": "py", "file_size_in_byte": 2057, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "unittest.TestCase", "line_number": 11, "usage_type": "attribute"}, {"api_name": "zope.app.testing.placelesssetup.setUp", "line_number": 15, "usage_type": "call"}, {"api_name": "zope.app.testing.placelesssetup.tearDown", "line_number": 18, "usage_type": "call"}, {"api_name": "zope.app.testing.ztapi.subscribe", "line_number": 26, "usage_type": "call"}, {"api_name": "zope.app.testing.ztapi", "line_number": 26, "usage_type": "name"}, {"api_name": "zope.app.container.interfaces.IContained", "line_number": 26, "usage_type": "name"}, {"api_name": "zope.app.container.interfaces.IObjectRemovedEvent", "line_number": 26, "usage_type": "name"}, {"api_name": "zope.app.container.contained.Contained", "line_number": 28, "usage_type": "call"}, {"api_name": "zope.app.container.contained.ObjectRemovedEvent", "line_number": 29, "usage_type": "call"}, {"api_name": "zope.component.event.component.event.objectEventNotify", "line_number": 30, "usage_type": "call"}, {"api_name": "zope.component.event.component", "line_number": 30, "usage_type": "attribute"}, {"api_name": "zope.component.event", "line_number": 30, "usage_type": "name"}, {"api_name": "zope.app.container.contained.Contained", "line_number": 37, "usage_type": "call"}, {"api_name": "zope.app.container.contained.ObjectRemovedEvent", "line_number": 38, "usage_type": "call"}, {"api_name": "zope.component.event.component.event.objectEventNotify", "line_number": 39, "usage_type": "call"}, {"api_name": "zope.component.event.component", "line_number": 39, "usage_type": "attribute"}, {"api_name": "zope.component.event", "line_number": 39, "usage_type": "name"}, {"api_name": "zope.component.event.component.provideHandler", "line_number": 43, "usage_type": "call"}, {"api_name": "zope.component.event.component", "line_number": 43, "usage_type": "attribute"}, {"api_name": "zope.component.event", "line_number": 43, "usage_type": "name"}, {"api_name": "zope.app.container.sample.SampleContainer", "line_number": 44, "usage_type": "call"}, {"api_name": "zope.app.container.contained.Contained", "line_number": 45, "usage_type": "call"}, {"api_name": "zope.app.testing.ztapi.subscribe", "line_number": 58, "usage_type": "call"}, {"api_name": "zope.app.testing.ztapi", "line_number": 58, "usage_type": "name"}, {"api_name": "zope.app.container.interfaces.IContained", "line_number": 58, "usage_type": "name"}, {"api_name": "zope.app.container.interfaces.IObjectRemovedEvent", "line_number": 58, "usage_type": "name"}, {"api_name": "unittest.TestSuite", "line_number": 64, "usage_type": "call"}, {"api_name": "unittest.makeSuite", "line_number": 65, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 69, "usage_type": "call"}]} +{"seq_id": "9119702923", "text": "#\n\n# map the labels\n\nfrom collections import Counter\nfrom mspx.data.rw import ReaderGetterConf, WriterGetterConf, FileStreamer\nfrom mspx.utils import zlog\n\nMAPPINGS = {\n'cner_T': { # trg2src\n 'PER': 'researcher, person, writer, musicalartist, politician, scientist',\n 'ORG': 'organisation, university, band, politicalparty',\n 'LOC': 'country, location',\n 'MISC': 'misc',\n}\n}\n\ndef main(input_path, output_path, code):\n # get the map\n _map = MAPPINGS[code]\n for k in list(_map.keys()):\n v = _map[k]\n if isinstance(v, str):\n v = [z.strip() for z in v.split(\",\")]\n _map[k] = set(v)\n if code.endswith(\"_T\"): # reverse\n _map2 = {}\n for k, v in _map.items():\n for k2 in v:\n assert k2 not in _map2\n _map2[k2] = k\n _map = _map2\n # --\n cc = Counter()\n cc2 = Counter()\n insts = list(ReaderGetterConf().get_reader(input_path=input_path))\n for inst in insts:\n cc['inst'] += 1\n for frame in inst.get_frames():\n trg_label = _map.get(frame.label)\n cc2[trg_label] += 1\n cc['frame'] += 1\n if trg_label is None:\n frame.del_self()\n cc['frame_del'] += 1\n elif trg_label != frame.label:\n frame.set_label(trg_label)\n cc['frame_reset'] += 1\n else:\n cc['frame_keep'] += 1\n zlog(f\"Finish processing {input_path}: {cc} {cc2}\")\n if output_path:\n with WriterGetterConf().get_writer(output_path=output_path) as writer:\n writer.write_insts(insts)\n # --\n\n# python3 -m mspx.scripts.data.ner.map_label\nif __name__ == '__main__':\n import sys\n main(*sys.argv[1:])\n", "repo_name": "zzsfornlp/zmsp", "sub_path": "mspx/scripts/data/ner/map_label.py", "file_name": "map_label.py", "file_ext": "py", "file_size_in_byte": 1755, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 25, "dataset": "github-code", "pt": "25", "api": [{"api_name": "collections.Counter", "line_number": 34, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 35, "usage_type": "call"}, {"api_name": "mspx.data.rw.ReaderGetterConf", "line_number": 36, "usage_type": "call"}, {"api_name": "mspx.utils.zlog", "line_number": 51, "usage_type": "call"}, {"api_name": "mspx.data.rw.WriterGetterConf", "line_number": 53, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 60, "usage_type": "attribute"}]} +{"seq_id": "1375948912", "text": "import re\nimport ssl\nimport base64\nfrom socket import *\n\nSERVER_ADDRESSES = {\n \"yandex\": (\"smtp.yandex.ru\", 465),\n \"mail\": (\"smtp.mail.ru\", 465),\n \"rambler\": (\"smtp.rambler.ru\", 465)\n}\n\nDIRECTORY = \"письмо\\\\\"\nLETTER_FILE = DIRECTORY + \"letter.txt\"\nCONFIG_FILE = DIRECTORY + \"config.txt\"\nTIMEOUT = 6\n\n\nclass Letter:\n def __init__(self):\n self.text = None\n self.subject = None\n self.recipients = []\n self.attachments = []\n\n def generate_letter(self, sender: bytes) -> bytes:\n text = add_escapes_to_text(self.text)\n boundary = self.generate_boundary()\n header = b'From: %s\\r\\n' % sender + \\\n b'To: %s\\r\\n' % ', '.join(self.recipients).encode() + \\\n b'Subject: %s\\r\\n' % self.subject.encode()[:-1]\n headers_and_text_plain = \\\n b'MIME-Version: 1.0\\r\\n' \\\n b'Content-Type: multipart/mixed; boundary=\"%s\"\\r\\n\\r\\n' % boundary + \\\n b'\\r\\n' \\\n b'--%s\\r\\n' % boundary + \\\n b'Content-Type: text/plain\\r\\n' \\\n b'\\r\\n' \\\n b'%s' % text\n attachments = self.convert_attachments(boundary)\n ending = b'\\r\\n--%s--\\r\\n' % boundary + \\\n b'.\\r\\n'\n return header + headers_and_text_plain + attachments + ending\n\n def generate_boundary(self) -> bytes:\n return b'boundary1q2w3e4r5t6y7u8i9o0pboundary'\n\n def convert_attachments(self, boundary: bytes) -> bytes:\n parts = []\n for name, data in self.attachments:\n parts.append(b\"\\r\\n--%s\\r\\n\" % boundary)\n header = b'Content-Disposition: attachment;\tfilename=\"%s\"\\r\\n' % name + \\\n b'Content-Transfer-Encoding: base64\\r\\n' + \\\n b'Content-Type: application/octet-stream; name=\"%s\"\\r\\n\\r\\n' % name\n parts.append(header)\n parts.append(base64.b64encode(data))\n return b''.join(parts)\n\n\ndef add_escapes_to_text(text: bytes) -> bytes:\n if text[0] == b'.':\n text = b'.' + text\n return re.sub(b\"\\n\\.\", b\"\\n..\", text)\n\n\ndef get_letter_from_files() -> Letter:\n letter = Letter()\n with open(LETTER_FILE, 'rb') as f:\n letter.text = f.read()\n with open(CONFIG_FILE, 'rb') as f:\n config = f.read().decode()\n letter.recipients, letter.subject, letter.attachments = parse_config(config)\n load_attachments(letter)\n return letter\n\n\ndef parse_config(config: str):\n to_start = config.find(\"TO:\")\n subject_start = config.find(\"SUBJECT:\")\n attachments_start = config.find(\"ATTACHMENTS:\")\n if to_start == -1 or subject_start == -1 or attachments_start == -1 \\\n and not (to_start < subject_start < attachments_start):\n raise ValueError(\"Incorrect config file\")\n to = config[to_start + len(\"TO:\\r\\n\"):subject_start].split('\\r\\n')\n subject = config[subject_start + len(\"SUBJECT:\\r\\n\"):attachments_start]\n attachments = config[attachments_start+len(\"ATTACHMENTS:\\r\\n\"):].split(\"\\r\\n\")\n return to, subject, attachments\n\n\ndef load_attachments(letter):\n letter.attachments = [(name.encode(), load_file(name)) for name in letter.attachments if name != \"\"]\n\n\ndef load_file(file_name):\n with open(DIRECTORY + file_name, 'rb') as file:\n data = file.read()\n return data\n\n\ndef check_login_and_parse_server(login: str):\n m = re.match('([-a-z0-9_.]+)@([-a-z0-9]+)\\.([a-z]{2,6})', login)\n if not m:\n return False\n return m.groups()[1]\n\n\ndef get_ssl_socket_connection(address):\n sock = socket()\n sock.settimeout(TIMEOUT)\n sock.connect(address)\n sock = ssl.wrap_socket(sock)\n return sock\n\n\ndef send_recv(sock: socket, command: bytes):\n try:\n sock.send(command)\n data = sock.recv(1024)\n except Exception as e:\n return b\"Connection error \" + str(e).encode()\n return data\n\n\nclass SMTPClient:\n def __init__(self, login, password):\n self.login = login.encode()\n self.password = password.encode()\n self.server = check_login_and_parse_server(login)\n if not self.server:\n raise Exception(\"Incorrect login\")\n if self.server not in SERVER_ADDRESSES:\n raise Exception(\"Client does not send letters from the mailboxes of this domain\")\n self.server_address = SERVER_ADDRESSES[self.server]\n self.sock = get_ssl_socket_connection(self.server_address)\n answer = self.sock.recv(1024)\n if not answer.startswith(b\"2\"):\n raise Exception(answer.decode())\n self.greet_server()\n self.introduce()\n\n def send_command_sequence(self, commands):\n i = 0\n prev_bad_command = -1\n while i < len(commands):\n command = commands[i]\n answer = send_recv(self.sock, command)\n if answer.startswith(b\"4\"):\n if prev_bad_command != i:\n prev_bad_command = i\n i = 0\n continue\n if not answer.startswith(b\"2\") and not answer.startswith(b\"3\"):\n raise Exception(answer.decode())\n i += 1\n\n def greet_server(self):\n command_seq = [\n b'EHLO %s\\r\\n' % self.login\n ]\n self.send_command_sequence(command_seq)\n\n def introduce(self):\n encode_login = base64.b64encode(self.login) + b'\\r\\n'\n encode_password = base64.b64encode(self.password) + b'\\r\\n'\n command_seq = [\n b\"AUTH LOGIN\\r\\n\",\n encode_login,\n encode_password\n ]\n self.send_command_sequence(command_seq)\n\n def send(self, letter):\n command_seq = [b\"MAIL FROM: <\" + self.login + b\">\\r\\n\"]\n for recipient in letter.recipients:\n if recipient:\n command_seq.append(b\"RCPT TO: <\" + recipient.encode() + b\">\\r\\n\")\n data = letter.generate_letter(self.login)\n command_seq.append(b\"DATA\\r\\n\")\n command_seq.append(data)\n self.send_command_sequence(command_seq)\n\n def finish_connection(self):\n send_recv(self.sock, b\"QUIT\\r\\n\")\n self.sock.close()\n\n\ndef main():\n while True:\n login = input(\"LOGIN: \")\n login = \"testtesttest100500@yandex.ru\"\n password = input(\"PASSWORD: \")\n password = \"12345678901234567890\"\n try:\n client = SMTPClient(login, password)\n except Exception as e:\n print(str(e))\n continue\n break\n print(\"Authentication was successful\")\n try:\n letter = get_letter_from_files()\n except Exception as e:\n print(str(e))\n return\n print(\"Letter was formed\")\n try:\n client.send(letter)\n except Exception as e:\n print(str(e))\n return\n print(\"Letter was sent\")\n\n\nif __name__ == \"__main__\":\n main()\n", "repo_name": "SvetlanaNesterova/internet_utils", "sub_path": "SMTPclient.py", "file_name": "SMTPclient.py", "file_ext": "py", "file_size_in_byte": 6800, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "base64.b64encode", "line_number": 55, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 62, "usage_type": "call"}, {"api_name": "re.match", "line_number": 100, "usage_type": "call"}, {"api_name": "ssl.wrap_socket", "line_number": 110, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 162, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 163, "usage_type": "call"}]} +{"seq_id": "10027206722", "text": "# Yukawa potential\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.optimize import bisect\n\ndef Veff(r): # effective potential\n return (L*(L+1)/(2*mass*r)-np.exp(-0.1*r))/r\n \ndef f(r): # Sch eqn in Numerov form\n return 2*mass*(E-Veff(r))\n \ndef numerov(f, u, n, x, h): # Numerov integrator for $u''+f(x)u=0$\n nodes, c = 0, h*h/12. # given $[u_0,u_1]$, return $[u_0,u_1,...,u_{n+1}]$\n f0, f1 = 0., f(x+h)\n for i in range(n):\n x += h\n f2 = f(x+h) # Numerov method below, \n u.append((2*(1-5*c*f1)*u[i+1] - (1+c*f0)*u[i])/(1+c*f2)) \n f0, f1 = f1, f2\n if (u[-1]*u[-2] < 0.1): nodes += 1\n return u, nodes # return u, nodes\n \ndef shoot(En):\n global E # E needed in f(r)\n E, c, xm = En, (h*h)/6., xL + M*h\n wfup, nup = numerov(f, [0,.01], M, xL, h)\n wfdn, ndn = numerov(f, [0,.01], N-M, xR, -h) # $f'$ from \n dup = ((1+c*f(xm+h))*wfup[-1] - (1+c*f(xm-h))*wfup[-3])/(h+h)\n ddn = ((1+c*f(xm+h))*wfdn[-3] - (1+c*f(xm-h))*wfdn[-1])/(h+h)\n return dup*wfdn[-2] - wfup[-2]*ddn\n\nxL, xR, N = 0., 120., 2200 # limits, intervals\nxa=np.linspace(xL, xR, N+1)\nh, mass = (xR-xL)/N, 1.0 # step size, mass\nLmax, EL, M = 1, [], 100 # M = matching point\n\n\nL=0\nS='E%f*27.211 ev'\nn, Ea, dE = L+1,[], 0.001 \nEstart = -.5/np.arange(1, Lmax+1)**2-0.1, # $\\sim -1/2n^2$\nE1=Estart[L]\n# sweep E range for each L\nwhile (E1 < -dE):\n E1 += dE\n if (shoot(E1)*shoot(E1 + dE) > 0): continue\n E = bisect(shoot, E1, E1 + dE)\n Ea.append(E)\n wfup, nup = numerov(f, [0,.1], M-1, xL, h) # calc wf\n wfdn, ndn = numerov(f, [0,.1], N-M-1, xR, -h)\n psix = np.concatenate((wfup[:-1], wfdn[::-1]))\n psix[M:] *= wfup[-1]/wfdn[-1] # match\n plt.plot(xa, psix, label=S%E )\n plt.legend()\n print ('nodes, n,l,E=', nup+ndn, n, L, E*27.211)\n n += 1\n \nplt.show()\n\n\n\n\n\n\n\n\n\n", "repo_name": "MrinalRajak/Yukawa_potential", "sub_path": "Yukawa_potential.py", "file_name": "Yukawa_potential.py", "file_ext": "py", "file_size_in_byte": 2026, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "numpy.exp", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 42, "usage_type": "call"}, {"api_name": "scipy.optimize.bisect", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}]} +{"seq_id": "12490504374", "text": "import sys\r\n\r\nfrom PyQt5.QtWidgets import QWidget, QApplication, QCheckBox,QLabel,QPushButton,QVBoxLayout\r\n\r\nclass Pencere(QWidget):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.init_ui()\r\n\r\n def init_ui(self):\r\n self.checkbox = QCheckBox(\"Pythonu seviyor musun ?\")\r\n self.yazı_alanı = QLabel(\"\")\r\n self.button =QPushButton(\"Buraya Tıkla\")\r\n\r\n v_box = QVBoxLayout()\r\n v_box.addWidget(self.checkbox)\r\n v_box.addWidget(self.yazı_alanı)\r\n v_box.addWidget(self.button)\r\n\r\n self.setLayout(v_box)\r\n\r\n self.setWindowTitle(\"Check Box\")\r\n\r\n self.button.clicked.connect(lambda : self.click(self.checkbox.isChecked(), self.yazı_alanı))\r\n\r\n self.show()\r\n \r\n def click(self,checkbox,yazı_alani):\r\n if checkbox:\r\n yazı_alani.setText(\"Çok güzel seviyorsun\")\r\n else:\r\n yazı_alani.setText(\"Neden sevmiyorsun\")\r\n\r\napp = QApplication(sys.argv)\r\n\r\npencere = Pencere()\r\n\r\nsys.exit(app.exec_())\r\n\r\n\r\n", "repo_name": "ahmet-candan/Working-on-PyQt5-", "sub_path": "checkbox.py", "file_name": "checkbox.py", "file_ext": "py", "file_size_in_byte": 1036, "program_lang": "python", "lang": "tr", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 5, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QCheckBox", "line_number": 12, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 13, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 14, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QVBoxLayout", "line_number": 16, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 35, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 35, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 39, "usage_type": "call"}]} +{"seq_id": "20947463472", "text": "from collections.abc import Sequence\n\nimport numpy as np\nfrom mmengine.logging import print_log\nfrom terminaltables import AsciiTable\n\nfrom .bbox_overlaps import bbox_overlaps\n\n\ndef _recalls(all_ious, proposal_nums, thrs):\n\n img_num = all_ious.shape[0]\n total_gt_num = sum([ious.shape[0] for ious in all_ious])\n\n _ious = np.zeros((proposal_nums.size, total_gt_num), dtype=np.float32)\n for k, proposal_num in enumerate(proposal_nums):\n tmp_ious = np.zeros(0)\n for i in range(img_num):\n ious = all_ious[i][:, :proposal_num].copy()\n gt_ious = np.zeros((ious.shape[0]))\n if ious.size == 0:\n tmp_ious = np.hstack((tmp_ious, gt_ious))\n continue\n for j in range(ious.shape[0]):\n gt_max_overlaps = ious.argmax(axis=1)\n max_ious = ious[np.arange(0, ious.shape[0]), gt_max_overlaps]\n gt_idx = max_ious.argmax()\n gt_ious[j] = max_ious[gt_idx]\n box_idx = gt_max_overlaps[gt_idx]\n ious[gt_idx, :] = -1\n ious[:, box_idx] = -1\n tmp_ious = np.hstack((tmp_ious, gt_ious))\n _ious[k, :] = tmp_ious\n\n _ious = np.fliplr(np.sort(_ious, axis=1))\n recalls = np.zeros((proposal_nums.size, thrs.size))\n for i, thr in enumerate(thrs):\n recalls[:, i] = (_ious >= thr).sum(axis=1) / float(total_gt_num)\n\n return recalls\n\n\ndef set_recall_param(proposal_nums, iou_thrs):\n \"\"\"Check proposal_nums and iou_thrs and set correct format.\"\"\"\n if isinstance(proposal_nums, Sequence):\n _proposal_nums = np.array(proposal_nums)\n elif isinstance(proposal_nums, int):\n _proposal_nums = np.array([proposal_nums])\n else:\n _proposal_nums = proposal_nums\n\n if iou_thrs is None:\n _iou_thrs = np.array([0.5])\n elif isinstance(iou_thrs, Sequence):\n _iou_thrs = np.array(iou_thrs)\n elif isinstance(iou_thrs, float):\n _iou_thrs = np.array([iou_thrs])\n else:\n _iou_thrs = iou_thrs\n\n return _proposal_nums, _iou_thrs\n\n\ndef eval_recalls(gts,\n proposals,\n proposal_nums=None,\n iou_thrs=0.5,\n logger=None,\n use_legacy_coordinate=False):\n \"\"\"Calculate recalls.\n\n Args:\n gts (list[ndarray]): a list of arrays of shape (n, 4)\n proposals (list[ndarray]): a list of arrays of shape (k, 4) or (k, 5)\n proposal_nums (int | Sequence[int]): Top N proposals to be evaluated.\n iou_thrs (float | Sequence[float]): IoU thresholds. Default: 0.5.\n logger (logging.Logger | str | None): The way to print the recall\n summary. See `mmengine.logging.print_log()` for details.\n Default: None.\n use_legacy_coordinate (bool): Whether use coordinate system\n in mmdet v1.x. \"1\" was added to both height and width\n which means w, h should be\n computed as 'x2 - x1 + 1` and 'y2 - y1 + 1'. Default: False.\n\n\n Returns:\n ndarray: recalls of different ious and proposal nums\n \"\"\"\n\n img_num = len(gts)\n assert img_num == len(proposals)\n proposal_nums, iou_thrs = set_recall_param(proposal_nums, iou_thrs)\n all_ious = []\n for i in range(img_num):\n if proposals[i].ndim == 2 and proposals[i].shape[1] == 5:\n scores = proposals[i][:, 4]\n sort_idx = np.argsort(scores)[::-1]\n img_proposal = proposals[i][sort_idx, :]\n else:\n img_proposal = proposals[i]\n prop_num = min(img_proposal.shape[0], proposal_nums[-1])\n if gts[i] is None or gts[i].shape[0] == 0:\n ious = np.zeros((0, img_proposal.shape[0]), dtype=np.float32)\n else:\n ious = bbox_overlaps(\n gts[i],\n img_proposal[:prop_num, :4],\n use_legacy_coordinate=use_legacy_coordinate)\n all_ious.append(ious)\n all_ious = np.array(all_ious)\n recalls = _recalls(all_ious, proposal_nums, iou_thrs)\n\n print_recall_summary(recalls, proposal_nums, iou_thrs, logger=logger)\n return recalls\n\n\ndef print_recall_summary(recalls,\n proposal_nums,\n iou_thrs,\n row_idxs=None,\n col_idxs=None,\n logger=None):\n \"\"\"Print recalls in a table.\n\n Args:\n recalls (ndarray): calculated from `bbox_recalls`\n proposal_nums (ndarray or list): top N proposals\n iou_thrs (ndarray or list): iou thresholds\n row_idxs (ndarray): which rows(proposal nums) to print\n col_idxs (ndarray): which cols(iou thresholds) to print\n logger (logging.Logger | str | None): The way to print the recall\n summary. See `mmengine.logging.print_log()` for details.\n Default: None.\n \"\"\"\n proposal_nums = np.array(proposal_nums, dtype=np.int32)\n iou_thrs = np.array(iou_thrs)\n if row_idxs is None:\n row_idxs = np.arange(proposal_nums.size)\n if col_idxs is None:\n col_idxs = np.arange(iou_thrs.size)\n row_header = [''] + iou_thrs[col_idxs].tolist()\n table_data = [row_header]\n for i, num in enumerate(proposal_nums[row_idxs]):\n row = [f'{val:.3f}' for val in recalls[row_idxs[i], col_idxs].tolist()]\n row.insert(0, num)\n table_data.append(row)\n table = AsciiTable(table_data)\n print_log('\\n' + table.table, logger=logger)\n\n\ndef plot_num_recall(recalls, proposal_nums):\n \"\"\"Plot Proposal_num-Recalls curve.\n\n Args:\n recalls(ndarray or list): shape (k,)\n proposal_nums(ndarray or list): same shape as `recalls`\n \"\"\"\n if isinstance(proposal_nums, np.ndarray):\n _proposal_nums = proposal_nums.tolist()\n else:\n _proposal_nums = proposal_nums\n if isinstance(recalls, np.ndarray):\n _recalls = recalls.tolist()\n else:\n _recalls = recalls\n\n import matplotlib.pyplot as plt\n f = plt.figure()\n plt.plot([0] + _proposal_nums, [0] + _recalls)\n plt.xlabel('Proposal num')\n plt.ylabel('Recall')\n plt.axis([0, proposal_nums.max(), 0, 1])\n f.show()\n\n\ndef plot_iou_recall(recalls, iou_thrs):\n \"\"\"Plot IoU-Recalls curve.\n\n Args:\n recalls(ndarray or list): shape (k,)\n iou_thrs(ndarray or list): same shape as `recalls`\n \"\"\"\n if isinstance(iou_thrs, np.ndarray):\n _iou_thrs = iou_thrs.tolist()\n else:\n _iou_thrs = iou_thrs\n if isinstance(recalls, np.ndarray):\n _recalls = recalls.tolist()\n else:\n _recalls = recalls\n\n import matplotlib.pyplot as plt\n f = plt.figure()\n plt.plot(_iou_thrs + [1.0], _recalls + [0.])\n plt.xlabel('IoU')\n plt.ylabel('Recall')\n plt.axis([iou_thrs.min(), 1, 0, 1])\n f.show()\n", "repo_name": "open-mmlab/mmdetection", "sub_path": "mmdet/evaluation/functional/recall.py", "file_name": "recall.py", "file_ext": "py", "file_size_in_byte": 6800, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 26167, "dataset": "github-code", "pt": "20", "api": [{"api_name": "numpy.zeros", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 15, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.fliplr", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 36, "usage_type": "call"}, {"api_name": "collections.abc.Sequence", "line_number": 45, "usage_type": "argument"}, {"api_name": "numpy.array", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 53, "usage_type": "call"}, {"api_name": "collections.abc.Sequence", "line_number": 54, "usage_type": "argument"}, {"api_name": "numpy.array", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 103, "usage_type": "attribute"}, {"api_name": "bbox_overlaps.bbox_overlaps", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 135, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 140, "usage_type": "call"}, {"api_name": "terminaltables.AsciiTable", "line_number": 147, "usage_type": "call"}, {"api_name": "mmengine.logging.print_log", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 158, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 162, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 168, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 168, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 169, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 169, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 170, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 170, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 171, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 171, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 172, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 172, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 183, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 187, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 193, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 193, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 194, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 194, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 195, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 195, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 196, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 196, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 197, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 197, "usage_type": "name"}]} +{"seq_id": "29305452255", "text": "from django.urls import path\nfrom .views import dashboard, profile_list, profile, notification\n\napp_name = \"prime\"\n\nurlpatterns = [\n path(\"\", dashboard, name=\"dashboard\"),\n path(\"profile_list/\", profile_list, name=\"profile_list\"),\n path(\"profile/\", profile, name=\"profile\"),\n path(\"notification\", notification, name=\"notification\"),\n]", "repo_name": "ikechukwuoha/primesocialapp", "sub_path": "prime/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 354, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "views.dashboard", "line_number": 7, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "views.profile_list", "line_number": 8, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "views.profile", "line_number": 9, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "views.notification", "line_number": 10, "usage_type": "argument"}]} +{"seq_id": "41196112900", "text": "import textwrap\nfrom typing import Optional\n\nfrom rich.align import Align, VerticalCenter\nfrom rich.console import Console, ConsoleOptions, RenderableType, RenderResult\nfrom rich.panel import Panel\nfrom rich.style import StyleType\nfrom textual import events\nfrom textual.reactive import Reactive\nfrom textual.widget import Widget\nfrom textual.widgets import ButtonPressed\n\n\nclass WelcomeScreen(Widget):\n\n def render(self) -> Panel:\n return Panel(\n Align.center(\n VerticalCenter(\n textwrap.dedent(\n r\"\"\"\n [blue]██████[/blue]\n [green]ooooooooo. ooooooooooooo ooooo ooo ooooo[/green] [blue]█▄██████[/blue]\n [green]`888 `Y88. 8' 888 `8 `888' `8' `888'[/green] [blue]█████[/blue] [yellow]██[/yellow]\n [green]888 .d88' oooo ooo 888 888 8 888[/green] [blue]█████████[/blue] [yellow]███[/yellow]\n [green]888ooo88P' `88. .8' 888 888 8 888[/green] [blue]█████[/blue] [yellow]█████[/yellow]\n [green]888 `88..8' 888 888 8 888[/green] [blue]███[/blue] [yellow]█████████[/yellow]\n [green]888 `888' 888 `88. .8' 888[/green] [blue]██[/blue] [yellow]█████[/yellow]\n [green]o888o .8' o888o `YbodP' o888o[/green] [yellow]██████▀█[/yellow]\n [green].o..P'[/green] [yellow]██████[/yellow]\n [green]`Y8P'[/green]\n \"\"\" # noqa: E501\n )\n )\n ),\n title=\"Welcome to PyTUI\",\n )\n\n\nclass ContinueButtonRenderable:\n def __init__(self, label: RenderableType, style: StyleType = \"\") -> None:\n self.label = label\n self.style = style\n\n def __rich_console__(\n self, console: Console, options: ConsoleOptions\n ) -> RenderResult:\n width = options.max_width\n height = 3\n\n yield Align.center(\n self.label, vertical=\"middle\", style=self.style, width=width, height=height\n )\n\n\nclass ContinueButton(Widget):\n def __init__(\n self,\n label: RenderableType,\n name: Optional[str] = None,\n style: StyleType = \"white on dark_blue\",\n ):\n super().__init__(name=name)\n self.name = name or str(label)\n self.button_style = style\n\n self.label = label\n\n label: Reactive[RenderableType] = Reactive(\"\")\n\n def render(self) -> RenderableType:\n return ContinueButtonRenderable(self.label, style=self.button_style)\n\n async def on_click(self, event: events.Click) -> None:\n await self.emit(ButtonPressed(self))\n", "repo_name": "doublevcodes/pythings", "sub_path": "pythings/widgets/welcome.py", "file_name": "welcome.py", "file_ext": "py", "file_size_in_byte": 3216, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "textual.widget.Widget", "line_number": 14, "usage_type": "name"}, {"api_name": "rich.panel.Panel", "line_number": 17, "usage_type": "call"}, {"api_name": "rich.align.Align.center", "line_number": 18, "usage_type": "call"}, {"api_name": "rich.align.Align", "line_number": 18, "usage_type": "name"}, {"api_name": "rich.align.VerticalCenter", "line_number": 19, "usage_type": "call"}, {"api_name": "textwrap.dedent", "line_number": 20, "usage_type": "call"}, {"api_name": "rich.panel.Panel", "line_number": 16, "usage_type": "name"}, {"api_name": "rich.console.RenderableType", "line_number": 41, "usage_type": "name"}, {"api_name": "rich.style.StyleType", "line_number": 41, "usage_type": "name"}, {"api_name": "rich.console.Console", "line_number": 46, "usage_type": "name"}, {"api_name": "rich.console.ConsoleOptions", "line_number": 46, "usage_type": "name"}, {"api_name": "rich.align.Align.center", "line_number": 51, "usage_type": "call"}, {"api_name": "rich.align.Align", "line_number": 51, "usage_type": "name"}, {"api_name": "rich.console.RenderResult", "line_number": 47, "usage_type": "name"}, {"api_name": "textual.widget.Widget", "line_number": 56, "usage_type": "name"}, {"api_name": "rich.console.RenderableType", "line_number": 59, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 60, "usage_type": "name"}, {"api_name": "rich.style.StyleType", "line_number": 61, "usage_type": "name"}, {"api_name": "textual.reactive.Reactive", "line_number": 69, "usage_type": "name"}, {"api_name": "rich.console.RenderableType", "line_number": 69, "usage_type": "name"}, {"api_name": "rich.console.RenderableType", "line_number": 71, "usage_type": "name"}, {"api_name": "textual.events.Click", "line_number": 74, "usage_type": "attribute"}, {"api_name": "textual.events", "line_number": 74, "usage_type": "name"}, {"api_name": "textual.widgets.ButtonPressed", "line_number": 75, "usage_type": "call"}]} +{"seq_id": "17797820577", "text": "# -*- encoding: utf-8 -*-\n'''\n--------------------------------------------------------------------\n@File : get_competition_resution.py\n@Time : 2021/09/28 14:27:24\n@Author : kuangxiong \n@Version : 1.0\n@Email : kuangxiong1993@163.com\n--------------------------------------------------------------------\n'''\n\nimport tensorflow as tf \nimport numpy as np \nimport time \nimport os\nimport re \nimport pandas as pd \nfrom tensorflow import keras\nfrom transformers import BertModel, BertTokenizer\nfrom role_classification.bert_model.data_postprocess import data_postprocess\nfrom role_classification.bert_model.models.bert_avgpool_mse import InitBertConfig, bert_model\nfrom role_classification.load_data import load_init_data\nfrom config import GlobalData\n\nlogger = InitBertConfig.cust_logger\n\nif __name__=='__main__':\n # 测试用例\n start_time = time.time()\n \n train_data, test_data = load_init_data(GlobalData)\n # 加载模型\n tokenizer = BertTokenizer.from_pretrained(InitBertConfig.bert_path)\n model = bert_model(InitBertConfig)\n ckpt = tf.train.Checkpoint(model=model)\n\n # .expect_partial()去掉不需要的信息,比如优化器参数等信息\n ckpt.restore(tf.train.latest_checkpoint(InitBertConfig.save_model)).expect_partial()\n print(model.summary())\n\n id_list, emotion_list = [], []\n for i in range(len(test_data)):\n id_list.append(test_data[i][0])\n try:\n tmp_str = \"\".join(test_data[i][1])\n token_output = tokenizer(\n tmp_str, \n padding='max_length', \n truncation=True, \n max_length=InitBertConfig.max_len\n )\n indices, segments = token_output['input_ids'], token_output['token_type_ids']\n mask_token = token_output['attention_mask']\n res = model.predict([np.array([indices]), np.array([segments]), np.array([mask_token])])\n res_post = data_postprocess(res[0])\n \n emotion_list.append(\",\".join(list(map(str, res_post))))\n except:\n emotion_list.append(\"0,0,0,0,0\")\n print(id_list[:5])\n print(emotion_list[:5])\n ans = pd.DataFrame({\"id\":id_list, \"emotion\":emotion_list})\n ans.to_csv(\"test/data_out/ans_v2.txt\", index=False, sep='\\t')", "repo_name": "kuangxiong/RoleClassification", "sub_path": "test/get_competition_resution.py", "file_name": "get_competition_resution.py", "file_ext": "py", "file_size_in_byte": 2313, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "role_classification.bert_model.models.bert_avgpool_mse.InitBertConfig.cust_logger", "line_number": 25, "usage_type": "attribute"}, {"api_name": "role_classification.bert_model.models.bert_avgpool_mse.InitBertConfig", "line_number": 25, "usage_type": "name"}, {"api_name": "time.time", "line_number": 29, "usage_type": "call"}, {"api_name": "role_classification.load_data.load_init_data", "line_number": 31, "usage_type": "call"}, {"api_name": "config.GlobalData", "line_number": 31, "usage_type": "argument"}, {"api_name": "transformers.BertTokenizer.from_pretrained", "line_number": 33, "usage_type": "call"}, {"api_name": "transformers.BertTokenizer", "line_number": 33, "usage_type": "name"}, {"api_name": "role_classification.bert_model.models.bert_avgpool_mse.InitBertConfig.bert_path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "role_classification.bert_model.models.bert_avgpool_mse.InitBertConfig", "line_number": 33, "usage_type": "name"}, {"api_name": "role_classification.bert_model.models.bert_avgpool_mse.bert_model", "line_number": 34, "usage_type": "call"}, {"api_name": "role_classification.bert_model.models.bert_avgpool_mse.InitBertConfig", "line_number": 34, "usage_type": "argument"}, {"api_name": "tensorflow.train.Checkpoint", "line_number": 35, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 35, "usage_type": "attribute"}, {"api_name": "tensorflow.train.latest_checkpoint", "line_number": 38, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 38, "usage_type": "attribute"}, {"api_name": "role_classification.bert_model.models.bert_avgpool_mse.InitBertConfig.save_model", "line_number": 38, "usage_type": "attribute"}, {"api_name": "role_classification.bert_model.models.bert_avgpool_mse.InitBertConfig", "line_number": 38, "usage_type": "name"}, {"api_name": "role_classification.bert_model.models.bert_avgpool_mse.InitBertConfig.max_len", "line_number": 50, "usage_type": "attribute"}, {"api_name": "role_classification.bert_model.models.bert_avgpool_mse.InitBertConfig", "line_number": 50, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 54, "usage_type": "call"}, {"api_name": "role_classification.bert_model.data_postprocess.data_postprocess", "line_number": 55, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 62, "usage_type": "call"}]} +{"seq_id": "35059571985", "text": "\"\"\" \n@author: Zhangkai\n@file: kNN5.py\n@Date: 2017/9/7 8:44\n\"\"\"\nfrom numpy import *\nimport matplotlib.pyplot as plt\ndef file2matrix(filename):\n fr = open(filename)\n arrayOfLines = fr.readlines()\n numberOfLines = len(arrayOfLines)\n returnMat = zeros((numberOfLines, 3))\n index = 0\n classLabelVector = []\n int = {'didntLike':1, 'smallDoses':2, 'largeDoses':3}\n for line in arrayOfLines:\n line = line.strip()\n listFromline = line.split('\\t')\n returnMat[index,:] = listFromline[0:3]\n classLabelVector.append(int[listFromline[-1]])\n index += 1\n return returnMat,classLabelVector\ndatingDataMat,datingLabels = file2matrix(\"datingTestSet.txt\")\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.scatter(datingDataMat[:,0], datingDataMat[:,1], 15.0*array(datingLabels), 15.0*array(datingLabels))\nplt.show()", "repo_name": "zk1023/MachineLearnPractice", "sub_path": "knn/kNN5.py", "file_name": "kNN5.py", "file_ext": "py", "file_size_in_byte": 856, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "matplotlib.pyplot.figure", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}]} +{"seq_id": "41239881955", "text": "import re\nimport datetime\nimport locale\nimport random\nimport string\nimport pycountry\n\nfrom flask import request\nfrom config.errors import InputValidationError\n\n\ndef validate_country_name(country_name):\n \"\"\"\n Validates the given country name using pycountry lib\n :param country_name: given country name\n :return: None if validation passes\n \"\"\"\n try:\n pycountry.countries.lookup(country_name)\n except LookupError as e:\n raise InputValidationError(message=\"Invalid country name specified\",\n payload={'country': country_name})\n\n\ndef format_url(uri):\n \"\"\"returns the full url\"\"\"\n return f'{request.root_url}{uri}'\n\n\ndef generate_team_name():\n \"\"\"\n Generates a random string\n :return: str\n \"\"\"\n return ''.join(\n random.choices(string.ascii_uppercase +\n string.digits, k=7)\n )\n\n\ndef adjust_market_value(ask_price):\n \"\"\"\n Increase player's market value by a random factor in range (10, 100)\n :param ask_price: current ask_price\n :return: updated ask_price\n \"\"\"\n percent_increase = random.randint(10, 100)\n increment = (percent_increase / 100) * ask_price\n return ask_price + increment\n\n\ndef currency_formatter(num):\n \"\"\"\n Format currency as USD\n :param num: int\n :return: $ amount\n \"\"\"\n locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')\n return locale.currency(num, grouping=True)\n\n\ndef player_age_generator():\n \"\"\"Generate random age in range (18, 40)\"\"\"\n return random.randint(18, 40)\n\n\ndef format_error(e):\n \"\"\"\n Format API error response\n :param e: exception object\n :return: JSON\n \"\"\"\n if \"password\" in e.payload:\n del e.payload[\"password\"]\n data = {\n \"success\": False,\n \"timestamp\": datetime.datetime.utcnow(),\n \"request_uri\": request.url,\n \"request_payload\": e.payload,\n \"error\": {\n \"name\": e.name,\n \"response code\": e.status_code,\n \"description\": e.message,\n }\n }\n return data, e.status_code\n\n\ndef format_generic_error(e):\n \"\"\"\n Format API error response\n :param e: exception object\n :return: JSON\n \"\"\"\n data = {\n \"success\": False,\n \"timestamp\": datetime.datetime.utcnow(),\n \"request_uri\": request.url,\n \"error\": {\n \"description\": str(e),\n \"name\": e.__class__.__name__\n }\n }\n return data, 500\n\n\ndef format_response(data, code):\n \"\"\"\n Format success response\n :param data: json result\n :param code: response code\n :return: JSON\n \"\"\"\n\n data = {\n \"success\": True,\n \"timestamp\": datetime.datetime.utcnow(),\n \"request_uri\": request.url,\n \"data\": data,\n \"status_code\": code,\n }\n\n return data\n\n\ndef is_valid_email(email_id):\n \"\"\"\n Validate if the provided email is a valid email\n :param email_id: email ID\n :return: boolean\n \"\"\"\n regex = r'\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b'\n if not re.fullmatch(regex, email_id):\n raise InputValidationError(message=\"Invalid email ID\",\n payload={\"username\": email_id})\n", "repo_name": "Pushp1403/soccer-manager-python-flask", "sub_path": "common/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 3198, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pycountry.countries.lookup", "line_number": 19, "usage_type": "call"}, {"api_name": "pycountry.countries", "line_number": 19, "usage_type": "attribute"}, {"api_name": "config.errors.InputValidationError", "line_number": 21, "usage_type": "call"}, {"api_name": "flask.request.root_url", "line_number": 27, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 27, "usage_type": "name"}, {"api_name": "random.choices", "line_number": 36, "usage_type": "call"}, {"api_name": "string.ascii_uppercase", "line_number": 36, "usage_type": "attribute"}, {"api_name": "string.digits", "line_number": 37, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 47, "usage_type": "call"}, {"api_name": "locale.setlocale", "line_number": 58, "usage_type": "call"}, {"api_name": "locale.LC_ALL", "line_number": 58, "usage_type": "attribute"}, {"api_name": "locale.currency", "line_number": 59, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 64, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 77, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 77, "usage_type": "attribute"}, {"api_name": "flask.request.url", "line_number": 78, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 78, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 97, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 97, "usage_type": "attribute"}, {"api_name": "flask.request.url", "line_number": 98, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 98, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 117, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 117, "usage_type": "attribute"}, {"api_name": "flask.request.url", "line_number": 118, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 118, "usage_type": "name"}, {"api_name": "re.fullmatch", "line_number": 133, "usage_type": "call"}, {"api_name": "config.errors.InputValidationError", "line_number": 134, "usage_type": "call"}]} +{"seq_id": "5956090857", "text": "import os\nimport re\nimport codecs\n\nfrom setuptools import setup\nfrom setuptools import find_packages\n\n##########################################################################\n## Package Information\n##########################################################################\n\n## Basic information\nNAME = \"baleen\"\nDESCRIPTION = \"An automated ingestion service for blogs to construct a corpus for NLP research.\"\nAUTHOR = \"Benjamin Bengfort\"\nEMAIL = \"benjamin@bengfort.com\"\nLICENSE = \"MIT\"\nREPOSITORY = \"https://github.com/bbengfort/baleen\"\nPACKAGE = \"baleen\"\n\n## Define the keywords\nKEYWORDS = ('nlp', 'baleen', 'ingestion', 'blogs', 'rss')\n\n## Define the classifiers\n## See https://pypi.python.org/pypi?%3Aaction=list_classifiers\nCLASSIFIERS = (\n 'Development Status :: 4 - Beta',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Software Development',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Topic :: Utilities',\n)\n\n## Important Paths\nPROJECT = os.path.abspath(os.path.dirname(__file__))\nREQUIRE_PATH = \"requirements.txt\"\nVERSION_PATH = os.path.join(PACKAGE, \"version.py\")\nPKG_DESCRIBE = \"DESCRIPTION.txt\"\n\n## Directories to ignore in find_packages\nEXCLUDES = (\n \"tests\", \"bin\", \"docs\", \"fixtures\", \"register\", \"notebooks\",\n)\n\n##########################################################################\n## Helper Functions\n##########################################################################\n\ndef read(*parts):\n \"\"\"\n Assume UTF-8 encoding and return the contents of the file located at the\n absolute path from the REPOSITORY joined with *parts.\n \"\"\"\n with codecs.open(os.path.join(PROJECT, *parts), 'rb', 'utf-8') as f:\n return f.read()\n\n\ndef get_version(path=VERSION_PATH):\n \"\"\"\n Reads the __init__.py defined in the VERSION_PATH to find the get_version\n function, and executes it to ensure that it is loaded correctly.\n \"\"\"\n namespace = {}\n exec(read(path), namespace)\n return namespace['get_version']()\n\n\ndef get_requires(path=REQUIRE_PATH):\n \"\"\"\n Yields a generator of requirements as defined by the REQUIRE_PATH which\n should point to a requirements.txt output by `pip freeze`.\n \"\"\"\n for line in read(path).splitlines():\n line = line.strip()\n if line and not line.startswith('#'):\n yield line\n\n##########################################################################\n## Define the configuration\n##########################################################################\n\nconfig = {\n \"name\": NAME,\n \"version\": get_version(),\n \"description\": DESCRIPTION,\n \"long_description\": read(PKG_DESCRIBE),\n \"license\": LICENSE,\n \"author\": AUTHOR,\n \"author_email\": EMAIL,\n \"maintainer\": AUTHOR,\n \"maintainer_email\": EMAIL,\n \"url\": REPOSITORY,\n \"download_url\": \"{}/tarball/v{}\".format(REPOSITORY, get_version()),\n \"packages\": find_packages(where=PROJECT, exclude=EXCLUDES),\n \"install_requires\": list(get_requires()),\n \"classifiers\": CLASSIFIERS,\n \"keywords\": KEYWORDS,\n \"zip_safe\": False,\n \"scripts\": ['bin/baleen'],\n}\n\n##########################################################################\n## Run setup script\n##########################################################################\n\nif __name__ == '__main__':\n setup(**config)\n", "repo_name": "DistrictDataLabs/baleen", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 3596, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 84, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.path.abspath", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path", "line_number": 43, "usage_type": "attribute"}, {"api_name": "codecs.open", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path", "line_number": 60, "usage_type": "attribute"}, {"api_name": "setuptools.find_packages", "line_number": 100, "usage_type": "call"}, {"api_name": "setuptools.setup", "line_number": 113, "usage_type": "call"}]} +{"seq_id": "28940005015", "text": "def LSTM_model(lookbehind, train_ratio, df):\n #importing required libraries\n from sklearn.preprocessing import MinMaxScaler\n from tensorflow.keras.models import Sequential\n from tensorflow.keras.layers import Dense, Dropout, LSTM\n import pandas as pd\n import numpy as np\n import matplotlib.pyplot as plt\n\n data = df.sort_index(ascending=True, axis=0)\n new_data = pd.DataFrame(index=range(0,len(df)),columns=['Date', 'Close'])\n for i in range(0,len(data)):\n new_data['Date'][i] = data['Date'][i]\n new_data['Close'][i] = data['Close'][i]\n\n #previous days to use for prediction\n #lookbehind = 60\n #train_ratio = .9\n num_samples = len(df)\n train_samples = int(train_ratio * num_samples)\n\n #setting index\n new_data.index = new_data.Date\n new_data.drop('Date', axis=1, inplace=True)\n\n #creating train and test sets\n dataset = new_data.values\n\n train = dataset[0:train_samples,:]\n valid = dataset[train_samples:,:]\n\n #converting dataset into x_train and y_train\n scaler = MinMaxScaler(feature_range=(0, 1))\n scaled_data = scaler.fit_transform(dataset)\n\n x_train, y_train = [], []\n for i in range(lookbehind,len(train)):\n x_train.append(scaled_data[i-lookbehind:i,0])\n y_train.append(scaled_data[i,0])\n x_train, y_train = np.array(x_train), np.array(y_train)\n\n x_train = np.reshape(x_train, (x_train.shape[0],x_train.shape[1],1))\n\n # create and fit the LSTM network\n model4 = Sequential()\n model4.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1],1)))\n model4.add(LSTM(units=50))\n model4.add(Dense(1))\n\n model4.compile(loss='mean_squared_error', optimizer='adam')\n model4.fit(x_train, y_train, epochs=1, batch_size=1, verbose=2)\n\n #predicting 246 values, using past 60 from the train data\n inputs = new_data[len(new_data) - len(valid) - lookbehind:].values\n inputs = inputs.reshape(-1,1)\n inputs = scaler.transform(inputs)\n\n X_test = []\n for i in range(lookbehind,inputs.shape[0]):\n X_test.append(inputs[i-lookbehind:i,0])\n X_test = np.array(X_test)\n\n X_test = np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1))\n closing_price = model4.predict(X_test)\n closing_price = scaler.inverse_transform(closing_price)\n\n rms=np.sqrt(np.mean(np.power((valid-closing_price),2)))\n\n train = new_data[:train_samples]\n valid = new_data[train_samples:]\n valid['Predictions'] = closing_price\n\n #plt.plot(train['Close'])\n plt.figure(figsize=(19,8))\n plt.plot(valid[['Close','Predictions']])\n plt.legend(['Actual','Predicted'])\n plt.title(str(lookbehind) + ' Day Interval, ' + ('{0:.0%}'.format(train_ratio)) + ' Train Split')\n\n plt.figure(figsize=(19,8))\n plt.plot(valid[['Close','Predictions']].tail(21))\n plt.legend(['Actual','Predicted'])\n plt.title(str(lookbehind) + ' Day Interval, ' + ('{0:.0%}'.format(train_ratio)) + ' Train Split')\n \n plt.figure(figsize=(19,8))\n plt.plot(valid['Close'].tail(21)-valid['Predictions'].tail(21))\n plt.legend(['Actual - Predicted'])\n plt.title('Residual: ' + str(lookbehind) + ' Day Interval, ' + ('{0:.0%}'.format(train_ratio)) + ' Train Split')", "repo_name": "ericwaxler/CCC", "sub_path": "Notebooks/.ipynb_checkpoints/LSTM_func-checkpoint.py", "file_name": "LSTM_func-checkpoint.py", "file_ext": "py", "file_size_in_byte": 3213, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pandas.DataFrame", "line_number": 11, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.MinMaxScaler", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 42, "usage_type": "call"}, {"api_name": "tensorflow.keras.models.Sequential", "line_number": 45, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.LSTM", "line_number": 46, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.LSTM", "line_number": 47, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 77, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 77, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 80, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 81, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 81, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 84, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 85, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 86, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 87, "usage_type": "name"}]} +{"seq_id": "14178874695", "text": "import pytest\nimport numpy as np\n\nimport passagerank.pruning.head_pruning as head_pruning\n\ndef mock_attention(head_mask):\n \"\"\" fake out some attention data for test purposes aranged such that the\n smallest index head in the largest indexed layer recieves the lowest scores\n HF models return attention scores as a tuple of B x nH x S x S matrices\n \"\"\"\n batch_size = 4\n context_size = 4\n n_layers = head_mask.shape[0]\n attentions = []\n totelems = 0\n for layer_i in range(n_layers):\n n_active_heads = np.sum(head_mask[layer_i])\n nelems = batch_size * n_active_heads * context_size * context_size\n totelems += nelems\n att = np.arange(nelems, dtype=np.float32) + nelems * (n_layers - layer_i)**2\n att = np.reshape(att, (batch_size, n_active_heads, context_size, context_size))\n attentions.append(att)\n \n return tuple(attentions)\n\n# mocks 2 layers of 4 heads each, with 2x2 attention for a context window of 2\nparams = [\n ([[1, 1, 1, 1], [1, 1, 1, 1]]),\n ([[1, 1, 1, 1], [1, 1, 1, 0]]),\n ([[1, 1, 1, 1], [0, 1, 1, 1]]),\n ([[0, 1, 1, 1], [0, 1, 1, 1]]),\n ([[0, 0, 0, 1], [0, 0, 0, 1]]),\n ([[0, 1, 0, 0], [0, 0, 1, 0]]),\n]\n@pytest.mark.parametrize(\"head_mask\", params)\ndef test_accumulate_scores(head_mask):\n head_mask = np.asarray(head_mask, dtype=np.int32)\n head_scores = np.zeros_like(head_mask, dtype=np.float32)\n orig_scores = np.copy(head_scores)\n attentions = mock_attention(head_mask)\n \n head_pruning.accumulate_scores(head_mask, head_scores, attentions)\n\n for li in range(head_mask.shape[0]):\n prev_score = 0\n for hi in range(head_mask.shape[1]):\n\n # Scores always increase for unmasked heads, never for masked\n if head_mask[li, hi] == 1:\n assert head_scores[li, hi] > orig_scores[li, hi]\n else:\n assert head_scores[li, hi] == orig_scores[li, hi]\n \n # Scores are aligned to the proper head when there were masked heads\n # among them, the fixture creates them in increasing order per layer\n if head_mask[li, hi] == 1:\n assert head_scores[li, hi] > prev_score\n prev_score = head_scores[li, hi]\n\n\n\n", "repo_name": "Kyle-Lewis/cheap-ir", "sub_path": "passagerank/tests/test_head_pruning.py", "file_name": "test_head_pruning.py", "file_ext": "py", "file_size_in_byte": 2272, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.sum", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 20, "usage_type": "attribute"}, {"api_name": "numpy.reshape", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 37, "usage_type": "attribute"}, {"api_name": "numpy.zeros_like", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 38, "usage_type": "attribute"}, {"api_name": "numpy.copy", "line_number": 39, "usage_type": "call"}, {"api_name": "passagerank.pruning.head_pruning.accumulate_scores", "line_number": 42, "usage_type": "call"}, {"api_name": "passagerank.pruning.head_pruning", "line_number": 42, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 35, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 35, "usage_type": "attribute"}]} +{"seq_id": "39705398469", "text": "# make a nice plot of SMR spectrum and label some lines and compare with solar spectrum (same temps)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nsmrdata = np.genfromtxt('../misc_data/bd60583.txt')\nsolardata = np.genfromtxt('../misc_data/objs_ap5.txt')\n\n\nsmr_wave = smrdata[1234:1341, 0]\nsmr_flux = smrdata[1234:1341, 1]\n\nsolar_wave = solardata[1234:1341, 0]\nsolar_flux = solardata[1234:1341, 1]\nsolar_wave = solar_wave + 0.42\nsolar_flux = solar_flux - 0.009\n\nfig=plt.figure(figsize=(9,4.5))\n\nplt.plot(solar_wave, solar_flux, linewidth=3.0, color='RoyalBlue', label='Sun, T=5770')\nplt.plot(smr_wave, smr_flux,linewidth=3.0, color='FireBrick', label='BD+60 583, T=5817')\n\nplt.xticks(np.arange(6704, 6727.5, 3))\nplt.yticks(np.arange(.70, 1.05, 0.05))\n\n\nplt.xlim((6702.7, 6723.1))\nplt.ylim((0.67, 1.03))\nplt.tick_params(labelsize=14)\n\nplt.ylabel('Normalized Flux', fontsize=14)\nplt.xlabel(r'Wavelength ($\\mathrm{\\AA}$)', fontsize=14)\n\n# plot various elements\nelmwidth = 1.75\n\nplt.text(6703.1, 0.85, 'Fe I', fontsize=12)\nplt.vlines(6703.6, 0.87, 0.90, linewidth=elmwidth)\n\nplt.text(6704.6, 0.82, 'Fe I', fontsize=12)\nplt.vlines(6705.1, 0.84, 0.87, linewidth=elmwidth)\n\nplt.text(6707.1, 0.90, 'Fe I', fontsize=12)\nplt.vlines(6707.6, 0.92, 0.95, linewidth=elmwidth)\n\nplt.text(6709.8, 0.88, 'Fe I', fontsize=12)\nplt.vlines(6710.3, 0.90, 0.93, linewidth=elmwidth)\n\nplt.text(6712.6, 0.85, 'Fe I', fontsize=12)\nplt.vlines(6713.1, 0.87, 0.90, linewidth=elmwidth)\n\nplt.text(6713.3, 0.87, 'Fe I', fontsize=12)\nplt.vlines(6713.8, 0.89, 0.92, linewidth=elmwidth)\n\nplt.text(6714.9, 0.85, 'Fe I', fontsize=12)\nplt.vlines(6715.4, 0.87, 0.90, linewidth=elmwidth)\n\nplt.text(6715.8, 0.88, 'Fe I', fontsize=12)\nplt.vlines(6716.3, 0.90, 0.93, linewidth=elmwidth)\n\nplt.text(6717.1, 0.68, 'Ca I', fontsize=12)\nplt.vlines(6717.6, 0.70, 0.73, linewidth=elmwidth)\n\nplt.text(6719.3, 0.87, 'Si I', fontsize=12)\nplt.vlines(6719.7, 0.89, 0.92, linewidth=elmwidth)\n\nplt.text(6721.4, 0.82, 'Si I', fontsize=12)\nplt.vlines(6721.8, 0.84, 0.87, linewidth=elmwidth)\n\n# work on the legend\nplt.legend(loc=3, prop={'size': 12}, frameon=False)\n\nplt.savefig('solar_smr_compare', format='pdf',bbox_inches='tight')\n\nplt.show()", "repo_name": "dleebrown/misc_plots", "sub_path": "smr_solar_compare.py", "file_name": "smr_solar_compare.py", "file_ext": "py", "file_size_in_byte": 2189, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "numpy.genfromtxt", "line_number": 6, "usage_type": "call"}, {"api_name": "numpy.genfromtxt", "line_number": 7, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tick_params", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.vlines", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.vlines", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.vlines", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.vlines", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.vlines", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.vlines", "line_number": 53, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 53, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.vlines", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 56, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 58, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.vlines", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.vlines", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.vlines", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.vlines", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}]} +{"seq_id": "23367540879", "text": "print(\"# Import Libraries\")\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\"\nimport sys\nimport time\nfrom skimage.metrics import structural_similarity as sk_ssim\nfrom utils.prettytable import PrettyTable\nimport csv\nimport numpy as np\nfrom tqdm import tqdm\nfrom PIL import Image\nimport tensorflow.compat.v1 as tf\nos.environ['TF_CPP_MIN_LOG_LEVEL']='3'\ntf.logging.set_verbosity(tf.logging.ERROR)\ntf.disable_v2_behavior()\nfrom tensorflow.python.platform import gfile\nimport cv2\n\n\n# clear old graphs that might be still stored in e.g. ipython console\ntf.reset_default_graph()\ntf.keras.backend.clear_session()\n\n\n\ndef restoreGraphFromPB(sess, graphFile):\n '''\n Restore the \"interface\" variables of the graph to perform inference.\n '''\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(graphFile.read())\n sess.graph.as_default()\n tf.import_graph_def(graph_def,\n input_map=None,\n return_elements=None,\n name=\"\",\n op_dict=None,\n producer_op_list=None)\n return getGraphVariables()\n\n\ndef getGraphVariables(): \n '''\n Get the input and output nodes of the model.\n '''\n graph = tf.get_default_graph()\n x = graph.get_tensor_by_name(\"input_1:0\") \n y_fake = graph.get_tensor_by_name(\"output_0:0\")\n \n return x, y_fake\n\n\n# ============================================================================= #\nprint(\"\\n# Define Parameters\")\n# data directory\nDATA_DIR = \"../_DATASETS_/occMapDataset_/train/_scenes/\"\n\n# for network verification\npossibleInputNames = [\"r_1\",\"r_5\",\"r_10\",\"r_20\",\"l\",\"d\",\"c\",\"lr20\",\"dr20\",\"s\",\"irm_1\",\"irm_20\"]\nMODEL_DIR = \"./models/exp_network_tuning/\"\nMODEL_NAMES = [MODEL_NAME for MODEL_NAME in os.listdir(MODEL_DIR) if MODEL_NAME.endswith(\".pb\")]\n# MODEL_NAMES = [\"dirNet_ilmMapPatchDisc_r_1__20201223_215714_ckpt_180.pb\",\n# \"shiftNet_ilmMapPatchDisc_r_1__20201223_215050_ckpt_198.pb\",\n# \"softNet_ilmMapPatchDisc_r_1__20201223_215415_ckpt_688.pb\"]\n# MODEL_NAMES = [\"occNet_075_ilmMapPatch_r_1__20201203_095051_ckpt_73.pb\",\n# \"occNet_100_ilmMapPatch_r_1__20201203_094530_ckpt_348.pb\"]\n# MODEL_NAMES = [\"_irm_1__\", \"_irm_20__\"]\n# MODEL_NAMES.sort()\n# MODEL_NAMES = MODEL_NAMES[7:]\n\n# MODEL_NAMES = [\"irm_1\"]\n\nfor MODEL_NAME in MODEL_NAMES:\n # retrieve input name from ckpt name\n inputName = \"\"\n for possibleInputName in possibleInputNames:\n if \"_\"+possibleInputName+\"__\" in MODEL_NAME:\n inputName = possibleInputName\n if inputName == \"\":\n inputName = MODEL_NAME\n\n print(\"\\n# Compute Metrics for \", MODEL_NAME)\n # get all directory names of scene data\n sceneNames = [sceneName for sceneName in os.listdir(DATA_DIR) if sceneName.startswith('scene')]\n sceneNames.sort()\n\n # store mean inference time on gpu and cpu\n mInfTime_gpu = -1\n mInfTime_cpu = -1\n\n # clear old graphs that might be still stored in e.g. ipython console\n tf.reset_default_graph()\n tf.keras.backend.clear_session()\n\n with tf.Session() as sess:\n if MODEL_NAME[-3:] == \".pb\":\n graphFile = gfile.FastGFile(MODEL_DIR + MODEL_NAME, 'rb')\n x, y_fake = restoreGraphFromPB(sess, graphFile)\n\n for iScene in tqdm(range(int(len(sceneNames)))):\n # for iScene in [0]:\n # get current scene\n sceneName = sceneNames[iScene]\n\n # loop thru all imgs in the scene and compute the metric\n xFiles = os.listdir(DATA_DIR + sceneName + \"/\" + inputName + \"/\")\n xFiles = [xFile for xFile in xFiles if xFile.startswith(inputName+'__')]\n xFiles.sort()\n\n # create folder to store results to\n curr_stor_path = os.path.join(DATA_DIR, sceneName, MODEL_NAME.split(\"__\")[0])\n os.makedirs(curr_stor_path, exist_ok=True)\n\n for iSample in range(len(xFiles)):\n x_ = np.array(Image.open(DATA_DIR + sceneName + \"/\"+inputName+\"/\" + xFiles[iSample]))\n\n # trafo inputs from [0,255] -> [0,1]\n if len(x_.shape) == 2:\n x_ = x_[np.newaxis, :, :, np.newaxis]/255\n else:\n x_ = x_[np.newaxis, :, :, :]/255\n\n # perform inference\n y_est = sess.run(y_fake, feed_dict={x: x_})[0, ...]\n\n # store the result\n y_est = Image.fromarray((y_est*255).astype(np.uint8))\n y_est.save(os.path.join(curr_stor_path, \"{0:05}.png\".format(iSample)))\n \n\nroot_folder_path = os.path.join(DATA_DIR, \"scene0042\")\nfolder_names = [file for file in os.listdir(root_folder_path) if os.path.isdir(os.path.join(root_folder_path, file))]\nimg_separator = np.ones((128, 10, 3))*255\n\nfor iImage in range(len(os.listdir(os.path.join(root_folder_path, folder_names[0])))):\n img_stiched = img_separator\n # load and stich images of same index from all folders\n for iPlt, folder_name in enumerate(folder_names):\n image_names = os.listdir(os.path.join(root_folder_path, folder_name))\n image_path = os.path.join(root_folder_path, folder_name, image_names[iImage])\n img = np.asarray(Image.open(image_path))\n if len(img.shape) == 2:\n img = np.repeat(img[:, :, np.newaxis], 3, axis=2)\n img_stiched = np.append(img_stiched, img, axis=1)\n img_stiched = np.append(img_stiched, img_separator, axis=1)\n # store stiched image\n img_stiched = Image.fromarray(img_stiched.astype(np.uint8))\n img_stiched.save(os.path.join(root_folder_path, \"{0:05}.png\".format(iImage)))\n\n \n \n \n \n \n \n \n \n \n \n \n ", "repo_name": "maskedmeerkat/diss", "sub_path": "code/nuScenesOccMappingPipeline/computeInference_ism.py", "file_name": "computeInference_ism.py", "file_ext": "py", "file_size_in_byte": 5731, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.environ", "line_number": 3, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 13, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v1.logging.set_verbosity", "line_number": 14, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1.logging", "line_number": 14, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v1", "line_number": 14, "usage_type": "name"}, {"api_name": "tensorflow.compat.v1.disable_v2_behavior", "line_number": 15, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1", "line_number": 15, "usage_type": "name"}, {"api_name": "tensorflow.compat.v1.reset_default_graph", "line_number": 21, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1", "line_number": 21, "usage_type": "name"}, {"api_name": "tensorflow.compat.v1.keras.backend.clear_session", "line_number": 22, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1.keras", "line_number": 22, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v1", "line_number": 22, "usage_type": "name"}, {"api_name": "tensorflow.compat.v1.GraphDef", "line_number": 30, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1", "line_number": 30, "usage_type": "name"}, {"api_name": "tensorflow.compat.v1.import_graph_def", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1", "line_number": 33, "usage_type": "name"}, {"api_name": "tensorflow.compat.v1.get_default_graph", "line_number": 46, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1", "line_number": 46, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 61, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 84, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1.reset_default_graph", "line_number": 92, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1", "line_number": 92, "usage_type": "name"}, {"api_name": "tensorflow.compat.v1.keras.backend.clear_session", "line_number": 93, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1.keras", "line_number": 93, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v1", "line_number": 93, "usage_type": "name"}, {"api_name": "tensorflow.compat.v1.Session", "line_number": 95, "usage_type": "call"}, {"api_name": "tensorflow.compat.v1", "line_number": 95, "usage_type": "name"}, {"api_name": "tensorflow.python.platform.gfile.FastGFile", "line_number": 97, "usage_type": "call"}, {"api_name": "tensorflow.python.platform.gfile", "line_number": 97, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 100, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 111, "usage_type": "call"}, {"api_name": "os.path", "line_number": 111, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 115, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 115, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 115, "usage_type": "name"}, {"api_name": "numpy.newaxis", "line_number": 119, "usage_type": "attribute"}, {"api_name": "numpy.newaxis", "line_number": 121, "usage_type": "attribute"}, {"api_name": "PIL.Image.fromarray", "line_number": 127, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 127, "usage_type": "name"}, {"api_name": "numpy.uint8", "line_number": 127, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 128, "usage_type": "call"}, {"api_name": "os.path", "line_number": 128, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 131, "usage_type": "call"}, {"api_name": "os.path", "line_number": 131, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 132, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 132, "usage_type": "call"}, {"api_name": "os.path", "line_number": 132, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 133, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 135, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 135, "usage_type": "call"}, {"api_name": "os.path", "line_number": 135, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 139, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 139, "usage_type": "call"}, {"api_name": "os.path", "line_number": 139, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 140, "usage_type": "call"}, {"api_name": "os.path", "line_number": 140, "usage_type": "attribute"}, {"api_name": "numpy.asarray", "line_number": 141, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 141, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 141, "usage_type": "name"}, {"api_name": "numpy.repeat", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 143, "usage_type": "attribute"}, {"api_name": "numpy.append", "line_number": 144, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 145, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 147, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 147, "usage_type": "name"}, {"api_name": "numpy.uint8", "line_number": 147, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 148, "usage_type": "call"}, {"api_name": "os.path", "line_number": 148, "usage_type": "attribute"}]} +{"seq_id": "14852259863", "text": "import sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport yt\nfrom yt.visualization.volume_rendering.transfer_function_helper import TransferFunctionHelper\nfrom yt.visualization.volume_rendering.api import PointSource\nfrom yt.visualization.volume_rendering.api import Scene, BoxSource\n\ndef red(time):\n\th=0.6711\n\th0=h*3.246753e-18\n\tomegam=0.3\n\tyrtos=3.15569e7\n\ttime = time*yrtos*1.e6\n\tredshift = pow((3.*h0*pow(omegam,0.5)*time/2.),-2./3.)-1.\n\treturn redshift\n\ndef tim(redshift):\n\th=0.6711\n\th0=h*3.246753e-18\n\tomegam=0.3\n\tyrtos=3.15569e7\n\ttime = 2.*pow((1.+redshift),-3./2.)/(3.*h0*pow(omegam,0.5))\n\ttime = time/(yrtos*1.e6)\n\treturn time\n\ndef sim_redshift(i):\n\tx = tim(30) + 2*i\n\treturn(red(x))\n\n#h=0.7\nh=1.0\nd=10.0\nx=d/h\n\nDIMX = 256\n\ntracking_array = np.load(\"proj.npy\")\n\ni=0\n#plt.imshow(slice, cmap='hot', interpolation='nearest')\ny, x = np.meshgrid(np.linspace(0, 10, DIMX), np.linspace(0, 10, DIMX))\n#y, x = np.arange(0,DIMX), np.arange(0,DIMX)\n\nfig, ax1 = plt.subplots(1,1, figsize=(8,8))\n#z_min, z_max = np.abs(dens_slice).min(), np.abs(dens_slice).max()\n#c = ax1.pcolormesh(x, y, dens_slice, cmap='RdBu', vmin=z_min, vmax=z_max)\n#fig.colorbar(c, ax=ax1, label='Overdensity')\n'''\nfig, ax2, = plt.subplots(1,1, figsize=(8,8))'''\n\nz_min, z_max = np.abs(tracking_array[i]).min(), np.abs(tracking_array[i]).max()\nc = ax1.pcolormesh(x, y, tracking_array[i], cmap='RdBu', vmin=z_min, vmax=z_max)\nax1.axis([x.min(), x.max(), y.min(), y.max()])\nfig.colorbar(c, ax=ax1, label='$z$ of ($x_{HII}$ > $0.9$')\n\nplt.savefig(\"proj_plot_{}.png\".format(i))\n\nthresholds = [0.9, 0.1, 0.5, 0.9]\n\nfor i in range(1,4):\n\t#plt.imshow(slice, cmap='hot', interpolation='nearest')\n\ty, x = np.meshgrid(np.linspace(0, 10, DIMX), np.linspace(0, 10, DIMX))\n\t#y, x = np.arange(0,DIMX), np.arange(0,DIMX)\n\n\tfig, ax1 = plt.subplots(1,1, figsize=(8,8))\n\t#z_min, z_max = np.abs(dens_slice).min(), np.abs(dens_slice).max()\n\t#c = ax1.pcolormesh(x, y, dens_slice, cmap='RdBu', vmin=z_min, vmax=z_max)\n\t#fig.colorbar(c, ax=ax1, label='Overdensity')\n\t'''\n\tfig, ax2, = plt.subplots(1,1, figsize=(8,8))'''\n\n\tz_min, z_max = np.abs(tracking_array[i]).min(), np.abs(tracking_array[i]).max()\n\tc = ax1.pcolormesh(x, y, tracking_array[i], cmap='RdBu', vmin=z_min, vmax=z_max)\n\tax1.axis([x.min(), x.max(), y.min(), y.max()])\n\tfig.colorbar(c, ax=ax1, label='$z$ of ($$ > ' + '{}'.format(thresholds[i]))\n\n\tplt.savefig(\"proj_plot_{}.png\".format(i))\n\n\"\"\"fig, (ax1, ax2) = plt.subplots(1,2, figsize=(16,8))\nz_min, z_max = np.abs(dens_slice).min(), np.abs(dens_slice).max()\nc = ax1.pcolormesh(x, y, dens_slice, cmap='RdBu', vmin=z_min, vmax=z_max)\nfig.colorbar(c, ax=ax1, label='Overdensity')\n'''\nfig, ax2, = plt.subplots(1,1, figsize=(8,8))'''\n\nz_min, z_max = np.abs(tracking_array).min(), np.abs(tracking_array).max()\nprint(\"av of {} = {}\".format(i, np.mean(tracking_array)))\nc = ax2.pcolormesh(x, y, tracking_array, cmap='RdBu', vmin=z_min, vmax=z_max)\nax2.axis([x.min(), x.max(), y.min(), y.max()])'''\nfig.colorbar(c, ax=ax2, label='$z$ of $(x_{HII} > 0.9)$')\"\"\"\"\"\"\n\nif(False):\n\tDIMX = 256\n\t'''bbox = np.array([[0.,x],[0.,x],[0.,x]])\n\n\tbounds = (8.e-2,1.e0)\n\t#arr = 1.0 - arr\n\t#data\t= dict(fraction = arr, density = arrD)\n\tdata\t= dict(\tx_h = arr_h,\n\t \t\t\tx_he = arr_he,\n\t\t\t\t\tenergy = arr_energy,\n\t\t\t\t\tdensity = arr_n\n\t )\n\tds\t= yt.load_uniform_grid(data, arr_h.shape, length_unit=\"Mpc\", bbox=bbox, nprocs=1)\n\tprint(ds)\n\tprint(ds.field_list)\n\t\n\tplot = yt.PhasePlot(\n\t\tds,\n\t\t('stream', 'x_h'),\n\t\t('stream', 'density'),\n\t\t('stream', 'x_he'),\n\t\tweight_field=None,\n\t)\n\n\tplot.save(\"phase.png\")'''\n\t\"\"\"\n\t#sc = yt.create_scene(ds, 'fraction', lens_type='perspective')\nif(False):\n\tsc = yt.create_scene(ds, 'fraction', lens_type='plane-parallel')\n\t\n\ttf = yt.ColorTransferFunction(np.log10(bounds))\n\t#cmap = plt.cm.get_cmap('algae')\n\t#cmap = plt.cm.get_cmap('RdYlBu')\n\t#cmap = plt.cm.get_cmap('viridis')\n\t#cmap = plt.cm.get_cmap('PRISM')\n\t'''\n\tcmap = plt.cm.get_cmap('bds_highcontrast')\n\tcen = [1.e-1, 8.e-1, 1.e0]\n\tcol = [cmap(0.2), cmap(0.45), cmap(1.0)]\n\th = [10.e0, 8.e-1, 3.e-1]\n\tw = [0.001, 0.001, 0.001]\n\t'''\n\tcmap = plt.cm.get_cmap('RdBu')\n\tcen = [1.e-1, 7.5e-1, 1.e0]\n\tcol = [cmap(1.0), cmap(0.2), cmap(0.0)]\n\th = [1.e1, 4.0e-1, 2.0e-1]\n\tw = [0.001, 0.001, 0.001]\n\tfor i in range(0, len(cen)):\n\t\ttf.add_gaussian(np.log10(cen[i]), width=w[i], height=[col[i][0], col[i][1], col[i][2], h[i]])\n\t#np.log(float(N)/(i+0.5))\n\tsource = sc[0]\n\tsource.tfh.tf = tf\n\tsource.tfh.bounds = bounds\n\t#source.tfh.plot('./transfer_function%03d.png' % arg, profile_field='fraction')\n\t\n\t#sc.annotate_text([0,0], 'Hello')\n\t\n\tslist = np.genfromtxt(\"./photons/slist%02d.dat\" % (arg/5))\n\tslist = np.float_(slist)\n\tpoints = slist[:,0:3]*x/DIMX\n\t#print(slist)\n\n\t'''points = points*2\n\tpoints = points[points[:,0]0] = 0.02\n\trad = np.zeros(slist[:,0].size)\n\tfor i in range(0, points[:,0].size):\n\t\trad[i] = int(2+2*np.log(slist[i][4])/np.log(slist[0][4]))\n\trad = rad.astype(int)\n\t\n\t#verts = PointSource(points, colors = colors, color_stride = 1, radii = int(DIM/512))\n\tverts = PointSource(points, colors = colors, color_stride = 1, radii = 1)\n\tsc.add_source(verts)\n\t\n\tcam.set_position((0.51, 0.51, 0.51))\n\t\n\t#DTheta = 10.0*np.pi/180.0\n\t#NTheta = 10\n\tDTheta = 2.0*np.pi/180.0\n\tNTheta = 1\n\t#cam.rotate((arg-slice0)*DTheta)\n\t\n\tj=0\n\tfor i in cam.iter_rotate(DTheta, NTheta):\n\t\tframe = NTheta*(arg-slice0) + j\n\t\t\n\t\ttheta = frame*DTheta/NTheta\n\t\tdx = np.cos(theta)\n\t\tdy = np.sin(theta)\n\t\tnorth_vector = (-dx, -dy, 0.7071)\n\t\torig = np.array([0.5, 0.5, 0.5])\t\t\n\t\tvec = np.array([0.7071*dx, 0.7071*dy, 0.5*(1.0 - frame/400.0)])\n\t\tcam.set_position(orig + 1.5*vec, north_vector = north_vector)\n\t\t#cam.set_focus((0.5, 0.5, 0.5))\n\t\t#cam.switch_orientation(normal_vector = normal_vector, north_vector=north_vector)\n\t\t\n\t\tprint(cam)\n\t\n\t\t'''xcam = 5+5*np.cos(theta)\n\t\tycam = 5+5*np.sin(theta)\n\t\tcam.set_position(xcam, ycam, 10.0)\n\t\tcam.set_focus(5, 5, 5)\n\t\tcam.switch_orientation()'''\n\t\n\t\t#sc.camera.width = (10, 'Mpc')\n\t\t#sc.camera.switch_orientation()\n\t\n\t\t#sc.annotate_grids(ds, alpha=0.01)\n\t\tsc.render()\n\t\tsc.save('./vis/rendering%03d.png' % frame, sigma_clip=1)\n\t\tj+=1\n\t\t#sc.save('./rendering%03d_y2.png' % arg, sigma_clip=2)\n\t\t#sc.save('./rendering%03d_3.png' % arg, sigma_clip=3)\n\t\t#sys.exit()\"\"\"\n'''\n// Returns redshift as a function of time in Myr\ndouble red(double time){\n\tdouble h=0.6711;\n\tdouble h0=h*3.246753e-18;\n\tdouble omegam=0.3;\n\tdouble yrtos=3.15569e7;\n\ttime = time*yrtos*1.e6;\n\tdouble redshift = pow((3.*h0*pow(omegam,0.5)*time/2.),-2./3.)-1.;\n\treturn redshift;\n}\n\n// Returns time in Myr as a function of redshift\ndouble tim(double redshift){\n\tdouble h=0.6711;\n\tdouble h0=h*3.246753e-18;\n\tdouble omegam=0.3;\n\tdouble yrtos=3.15569e7;\n\tdouble time = 2.*pow((1.+redshift),-3./2.)/(3.*h0*pow(omegam,0.5));\n\ttime = time/(yrtos*1.e6);\n\treturn time;\n}'''\n", "repo_name": "blakehartley/ARC", "sub_path": "dat/proj/proj_plot.py", "file_name": "proj_plot.py", "file_ext": "py", "file_size_in_byte": 7256, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.load", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}, {"api_name": "numpy.abs", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}, {"api_name": "numpy.meshgrid", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "numpy.abs", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 78, "usage_type": "name"}, {"api_name": "yt.create_scene", "line_number": 121, "usage_type": "call"}, {"api_name": "yt.ColorTransferFunction", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 123, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.cm.get_cmap", "line_number": 135, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 135, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 135, "usage_type": "name"}, {"api_name": "numpy.log10", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.genfromtxt", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.float_", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 170, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 174, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 176, "usage_type": "call"}, {"api_name": "yt.visualization.volume_rendering.api.PointSource", "line_number": 180, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 187, "usage_type": "attribute"}, {"api_name": "numpy.cos", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 197, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 199, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 200, "usage_type": "call"}]} +{"seq_id": "19725654788", "text": "import time\n\nfrom multiprocess_external import runProcess\nfrom multiprocessing.spawn import freeze_support\n\ndef processLoadCPU(no):\n import signal\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n # import psutil\n # import os\n # p = psutil.Process(os.getpid())\n # set to lowest priority, this is windows only, on Unix use ps.nice(19)\n # Get or set process niceness (priority). On UNIX this is a number which usually goes from -20 to 20\n # The higher the nice value, the lower the priority of the process.\n # p.nice(20)\n start_time = round(time.monotonic() * 1000)\n while True:\n time.sleep(0.001)\n # try:\n time_taken_idle = round(time.monotonic() * 1000) - start_time\n # print(no, \"processLoadCPU loop idle\", str(time_taken_idle), \"ms\") # 10 ms\n start_time = round(time.monotonic() * 1000)\n # lst = [i for i in range(1000000)]\n # lst = [i * i for i in lst]\n # lst = [i * i for i in lst]\n # lst = lst\n time_taken = round(time.monotonic() * 1000) - start_time\n print(no, \"processLoadCPU loop\", time_taken, \"+\", time_taken_idle, \"ms\")\n # with youtube, no realsense 2 loads 1460 on 10000000 GPU=28% CPU=130%\n # with youtube, realsense 2 loads 1460 on 10000000 GPU=24% CPU=115%\n # without youtube, no realsense 2 loads 1330 on 10000000 GPU=12% CPU=100%\n # without youtube, no realsense 1 load 1290 on 10000000 GPU=3% CPU=100%\n start_time = round(time.monotonic() * 1000)\n # except KeyboardInterrupt:\n # # **** THIS PART NEVER EXECUTES. ****\n # # pool.terminate()\n # print(\"You cancelled the program!\")\n # # sys.exit(1)\n # # return\n\nif __name__ == '__main__':\n freeze_support()\n runProcess(processLoadCPU, args=(1,))\n time.sleep(1000.001)\n", "repo_name": "LumaRay/python-tests", "sub_path": "parallellizing/multiprocess_main.py", "file_name": "multiprocess_main.py", "file_ext": "py", "file_size_in_byte": 1846, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "signal.signal", "line_number": 8, "usage_type": "call"}, {"api_name": "signal.SIGINT", "line_number": 8, "usage_type": "attribute"}, {"api_name": "signal.SIG_IGN", "line_number": 8, "usage_type": "attribute"}, {"api_name": "time.monotonic", "line_number": 16, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 18, "usage_type": "call"}, {"api_name": "time.monotonic", "line_number": 20, "usage_type": "call"}, {"api_name": "time.monotonic", "line_number": 22, "usage_type": "call"}, {"api_name": "time.monotonic", "line_number": 27, "usage_type": "call"}, {"api_name": "time.monotonic", "line_number": 33, "usage_type": "call"}, {"api_name": "multiprocessing.spawn.freeze_support", "line_number": 42, "usage_type": "call"}, {"api_name": "multiprocess_external.runProcess", "line_number": 43, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 44, "usage_type": "call"}]} +{"seq_id": "29482908932", "text": "## Script to filter results of concurrency test to include only warm starts\n\nimport json\n\n# Read JSON data from a file\nwith open('/home/m/Documents/MasterTGN/MasterThesis/results/final/1_wasm_concurrency_mixed_75_25.log', 'r') as file:\n #data = json.load(file)\n data = file.read()\n\njson_elements = data.split('\\n')\n\nfor json_element in json_elements:\n if json_element.strip(): # Check if the line is not empty\n parsed_data = json.loads(json_element)\n # Filter the JSON data\n filtered_data = []\n for item in parsed_data:\n new_item = {\n \"no_concurrent_requests\": item[\"no_concurrent_requests\"],\n \"responses\": []\n }\n for response in item[\"responses\"]:\n annotations = response[\"annotations\"]\n has_init_time = any(ann[\"key\"] == \"initTime\" for ann in annotations)\n has_wait_time = any(ann[\"key\"] == \"waitTime\" for ann in annotations)\n \n if has_wait_time and not has_init_time:\n new_item[\"responses\"].append(response)\n \n if new_item[\"responses\"]:\n filtered_data.append(new_item)\n\n # Write the filtered JSON data to a new file\n with open('3_wasm_concurrency_mixed_75_25.log', 'a') as file:\n json.dump(filtered_data, file, indent=2)", "repo_name": "MarlonFunk/MasterThesis", "sub_path": "results/extract_warm_start.py", "file_name": "extract_warm_start.py", "file_ext": "py", "file_size_in_byte": 1384, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "json.loads", "line_number": 14, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 35, "usage_type": "call"}]} +{"seq_id": "7818904939", "text": "from typing import List, Any\nfrom urllib.parse import urljoin\nimport requests\nfrom UtilsManager import validate_response\nfrom OrcaSecurityParser import OrcaSecurityParser\nfrom constants import ENDPOINTS, POSSIBLE_SEVERITIES, DEFAULT_MAX_LIMIT, WHITELIST_FILTER, BLACKLIST_FILTER\nfrom SiemplifyUtils import unix_now\n\n\nclass OrcaSecurityManager:\n def __init__(self, api_root, api_key, api_token, verify_ssl, ui_root=\"\", siemplify_logger=None):\n \"\"\"\n The method is used to init an object of Manager class\n :param api_root: {str} OrcaSecurity API root\n :param api_key: {str} OrcaSecurity API key\n :param api_token: {str} OrcaSecurity API token\n :param verify_ssl: {bool} Specifies if certificate that is configured on the api root should be validated\n :param ui_root: {str} OrcaSecurity UI root\n :param siemplify_logger: Siemplify logger\n \"\"\"\n self.api_root = api_root[:-1] if api_root.endswith(\"/\") else api_root\n self.api_key = api_key\n self.api_token = api_token\n self.verify_ssl = verify_ssl\n self.ui_root = ui_root\n self.siemplify_logger = siemplify_logger\n self.parser = OrcaSecurityParser()\n self.session = requests.Session()\n self.session.verify = verify_ssl\n if self.api_token:\n self.session.headers = {\"Authorization\": f\"Token {self.api_token}\"}\n elif self.api_key:\n self.set_auth_cookies()\n else:\n raise Exception('Either \\\"API Key\\\" or \\\"API Token\\\" needs to be provided for authentication.')\n\n def _get_full_url(self, url_id, **kwargs):\n \"\"\"\n Get full url from url identifier.\n :param url_id: {str} The id of url\n :param kwargs: {dict} Variables passed for string formatting\n :return: {str} The full url\n \"\"\"\n return urljoin(self.api_root, ENDPOINTS[url_id].format(**kwargs))\n\n def set_auth_cookies(self):\n \"\"\"\n Set authorization cookies\n :return: {void}\n \"\"\"\n url = self._get_full_url(\"login\")\n params = {\n \"security_token\": self.api_key\n }\n\n response = self.session.get(url, params=params, allow_redirects=False)\n validate_response(response)\n\n for cookie in response.cookies:\n if cookie.name == 'csrftoken':\n self.session.cookies.update({\"csrftoken\": cookie.value})\n if cookie.name == 'sessionid':\n self.session.cookies.update({\"sessionid\": cookie.value})\n\n def test_connectivity(self):\n \"\"\"\n Test connectivity\n :return: {void}\n \"\"\"\n payload = {\"limit\": 1}\n url = self._get_full_url(\"vulnerability_details\")\n response = self.session.post(url, json=payload)\n validate_response(response)\n\n def get_alerts(self, start_timestamp, limit, lowest_severity=None, categories=None, title_filter=None,\n title_filter_type=WHITELIST_FILTER, alert_types=None):\n \"\"\"\n Get alerts\n :param start_timestamp: {int} timestamp for oldest alert to fetch\n :param limit: {int} limit for results\n :param lowest_severity: {str} lowest severity to use for fetching\n :param categories: {list} list of category filters to use for fetching\n :param title_filter: {list} list of title filters to use for fetching\n :param title_filter_type: {int} specifies if includes or excludes should be used for title filter\n :param alert_types: {list} list of alert type filters to use for fetching\n :return: {list} list of Alert objects\n \"\"\"\n url = self._get_full_url(\"get_alerts\")\n\n payload = {\n \"dsl_filter\": {\n \"filter\": [\n {\n \"field\": \"state.created_at\",\n \"range\": {\n \"gte\": start_timestamp,\n \"lte\": unix_now()\n }\n },\n {\n \"field\": \"state.status\",\n \"includes\": [\n \"open\",\n \"in_progress\"\n ]\n }\n ],\n \"sort\": [\n {\n \"field\": \"state.created_at\",\n \"order\": \"asc\"\n }\n ]\n },\n \"limit\": max(limit, DEFAULT_MAX_LIMIT),\n \"start_at_index\": 0,\n \"resolved_alerts\": False,\n \"grouping\": True,\n \"show_all_statuses_alerts\": True\n }\n\n if lowest_severity:\n payload.get(\"dsl_filter\").get(\"filter\").append({\n \"field\": \"state.severity\",\n \"includes\": POSSIBLE_SEVERITIES[:POSSIBLE_SEVERITIES.index(lowest_severity) + 1]\n })\n\n if categories:\n payload.get(\"dsl_filter\").get(\"filter\").append({\n \"field\": \"category\",\n \"includes\": categories\n })\n\n if title_filter:\n payload.get(\"dsl_filter\").get(\"filter\").append({\n \"field\": \"data.title\",\n \"excludes\" if title_filter_type == BLACKLIST_FILTER else \"includes\": title_filter\n })\n\n if alert_types:\n payload.get(\"dsl_filter\").get(\"filter\").append({\n \"field\": \"type\",\n \"includes\": alert_types\n })\n\n response = self.session.post(url, json=payload)\n validate_response(response)\n return self.parser.build_alert_objects(response.json())\n\n def verify_alert(self, alert_id):\n \"\"\"\n Verify Alert\n :param alert_id: {str} alert id\n :return: {void}\n \"\"\"\n url = self._get_full_url(\"verify_alert\", alert_id=alert_id)\n response = self.session.put(url)\n validate_response(response)\n\n def snooze_alert(self, alert_id, snooze_days):\n \"\"\"\n Snooze alert\n :param alert_id: {str} alert id\n :param snooze_days: {int} specifies how many days alert needs to be snoozed\n :return: {void}\n \"\"\"\n url = self._get_full_url(\"snooze_alert\", alert_id=alert_id)\n payload = {\n \"days\": snooze_days\n }\n\n response = self.session.put(url, json=payload)\n validate_response(response)\n\n def update_alert_status(self, alert_id, status):\n \"\"\"\n Update alert status\n :param alert_id: {str} alert id\n :param status: {int} specifies what status to set for alert\n :return: {void}\n \"\"\"\n url = self._get_full_url(\"update_alert_status\", alert_id=alert_id, status=status)\n response = self.session.put(url)\n validate_response(response)\n\n def get_alert_data(self, alert_id):\n \"\"\"\n Get alert data\n :param alert_id: {str} alert id\n :return: {Alert} Alert object\n \"\"\"\n url = self._get_full_url(\"get_alert_data\", alert_id=alert_id)\n response = self.session.get(url)\n validate_response(response)\n return self.parser.build_alert_object(response.json())\n\n def add_alert_comment(self, alert_id, comment):\n \"\"\"\n Add comment to alert\n :param alert_id: {str} alert id\n :param comment: {str} comment to add\n :return: {AlertComment} AlertComment object\n \"\"\"\n url = self._get_full_url(\"add_alert_comment\", alert_id=alert_id)\n payload = {\n \"comment\": comment\n }\n\n response = self.session.put(url, json=payload)\n validate_response(response)\n return self.parser.build_alert_comment_object(response.json())\n\n def get_frameworks(self, framework_names, limit):\n \"\"\"\n Get frameworks\n :param framework_names: {list} list of framework names to retrieve\n :param limit: {int} limit for results\n :return: {([Framework], [str])} list of Framework objects, list of not found framework names\n \"\"\"\n url = self._get_full_url(\"get_frameworks\")\n response = self.session.post(url)\n validate_response(response)\n return self.filter_frameworks(self.parser.build_framework_objects(response.json()), framework_names, limit)\n\n @staticmethod\n def filter_frameworks(frameworks, framework_names, limit):\n \"\"\"\n Filter frameworks by names\n :param frameworks: {list} list of Framework objects to filter\n :param framework_names: {list} list of framework names to use for filtering\n :param limit: {int} limit for results\n :return: {([Framework], [str])} list of filtered Framework objects, list of not found framework names\n \"\"\"\n if framework_names:\n filtered_frameworks = [framework for framework in frameworks if framework.display_name in framework_names]\n not_found_frameworks = list(\n set(framework_names) - set([framework.display_name for framework in filtered_frameworks])\n )\n else:\n filtered_frameworks = frameworks\n not_found_frameworks = []\n\n return filtered_frameworks[:limit] if limit else filtered_frameworks, not_found_frameworks\n\n def start_scan(self, asset_id):\n \"\"\"\n Start scan for asset by id\n :param asset_id: {str} asset id\n :return: {ScanStatus} ScanStatus object\n \"\"\"\n url = self._get_full_url(\"start_scan\", asset_id=asset_id)\n response = self.session.post(url)\n validate_response(response)\n return self.parser.build_scan_status_object(response.json())\n\n def get_scan_status(self, scan_id):\n \"\"\"\n Get scan status by id\n :param scan_id: {str} scan id\n :return: {ScanStatus} ScanStatus object\n \"\"\"\n url = self._get_full_url(\"get_scan_status\", scan_id=scan_id)\n response = self.session.get(url)\n validate_response(response)\n return self.parser.build_scan_status_object(response.json())\n\n def get_vulnerability_results(self, cve_id, limit=None, create_insight=False) -> List[Any]:\n payload = {\n \"dsl_filter\": {\n \"filter\": [\n {\n \"field\": \"cve_id\",\n \"includes\": [cve_id]\n }\n ],\n \"sort\": [\n {\n \"field\": \"severity\",\n \"order\": \"desc\"\n }\n ]\n }\n }\n\n results = self._paginate_results(method='POST', url=self._get_full_url(\"vulnerability_details\"),\n body=payload, limit=limit)\n enrichment_data = self.parser.build_results(raw_json=results[:limit], pure_data=True, method='build_cve_object')\n return_list = [enrichment_data, None]\n if create_insight:\n # for insight generation whole data is required\n insight_data = self.parser.build_results(raw_json=results, pure_data=True, method='build_cve_object')\n return_list[1] = insight_data\n return return_list\n\n def get_asset_details(self, asset_id):\n \"\"\"\n Get asset details\n :param asset_id: {str} asset unique id\n :return: {Asset} object of Asset datamodel\n \"\"\"\n response = self.session.get(self._get_full_url(\"asset_details\", asset_id=asset_id))\n validate_response(response)\n\n return self.parser.build_asset_object(response.json())\n\n def get_vulnerability_details(self, asset_id, severity, limit=None):\n \"\"\"\n Get vulnerability details by severity value\n :param asset_id: {str} asset unique id\n :param severity: {str} lowest severity value\n :param limit: {int} limit of returning data\n :return: {list} list of vulnerabilities\n \"\"\"\n payload = {\n \"dsl_filter\": {\n \"filter\": [\n {\n \"field\": \"asset_unique_id\",\n \"includes\": [asset_id]\n }\n ],\n \"sort\": [\n {\n \"field\": \"score\",\n \"order\": \"desc\"\n }\n ]\n },\n \"limit\": limit,\n \"start_at_index\": 0,\n \"grouping\": True\n }\n\n if severity:\n payload.get(\"dsl_filter\").get(\"filter\").append({\n \"field\": \"severity\",\n \"includes\": POSSIBLE_SEVERITIES[:POSSIBLE_SEVERITIES.index(severity.lower()) + 1]\n })\n\n response = self.session.post(self._get_full_url(\"vulnerability_details\"), json=payload)\n validate_response(response)\n\n return self.parser.build_results(raw_json=response.json(), method='build_cve_object')\n\n def _paginate_results(\n self, method, url, params=None, body=None, limit=None, err_msg=\"Unable to get results\", **kwargs\n ):\n \"\"\"\n Paginate the results of a request\n :param method: {str} The method of the request (GET, POST, PUT, DELETE, PATCH)\n :param url: {str} The url to send request to\n :param params: {dict} The params of the request\n :param body: {dict} The json payload of the request\n :param limit: {int} The limit of the results to fetch\n :param err_msg: {str} The message to display on error\n :return: {list} List of results\n \"\"\"\n if body is None:\n body = {}\n\n body.update({\n \"limit\": 1000\n })\n\n response = self.session.request(method, url, params=params, json=body)\n\n validate_response(response, err_msg)\n json_response = response.json()\n results = json_response.get(\"data\", [])\n next_page_token = json_response.get(\"next_page_token\", \"\")\n\n while next_page_token:\n body.update({\n \"next_page_token\": next_page_token\n })\n\n response = self.session.request(method, url, params=params, json=body)\n validate_response(response, err_msg)\n json_response = response.json()\n next_page_token = json_response.get(\"next_page_token\", \"\")\n results.extend(json_response.get(\"data\", []))\n return results\n", "repo_name": "chronicle/tip-marketplace", "sub_path": "Integrations/OrcaSecurity/Managers/OrcaSecurityManager.py", "file_name": "OrcaSecurityManager.py", "file_ext": "py", "file_size_in_byte": 14386, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "20", "api": [{"api_name": "OrcaSecurityParser.OrcaSecurityParser", "line_number": 27, "usage_type": "call"}, {"api_name": "requests.Session", "line_number": 28, "usage_type": "call"}, {"api_name": "urllib.parse.urljoin", "line_number": 44, "usage_type": "call"}, {"api_name": "constants.ENDPOINTS", "line_number": 44, "usage_type": "name"}, {"api_name": "UtilsManager.validate_response", "line_number": 57, "usage_type": "call"}, {"api_name": "UtilsManager.validate_response", "line_number": 73, "usage_type": "call"}, {"api_name": "constants.WHITELIST_FILTER", "line_number": 76, "usage_type": "name"}, {"api_name": "SiemplifyUtils.unix_now", "line_number": 97, "usage_type": "call"}, {"api_name": "constants.DEFAULT_MAX_LIMIT", "line_number": 115, "usage_type": "argument"}, {"api_name": "constants.POSSIBLE_SEVERITIES", "line_number": 125, "usage_type": "name"}, {"api_name": "constants.POSSIBLE_SEVERITIES.index", "line_number": 125, "usage_type": "call"}, {"api_name": "constants.BLACKLIST_FILTER", "line_number": 137, "usage_type": "name"}, {"api_name": "UtilsManager.validate_response", "line_number": 147, "usage_type": "call"}, {"api_name": "UtilsManager.validate_response", "line_number": 158, "usage_type": "call"}, {"api_name": "UtilsManager.validate_response", "line_number": 173, "usage_type": "call"}, {"api_name": "UtilsManager.validate_response", "line_number": 184, "usage_type": "call"}, {"api_name": "UtilsManager.validate_response", "line_number": 194, "usage_type": "call"}, {"api_name": "UtilsManager.validate_response", "line_number": 210, "usage_type": "call"}, {"api_name": "UtilsManager.validate_response", "line_number": 222, "usage_type": "call"}, {"api_name": "UtilsManager.validate_response", "line_number": 253, "usage_type": "call"}, {"api_name": "UtilsManager.validate_response", "line_number": 264, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 267, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 267, "usage_type": "name"}, {"api_name": "UtilsManager.validate_response", "line_number": 302, "usage_type": "call"}, {"api_name": "constants.POSSIBLE_SEVERITIES", "line_number": 337, "usage_type": "name"}, {"api_name": "constants.POSSIBLE_SEVERITIES.index", "line_number": 337, "usage_type": "call"}, {"api_name": "UtilsManager.validate_response", "line_number": 341, "usage_type": "call"}, {"api_name": "UtilsManager.validate_response", "line_number": 367, "usage_type": "call"}, {"api_name": "UtilsManager.validate_response", "line_number": 378, "usage_type": "call"}]} +{"seq_id": "2979815940", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.base import TransformerMixin, BaseEstimator\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection._split import check_cv\nfrom sklearn.base import clone, is_classifier\nfrom scipy.stats import kurtosis, skew\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\nclass ClassifierTransformer(BaseEstimator, TransformerMixin):\n \n def __init__(self, estimator=None, n_classes=2, cv=3):\n self.estimator = estimator\n self.n_classes = n_classes\n self.cv = cv\n \n def _get_labels(self, y):\n y_labels = np.zeros(len(y))\n y_us = np.sort(np.unique(y))\n step = int(len(y_us) / self.n_classes)\n \n for i_class in range(self.n_classes):\n if i_class + 1 == self.n_classes:\n y_labels[y >= y_us[i_class * step]] = i_class\n else:\n y_labels[\n np.logical_and(\n y >= y_us[i_class * step],\n y < y_us[(i_class + 1) * step]\n )\n ] = i_class\n return y_labels\n \n def fit(self, X, y):\n X = X.replace([np.inf,-np.inf], np.nan)\n X = X.fillna(0)\n y_labels = self._get_labels(y)\n cv = check_cv(self.cv, y_labels, classifier=is_classifier(self.estimator))\n self.estimators_ = []\n \n for train, _ in cv.split(X, y_labels):\n X = np.array(X)\n self.estimators_.append(\n clone(self.estimator).fit(X[train], y_labels[train])\n )\n return self\n \n def transform(self, X, y=None):\n cv = check_cv(self.cv, y, classifier=is_classifier(self.estimator))\n X = X.replace([np.inf,-np.inf], np.nan)\n X = X.fillna(0)\n X = np.array(X)\n X_prob = np.zeros((X.shape[0], self.n_classes))\n X_pred = np.zeros(X.shape[0])\n \n for estimator, (_, test) in zip(self.estimators_, cv.split(X)):\n X_prob[test] = estimator.predict_proba(X[test])\n X_pred[test] = estimator.predict(X[test])\n return np.hstack([X_prob, np.array([X_pred]).T])\n\ndef reduce_mem_usage(df, verbose=True):\n numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n start_mem = df.memory_usage().sum() / 1024**2 \n for col in df.columns:\n col_type = df[col].dtypes\n if col_type in numerics:\n c_min = df[col].min()\n c_max = df[col].max()\n if str(col_type)[:3] == 'int':\n if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n df[col] = df[col].astype(np.int8)\n elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n df[col] = df[col].astype(np.int16)\n elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n df[col] = df[col].astype(np.int32)\n elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n df[col] = df[col].astype(np.int64) \n else:\n if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n df[col] = df[col].astype(np.float16)\n elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n df[col] = df[col].astype(np.float32)\n else:\n df[col] = df[col].astype(np.float64) \n end_mem = df.memory_usage().sum() / 1024**2\n if verbose: print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) / start_mem))\n return df\n\nall_features = ['type', 'atom_x', 'x_x', 'y_x','z_x', 'n_bonds_x', 'atom_y', 'x_y', 'y_y',\n 'z_y', 'n_bonds_y', 'C', 'F', 'H', 'N', 'O', 'distance', 'dist_mean_x','dist_mean_y',\n 'x_dist', 'y_dist', 'z_dist', 'x_dist_abs', 'y_dist_abs', 'z_dist_abs','inv_distance3']\n\n\n# In[2]:\n\n\n\ndef struct_change(X):\n \n atom_rad = [atomic_radius[x] for x in X['atom'].values]\n X['rad'] = atom_rad\n position = X[['x','y','z']].values\n p_temp = position\n molec_name = X['molecule_name'].values\n m_temp = molec_name\n radius = X['rad'].values\n r_temp = radius\n bond = 0\n dist_keep = 0\n dist_bond = 0 \n no_bond = 0\n dist_no_bond = 0\n dist_matrix = np.zeros((X.shape[0],2*29))\n dist_matrix_bond = np.zeros((X.shape[0],2*29))\n dist_matrix_no_bond = np.zeros((X.shape[0],2*29))\n\n for i in range(29):\n p_temp = np.roll(p_temp,-1,axis=0)\n m_temp = np.roll(m_temp,-1,axis=0)\n r_temp = np.roll(r_temp,-1,axis=0)\n mask = (m_temp==molec_name)\n dist = np.linalg.norm(position-p_temp,axis=1) * mask \n dist_temp = np.roll(np.linalg.norm(position-p_temp,axis=1)*mask,i+1,axis=0)\n diff_radius_dist = (dist-(radius+r_temp)) * (dist<(radius+r_temp)) * mask\n diff_radius_dist_temp = np.roll(diff_radius_dist,i+1,axis=0)\n bond += (dist<(radius+r_temp)) * mask\n bond_temp = np.roll((dist<(radius+r_temp)) * mask,i+1,axis=0)\n no_bond += (dist>=(radius+r_temp)) * mask\n no_bond_temp = np.roll((dist>=(radius+r_temp)) * mask,i+1,axis=0)\n bond += bond_temp\n no_bond += no_bond_temp\n dist_keep += dist * mask\n dist_matrix[:,2*i] = dist\n dist_matrix[:,2*i+1] = dist_temp\n dist_matrix_bond[:,2*i] = dist * (dist<(radius+r_temp)) * mask\n dist_matrix_bond[:,2*i+1] = dist_temp * bond_temp\n dist_matrix_no_bond[:,2*i] = dist * (dist>(radius+r_temp)) * mask\n dist_matrix_no_bond[:,2*i+1] = dist_temp * no_bond_temp\n X['n_bonds'] = bond\n X['n_no_bonds'] = no_bond\n X['dist_mean'] = np.nanmean(np.where(dist_matrix==0,np.nan,dist_matrix), axis=1)\n X['dist_median'] = np.nanmedian(np.where(dist_matrix==0,np.nan,dist_matrix), axis=1)\n X['dist_std_bond'] = np.nanstd(np.where(dist_matrix_bond==0,np.nan,dist_matrix), axis=1)\n X['dist_mean_bond'] = np.nanmean(np.where(dist_matrix_bond==0,np.nan,dist_matrix), axis=1)\n X['dist_median_bond'] = np.nanmedian(np.where(dist_matrix_bond==0,np.nan,dist_matrix), axis=1)\n X['dist_mean_no_bond'] = np.nanmean(np.where(dist_matrix_no_bond==0,np.nan,dist_matrix), axis=1)\n X['dist_std_no_bond'] = np.nanstd(np.where(dist_matrix_no_bond==0,np.nan,dist_matrix), axis=1)\n X['dist_median_no_bond'] = np.nanmedian(np.where(dist_matrix_no_bond==0,np.nan,dist_matrix), axis=1)\n X['dist_std'] = np.nanstd(np.where(dist_matrix==0,np.nan,dist_matrix), axis=1)\n X['dist_min'] = np.nanmin(np.where(dist_matrix==0,np.nan,dist_matrix), axis=1)\n X['dist_max'] = np.nanmax(np.where(dist_matrix==0,np.nan,dist_matrix), axis=1)\n X['range_dist'] = np.absolute(X['dist_max']-X['dist_min'])\n X['dist_bond_min'] = np.nanmin(np.where(dist_matrix_bond==0,np.nan,dist_matrix), axis=1)\n X['dist_bond_max'] = np.nanmax(np.where(dist_matrix_bond==0,np.nan,dist_matrix), axis=1)\n X['range_dist_bond'] = np.absolute(X['dist_bond_max']-X['dist_bond_min'])\n X['dist_no_bond_min'] = np.nanmin(np.where(dist_matrix_no_bond==0,np.nan,dist_matrix), axis=1)\n X['dist_no_bond_max'] = np.nanmax(np.where(dist_matrix_no_bond==0,np.nan,dist_matrix), axis=1)\n X['range_dist_no_bond'] = np.absolute(X['dist_no_bond_max']-X['dist_no_bond_min'])\n X['n_diff'] = pd.DataFrame(np.around(dist_matrix_bond,5)).nunique(axis=1).values #5\n X = reduce_mem_usage(X,verbose=False)\n return X\n\n\n\n \ndef more_feas(X):\n X['distance'] = np.linalg.norm(X[['x_x','y_x','z_x']].values - X[['x_y','y_y','z_y']].values ,axis=1)\n X['x_dist'] = X['x_x'] - X['x_y']\n X['y_dist'] = X['y_x'] - X['y_y']\n X['z_dist'] = X['z_x'] - X['z_y']\n #绝对值\n X['x_dist_abs'] = np.absolute(X['x_dist'])\n X['y_dist_abs'] = np.absolute(X['y_dist'])\n X['z_dist_abs'] = np.absolute(X['z_dist'])\n X['inv_distance3'] = 1/(X['distance']**3)\n #分子中原子对,x轴的距离最大时-x轴距离最小时\n X['dimension_x'] = np.absolute(X.groupby(['molecule_name'])['x_x'].transform('max') - X.groupby(['molecule_name'])['x_x'].transform('min'))\n X['dimension_y'] = np.absolute(X.groupby(['molecule_name'])['y_x'].transform('max') - X.groupby(['molecule_name'])['y_x'].transform('min'))\n X['dimension_z'] = np.absolute(X.groupby(['molecule_name'])['z_x'].transform('max') - X.groupby(['molecule_name'])['z_x'].transform('min'))\n\n X['molecule_dist_mean_x'] = X.groupby(['molecule_name'])['dist_mean_x'].transform('mean')\n X['molecule_dist_mean_y'] = X.groupby(['molecule_name'])['dist_mean_y'].transform('mean')\n X['molecule_dist_mean_bond_x'] = X.groupby(['molecule_name'])['dist_mean_bond_x'].transform('mean')\n X['molecule_dist_mean_bond_y'] = X.groupby(['molecule_name'])['dist_mean_bond_y'].transform('mean')\n X['molecule_dist_range_x'] = X.groupby(['molecule_name'])['dist_mean_x'].transform('max') - X.groupby(['molecule_name'])['dist_mean_x'].transform('min')\n X['molecule_dist_range_y'] = X.groupby(['molecule_name'])['dist_mean_y'].transform('max') - X.groupby(['molecule_name'])['dist_mean_y'].transform('min')\n\n X['molecule_type_dist_min'] = X.groupby(['molecule_name','type'])['distance'].transform('min') \n X['molecule_type_dist_max'] = X.groupby(['molecule_name','type'])['distance'].transform('max') \n X['molecule_dist_mean_no_bond_x'] = X.groupby(['molecule_name'])['dist_mean_no_bond_x'].transform('mean')\n X['molecule_dist_mean_no_bond_y'] = X.groupby(['molecule_name'])['dist_mean_no_bond_y'].transform('mean')\n X['molecule_atom_index_0_dist_min'] = X.groupby(['molecule_name', 'atom_index_0'])['distance'].transform('min') #new variable - dont include\n X['molecule_atom_index_0_dist_std'] = X.groupby(['molecule_name', 'atom_index_0'])['distance'].transform('std') #new variable - dont include\n \n X['molecule_atom_index_0_dist_min_div'] = X['molecule_atom_index_0_dist_min']/X['distance'] #new variable - include\n X['molecule_atom_index_0_dist_std_div'] = X['molecule_atom_index_0_dist_std']/X['distance'] #new variable - include\n X['molecule_atom_index_1_dist_min'] = X.groupby(['molecule_name', 'atom_index_1'])['distance'].transform('min') #new variable - include\n X['molecule_atom_index_1_dist_mean'] = X.groupby(['molecule_name', 'atom_index_1'])['distance'].transform('mean') #new variable - include\n X['molecule_atom_index_1_dist_min_div'] = X['molecule_atom_index_1_dist_min']/X['distance'] #new variable - include\n\n X['molecule_atom_index_1_dist_mean_div'] = X['molecule_atom_index_1_dist_mean']/X['distance'] #new variable - include\n\n\n X = reduce_mem_usage(X,verbose=False)\n return X\n\n\n# In[3]:\n\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import make_pipeline, make_union\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.ensemble import RandomForestClassifier\nimport lightgbm as lgb\nimport gc\nfrom time import time\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nt0 = time()\n\n\ndef map_atom_info(df_1, df_2, atom_idx):\n df = pd.merge(df_1, df_2, how = 'left',\n left_on = ['molecule_name', f'atom_index_{atom_idx}'],\n right_on = ['molecule_name', 'atom_index'])\n \n df = df.drop('atom_index', axis=1)\n return df\n\n \ndef find_dist(df):\n df_p_0 = df[['x_0', 'y_0', 'z_0']].values\n df_p_1 = df[['x_1', 'y_1', 'z_1']].values\n \n df['dist'] = np.linalg.norm(df_p_0 - df_p_1, axis=1)\n df['dist_inv2'] = 1/df['dist']**2\n df['dist_x'] = (df['x_0'] - df['x_1']) ** 2\n df['dist_y'] = (df['y_0'] - df['y_1']) ** 2\n df['dist_z'] = (df['z_0'] - df['z_1']) ** 2\n return df\n\ndef find_closest_atom(df): \n df_temp = df.loc[:,[\"molecule_name\",\n \"atom_index_0\",\"atom_index_1\",\n \"dist\",\"x_0\",\"y_0\",\"z_0\",\"x_1\",\"y_1\",\"z_1\"]].copy()\n df_temp_ = df_temp.copy()\n df_temp_ = df_temp_.rename(columns={'atom_index_0': 'atom_index_1',\n 'atom_index_1': 'atom_index_0',\n 'x_0': 'x_1',\n 'y_0': 'y_1',\n 'z_0': 'z_1',\n 'x_1': 'x_0',\n 'y_1': 'y_0',\n 'z_1': 'z_0'})\n df_temp_all = pd.concat((df_temp,df_temp_),axis=0)\n\n df_temp_all[\"min_distance\"]=df_temp_all.groupby(['molecule_name', \n 'atom_index_0'])['dist'].transform('min')\n df_temp_all[\"max_distance\"]=df_temp_all.groupby(['molecule_name', \n 'atom_index_0'])['dist'].transform('max')\n \n df_temp = df_temp_all[df_temp_all[\"min_distance\"]==df_temp_all[\"dist\"]].copy()\n df_temp = df_temp.drop(['x_0','y_0','z_0','min_distance'], axis=1)\n df_temp = df_temp.rename(columns={'atom_index_0': 'atom_index',\n 'atom_index_1': 'atom_index_closest',\n 'dist': 'distance_closest',\n 'x_1': 'x_closest',\n 'y_1': 'y_closest',\n 'z_1': 'z_closest'})\n df_temp = df_temp.drop_duplicates(subset=['molecule_name', 'atom_index'])\n \n for atom_idx in [0,1]:\n df = map_atom_info(df,df_temp, atom_idx)\n df = df.rename(columns={'atom_index_closest': f'atom_index_closest_{atom_idx}',\n 'distance_closest': f'distance_closest_{atom_idx}',\n 'x_closest': f'x_closest_{atom_idx}',\n 'y_closest': f'y_closest_{atom_idx}',\n 'z_closest': f'z_closest_{atom_idx}'})\n \n df_temp= df_temp_all[df_temp_all[\"max_distance\"]==df_temp_all[\"dist\"]].copy()\n df_temp = df_temp.drop(['x_0','y_0','z_0','max_distance'], axis=1)\n df_temp= df_temp.rename(columns={'atom_index_0': 'atom_index',\n 'atom_index_1': 'atom_index_farthest',\n 'dist': 'distance_farthest',\n 'x_1': 'x_farthest',\n 'y_1': 'y_farthest',\n 'z_1': 'z_farthest'})\n df_temp = df_temp.drop_duplicates(subset=['molecule_name', 'atom_index'])\n \n for atom_idx in [0,1]:\n df = map_atom_info(df,df_temp, atom_idx)\n df = df.rename(columns={'atom_index_farthest': f'atom_index_farthest_{atom_idx}',\n 'distance_farthest': f'distance_farthest_{atom_idx}',\n 'x_farthest': f'x_farthest_{atom_idx}',\n 'y_farthest': f'y_farthest_{atom_idx}',\n 'z_farthest': f'z_farthest_{atom_idx}'})\n return df\n\n\ndef add_cos_features(df):\n \n df[\"distance_center0\"] = np.sqrt((df['x_0']-df['c_x'])**2 + (df['y_0']-df['c_y'])**2 + (df['z_0']-df['c_z'])**2)\n df[\"distance_center1\"] = np.sqrt((df['x_1']-df['c_x'])**2 + (df['y_1']-df['c_y'])**2 + (df['z_1']-df['c_z'])**2)\n \n df['distance_c0'] = np.sqrt((df['x_0']-df['x_closest_0'])**2 + (df['y_0']-df['y_closest_0'])**2 + (df['z_0']-df['z_closest_0'])**2)\n df['distance_c1'] = np.sqrt((df['x_1']-df['x_closest_1'])**2 + (df['y_1']-df['y_closest_1'])**2 + (df['z_1']-df['z_closest_1'])**2)\n \n df[\"distance_f0\"] = np.sqrt((df['x_0']-df['x_farthest_0'])**2 + (df['y_0']-df['y_farthest_0'])**2 + (df['z_0']-df['z_farthest_0'])**2)\n df[\"distance_f1\"] = np.sqrt((df['x_1']-df['x_farthest_1'])**2 + (df['y_1']-df['y_farthest_1'])**2 + (df['z_1']-df['z_farthest_1'])**2)\n \n vec_center0_x = (df['x_0']-df['c_x'])/(df[\"distance_center0\"]+1e-10)\n vec_center0_y = (df['y_0']-df['c_y'])/(df[\"distance_center0\"]+1e-10)\n vec_center0_z = (df['z_0']-df['c_z'])/(df[\"distance_center0\"]+1e-10)\n \n vec_center1_x = (df['x_1']-df['c_x'])/(df[\"distance_center1\"]+1e-10)\n vec_center1_y = (df['y_1']-df['c_y'])/(df[\"distance_center1\"]+1e-10)\n vec_center1_z = (df['z_1']-df['c_z'])/(df[\"distance_center1\"]+1e-10)\n \n vec_c0_x = (df['x_0']-df['x_closest_0'])/(df[\"distance_c0\"]+1e-10)\n vec_c0_y = (df['y_0']-df['y_closest_0'])/(df[\"distance_c0\"]+1e-10)\n vec_c0_z = (df['z_0']-df['z_closest_0'])/(df[\"distance_c0\"]+1e-10)\n \n vec_c1_x = (df['x_1']-df['x_closest_1'])/(df[\"distance_c1\"]+1e-10)\n vec_c1_y = (df['y_1']-df['y_closest_1'])/(df[\"distance_c1\"]+1e-10)\n vec_c1_z = (df['z_1']-df['z_closest_1'])/(df[\"distance_c1\"]+1e-10)\n \n vec_f0_x = (df['x_0']-df['x_farthest_0'])/(df[\"distance_f0\"]+1e-10)\n vec_f0_y = (df['y_0']-df['y_farthest_0'])/(df[\"distance_f0\"]+1e-10)\n vec_f0_z = (df['z_0']-df['z_farthest_0'])/(df[\"distance_f0\"]+1e-10)\n \n vec_f1_x = (df['x_1']-df['x_farthest_1'])/(df[\"distance_f1\"]+1e-10)\n vec_f1_y = (df['y_1']-df['y_farthest_1'])/(df[\"distance_f1\"]+1e-10)\n vec_f1_z = (df['z_1']-df['z_farthest_1'])/(df[\"distance_f1\"]+1e-10)\n \n vec_x = (df['x_1']-df['x_0'])/df['dist']\n vec_y = (df['y_1']-df['y_0'])/df['dist']\n vec_z = (df['z_1']-df['z_0'])/df['dist']\n \n df[\"cos_c0_c1\"] = vec_c0_x*vec_c1_x + vec_c0_y*vec_c1_y + vec_c0_z*vec_c1_z\n df[\"cos_f0_f1\"] = vec_f0_x*vec_f1_x + vec_f0_y*vec_f1_y + vec_f0_z*vec_f1_z\n \n df[\"cos_c0_f0\"] = vec_c0_x*vec_f0_x + vec_c0_y*vec_f0_y + vec_c0_z*vec_f0_z\n df[\"cos_c1_f1\"] = vec_c1_x*vec_f1_x + vec_c1_y*vec_f1_y + vec_c1_z*vec_f1_z\n \n df[\"cos_center0_center1\"] = vec_center0_x*vec_center1_x + vec_center0_y*vec_center1_y + vec_center0_z*vec_center1_z\n \n df[\"cos_c0\"] = vec_c0_x*vec_x + vec_c0_y*vec_y + vec_c0_z*vec_z\n df[\"cos_c1\"] = vec_c1_x*vec_x + vec_c1_y*vec_y + vec_c1_z*vec_z\n \n df[\"cos_f0\"] = vec_f0_x*vec_x + vec_f0_y*vec_y + vec_f0_z*vec_z\n df[\"cos_f1\"] = vec_f1_x*vec_x + vec_f1_y*vec_y + vec_f1_z*vec_z\n \n df[\"cos_center0\"] = vec_center0_x*vec_x + vec_center0_y*vec_y + vec_center0_z*vec_z\n df[\"cos_center1\"] = vec_center1_x*vec_x + vec_center1_y*vec_y + vec_center1_z*vec_z\n\n return df\n\ndef dummies(df, list_cols):\n for col in list_cols:\n df_dummies = pd.get_dummies(df[col], drop_first=True, \n prefix=(str(col)))\n df = pd.concat([df, df_dummies], axis=1)\n return df\n\n\ndef add_qm9_features(df):\n data_qm9 = pd.read_pickle('../input/quantum-machine-9-qm9/data.covs.pickle')\n to_drop = ['type', \n 'linear', \n 'atom_index_0', \n 'atom_index_1', \n 'scalar_coupling_constant', \n 'U', 'G', 'H', \n 'mulliken_mean', 'r2', 'U0']\n data_qm9 = data_qm9.drop(columns = to_drop, axis=1)\n data_qm9 = reduce_mem_usage(data_qm9,verbose=False)\n df = pd.merge(df, data_qm9, how='left', on=['molecule_name','id'])\n del data_qm9\n \n df = dummies(df, ['type', 'atom_1'])\n return df\n\ndef get_features(df, struct):\n for atom_idx in [0,1]:\n df = map_atom_info(df, struct, atom_idx)\n df = df.rename(columns={'atom': f'atom_{atom_idx}',\n 'x': f'x_{atom_idx}',\n 'y': f'y_{atom_idx}',\n 'z': f'z_{atom_idx}'})\n struct['c_x'] = struct.groupby('molecule_name')['x'].transform('mean')\n struct['c_y'] = struct.groupby('molecule_name')['y'].transform('mean')\n struct['c_z'] = struct.groupby('molecule_name')['z'].transform('mean')\n\n\n return df\n\ndef comp_score (y_true, y_pred, jtype):\n df = pd.DataFrame()\n df['y_true'] , df['y_pred'], df['jtype'] = y_true , y_pred, jtype\n score = 0 \n for t in jtype.unique():\n score_jtype = np.log(mean_absolute_error(df[df.jtype==t]['y_true'],df[df.jtype==t]['y_pred']))\n score += score_jtype\n print(f'{t} : {score_jtype}')\n score /= len(jtype.unique())\n return score\n\ndef feat_from_structures(df, st):\n df = pd.merge(df,st,how='left',left_on=['molecule_name','atom_index_0'], right_on=['molecule_name','atom_index'])\n df = pd.merge(df,st,how='left',left_on=['molecule_name','atom_index_1'], right_on=['molecule_name','atom_index'])\n n_atoms = st.groupby(['molecule_name','atom'])['atom'].size().to_frame(name = 'count').reset_index()\n n_atoms_df = n_atoms.pivot_table('count',['molecule_name'], 'atom')\n n_atoms_df.fillna(0,inplace=True)\n df = pd.merge(df,n_atoms_df,on=['molecule_name'],how='left')\n del n_atoms\n gc.collect()\n return df\n\natomic_radius = {'H': 0.43, 'C': 0.82, 'N': 0.8, 'O': 0.78, 'F': 0.76}\nelectronegativity = {'H': 2.2, 'C': 2.55, 'N': 3.04, 'O': 3.44, 'F': 3.98}\nstruct = pd.read_csv('../input/champs-scalar-coupling/structures.csv')\ntrain = pd.read_csv('../input/champs-scalar-coupling/train.csv')\ntest = pd.read_csv('../input/champs-scalar-coupling/test.csv')\n\n\n# In[4]:\n\n\nstruct = struct_change(struct)\nprint('struct')\ndisplay(struct.head())\nprint('train')\ntrain = feat_from_structures(train,struct)\ntrain = more_feas(train)\ndisplay(train.head())\nprint('test')\ntest = feat_from_structures(test,struct)\ntest = more_feas(test)\ndisplay(test.head())\n\n\n# In[5]:\n\n\nprint(train.shape)\nprint(test.shape)\n\n\n# In[6]:\n\n\ntrain.columns\n\n\n# In[7]:\n\n\nneed_feas=['id', \n 'n_bonds_x', 'n_no_bonds_x', 'dist_mean_x',\n 'dist_median_x', 'dist_std_bond_x', 'dist_mean_bond_x',\n 'dist_median_bond_x', 'dist_mean_no_bond_x', 'dist_std_no_bond_x',\n 'dist_median_no_bond_x', \n 'range_dist_x', 'dist_bond_min_x', 'dist_bond_max_x',\n 'range_dist_bond_x', 'dist_no_bond_min_x', 'dist_no_bond_max_x',\n 'range_dist_no_bond_x', 'n_diff_x', \n 'n_bonds_y', 'n_no_bonds_y', \n 'dist_median_y', 'dist_std_bond_y', 'dist_mean_bond_y',\n 'dist_median_bond_y', 'dist_mean_no_bond_y', 'dist_std_no_bond_y',\n 'dist_median_no_bond_y', \n 'range_dist_y', 'dist_bond_min_y', 'dist_bond_max_y',\n 'range_dist_bond_y', 'dist_no_bond_min_y', 'dist_no_bond_max_y',\n 'range_dist_no_bond_y', 'n_diff_y', 'C', 'F', 'H', 'N', 'O', \n 'x_dist_abs', 'y_dist_abs', 'z_dist_abs',\n 'inv_distance3', 'dimension_x', 'dimension_y',\n 'dimension_z', \n 'molecule_dist_mean_bond_x', 'molecule_dist_mean_bond_y',\n 'molecule_dist_range_x', 'molecule_dist_range_y',\n \n 'molecule_dist_mean_no_bond_x', 'molecule_dist_mean_no_bond_y',\n \n 'molecule_atom_index_0_dist_min_div',\n 'molecule_atom_index_0_dist_std_div', \n 'molecule_atom_index_1_dist_min_div',\n 'molecule_atom_index_1_dist_mean_div']\n\n\n# In[8]:\n\n\ntrain_df = train[need_feas]\ntest_df = test[need_feas]\n\n\n# In[9]:\n\n\nprint(train_df.shape)\nprint(test_df.shape)\ndisplay(train_df.head())\ndisplay(test_df.head())\n\n\n# In[10]:\n\n\ntrain_df.to_csv('/kaggle/working/bond_train.csv.gz',compression='gzip',index=False)\ntest_df.to_csv('/kaggle/working/bond_test.csv.gz',compression='gzip',index=False)\n\n", "repo_name": "Liangsancun/kaggle", "sub_path": "代码及notebook/代码_py版/构造特征群/bond.py", "file_name": "bond.py", "file_ext": "py", "file_size_in_byte": 23737, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "warnings.simplefilter", "line_number": 15, "usage_type": "call"}, {"api_name": "sklearn.base.BaseEstimator", "line_number": 17, "usage_type": "name"}, {"api_name": "sklearn.base.TransformerMixin", "line_number": 17, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.logical_and", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 42, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 42, "usage_type": "attribute"}, {"api_name": "sklearn.model_selection._split.check_cv", "line_number": 45, "usage_type": "call"}, {"api_name": "sklearn.base.is_classifier", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 49, "usage_type": "call"}, {"api_name": "sklearn.base.clone", "line_number": 51, "usage_type": "call"}, {"api_name": "sklearn.model_selection._split.check_cv", "line_number": 56, "usage_type": "call"}, {"api_name": "sklearn.base.is_classifier", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 57, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 57, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.iinfo", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.int8", "line_number": 77, "usage_type": "attribute"}, {"api_name": "numpy.int8", "line_number": 78, "usage_type": "attribute"}, {"api_name": "numpy.iinfo", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.int16", "line_number": 79, "usage_type": "attribute"}, {"api_name": "numpy.int16", "line_number": 80, "usage_type": "attribute"}, {"api_name": "numpy.iinfo", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 81, "usage_type": "attribute"}, {"api_name": "numpy.int32", "line_number": 82, "usage_type": "attribute"}, {"api_name": "numpy.iinfo", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.int64", "line_number": 83, "usage_type": "attribute"}, {"api_name": "numpy.int64", "line_number": 84, "usage_type": "attribute"}, {"api_name": "numpy.finfo", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.float16", "line_number": 86, "usage_type": "attribute"}, {"api_name": "numpy.float16", "line_number": 87, "usage_type": "attribute"}, {"api_name": "numpy.finfo", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 88, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 89, "usage_type": "attribute"}, {"api_name": "numpy.float64", "line_number": 91, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.roll", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.roll", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.roll", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 129, "usage_type": "attribute"}, {"api_name": "numpy.roll", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 130, "usage_type": "attribute"}, {"api_name": "numpy.roll", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.roll", "line_number": 134, "usage_type": "call"}, {"api_name": "numpy.roll", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 148, "usage_type": "attribute"}, {"api_name": "numpy.nanmedian", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 149, "usage_type": "attribute"}, {"api_name": "numpy.nanstd", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 150, "usage_type": "attribute"}, {"api_name": "numpy.nanmean", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 151, "usage_type": "attribute"}, {"api_name": "numpy.nanmedian", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 152, "usage_type": "attribute"}, {"api_name": "numpy.nanmean", "line_number": 153, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 153, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 153, "usage_type": "attribute"}, {"api_name": "numpy.nanstd", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 154, "usage_type": "attribute"}, {"api_name": "numpy.nanmedian", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 155, "usage_type": "attribute"}, {"api_name": "numpy.nanstd", "line_number": 156, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 156, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 156, "usage_type": "attribute"}, {"api_name": "numpy.nanmin", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 157, "usage_type": "attribute"}, {"api_name": "numpy.nanmax", "line_number": 158, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 158, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 158, "usage_type": "attribute"}, {"api_name": "numpy.absolute", "line_number": 159, "usage_type": "call"}, {"api_name": "numpy.nanmin", "line_number": 160, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 160, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 160, "usage_type": "attribute"}, {"api_name": "numpy.nanmax", "line_number": 161, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 161, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 161, "usage_type": "attribute"}, {"api_name": "numpy.absolute", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.nanmin", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 163, "usage_type": "attribute"}, {"api_name": "numpy.nanmax", "line_number": 164, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 164, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 164, "usage_type": "attribute"}, {"api_name": "numpy.absolute", "line_number": 165, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.around", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 174, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 174, "usage_type": "attribute"}, {"api_name": "numpy.absolute", "line_number": 179, "usage_type": "call"}, {"api_name": "numpy.absolute", "line_number": 180, "usage_type": "call"}, {"api_name": "numpy.absolute", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.absolute", "line_number": 184, "usage_type": "call"}, {"api_name": "numpy.absolute", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.absolute", "line_number": 186, "usage_type": "call"}, {"api_name": "time.time", "line_number": 230, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 234, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 246, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 246, "usage_type": "attribute"}, {"api_name": "pandas.concat", "line_number": 266, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 313, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 314, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 316, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 317, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 319, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 320, "usage_type": "call"}, {"api_name": "pandas.get_dummies", "line_number": 371, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 373, "usage_type": "call"}, {"api_name": "pandas.read_pickle", "line_number": 378, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 388, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 409, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 413, "usage_type": "call"}, {"api_name": "sklearn.metrics.mean_absolute_error", "line_number": 413, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 420, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 421, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 425, "usage_type": "call"}, {"api_name": "gc.collect", "line_number": 427, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 432, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 433, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 434, "usage_type": "call"}]} +{"seq_id": "14636112916", "text": "#Import the requests package that allows us to access the Metro Transit API\r\nimport requests\r\n\r\n#Method to get the directions of the selected route\r\ndef getDirections():\r\n #Global variable to hold the users route\r\n global myRoute\r\n myRoute = input(\"Which route do you want to take:\")\r\n\r\n link = 'http://svc.metrotransit.org/NexTrip/Directions/' + myRoute + '?format=json'\r\n d = requests.get(link)\r\n #Global variable to hold the directions list returned from the API\r\n global directions\r\n directions = d.json()\r\n try:\r\n #Global variable to hold the two directions of the bus\r\n global dir1,dir2\r\n dir1= directions[0].get('Text')\r\n dir2= directions[1].get('Text')\r\n except IndexError:\r\n print(\"Wrong route entered!\")\r\n else:\r\n getStops()\r\n\r\n#Method to get the stops of a particular route and direction\r\ndef getStops():\r\n #Global variable to hold the users selected directions\r\n global myDir\r\n myDir = int(input('Enter 1 for ' + dir1 + ' and 2 for ' + dir2 + ':'))\r\n if myDir == 1:\r\n routeCode = directions[0].get('Value')\r\n elif myDir == 2:\r\n routeCode = directions[1].get('Value')\r\n else:\r\n print(\"Wrong choice entered!\")\r\n return\r\n\r\n link = 'http://svc.metrotransit.org/NexTrip/Stops/' + myRoute + '/' + routeCode + '?format=json'\r\n s = requests.get(link)\r\n #Global variable to hold the list of all stops of a particular route\r\n global stops\r\n stops = s.json()\r\n getTimes()\r\n\r\n#Method to get the times of the buses at a particular stop\r\ndef getTimes():\r\n #Prints all the stops to the user\r\n for stop in stops:\r\n print(stop.get('Text') + \":\" + stop.get('Value'))\r\n myStop = input(\"Enter a stop code from the list above:\")\r\n link = \"http://svc.metrotransit.org/NexTrip/\"+ myRoute +'/'+ str(myDir) + \"/\" + myStop +\"?format=json\"\r\n st = requests.get(link)\r\n myTimes = st.json()\r\n \r\n #Prints the times to the users\r\n try:\r\n print(\"The next bus is in/at \" + myTimes[0].get('DepartureText'))\r\n except IndexError:\r\n print(\"Error! Please check the stop code entered. If you entered the correct code, there is no bus available at this stop\")\r\n\r\n\r\ngetDirections()", "repo_name": "VihanAgarwal97/InternetComputing", "sub_path": "CW_0_MetroTransit/getDepartureTimes.py", "file_name": "getDepartureTimes.py", "file_ext": "py", "file_size_in_byte": 2239, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "requests.get", "line_number": 11, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 39, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 52, "usage_type": "call"}]} +{"seq_id": "73435802946", "text": "import numpy as np\r\nimport os\r\nimport src.P0 as P0\r\nimport random\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\nimport cv2\r\n\r\nfrom src import config\r\n\r\n\r\ndef readBWColor(folderName,randomizar=False):\r\n print(\"Reading Images and Resizing....\")\r\n cwd = folderName\r\n\r\n nameImages = [f for f in listdir(cwd) if isfile(join(cwd, f))]\r\n if randomizar:\r\n random.shuffle(nameImages) # randomizes list in its place\r\n\r\n images = []\r\n imagesColor = []\r\n get_image = lambda route: os.path.join(cwd, route)\r\n\r\n for item in nameImages:\r\n tmp = np.uint8(P0.readIm(get_image(item), 0))\r\n tmpColor = np.uint8(P0.readIm(get_image(item), 1))\r\n if config.resizeImage == 1:\r\n basewidth = config.basewidth\r\n wpercent = (basewidth/float(tmp.shape[0]))\r\n hsize = int((float(tmp.shape[1]) * float(wpercent)))\r\n\r\n tmp = cv2.resize(tmp, (hsize,basewidth),interpolation = cv2.INTER_CUBIC)\r\n tmpColor = cv2.resize(tmpColor, (hsize,basewidth), interpolation=cv2.INTER_CUBIC)\r\n\r\n #Para guardar archivo\r\n #ruta = os.path.join(\"C:/Users/alvar/iCloudDrive/COSI/2nd Semester UGR/Computer Vision/Final Project/Own Development/images/CustomPano2/small/\", str(item))\r\n #cv2.imwrite(ruta, cv2.cvtColor(tmpColor, cv2.COLOR_BGR2RGB))\r\n\r\n images.append(tmp)\r\n imagesColor.append(tmpColor) # we convert to int because opencv argues later on to display in color\r\n\r\n print(\"Reading Images and Resizing: DONE\")\r\n return images, imagesColor\r\n", "repo_name": "DevAlvaroF/Automatic-Blind-Panorama-Stitcher", "sub_path": "src/imgIO.py", "file_name": "imgIO.py", "file_ext": "py", "file_size_in_byte": 1570, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.listdir", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 16, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "numpy.uint8", "line_number": 25, "usage_type": "call"}, {"api_name": "src.P0.readIm", "line_number": 25, "usage_type": "call"}, {"api_name": "src.P0", "line_number": 25, "usage_type": "name"}, {"api_name": "numpy.uint8", "line_number": 26, "usage_type": "call"}, {"api_name": "src.P0.readIm", "line_number": 26, "usage_type": "call"}, {"api_name": "src.P0", "line_number": 26, "usage_type": "name"}, {"api_name": "src.config.resizeImage", "line_number": 27, "usage_type": "attribute"}, {"api_name": "src.config", "line_number": 27, "usage_type": "name"}, {"api_name": "src.config.basewidth", "line_number": 28, "usage_type": "attribute"}, {"api_name": "src.config", "line_number": 28, "usage_type": "name"}, {"api_name": "cv2.resize", "line_number": 32, "usage_type": "call"}, {"api_name": "cv2.INTER_CUBIC", "line_number": 32, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.INTER_CUBIC", "line_number": 33, "usage_type": "attribute"}]} +{"seq_id": "6478494238", "text": "from flask import abort, current_app\n\n\nclass AuthChecker:\n\n def __init__(self, db):\n self._db = db\n\n def check(self, resource, action, user_id):\n\n user = current_app.db['users'].user_id.fetchone(lambda x: x == user_id)\n if not user:\n abort(403)\n\n user_role = current_app.db['user_roles'].username.fetchone(lambda x: x == user['username'])\n\n if not user_role:\n abort(403)\n\n roles_permissions = current_app.db['roles_permissions'].role.query(lambda x: x == user_role['role'])\n\n for roles_permission in roles_permissions:\n perm_id = int(roles_permission['permission'])\n permission = current_app.db['permissions'].permission_id.fetchone(lambda x: x == perm_id)\n\n\n if permission['resource'] != resource:\n continue\n\n amount_of_actions = permission['actions']\n if action in amount_of_actions:\n\n return True\n\n abort(403)\n\n\n\n", "repo_name": "sa1am9/game-store-rd1", "sub_path": "game_store/auth/permission.py", "file_name": "permission.py", "file_ext": "py", "file_size_in_byte": 985, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "flask.current_app.db", "line_number": 11, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 11, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 13, "usage_type": "call"}, {"api_name": "flask.current_app.db", "line_number": 15, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 15, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 18, "usage_type": "call"}, {"api_name": "flask.current_app.db", "line_number": 20, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 20, "usage_type": "name"}, {"api_name": "flask.current_app.db", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 24, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 35, "usage_type": "call"}]} +{"seq_id": "2985276287", "text": "import sys\nfrom time import sleep\n\nimport pygame\n\nfrom alien import Alien\nfrom bullet import Bullet\nfrom button import Button\nfrom game_stats import GameStats\nfrom settings import Settings\nfrom scoreboard import Scoreboard\nfrom ship import Ship\n\n\n\nclass AlienInvasion:\n\n def __init__(self):\n '''Инициализирует игру и создает игровые ресурсы'''\n pygame.init()\n self.settings = Settings()\n\n self.screen = pygame.display.set_mode(\n (self.settings.screen_width, self.settings.screen_height)\n )\n pygame.display.set_caption('Alien Invasion')\n\n self.stats = GameStats(self)\n self.sb = Scoreboard(self)\n\n self.ship = Ship(self)\n self.bullets = pygame.sprite.Group()\n self.aliens = pygame.sprite.Group()\n\n self._create_fleet()\n \n self.play_button = Button(self, 'Play')\n\n def run_game(self):\n while True:\n self._check_events()\n\n if self.stats.game_active:\n self.ship.moving()\n self._update_bullets()\n self._update_aliens()\n \n self._update_screen()\n \n def _check_events(self):\n '''Обрабатывает нажатия клавиш и события мыши'''\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n if event.type == pygame.KEYDOWN:\n self._check_keydown_events(event)\n elif event.type == pygame.KEYUP:\n self._check_keyup_events(event)\n if event.type == pygame.MOUSEBUTTONDOWN:\n mouse_pos = pygame.mouse.get_pos()\n self._check_play_button(mouse_pos)\n\n def _check_keydown_events(self, event):\n '''Реагирует на нажатие клавиш'''\n if event.key == pygame.K_RIGHT:\n self.ship.moving_right = True\n if event.key == pygame.K_LEFT:\n self.ship.moving_left = True\n if event.key == pygame.K_q:\n sys.exit()\n if event.key == pygame.K_SPACE:\n self._fire_bullet()\n if event.key == pygame.K_p:\n if self.stats.game_active:\n return\n self._start_game()\n\n def _check_keyup_events(self, event):\n '''Реагирует на отпускание клавиш'''\n if event.key == pygame.K_RIGHT:\n self.ship.moving_right = False\n if event.key == pygame.K_LEFT:\n self.ship.moving_left = False\n \n def _check_play_button(self, mouse_pos):\n button_clicked = self.play_button.rect.collidepoint(mouse_pos)\n if self.stats.game_active and button_clicked:\n return\n self._start_game()\n self.settings.initialize_dynamic_settings()\n\n def _start_game(self): \n self.stats.reset_stats() \n self.stats.game_active = True\n self.sb.prep_score()\n self.sb.prep_level()\n self.sb.prep_ships()\n\n self.aliens.empty()\n self.bullets.empty()\n\n self._create_fleet()\n self.ship.center_ship()\n\n pygame.mouse.set_visible(False)\n\n def _fire_bullet(self):\n '''Создание нового снаряда и включение его в группу bullets'''\n if len(self.bullets) < self.settings.bullets_allowed:\n new_bullet = Bullet(self)\n self.bullets.add(new_bullet)\n\n def _update_bullets(self):\n '''Обновляет позиции снарядов и удаляет старые пули'''\n self.bullets.update()\n\n for bullet in self.bullets.copy():\n if bullet.rect.bottom <= 0:\n self.bullets.remove(bullet)\n \n self._check_bullet_alien_collisions()\n\n def _check_bullet_alien_collisions(self):\n '''Обработка попаданий в пришельцев'''\n collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)\n\n if collisions:\n for aliens in collisions.values():\n self.stats.score += self.settings.alien_points * len(aliens)\n self.sb.prep_score()\n self.sb.check_high_score()\n\n if self.aliens:\n return\n self.bullets.empty()\n self._create_fleet()\n self.settings.increase_speed()\n \n self.stats.level += 1\n self.sb.prep_level()\n \n def _update_aliens(self):\n '''\n Проверяет, достиг ли флот края экрана \n и обновляет пришельцев во флоте\n '''\n self._check_fleet_edges()\n self.aliens.update()\n\n '''Проверка столкновения корабля и пришельцев'''\n if pygame.sprite.spritecollideany(self.ship, self.aliens):\n self._ship_hit()\n self._check_aliens_bottom()\n\n def _ship_hit(self):\n '''Обработка столкновения корабля с пришельцем'''\n if self.stats.ship_left <= 0:\n self.stats.game_active = False\n pygame.mouse.set_visible(True)\n self.stats.ship_left -= 1\n self.sb.prep_ships()\n\n self.aliens.empty()\n self.bullets.empty()\n\n self._create_fleet()\n self.ship.center_ship()\n\n sleep(0.5)\n\n def _check_aliens_bottom(self):\n '''Проверка касания пришельцев нижнего края экрана'''\n screen_rect = self.screen.get_rect()\n for alien in self.aliens.sprites():\n if alien.rect.bottom >= screen_rect.bottom:\n self._ship_hit()\n break\n\n def _create_fleet(self):\n '''создание флота пришельцев'''\n alien = Alien(self)\n alien_width, alien_height = alien.rect.size\n available_space_x = self.settings.screen_width - (2 * alien_width)\n number_aliens_x = available_space_x // (2 * alien_width)\n\n '''Определяет количество рядов, помещающихся на экране'''\n ship_height = self.ship.rect.height\n available_space_y = (self.settings.screen_height - \n (3 * alien_height) - ship_height)\n number_rows = available_space_y // (2 * alien_height)\n\n for row_number in range(number_rows):\n [self._create_alien(alien_number, row_number) \n for alien_number in range(number_aliens_x)]\n \n def _create_alien(self, alien_number, row_number):\n alien = Alien(self)\n alien_width, alien_height = alien.rect.size\n alien.x = alien_width + 2 * alien_width * alien_number\n alien.rect.x = alien.x\n alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number\n self.aliens.add(alien)\n\n def _check_fleet_edges(self):\n '''Реагирует на достижение пришельцем конца экрана'''\n for alien in self.aliens.sprites():\n if alien.check_edges():\n self._change_fleet_direction()\n break\n \n def _change_fleet_direction(self):\n '''Опускает флот и меняет направление'''\n for alien in self.aliens.sprites():\n alien.rect.y += self.settings.fleet_drop_speed\n self.settings.fleet_direction *= -1\n\n def _update_screen(self):\n '''Обновляет изображения на экране и отображает новый экран'''\n self.screen.fill(self.settings.bg_color)\n for bullet in self.bullets.sprites():\n bullet.draw_bullet()\n self.aliens.draw(self.screen)\n self.ship.blitme()\n self.sb.show_score()\n\n if not self.stats.game_active:\n self.play_button.draw_button()\n\n pygame.display.flip()\n\nif __name__ == '__main__':\n ai = AlienInvasion()\n ai.run_game()\n\n ", "repo_name": "sokolclaw/alien_invasion", "sub_path": "alien_invasion.py", "file_name": "alien_invasion.py", "file_ext": "py", "file_size_in_byte": 8111, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pygame.init", "line_number": 20, "usage_type": "call"}, {"api_name": "settings.Settings", "line_number": 21, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 23, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 26, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 26, "usage_type": "attribute"}, {"api_name": "game_stats.GameStats", "line_number": 28, "usage_type": "call"}, {"api_name": "scoreboard.Scoreboard", "line_number": 29, "usage_type": "call"}, {"api_name": "ship.Ship", "line_number": 31, "usage_type": "call"}, {"api_name": "pygame.sprite.Group", "line_number": 32, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 32, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Group", "line_number": 33, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 33, "usage_type": "attribute"}, {"api_name": "button.Button", "line_number": 37, "usage_type": "call"}, {"api_name": "pygame.event.get", "line_number": 52, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 52, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 53, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 54, "usage_type": "call"}, {"api_name": "pygame.KEYDOWN", "line_number": 55, "usage_type": "attribute"}, {"api_name": "pygame.KEYUP", "line_number": 57, "usage_type": "attribute"}, {"api_name": "pygame.MOUSEBUTTONDOWN", "line_number": 59, "usage_type": "attribute"}, {"api_name": "pygame.mouse.get_pos", "line_number": 60, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 60, "usage_type": "attribute"}, {"api_name": "pygame.K_RIGHT", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pygame.K_LEFT", "line_number": 67, "usage_type": "attribute"}, {"api_name": "pygame.K_q", "line_number": 69, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 70, "usage_type": "call"}, {"api_name": "pygame.K_SPACE", "line_number": 71, "usage_type": "attribute"}, {"api_name": "pygame.K_p", "line_number": 73, "usage_type": "attribute"}, {"api_name": "pygame.K_RIGHT", "line_number": 80, "usage_type": "attribute"}, {"api_name": "pygame.K_LEFT", "line_number": 82, "usage_type": "attribute"}, {"api_name": "pygame.mouse.set_visible", "line_number": 105, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 105, "usage_type": "attribute"}, {"api_name": "bullet.Bullet", "line_number": 110, "usage_type": "call"}, {"api_name": "bullet.rect", "line_number": 118, "usage_type": "attribute"}, {"api_name": "pygame.sprite.groupcollide", "line_number": 125, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 125, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollideany", "line_number": 151, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 151, "usage_type": "attribute"}, {"api_name": "pygame.mouse.set_visible", "line_number": 159, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 159, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 169, "usage_type": "call"}, {"api_name": "alien.rect", "line_number": 175, "usage_type": "attribute"}, {"api_name": "alien.Alien", "line_number": 181, "usage_type": "call"}, {"api_name": "alien.rect", "line_number": 182, "usage_type": "attribute"}, {"api_name": "alien.Alien", "line_number": 197, "usage_type": "call"}, {"api_name": "alien.rect", "line_number": 198, "usage_type": "attribute"}, {"api_name": "alien.x", "line_number": 199, "usage_type": "attribute"}, {"api_name": "alien.rect", "line_number": 200, "usage_type": "attribute"}, {"api_name": "alien.x", "line_number": 200, "usage_type": "attribute"}, {"api_name": "alien.rect", "line_number": 201, "usage_type": "attribute"}, {"api_name": "alien.check_edges", "line_number": 207, "usage_type": "call"}, {"api_name": "alien.rect", "line_number": 214, "usage_type": "attribute"}, {"api_name": "bullet.draw_bullet", "line_number": 221, "usage_type": "call"}, {"api_name": "pygame.display.flip", "line_number": 229, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 229, "usage_type": "attribute"}]} +{"seq_id": "42943738874", "text": "from pyspark.sql import SparkSession,Row\nfrom pyspark.sql.functions import count,expr,col,count_distinct\nfrom unittest import TestCase\n\n\nclass TestFriends(TestCase):\n def setUp(self) -> None:\n self.spark=SparkSession.builder.appName('Test').getOrCreate()\n self.file=self.spark.read.option('header','true').option('inferschema','true').csv('fakefriends-header.csv')\n self.mockData=[\n ('500','Usmonov','20','2'),\n ('501','Anderson','30','2')\n ]\n\n def test_countRows(self):\n self.assertEqual(len(self.file.columns),4,msg=\"Counted 4: 'userID', 'name', 'age', 'friends\")\n newRows=self.file.withColumn('friendsWithAge',expr('friends+age'))\n self.assertEqual(len(newRows.columns),5,msg=\"Counted 4: 'userID', 'name', 'age', 'friends,'friendsWithAge\")\n self.spark.stop()\n \n def test_columNames(self):\n new_name=self.file.withColumnRenamed('age','ages')\n self.assertEqual(new_name.columns[2],'ages')\n\n def test_countOutputs(self):\n self.assertEqual(self.file.where('friends ==2').count(),4,msg='Count of people with 2 friends should be 4 in this datframe!')\n new_dataframe=self.spark.createDataFrame(self.mockData)\n combined_df=self.file.union(new_dataframe)\n test_result=combined_df.where(\"friends == 2\").count()\n self.assertEqual(test_result,6)\n \n def test_teensGroupMost(self):\n selectCol=self.file.select('age','friends')\n agg=selectCol.groupBy('age').sum('friends')\n sortAge=agg.orderBy(col('age').asc())\n filterTeen=sortAge.where('age == 18')\n #transfer to RDD\n myRdd=filterTeen.rdd\n result=''\n for element in myRdd.collect():\n result=element[1]\n self.assertEqual(result,2747,msg='The number of friends by 18 year old teens in source') \n \n def test_countDistinct(self):\n countDistinct=self.file.select(count_distinct('age','friends'))\n result=int(countDistinct.collect()[0][0])\n self.assertEqual(result,498)\n\nif __name__ == '__main__':\n TestFriends.main()", "repo_name": "HusanboyUs/pyspark_unittests", "sub_path": "friends.py", "file_name": "friends.py", "file_ext": "py", "file_size_in_byte": 2118, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "unittest.TestCase", "line_number": 6, "usage_type": "name"}, {"api_name": "pyspark.sql.SparkSession.builder.appName", "line_number": 8, "usage_type": "call"}, {"api_name": "pyspark.sql.SparkSession.builder", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession", "line_number": 8, "usage_type": "name"}, {"api_name": "pyspark.sql.functions.expr", "line_number": 17, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.col", "line_number": 35, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.count_distinct", "line_number": 45, "usage_type": "call"}]} +{"seq_id": "36168731705", "text": "import pytest\n\nfrom tests.common.mock_repositories import CartMockRepository, OrderMockRepository\nfrom domain.order.exceptions import InvalidOrderException\nfrom application.order.services import OrderService\nfrom application.order.dtos import OrderCreateDTO\n\n\n@pytest.fixture()\ndef cart_repository():\n return CartMockRepository()\n\n\n@pytest.fixture()\ndef order_repository():\n return OrderMockRepository()\n\n\n@pytest.fixture\ndef service(order_repository, cart_repository):\n return OrderService(order_repository, cart_repository)\n\n\ndef test_create_order_service_working_correctly(service, cart_repository):\n dto = OrderCreateDTO(\n cart_id=\"exists\",\n name=\"mark\",\n surname=\"mark\",\n street=\"street\",\n city=\"city\",\n country=\"country\",\n postal_code=\"postal code\"\n )\n order = service.create_order(dto)\n cart = cart_repository.find_by(\"exists\")\n assert len(order.items) == len(cart.items)\n assert order.cart_id == cart.id\n assert order.customer.name == dto.name\n assert order.customer.surname == dto.surname\n assert order.shipping_address.street == dto.street\n assert order.shipping_address.city == dto.city\n assert order.shipping_address.country == dto.country\n assert order.shipping_address.postal_code == dto.postal_code\n assert order.total.value == cart.total.value\n assert order.discount.value == sum([discount.value for discount in cart.discounts])\n\n\ndef test_create_order_service_cart_not_found_exception(service):\n dto = OrderCreateDTO(cart_id=\"dfdfdf\")\n with pytest.raises(InvalidOrderException) as error:\n service.create_order(dto)\n\n assert error.value.message == f\"Cart with id {dto.cart_id} does not exists\"\n", "repo_name": "KestutisKazlauskas/shop-api-challange", "sub_path": "tests/order/application/test_order_service.py", "file_name": "test_order_service.py", "file_ext": "py", "file_size_in_byte": 1726, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "tests.common.mock_repositories.CartMockRepository", "line_number": 11, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 9, "usage_type": "call"}, {"api_name": "tests.common.mock_repositories.OrderMockRepository", "line_number": 16, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 14, "usage_type": "call"}, {"api_name": "application.order.services.OrderService", "line_number": 21, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 19, "usage_type": "attribute"}, {"api_name": "application.order.dtos.OrderCreateDTO", "line_number": 25, "usage_type": "call"}, {"api_name": "application.order.dtos.OrderCreateDTO", "line_number": 49, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 50, "usage_type": "call"}, {"api_name": "domain.order.exceptions.InvalidOrderException", "line_number": 50, "usage_type": "argument"}]} +{"seq_id": "25047790105", "text": "import json\n\nfrom keep_alive import keep_alive\nfrom discord.ext import commands\n\ndb = {}\n\n\n# ____________________________\n# |\n# | FUNCTIONS\n# |____________________________\n\ndef init():\n # check if bot has entry in database\n\n with open(\"database.json\", \"r\") as file_name:\n database = json.load(file_name)\n\n print(\"database initialized: {}\".format(database))\n\n\ndef save_db():\n # check if bot has entry in database\n with open(\"database.json\", \"w\") as file_name:\n json.dump(db, file_name)\n\n print(db)\n\n\n# ____________________________\n# |\n# | COMMANDS: General\n# |____________________________\n\nbot = commands.Bot(command_prefix=\"!\")\n\n\n@bot.event\nasync def on_ready():\n print(\"Successfully logged in as {}\".format(bot.user))\n\n\n# new messages and commands will always land here\n@bot.event\nasync def on_message(message):\n # do nothing on messages from this bot\n if message.author == bot.user:\n return\n\n # if its a command, it will land here\n await bot.process_commands(message)\n\n\n# ____________________________\n# |\n# | COMMANDS: adding nicknames for Lichess or chess.com\n# |____________________________\n\n@bot.command()\nasync def addLichess(ctx, args):\n # get variables\n server_id = ctx.message.guild.id\n user_id = ctx.message.author.id\n nickname = args\n\n # check if user exits on Lichess\n\n # add user to database\n if server_id not in db:\n db[server_id] = {}\n\n if \"users\" not in db[server_id]:\n db[server_id][\"users\"] = {}\n\n if user_id not in db[server_id][\"users\"]:\n db[server_id][\"users\"][user_id] = {}\n\n db[server_id][\"users\"][user_id][\"Lichess\"] = nickname\n save_db()\n await ctx.author.send(\"Your account {} on Lichess has been added\".format(nickname))\n\n\n# ____________________________\n# |\n# | COMMANDS: requests and offers\n# |____________________________\n\n@bot.command()\nasync def request(ctx, *args):\n # get variables\n server_id = ctx.message.guild.id\n user_id = ctx.message.author.id\n\n # add user to database\n if server_id not in db:\n db[server_id] = {}\n\n if \"requests\" not in db[server_id]:\n db[server_id][\"requests\"] = {}\n\n try:\n user_request = {\n \"rating-me\": args[0],\n \"time-control\": args[1],\n \"website\": args[2],\n \"rating-you\": args[3],\n \"voice\": args[4]\n }\n\n if len(args) > 5:\n user_request[\"notes\"] = args[5]\n\n db[server_id][\"requests\"][user_id] = user_request\n\n save_db()\n await ctx.author.send(\"Your request has been added!:\\n{}\"\n .format(json.dumps(request)))\n\n except Exception as e:\n print(e)\n await ctx.author.send(\"There was an error accepting your requesting. \"\n \"Make sure your input matches the requirements.\")\n\n\n@bot.command()\nasync def requests(ctx):\n message = \"Here are all the open requests:\\n```\"\n for key in requests:\n message = \"{}\\n{}: {}\".format(message, bot.get_user(key),\n requests[key])\n message = message + \"```\"\n\n await ctx.channel.send(message)\n\n\n# ____________________________\n# |\n# | COMMANDS: requests and offers\n# |____________________________\n\ninit()\nkeep_alive()\n\nwith open(\"bot_token.json\", \"r\") as file:\n data = json.load(file)\n bot.run(data[\"token\"])\n", "repo_name": "sflofty/ChessBot", "sub_path": "src/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 3390, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "json.load", "line_number": 18, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 26, "usage_type": "call"}, {"api_name": "discord.ext.commands.Bot", "line_number": 36, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 36, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 118, "usage_type": "call"}, {"api_name": "keep_alive.keep_alive", "line_number": 143, "usage_type": "call"}, {"api_name": "json.load", "line_number": 146, "usage_type": "call"}]} +{"seq_id": "27254781866", "text": "from argparse import ArgumentParser, Namespace\n\nfrom tqdm import tqdm\n\nfrom textgrid_tools import sync_grid_to_audio\nfrom textgrid_tools_cli.globals import ExecutionResult\nfrom textgrid_tools_cli.helper import (add_directory_argument, add_encoding_argument,\n add_output_directory_argument, add_overwrite_argument,\n get_audio_files, get_grid_files, get_optional,\n parse_existing_directory, read_audio, try_copy_grid,\n try_load_grid, try_save_grid)\nfrom textgrid_tools_cli.logging_configuration import get_file_logger, init_and_get_console_logger\n\n\ndef get_audio_synchronization_parser(parser: ArgumentParser):\n parser.description = \"This command synchronizes the grids minTime and maxTime according to the audio, i.e., if minTime is not zero, then the first interval will be set to start at zero and if the last interval is not ending at the total duration of the audio, it will be adjusted to it.\"\n add_directory_argument(parser)\n parser.add_argument(\"--audio-directory\", type=get_optional(parse_existing_directory), metavar=\"PATH\",\n help=\"directory containing the audio files if not the same directory\")\n add_encoding_argument(parser)\n add_output_directory_argument(parser)\n add_overwrite_argument(parser)\n return app_sync_grid_to_audio\n\n\ndef app_sync_grid_to_audio(ns: Namespace) -> ExecutionResult:\n logger = init_and_get_console_logger(__name__)\n flogger = get_file_logger()\n\n audio_directory = ns.audio_directory\n if audio_directory is None:\n audio_directory = ns.directory\n\n output_directory = ns.output_directory\n if output_directory is None:\n output_directory = ns.directory\n\n grid_files = get_grid_files(ns.directory)\n audio_files = get_audio_files(audio_directory)\n\n common_files = set(grid_files.keys()).intersection(audio_files.keys())\n missing_grid_files = set(audio_files.keys()).difference(grid_files.keys())\n missing_audio_files = set(grid_files.keys()).difference(audio_files.keys())\n\n if len(missing_grid_files) > 0:\n logger.info(f\"{len(missing_grid_files)} grid files missing.\")\n\n if len(missing_audio_files) > 0:\n logger.info(f\"{len(missing_audio_files)} audio files missing.\")\n\n #logger.info(f\"Found {len(common_files)} matching files.\")\n\n total_success = True\n total_changed_anything = False\n\n for file_nr, file_stem in enumerate(tqdm(common_files), start=1):\n flogger.info(f\"Processing {file_stem}\")\n grid_file_out_abs = output_directory / grid_files[file_stem]\n if grid_file_out_abs.exists() and not ns.overwrite:\n flogger.info(\"Grid already exists. Skipped.\")\n continue\n\n grid_file_in_abs = ns.directory / grid_files[file_stem]\n error, grid = try_load_grid(grid_file_in_abs, ns.encoding)\n\n if error:\n flogger.debug(error.exception)\n flogger.error(error.default_message)\n flogger.info(\"Skipped.\")\n continue\n assert grid is not None\n\n audio_file_in_abs = audio_directory / audio_files[file_stem]\n sample_rate, audio_in = read_audio(audio_file_in_abs)\n error, changed_anything = sync_grid_to_audio(grid, audio_in, sample_rate, flogger)\n success = error is None\n total_success &= success\n total_changed_anything |= changed_anything\n\n if not success:\n flogger.error(error.default_message)\n flogger.info(\"Skipped.\")\n continue\n\n if changed_anything:\n error = try_save_grid(grid_file_out_abs, grid, ns.encoding)\n if error is not None:\n flogger.debug(error.exception)\n flogger.error(error.default_message)\n flogger.info(\"Skipped.\")\n total_success = False\n continue\n elif ns.directory != output_directory:\n error = try_copy_grid(grid_file_in_abs, grid_file_out_abs)\n if error is not None:\n flogger.debug(error.exception)\n flogger.error(error.default_message)\n flogger.info(\"Skipped.\")\n total_success = False\n continue\n\n return total_success, total_changed_anything\n", "repo_name": "stefantaubert/textgrid-ipa", "sub_path": "src/textgrid_tools_cli/grid/audio_synchronization.py", "file_name": "audio_synchronization.py", "file_ext": "py", "file_size_in_byte": 4073, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "25", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 15, "usage_type": "name"}, {"api_name": "textgrid_tools_cli.helper.add_directory_argument", "line_number": 17, "usage_type": "call"}, {"api_name": "textgrid_tools_cli.helper.get_optional", "line_number": 18, "usage_type": "call"}, {"api_name": "textgrid_tools_cli.helper.parse_existing_directory", "line_number": 18, "usage_type": "argument"}, {"api_name": "textgrid_tools_cli.helper.add_encoding_argument", "line_number": 20, "usage_type": "call"}, {"api_name": "textgrid_tools_cli.helper.add_output_directory_argument", "line_number": 21, "usage_type": "call"}, {"api_name": "textgrid_tools_cli.helper.add_overwrite_argument", "line_number": 22, "usage_type": "call"}, {"api_name": "argparse.Namespace", "line_number": 26, "usage_type": "name"}, {"api_name": "textgrid_tools_cli.logging_configuration.init_and_get_console_logger", "line_number": 27, "usage_type": "call"}, {"api_name": "textgrid_tools_cli.logging_configuration.get_file_logger", "line_number": 28, "usage_type": "call"}, {"api_name": "textgrid_tools_cli.helper.get_grid_files", "line_number": 38, "usage_type": "call"}, {"api_name": "textgrid_tools_cli.helper.get_audio_files", "line_number": 39, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 56, "usage_type": "call"}, {"api_name": "textgrid_tools_cli.helper.try_load_grid", "line_number": 64, "usage_type": "call"}, {"api_name": "textgrid_tools_cli.helper.read_audio", "line_number": 74, "usage_type": "call"}, {"api_name": "textgrid_tools.sync_grid_to_audio", "line_number": 75, "usage_type": "call"}, {"api_name": "textgrid_tools_cli.helper.try_save_grid", "line_number": 86, "usage_type": "call"}, {"api_name": "textgrid_tools_cli.helper.try_copy_grid", "line_number": 94, "usage_type": "call"}, {"api_name": "textgrid_tools_cli.globals.ExecutionResult", "line_number": 26, "usage_type": "name"}]} +{"seq_id": "10492469128", "text": "from flask import request, Flask, escape, render_template, jsonify\nimport sqlite3\nimport pymysql\nimport requests\nimport json\n\ntype_translate_dict={\n 'speed': 'speed',\n 'velocity': 'speed',\n 'residual_energy': 'soc'\n}\n\n# rawDbName = './raw.db'\n\ndef parse_position(pos_raw):\n if pos_raw > 200:\n return float(pos_raw)/1000000\n else:\n return float(pos_raw)\n\n\ndef dict_factory(cursor, row): \n d = {} \n for idx, col in enumerate(cursor.description): \n d[col[0]] = row[idx] \n return d \n\ndef getRawAllData():\n conn = sqlite3.connect(rawDbName)\n conn.row_factory = dict_factory\n c = conn.cursor()\n cursor = c.execute(\"SELECT Id, Time, Text, UserName FROM MENTION\")\n result = []\n for row in cursor:\n print(row)\n result.append(row)\n conn.close()\n return result\n\n\napp = Flask(__name__)\n\napp.config['JSON_AS_ASCII'] = False\n\n@app.route('/')\ndef hello_world():\n return 'Hello, World!'\n\n@app.route('/user/')\ndef show_user_profile(username):\n # show the user profile for that user\n return 'User %s' % (username)\n\n@app.route('/ht')\ndef ht():\n return render_template('index.html')\n\n@app.route('/base')\ndef base():\n return render_template('base.html')\n\n# 请求全部车辆位置与状态信息\n@app.route('/query/all/location/batch')\ndef query_all_location():\n db_loc = pymysql.connect(host=\"localhost\",user=\"root\",passwd=\"sjtu123\",db=\"xmjl\")\n print(\"/query/all/location/batch\")\n cursor_loc = db_loc.cursor()\n cursor_loc.execute(\"SELECT vin, CAST(create_time AS CHAR) collectTime, create_time, longi_val, lati_val, status, caution_level, caution_flag FROM xmjl_sql WHERE create_time IN (SELECT max(create_time) from xmjl_sql GROUP BY vin);\")\n # cursor.execute(\"SELECT vin, create_time, longi_val, lati_val, status, caution_level, caution_flag FROM xmjl_sql WHERE create_time IN (SELECT max(create_time) from xmjl_sql GROUP BY vin);\")\n raw_data_loc = cursor_loc.fetchall()\n # print(raw_data)\n db_loc.close()\n\n result_data_loc = []\n for item in raw_data_loc:\n result_data_loc.append({\n 'VIN': item[0],\n 'collectTime': item[1],\n 'longitude': item[3],\n 'latitude': item[4],\n 'status': item[5],\n 'caution_level': item[6],\n 'caution_flag': item[7]\n })\n # print(result_data)\n return jsonify(result_data_loc)\n\n# 请求全部车辆的vin信息\n@app.route('/query/all/vin')\ndef query_all_vin():\n db_vin = pymysql.connect(host=\"localhost\",user=\"root\",passwd=\"sjtu123\",db=\"xmjl\")\n print(\"/query/all/vin\")\n cursor_vin = db_vin.cursor()\n cursor_vin.execute(\"SELECT DISTINCT vin FROM xmjl_sql;\")\n # cursor.execute(\"SELECT vin, create_time, longi_val, lati_val, status, caution_level, caution_flag FROM xmjl_sql WHERE create_time IN (SELECT max(create_time) from xmjl_sql GROUP BY vin);\")\n raw_data_vin = cursor_vin.fetchall()\n # print(raw_data_vin)\n db_vin.close()\n\n result_data_vin = []\n for item in raw_data_vin:\n result_data_vin.append({\n 'VIN': item[0],\n # 'collectTime': item[1],\n # 'longitude': item[3],\n # 'latitude': item[4],\n # 'status': item[5],\n # 'caution_level': item[6],\n # 'caution_flag': item[7]\n })\n # print(result_data)\n return jsonify(result_data_vin)\n\n# TODO:再说\n@app.route('/query/history/status')\ndef query_history_status():\n limit = 100\n if (int(request.args.get(\"limit\"))):\n limit = int(request.args.get(\"limit\"))\n print(\"/query/history/status?limit=%d\" % (limit))\n\n@app.route('/query/single/route')\ndef query_single_route():\n limit = 100\n if (int(request.args.get(\"limit\"))):\n limit = int(request.args.get(\"limit\"))\n car_vin = request.args.get(\"car_VIN\")\n print(\"/query/history/status?vin=%s&limit=%d\" % (car_vin,limit))\n\n db_single_route = pymysql.connect(host=\"localhost\",user=\"root\",passwd=\"sjtu123\",db=\"xmjl\")\n cursor_single_route = db_single_route.cursor()\n\n cursor_single_route.execute(\"\\\n SELECT DISTINCT CAST(create_time AS CHAR) collectTime, longi_val, lati_val FROM xmjl_sql \\\n WHERE vin = '%s' and create_time > date_sub(current_timestamp(), interval %d minute) ORDER BY collectTime;\" %\\\n (car_vin, limit))\n raw_data_single_route = cursor_single_route.fetchall()\n db_single_route.close()\n\n result_data_single_route = []\n for item in raw_data_single_route:\n result_data_single_route.append({\n 'collectTime': item[0],\n 'longitude': parse_position(item[1]),\n 'latitude': parse_position(item[2]),\n })\n # print(result_data)\n return jsonify(result_data_single_route)\n\n@app.route('/query/single/history')\ndef query_single_history():\n limit = 100\n if (int(request.args.get(\"limit\"))):\n limit = int(request.args.get(\"limit\"))\n car_vin = request.args.get(\"car_VIN\")\n request_type = request.args.get(\"type\")\n print(\"/query/history/history?vin=%s&type=%s&limit=%d\" % (car_vin,request_type,limit))\n\n db_single_history = pymysql.connect(host=\"localhost\",user=\"root\",passwd=\"sjtu123\",db=\"xmjl\")\n cursor_single_history = db_single_history.cursor()\n\n cursor_single_history.execute(\"\\\n SELECT DISTINCT CAST(create_time AS CHAR) collectTime, %s FROM xmjl_sql \\\n WHERE vin = '%s' and create_time > date_sub(current_timestamp(), interval %d minute) ORDER BY collectTime;\" %\\\n (type_translate_dict[request_type], car_vin, limit))\n raw_data_single_history = cursor_single_history.fetchall()\n db_single_history.close()\n\n result_data_single_history = []\n for item in raw_data_single_history:\n result_data_single_history.append({\n 'collectTime': item[0],\n request_type: item[1],\n })\n # print(result_data)\n return jsonify(result_data_single_history)\n\n@app.route('/query/single/eagle/create')\ndef single_eagle_create():\n url_single_eagle_create=\"http://yingyan.baidu.com/api/v3/entity/add\"\n request_single_eagle_create = request.args.to_dict()\n print(request_single_eagle_create)\n # request_single_eagle_create['service_id'] = int(request_single_eagle_create['service_id'])\n # headers = {\n # \"Content-Type\": \"application/json; charset=UTF-8\"\n # }\n\n print(request_single_eagle_create)\n response_single_eagle_create = requests.post(url_single_eagle_create, data=request_single_eagle_create)\n\n result_single_eagle_create = response_single_eagle_create.text\n print(response_single_eagle_create)\n\n return jsonify(result_single_eagle_create)\n\n\n@app.route('/query/single/info_java')\ndef query_single_infojava():\n car_vin = request.args.get(\"car_VIN\")\n print(\"/query/single/info_java?vin=%s\" % (car_vin))\n\n db_infojava = pymysql.connect(host=\"localhost\",user=\"root\",passwd=\"sjtu123\",db=\"xmjl\")\n print(\"/query/all/location/batch\")\n cursor_infojava = db_infojava.cursor()\n cursor_infojava.execute(\"SELECT vin, CAST(create_time AS CHAR) collectTime, create_time, \\\n status, speed, soc, temperature, longi_val, lati_val, \\\n caution_level, caution_flag \\\n FROM xmjl_sql \\\n WHERE vin = '%s' AND create_time IN (SELECT max(create_time) from xmjl_sql WHERE vin = '%s');\" \\\n % (car_vin, car_vin))\n # cursor.execute(\"SELECT vin, create_time, longi_val, lati_val, status, caution_level, caution_flag FROM xmjl_sql WHERE create_time IN (SELECT max(create_time) from xmjl_sql GROUP BY vin);\")\n raw_data_infojava = cursor_infojava.fetchall()\n # print(raw_data)\n db_infojava.close()\n\n result_data_infojava = []\n for item in raw_data_infojava:\n result_data_infojava.append({\n 'VIN': item[0],\n 'collectTime': item[1],\n 'status': item[3],\n 'speed': item[4],\n 'soc': item[5],\n 'temperature': item[6],\n 'longitude': item[7],\n 'latitude': item[8],\n 'caution_level': item[9],\n 'caution_flag': item[10]\n })\n # print(result_data)\n return jsonify(result_data_infojava)\n\n\n\n@app.route('/js')\ndef js():\n return {\n 'name':'1',\n 'id':'22',\n }\n\n@app.route('/rawAll')\ndef rawAll():\n mentionAll = getRawAllData()\n print(mentionAll)\n return jsonify(mentionAll)\n\nif __name__ == '__main__':\n app.run(\n host='0.0.0.0',\n port=8101,\n )\n", "repo_name": "FrontierSetter/xmjl", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 8471, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "sqlite3.connect", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 41, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 56, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 60, "usage_type": "call"}, {"api_name": "pymysql.connect", "line_number": 65, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 86, "usage_type": "call"}, {"api_name": "pymysql.connect", "line_number": 91, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 112, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 118, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 118, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 118, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 119, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 119, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 119, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 125, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 125, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 125, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 126, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 126, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 126, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 127, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 127, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 127, "usage_type": "name"}, {"api_name": "pymysql.connect", "line_number": 130, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 148, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 153, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 153, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 153, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 154, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 154, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 154, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 155, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 155, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 155, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 156, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 156, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 156, "usage_type": "name"}, {"api_name": "pymysql.connect", "line_number": 159, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 176, "usage_type": "call"}, {"api_name": "flask.request.args.to_dict", "line_number": 181, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 181, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 181, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 189, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 194, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 199, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 199, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 199, "usage_type": "name"}, {"api_name": "pymysql.connect", "line_number": 202, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 231, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 246, "usage_type": "call"}]} +{"seq_id": "6147438625", "text": "import os\nimport sys\nimport glob\nimport torch\n\nsys.path.append(os.path.dirname(os.path.dirname(__file__)))\n\nfrom utils import get_args, get, print_args, get_seed\nfrom logger import set_logger\nfrom model.executors import Trainor, Validator, create_model, create_data_loader\n\n\ndef get_n_best(mode):\n n = 1\n # checking if args is formatted as best-n\n if '-' in mode:\n n = int(mode.split('-')[-1])\n return n\n\n\ndef get_ckpts(path, mode):\n ckpts = glob.glob(path)\n\n # Sort by score\n ckpts = sorted(ckpts, reverse=True)\n\n # Getting n-best models\n if 'best' in mode:\n n = get_n_best(mode)\n ckpts = ckpts[:n]\n return ckpts\n\n\ndef main():\n opts = get_args()\n ensemble_opts = get(opts, 'ensemblor')\n seed = '{}_{}_{}'.format(\n ensemble_opts.mode, ensemble_opts.beam_width, get_seed())\n set_logger(opts.ckpt_dir, seed)\n\n # Nice printing the args\n print_args(opts, ['ensemblor'], seed)\n\n # Create validator, dont give any models yet\n evaluator = Validator(opts=ensemble_opts,\n models=None,\n seed=seed)\n\n # fetching all ckpt according to 'mode\"\n ckpts = get_ckpts(os.path.join(\n evaluator.opts.ckpt_dir, '*.pth'), ensemble_opts.mode)\n # if specific checkpoint is specified\n if ensemble_opts.ckpt is not None:\n ckpts = [os.path.join(evaluator.opts.ckpt_dir, ensemble_opts.ckpt)]\n\n if not ckpts:\n evaluator.logger.settings(\"No checkpoints found\")\n sys.exit()\n\n evaluator.logger.settings(\"Checkpoints are {}\".format(\"\\n\".join(ckpts)))\n\n # Give models to evaluator\n evaluator.models = [create_model(opts=ensemble_opts,\n # we give the first evaluation split's dataloader to model\n dl=evaluator.splits[0][1],\n logger=evaluator.logger,\n state_dict=torch.load(ckpt)).cuda().eval() for ckpt in ckpts]\n\n # Boom\n evaluator.start()\n\n\nif __name__ == \"__main__\":\n main()\n", "repo_name": "Ascensiony/nlp-gpu", "sub_path": "bin/ensemble.py", "file_name": "ensemble.py", "file_ext": "py", "file_size_in_byte": 2079, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sys.path.append", "line_number": 6, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 22, "usage_type": "call"}, {"api_name": "utils.get_args", "line_number": 35, "usage_type": "call"}, {"api_name": "utils.get", "line_number": 36, "usage_type": "call"}, {"api_name": "utils.get_seed", "line_number": 38, "usage_type": "call"}, {"api_name": "logger.set_logger", "line_number": 39, "usage_type": "call"}, {"api_name": "utils.print_args", "line_number": 42, "usage_type": "call"}, {"api_name": "model.executors.Validator", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path", "line_number": 54, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 58, "usage_type": "call"}, {"api_name": "model.executors.create_model", "line_number": 63, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 67, "usage_type": "call"}]} +{"seq_id": "31701158208", "text": "import cv2\nimport numpy as np\nimport sys\nimport os\n\n\n\ncap = cv2.VideoCapture(\"/dev/video0\")\n\n#out_send = cv2.VideoWriter('appsrc ! queue ! videoconvert ! video/x-raw ! omxh264enc ! video/x-h264 ! h264parse ! rtph264pay ! udpsink host=192.168.1.17 port=5000 sync=false',0,25.0,(640,480))\n\nprint('test1')\n\nwhile True:\n ret,frame = cap.read()\n\n if not ret:\n print('empty frame')\n break\n\n #out_send.write(frame)\n os.write( 1, frame.tostring())\n #cv2.imshow('send', frame)\n if cv2.waitKey(1)&0xFF == ord('q'):\n break", "repo_name": "ImbalanceoneRlS/AI-course", "sub_path": "VideoSend/videoSender.py", "file_name": "videoSender.py", "file_ext": "py", "file_size_in_byte": 550, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "cv2.VideoCapture", "line_number": 8, "usage_type": "call"}, {"api_name": "os.write", "line_number": 22, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 24, "usage_type": "call"}]} +{"seq_id": "40166182072", "text": "\nfrom enum import Enum\nimport multiprocessing\nimport threading\nimport time\nimport datetime\nimport queue\n_global_lock = threading.Condition()\ndef _run_target(q, func, args, kwargs):\n\tq.put(func(*args, **kwargs))\n\nclass ProcessWrapState(Enum):\n\tRUNNING = 0\n\tCOMPLETE = 1\n\tERROR = 2\n\tPICKLING_ERROR = 3\n\tPENDING = 4\n\t\nclass ProcessWrap():\n\tdef __init__(self, func, args=[], kwargs={}, callback=None, pid=None, use_thread=False):\n\t\t#call back will send the following: callback(self.state, self.r, self.begin_time, self.end_time, self.pid)\n\t\tself.func = func\n\t\tself.args = args\n\t\tself.kwargs = kwargs\n\t\tself.callback = callback\n\t\tself.state = ProcessWrapState.PENDING\n\t\tself.pid = pid\n\t\tself.use_thread = use_thread\n\t\tself.plock = threading.Condition()\n\t\t\n\tdef start(self):\n\t\tthreading.Thread(target=self._start_process, args=[self.func, self.args, self.kwargs]).start()\n# \t\tself._start_process(self.func, self.args, self.kwargs)\n\tdef kill(self):\n\t\tself.plock.acquire()\n\t\tif self.state == ProcessWrapState.RUNNING:\n\t\t\tself.p.kill()\n\t\tself.plock.release()\n\tdef _start_process(self, func, args, kwargs):\n\t\tself.begin_time = datetime.datetime.now()\n\t\t\n\t\ttrials = 10\n\t\t\n\t\twhile trials > 0:\n\t\t\tself.plock.acquire()\n# \t\t\t_global_lock.acquire()\n\t\t\ttry:\n\t\t\t\tif self.use_thread:\n\t\t\t\t\tq = queue.Queue()\n\t\t\t\t\tp = threading.Thread(target=_run_target, args=[q, func, args, kwargs])\n\t\t\t\telse:\n\t\t\t\t\tq = multiprocessing.Queue()\n\t\t\t\t\tp = multiprocessing.Process(target=_run_target, args=[q, func, args, kwargs])\n\t\t\t\t\t\n\t\t\t\tself.p = p\n\t\t\t\tself.q = q\n\t\t\t\tself.r = None\n\t\t\t\tp.start()\n# \t\t\t\t_global_lock.release()\n\t\t\t\t#threading.Thread(target=self._completion_check).start()\n\t\t\t\tself.plock.release()\n\t\t\t\tself.state = ProcessWrapState.RUNNING\n\t\t\t\tself._completion_check()\n\t\t\t\tbreak\n\t\t\texcept:\n\t\t\t\tprint(\"There could be unexpected exception on multiprocessing. Retrying pid: \", self.pid)\n# \t\t\t\t_global_lock.release()\n\t\t\t#threading.Thread(target=self._completion_check).start()\n\t\t\t\tself.plock.release()\n\t\t\t\ttime.sleep(3)\n\t\t\ttrials -= 1\n\t\t\t\n\t\telse:\n\t\t\tprint(\"Cannot start the process. pid: \") + self.pid\n\tdef _completion_check(self):\n\t\t# Update frequency\n\t\twhile self.p.is_alive() and self.q.empty():\n\t\t\ttime.sleep(0.5)\n\t\t# Try to guess the state: Complete, error, or pickling error?\n\t\t# Deduction is not guaranteed to be accurate.\n\t\t# In the future I may want to add support to corrupted queue.\n\t\tself.plock.acquire()\n# \t\tself.p.join()\n\t\tif not self.q.empty():\n\t\t\tself.r = self.q.get()\n\t\t\tmax_trials = 3\n\t\t\twhile max_trials >= 0:\n\t\t\t\ttry:\n\t\t\t\t\tself.p.join()\n\t\t\t\t\tbreak\n\t\t\t\texcept:\n\t\t\t\t\ttime.sleep(3)\n\t\t\t\t\tmax_trials -= 1\n\t\t\tself.state = ProcessWrapState.COMPLETE\n\t\telse:\n\t\t\tmax_trials = 3\n\t\t\twhile max_trials >= 0:\n\t\t\t\ttry:\n\t\t\t\t\tself.p.join()\n\t\t\t\t\tbreak\n\t\t\t\texcept:\n\t\t\t\t\ttime.sleep(3)\n\t\t\t\t\tmax_trials -= 1\n\t\t\t\n\t\t\tif self.use_thread:\n\t\t\t\tself.state = ProcessWrapState.ERROR\n\t\t\telse:\n\t\t\t\tif self.p.exitcode != 0:\n\t\t\t\t\tself.state = ProcessWrapState.ERROR\n\t\t\t\telif self.p.exitcode == 0:\n\t\t\t\t\tself.state = ProcessWrapState.PICKLING_ERROR\n\t\t\t\telse:\n\t\t\t\t\tassert False\n\t\tself.end_time = datetime.datetime.now()\n\t\t\n\t\tif not self.use_thread:\n\t\t\tself.p.close()\n\t\t\tself.q.close()\n\t\tself.plock.release()\n\t\tif self.callback is not None:\n\t\t\tself.callback(self.state, self.r, self.begin_time, self.end_time, self.pid)\n\n# import dill\ndef _run_target2(q, func, args, kwargs):\n\targs = [dill.loads(arg) for arg in args]\n\tkwargs = {dill.loads(k):dill.loads(arg) for k, arg in kwargs.items()}\n\tq.put(dill.dumps(func(*args, **kwargs)))\n\nclass ProcessWrap2():\n\t# Testing class\n\tdef __init__(self, func, args=[], kwargs={}, callback=None, pid=None, use_thread=False):\n\t\tself.func = func\n\t\tself.args = args\n\t\tself.kwargs = kwargs\n\t\tself.callback = callback\n\t\tself.state = ProcessWrapState.PENDING\n\t\tself.pid = pid\n\t\tself.use_thread = use_thread\n\t\tself.plock = threading.Condition()\n\t\t\n\tdef start(self):\n\t\tthreading.Thread(target=self._start_process, args=[self.func, self.args, self.kwargs]).start()\n# \t\tself._start_process(self.func, self.args, self.kwargs)\n\tdef kill(self):\n\t\tself.plock.acquire()\n\t\tif self.state == ProcessWrapState.RUNNING:\n\t\t\tself.p.kill()\n\t\tself.plock.release()\n\tdef _start_process(self, func, args, kwargs):\n\t\tself.plock.acquire()\n\t\tself.begin_time = datetime.datetime.now()\n\t\t\n\t\tif self.use_thread:\n\t\t\tq = queue.Queue()\n\t\t\tp = threading.Thread(target=_run_target, args=[q, func, args, kwargs])\n\t\telse:\n\t\t\tq = multiprocessing.Queue()\n\t\t\targs = [dill.dumps(arg) for arg in args]\n\t\t\tkwargs = {dill.dumps(k):dill.dumps(arg) for k, arg in kwargs.items()}\n\t\t\t\n\t\t\tp = multiprocessing.Process(target=_run_target, args=[q, func, args, kwargs])\n\t\t\t\n\t\tself.p = p\n\t\tself.q = q\n\t\tself.r = None\n\t\t_global_lock.acquire()\n\t\tp.start()\n\t\t_global_lock.release()\n\t\tself.state = ProcessWrapState.RUNNING\n\t\t#threading.Thread(target=self._completion_check).start()\n\t\tself.plock.release()\n\t\tself._completion_check()\n\t\t\n\tdef _completion_check(self):\n\t\t# Update frequency\n\t\twhile self.p.is_alive() and self.q.empty():\n\t\t\ttime.sleep(0.5)\n\t\t# Try to guess the state: Complete, error, or pickling error?\n\t\t# Deduction is not guaranteed to be accurate.\n\t\t# In the future I may want to add support to corrupted queue.\n\t\tself.plock.acquire()\n# \t\tself.p.join()\n\t\tif not self.q.empty():\n\t\t\tself.r = dill.loads(self.q.get())\n\t\t\tself.p.join()\n\t\t\tself.state = ProcessWrapState.COMPLETE\n\t\telse:\n\t\t\tself.p.join()\n\t\t\tif self.use_thread:\n\t\t\t\tself.state = ProcessWrapState.ERROR\n\t\t\telse:\n\t\t\t\tif self.p.exitcode != 0:\n\t\t\t\t\tself.state = ProcessWrapState.ERROR\n\t\t\t\telif self.p.exitcode == 0:\n\t\t\t\t\tself.state = ProcessWrapState.PICKLING_ERROR\n\t\t\t\telse:\n\t\t\t\t\tassert False\n\t\tself.end_time = datetime.datetime.now()\n\t\t\n\t\tif not self.use_thread:\n\t\t\tself.p.close()\n\t\t\tself.q.close()\n\t\tself.plock.release()\n\t\tif self.callback is not None:\n\t\t\tself.callback(self.state, self.r, self.begin_time, self.end_time, self.pid)\n\n\nfrom collections import OrderedDict, defaultdict\nimport concurrent.futures\nimport logging \nclass ProcessWrapPool():\n\t'''\n\tProcess is not recycled. Hence this is very inefficient for running many short processes. \n\tHowever, it benefits from interruptable Process, and not affected by jupyter's \"stop\" \n\t'''\n\tdef __init__(self, nthread, default_func = None, use_thread=False): #, use_hybrid_process_thread=False \n\t\tself.default_func = default_func\n\t\tself.nthread = nthread\n\t\t\n\t\tself.pending_tasks_lock = threading.Condition() # A lock for accessing pending_tasks and next_pid\n\t\tself.pending_tasks = OrderedDict()\n\t\tself.next_pid = 0\n\t\t\n\t\tself.finished_tasks_lock = threading.Condition() # A lock for accessing finished_tasks\n\t\tself.finished_tasks = set()\n\t\t\n\t\tself.futures_lock = threading.Condition() # A lock for accessing futures and futures_pid_map\n\t\tself.futures = OrderedDict()\n\t\tself.futures_pid_map = OrderedDict() # It is no longer used\n\n\t\tself.closing = False\n\t\t\n\t\tself.use_thread = use_thread\n\t\t# The thread run tills closing is True and no more pending tasks remain.\n\t\tthreading.Thread(target=self._run_pending_tasks).start()\n\t\t\n\t\t\n\tdef run(self, func=None, dependencies=[], args=[], kwargs={}):\n\t\t'''\n\t\t'''\n\t\tif self.closing:\n\t\t\traise ValueError(\"Invalid state\")\n\t\tif func is None:\n\t\t\tfunc = self.default_func\n\t\tself.pending_tasks_lock.acquire()\n\t\tpid = self.next_pid\n\t\tself.next_pid += 1\n\t\tself.pending_tasks[pid] = (func, dependencies, args, kwargs)\n\t\tself.pending_tasks_lock.notify_all()\n\t\tself.pending_tasks_lock.release()\n\t\treturn pid\n\t\n\tdef _run_pending_tasks(self):\n\t\t'''\n\t\tCheck pending tasks and submit them to the pool executor if the dependencies are fulfilled.\n\t\tThe submitted pending tasks are removed from self.pending_tasks\n\t\tThis thread will be run at the beginning, until all pending tasks are complete and close\n\t\t'''\n\t\tself.pending_tasks_lock.acquire()\n\t\twhile not self.closing or len(self.pending_tasks) > 0: # Loop until closing and no more pending tasks remain\n\t\t\t# Check if I can run any jobs from the pending tasks\n\t\t\tself.futures_lock.acquire()\n\t\t\tself.finished_tasks_lock.acquire()\n\t\t\ttotal_running_processes = len(self.futures) - len(self.finished_tasks)\n\t\t\tself.finished_tasks_lock.release()\n\t\t\tself.futures_lock.release()\n\t\t\t\n\t\t\tif total_running_processes < self.nthread:\n\t\t\t\tnidlethread = self.nthread - total_running_processes\n\t\t\t\n\t\t\t\tself.finished_tasks_lock.acquire()\n\t\t\t\tlogging.debug(f\"Checking pending tasks to submit...\")\n\t\t\t\tavailable_to_run_pids = []\n\t\t\t\tfor pid, (func, dependencies, args, kwargs) in self.pending_tasks.items():\n\t\t\t\t\tif len(dependencies) == 0 or all(dependency in self.finished_tasks for dependency in dependencies):\n\t\t\t\t\t\tavailable_to_run_pids.append(pid)\n\t\t\t\tlogging.debug(f\"Total pending pids available to submit: {len(available_to_run_pids)} / {len(self.pending_tasks)}\")\n\t\t\t\tself.finished_tasks_lock.release()\n\t\t\t\t\n\t\t\t\tif len(available_to_run_pids) > 0:\n\t\t\t\t\tfor pid in available_to_run_pids[:nidlethread]:\n\t\t\t\t\t\tfunc, dependencies, args, kwargs = self.pending_tasks.pop(pid)\n\t\t\t\t\t\tpw = ProcessWrap(func, args, kwargs, self._completion_callback, pid, use_thread=self.use_thread)\n\t\t\t\t\t\tpw.start()\n\t\t\t\t\t\t\n\t\t\t\t\t\tself.futures_lock.acquire()\n\t\t\t\t\t\tself.futures[pid] = pw\n\t\t\t\t\t\tself.futures_lock.release()\n\t# \t\t\t\t\tfuture.add_done_callback(self._future_result_update)\n\t\t\t\t\tlogging.info(f\"Remaining pending tasks: {len(self.pending_tasks)}\")\n\t\t\t\telse:\n\t\t\t\t\tself.pending_tasks_lock.wait()\n\t\t\telse:\n\t\t\t\tself.pending_tasks_lock.wait()\n\t\tself.pending_tasks_lock.release()\n\t\n\tdef _completion_callback(self, state, r, begin_time, end_time, pid):\n\t\t'''\n\t\tAdd pids to finished tasks. \n\t\tNotify pending tasks\n\t\t'''\n\t\tself.futures_lock.acquire() # I don't think I need this here\n\t\tself.finished_tasks_lock.acquire()\n\t\tself.finished_tasks.add(pid)\n\t\tlogging.info(f\"{pid} has finished.\")\n\t\t#logging.info(f\"{len(self.finished_tasks)} / {len(self.futures_pid_map)} has completed.\")\n\t\tself.finished_tasks_lock.notify_all()\n\t\tself.finished_tasks_lock.release()\n\t\tself.futures_lock.release()\n\t\t\n\t\tself.pending_tasks_lock.acquire()\n\t\tself.pending_tasks_lock.notify_all()\n\t\tself.pending_tasks_lock.release()\n\t\t\n\n\n\tdef get(self, wait=False):\n\t\t'''\n\t\tA point for synchronization before further job submission. \n\t\tBlock and return all results. \n\t\t'''\n\t\tif wait:\n\t\t\tself.pending_tasks_lock.acquire()\n\t\t\twhile len(self.pending_tasks) > 0:\n\t\t\t\tself.pending_tasks_lock.wait()\n\t\t\tself.pending_tasks_lock.release()\n\t\t\tself.finished_tasks_lock.acquire()\n\t\t\twhile True:\n\t\t\t\tself.futures_lock.acquire()\n\t\t\t\ttotal_running_processes = len(self.futures) - len(self.finished_tasks)\n\t\t\t\tself.futures_lock.release()\n\t\t\t\tif total_running_processes == 0:\n\t\t\t\t\tbreak\n\t\t\t\tlogging.info(f\"Waiting for {total_running_processes} to complete.\")\n\t\t\t\tself.finished_tasks_lock.wait()\n\t\t\tself.finished_tasks_lock.release()\n\n\t\t\t\n\t\tself.finished_tasks_lock.acquire()\n\t\tself.futures_lock.acquire()\n\t\tresults = OrderedDict()\n\t\terror_pids = defaultdict(list)\n\t\tfor pid in sorted(self.finished_tasks):\n\t\t\tpw = self.futures[pid]\n\t\t\tif pw.state == ProcessWrapState.COMPLETE:\n\t\t\t\tresults[pid] = pw.r\n\t\t\telse:\n\t\t\t\terror_pids[pw.state].append(pid)\n\t\tfor pwstate, pids in error_pids.items():\n\t\t\tlogging.warn(f\"Process State {pwstate.name} occurs for the following pids: \" + \",\".join(map(str, pids)))\n\t\tself.futures_lock.release()\n\t\tself.finished_tasks_lock.release()\n\t\treturn results\n\n\tdef cancel(self, pids):\n\t\t'''\n\t\tAttempts to cancel a task if it is still pending. \n\t\tIf a task is being executed or completed, it will be cancelled. \n\t\tSee also kill. \n\t\t'''\n\t\tremoved_from_pending_tasks = []\n\t\tself.pending_tasks_lock.acquire()\n\t\tfor pid in pids:\n\t\t\tif pid in self.pending_tasks:\n\t\t\t\tself.pending_tasks.pop(pid)\n\t\t\t\tremoved_from_pending_tasks.append(pid)\n\t\tself.pending_tasks_lock.notify_all()\n\t\tself.pending_tasks_lock.release()\n\t\t\n# \t\tlogging.info(f\"Removed from pending tasks: {join_str(removed_from_pending_tasks, ',')}\")\n# \t\tlogging.info(f\"Removed from pools: {join_str(removed_from_futures, ',')}\")\n\tdef cancel_all(self):\n\t\t'''\n\t\tAttempts to cancel all pending tasks \n\t\t'''\n\t\tremoved_from_pending_tasks = []\n\t\tself.pending_tasks_lock.acquire()\n\t\tfor pid in list(self.pending_tasks.keys()):\n\t\t\tself.pending_tasks.pop(pid)\n\t\t\tremoved_from_pending_tasks.append(pid)\n\t\tself.pending_tasks_lock.notify_all()\n\t\tself.pending_tasks_lock.release()\n\t\t\n\t\tremoved_from_futures = []\n\t\tself.futures_lock.acquire()\t\t\n\t\tfor pid in self.futures.keys():\n\t\t\tif self.futures[pid].cancel():\n\t\t\t\tremoved_from_futures.append(pid)\n\t\tself.futures_lock.release()\n\t\t\n\tdef kill(self, pids):\n\t\tself.pending_tasks_lock.acquire()\n\t\tself.futures_lock.acquire()\n\t\tfor pid in pids:\n\t\t\tself.futures[pid].kill()\n\t\tself.pending_tasks_lock.notify_all()\n\t\tself.pending_tasks_lock.release()\n\t\tself.futures_lock.release()\n\t\t\n\tdef kill_all(self, pids):\n\t\tself.pending_tasks_lock.acquire()\n\t\tself.futures_lock.acquire()\n\t\tfor pid in list(self.futures.keys()):\n\t\t\tself.futures[pid].kill()\n\t\tself.pending_tasks_lock.notify_all()\n\t\tself.pending_tasks_lock.release()\n\t\tself.futures_lock.release()\n\n# \t\tlogging.info(f\"Removed from pending tasks: {join_str(removed_from_pending_tasks, ',')}\")\n# \t\tlogging.info(f\"Removed from pools: {join_str(removed_from_futures, ',')}\")\n\tdef clear(self):\n\t\t'''\n\t\t'''\n\t\traise NotImplementedError()\n\t\tpass\n\tdef close(self):\n\t\t'''\n\t\tTerminate the MultiProcessRun\n\t\t'''\n\t\tself.closing = True\n\t\t\n\t\t# Notify the pending_tasks_lock so that the thread knows to terminate\n\t\tself.pending_tasks_lock.acquire()\n\t\tself.pending_tasks_lock.notify_all()\n\t\tself.pending_tasks_lock.release()\n\t\t\n\t\tself.get()\n\t\t#self.pool.shutdown()\n\t\t\n\n\tdef __enter__(self): \n\t\treturn self\n\t\n\tdef __exit__(self, type, value, traceback): \n\t\tself.close()\n\t\n\n\n# def run_list(data, func, step, nthread):\n# \tdef f():\n# \t\treturn [func(d) for d in data]\n# \t\t\t\n# \tpool = ProcessWrapPool(nthread)\n# \tfor i in range(0, len(data), step):\n# \t\tpool.run(func, )\n# \t.get()\n# \t", "repo_name": "aldenleung/rmsp", "sub_path": "rmsp/mphelper.py", "file_name": "mphelper.py", "file_ext": "py", "file_size_in_byte": 13761, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "27", "api": [{"api_name": "threading.Condition", "line_number": 8, "usage_type": "call"}, {"api_name": "enum.Enum", "line_number": 12, "usage_type": "name"}, {"api_name": "threading.Condition", "line_number": 29, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 32, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 40, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 40, "usage_type": "attribute"}, {"api_name": "queue.Queue", "line_number": 49, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 50, "usage_type": "call"}, {"api_name": "multiprocessing.Queue", "line_number": 52, "usage_type": "call"}, {"api_name": "multiprocessing.Process", "line_number": 53, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 70, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 78, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 92, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 102, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 114, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 114, "usage_type": "attribute"}, {"api_name": "threading.Condition", "line_number": 139, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 142, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 151, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 151, "usage_type": "attribute"}, {"api_name": "queue.Queue", "line_number": 154, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 155, "usage_type": "call"}, {"api_name": "multiprocessing.Queue", "line_number": 157, "usage_type": "call"}, {"api_name": "multiprocessing.Process", "line_number": 161, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 177, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 198, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 198, "usage_type": "attribute"}, {"api_name": "threading.Condition", "line_number": 220, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 221, "usage_type": "call"}, {"api_name": "threading.Condition", "line_number": 224, "usage_type": "call"}, {"api_name": "threading.Condition", "line_number": 227, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 228, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 229, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 235, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 272, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 277, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 290, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 305, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 334, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 341, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 342, "usage_type": "call"}, {"api_name": "logging.warn", "line_number": 350, "usage_type": "call"}]} +{"seq_id": "43643335083", "text": "from django.conf.urls import patterns, include, url\nfrom django.views.decorators.cache import cache_page\nfrom django.views.generic import TemplateView\nfrom django.views.i18n import javascript_catalog\n\nfrom wirecloud.commons.views import ResourceSearch\nfrom wirecloud.platform import views\nfrom wirecloud.platform.context import views as context_views\nfrom wirecloud.platform.iwidget import views as iwidget_views\nfrom wirecloud.platform.localcatalogue import views as localcatalogue_views\nfrom wirecloud.platform.markets import views as market_views\nfrom wirecloud.platform.plugins import get_plugin_urls\nfrom wirecloud.platform.wiring import views as wiring_views\nfrom wirecloud.platform.preferences import views as preferences_views\nfrom wirecloud.platform.theme import views as theme_views\nfrom wirecloud.platform.widget import views as widget_views\nfrom wirecloud.platform.workspace import views as workspace_views\nfrom wirecloud.platform.testsx import views as testsx_views #sixuan test\n\n\nurlpatterns = patterns('wirecloud.platform.views',\n\n url(r'^$', 'render_root_page', name='wirecloud.root'),\n \n #url(r'^testsx/$', testsx_views.hello),\n\n url(r'^articles/(\\d{4})/$', testsx_views.year_archive),\n \n url(r'^api/features/?$',\n views.FeatureCollection(permitted_methods=('GET',)),\n name='wirecloud.features'),\n\n # i18n\n url(r'^api/i18n/', include('django.conf.urls.i18n')),\n url(r'^api/i18n/js_catalogue/?$',\n cache_page(60 * 60 * 24)(javascript_catalog), {'packages': ()},\n name=\"wirecloud.javascript_translation_catalogue\"),\n\n # Context\n url(r'^api/context/?$',\n context_views.PlatformContextCollection(permitted_methods=('GET',)),\n name='wirecloud.platform_context_collection'),\n\n url(r'^showcase/media/(?P[^/]+)/(?P[^/]+)/(?P[^/]+)/(?P.+)$',\n widget_views.serve_showcase_media,\n name='wirecloud.showcase_media'\n ),\n\n # Resource search\n url(r'^api/search$',\n ResourceSearch(permitted_methods=('GET',)),\n name='wirecloud.resource_search'\n ),\n\n # Widgets\n url(r'^api/resources/?$',\n localcatalogue_views.ResourceCollection(permitted_methods=('GET', 'POST',)),\n name='wirecloud.resource_collection'),\n url(r'^api/resource/(?P[^/]+)/(?P[^/]+)/(?P[^/]+)/?$',\n localcatalogue_views.ResourceEntry(permitted_methods=('DELETE', 'GET')),\n name='wirecloud.resource_entry'),\n url(r'^api/resource/(?P[^/]+)/(?P[^/]+)/?$',\n localcatalogue_views.ResourceEntry(permitted_methods=('DELETE',)),\n name='wirecloud.unversioned_resource_entry'),\n url(r'^api/resource/(?P[^/]+)/(?P[^/]+)/(?P[^/]+)/description/?$',\n localcatalogue_views.ResourceDescriptionEntry(permitted_methods=('GET',)),\n name='wirecloud.resource_description_entry'),\n url(r'^api/widget/(?P[^/]+)/(?P[^/]+)/(?P[^/]+)/xhtml/?$',\n widget_views.WidgetCodeEntry(permitted_methods=('GET',)),\n name='wirecloud.widget_code_entry'),\n\n # IWidgets\n url(r'^api/workspace/(?P\\d+)/tab/(?P\\d+)/iwidgets/?$',\n iwidget_views.IWidgetCollection(permitted_methods=('GET', 'POST', 'PUT',)),\n name='wirecloud.iwidget_collection'\n ),\n url(r'^api/workspace/(?P\\d+)/tab/(?P\\d+)/iwidget/(?P\\d+)/?$',\n iwidget_views.IWidgetEntry(permitted_methods=('GET', 'POST', 'DELETE',)),\n name='wirecloud.iwidget_entry'\n ),\n url(r'^api/workspace/(?P\\d+)/tab/(?P\\d+)/iwidget/(?P\\d+)/preferences/?$',\n iwidget_views.IWidgetPreferences(permitted_methods=('POST',)),\n name='wirecloud.iwidget_preferences'\n ),\n url(r'^api/workspace/(?P\\d+)/tab/(?P\\d+)/iwidget/(?P\\d+)/properties$',\n iwidget_views.IWidgetProperties(permitted_methods=('POST',)),\n name='wirecloud.iwidget_properties'\n ),\n url(r'^api/workspace/(?P\\d+)/tab/(?P\\d+)/iwidget/(?P\\d+)/version/?$',\n iwidget_views.IWidgetVersion(permitted_methods=('PUT',)),\n name='wirecloud.iwidget_version_entry'\n ),\n\n # Preferences\n url(r'^api/preferences/platform/?$',\n preferences_views.PlatformPreferencesCollection(permitted_methods=('GET', 'POST')),\n name='wirecloud.platform_preferences'\n ),\n url(r'^api/workspace/(?P\\d+)/preferences/?$',\n preferences_views.WorkspacePreferencesCollection(permitted_methods=('GET', 'POST')),\n name='wirecloud.workspace_preferences'\n ),\n url(r'^api/workspace/(?P\\d+)/tab/(?P\\d+)/preferences/?$',\n preferences_views.TabPreferencesCollection(permitted_methods=('GET', 'POST')),\n name='wirecloud.tab_preferences'\n ),\n\n url(r'^api/operator/(?P[^/]+)/(?P[^/]+)/(?P[^/]+)/html$',\n wiring_views.OperatorEntry(permitted_methods=('GET',)),\n name='wirecloud.operator_code_entry'\n ),\n\n url(r'^api/markets/?$',\n market_views.MarketCollection(permitted_methods=('GET', 'POST')),\n name='wirecloud.market_collection'\n ),\n url(r'^api/market/(?P[\\w -]+)/?$',\n market_views.MarketEntry(permitted_methods=('DELETE',)),\n name='wirecloud.market_entry'\n ),\n url(r'^api/market/(?P[^/]+)/(?P[\\w -]+)/?$',\n market_views.MarketEntry(permitted_methods=('DELETE',)),\n name='wirecloud.market_entry'\n ),\n url(r'^api/markets/publish/?$',\n market_views.PublishService(),\n name='wirecloud.publish_on_other_marketplace'\n ),\n\n # Themes\n url(r'^api/theme/(?P[^/]+)/?$',\n theme_views.ThemeEntry(permitted_methods=('GET',)),\n name='wirecloud.theme_entry'\n ),\n\n # Workspace\n url(r'^api/workspaces/?$',\n workspace_views.WorkspaceCollection(permitted_methods=('GET', 'POST', )),\n name='wirecloud.workspace_collection'\n ),\n url(r'^api/workspace/(?P\\d+)/?$',\n workspace_views.WorkspaceEntry(permitted_methods=('GET', 'POST', 'DELETE',)),\n name='wirecloud.workspace_entry'\n ),\n url(r'^api/workspace/(?P\\d+)/tabs/?$',\n workspace_views.TabCollection(permitted_methods=('POST',)),\n name='wirecloud.tab_collection'\n ),\n url(r'^api/workspace/(?P\\d+)/tabs/order/?$',\n workspace_views.TabOrderService(),\n name='wirecloud.tab_order'\n ),\n url(r'^api/workspace/(?P\\d+)/tab/(?P\\w+)/?$',\n workspace_views.TabEntry(permitted_methods=('PUT', 'DELETE',)),\n name='wirecloud.tab_entry'\n ),\n\n url(r'^api/workspace/(?P\\d+)/resources$',\n localcatalogue_views.WorkspaceResourceCollection(permitted_methods=('GET',)),\n name='wirecloud.workspace_resource_collection'\n ),\n\n url(r'^api/workspace/(?P\\d+)/wiring$',\n wiring_views.WiringEntry(permitted_methods=('PUT',)),\n name='wirecloud.workspace_wiring'\n ),\n\n url(r'^api/workspace/(?P\\d+)/merge/?$',\n workspace_views.MashupMergeService(),\n name='wirecloud.workspace_merge'\n ),\n\n url(r'^api/workspace/(?P\\d+)/publish/?$',\n workspace_views.WorkspacePublisherEntry(permitted_methods=('POST',)),\n name='wirecloud.workspace_publish'\n ),\n\n url('^oauth2/default_redirect_uri$',\n TemplateView.as_view(template_name='wirecloud/oauth2/default_redirect_uri.html'),\n name='oauth.default_redirect_uri'),\n\n) + get_plugin_urls() + patterns('wirecloud.platform.views',\n\n url(r'^(?P[^/]+)/(?P[^/]+)/?$', 'render_workspace_view', name='wirecloud.workspace_view'),\n)\n", "repo_name": "sixuanwang/SAMSaaS", "sub_path": "wirecloud-develop/src/wirecloud/platform/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 7811, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.conf.urls.patterns", "line_number": 21, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 23, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 27, "usage_type": "call"}, {"api_name": "wirecloud.platform.testsx.views.year_archive", "line_number": 27, "usage_type": "attribute"}, {"api_name": "wirecloud.platform.testsx.views", "line_number": 27, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 29, "usage_type": "call"}, {"api_name": "wirecloud.platform.views.FeatureCollection", "line_number": 30, "usage_type": "call"}, {"api_name": "wirecloud.platform.views", "line_number": 30, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 34, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 34, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 35, "usage_type": "call"}, {"api_name": "django.views.i18n.javascript_catalog", "line_number": 36, "usage_type": "argument"}, {"api_name": "django.views.decorators.cache.cache_page", "line_number": 36, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 40, "usage_type": "call"}, {"api_name": "wirecloud.platform.context.views.PlatformContextCollection", "line_number": 41, "usage_type": "call"}, {"api_name": "wirecloud.platform.context.views", "line_number": 41, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 44, "usage_type": "call"}, {"api_name": "wirecloud.platform.widget.views.serve_showcase_media", "line_number": 45, "usage_type": "attribute"}, {"api_name": "wirecloud.platform.widget.views", "line_number": 45, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 50, "usage_type": "call"}, {"api_name": "wirecloud.commons.views.ResourceSearch", "line_number": 51, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 56, "usage_type": "call"}, {"api_name": "wirecloud.platform.localcatalogue.views.ResourceCollection", "line_number": 57, "usage_type": "call"}, {"api_name": "wirecloud.platform.localcatalogue.views", "line_number": 57, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 59, "usage_type": "call"}, {"api_name": "wirecloud.platform.localcatalogue.views.ResourceEntry", "line_number": 60, "usage_type": "call"}, {"api_name": "wirecloud.platform.localcatalogue.views", "line_number": 60, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 62, "usage_type": "call"}, {"api_name": "wirecloud.platform.localcatalogue.views.ResourceEntry", "line_number": 63, "usage_type": "call"}, {"api_name": "wirecloud.platform.localcatalogue.views", "line_number": 63, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 65, "usage_type": "call"}, {"api_name": "wirecloud.platform.localcatalogue.views.ResourceDescriptionEntry", "line_number": 66, "usage_type": "call"}, {"api_name": "wirecloud.platform.localcatalogue.views", "line_number": 66, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 68, "usage_type": "call"}, {"api_name": "wirecloud.platform.widget.views.WidgetCodeEntry", "line_number": 69, "usage_type": "call"}, {"api_name": "wirecloud.platform.widget.views", "line_number": 69, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 73, "usage_type": "call"}, {"api_name": "wirecloud.platform.iwidget.views.IWidgetCollection", "line_number": 74, "usage_type": "call"}, {"api_name": "wirecloud.platform.iwidget.views", "line_number": 74, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 77, "usage_type": "call"}, {"api_name": "wirecloud.platform.iwidget.views.IWidgetEntry", "line_number": 78, "usage_type": "call"}, {"api_name": "wirecloud.platform.iwidget.views", "line_number": 78, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 81, "usage_type": "call"}, {"api_name": "wirecloud.platform.iwidget.views.IWidgetPreferences", "line_number": 82, "usage_type": "call"}, {"api_name": "wirecloud.platform.iwidget.views", "line_number": 82, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 85, "usage_type": "call"}, {"api_name": "wirecloud.platform.iwidget.views.IWidgetProperties", "line_number": 86, "usage_type": "call"}, {"api_name": "wirecloud.platform.iwidget.views", "line_number": 86, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 89, "usage_type": "call"}, {"api_name": "wirecloud.platform.iwidget.views.IWidgetVersion", "line_number": 90, "usage_type": "call"}, {"api_name": "wirecloud.platform.iwidget.views", "line_number": 90, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 95, "usage_type": "call"}, {"api_name": "wirecloud.platform.preferences.views.PlatformPreferencesCollection", "line_number": 96, "usage_type": "call"}, {"api_name": "wirecloud.platform.preferences.views", "line_number": 96, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 99, "usage_type": "call"}, {"api_name": "wirecloud.platform.preferences.views.WorkspacePreferencesCollection", "line_number": 100, "usage_type": "call"}, {"api_name": "wirecloud.platform.preferences.views", "line_number": 100, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 103, "usage_type": "call"}, {"api_name": "wirecloud.platform.preferences.views.TabPreferencesCollection", "line_number": 104, "usage_type": "call"}, {"api_name": "wirecloud.platform.preferences.views", "line_number": 104, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 108, "usage_type": "call"}, {"api_name": "wirecloud.platform.wiring.views.OperatorEntry", "line_number": 109, "usage_type": "call"}, {"api_name": "wirecloud.platform.wiring.views", "line_number": 109, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 113, "usage_type": "call"}, {"api_name": "wirecloud.platform.markets.views.MarketCollection", "line_number": 114, "usage_type": "call"}, {"api_name": "wirecloud.platform.markets.views", "line_number": 114, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 117, "usage_type": "call"}, {"api_name": "wirecloud.platform.markets.views.MarketEntry", "line_number": 118, "usage_type": "call"}, {"api_name": "wirecloud.platform.markets.views", "line_number": 118, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 121, "usage_type": "call"}, {"api_name": "wirecloud.platform.markets.views.MarketEntry", "line_number": 122, "usage_type": "call"}, {"api_name": "wirecloud.platform.markets.views", "line_number": 122, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 125, "usage_type": "call"}, {"api_name": "wirecloud.platform.markets.views.PublishService", "line_number": 126, "usage_type": "call"}, {"api_name": "wirecloud.platform.markets.views", "line_number": 126, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 131, "usage_type": "call"}, {"api_name": "wirecloud.platform.theme.views.ThemeEntry", "line_number": 132, "usage_type": "call"}, {"api_name": "wirecloud.platform.theme.views", "line_number": 132, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 137, "usage_type": "call"}, {"api_name": "wirecloud.platform.workspace.views.WorkspaceCollection", "line_number": 138, "usage_type": "call"}, {"api_name": "wirecloud.platform.workspace.views", "line_number": 138, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 141, "usage_type": "call"}, {"api_name": "wirecloud.platform.workspace.views.WorkspaceEntry", "line_number": 142, "usage_type": "call"}, {"api_name": "wirecloud.platform.workspace.views", "line_number": 142, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 145, "usage_type": "call"}, {"api_name": "wirecloud.platform.workspace.views.TabCollection", "line_number": 146, "usage_type": "call"}, {"api_name": "wirecloud.platform.workspace.views", "line_number": 146, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 149, "usage_type": "call"}, {"api_name": "wirecloud.platform.workspace.views.TabOrderService", "line_number": 150, "usage_type": "call"}, {"api_name": "wirecloud.platform.workspace.views", "line_number": 150, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 153, "usage_type": "call"}, {"api_name": "wirecloud.platform.workspace.views.TabEntry", "line_number": 154, "usage_type": "call"}, {"api_name": "wirecloud.platform.workspace.views", "line_number": 154, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 158, "usage_type": "call"}, {"api_name": "wirecloud.platform.localcatalogue.views.WorkspaceResourceCollection", "line_number": 159, "usage_type": "call"}, {"api_name": "wirecloud.platform.localcatalogue.views", "line_number": 159, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 163, "usage_type": "call"}, {"api_name": "wirecloud.platform.wiring.views.WiringEntry", "line_number": 164, "usage_type": "call"}, {"api_name": "wirecloud.platform.wiring.views", "line_number": 164, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 168, "usage_type": "call"}, {"api_name": "wirecloud.platform.workspace.views.MashupMergeService", "line_number": 169, "usage_type": "call"}, {"api_name": "wirecloud.platform.workspace.views", "line_number": 169, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 173, "usage_type": "call"}, {"api_name": "wirecloud.platform.workspace.views.WorkspacePublisherEntry", "line_number": 174, "usage_type": "call"}, {"api_name": "wirecloud.platform.workspace.views", "line_number": 174, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 178, "usage_type": "call"}, {"api_name": "django.views.generic.TemplateView.as_view", "line_number": 179, "usage_type": "call"}, {"api_name": "django.views.generic.TemplateView", "line_number": 179, "usage_type": "name"}, {"api_name": "wirecloud.platform.plugins.get_plugin_urls", "line_number": 182, "usage_type": "call"}, {"api_name": "django.conf.urls.patterns", "line_number": 182, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 184, "usage_type": "call"}]} +{"seq_id": "22092583168", "text": "import keras\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense,Activation,Dropout,Flatten,Conv2D,MaxPooling2D,ZeroPadding2D\r\nfrom keras.layers.normalization import BatchNormalization\r\nfrom keras.optimizers import Adam,SGD\r\nfrom keras.regularizers import l2\r\nimport numpy as np\r\n\r\nnp.random.seed(100)\r\n\r\nclass AlexNet:\r\n @staticmethod\r\n def build():\r\n model = Sequential()\r\n\r\n\r\n #layer 1\r\n model.add(Conv2D(filters=96,kernel_size=(11,11),input_shape=(224,224,3),strides=(4,4),padding='same',kernel_regularizer=l2(0.01)))\r\n model.add(BatchNormalization())\r\n model.add(Activation('relu'))\r\n #maxpooling1\r\n model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2),padding='same'))\r\n\r\n\r\n #layer 2\r\n model.add(Conv2D(filters=256,kernel_size=(11,11),strides=(1,1),padding='same',kernel_regularizer = l2(0.01)))\r\n model.add(BatchNormalization())\r\n model.add(Activation('relu'))\r\n #maxpooling2\r\n model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2),padding='same'))\r\n\r\n\r\n #layer3\r\n\r\n model.add(Conv2D(filters=384,kernel_size=(3,3),strides=(1,1),padding='same',kernel_regularizer=l2(0.01)))\r\n model.add(BatchNormalization())\r\n model.add(Activation('relu'))\r\n\r\n #layer4\r\n\r\n model.add(Conv2D(filters=384,kernel_size=(3,3),strides=(1,1),padding='same',kernel_regularizer=l2(0.01)))\r\n model.add(BatchNormalization())\r\n model.add(Activation('relu'))\r\n\r\n #layer5\r\n\r\n model.add(Conv2D(filters=256,kernel_size=(3,3),strides=(1,1),padding='same',kernel_regularizer=l2(0.01)))\r\n model.add(BatchNormalization())\r\n model.add(Activation('relu'))\r\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same'))\r\n\r\n #fc layers\r\n\r\n model.add(Flatten())\r\n model.add(Dense(3072))\r\n model.add(BatchNormalization())\r\n model.add(Activation('relu'))\r\n model.add(Dropout(0.5))\r\n\r\n # Layer 7\r\n model.add(Dense(4096))\r\n model.add(BatchNormalization())\r\n model.add(Activation('relu'))\r\n model.add(Dropout(0.5))\r\n\r\n # Layer 8\r\n model.add(Dense(3))\r\n model.add(BatchNormalization())\r\n model.add(Activation('softmax'))\r\n\r\n model.summary()\r\n opt = SGD(lr =0.1,momentum=0.5,decay=1e-6)\r\n\r\n model.compile(loss=keras.losses.categorical_crossentropy,optimizer=opt,metrics=['accuracy'])\r\n\r\n return model\r\n\r\n\r\n\r\n\r\n", "repo_name": "golu360/Final-Project", "sub_path": "AlexNet.py", "file_name": "AlexNet.py", "file_ext": "py", "file_size_in_byte": 2516, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.random.seed", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 9, "usage_type": "attribute"}, {"api_name": "keras.models.Sequential", "line_number": 14, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 18, "usage_type": "call"}, {"api_name": "keras.regularizers.l2", "line_number": 18, "usage_type": "call"}, {"api_name": "keras.layers.normalization.BatchNormalization", "line_number": 19, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 20, "usage_type": "call"}, {"api_name": "keras.layers.MaxPooling2D", "line_number": 22, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 26, "usage_type": "call"}, {"api_name": "keras.regularizers.l2", "line_number": 26, "usage_type": "call"}, {"api_name": "keras.layers.normalization.BatchNormalization", "line_number": 27, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 28, "usage_type": "call"}, {"api_name": "keras.layers.MaxPooling2D", "line_number": 30, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 35, "usage_type": "call"}, {"api_name": "keras.regularizers.l2", "line_number": 35, "usage_type": "call"}, {"api_name": "keras.layers.normalization.BatchNormalization", "line_number": 36, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 37, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 41, "usage_type": "call"}, {"api_name": "keras.regularizers.l2", "line_number": 41, "usage_type": "call"}, {"api_name": "keras.layers.normalization.BatchNormalization", "line_number": 42, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 43, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 47, "usage_type": "call"}, {"api_name": "keras.regularizers.l2", "line_number": 47, "usage_type": "call"}, {"api_name": "keras.layers.normalization.BatchNormalization", "line_number": 48, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 49, "usage_type": "call"}, {"api_name": "keras.layers.MaxPooling2D", "line_number": 50, "usage_type": "call"}, {"api_name": "keras.layers.Flatten", "line_number": 54, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 55, "usage_type": "call"}, {"api_name": "keras.layers.normalization.BatchNormalization", "line_number": 56, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 57, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 58, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 61, "usage_type": "call"}, {"api_name": "keras.layers.normalization.BatchNormalization", "line_number": 62, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 63, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 64, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 67, "usage_type": "call"}, {"api_name": "keras.layers.normalization.BatchNormalization", "line_number": 68, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 69, "usage_type": "call"}, {"api_name": "keras.optimizers.SGD", "line_number": 72, "usage_type": "call"}, {"api_name": "keras.losses", "line_number": 74, "usage_type": "attribute"}]} +{"seq_id": "25691983333", "text": "import os, sys, sqlite3\nfrom time import strftime\nfrom time import gmtime\nimport time\nfrom openpyxl.styles import numbers\n\nimport LSglobal\n\n# Excel\n#========================================================================\n# open existent workbook:\nfrom openpyxl import load_workbook\n\nfilename = 'Startreihenfolge_offiziell.xlsx'\n# filename = 'Startreihenfolge_H2020.xlsx'\n# filename = LSglobal.StartXLS\n\n# read the last used value (not the formula)\nwb = load_workbook(filename, data_only=True)\n\nprint(wb.sheetnames)\n# load worksheets: the last used one, may be wrong ...\n#ws = wb.active\n# Lese Meldungen\nws = wb[\"Meldungen\"]\n# ws = wb.get_sheet_by_name(\"Rennen\")\n#========================================================================\n# Verbindung zur Datenbank erzeugen\nconnection = sqlite3.connect( LSglobal.SQLiteFile )\n#\n# Datensatzcursor erzeugen\ncursor = connection.cursor()\ncursorR = connection.cursor()\n#\n#========================================================================\n#\nzeile = 7\nwhile zeile > 6:\n #________________________________________________________________\n # integer Werte\n Rennen = ws['A' + str(zeile)].value \n Positi = ws['B' + str(zeile)].value \n StNr = ws['C' + str(zeile)].value\n Boot = ws['K' + str(zeile)].value\n # Zeit-String\n bZeit = str(ws['D' + str(zeile)].value)\n #\n # if(Boot == None):\n # print(' - ')\n # elif(Boot < 1):\n # print('---')\n # else:\n if(Boot != None and Boot > 0):\n myT = bZeit.split(\":\")\n mySec = 3600*int(myT[0]) + 60*int(myT[1]) + int(myT[2])\n print(\"Zeile \" + str(zeile) + \": _____________\")\n # \n Vornamen = ws['E' + str(zeile)].value\n Vorname = Vornamen.split(\"\\n\")\n #\n Namen = ws['F' + str(zeile)].value\n Name = Namen.split(\"\\n\")\n #\n Jahrgang = str(ws['G' + str(zeile)].value)\n Jahre = Jahrgang.split(\"\\n\")\n #\n Vereine = ws['I' + str(zeile)].value\n Verein = Vereine.split(\"\\n\")\n #\n print(\"Rennen \" + str(Rennen) + \".\" + str(Positi) + \"= #\" + str(StNr) + \" (\" + str(Boot) + \") : \" + str(mySec)) \n sql = \"UPDATE rennen SET status = 2 WHERE nummer = \" + str(Rennen)\n # print( sql )\n cursor.execute(sql)\n connection.commit()\n\n #\n # SQL-Abfrage\n sql = \"SELECT * FROM boote WHERE nummer = \" + str(Boot)\n #\n # Empfang des Ergebnisses\n cursor.execute(sql)\n # _______________________________________________________________________ korrekte Ruderer ?\n # for dsatz in cursor:\n dsatz = cursor.fetchone()\n # print(dsatz)\n # print(\"Rennen \" + str(Rennen) + \" = \" + str(dsatz[2]) )\n # print(\"Verein \" + Verein[0] + \" = \" + dsatz[3])\n ruderer = ()\n # dsatz[4].split(',')\n for iR in range(0, (len(ruderer) - 3)):\n #\n sql = \"SELECT * FROM ruderer WHERE nummer = \" + str(ruderer[iR + 1])\n # Empfang des Ergebnisses\n cursorR.execute(sql)\n Rd = cursorR.fetchone()\n # Vorname\n sqlVorname = Rd[0]\n # Nachname\n sqlName = Rd[1]\n # Jahrgang\n sqlJahrgang = str( Rd[3] )\n if( Vorname[iR] != sqlVorname or Name[iR] != sqlName ):\n print(Vorname[iR] + \" \" + Name[iR] + \" != \" + sqlVorname + \" \" + sqlName)\n # x = raw_input(\"Ändern? [Y/n]\")\n x = input(\"Ändern? [Y/n] > \")\n if(x == \"Y\" or x== \"y\" or x == \"j\" or x == \"J\"):\n sql = \"UPDATE ruderer SET vorname = \" + Vorname[iR] + \", name = \" + Name[iR] + \" WHERE nummer = \" + str(ruderer[iR + 1])\n # print( sql )\n cursor.execute(sql)\n connection.commit()\n print(\"Würde jetzt ändern!\")\n if( Jahre[iR] != sqlJahrgang ):\n print(Jahre[iR] + \" != \" + sqlJahrgang + \" (\" + sqlVorname + \" \" + sqlName + \")\")\n x = input(\"Ändern? [Y/n] > \")\n if(x == \"Y\" or x== \"y\" or x == \"j\" or x == \"J\"):\n print(\"Würde jetzt ändern!\")\n # ToDo: Abfrage oder Änderung?\n # ______________________________________________________________________________________\n #\n if( Rennen != dsatz[2] ):\n print( \"Boot \" + str(Boot) + \" mit Startnr \" + str(StNr) + \" von Rennen \" + str(dsatz[2]) + \" nach \" + str(Rennen) + \" ?!\" )\n # x = raw_input(\"Ändern? [Y/n]\")\n x = input(\"Ändern? [Y/n] > \")\n if(x == \"Y\" or x== \"y\" or x == \"j\" or x == \"J\"):\n sql = \"UPDATE boote SET rennen = \" + str(Rennen) + \" WHERE nummer = \" + str(Boot)\n # print( sql )\n cursor.execute(sql)\n connection.commit()\n print(\"... geändert !\")\n \n # ______________________________________________________________________________________\n #\n sql = \"UPDATE boote SET startnummer = \" + str(StNr) + \", planstart = \" + str(mySec) + \" WHERE nummer = \" + str(Boot)\n # print( sql )\n cursor.execute(sql)\n connection.commit()\n # dto. mit StNr\n #\n zeile = zeile + 1\n if(bZeit == None):\n zeile = 0\n if(len(bZeit) <= 5):\n zeile = 0\n #_____________________________________________________________\n\n\n#______________________________________ EOF\n", "repo_name": "DrUlme/LS_python", "sub_path": "lese_Startreihenfolge.py", "file_name": "lese_Startreihenfolge.py", "file_ext": "py", "file_size_in_byte": 5268, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "openpyxl.load_workbook", "line_number": 19, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 29, "usage_type": "call"}, {"api_name": "LSglobal.SQLiteFile", "line_number": 29, "usage_type": "attribute"}]} +{"seq_id": "30671162491", "text": "import pytest\nimport wandb\n\nimport weave\nfrom weave.weave_internal import define_fn, make_const_node, const\nfrom ..api import use\nfrom .. import graph\nfrom .. import weave_types as types\nfrom .. import async_demo\nfrom .. import compile\n\n\ndef test_automatic_await_compile():\n twelve = async_demo.slowmult(3, 4, 0.01)\n twenty_four = async_demo.slowmult(2, twelve, 0.01)\n result = compile.compile([twenty_four])\n assert str(result[0]) == \"2.slowmult(slowmult(3, 4, 0.01).await(), 0.01)\"\n\n\n@pytest.mark.parametrize(\n \"nodes_with_expected_values\",\n [\n # Simple graph with no modification needed\n [\n (\n 3,\n graph.OutputNode(\n types.Number(),\n \"add\",\n {\n \"lhs\": graph.ConstNode(types.Number(), 1),\n \"rhs\": graph.ConstNode(types.Number(), 2),\n },\n ),\n )\n ],\n # Single Replacement Needed\n [\n (\n [3, 4, 5],\n graph.OutputNode(\n types.Number(),\n \"add\",\n {\n \"lhs\": graph.ConstNode(types.List(types.Number()), [1, 2, 3]),\n \"rhs\": graph.ConstNode(types.Number(), 2),\n },\n ),\n )\n ],\n # Nested Replacement Needed\n [\n (\n [13, 14, 15],\n graph.OutputNode(\n types.Number(),\n \"add\",\n {\n \"lhs\": graph.OutputNode(\n types.Number(),\n \"add\",\n {\n \"lhs\": graph.ConstNode(\n types.List(types.Number()), [1, 2, 3]\n ),\n \"rhs\": graph.ConstNode(types.Number(), 2),\n },\n ),\n \"rhs\": graph.ConstNode(types.Number(), 10),\n },\n ),\n )\n ],\n # Nested Replacement Through Valid Node\n [\n (\n [13, 14, 15],\n graph.OutputNode(\n types.Number(),\n \"add\",\n {\n \"lhs\": graph.OutputNode(\n types.Number(),\n \"index\",\n {\n \"arr\": graph.OutputNode(\n types.List(types.Number()),\n \"list\",\n {\n \"0\": graph.OutputNode(\n types.Number(),\n \"add\",\n {\n \"lhs\": graph.ConstNode(\n types.List(types.Number()),\n [1, 2, 3],\n ),\n \"rhs\": graph.ConstNode(\n types.Number(), 2\n ),\n },\n ),\n },\n ),\n \"index\": graph.ConstNode(types.Number(), 0),\n },\n ),\n \"rhs\": graph.ConstNode(types.Number(), 10),\n },\n ),\n )\n ],\n ],\n)\ndef test_executing_js_graphs(nodes_with_expected_values):\n nodes = [node for exp_val, node in nodes_with_expected_values]\n exp_vals = [exp_val for exp_val, node in nodes_with_expected_values]\n assert use(nodes) == exp_vals\n\n\ndef test_executing_js_multi_root():\n node = graph.OutputNode(\n types.Number(),\n \"add\",\n {\n \"lhs\": graph.ConstNode(\n types.List(types.Number()),\n [1, 2, 3],\n ),\n \"rhs\": graph.ConstNode(types.Number(), 2),\n },\n )\n node2 = graph.OutputNode(\n types.Number(),\n \"add\",\n {\n \"lhs\": node,\n \"rhs\": graph.ConstNode(types.Number(), 4),\n },\n )\n assert use([node, node2]) == [[3, 4, 5], [7, 8, 9]]\n\n\ndef test_optimize_merge_empty_dict():\n non_empty_dict = weave.ops.dict_(a=5, b=2)\n assert (\n compile.compile_simple_optimizations(\n [weave.ops.TypedDict.merge(non_empty_dict, weave.ops.dict_())]\n )[0].to_json()\n == non_empty_dict.to_json()\n )\n assert (\n compile.compile_simple_optimizations(\n [weave.ops.TypedDict.merge(weave.ops.dict_(), non_empty_dict)]\n )[0].to_json()\n == non_empty_dict.to_json()\n )\n non_simplified_merge = weave.ops.TypedDict.merge(\n weave.ops.dict_(j=3), non_empty_dict\n )\n assert (\n compile.compile_simple_optimizations([non_simplified_merge])[0].to_json()\n == non_simplified_merge.to_json()\n )\n\n\ndef test_compile_lambda_uniqueness():\n list_node_1 = weave.ops.make_list(a=make_const_node(weave.types.Number(), 1))\n list_node_2 = weave.ops.make_list(a=make_const_node(weave.types.Number(), 2))\n fn_node = define_fn({\"row\": weave.types.Number()}, lambda row: row + 1)\n mapped_1 = list_node_1.map(fn_node)\n mapped_2 = list_node_2.map(fn_node)\n combined = weave.ops.make_list(a=mapped_1, b=mapped_2)\n concatted = combined.concat()\n\n # list node contains 2 nodes (const, list), x 2 = 4\n # fn node contains 3 nodes (row, add, const) + the fn node itself, x1 = 4\n # map node contains 1 node, x2 = 2\n # combined node contains 1 node, x1 = 1\n # concat node contains 1 node, x1 = 1\n # total = 12\n assert graph.count(concatted) == 12\n\n # However, after lambda compilation, we should get\n # 3 more nodes (new row, add, and fn), the const 1\n # is not deduped because in one case (inside the lambda function),\n # it is an int and in the other, it is a number\n compiled = compile.compile([concatted])[0]\n\n assert graph.count(compiled) == 15\n\n\n# We actually don't want this to work because it would require\n# mutating a static lambda function!\n# def test_compile_through_execution(user_by_api_key_in_env):\n# run = wandb.init(project=\"project_exists\")\n# for i in range(10):\n# run.log({\"val\": i, \"cat\": i % 2})\n# run.finish()\n\n# \"\"\"\n# This test demonstrates successful execution when there is an explicit\n# const function instead of a direct node (resulting in an intermediate execution op)\n# \"\"\"\n# history_node = weave.ops.project(run.entity, run.project).run(run.id).history2()\n# pick = const(history_node).pick(\"val\")\n# res = weave.use(pick)\n# assert res.to_pylist_notags() == list(range(10))\n\n\ndef test_compile_through_function_call(user_by_api_key_in_env):\n run = wandb.init(project=\"project_exists\")\n for i in range(10):\n run.log({\"val\": i, \"cat\": i % 2})\n run.finish()\n\n \"\"\"\n This test demonstrates successful execution when there is an explicit\n function-__call__ in the graph)\n \"\"\"\n fn_node = define_fn(\n {\"entity_name\": types.String()},\n lambda entity_name: (\n weave.ops.project(entity_name, run.project).run(run.id).history2()\n ),\n )\n called_node = fn_node(run.entity)\n pick = called_node.pick(\"val\")\n res = weave.use(pick)\n assert res.to_pylist_notags() == list(range(10))\n", "repo_name": "wandb/weave", "sub_path": "weave/tests/test_compile.py", "file_name": "test_compile.py", "file_ext": "py", "file_size_in_byte": 7880, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 420, "dataset": "github-code", "pt": "20", "api": [{"api_name": "api.use", "line_number": 118, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 20, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 20, "usage_type": "attribute"}, {"api_name": "api.use", "line_number": 141, "usage_type": "call"}, {"api_name": "weave.ops.dict_", "line_number": 145, "usage_type": "call"}, {"api_name": "weave.ops", "line_number": 145, "usage_type": "attribute"}, {"api_name": "weave.ops.TypedDict.merge", "line_number": 148, "usage_type": "call"}, {"api_name": "weave.ops", "line_number": 148, "usage_type": "attribute"}, {"api_name": "weave.ops.dict_", "line_number": 148, "usage_type": "call"}, {"api_name": "weave.ops.TypedDict.merge", "line_number": 154, "usage_type": "call"}, {"api_name": "weave.ops", "line_number": 154, "usage_type": "attribute"}, {"api_name": "weave.ops.dict_", "line_number": 154, "usage_type": "call"}, {"api_name": "weave.ops.TypedDict.merge", "line_number": 158, "usage_type": "call"}, {"api_name": "weave.ops", "line_number": 158, "usage_type": "attribute"}, {"api_name": "weave.ops.dict_", "line_number": 159, "usage_type": "call"}, {"api_name": "weave.ops", "line_number": 159, "usage_type": "attribute"}, {"api_name": "weave.ops.make_list", "line_number": 168, "usage_type": "call"}, {"api_name": "weave.ops", "line_number": 168, "usage_type": "attribute"}, {"api_name": "weave.weave_internal.make_const_node", "line_number": 168, "usage_type": "call"}, {"api_name": "weave.types.Number", "line_number": 168, "usage_type": "call"}, {"api_name": "weave.types", "line_number": 168, "usage_type": "attribute"}, {"api_name": "weave.ops.make_list", "line_number": 169, "usage_type": "call"}, {"api_name": "weave.ops", "line_number": 169, "usage_type": "attribute"}, {"api_name": "weave.weave_internal.make_const_node", "line_number": 169, "usage_type": "call"}, {"api_name": "weave.types.Number", "line_number": 169, "usage_type": "call"}, {"api_name": "weave.types", "line_number": 169, "usage_type": "attribute"}, {"api_name": "weave.weave_internal.define_fn", "line_number": 170, "usage_type": "call"}, {"api_name": "weave.types.Number", "line_number": 170, "usage_type": "call"}, {"api_name": "weave.types", "line_number": 170, "usage_type": "attribute"}, {"api_name": "weave.ops.make_list", "line_number": 173, "usage_type": "call"}, {"api_name": "weave.ops", "line_number": 173, "usage_type": "attribute"}, {"api_name": "wandb.init", "line_number": 212, "usage_type": "call"}, {"api_name": "weave.weave_internal.define_fn", "line_number": 221, "usage_type": "call"}, {"api_name": "weave.ops.project", "line_number": 224, "usage_type": "call"}, {"api_name": "weave.ops", "line_number": 224, "usage_type": "attribute"}, {"api_name": "weave.use", "line_number": 229, "usage_type": "call"}]} +{"seq_id": "14172058325", "text": "import streamlit as st\r\nimport requirements.txt\r\n\r\ndef load_data():\r\n url = \"http://promise.site.uottawa.ca/SERepository/datasets/jm1.arff\"\r\n try:\r\n response = requests.get(url)\r\n data = arff.loads(response.text)\r\n df = pd.DataFrame(data[0])\r\n # Handle missing values by filling with median\r\n df.fillna(df.median(), inplace=True)\r\n return df\r\n except Exception as e:\r\n st.error(f\"Error loading data: {str(e)}\")\r\n return None\r\n\r\n# Function to calculate feature importance\r\ndef feature_importance(data, target_col):\r\n if target_col not in data.columns:\r\n st.warning(f\"{target_col} not found in the dataset.\")\r\n return\r\n\r\n # Split the data into features and target\r\n X = data.drop(columns=[target_col])\r\n y = data[target_col]\r\n\r\n # Encode the categorical labels to numeric\r\n label_encoder = LabelEncoder()\r\n y_encoded = label_encoder.fit_transform(y)\r\n\r\n # Impute missing values\r\n imputer = SimpleImputer(strategy='mean')\r\n X_imputed = imputer.fit_transform(X)\r\n\r\n # Fit a random forest classifier to determine feature importance\r\n clf = RandomForestClassifier()\r\n clf.fit(X_imputed, y_encoded)\r\n\r\n # Get feature importances\r\n feature_importances = clf.feature_importances_\r\n\r\n # Create a DataFrame to store feature names and their importance scores\r\n importance_df = pd.DataFrame({'Feature': X.columns, 'Importance': feature_importances})\r\n\r\n # Sort features by importance\r\n importance_df = importance_df.sort_values(by='Importance', ascending=False)\r\n\r\n # Plot feature importance using Plotly\r\n fig = px.bar(importance_df, x='Importance', y='Feature', orientation='h', title='Feature Importance')\r\n st.plotly_chart(fig)\r\n\r\n# Function to plot numeric distribution\r\ndef plot_numeric_distribution(data, selected_features, color_type, line_type):\r\n if not selected_features:\r\n st.warning(\"Please select numeric features for visualization.\")\r\n return\r\n\r\n numeric_features = data.select_dtypes(include=['float64', 'int64'])\r\n\r\n # Create subplots\r\n fig, axes = plt.subplots(1, len(selected_features), figsize=(15, 5))\r\n\r\n # Set line style\r\n line_styles = ['solid', 'dotted', 'dashed']\r\n line_style = line_styles[0] # Default to solid line\r\n if line_type == 'dotted':\r\n line_style = 'dotted'\r\n elif line_type == 'dashed':\r\n line_style = 'dashed'\r\n\r\n # Set color\r\n colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']\r\n color = colors[0] # Default to blue\r\n if color_type in colors:\r\n color = color_type\r\n\r\n # Plot histograms for each selected numeric feature\r\n for i, col in enumerate(selected_features):\r\n ax = axes[i]\r\n sns.histplot(data[col], kde=True, ax=ax, color=color, linestyle=line_style)\r\n ax.set_title(f'Distribution of {col}')\r\n ax.set_xlabel(col)\r\n ax.set_ylabel('Frequency')\r\n\r\n plt.tight_layout()\r\n st.pyplot(fig)\r\n\r\nst.title(\"Data Visualization App\")\r\ndata = load_data()\r\n\r\nst.sidebar.header(\"Data Filters\")\r\nmin_rows = st.sidebar.number_input(\"Minimum Number of Rows\", min_value=0, value=0)\r\nselected_features = st.sidebar.multiselect(\"Select Features for Visualization\", data.columns)\r\n\r\nfiltered_data = data.head(min_rows) # Filter by the number of rows\r\n\r\nst.sidebar.header(\"Visualization Settings\")\r\ncolor_type = st.sidebar.selectbox(\"Color Type\", ['b', 'g', 'r', 'c', 'm', 'y', 'k'])\r\nline_type = st.sidebar.selectbox(\"Line Type\", ['solid', 'dotted', 'dashed'])\r\n\r\nst.subheader(\"Feature Importance\")\r\nfeature_importance(data, selected_features)\r\n\r\nst.subheader(\"Numeric Feature Distribution\")\r\nplot_numeric_distribution(data, selected_features, color_type, line_type)\r\n", "repo_name": "NikitaMlk/EmpiricMethods2", "sub_path": "my_app.py", "file_name": "my_app.py", "file_ext": "py", "file_size_in_byte": 3743, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "streamlit.error", "line_number": 14, "usage_type": "call"}, {"api_name": "streamlit.warning", "line_number": 20, "usage_type": "call"}, {"api_name": "streamlit.plotly_chart", "line_number": 50, "usage_type": "call"}, {"api_name": "streamlit.warning", "line_number": 55, "usage_type": "call"}, {"api_name": "streamlit.pyplot", "line_number": 86, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 88, "usage_type": "call"}, {"api_name": "streamlit.sidebar.header", "line_number": 91, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 91, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.number_input", "line_number": 92, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 92, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.multiselect", "line_number": 93, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 93, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.header", "line_number": 97, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 97, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.selectbox", "line_number": 98, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 98, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.selectbox", "line_number": 99, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 99, "usage_type": "attribute"}, {"api_name": "streamlit.subheader", "line_number": 101, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 104, "usage_type": "call"}]} +{"seq_id": "21504000246", "text": "import json\nfrom decouple import config\nimport requests\nimport datetime\nimport os\n\n\nclass Updater():\n def __init__(self):\n self.savefilepath = './data/habits.json'\n self.NOTION_URL = \"https://api.notion.com/v1/databases/\"\n self.integration_token = config(\"INTEGRATION_TOKEN\")\n self.DATABASE_ID = config(\"DATABASE_ID\")\n self.database_url = self.NOTION_URL + self.DATABASE_ID + \"/query\"\n\n # Adjust self.today and self.start_date for the duration to be refreshed\n self.today = datetime.datetime.strftime(\n datetime.datetime.now(), \"%Y-%m-%d\")\n self.start_date = datetime.datetime.strftime(\n datetime.datetime.now() - datetime.timedelta(30), \"%Y-%m-%d\") # '2021-09-30'\n self.data = {\n \"filter\": {\n \"and\": [\n {\n \"property\": \"Date\",\n \"date\": {\n \"after\": self.start_date\n }\n },\n {\n \"property\": \"Date\",\n \"date\": {\n \"on_or_before\": self.today\n }\n }\n ]\n },\n \"sorts\": [\n {\n \"property\": \"Date\",\n \"direction\": \"descending\"\n }\n ]\n }\n\n def get_response(self):\n response = requests.post(self.database_url,\n headers={\"Authorization\": f\"{self.integration_token}\",\n \"Notion-Version\": \"2021-08-16\"},\n json=self.data)\n if response.status_code != 200:\n raise ApiError(f'Response Status: {response.status_code}')\n else:\n return response.json()\n\n def get_checks_from_day(self, day):\n # day is a dictionary\n # with the key of properties\n # for all the 'headers' in the notion table\n output_dic = {}\n for prop_name, prop_dic in day['properties'].items():\n if prop_dic['type'] == 'checkbox':\n col_name = prop_name.encode(\n 'ascii', 'ignore').decode('ascii').strip()\n col_status = prop_dic['checkbox']\n output_dic[col_name] = col_status\n return {day['properties']['Date']['date']['start']: output_dic}\n\n def get_saved_data(self, savefilepath):\n if os.path.exists(savefilepath):\n with open(savefilepath, 'r') as f:\n data = json.load(f)\n else:\n os.makedirs(savefilepath)\n data = {}\n return data\n\n def save_data(self, new_data, savefilepath):\n data = self.get_saved_data(savefilepath)\n data.update(new_data)\n with open(savefilepath, 'w') as f:\n json.dump(data, f)\n\n def run(self):\n results = self.get_response()\n new_data = {}\n for day in results['results']:\n day_habits_dic = self.get_checks_from_day(day)\n new_data.update(day_habits_dic)\n self.save_data(new_data, self.savefilepath)\n\n\nif __name__ == \"__main__\":\n updater = Updater()\n updater.run()\n", "repo_name": "gerpang/NotionHabitsViz", "sub_path": "updater.py", "file_name": "updater.py", "file_ext": "py", "file_size_in_byte": 3262, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "decouple.config", "line_number": 12, "usage_type": "call"}, {"api_name": "decouple.config", "line_number": 13, "usage_type": "call"}, {"api_name": "datetime.datetime.strftime", "line_number": 17, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 17, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 18, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strftime", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 19, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 20, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 20, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 20, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 47, "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": "json.load", "line_number": 72, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 74, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 82, "usage_type": "call"}]} +{"seq_id": "35420898333", "text": "\nimport json\nfrom ahk import AHK, Hotkey\nfrom ahk.directives import NoTrayIcon\nimport os\n\nbasedir = os.path.dirname(__file__)\n\n\na_file = open(f\"{basedir}\\JSON USER.json\", \"r\")\njson_object = json.load(a_file)\na_file.close()\n\n\n\nahk = AHK(directives=[NoTrayIcon])\nnl = '\\n'\nOUT = '\"'\nIN = '\"'\n\nAodobeString = f\"if WinActive({IN}ahk_class {json_object['CONDITIONAL_2'][0]}{OUT}){nl}\"\nExcelString = f\"if WinActive({IN}ahk_class {json_object['CONDITIONAL_3'][0]}{OUT}){nl}\"\nWordString = f\"if WinActive({IN}ahk_class {json_object['CONDITIONAL_4'][0]}{OUT}){nl}\"\nElseString = f\"else{nl}\"\nDoubleString = f\"if (A_PriorHotkey = A_ThisHotkey) && (A_TimeSincePriorHotkey < 400){nl}\"\nCabinetString = f\"if WinActive({IN}ahk_class CabinetWClass{OUT}){nl}\"\nChromeString = f\"if WinActive({IN}ahk_class {json_object['CONDITIONAL_5'][0]}{OUT}){nl}\"\n\n\nkey_combo1 = \"+WheelDown\"\nscript1 = f\"send {json_object['1.1 +WheelDown'][0]}\"\nhotkey1 = Hotkey(ahk, key_combo1, script1)\n\nkey_combo2 = \"+WheelUp\"\nscript2 = f\"send {json_object['2.1 +WheelUp'][0]}\"\nhotkey2 = Hotkey(ahk, key_combo2, script2)\n\nkey_combo3 = \"#CapsLock\"\nscript3 = f\"send {json_object['3.1 #CapsLock'][0]}\"\nhotkey3 = Hotkey(ahk, key_combo3, script3)\n\nkey_combo4 = \"!`\"\nscript4 = f\"send {{text}}{json_object['4.1 !`'][0]}\"\nhotkey4 = Hotkey(ahk, key_combo4, script4)\n\n\nkey_combo5 = \"Tab & WheelDown\"\nscript5 = f\"{WordString} send {json_object['5.4 Tab & WheelDown'][0]}{nl}{ExcelString} send {json_object['5.3 Tab & WheelDown'][0]}\"\nhotkey5 = Hotkey(ahk, key_combo5, script5)\n\nkey_combo6 = \"~Tab & WheelUp\"\nscript6 = f\"{WordString} send {json_object['6.4 Tab & WheelUp'][0]}{nl}{ExcelString} send {json_object['6.3 Tab & WheelUp'][0]}\"\nhotkey6 = Hotkey(ahk, key_combo6, script6)\n\n\nkey_combo7 = \"~Tab & Z\"\nscript7 = f\"{ExcelString} send {json_object['7.3 Tab & Z'][0]}{nl}{WordString} send {json_object['7.4 Tab & Z'][0]}{nl}{ElseString} send {json_object['7.1 Tab & Z'][0]}{nl}{AodobeString} send {json_object['7.2 Tab & Z'][0]}{nl}\"\nhotkey7 = Hotkey(ahk, key_combo7, script7)\n\n\nkey_combo8 = \"~Tab & X\"\nscript8 = f\"{WordString} send {json_object['8.4 Tab & X'][0]}{nl}{AodobeString} send {json_object['8.2 Tab & X'][0]}{nl}{ExcelString} send {json_object['8.3 Tab & X'][0]}\"\nhotkey8 = Hotkey(ahk, key_combo8, script8)\n\nkey_combo9 = \"~Tab & Space\"\nscript9 = f\"{ExcelString} send {json_object['9.3 Tab & Space'][0]}\"\nhotkey9 = Hotkey(ahk, key_combo9, script9)\n\nkey_combo10 = \"MButton\"\nscript10 = f\"send {json_object['10.1 MButton'][0]}\"\nhotkey10 = Hotkey(ahk, key_combo10, script10)\n\nkey_combo11 = \"+MButton\"\nscript11 = f\"{ExcelString} send {json_object['11.3 +MButton'][0]}{nl}{ChromeString} send {json_object['11.5 +MButton'][0]}{nl}{ElseString} send {json_object['11.1 +MButton'][0]}\"\nhotkey11 = Hotkey(ahk, key_combo11, script11)\n\nkey_combo12 = \"+LButton\"\nscript12 = f\"{AodobeString} send {json_object['12.2 +LButton'][0]}{nl}{ElseString} send {json_object['12.1 +LButton'][0]}\"\nhotkey12 = Hotkey(ahk, key_combo12, script12)\n\nkey_combo13 = \"+RButton\"\nscript13 = f\"{AodobeString} send {json_object['13.2 +RButton'][0]}{nl}{ElseString} send {json_object['13.1 +RButton'][0]}\"\nhotkey13 = Hotkey(ahk, key_combo13, script13)\n\nkey_combo14 = \"^MButton\"\nscript14 = f\"{ChromeString} send {json_object['14.5 ^MButton'][0]}{nl}{ExcelString} send {json_object['14.3 ^MButton'][0]}{nl}{ElseString} send {json_object['14.1 ^MButton'][0]}\"\nhotkey14 = Hotkey(ahk, key_combo14, script14)\n\nkey_combo15 = \"CapsLock & 5\"\nscript15 = f\"send {json_object['15.1 CapsLock & 5'][0]}\"\nhotkey15 = Hotkey(ahk, key_combo15, script15)\n\nkey_combo16 = \"+Capslock\"\nscript16 = f\"{WordString} send {json_object['16.4 +Capslock'][0]}{nl}{ElseString} send {json_object['16.1 +Capslock'][0]}\"\nhotkey16 = Hotkey(ahk, key_combo16, script16)\n\nkey_combo17 = \"^Q\"\nscript17 = f\"{ExcelString} send {json_object['17.3 ^Q'][0]}{nl}{CabinetString} return{nl}{ElseString} send {json_object['17.1 ^Q'][0]}\"\nhotkey17 = Hotkey(ahk, key_combo17, script17)\n\nkey_combo18 = \"^!LButton\"\nscript18 = f\"send {json_object['18.1 ^!LButton'][0]}\"\nhotkey18 = Hotkey(ahk, key_combo18, script18)\n\nkey_combo19 = \"^!RButton\"\nscript19 = f\"send {json_object['19.1 ^!RButton'][0]}\"\nhotkey19 = Hotkey(ahk, key_combo19, script19)\n\nkey_combo20 = \"^+Q\"\nscript20 = f\"send {json_object['20.1 ^+Q'][0]}\"\nhotkey20 = Hotkey(ahk, key_combo20, script20)\n\nkey_combo21 = \"^+F\"\nscript21 = f\"{ExcelString} send {json_object['21.3 ^+F'][0]}\"\nhotkey21 = Hotkey(ahk, key_combo21, script21)\n\nkey_combo22 = \"~CapsLock & RButton\"\nscript22 = f\"{AodobeString} send {json_object['22.2 CapsLock & RButton'][0]}{nl}{ElseString} send {json_object['22.1 CapsLock & RButton'][0]}\"\nhotkey22 = Hotkey(ahk, key_combo22, script22)\n\nkey_combo23 = \"~CapsLock & LButton\"\nscript23 = f\"{AodobeString} send {json_object['23.2 CapsLock & LButton'][0]}{nl}{ElseString} send {json_object['23.1 CapsLock & LButton'][0]}\"\nhotkey23 = Hotkey(ahk, key_combo23, script23)\n\nkey_combo24 = \"Shift & ~Tab\"\nscript24 = f\"{ExcelString} send {json_object['24.3 +Tab'][0]}{nl}{WordString} send {json_object['24.4 +Tab'][0]}{nl}{ElseString} send {json_object['24.1 +Tab'][0]}\"\nhotkey24 = Hotkey(ahk, key_combo24, script24)\n\nkey_combo25 = \"~CapsLock & MButton\"\nscript25 = f\"send {json_object['25.1 CapsLock & MButton'][0]}\"\nhotkey25 = Hotkey(ahk, key_combo25, script25)\n\nkey_combo26 = \"~CapsLock & Q\"\nscript26 = f\"{ExcelString} send {json_object['26.3 CapsLock & Q'][0]}\"\nhotkey26 = Hotkey(ahk, key_combo26, script26)\n\nkey_combo27 = \"~CapsLock & W\"\nscript27 = f\"{ExcelString} send {json_object['27.3 CapsLock & W'][0]}\"\nhotkey27 = Hotkey(ahk, key_combo27, script27)\n\nkey_combo28 = \"~CapsLock & F\"\nscript28 = f\"{ExcelString} send {json_object['28.3 CapsLock & F'][0]}\"\nhotkey28 = Hotkey(ahk, key_combo28, script28)\n\nkey_combo29 = \"~CapsLock & S\"\nscript29 = f\"{ExcelString} send {json_object['29.3 CapsLock & S'][0]}\"\nhotkey29 = Hotkey(ahk, key_combo29, script29)\n\nkey_combo30 = \"~CapsLock & A\"\nscript30 = f\"{ExcelString} send {json_object['30.3 CapsLock & A'][0]}\"\nhotkey30 = Hotkey(ahk, key_combo30, script30)\n\nkey_combo31 = \"~CapsLock & G\"\nscript31 = f\"{ExcelString} send {json_object['31.3 CapsLock & G'][0]}\"\nhotkey31 = Hotkey(ahk, key_combo31, script31)\n\nkey_combo32 = \"~CapsLock & D\"\nscript32 = f\"{ExcelString} send {json_object['32.3 CapsLock & D'][0]}\"\nhotkey32 = Hotkey(ahk, key_combo32, script32)\n\nkey_combo33 = \"~CapsLock & `\"\nscript33 = f\"{WordString} send {json_object['33.4 CapsLock & `'][0]}{nl}{ElseString} send {json_object['33.1 CapsLock & `'][0]}\"\nhotkey33 = Hotkey(ahk, key_combo33, script33)\n\nkey_combo34 = \"~CapsLock Up\"\nscript34 = f\"{DoubleString} send {json_object['34.12x CapsLock'][0]}{nl}{ElseString}{json_object['34.0 CapsLock'][0]}\"\nhotkey34 = Hotkey(ahk, key_combo34, script34)\n\nkey_combo35 = \"~Tab & 2\"\nscript35 = f\"{ExcelString} send {json_object['35.3 Tab & 2'][0]}\"\nhotkey35 = Hotkey(ahk, key_combo35, script35)\n\nkey_combo36 = \"~Tab & S\"\nscript36 = f\"{ExcelString} {DoubleString} send {json_object['36.32x Tab & S'][0]}{nl}{ElseString} send {json_object['36.1 Tab & S'][0]}\"\nhotkey36 = Hotkey(ahk, key_combo36, script36)\n\nkey_combo37 = \"~Tab & W\"\nscript37 = f\"send {json_object['37.1 Tab & W'][0]}\"\nhotkey37 = Hotkey(ahk, key_combo37, script37)\n\nkey_combo38 = \"~Tab & A\"\nscript38 = f\"send {json_object['38.1 Tab & A'][0]}\"\nhotkey38 = Hotkey(ahk, key_combo38, script38)\n\nkey_combo39 = \"~Tab & D\"\nscript39 = f\"send {json_object['39.1 Tab & D'][0]}\"\nhotkey39 = Hotkey(ahk, key_combo39, script39)\n\nkey_combo40 = \"~Tab & 3\"\nscript40 = f\"{ExcelString} send {json_object['40.3 Tab & 3'][0]}\"\nhotkey40 = Hotkey(ahk, key_combo40, script40)\n\nkey_combo41 = \"+`\"\nscript41 = f\"{WordString} send {json_object['41.4 +`'][0]}{nl}{ElseString} send {json_object['41.1 +`'][0]}\"\nhotkey41 = Hotkey(ahk, key_combo41, script41)\n\nkey_combo42 = \"~Tab & Q\"\nscript42 = f\"send {json_object['42.1 Tab & Q'][0]}\"\nhotkey42 = Hotkey(ahk, key_combo42, script42)\n\nkey_combo43 = \"~Tab & RButton\"\nscript43 = f\"{AodobeString} send {json_object['43.2 Tab & RButton'][0]}{nl}{ExcelString} send {json_object['43.3 Tab & RButton'][0]}\"\nhotkey43 = Hotkey(ahk, key_combo43, script43)\n\nkey_combo44 = \"~Tab & LButton\"\nscript44 = f\"{AodobeString} send {json_object['44.2 Tab & LButton'][0]}{nl}{ExcelString} send {json_object['44.3 Tab & LButton'][0]}\"\nhotkey44 = Hotkey(ahk, key_combo44, script44)\n\nkey_combo45 = \"~Tab & MButton\"\nscript45 = f\"{ExcelString} send {json_object['45.3 Tab & MButton'][0]}{nl}{AodobeString} send {json_object['45.2 Tab & MButton'][0]}{nl}{ChromeString} send {json_object['45.5 Tab & MButton'][0]}\"\nhotkey45 = Hotkey(ahk, key_combo45, script45)\n\n\nkey_combo46 = \"~Tab & 1\"\nscript46 = f\"{ExcelString} send {json_object['46.3 Tab & 1'][0]}\"\nhotkey46 = Hotkey(ahk, key_combo46, script46)\n\nkey_combo47 = \"~Tab & F1\"\nscript47 = f\"send {json_object['47.1 Tab & F1'][0]}\"\nhotkey47 = Hotkey(ahk, key_combo47, script47)\n\nkey_combo48 = \"~Tab & F2\"\nscript48 = f\"send {json_object['48.1 Tab & F2'][0]}\"\nhotkey48 = Hotkey(ahk, key_combo48, script48)\n\nkey_combo49 = \"~Tab & F3\"\nscript49 = f\"send {json_object['49.1 Tab & F3'][0]}\"\nhotkey49 = Hotkey(ahk, key_combo49, script49)\n\nkey_combo50 = \"~Tab & F4\"\nscript50 = f\"send {json_object['50.1 Tab & F4'][0]}\"\nhotkey50 = Hotkey(ahk, key_combo50, script50)\n\nkey_combo51 = \"CapsLock & 6\"\nscript51 = f\"send {json_object['51.1 CapsLock & 6'][0]}\"\nhotkey51 = Hotkey(ahk, key_combo51, script51)\n\nkey_combo52 = \"~Alt Up\"\nscript52 = f\"{DoubleString} send {json_object['52.12x Alt'][0]}\"\nhotkey52 = Hotkey(ahk, key_combo52, script52)\n\nkey_combo53 = \"!MButton\"\nscript53 = f\"send {json_object['53.1 !MButton'][0]}\"\nhotkey53 = Hotkey(ahk, key_combo53, script53)\n\nkey_combo54 = \"!CapsLock\"\nscript54 = f\"send {json_object['54.1 !CapsLock'][0]}{nl}{json_object['54.0 !CapsLock'][0]}\"\nhotkey54 = Hotkey(ahk, key_combo54, script54)\n\nkey_combo55 = \"!+LButton\"\nscript55 = f\"send {json_object['55.1 !+LButton'][0]}\"\nhotkey55 = Hotkey(ahk, key_combo55, script55)\n\nkey_combo56 = \"!+RButton\"\nscript56 = f\"send {json_object['56.1 !+RButton'][0]}\"\nhotkey56 = Hotkey(ahk, key_combo56, script56)\n\nkey_combo57 = \"!+MButton\"\nscript57 = f\"{ExcelString} send {json_object['57.3 !+MButton'][0]}\"\nhotkey57 = Hotkey(ahk, key_combo57, script57)\n\nkey_combo58 = \"`\"\nscript58 = f\"send {json_object['58.1 `'][0]}\"\nhotkey58 = Hotkey(ahk, key_combo58, script58)\n\nkey_combo59 = \"^+!MButton\"\nscript59 = f\"send {json_object['59.1 ^+!MButton'][0]}\"\nhotkey59 = Hotkey(ahk, key_combo59, script59)\n\nkey_combo60 = \"^W\"\nscript60 = f\"{WordString} send {json_object['60.4 ^W'][0]}\"\nhotkey60 = Hotkey(ahk, key_combo60, script60)\n\nkey_combo61 = \"~Tab & R\"\nscript61 = f\"{WordString} send {json_object['61.4 Tab & R'][0]}\"\nhotkey61 = Hotkey(ahk, key_combo61, script61)\n\nkey_combo62 = \"~Tab & T\"\nscript62 = f\"{WordString} send {json_object['62.4 Tab & T'][0]}\"\nhotkey62 = Hotkey(ahk, key_combo62, script62)\n\nkey_combo63 = \"~Tab & 4\"\nscript63 = f\"{ExcelString} send {json_object['63.3 Tab & 4'][0]}\"\nhotkey63 = Hotkey(ahk, key_combo63, script63)\n\nkey_combo64 = \"~Tab & 5\"\nscript64 = f\"{ExcelString} send {json_object['64.3 Tab & 5'][0]}{nl}{ElseString} send {json_object['64.1 Tab & 5'][0]}\"\nhotkey64 = Hotkey(ahk, key_combo64, script64)\n\nkey_combo65 = \"~Tab & 6\"\nscript65 = f\"{ExcelString} send {json_object['65.3 Tab & 6'][0]}{nl}{ElseString} send {json_object['65.1 Tab & 6'][0]}\"\nhotkey65 = Hotkey(ahk, key_combo65, script65)\n\nkey_combo66 = \"~CapsLock & 1\"\nscript66 = f\"{ExcelString} send {json_object['66.3 CapsLock & 1'][0]}\"\nhotkey66 = Hotkey(ahk, key_combo66, script66)\n\nkey_combo67 = \"~CapsLock & 2\"\nscript67 = f\"send {json_object['67.1 CapsLock & 2'][0]}\"\nhotkey67 = Hotkey(ahk, key_combo67, script67)\n\nkey_combo68 = \"~CapsLock & 3\"\nscript68 = f\"send {json_object['68.1 CapsLock & 3'][0]}\"\nhotkey68 = Hotkey(ahk, key_combo68, script68)\n\nkey_combo69 = \"~CapsLock & 4\"\nscript69 = f\"send {json_object['69.1 CapsLock & 4'][0]}\"\nhotkey69 = Hotkey(ahk, key_combo69, script69)\n\nkey_combo70 = \"~CapsLock & Z\"\nscript70 = f\"send {json_object['70.1 CapsLock & Z'][0]}{nl}{ChromeString} send {json_object['70.5 CapsLock & Z'][0]}\"\nhotkey70 = Hotkey(ahk, key_combo70, script70)\n\nkey_combo71 = \"~CapsLock & X\"\nscript71 = f\"{ExcelString} send {json_object['71.3 CapsLock & X'][0]}{nl}{AodobeString} send {json_object['71.2 CapsLock & X'][0]}{nl}{WordString} send {json_object['71.4 CapsLock & X'][0]}{nl}{ChromeString} send {json_object['71.5 CapsLock & X'][0]}\"\nhotkey71 = Hotkey(ahk, key_combo71, script71)\n\nkey_combo72 = \"^+Space\"\nscript72 = f\"send {json_object['72.1 ^+Space'][0]}\"\nhotkey72 = Hotkey(ahk, key_combo72, script72)\n\nkey_combo73 = \"~CapsLock & R\"\nscript73 = f\"send {json_object['73.1 CapsLock & R'][0]}\"\nhotkey73 = Hotkey(ahk, key_combo73, script73)\n\nkey_combo74 = \"~CapsLock & E\"\nscript74 = f\"send {json_object['74.1 CapsLock & E'][0]}\"\nhotkey74 = Hotkey(ahk, key_combo74, script74)\n\nkey_combo75 = \"~CapsLock & F1\"\nscript75 = f\"{WordString} send {json_object['75.4 CapsLock & F1'][0]}\"\nhotkey75 = Hotkey(ahk, key_combo75, script75)\n\nkey_combo76 = \"~CapsLock & F2\"\nscript76 = f\"send {json_object['76.1 CapsLock & F2'][0]}\"\nhotkey76 = Hotkey(ahk, key_combo76, script76)\n\nkey_combo77 = \"~CapsLock & F3\"\nscript77 = f\"Run {json_object['77.6 CapsLock & F3'][0]}\"\nhotkey77 = Hotkey(ahk, key_combo77, script77)\n\nkey_combo78 = \"~CapsLock & F4\"\nscript78 = f\"Run {json_object['78.6 CapsLock & F4'][0]}\"\nhotkey78 = Hotkey(ahk, key_combo78, script78)\n\nkey_combo79 = \"~CapsLock & F5\"\nscript79 = f\"Run {json_object['79.6 CapsLock & F5'][0]}\"\nhotkey79 = Hotkey(ahk, key_combo79, script79)\n\nkey_combo80 = \"~CapsLock & F6\"\nscript80 = f\"Run {json_object['80.6 CapsLock & F6'][0]}\"\nhotkey80 = Hotkey(ahk, key_combo80, script80)\n\nkey_combo81 = \"~CapsLock & F7\"\nscript81 = f\"Run {json_object['81.6 CapsLock & F7'][0]}\"\nhotkey81 = Hotkey(ahk, key_combo81, script81)\n\nkey_combo82 = \"~CapsLock & F8\"\nscript82 = f\"Run {json_object['82.6 CapsLock & F8'][0]}\"\nhotkey82 = Hotkey(ahk, key_combo82, script82)\n\nkey_combo83 = \"~CapsLock & F9\"\nscript83 = f\"Run {json_object['83.6 CapsLock & F9'][0]}\"\nhotkey83 = Hotkey(ahk, key_combo83, script83)\n\nkey_combo84 = \"~CapsLock & F10\"\nscript84 = f\"Run {json_object['84.6 CapsLock & F10'][0]}\"\nhotkey84 = Hotkey(ahk, key_combo84, script84)\n\nkey_combo85 = \"~CapsLock & Space\"\nscript85 = f\"{ExcelString} send {json_object['85.3 CapsLock & Space'][0]}\"\nhotkey85 = Hotkey(ahk, key_combo85, script85)\n\nkey_combo86 = \"^+MButton\"\nscript86 = f\"send {json_object['86.1 ^+MButton'][0]}\"\nhotkey86 = Hotkey(ahk, key_combo86, script86)\n\nkey_combo87 = \"!LButton\"\nscript87 = f\"{ChromeString} send {json_object['87.5 !LButton'][0]}{nl}{ExcelString} send {json_object['87.3 !LButton'][0]}{nl}{ElseString} send {json_object['87.1 !LButton'][0]}\"\nhotkey87 = Hotkey(ahk, key_combo87, script87)\n\nkey_combo88 = \"^Space\"\nscript88 = f\"{ExcelString} send {json_object['88.3 ^Space'][0]}{nl}{AodobeString} send {json_object['88.2 ^Space'][0]}{nl}{ElseString} send {json_object['88.1 ^Space'][0]}\"\nhotkey88 = Hotkey(ahk, key_combo88, script88)\n\nkey_combo89 = \"~Alt & ~Tab Up\"\nscript89 = f\"send {json_object['89.1 ~Alt & ~Tab Up'][0]}\"\nhotkey89 = Hotkey(ahk, key_combo89, script89)\n\nkey_combo90 = \"~Tab & `\"\nscript90 = f\"send {{text}}{json_object['90.1 Tab Tilde'][0]}\"\nhotkey90 = Hotkey(ahk, key_combo90, script90)\n\nkey_combo91 = \"^x\"\nscript91 = f\"send {json_object['91.1 ^x'][0]}\"\nhotkey91 = Hotkey(ahk, key_combo91, script91)\n\nkey_combo92 = \"^+X\"\nscript92 = f\"send {json_object['92.1 ^+X'][0]}\"\nhotkey92 = Hotkey(ahk, key_combo92, script92)\n\nkey_combo93 = \"^!MButton\"\nscript93 = f\"{DoubleString} send {json_object['93.12x ^!MButton'][0]}{nl}{ElseString} send {json_object['93.1 ^!MButton'][0]}\"\nhotkey93 = Hotkey(ahk, key_combo93, script93)\n\nkey_combo94 = \"~CapsLock & F11\"\nscript94 = f\"Run {json_object['94.6 CapsLock & F11'][0]}\"\nhotkey94 = Hotkey(ahk, key_combo94, script94)\n\nkey_combo95 = \"~CapsLock & F12\"\nscript95 = f\"Run {json_object['95.6 CapsLock & F12'][0]}\"\nhotkey95 = Hotkey(ahk, key_combo95, script95)\n\nkey_combo96 = \"~Tab & F5\"\nscript96 = f\"send {json_object['96.1 Tab & F5'][0]}\"\nhotkey96 = Hotkey(ahk, key_combo96, script96)\n\nkey_combo97 = \"~Tab & F6\"\nscript97 = f\"send {json_object['97.1 Tab & F6'][0]}\"\nhotkey97 = Hotkey(ahk, key_combo97, script97)\n\n\ndef StopHotkeys():\n if (RUNTIME_DICT[\"HOTKEY_1\"] == 1):\n hotkey1.stop()\n if (RUNTIME_DICT[\"HOTKEY_2\"] == 1):\n hotkey2.stop()\n if (RUNTIME_DICT[\"HOTKEY_3\"] == 1):\n hotkey3.stop()\n if (RUNTIME_DICT[\"HOTKEY_4\"] == 1):\n hotkey4.stop()\n if (RUNTIME_DICT[\"HOTKEY_5\"] == 1):\n hotkey5.stop()\n if (RUNTIME_DICT[\"HOTKEY_6\"] == 1):\n hotkey6.stop()\n if (RUNTIME_DICT[\"HOTKEY_7\"] == 1):\n hotkey7.stop()\n if (RUNTIME_DICT[\"HOTKEY_8\"] == 1):\n hotkey8.stop()\n if (RUNTIME_DICT[\"HOTKEY_9\"] == 1):\n hotkey9.stop()\n if (RUNTIME_DICT[\"HOTKEY_10\"] == 1):\n hotkey10.stop()\n if (RUNTIME_DICT[\"HOTKEY_11\"] == 1):\n hotkey11.stop()\n if (RUNTIME_DICT[\"HOTKEY_12\"] == 1):\n hotkey12.stop()\n if (RUNTIME_DICT[\"HOTKEY_13\"] == 1):\n hotkey13.stop()\n if (RUNTIME_DICT[\"HOTKEY_14\"] == 1):\n hotkey14.stop()\n if (RUNTIME_DICT[\"HOTKEY_15\"] == 1):\n hotkey15.stop()\n if (RUNTIME_DICT[\"HOTKEY_16\"] == 1):\n hotkey16.stop()\n if (RUNTIME_DICT[\"HOTKEY_17\"] == 1):\n hotkey17.stop()\n if (RUNTIME_DICT[\"HOTKEY_18\"] == 1):\n hotkey18.stop()\n if (RUNTIME_DICT[\"HOTKEY_19\"] == 1):\n hotkey19.stop()\n if (RUNTIME_DICT[\"HOTKEY_20\"] == 1):\n hotkey20.stop()\n if (RUNTIME_DICT[\"HOTKEY_21\"] == 1):\n hotkey21.stop()\n if (RUNTIME_DICT[\"HOTKEY_22\"] == 1):\n hotkey22.stop()\n if (RUNTIME_DICT[\"HOTKEY_23\"] == 1):\n hotkey23.stop()\n if (RUNTIME_DICT[\"HOTKEY_24\"] == 1):\n hotkey24.stop()\n if (RUNTIME_DICT[\"HOTKEY_25\"] == 1):\n hotkey25.stop()\n if (RUNTIME_DICT[\"HOTKEY_26\"] == 1):\n hotkey26.stop()\n if (RUNTIME_DICT[\"HOTKEY_27\"] == 1):\n hotkey27.stop()\n if (RUNTIME_DICT[\"HOTKEY_28\"] == 1):\n hotkey28.stop()\n if (RUNTIME_DICT[\"HOTKEY_29\"] == 1):\n hotkey29.stop()\n if (RUNTIME_DICT[\"HOTKEY_30\"] == 1):\n hotkey30.stop()\n if (RUNTIME_DICT[\"HOTKEY_31\"] == 1):\n hotkey31.stop()\n if (RUNTIME_DICT[\"HOTKEY_32\"] == 1):\n hotkey32.stop()\n if (RUNTIME_DICT[\"HOTKEY_33\"] == 1):\n hotkey33.stop()\n if (RUNTIME_DICT[\"HOTKEY_34\"] == 1):\n hotkey34.stop()\n if (RUNTIME_DICT[\"HOTKEY_35\"] == 1):\n hotkey35.stop()\n if (RUNTIME_DICT[\"HOTKEY_36\"] == 1):\n hotkey36.stop()\n if (RUNTIME_DICT[\"HOTKEY_37\"] == 1):\n hotkey37.stop()\n if (RUNTIME_DICT[\"HOTKEY_38\"] == 1):\n hotkey38.stop()\n if (RUNTIME_DICT[\"HOTKEY_39\"] == 1):\n hotkey39.stop()\n if (RUNTIME_DICT[\"HOTKEY_40\"] == 1):\n hotkey40.stop()\n if (RUNTIME_DICT[\"HOTKEY_41\"] == 1):\n hotkey41.stop()\n if (RUNTIME_DICT[\"HOTKEY_42\"] == 1):\n hotkey42.stop()\n if (RUNTIME_DICT[\"HOTKEY_43\"] == 1):\n hotkey43.stop()\n if (RUNTIME_DICT[\"HOTKEY_44\"] == 1):\n hotkey44.stop()\n if (RUNTIME_DICT[\"HOTKEY_45\"] == 1):\n hotkey45.stop()\n if (RUNTIME_DICT[\"HOTKEY_46\"] == 1):\n hotkey46.stop()\n if (RUNTIME_DICT[\"HOTKEY_47\"] == 1):\n hotkey47.stop()\n if (RUNTIME_DICT[\"HOTKEY_48\"] == 1):\n hotkey48.stop()\n if (RUNTIME_DICT[\"HOTKEY_49\"] == 1):\n hotkey49.stop()\n if (RUNTIME_DICT[\"HOTKEY_50\"] == 1):\n hotkey50.stop()\n if (RUNTIME_DICT[\"HOTKEY_51\"] == 1):\n hotkey51.stop()\n if (RUNTIME_DICT[\"HOTKEY_52\"] == 1):\n hotkey52.stop()\n if (RUNTIME_DICT[\"HOTKEY_53\"] == 1):\n hotkey53.stop()\n if (RUNTIME_DICT[\"HOTKEY_54\"] == 1):\n hotkey54.stop()\n if (RUNTIME_DICT[\"HOTKEY_55\"] == 1):\n hotkey55.stop()\n if (RUNTIME_DICT[\"HOTKEY_56\"] == 1):\n hotkey56.stop()\n if (RUNTIME_DICT[\"HOTKEY_57\"] == 1):\n hotkey57.stop()\n if (RUNTIME_DICT[\"HOTKEY_58\"] == 1):\n hotkey58.stop()\n if (RUNTIME_DICT[\"HOTKEY_59\"] == 1):\n hotkey59.stop()\n if (RUNTIME_DICT[\"HOTKEY_60\"] == 1):\n hotkey60.stop()\n if (RUNTIME_DICT[\"HOTKEY_61\"] == 1):\n hotkey61.stop()\n if (RUNTIME_DICT[\"HOTKEY_62\"] == 1):\n hotkey62.stop()\n if (RUNTIME_DICT[\"HOTKEY_63\"] == 1):\n hotkey63.stop()\n if (RUNTIME_DICT[\"HOTKEY_64\"] == 1):\n hotkey64.stop()\n if (RUNTIME_DICT[\"HOTKEY_65\"] == 1):\n hotkey65.stop()\n if (RUNTIME_DICT[\"HOTKEY_66\"] == 1):\n hotkey66.stop()\n if (RUNTIME_DICT[\"HOTKEY_67\"] == 1):\n hotkey67.stop()\n if (RUNTIME_DICT[\"HOTKEY_68\"] == 1):\n hotkey68.stop()\n if (RUNTIME_DICT[\"HOTKEY_69\"] == 1):\n hotkey69.stop()\n if (RUNTIME_DICT[\"HOTKEY_70\"] == 1):\n hotkey70.stop()\n if (RUNTIME_DICT[\"HOTKEY_71\"] == 1):\n hotkey71.stop()\n if (RUNTIME_DICT[\"HOTKEY_72\"] == 1):\n hotkey72.stop()\n if (RUNTIME_DICT[\"HOTKEY_73\"] == 1):\n hotkey73.stop()\n if (RUNTIME_DICT[\"HOTKEY_74\"] == 1):\n hotkey74.stop()\n if (RUNTIME_DICT[\"HOTKEY_75\"] == 1):\n hotkey75.stop()\n if (RUNTIME_DICT[\"HOTKEY_76\"] == 1):\n hotkey76.stop()\n if (RUNTIME_DICT[\"HOTKEY_77\"] == 1):\n hotkey77.stop()\n if (RUNTIME_DICT[\"HOTKEY_78\"] == 1):\n hotkey78.stop()\n if (RUNTIME_DICT[\"HOTKEY_79\"] == 1):\n hotkey79.stop()\n if (RUNTIME_DICT[\"HOTKEY_80\"] == 1):\n hotkey80.stop()\n if (RUNTIME_DICT[\"HOTKEY_81\"] == 1):\n hotkey81.stop()\n if (RUNTIME_DICT[\"HOTKEY_82\"] == 1):\n hotkey82.stop()\n if (RUNTIME_DICT[\"HOTKEY_83\"] == 1):\n hotkey83.stop()\n if (RUNTIME_DICT[\"HOTKEY_84\"] == 1):\n hotkey84.stop()\n if (RUNTIME_DICT[\"HOTKEY_85\"] == 1):\n hotkey85.stop()\n if (RUNTIME_DICT[\"HOTKEY_86\"] == 1):\n hotkey86.stop()\n if (RUNTIME_DICT[\"HOTKEY_87\"] == 1):\n hotkey87.stop()\n if (RUNTIME_DICT[\"HOTKEY_88\"] == 1):\n hotkey88.stop()\n if (RUNTIME_DICT[\"HOTKEY_89\"] == 1):\n hotkey89.stop()\n if (RUNTIME_DICT[\"HOTKEY_90\"] == 1):\n hotkey90.stop()\n if (RUNTIME_DICT[\"HOTKEY_91\"] == 1):\n hotkey91.stop()\n if (RUNTIME_DICT[\"HOTKEY_92\"] == 1):\n hotkey92.stop()\n if (RUNTIME_DICT[\"HOTKEY_93\"] == 1):\n hotkey93.stop()\n if (RUNTIME_DICT[\"HOTKEY_94\"] == 1):\n hotkey94.stop()\n if (RUNTIME_DICT[\"HOTKEY_95\"] == 1):\n hotkey95.stop()\n if (RUNTIME_DICT[\"HOTKEY_96\"] == 1):\n hotkey96.stop()\n if (RUNTIME_DICT[\"HOTKEY_97\"] == 1):\n hotkey97.stop()\n\n\ndef StartHotkeys():\n if f\"{json_object['HOTKEY_1'][0]}\" == \"T\":\n hotkey1.start()\n RUNTIME_DICT[\"HOTKEY_1\"] = 1\n\n if f\"{json_object['HOTKEY_2'][0]}\" == \"T\":\n hotkey2.start()\n RUNTIME_DICT[\"HOTKEY_2\"] = 1\n\n if f\"{json_object['HOTKEY_3'][0]}\" == \"T\":\n hotkey3.start()\n RUNTIME_DICT[\"HOTKEY_3\"] = 1\n\n if f\"{json_object['HOTKEY_4'][0]}\" == \"T\":\n hotkey4.start()\n RUNTIME_DICT[\"HOTKEY_4\"] = 1\n\n if f\"{json_object['HOTKEY_5'][0]}\" == \"T\":\n hotkey5.start()\n RUNTIME_DICT[\"HOTKEY_5\"] = 1\n\n if f\"{json_object['HOTKEY_6'][0]}\" == \"T\":\n hotkey6.start()\n RUNTIME_DICT[\"HOTKEY_6\"] = 1\n\n if f\"{json_object['HOTKEY_7'][0]}\" == \"T\":\n hotkey7.start()\n RUNTIME_DICT[\"HOTKEY_7\"] = 1\n\n if f\"{json_object['HOTKEY_8'][0]}\" == \"T\":\n hotkey8.start()\n RUNTIME_DICT[\"HOTKEY_8\"] = 1\n\n if f\"{json_object['HOTKEY_9'][0]}\" == \"T\":\n hotkey9.start()\n RUNTIME_DICT[\"HOTKEY_9\"] = 1\n\n if f\"{json_object['HOTKEY_10'][0]}\" == \"T\":\n hotkey10.start()\n RUNTIME_DICT[\"HOTKEY_10\"] = 1\n\n if f\"{json_object['HOTKEY_11'][0]}\" == \"T\":\n hotkey11.start()\n RUNTIME_DICT[\"HOTKEY_11\"] = 1\n\n if f\"{json_object['HOTKEY_12'][0]}\" == \"T\":\n hotkey12.start()\n RUNTIME_DICT[\"HOTKEY_12\"] = 1\n\n if f\"{json_object['HOTKEY_13'][0]}\" == \"T\":\n hotkey13.start()\n RUNTIME_DICT[\"HOTKEY_13\"] = 1\n\n if f\"{json_object['HOTKEY_14'][0]}\" == \"T\":\n hotkey14.start()\n RUNTIME_DICT[\"HOTKEY_14\"] = 1\n\n if f\"{json_object['HOTKEY_15'][0]}\" == \"T\":\n hotkey15.start()\n RUNTIME_DICT[\"HOTKEY_15\"] = 1\n\n if f\"{json_object['HOTKEY_16'][0]}\" == \"T\":\n hotkey16.start()\n RUNTIME_DICT[\"HOTKEY_16\"] = 1\n\n if f\"{json_object['HOTKEY_17'][0]}\" == \"T\":\n hotkey17.start()\n RUNTIME_DICT[\"HOTKEY_17\"] = 1\n\n if f\"{json_object['HOTKEY_18'][0]}\" == \"T\":\n hotkey18.start()\n RUNTIME_DICT[\"HOTKEY_18\"] = 1\n\n if f\"{json_object['HOTKEY_19'][0]}\" == \"T\":\n hotkey19.start()\n RUNTIME_DICT[\"HOTKEY_19\"] = 1\n\n if f\"{json_object['HOTKEY_20'][0]}\" == \"T\":\n hotkey20.start()\n RUNTIME_DICT[\"HOTKEY_20\"] = 1\n\n if f\"{json_object['HOTKEY_21'][0]}\" == \"T\":\n hotkey21.start()\n RUNTIME_DICT[\"HOTKEY_21\"] = 1\n\n if f\"{json_object['HOTKEY_22'][0]}\" == \"T\":\n hotkey22.start()\n RUNTIME_DICT[\"HOTKEY_22\"] = 1\n\n if f\"{json_object['HOTKEY_23'][0]}\" == \"T\":\n hotkey23.start()\n RUNTIME_DICT[\"HOTKEY_23\"] = 1\n\n if f\"{json_object['HOTKEY_24'][0]}\" == \"T\":\n hotkey24.start()\n RUNTIME_DICT[\"HOTKEY_24\"] = 1\n\n if f\"{json_object['HOTKEY_25'][0]}\" == \"T\":\n hotkey25.start()\n RUNTIME_DICT[\"HOTKEY_25\"] = 1\n\n if f\"{json_object['HOTKEY_26'][0]}\" == \"T\":\n hotkey26.start()\n RUNTIME_DICT[\"HOTKEY_26\"] = 1\n\n if f\"{json_object['HOTKEY_27'][0]}\" == \"T\":\n hotkey27.start()\n RUNTIME_DICT[\"HOTKEY_27\"] = 1\n\n if f\"{json_object['HOTKEY_28'][0]}\" == \"T\":\n hotkey28.start()\n RUNTIME_DICT[\"HOTKEY_28\"] = 1\n\n if f\"{json_object['HOTKEY_29'][0]}\" == \"T\":\n hotkey29.start()\n RUNTIME_DICT[\"HOTKEY_29\"] = 1\n\n if f\"{json_object['HOTKEY_30'][0]}\" == \"T\":\n hotkey30.start()\n RUNTIME_DICT[\"HOTKEY_30\"] = 1\n\n if f\"{json_object['HOTKEY_31'][0]}\" == \"T\":\n hotkey31.start()\n RUNTIME_DICT[\"HOTKEY_31\"] = 1\n\n if f\"{json_object['HOTKEY_32'][0]}\" == \"T\":\n hotkey32.start()\n RUNTIME_DICT[\"HOTKEY_32\"] = 1\n\n if f\"{json_object['HOTKEY_33'][0]}\" == \"T\":\n hotkey33.start()\n RUNTIME_DICT[\"HOTKEY_33\"] = 1\n\n if f\"{json_object['HOTKEY_34'][0]}\" == \"T\":\n hotkey34.start()\n RUNTIME_DICT[\"HOTKEY_34\"] = 1\n\n if f\"{json_object['HOTKEY_35'][0]}\" == \"T\":\n hotkey35.start()\n RUNTIME_DICT[\"HOTKEY_35\"] = 1\n\n if f\"{json_object['HOTKEY_36'][0]}\" == \"T\":\n hotkey36.start()\n RUNTIME_DICT[\"HOTKEY_36\"] = 1\n\n if f\"{json_object['HOTKEY_37'][0]}\" == \"T\":\n hotkey37.start()\n RUNTIME_DICT[\"HOTKEY_37\"] = 1\n\n if f\"{json_object['HOTKEY_38'][0]}\" == \"T\":\n hotkey38.start()\n RUNTIME_DICT[\"HOTKEY_38\"] = 1\n\n if f\"{json_object['HOTKEY_39'][0]}\" == \"T\":\n hotkey39.start()\n RUNTIME_DICT[\"HOTKEY_39\"] = 1\n\n if f\"{json_object['HOTKEY_40'][0]}\" == \"T\":\n hotkey40.start()\n RUNTIME_DICT[\"HOTKEY_40\"] = 1\n\n if f\"{json_object['HOTKEY_41'][0]}\" == \"T\":\n hotkey41.start()\n RUNTIME_DICT[\"HOTKEY_41\"] = 1\n\n if f\"{json_object['HOTKEY_42'][0]}\" == \"T\":\n hotkey42.start()\n RUNTIME_DICT[\"HOTKEY_42\"] = 1\n\n if f\"{json_object['HOTKEY_43'][0]}\" == \"T\":\n hotkey43.start()\n RUNTIME_DICT[\"HOTKEY_43\"] = 1\n\n if f\"{json_object['HOTKEY_44'][0]}\" == \"T\":\n hotkey44.start()\n RUNTIME_DICT[\"HOTKEY_44\"] = 1\n\n if f\"{json_object['HOTKEY_45'][0]}\" == \"T\":\n hotkey45.start()\n RUNTIME_DICT[\"HOTKEY_45\"] = 1\n\n if f\"{json_object['HOTKEY_46'][0]}\" == \"T\":\n hotkey46.start()\n RUNTIME_DICT[\"HOTKEY_46\"] = 1\n\n if f\"{json_object['HOTKEY_47'][0]}\" == \"T\":\n hotkey47.start()\n RUNTIME_DICT[\"HOTKEY_47\"] = 1\n\n if f\"{json_object['HOTKEY_48'][0]}\" == \"T\":\n hotkey48.start()\n RUNTIME_DICT[\"HOTKEY_48\"] = 1\n\n if f\"{json_object['HOTKEY_49'][0]}\" == \"T\":\n hotkey49.start()\n RUNTIME_DICT[\"HOTKEY_49\"] = 1\n\n if f\"{json_object['HOTKEY_50'][0]}\" == \"T\":\n hotkey50.start()\n RUNTIME_DICT[\"HOTKEY_50\"] = 1\n\n if f\"{json_object['HOTKEY_51'][0]}\" == \"T\":\n hotkey51.start()\n RUNTIME_DICT[\"HOTKEY_51\"] = 1\n\n if f\"{json_object['HOTKEY_52'][0]}\" == \"T\":\n hotkey52.start()\n RUNTIME_DICT[\"HOTKEY_52\"] = 1\n\n if f\"{json_object['HOTKEY_53'][0]}\" == \"T\":\n hotkey53.start()\n RUNTIME_DICT[\"HOTKEY_53\"] = 1\n\n if f\"{json_object['HOTKEY_54'][0]}\" == \"T\":\n hotkey54.start()\n RUNTIME_DICT[\"HOTKEY_54\"] = 1\n\n if f\"{json_object['HOTKEY_55'][0]}\" == \"T\":\n hotkey55.start()\n RUNTIME_DICT[\"HOTKEY_55\"] = 1\n\n if f\"{json_object['HOTKEY_56'][0]}\" == \"T\":\n hotkey56.start()\n RUNTIME_DICT[\"HOTKEY_56\"] = 1\n\n if f\"{json_object['HOTKEY_57'][0]}\" == \"T\":\n hotkey57.start()\n RUNTIME_DICT[\"HOTKEY_57\"] = 1\n\n if f\"{json_object['HOTKEY_58'][0]}\" == \"T\":\n hotkey58.start()\n RUNTIME_DICT[\"HOTKEY_58\"] = 1\n\n if f\"{json_object['HOTKEY_59'][0]}\" == \"T\":\n hotkey59.start()\n RUNTIME_DICT[\"HOTKEY_59\"] = 1\n\n if f\"{json_object['HOTKEY_60'][0]}\" == \"T\":\n hotkey60.start()\n RUNTIME_DICT[\"HOTKEY_60\"] = 1\n\n if f\"{json_object['HOTKEY_61'][0]}\" == \"T\":\n hotkey61.start()\n RUNTIME_DICT[\"HOTKEY_61\"] = 1\n\n if f\"{json_object['HOTKEY_62'][0]}\" == \"T\":\n hotkey62.start()\n RUNTIME_DICT[\"HOTKEY_62\"] = 1\n\n if f\"{json_object['HOTKEY_63'][0]}\" == \"T\":\n hotkey63.start()\n RUNTIME_DICT[\"HOTKEY_63\"] = 1\n\n if f\"{json_object['HOTKEY_64'][0]}\" == \"T\":\n hotkey64.start()\n RUNTIME_DICT[\"HOTKEY_64\"] = 1\n\n if f\"{json_object['HOTKEY_65'][0]}\" == \"T\":\n hotkey65.start()\n RUNTIME_DICT[\"HOTKEY_65\"] = 1\n\n if f\"{json_object['HOTKEY_66'][0]}\" == \"T\":\n hotkey66.start()\n RUNTIME_DICT[\"HOTKEY_66\"] = 1\n\n if f\"{json_object['HOTKEY_67'][0]}\" == \"T\":\n hotkey67.start()\n RUNTIME_DICT[\"HOTKEY_67\"] = 1\n\n if f\"{json_object['HOTKEY_68'][0]}\" == \"T\":\n hotkey68.start()\n RUNTIME_DICT[\"HOTKEY_68\"] = 1\n\n if f\"{json_object['HOTKEY_69'][0]}\" == \"T\":\n hotkey69.start()\n RUNTIME_DICT[\"HOTKEY_69\"] = 1\n\n if f\"{json_object['HOTKEY_70'][0]}\" == \"T\":\n hotkey70.start()\n RUNTIME_DICT[\"HOTKEY_70\"] = 1\n\n if f\"{json_object['HOTKEY_71'][0]}\" == \"T\":\n hotkey71.start()\n RUNTIME_DICT[\"HOTKEY_71\"] = 1\n\n if f\"{json_object['HOTKEY_72'][0]}\" == \"T\":\n hotkey72.start()\n RUNTIME_DICT[\"HOTKEY_72\"] = 1\n\n if f\"{json_object['HOTKEY_73'][0]}\" == \"T\":\n hotkey73.start()\n RUNTIME_DICT[\"HOTKEY_73\"] = 1\n\n if f\"{json_object['HOTKEY_74'][0]}\" == \"T\":\n hotkey74.start()\n RUNTIME_DICT[\"HOTKEY_74\"] = 1\n\n if f\"{json_object['HOTKEY_75'][0]}\" == \"T\":\n hotkey75.start()\n RUNTIME_DICT[\"HOTKEY_75\"] = 1\n\n if f\"{json_object['HOTKEY_76'][0]}\" == \"T\":\n hotkey76.start()\n RUNTIME_DICT[\"HOTKEY_76\"] = 1\n\n if f\"{json_object['HOTKEY_77'][0]}\" == \"T\":\n hotkey77.start()\n RUNTIME_DICT[\"HOTKEY_77\"] = 1\n\n if f\"{json_object['HOTKEY_78'][0]}\" == \"T\":\n hotkey78.start()\n RUNTIME_DICT[\"HOTKEY_78\"] = 1\n\n if f\"{json_object['HOTKEY_79'][0]}\" == \"T\":\n hotkey79.start()\n RUNTIME_DICT[\"HOTKEY_79\"] = 1\n\n if f\"{json_object['HOTKEY_80'][0]}\" == \"T\":\n hotkey80.start()\n RUNTIME_DICT[\"HOTKEY_80\"] = 1\n\n if f\"{json_object['HOTKEY_81'][0]}\" == \"T\":\n hotkey81.start()\n RUNTIME_DICT[\"HOTKEY_81\"] = 1\n\n if f\"{json_object['HOTKEY_82'][0]}\" == \"T\":\n hotkey82.start()\n RUNTIME_DICT[\"HOTKEY_82\"] = 1\n\n if f\"{json_object['HOTKEY_83'][0]}\" == \"T\":\n hotkey83.start()\n RUNTIME_DICT[\"HOTKEY_83\"] = 1\n\n if f\"{json_object['HOTKEY_84'][0]}\" == \"T\":\n hotkey84.start()\n RUNTIME_DICT[\"HOTKEY_84\"] = 1\n\n if f\"{json_object['HOTKEY_85'][0]}\" == \"T\":\n hotkey85.start()\n RUNTIME_DICT[\"HOTKEY_85\"] = 1\n\n if f\"{json_object['HOTKEY_86'][0]}\" == \"T\":\n hotkey86.start()\n RUNTIME_DICT[\"HOTKEY_86\"] = 1\n\n if f\"{json_object['HOTKEY_87'][0]}\" == \"T\":\n hotkey87.start()\n RUNTIME_DICT[\"HOTKEY_87\"] = 1\n\n if f\"{json_object['HOTKEY_88'][0]}\" == \"T\":\n hotkey88.start()\n RUNTIME_DICT[\"HOTKEY_88\"] = 1\n\n if f\"{json_object['HOTKEY_89'][0]}\" == \"T\":\n hotkey89.start()\n RUNTIME_DICT[\"HOTKEY_89\"] = 1\n\n if f\"{json_object['HOTKEY_90'][0]}\" == \"T\":\n hotkey90.start()\n RUNTIME_DICT[\"HOTKEY_90\"] = 1\n\n if f\"{json_object['HOTKEY_91'][0]}\" == \"T\":\n hotkey91.start()\n RUNTIME_DICT[\"HOTKEY_91\"] = 1\n\n if f\"{json_object['HOTKEY_92'][0]}\" == \"T\":\n hotkey92.start()\n RUNTIME_DICT[\"HOTKEY_92\"] = 1\n\n if f\"{json_object['HOTKEY_93'][0]}\" == \"T\":\n hotkey93.start()\n RUNTIME_DICT[\"HOTKEY_93\"] = 1\n\n if f\"{json_object['HOTKEY_94'][0]}\" == \"T\":\n hotkey94.start()\n RUNTIME_DICT[\"HOTKEY_94\"] = 1\n\n if f\"{json_object['HOTKEY_95'][0]}\" == \"T\":\n hotkey95.start()\n RUNTIME_DICT[\"HOTKEY_95\"] = 1\n\n if f\"{json_object['HOTKEY_96'][0]}\" == \"T\":\n hotkey96.start()\n RUNTIME_DICT[\"HOTKEY_96\"] = 1\n\n if f\"{json_object['HOTKEY_97'][0]}\" == \"T\":\n hotkey97.start()\n RUNTIME_DICT[\"HOTKEY_97\"] = 1\n\n\nScriptList = [script1, script2, script3, script4, script5, script6, script7, script8, script9, script10, script11, script12,\n script13, script14, script15, script16, script17, script18, script19, script20, script21, script22, script23, script24, script25,\n script26, script27, script28, script29, script30, script31, script32, script33, script34, script35, script36, script37,\n script38, script39, script40, script41, script42, script43, script44, script45, script46, script47, script48, script49,\n script50, script51, script52, script53, script54, script55, script56, script57, script58, script59, script60, script61, script62,\n script63, script64, script65, script66, script67, script68, script69, script70, script71, script72, script73, script74,\n script75, script76, script77, script78, script79, script80, script81, script82, script83, script84, script85, script86,\n script87, script88, script89, script90, script91, script92, script93, script94, script95, script96, script97]\n\n\nRUNTIME_DICT = {\n \"HOTKEY_1\": 0,\n \"HOTKEY_2\": 0,\n \"HOTKEY_3\": 0,\n \"HOTKEY_4\": 0,\n \"HOTKEY_5\": 0,\n \"HOTKEY_6\": 0,\n \"HOTKEY_7\": 0,\n \"HOTKEY_8\": 0,\n \"HOTKEY_9\": 0,\n \"HOTKEY_10\": 0,\n \"HOTKEY_11\": 0,\n \"HOTKEY_12\": 0,\n \"HOTKEY_13\": 0,\n \"HOTKEY_14\": 0,\n \"HOTKEY_15\": 0,\n \"HOTKEY_16\": 0,\n \"HOTKEY_17\": 0,\n \"HOTKEY_18\": 0,\n \"HOTKEY_19\": 0,\n \"HOTKEY_20\": 0,\n \"HOTKEY_21\": 0,\n \"HOTKEY_22\": 0,\n \"HOTKEY_23\": 0,\n \"HOTKEY_24\": 0,\n \"HOTKEY_25\": 0,\n \"HOTKEY_26\": 0,\n \"HOTKEY_27\": 0,\n \"HOTKEY_28\": 0,\n \"HOTKEY_29\": 0,\n \"HOTKEY_30\": 0,\n \"HOTKEY_31\": 0,\n \"HOTKEY_32\": 0,\n \"HOTKEY_33\": 0,\n \"HOTKEY_34\": 0,\n \"HOTKEY_35\": 0,\n \"HOTKEY_36\": 0,\n \"HOTKEY_37\": 0,\n \"HOTKEY_38\": 0,\n \"HOTKEY_39\": 0,\n \"HOTKEY_40\": 0,\n \"HOTKEY_41\": 0,\n \"HOTKEY_42\": 0,\n \"HOTKEY_43\": 0,\n \"HOTKEY_44\": 0,\n \"HOTKEY_45\": 0,\n \"HOTKEY_46\": 0,\n \"HOTKEY_47\": 0,\n \"HOTKEY_48\": 0,\n \"HOTKEY_49\": 0,\n \"HOTKEY_50\": 0,\n \"HOTKEY_51\": 0,\n \"HOTKEY_52\": 0,\n \"HOTKEY_53\": 0,\n \"HOTKEY_54\": 0,\n \"HOTKEY_55\": 0,\n \"HOTKEY_56\": 0,\n \"HOTKEY_57\": 0,\n \"HOTKEY_58\": 0,\n \"HOTKEY_59\": 0,\n \"HOTKEY_60\": 0,\n \"HOTKEY_61\": 0,\n \"HOTKEY_62\": 0,\n \"HOTKEY_63\": 0,\n \"HOTKEY_64\": 0,\n \"HOTKEY_65\": 0,\n \"HOTKEY_66\": 0,\n \"HOTKEY_67\": 0,\n \"HOTKEY_68\": 0,\n \"HOTKEY_69\": 0,\n \"HOTKEY_70\": 0,\n \"HOTKEY_71\": 0,\n \"HOTKEY_72\": 0,\n \"HOTKEY_73\": 0,\n \"HOTKEY_74\": 0,\n \"HOTKEY_75\": 0,\n \"HOTKEY_76\": 0,\n \"HOTKEY_77\": 0,\n \"HOTKEY_78\": 0,\n \"HOTKEY_79\": 0,\n \"HOTKEY_80\": 0,\n \"HOTKEY_81\": 0,\n \"HOTKEY_82\": 0,\n \"HOTKEY_83\": 0,\n \"HOTKEY_84\": 0,\n \"HOTKEY_85\": 0,\n \"HOTKEY_86\": 0,\n \"HOTKEY_87\": 0,\n \"HOTKEY_88\": 0,\n \"HOTKEY_89\": 0,\n \"HOTKEY_90\": 0,\n \"HOTKEY_91\": 0,\n \"HOTKEY_92\": 0,\n \"HOTKEY_93\": 0,\n \"HOTKEY_94\": 0,\n \"HOTKEY_95\": 0,\n \"HOTKEY_96\": 0,\n \"HOTKEY_97\": 0,\n}\n\n", "repo_name": "MGM1995/MATERIALITY", "sub_path": "MainApp.py", "file_name": "MainApp.py", "file_ext": "py", "file_size_in_byte": 36361, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "27", "api": [{"api_name": "os.path.dirname", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 11, "usage_type": "call"}, {"api_name": "ahk.AHK", "line_number": 16, "usage_type": "call"}, {"api_name": "ahk.directives.NoTrayIcon", "line_number": 16, "usage_type": "name"}, {"api_name": "ahk.Hotkey", "line_number": 32, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 36, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 40, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 44, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 49, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 53, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 58, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 63, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 67, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 71, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 75, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 79, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 83, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 87, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 91, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 95, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 99, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 103, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 107, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 111, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 115, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 119, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 123, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 127, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 131, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 135, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 139, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 143, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 147, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 151, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 155, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 159, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 163, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 167, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 171, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 175, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 179, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 183, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 187, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 191, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 195, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 199, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 203, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 207, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 211, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 216, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 220, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 224, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 228, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 232, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 236, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 240, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 244, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 248, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 252, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 256, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 260, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 264, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 268, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 272, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 276, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 280, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 284, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 288, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 292, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 296, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 300, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 304, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 308, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 312, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 316, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 320, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 324, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 328, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 332, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 336, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 340, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 344, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 348, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 352, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 356, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 360, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 364, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 368, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 372, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 376, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 380, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 384, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 388, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 392, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 396, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 400, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 404, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 408, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 412, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 416, "usage_type": "call"}, {"api_name": "ahk.Hotkey", "line_number": 420, "usage_type": "call"}]} +{"seq_id": "26022336845", "text": "#!/usr/bin/env python\n\"\"\"\nWrapper for langid.net\nbased on code from http://stackoverflow.com/questions/1136604/how-do-i-use-the-json-google-translate-api\n\"\"\"\nimport urllib\nimport json\nimport time\nimport random\nimport logging\nlogger = logging.getLogger(__name__)\n\nclass LangidNetLangid(object):\n base_url='http://api.langid.net/identify.json?'\n\n def __init__( self, simulate=False, rate=None, apikey=None, retry=60 ):\n if rate is None:\n if apikey is None:\n self.rate = 100\n else:\n self.rate = 1000\n else:\n self.rate = rate\n self.simulate = simulate\n self.apikey = apikey\n self.retry = retry\n\n def classify(self, text):\n if isinstance(text, unicode): text = text.encode('utf-8')\n if self.simulate:\n response = {'response':{'iso':'en'}}\n else:\n query = {'string': text[:199]}\n if self.apikey is not None:\n query['api-key'] = self.apikey\n data = urllib.urlencode(query)\n search_results = urllib.urlopen(self.base_url+data)\n response = json.loads(search_results.read())\n retry = self.retry\n while response['response'] is None:\n logger.warning(response)\n logger.warning(\"Got a None response, retrying in %d seconds\", retry)\n time.sleep(retry)\n retry *= 2\n search_results = urllib.urlopen(self.base_url+data)\n try:\n response = json.loads(search_results.read())\n except ValueError:\n response = {'response': None}\n result = response['response']['iso']\n return result\n\n def batch_classify(self, texts):\n result = []\n interval = 3600.0 / self.rate \n for text in texts:\n result.append(self.classify(text))\n time.sleep(interval)\n return result\n \n\n", "repo_name": "eyadsibai/hydrat", "sub_path": "src/hydrat/wrapper/langidnet.py", "file_name": "langidnet.py", "file_ext": "py", "file_size_in_byte": 1716, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "logging.getLogger", "line_number": 11, "usage_type": "call"}, {"api_name": "urllib.urlencode", "line_number": 36, "usage_type": "call"}, {"api_name": "urllib.urlopen", "line_number": 37, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 38, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 43, "usage_type": "call"}, {"api_name": "urllib.urlopen", "line_number": 45, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 47, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 58, "usage_type": "call"}]} +{"seq_id": "28595515592", "text": "import csv\nimport numpy as np\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.tree import export_graphviz\nfrom subprocess import call\n\n#load data\ndata = []\nwith open('spam.csv', 'r') as csvfile:\n reader = csv.reader(csvfile)\n data = list(reader)\n\n#clean data\nlabels = []\nx = []\nheader = data[0] #the first row has headers\nheader = header[1:-1] #exclude the type header and the empty header\ndata = data[1:]\nfor row in data: #skip header row\n clean_row = []\n labels.append(row[-1]) #add the label\n row = row[1:-1] #exlude the label and the first num\n for elem in row:\n clean_row.append(float(elem))\n x.append(clean_row)\nassert(len(labels) == len(x))\n\n#split into test/train\nx_train, x_test, labels_train,labels_test = train_test_split(x,labels,test_size=.5)\n\n#train decision tree\n# tree_classifier = DecisionTreeClassifier(max_depth = 5) #stop overfitting\ntree_classifier = DecisionTreeClassifier() #let it overfit\ntree_classifier = tree_classifier.fit(x_train,labels_train)\nprint(\"Decision Tree Train Score:\",tree_classifier.score(x_train,labels_train))\nprint(\"Decision Tree Test Score:\",tree_classifier.score(x_test,labels_test))\n\n#train random forest\nforest_classifier = RandomForestClassifier()\nforest_classifier = forest_classifier.fit(x_train,labels_train)\nprint(\"Random Forest Train Score:\",forest_classifier.score(x_train,labels_train))\nprint(\"Random Forest Test Score:\",forest_classifier.score(x_test,labels_test))\n\nexport_graphviz(tree_classifier,out_file='tree.dot')\ncall(['dot','-Tpng','tree.dot','-o','tree.png'])\n", "repo_name": "CMU15-112/15-112-Optional-Lectures", "sub_path": "15-112-Optional-Lecture-Spam-Filter/tree.py", "file_name": "tree.py", "file_ext": "py", "file_size_in_byte": 1672, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "csv.reader", "line_number": 12, "usage_type": "call"}, {"api_name": "sklearn.cross_validation.train_test_split", "line_number": 31, "usage_type": "call"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 35, "usage_type": "call"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 41, "usage_type": "call"}, {"api_name": "sklearn.tree.export_graphviz", "line_number": 46, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 47, "usage_type": "call"}]} +{"seq_id": "10517211817", "text": "import unittest\nfrom collections import defaultdict\n\n\"\"\"\n\nYou are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.\n\nNote that the partition is done so that after concatenating all the parts in order, the resultant string should be s.\n\nReturn a list of integers representing the size of these parts.\n\nConstraints:\n\n1 <= s.length <= 500\ns consists of lowercase English letters.\n\n\"\"\"\n\n\nclass Solution:\n def partitionLabels(self, s: str) -> [int]:\n\n # GREEDY (O)2n\n ret = []\n last = defaultdict()\n for i in range(len(s)): last[s[i]] = i\n\n localMax = last[s[0]]\n\n for i in range(len(s)):\n\n localMax = max(last[s[i]], localMax)\n\n if localMax == i:\n if len(ret): ret.append(i+1-sum(ret))\n else: ret.append(i+1)\n\n return ret\n\ndef test_partitionLabels():\n solution = Solution()\n\n # Test case 1\n s = \"abac\"\n expected_output = [3,1]\n assert solution.partitionLabels(s) == expected_output\n\n # Test case 2\n s = \"abcdef\"\n expected_output = [1, 1, 1, 1, 1, 1]\n assert solution.partitionLabels(s) == expected_output\n\n # Test case 3\n s = \"aabbccddeeffgg\"\n expected_output = [2, 2, 2, 2, 2, 2, 2]\n assert solution.partitionLabels(s) == expected_output\n\n # Test case 4\n s = \"abcde\"\n expected_output = [1, 1, 1, 1, 1]\n assert solution.partitionLabels(s) == expected_output\n\n # Test case 5 (single character)\n s = \"a\"\n expected_output = [1]\n assert solution.partitionLabels(s) == expected_output\n print(\"All test cases passed.\")\n\n\ntest_partitionLabels()\n", "repo_name": "lostintime101/leetcode-algos-data-structures", "sub_path": "greedy/763_partition_labels.py", "file_name": "763_partition_labels.py", "file_ext": "py", "file_size_in_byte": 1684, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "collections.defaultdict", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "9080773249", "text": "import torch\nimport matplotlib.pyplot as plt\ntorch.manual_seed(10)\n\n# 学习率 20191015修改\nlr = 0.05\n\n# 创建训练数据\nx = torch.rand(20, 1) * 10 # x data (tensor), shape=(20, 1)\ny = 2*x + (5 + torch.randn(20, 1)) # y data (tensor), shape=(20, 1), torch.randn(20, 1)是添加的随机噪声\n\n# 构建线性回归参数\nw = torch.randn((1), requires_grad=True)\nb = torch.zeros((1), requires_grad=True)\n\nfor iteration in range(1000):\n\n # 前向传播(构建y=wx+b)\n wx = torch.mul(w, x)\n y_pred = torch.add(wx, b)\n\n # 计算 MSE loss(0.5是为了约掉求导时的2)\n loss = (0.5 * (y - y_pred) ** 2).mean()\n\n # 反向传播(计算反向传播的梯度)\n loss.backward()\n\n # 更新参数(w=w-LR*w.grad b=b-LR*w.grad)\n b.data.sub_(lr * b.grad)\n w.data.sub_(lr * w.grad)\n\n # 清零张量的梯度(20191015增加,每次迭代完一次对张量清零)\n w.grad.zero_()\n b.grad.zero_()\n\n # 绘图\n if iteration % 20 == 0:\n\n plt.scatter(x.data.numpy(), y.data.numpy()) # 训练数据的散点图\n plt.plot(x.data.numpy(), y_pred.data.numpy(), 'r-', lw=5) # 每次迭代得到的拟合线\n plt.text(2, 20, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'}) # 显示损失\n plt.xlim(1.5, 10) # X轴\n plt.ylim(8, 28) # Y轴\n plt.title(\"Iteration: {}\\nw: {} b: {}\".format(iteration, w.data.numpy(), b.data.numpy())) # 表头数据\n plt.pause(1) # 动图显示的间隔\n\n # 停止的条件,当loss小于1时停止训练\n if loss.data.numpy() < 1:\n break\n", "repo_name": "Perry2019/PyTorchABC", "sub_path": "lesson-03/lesson-03-Linear-Regression.py", "file_name": "lesson-03-Linear-Regression.py", "file_ext": "py", "file_size_in_byte": 1610, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "torch.manual_seed", "line_number": 3, "usage_type": "call"}, {"api_name": "torch.rand", "line_number": 9, "usage_type": "call"}, {"api_name": "torch.randn", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.randn", "line_number": 13, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 14, "usage_type": "call"}, {"api_name": "torch.mul", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.add", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.text", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.pause", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}]} +{"seq_id": "73922168385", "text": "#!/usr/bin/env python\nimport serial\nimport sys\nimport time\nimport calendar\nimport rospy\nfrom sensor_msgs.msg import NavSatFix\n\n# Convert Saxagesimal to decimal\ndef Sexagesimal2Decimal(data_in):\n\tlength = len(data_in)\n\t# 6 bit min + 1 bit dot\n\tdata_out = float(data_in[0 :length-7])\n\tmin_ = float(data_in[length-7 :length])\n\tdata_out += min_ / 60.\n\treturn data_out\n\n# Convert HHMMSS to time.time() format\ndef ToTimeFormat(in_str):\n\tutc_struct = time.gmtime()\n\tutc_list = list(utc_struct)\n\thours = int(in_str[0:2])\n\tminutes = int(in_str[2:4])\n\tseconds = int(in_str[4:6])\n\tutc_list[3] = hours\n\tutc_list[4] = minutes\n\tutc_list[5] = seconds\n\treturn calendar.timegm(tuple(utc_list))\n\nclass GPSHandler(object):\n\tdef __init__(self, port):\n\t\tself.node_name = rospy.get_name()\n\t\tself.port = port\n\t\tself.info = \"\"\n\t\tself.info_list = None\n\t\tself.seq = 0\n\t\tself.pub_fix = rospy.Publisher(\"fix\", NavSatFix, queue_size = 10)\n\t\trospy.loginfo(\"[%s] Initializing ...\" %(self.node_name))\n\tdef read_info(self, event):\n\t\t# Read one line \n\t\tself.info = self.port.readline()\n\t\t# Split with ','\n\t\tself.info_list = self.info.split(',')\n\t\tif self.info_list[0] == '$GPGGA':\n\t\t\tself._gps_pub()\n\tdef _gps_pub(self):\n\t\tif self.info_list[2] == '':\n\t\t\trospy.loginfo(\"[%s] No data receiving ... Try go outside?\" %(self.node_name))\n\t\t\treturn\n\t\t# info format:\n\t\t# GPGGA UTC_time latitude N/S longitude E/W state number_of_sat HDOP altitude others\t\t\n\t\tfix = NavSatFix()\n\t\tfix.header.seq = self.seq\n\t\t# Use received data\n\t\t#fix.header.stamp = ToTimeFormat(self.info_list[1])\n\t\t# Use rospy.Time.now\n\t\tfix.header.stamp = rospy.Time.now()\n\t\tfix.header.frame_id = 'gps_'\n\t\tlat = float(Sexagesimal2Decimal(self.info_list[2]))\n\t\tlongi = float(Sexagesimal2Decimal(self.info_list[4]))\n\t\tif self.info_list[3] == 'S':\n\t\t\tfix.latitude = -lat\n\t\telse:\n\t\t\tfix.latitude = lat\n\n\t\tif self.info_list[5] == 'W':\n\t\t\tfix.longitude = -longi\n\t\telse:\n\t\t\tfix.longitude = longi\n\n\t\trospy.loginfo(\"[%s] %s %s %s %s\" %(self.node_name, self.info_list[3], \n\t\t\t\t\t\t lat, self.info_list[5],\n\t\t\t\t\t\t longi))\n\t\t# Covariance matrix\n\t\t# Refer to nmea_navsat_driver\n\t\ttry:\n\t\t\thdop = float(self.info_list[8])\n\t\texcept ValueError:\n\t\t\tpass\n\t\tfix.position_covariance[0] = hdop ** 2\n\t\tfix.position_covariance[4] = hdop ** 2\n\t\tfix.position_covariance[8] = (2* hdop) ** 2\n\t\tfix.position_covariance_type = \\\n\t\t\tNavSatFix.COVARIANCE_TYPE_APPROXIMATED\n\t\tfix.altitude = float(self.info_list[9]) + float(self.info_list[11])\n\t\tself.pub_fix.publish(fix)\n\t\tself.info = \"\"\n\t\tself.info_list = None\n\t\tself.seq += 1\nif __name__ == \"__main__\":\n\trospy.init_node(\"gps_node\", anonymous = False)\n\t# Parameters\n\tport = rospy.get_param(\"~port\", '/dev/ttyUSB0')\n\tflush_size = rospy.get_param(\"~flush_size\", 20)\n\ttry:\n\t\tgps_port = serial.Serial(port, 4800, timeout = 1)\n\texcept:\n\t\trospy.loginfo(\"[%s] Cann't find port: %s\" %(rospy.get_name(), port))\n\t\tsys.exit(0)\n\tgps = GPSHandler(gps_port)\n\t# Flush first data\n\trospy.loginfo(\"[%s] Flush first %s data\" %(rospy.get_name(), flush_size))\n\tfor i in range(0, flush_size):\n\t\tgps_port.readline()\n\trospy.loginfo(\"[%s] Start to publish gps data\" %(rospy.get_name()))\n\trospy.Timer(rospy.Duration.from_sec(0.1), gps.read_info)\n\trospy.spin()\n", "repo_name": "championway/self-driving-robot", "sub_path": "catkin_ws/src/gps_receiver/src/gps_node.py", "file_name": "gps_node.py", "file_ext": "py", "file_size_in_byte": 3184, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "time.gmtime", "line_number": 20, "usage_type": "call"}, {"api_name": "calendar.timegm", "line_number": 28, "usage_type": "call"}, {"api_name": "rospy.get_name", "line_number": 32, "usage_type": "call"}, {"api_name": "rospy.Publisher", "line_number": 37, "usage_type": "call"}, {"api_name": "sensor_msgs.msg.NavSatFix", "line_number": 37, "usage_type": "argument"}, {"api_name": "rospy.loginfo", "line_number": 38, "usage_type": "call"}, {"api_name": "rospy.loginfo", "line_number": 48, "usage_type": "call"}, {"api_name": "sensor_msgs.msg.NavSatFix", "line_number": 52, "usage_type": "call"}, {"api_name": "rospy.Time.now", "line_number": 57, "usage_type": "call"}, {"api_name": "rospy.Time", "line_number": 57, "usage_type": "attribute"}, {"api_name": "rospy.loginfo", "line_number": 71, "usage_type": "call"}, {"api_name": "sensor_msgs.msg.NavSatFix.COVARIANCE_TYPE_APPROXIMATED", "line_number": 84, "usage_type": "attribute"}, {"api_name": "sensor_msgs.msg.NavSatFix", "line_number": 84, "usage_type": "name"}, {"api_name": "rospy.init_node", "line_number": 91, "usage_type": "call"}, {"api_name": "rospy.get_param", "line_number": 93, "usage_type": "call"}, {"api_name": "rospy.get_param", "line_number": 94, "usage_type": "call"}, {"api_name": "serial.Serial", "line_number": 96, "usage_type": "call"}, {"api_name": "rospy.loginfo", "line_number": 98, "usage_type": "call"}, {"api_name": "rospy.get_name", "line_number": 98, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 99, "usage_type": "call"}, {"api_name": "rospy.loginfo", "line_number": 102, "usage_type": "call"}, {"api_name": "rospy.get_name", "line_number": 102, "usage_type": "call"}, {"api_name": "rospy.loginfo", "line_number": 105, "usage_type": "call"}, {"api_name": "rospy.get_name", "line_number": 105, "usage_type": "call"}, {"api_name": "rospy.Timer", "line_number": 106, "usage_type": "call"}, {"api_name": "rospy.Duration.from_sec", "line_number": 106, "usage_type": "call"}, {"api_name": "rospy.Duration", "line_number": 106, "usage_type": "attribute"}, {"api_name": "rospy.spin", "line_number": 107, "usage_type": "call"}]} +{"seq_id": "30593332865", "text": "# -*- coding: utf-8 -*-\nfrom typing import Optional, Union\n\n\ndef comma_format(number: Union[str, float, int]) -> str:\n \"\"\"\n Format a number with commas if it's greater than 999.\n eg: `1000 -> '1,000'\n 123456.78 -> '123,456.78'\n '1000000' -> '1,000,000'\n 500 -> '500'\n\n :param number: The number to be formatted. Either an int, a float or a str.\n :return: A string of the comma formatted number\n \"\"\"\n if isinstance(number, str):\n try:\n number = int(number)\n except ValueError:\n number = float(number)\n\n if isinstance(number, int):\n # Don't need to add decimal places to an int\n return f\"{number:,}\"\n else:\n return f\"{number:,.2f}\"\n\n\ndef _with_a(name: str) -> str:\n \"\"\"\n Try to work out whether to use 'a' or 'an'. The rule is that we should use 'an' where the word starts with a vowel\n sound. This is not the same as starting with a vowel (e.g. 'an hour', 'a unit'). Apply a heuristic that should work\n most of the time, with a special case for an obvious edge-case.\n\n If this is not enough, we shouldn't try to make this heuristic work better - english is hard. Instead, we should use\n https://github.com/jaraco/inflect and rely on people who've already done the hard work to make it simple.\n \"\"\"\n if name.startswith((\"a\", \"e\", \"i\", \"o\", \"hour\")):\n return f\" an {name}\"\n return f\" a {name}\"\n\n\ndef format_price(min_price: Optional[Union[str, float]],\n max_price: Optional[Union[str, float]],\n unit: Optional[str],\n interval: Optional[str],\n hours_for_price: Optional[str] = None):\n \"\"\"Format a price string\"\"\"\n if min_price is not None and min_price != '':\n min_price = comma_format(min_price)\n if max_price is not None and max_price != '':\n max_price = comma_format(max_price)\n\n if not (min_price or max_price):\n raise TypeError('One of min_price or max_price should be number or non-empty string, not None')\n\n if hours_for_price:\n return u'{} for £{}'.format(hours_for_price, min_price or max_price)\n\n formatted_price = \"\"\n if min_price:\n formatted_price += u'£{}'.format(min_price)\n if min_price and max_price:\n formatted_price += u' to '\n if max_price:\n formatted_price += u'£{}'.format(max_price)\n if unit:\n formatted_price += _with_a(unit.lower())\n if interval:\n formatted_price += _with_a(interval.lower())\n return formatted_price\n\n\ndef format_service_price(service):\n \"\"\"Format a price string from a service dictionary\n\n :param service: a service dictionary, returned from data API\n\n :return: a formatted price string if the required\n fields are set in the service dictionary.\n \"\"\"\n if not service.get('priceMin'):\n return ''\n return format_price(\n service.get('priceMin'),\n service.get('priceMax'),\n service.get('priceUnit'),\n service.get('priceInterval'))\n", "repo_name": "Crown-Commercial-Service/digitalmarketplace-content-loader", "sub_path": "dmcontent/formats.py", "file_name": "formats.py", "file_ext": "py", "file_size_in_byte": 3035, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.Union", "line_number": 5, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 43, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 43, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 44, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 44, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 45, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 46, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 47, "usage_type": "name"}]} +{"seq_id": "74705874624", "text": "from rudra.data_store.aws import AmazonS3\nfrom training.datastore.utils import Utility\nfrom recommendation_engine.config.path_constants import TEMPORARY_DATA_PATH\nfrom rudra import logger\nimport numpy as np\nimport time\nimport os\nimport json\n\n\nclass GetData:\n \"\"\"This class defines the S3 Connections viz fetching and storing data.\"\"\"\n\n def __init__(self,\n aws_access_key_id,\n aws_secret_access_key,\n num_train_per_user,\n aws_bucket_name,\n model_version):\n \"\"\"Create an instance of GetData.\"\"\"\n self.aws_access_key_id = os.environ.get('AWS_S3_ACCESS_KEY_ID', aws_access_key_id)\n self.aws_secret_access_key = os.environ.get('AWS_S3_SECRET_ACCESS_KEY',\n aws_secret_access_key)\n self.github_token = os.environ.get('GITHUB_TOKEN', '')\n self.bucket_name = aws_bucket_name\n self.version_name = model_version\n self.s3_object = AmazonS3(bucket_name=self.bucket_name,\n aws_access_key_id=self.aws_access_key_id,\n aws_secret_access_key=self.aws_secret_access_key\n )\n self.num_train_per_user = num_train_per_user\n self.s3_client = self.load_s3()\n self.utility = Utility()\n\n def load_s3(self):\n \"\"\"Establish the connection with S3.\"\"\"\n self.s3_object.connect()\n if self.s3_object.is_connected():\n logger.info(\"S3 connection established.\")\n return self.s3_object\n else:\n raise Exception\n\n def load_raw_data(self):\n \"\"\"Load the raw data from S3 bucket.\"\"\"\n NPM_raw_data_path = os.path.join(self.version_name,\n \"data/manifest.json\")\n logger.info(\"Reading raw data from {}\".format(self.version_name))\n if (self.s3_client.object_exists(NPM_raw_data_path)):\n try:\n raw_data_dict_ = self.s3_client.read_json_file(NPM_raw_data_path)\n logger.info(\"Size of Raw Manifest file is: {}\".format(len(raw_data_dict_)))\n return raw_data_dict_\n except Exception:\n raise Exception\n\n def load_existing_data(self):\n \"\"\"Load the node registry dump from S3 bucket.\"\"\"\n NPM_clean_json_data_path = os.path.join(\"training-utils\",\n \"node-package-details.json\")\n if self.s3_client.object_exists(NPM_clean_json_data_path):\n try:\n logger.info(\"Reading dump data from training-utils folder.\")\n existing_data = self.s3_client.read_json_file(NPM_clean_json_data_path)\n logger.info(\"Size of raw json: %d\", len(existing_data))\n return existing_data\n except Exception:\n raise Exception(\"S3 connection error\")\n else:\n raise ValueError(\"Given Path is not present.\")\n\n def load_user_item_data(self):\n \"\"\"Load the manifest file.\"\"\"\n NPM_manifest_user_data_path = os.path.join(TEMPORARY_DATA_PATH, \"manifest_user_data.dat\")\n try:\n with open(NPM_manifest_user_data_path, 'rb') as f:\n user_item_data = f.read()\n return user_item_data\n except Exception:\n raise Exception(\"S3 could not read the file.\")\n\n def create_package_train_user_data(self):\n \"\"\"Create package train user data.\"\"\"\n self.package_train_user_data = list()\n for user_id in range(self.num_users):\n this_user_items = self.pairs_train[self.pairs_train[:, 0] == user_id, 1]\n items_str = \" \".join(str(x) for x in this_user_items)\n self.package_train_user_data.append([len(this_user_items), items_str])\n return self.package_train_user_data\n\n def create_package_train_item_data(self):\n \"\"\"Create package train item data.\"\"\"\n self.package_train_item_data = list()\n for item_id in range(self.num_items):\n this_item_users = self.pairs_train[self.pairs_train[:, 1] == item_id, 0]\n users_str = \" \".join(str(x) for x in this_item_users)\n self.package_train_item_data.append([len(this_item_users), users_str])\n return self.package_train_item_data\n\n def create_package_test_user_data(self):\n \"\"\"Create package test user data.\"\"\"\n self.package_test_user_data = list()\n for user_id in range(self.num_users):\n this_user_items = self.pairs_test[self.pairs_test[:, 0] == user_id, 1]\n items_str = \" \".join(str(x) for x in this_user_items)\n self.package_test_user_data.append([len(this_user_items), items_str])\n return self.package_test_user_data\n\n def create_package_test_item_data(self):\n \"\"\"Create package test item data.\"\"\"\n self.package_test_item_data = list()\n for item_id in range(self.num_items):\n this_item_users = self.pairs_test[self.pairs_test[:, 1] == item_id, 0]\n users_str = \" \".join(str(x) for x in this_item_users)\n self.package_test_item_data.append([len(this_item_users), users_str])\n return self.package_test_item_data\n\n def train_test_data(self):\n \"\"\"Create the training testing data for PMF.\"\"\"\n data_list = self.split_training_testing_data()\n self.pairs_train = data_list[0]\n self.pairs_test = data_list[1]\n self.num_users = data_list[2]\n self.num_items = data_list[3]\n packagedata_train_users = self.create_package_train_user_data()\n packagedata_train_items = self.create_package_train_item_data()\n packagedata_test_users = self.create_package_test_user_data()\n packagedata_test_items = self.create_package_test_item_data()\n return packagedata_train_users, packagedata_train_items, \\\n packagedata_test_users, packagedata_test_items\n\n def split_training_testing_data(self):\n \"\"\"Split data into training and testing.\"\"\"\n data_in_bytes = self.load_user_item_data()\n data = data_in_bytes.decode(\"utf-8\")\n data_list = data.split('\\n')\n pairs_train = []\n pairs_test = []\n user_id = 0\n np.random.seed(int(time.time()))\n logger.info(\"Splitting data into training and testing.\")\n for line in data_list:\n arr = line.strip().split()\n arr = np.asarray([int(x) for x in arr[1:]])\n n = len(arr)\n idx = np.random.permutation(n)\n for i in range(min(self.num_train_per_user, n)):\n pairs_train.append((user_id, arr[idx[i]]))\n if n > self.num_train_per_user:\n for i in range(self.num_train_per_user, n):\n pairs_test.append((user_id, arr[idx[i]]))\n user_id += 1\n num_users = user_id\n pairs_train = np.asarray(pairs_train)\n pairs_test = np.asarray(pairs_test)\n num_items = np.maximum(np.max(pairs_train[:, 1]), np.max(pairs_test[:, 1])) + 1\n logger.info(\"Number of users and items are respectively {},\"\n \" {}\".format(num_users, num_items))\n return [pairs_train, pairs_test, num_users, num_items]\n\n def check_path(self, path):\n \"\"\"Check the given datastore path.\"\"\"\n logger.info(\"Given path is: {}\".format(path))\n try:\n if not os.path.exists(path):\n os.makedirs(path)\n return path\n except Exception as e:\n raise e\n\n def save_file_temporary(self, content, filename, datastore):\n \"\"\"Store data file in temporary storage.\"\"\"\n path = self.check_path(datastore)\n try:\n with open(os.path.join(path, filename), 'w') as f:\n for lst in content:\n ele_str = \" \".join([str(x) for x in lst[1:]])\n f.write(\"{} {}\\n\".format(lst[0], ele_str))\n logger.info(\"File has been stored successfully.\")\n except Exception as e:\n raise e\n\n def save_manifest_file_temporary(self, content, filename, datastore):\n \"\"\"Store manifest file in temporary storage.\"\"\"\n path = self.check_path(datastore)\n try:\n with open(os.path.join(path, filename), 'w') as f:\n for lst in content:\n f.write(\"{} {}\\n\".format(lst[0], \" \".join(str(x) for x in lst[1:])))\n logger.info(\"Manifest File has been stored successfully.\")\n\n except Exception as e:\n raise e\n\n def save_numpy_matrix_temporary(self, content, filename, datastore):\n \"\"\"Store numpy matrix in temporary storage.\"\"\"\n path = self.check_path(datastore)\n try:\n np.savez(os.path.join(path, filename), matrix=content)\n logger.info(\"Numpy matrix has been stored successfully.\")\n\n except Exception as e:\n raise e\n\n def save_json_file_temporary(self, content, filename, datastore):\n \"\"\"Store JSON file in temporary storage.\"\"\"\n path = self.check_path(datastore)\n try:\n with open(os.path.join(path, filename), 'w') as f:\n json.dump(content, f)\n logger.info(\"JSON file has been stored successfully.\")\n except Exception as e:\n raise e\n\n def save_on_s3(self, folder_path):\n \"\"\"Store all the contents on S3.\"\"\"\n try:\n if os.path.exists(folder_path):\n if 'intermediate-model' in folder_path:\n self.s3_client.s3_upload_folder(folder_path=folder_path,\n prefix=self.version_name + '/intermediate-model'\n )\n else:\n self.s3_client.s3_upload_folder(folder_path=folder_path,\n prefix=self.version_name + '')\n logger.info(\"Folders are successfully saved on S3.\")\n else:\n logger.error(\"Folder path doesn't exist.\")\n except Exception as e:\n raise e\n", "repo_name": "fabric8-analytics/fabric8-analytics-npm-insights", "sub_path": "training/datastore/s3_connection.py", "file_name": "s3_connection.py", "file_ext": "py", "file_size_in_byte": 10165, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.environ.get", "line_number": 21, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 22, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 24, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 24, "usage_type": "attribute"}, {"api_name": "rudra.data_store.aws.AmazonS3", "line_number": 27, "usage_type": "call"}, {"api_name": "training.datastore.utils.Utility", "line_number": 33, "usage_type": "call"}, {"api_name": "rudra.logger.info", "line_number": 39, "usage_type": "call"}, {"api_name": "rudra.logger", "line_number": 39, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path", "line_number": 46, "usage_type": "attribute"}, {"api_name": "rudra.logger.info", "line_number": 48, "usage_type": "call"}, {"api_name": "rudra.logger", "line_number": 48, "usage_type": "name"}, {"api_name": "rudra.logger.info", "line_number": 52, "usage_type": "call"}, {"api_name": "rudra.logger", "line_number": 52, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path", "line_number": 59, "usage_type": "attribute"}, {"api_name": "rudra.logger.info", "line_number": 63, "usage_type": "call"}, {"api_name": "rudra.logger", "line_number": 63, "usage_type": "name"}, {"api_name": "rudra.logger.info", "line_number": 65, "usage_type": "call"}, {"api_name": "rudra.logger", "line_number": 65, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 74, "usage_type": "call"}, {"api_name": "recommendation_engine.config.path_constants.TEMPORARY_DATA_PATH", "line_number": 74, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 74, "usage_type": "attribute"}, {"api_name": "numpy.random.seed", "line_number": 140, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 140, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 140, "usage_type": "call"}, {"api_name": "rudra.logger.info", "line_number": 141, "usage_type": "call"}, {"api_name": "rudra.logger", "line_number": 141, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 144, "usage_type": "call"}, {"api_name": "numpy.random.permutation", "line_number": 146, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 146, "usage_type": "attribute"}, {"api_name": "numpy.asarray", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 156, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 156, "usage_type": "call"}, {"api_name": "rudra.logger.info", "line_number": 157, "usage_type": "call"}, {"api_name": "rudra.logger", "line_number": 157, "usage_type": "name"}, {"api_name": "rudra.logger.info", "line_number": 163, "usage_type": "call"}, {"api_name": "rudra.logger", "line_number": 163, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 165, "usage_type": "call"}, {"api_name": "os.path", "line_number": 165, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 166, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 175, "usage_type": "call"}, {"api_name": "os.path", "line_number": 175, "usage_type": "attribute"}, {"api_name": "rudra.logger.info", "line_number": 179, "usage_type": "call"}, {"api_name": "rudra.logger", "line_number": 179, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 187, "usage_type": "call"}, {"api_name": "os.path", "line_number": 187, "usage_type": "attribute"}, {"api_name": "rudra.logger.info", "line_number": 190, "usage_type": "call"}, {"api_name": "rudra.logger", "line_number": 190, "usage_type": "name"}, {"api_name": "numpy.savez", "line_number": 199, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 199, "usage_type": "call"}, {"api_name": "os.path", "line_number": 199, "usage_type": "attribute"}, {"api_name": "rudra.logger.info", "line_number": 200, "usage_type": "call"}, {"api_name": "rudra.logger", "line_number": 200, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 209, "usage_type": "call"}, {"api_name": "os.path", "line_number": 209, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 210, "usage_type": "call"}, {"api_name": "rudra.logger.info", "line_number": 211, "usage_type": "call"}, {"api_name": "rudra.logger", "line_number": 211, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 218, "usage_type": "call"}, {"api_name": "os.path", "line_number": 218, "usage_type": "attribute"}, {"api_name": "rudra.logger.info", "line_number": 226, "usage_type": "call"}, {"api_name": "rudra.logger", "line_number": 226, "usage_type": "name"}, {"api_name": "rudra.logger.error", "line_number": 228, "usage_type": "call"}, {"api_name": "rudra.logger", "line_number": 228, "usage_type": "name"}]} +{"seq_id": "33442696536", "text": "from django import forms\nfrom django.utils.translation import gettext_lazy as _\n\nfrom .models import Customer\n\n\nclass CustomerForm(forms.ModelForm):\n class Meta:\n model = Customer\n fields = ['name', 'customer_id', 'contract_number', 'invoice_name',\n 'invoice_street', 'invoice_city', 'default_fee']\n\n default_fee = forms.DecimalField(label=_('Project fee per hour'),\n localize=True,\n max_digits=5,\n decimal_places=2)", "repo_name": "molecode/DocumentPanda", "sub_path": "customer/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 561, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.forms.ModelForm", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 7, "usage_type": "name"}, {"api_name": "models.Customer", "line_number": 9, "usage_type": "name"}, {"api_name": "django.forms.DecimalField", "line_number": 13, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 13, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 13, "usage_type": "call"}]} +{"seq_id": "29561384240", "text": "# -*- coding: utf-8 -*-\nimport sys, getopt, distutils\nfrom distutils.util import strtobool\n\ninputfile = ''\noutputfile = ''\nmingram = 1\nmaxgram = 1\nlemmatise = 1\nremove_stopwords = 1\nseparator = '\\n'\npattern = \"\"\ntry:\n opts, args = getopt.getopt(sys.argv[1:], \"i:o:m:M:l:s:S:p:h\", [\"inputfile=\", \"outputfile=\", \"mingram=\", \"maxgram=\", \"lemmatise=\", \"stopwords=\", \"separator=\", \"pattern=\", \"help\"])\nexcept getopt.GetoptError:\n print('usage: main.py -i -o [-m ] [-M ] [-l ] [-s ] [-S ] [-p ]')\n sys.exit(2)\nfor opt, arg in opts:\n if opt in (\"-i\", \"--inputfile\"):\n inputfile = arg\n elif opt in (\"-o\", \"--outputfile\"):\n outputfile = arg\n elif opt in (\"-m\", \"--mingram\"):\n try:\n mingram = int(arg)\n except ValueError: print(\"-m parameter value is not an integer so it will take 1 !\")\n elif opt in (\"-M\", \"--maxgram\"):\n try:\n maxgram = int(arg)\n except ValueError: print(\"-M parameter value is not an integer so it will take \"+str(mingram)+\" !\")\n elif opt in (\"-l\", \"--lemmatise\"):\n try:\n lemmatise = distutils.util.strtobool(arg)\n except ValueError: print(\"-l parameter value is not a boolean like value so it will take 1 !\")\n elif opt in (\"-s\", \"--stopwords\"):\n try:\n remove_stopwords = distutils.util.strtobool(arg)\n except ValueError: print(\"-s parameter value is not a boolean like value so it will take 1 !\")\n elif opt in (\"-S\", \"--separator\"):\n separator = arg\n elif opt in (\"-p\", \"--pattern\"):\n pattern = arg\n elif opt in (\"-h\", \"--help\"):\n print('usage: main.py -i -o [-m ] [-M ] [-l ] [-s ] [-S ] [-p ]')\n print('-i : input text file')\n print('-o : output JSON file. No need to write .json, it will be added automatically')\n print('-m : minimal n-gram. Default is 1')\n print('-M : maximal n-gram. Default is minimal n-gram')\n print('-l : if input text file must be lemmatized. Default is 1|true|yes|on. Can also be 0|false|no|off')\n print('-s : remove stopwords from input text file. Default is 1|true|yes|on. Can also be 0|false|no|off')\n print('-S : a string that represent the document separator. Default is \\\\n')\n print('-p : a string that represent a pattern to work on in the input text file. Default is \"\" meaning no pattern search')\n sys.exit(0)\n\nif inputfile=='' or outputfile=='':\n print('usage: main.py -i -o [-m ] [-M ] [-l ] [-s ] [-S ] [-p ]')\n sys.exit(2)\n\nif mingram>maxgram: maxgram = mingram\n\nfrom website import WebSite, Word, Dictionnary\n#import treetaggerwrapper # For proper print of sequences.\nimport pprint\nfrom itertools import groupby\n\nimport string\nimport nltk\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.corpus import stopwords\nimport re\n\nimport string\nimport nltk\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.corpus import stopwords\nimport re\nimport sys\n\nfrom nltk.stem.snowball import FrenchStemmer\n\nfrom corpus import *\n\nfrom parser import *\n\nfrom nltk import ngrams, FreqDist\nfrom nltk.tokenize import sent_tokenize, word_tokenize\nfrom nltk.stem import WordNetLemmatizer\n\nimport json\n\ndef serialize_to_outfile(L, output_file_path):\n myDict = []\n for i in range(len(L)):\n data = {\"element\": L[i][0], \"frequency\": int(L[i][1])}\n myDict.append(data)\n with open(output_file_path, 'w') as outfile:\n json.dump(myDict, outfile, indent = 3, ensure_ascii = False)\n\ndef get_score(name_and_value):\n return name_and_value[1]\n\n\"----------------------------------------------------------------------\"\n\nfile = open(inputfile, \"r\") #chemin du fichier\nwebsites = getWebSiteSet(file, separator, pattern)\ncp = Corpus()\ncp.set_content(websites, lemmatise, remove_stopwords)\nL = sorted(cp.get_relevant_elements((mingram, maxgram)), key = get_score, reverse = True)\nserialize_to_outfile(L, outputfile+'.json')\n", "repo_name": "bbobox/NER", "sub_path": "py_src_files/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 4116, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "getopt.getopt", "line_number": 14, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 14, "usage_type": "attribute"}, {"api_name": "getopt.GetoptError", "line_number": 15, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 17, "usage_type": "call"}, {"api_name": "distutils.util.strtobool", "line_number": 33, "usage_type": "call"}, {"api_name": "distutils.util", "line_number": 33, "usage_type": "attribute"}, {"api_name": "distutils.util.strtobool", "line_number": 37, "usage_type": "call"}, {"api_name": "distutils.util", "line_number": 37, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 53, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 57, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 97, "usage_type": "call"}]} +{"seq_id": "20906578309", "text": "from lib.aoclib import AOCLib\n\npuzzle = (2020, 12)\n\n# Initialise the helper library1\n\naoc = AOCLib(puzzle[0])\n\npuzzle_input = aoc.get_puzzle_input(puzzle[1], AOCLib.lines_to_list)\n\nposition1 = position2 = (0, 0)\ndirection = 0\nincrements = ((1, 0), (0, -1), (-1, 0), (0, 1))\nwaypoint = (10, 1)\n\nfor instruction in puzzle_input:\n action = instruction[0]\n value = int(instruction[1:])\n if action in 'ESWN':\n i = 'ESWN'.index(action)\n position1 = (position1[0] + value * increments[i][0],\n position1[1] + value * increments[i][1])\n waypoint = (waypoint[0] + value * increments[i][0],\n waypoint[1] + value * increments[i][1])\n elif action == 'F':\n position1 = (position1[0] + value * increments[direction][0],\n position1[1] + value * increments[direction][1])\n position2 = (position2[0] + value * waypoint[0],\n position2[1] + value * waypoint[1])\n else:\n if value == 180:\n waypoint = (-waypoint[0], -waypoint[1])\n direction = (direction + 2) % 4\n elif instruction in ('L90', 'R270'):\n waypoint = (-waypoint[1], waypoint[0])\n direction = (direction + 3) % 4\n else:\n waypoint = (waypoint[1], -waypoint[0])\n direction = (direction + 1) % 4\n\naoc.print_solution(1, abs(position1[0]) + abs(position1[1]))\naoc.print_solution(2, abs(position2[0]) + abs(position2[1]))\n", "repo_name": "thebertster/aoc_2020", "sub_path": "day_12.py", "file_name": "day_12.py", "file_ext": "py", "file_size_in_byte": 1471, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "lib.aoclib.AOCLib", "line_number": 7, "usage_type": "call"}, {"api_name": "lib.aoclib.AOCLib.lines_to_list", "line_number": 9, "usage_type": "attribute"}, {"api_name": "lib.aoclib.AOCLib", "line_number": 9, "usage_type": "name"}]} +{"seq_id": "20559406744", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\nglobe_legend = {\n \"GO_Grass\": \"#00F100\",\n \"GO_Barren\": \"#AA7941\",\n \"GO_Trees\": \"#007500\",\n \"GO_Shrub\": \"#DBED00\",\n \"GO_Cultivated\": \"#FF00D6\",\n \"GO_Water\": \"#00B7F2\",\n \"GO_BuiltUp\": \"#FF8080\",\n}\n\nceo_legend = {\n \"Trees_CanopyCover\": \"#007500\",\n \"bush/scrub\": \"#DBED00\",\n \"grass\": \"#00F100\",\n \"cultivated vegetation\": \"#FF00D6\",\n \"Water>treated pool\": \"#00F1DE\",\n \"Water>lake/ponded/container\": \"#00B7F2\",\n \"Water>rivers/stream\": \"#1527F6\",\n \"Water>irrigation ditch\": \"#007570\",\n \"shadow\": \"#000000\",\n \"unknown\": \"#C8D2D3\",\n \"Bare Ground\": \"#AA7941\",\n \"Building\": \"#FF8080\",\n \"Impervious Surface (no building)\": \"#FF0000\",\n}\n\nharmonized_ceo_legend = {\n \"CEO_Trees\": \"#007500\",\n \"CEO_Shrubland\": \"#DBED00\",\n \"CEO_Grassland\": \"#00F100\",\n \"CEO_Cropland\": \"#FF00D6\",\n \"CEO_BuiltUp\": \"#FF8080\",\n \"CEO_Barren\": \"#AA7941\",\n \"CEO_Water\": \"#00B7F2\",\n}\n\nworldcover_legend = {\n \"Trees\": \"#006400\",\n \"Shrubland\": \"#ffbb22\",\n \"Grassland\": \"#ffff4c\",\n \"Cropland\": \"#f096ff\",\n \"Built-up\": \"#fa0000\",\n \"Barren / Sparse Vegetation\": \"#b4b4b4\",\n \"Open Water\": \"#0064c8\",\n \"Herbaceous Wetland\": \"#0096a0\",\n \"Moss and Lichen\": \"#fae6a0\",\n}\n\n\ndef aoi_composition_plot(df, name, classifications, colors, directory=\"\"):\n title = f\"Mean Composition -- {name}\"\n filename = f\"{title}.png\"\n if directory:\n filename = f\"{directory}/{filename}\"\n\n plt.figure()\n mean = np.mean(df[classifications])\n patches, text, _ = plt.pie(mean, colors=colors, autopct=\"%.2f\", pctdistance=1.1)\n plt.legend(patches, classifications, bbox_to_anchor=(1.15, 1), loc=\"upper left\")\n plt.title(title, fontweight=\"bold\")\n plt.savefig(filename)\n plt.show()\n\n\ndef dataset_comparison_plot(\n df, datasets, harmonization_table, harmonization_table_lookup, directory=\"\"\n):\n title = \"\"\n for dataset in datasets[:-1]:\n title += f\"{dataset} vs. \"\n title += datasets[-1]\n title = f\"{title} Landcover Class Distributions\"\n\n column_list = [harmonization_table_lookup[dataset] for dataset in datasets]\n\n color = sns.color_palette()\n sns.set_style(\"darkgrid\")\n fig, axs = plt.subplots(len(harmonization_table.keys()), 1)\n fig.set_figwidth(10)\n fig.set_figheight(15)\n fig.suptitle(title, fontweight=\"bold\", fontsize=18)\n\n fig.tight_layout(pad=3.0)\n fig.subplots_adjust(top=0.94)\n for i, item in enumerate(harmonization_table.items()):\n classification, total_columns = item\n desired_columns = [total_columns[num] for num in column_list]\n axs[i].bar(datasets, np.mean(df[desired_columns]), color=color)\n axs[i].set_title(f\"Mean {classification} Distribution\")\n axs[i].title.set_weight(\"bold\")\n if directory:\n plt.savefig(f\"{directory}/{title} Bar Graph.png\")\n else:\n plt.savefig(f\"{title} Bar Graph.png\")\n plt.show()\n", "repo_name": "Piphi5/Adopt-a-Pixel3km-Notebooks", "sub_path": "utils/code/plotting_utils.py", "file_name": "plotting_utils.py", "file_ext": "py", "file_size_in_byte": 2976, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "matplotlib.pyplot.figure", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.pie", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "seaborn.color_palette", "line_number": 80, "usage_type": "call"}, {"api_name": "seaborn.set_style", "line_number": 81, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 92, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 96, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 96, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 98, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 98, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 99, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 99, "usage_type": "name"}]} +{"seq_id": "30061210512", "text": "# coding:utf-8\nimport os\nimport torch\nfrom torch.autograd import Variable\nimport os\nimport pandas as pd\nimport multiprocessing\nfrom utils.util import CheckPath\n\n\nclass Config():\n def __init__(self):\n\n # set path and savetype\n self.dataset = 'FB15k'\n self.rootpath = './data/' + self.dataset\n self.trainpath = self.rootpath + \"/train2id.txt\"\n self.testpath = self.rootpath + '/test2id.txt'\n self.validpath = self.rootpath + \"/valid2id.txt\"\n self.entitypath = self.rootpath + '/entity2id.txt'\n self.relationpath = self.rootpath + '/relation2id.txt'\n\n # Other arguments\n self.embedpath = \"./source/embed/\"\n self.logpath = \"./source/log/\"\n self.modelpath = \"./source/model/\"\n self.summarydir = \"./source/summary/\"\n\n # DataLoader arguments\n self.batch_size = 1024\n self.eval_batch_size = 1\n self.numworkers = 6\n self.evalnumberworkers = multiprocessing.cpu_count()\n self.neg_sample_rate = 1\n\n # Model arguments\n self.model = 'TransD'\n self.usegpu = torch.cuda.is_available()\n self.epochs = 500\n self.evalepoch = 5\n self.learningrate = 0.01\n self.lrdecay = 0.95\n self.lrdecayepoch = 5\n self.shuffle = True\n self.optimizer = 'Adam'\n self.weight_decay = 0\n self.drop_last = True\n\n # load pre-trained model/emb\n self.init_checkpoint = None\n self.entityfile = \"./source/embed/entityEmbedding.txt\"\n self.relationfile = \"./source/embed/relationEmbedding.txt\"\n self.loadembed = False\n\n # Check Path\n self.check()\n\n def init(self):\n\n if self.model == 'TransE':\n self.modelparam = TransE_config()\n elif self.model == 'TransD':\n self.modelparam = TransD_config()\n elif self.model == 'TransH':\n self.modelparam = TransH_config()\n elif self.model == 'TransA':\n self.modelparam = TransA_config()\n elif self.model == 'ConvE':\n self.modelparam = ConvE_config()\n elif self.model == 'RotatE':\n self.modelparam = RotatE_config()\n elif self.model == 'SimplE':\n self.modelparam = SimplE_config()\n else:\n print(\"error model name %s\" %self.model)\n exit(1)\n\n self.modelparam.entTotal = len(pd.read_csv(self.entitypath, sep='\\t', header=None))\n self.modelparam.relTotal = len(pd.read_csv(self.relationpath, sep='\\t', header=None))\n self.modelparam.batch_size = self.batch_size * self.neg_sample_rate\n self.modelparam.batch_seq_size = int(self.batch_size * 2)\n self.modelparam.usegpu = self.usegpu\n\n # save path\n self.savepath = self.modelpath + self.model\n CheckPath(self.savepath, raise_error=False)\n def check(self):\n # Check files\n CheckPath(self.trainpath)\n CheckPath(self.testpath)\n CheckPath(self.validpath)\n\n # Check dirs\n CheckPath(self.modelpath, raise_error=False)\n CheckPath(self.summarydir, raise_error=False)\n CheckPath(self.logpath, raise_error=False)\n CheckPath(self.embedpath, raise_error=False)\n\n\n\n def set_model_arg(self, lr=0.01, lrdecay=0.96, lrdecayepoch=5, epoch=5, hidden_size=100, margin=1, shuffle=True,\n optimizer='Adam'):\n self.learningrate = lr\n self.lrdecay = lrdecay\n self.lrdecayepoch = lrdecayepoch\n self.epochs = epoch\n self.hidden_size = hidden_size\n self.margin = margin\n self.shuffle = shuffle\n self.optimizer = optimizer\n\n def set_setpath(self, trainpath=None, testpath=None, validpath=None, entitypath=None, \\\n relationpath=None, summarydir=None, modelpath=None):\n if trainpath:\n self.trainpath = trainpath\n if testpath:\n self.testpath = testpath\n if validpath:\n self.validpath = validpath\n if entitypath:\n self.entitypath = entitypath\n self.init()\n if relationpath:\n self.relationpath = relationpath\n self.init()\n if summarydir:\n self.summarydir = summarydir\n if modelpath:\n self.modelpath = modelpath\n self.check()\n\n def set_dataloader_args(self, ent=0.5, rel=0.5, numworkers=1, batch_size=1024, ):\n self.ent_neg_rate = ent\n self.rel_neg_rate = rel\n self.numworkers = numworkers\n self.batch_size = batch_size\n self.init()\n\n def set_pre_model(self, path):\n if os.path.exists(path):\n self.premodel = path\n self.loadmod = True\n else:\n print('[ERR] The pretrained model path is valid. The path is %s.' % path)\n\n def set_pre_emb(self, loademb, entfile, relfile):\n if os.path.exists(entfile) and os.path.exists(relfile):\n self.entityfile = entfile\n self.relationfile = relfile\n if loademb:\n self.loadembed = True\n\n\nclass TransE_config():\n def __init__(self):\n self.margin = 2.0\n self.hidden_size = 100\n self.L = 2\n self.regularization = 0.5\n\n self.entTotal = 0\n self.relTotal = 0\n self.batch_size = 0\n self.batch_seq_size = int(self.batch_size * 2)\n\n\nclass TransD_config():\n def __init__(self):\n self.margin = 1.0\n self.hidden_size = 50\n self.L = 2\n self.regularization = 0.25\n\n self.entTotal = 0\n self.relTotal = 0\n self.batch_size = 0\n self.batch_seq_size = int(self.batch_size * 2)\n\n\nclass TransH_config():\n def __init__(self):\n self.margin = 1.0\n self.hidden_size = 100\n self.L = 2\n self.C = 0.01\n self.eps = 0.001\n\n self.entTotal = 0\n self.relTotal = 0\n self.batch_size = 0\n self.batch_seq_size = int(self.batch_size * 2)\n\n\nclass TransA_config():\n def __init__(self):\n self.margin = 3.2\n self.hidden_size = 200\n self.L = 2\n self.lamb = 0.01\n self.regularization = 0.2\n\n self.entTotal = 0\n self.relTotal = 0\n self.batch_size = 1024\n self.batch_seq_size = int(self.batch_size * 2)\n\nclass ConvE_config():\n def __init__(self):\n self.hidden_size = 200\n self.label_smoothing_epsilon = 0.1\n self.use_bias = True\n\n self.input_dropout = 0.2\n self.feature_map_dropout = 0.2\n self.dropout = 0.3\n\nclass RotatE_config():\n def __init__(self):\n self.negative_adversarial_sampling = True\n self.adversarial_temperature = 1.0\n self.regularization = 0\n self.uni_weight = True\n self.gamma = 12.0\n self.hidden_size = 256 # model will automatically double it\n\nclass SimplE_config():\n def __init__(self):\n self.regularization =0.3\n self.L = 2\n self.hidden_size = 200\n\n\n", "repo_name": "RuisongZhou/KGE_pytorch", "sub_path": "Config.py", "file_name": "Config.py", "file_ext": "py", "file_size_in_byte": 6971, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "25", "api": [{"api_name": "multiprocessing.cpu_count", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 38, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 78, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 79, "usage_type": "call"}, {"api_name": "utils.util.CheckPath", "line_number": 86, "usage_type": "call"}, {"api_name": "utils.util.CheckPath", "line_number": 89, "usage_type": "call"}, {"api_name": "utils.util.CheckPath", "line_number": 90, "usage_type": "call"}, {"api_name": "utils.util.CheckPath", "line_number": 91, "usage_type": "call"}, {"api_name": "utils.util.CheckPath", "line_number": 94, "usage_type": "call"}, {"api_name": "utils.util.CheckPath", "line_number": 95, "usage_type": "call"}, {"api_name": "utils.util.CheckPath", "line_number": 96, "usage_type": "call"}, {"api_name": "utils.util.CheckPath", "line_number": 97, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 140, "usage_type": "call"}, {"api_name": "os.path", "line_number": 140, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 147, "usage_type": "call"}, {"api_name": "os.path", "line_number": 147, "usage_type": "attribute"}]} +{"seq_id": "72755249986", "text": "#!/usr/bin/env python3\n# Class: FIOEndpProfile(LFCliBase)\n\n# Written by Candela Technologies Inc.\n# Updated by:\nimport sys\nimport os\nimport importlib\nimport time\nimport logging\n\n\nsys.path.append(os.path.join(os.path.abspath(__file__ + \"../../../\")))\n\nlfcli_base = importlib.import_module(\"py-json.LANforge.lfcli_base\")\nLFCliBase = lfcli_base.LFCliBase\n\nlogger = logging.getLogger(__name__)\n\n\nclass FIOEndpProfile(LFCliBase):\n \"\"\"\n Very often you will create the FileIO writer profile first so that it creates the data\n that a reader profile will subsequently use.\n \"\"\"\n\n def __init__(self, lfclient_host, lfclient_port, local_realm, io_direction=\"write\", debug_=False):\n super().__init__(lfclient_host, lfclient_port, debug_)\n self.local_realm = local_realm\n self.fs_type = \"fe_nfsv4\"\n self.min_rw_size = 128 * 1024\n self.max_rw_size = 128 * 1024\n self.min_file_size = 10 * 1024 * 1024\n self.max_file_size = 10 * 1024 * 1024\n\n self.min_read_rate_bps = 10 * 1000 * 1000\n self.max_read_rate_bps = 10 * 1000 * 1000\n self.min_write_rate_bps = 1000 * 1000 * 1000\n self.max_write_rate_bps = 1000 * 1000 * 1000\n\n self.file_num = 10 # number of files to write\n self.directory = None # directory like /mnt/lf/$endp_name\n\n # this refers to locally mounted directories presently used for writing\n # you would set this when doing read tests simultaneously to write tests\n # so like, if your endpoint names are like wo_300GB_001, your Directory value\n # defaults to /mnt/lf/wo_300GB_001; but reader enpoint would be named\n # /mnt/lf/ro_300GB_001, this overwrites a readers directory name to wo_300GB_001\n self.mount_dir = \"AUTO\"\n\n self.server_mount = None # like cifs://10.0.0.1/bashful or 192.168.1.1:/var/tmp\n self.mount_options = None\n self.iscsi_vol = None\n self.retry_timer_ms = 2000\n self.io_direction = io_direction # read / write\n self.quiesce_ms = 3000\n self.pattern = \"increasing\"\n self.file_prefix = \"AUTO\" # defaults to endp_name\n self.cx_prefix = \"wo_\"\n\n self.created_cx = {}\n self.created_endp = []\n\n def start_cx(self):\n logger.info(\"Starting CXs...\")\n for cx_name in self.created_cx.keys():\n self.json_post(\"/cli-json/set_cx_state\", {\n \"test_mgr\": \"default_tm\",\n \"cx_name\": self.created_cx[cx_name],\n \"cx_state\": \"RUNNING\"\n }, debug_=self.debug)\n # this is for a visual affect someone watching the screen, leave as print\n print(\".\", end='')\n print(\"\")\n\n def stop_cx(self):\n logger.info(\"Stopping CXs...\")\n for cx_name in self.created_cx.keys():\n self.json_post(\"/cli-json/set_cx_state\", {\n \"test_mgr\": \"default_tm\",\n \"cx_name\": self.created_cx[cx_name],\n \"cx_state\": \"STOPPED\"\n }, debug_=self.debug)\n # this is for a visual affect someone watching the screen, leave as print\n print(\".\", end='')\n print(\"\")\n\n def create_ro_profile(self):\n ro_profile = self.local_realm.new_fio_endp_profile()\n ro_profile.realm = self.local_realm\n\n ro_profile.fs_type = self.fs_type\n ro_profile.min_read_rate_bps = self.min_write_rate_bps\n ro_profile.max_read_rate_bps = self.max_write_rate_bps\n ro_profile.min_write_rate_bps = self.min_read_rate_bps\n ro_profile.max_write_rate_bps = self.max_read_rate_bps\n ro_profile.file_num = self.file_num\n ro_profile.directory = self.directory\n ro_profile.mount_dir = self.directory\n ro_profile.server_mount = self.server_mount\n ro_profile.mount_options = self.mount_options\n ro_profile.iscsi_vol = self.iscsi_vol\n ro_profile.retry_timer_ms = self.retry_timer_ms\n ro_profile.io_direction = \"read\"\n ro_profile.quiesce_ms = self.quiesce_ms\n ro_profile.pattern = self.pattern\n ro_profile.file_prefix = self.file_prefix\n ro_profile.cx_prefix = \"ro_\"\n return ro_profile\n\n def cleanup(self):\n logger.info(\"Cleaning up cxs and endpoints\")\n if len(self.created_cx) != 0:\n for cx_name in self.created_cx.keys():\n req_url = \"cli-json/rm_cx\"\n data = {\n \"test_mgr\": \"default_tm\",\n \"cx_name\": self.created_cx[cx_name]\n }\n self.json_post(req_url, data)\n # pprint(data)\n req_url = \"cli-json/rm_endp\"\n data = {\n \"endp_name\": cx_name\n }\n self.json_post(req_url, data)\n # pprint(data)\n\n def create(self, ports=None, connections_per_port=1, sleep_time=.5, debug_=False, suppress_related_commands_=None):\n if ports is None:\n ports = []\n cx_post_data = []\n for port_name in ports:\n for num_connection in range(connections_per_port):\n # \n if len(self.local_realm.name_to_eid(port_name)) >= 3:\n shelf = self.local_realm.name_to_eid(port_name)[0]\n resource = self.local_realm.name_to_eid(port_name)[1]\n name = self.local_realm.name_to_eid(port_name)[2]\n else:\n logger.critical(\"Unexpected name for port_name %s\" % port_name)\n raise ValueError(\"Unexpected name for port_name %s\" % port_name)\n if self.directory is None or self.server_mount is None or self.fs_type is None:\n logger.critical(\"directory [%s], server_mount [%s], and type [%s] must not be None\" % (\n self.directory, self.server_mount, self.fs_type))\n raise ValueError(\"directory [%s], server_mount [%s], and type [%s] must not be None\" % (\n self.directory, self.server_mount, self.fs_type))\n endp_data = {\n \"alias\": self.cx_prefix + name + \"_\" + str(num_connection) + \"_fio\",\n \"shelf\": shelf,\n \"resource\": resource,\n \"port\": name,\n \"type\": self.fs_type,\n \"min_read_rate\": self.min_read_rate_bps,\n \"max_read_rate\": self.max_read_rate_bps,\n \"min_write_rate\": self.min_write_rate_bps,\n \"max_write_rate\": self.max_write_rate_bps,\n \"directory\": self.directory,\n \"server_mount\": self.server_mount,\n \"mount_dir\": self.mount_dir,\n \"prefix\": self.file_prefix,\n \"payload_pattern\": self.pattern,\n\n }\n # Read direction is copy of write only directory\n if self.io_direction == \"read\":\n endp_data[\"prefix\"] = \"wo_\" + name + \"_\" + str(num_connection) + \"_fio\"\n endp_data[\"directory\"] = \"/mnt/lf/wo_\" + name + \"_\" + str(num_connection) + \"_fio\"\n\n url = \"cli-json/add_file_endp\"\n self.local_realm.json_post(url, endp_data, debug_=False,\n suppress_related_commands_=suppress_related_commands_)\n time.sleep(sleep_time)\n\n data = {\n \"name\": self.cx_prefix + name + \"_\" + str(num_connection) + \"_fio\",\n \"io_direction\": self.io_direction,\n \"num_files\": 5\n }\n self.local_realm.json_post(\"cli-json/set_fe_info\", data, debug_=debug_,\n suppress_related_commands_=suppress_related_commands_)\n\n self.local_realm.json_post(\"/cli-json/nc_show_endpoints\", {\"endpoint\": \"all\"})\n for port_name in ports:\n for num_connection in range(connections_per_port):\n name = self.local_realm.name_to_eid(port_name)[2]\n\n endp_data = {\n \"alias\": \"CX_\" + self.cx_prefix + name + \"_\" + str(num_connection) + \"_fio\",\n \"test_mgr\": \"default_tm\",\n \"tx_endp\": self.cx_prefix + name + \"_\" + str(num_connection) + \"_fio\",\n \"rx_endp\": \"NA\"\n }\n cx_post_data.append(endp_data)\n self.created_cx[self.cx_prefix + name + \"_\" + str(\n num_connection) + \"_fio\"] = \"CX_\" + self.cx_prefix + name + \"_\" + str(num_connection) + \"_fio\"\n\n for cx_data in cx_post_data:\n url = \"/cli-json/add_cx\"\n self.local_realm.json_post(url, cx_data, debug_=debug_,\n suppress_related_commands_=suppress_related_commands_)\n time.sleep(sleep_time)\n", "repo_name": "greearb/lanforge-scripts", "sub_path": "py-json/fio_endp_profile.py", "file_name": "fio_endp_profile.py", "file_ext": "py", "file_size_in_byte": 8909, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 15, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sys.path.append", "line_number": 13, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 13, "usage_type": "call"}, {"api_name": "importlib.import_module", "line_number": 15, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 18, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 173, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 202, "usage_type": "call"}]} +{"seq_id": "11601677158", "text": "import codecs\nimport sys\nimport os\nfrom tqdm import tqdm\nimport logging\nfrom utils import load_from_pkl, KNeighbor, dump_to_pkl, logging_set\n\n\nclass NSselect:\n def __init__(self,\n input_wvectors,\n input_word2id,\n input_id2word,\n input_vocabulary,\n pair_file_path,\n kn_file_name,\n output_file_name,\n topn = 20):\n word2id = dict()\n with codecs.open(input_word2id, 'r', encoding='utf-8') as f:\n for lines in f:\n word2id[lines.strip().split()[0]] = int(lines.strip().split()[1])\n id2word = dict()\n with codecs.open(input_id2word, 'r', encoding='utf-8') as f:\n for lines in f:\n id2word[int(lines.strip().split()[0])] = lines.strip().split()[1]\n vocabulary = []\n with codecs.open(input_vocabulary, 'r', encoding='utf-8') as f:\n for lines in f:\n vocabulary.append(int(lines.strip()))\n\n self.topn = topn\n kneighbor = KNeighbor(input_wvectors, vocabulary, word2id, id2word)\n dump_to_pkl(kneighbor, kn_file_name)\n\n logging_set('NSselect.log')\n files = os.listdir(pair_file_path)\n pairs = dict()\n for file in tqdm(files):\n if not os.path.isdir(file):\n path = pair_file_path + \"/\" + file\n pair = load_from_pkl(path)\n logging.info(\"pair size: %d\" % (len(pair)))\n if len(pairs) == 0:\n pairs = pair\n else:\n for key in pair.keys():\n if key in pairs:\n pairs[key] += pair[key]\n else:\n pairs[key] = pair[key]\n logging.info(\"current total pair size: %d\" % (len(pairs)))\n logging.info(\"start calculate score\")\n score = self.select_new(pairs, kneighbor, self.topn)\n #score1 = self.select(pairs, kneighbor)\n logging.info(\"start saving\")\n dump_to_pkl(score, output_file_name)\n\n def select_new(self, pairs, kneighbor, topn):\n score = dict()\n for keyp in tqdm(pairs.keys()):\n if keyp[0] in kneighbor:\n if not keyp[0] in score:\n score[keyp[0]] = []\n #i = 0\n for value in kneighbor[keyp[0]]:\n replace = tuple([value] + list(keyp[1:]))\n if replace in pairs:\n s = pairs[replace]/pairs[keyp]\n else:\n s = 0\n #i += 1\n score[keyp[0]].append(s)\n score_f = dict()\n for key in score:\n score_f[key] = []\n iter = len(score[key]) / topn\n for i in range(topn):\n s_f = sum([score[key][x*topn+i] for x in range(int(iter))])/iter\n score_f[key].append(s_f)\n return score_f\n\n\n def select(self, pairs, kneighbor):\n score = dict()\n for keyn in tqdm(kneighbor.keys()):\n score[keyn] = []\n for value in kneighbor[keyn]:\n s = 0\n i = 0\n for keyp in pairs.keys():\n if keyp[0]==keyn:\n replace = tuple([value]+list(keyp[1:]))\n if replace in pairs:\n s += pairs[replace]/pairs[keyp]\n i += 1\n else:\n s += 0\n i +=1\n score[keyn].append(s/i)\n return score\n\n\nif __name__ == '__main__':\n ns = NSselect(input_wvectors=sys.argv[1], input_word2id = sys.argv[2], input_id2word = sys.argv[3], input_vocabulary = sys.argv[4], pair_file_path=sys.argv[5], kn_file_name = sys.argv[6], output_file_name=sys.argv[7])\n", "repo_name": "Yueqi-Zhang/fine-tune-w2v-v2", "sub_path": "NSselect.py", "file_name": "NSselect.py", "file_ext": "py", "file_size_in_byte": 3938, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "codecs.open", "line_number": 20, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 24, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 28, "usage_type": "call"}, {"api_name": "utils.KNeighbor", "line_number": 33, "usage_type": "call"}, {"api_name": "utils.dump_to_pkl", "line_number": 34, "usage_type": "call"}, {"api_name": "utils.logging_set", "line_number": 36, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 37, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "utils.load_from_pkl", "line_number": 42, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 43, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 52, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 53, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 56, "usage_type": "call"}, {"api_name": "utils.dump_to_pkl", "line_number": 57, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 61, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 86, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 105, "usage_type": "attribute"}]} +{"seq_id": "43374961948", "text": "import sys\nfrom typing import List\n\nfrom .device import Device\nfrom .enumeratehelper import EnumerateHelper\n\n\nclass DeviceManager(object):\n __instance = None\n\n @classmethod\n def instance(cls):\n if cls.__instance is None:\n helper = EnumerateHelper()\n cls.__instance = cls(helper)\n return cls.__instance\n\n def __init__(self, helper: EnumerateHelper):\n self.helper = helper\n self.devices: List[Device] = []\n if \"--add-dummy-joystick\" in sys.argv:\n self.add_joystick_device(\n {\n \"axes\": 2,\n \"hats\": 0,\n \"balls\": 0,\n \"buttons\": 1,\n \"name\": \"Dummy Joystick\",\n \"id\": \"Dummy Joystick\",\n }\n )\n\n def get_devices(self, refresh: bool = False) -> List[Device]:\n print(\"DeviceManager.get_devices\")\n if self.helper is not None:\n if refresh:\n self.helper.update()\n else:\n self.helper.init()\n return self.helper.devices\n print(\"DeviceManager.get_devices ->\", self.devices)\n return self.devices\n\n def add_device_from_event(self, event):\n if event[\"type\"] == \"joy-device-added\":\n return self.add_joystick_device(event)\n elif event[\"type\"] == \"mouse-device-added\":\n return self.add_mouse_device(event)\n elif event[\"type\"] == \"keyboard-device-added\":\n return self.add_keyboard_device(event)\n else:\n assert False\n\n def add_joystick_device(self, event):\n device = Device()\n device.axes = event[\"axes\"]\n device.balls = event[\"balls\"]\n device.hats = event[\"hats\"]\n device.buttons = event[\"buttons\"]\n device.name = event[\"name\"]\n device.id = event[\"id\"]\n device.type = Device.TYPE_JOYSTICK\n self.devices.append(device)\n print(\"[INPUT] Joystick device added:\", device.name)\n return device\n\n def add_keyboard_device(self, event):\n device = Device()\n device.name = event[\"name\"]\n device.id = event[\"id\"]\n device.type = Device.TYPE_KEYBOARD\n self.devices.append(device)\n print(\"[INPUT] Keyboard device added:\", device.name)\n return device\n\n def add_mouse_device(self, event):\n device = Device()\n device.name = event[\"name\"]\n device.id = event[\"id\"]\n device.type = Device.TYPE_MOUSE\n self.devices.append(device)\n print(\"[INPUT] Mouse device added:\", device.name)\n return device\n\n def remove_all_devices(self):\n for device in self.devices:\n print(\"[INPUT] Removing device\", device.name)\n self.devices.clear()\n", "repo_name": "FrodeSolheim/fs-uae-launcher", "sub_path": "fsgamesys/input/devicemanager.py", "file_name": "devicemanager.py", "file_ext": "py", "file_size_in_byte": 2793, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 52, "dataset": "github-code", "pt": "25", "api": [{"api_name": "enumeratehelper.EnumerateHelper", "line_number": 14, "usage_type": "call"}, {"api_name": "enumeratehelper.EnumerateHelper", "line_number": 18, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 20, "usage_type": "name"}, {"api_name": "device.Device", "line_number": 20, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 21, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 33, "usage_type": "name"}, {"api_name": "device.Device", "line_number": 33, "usage_type": "name"}, {"api_name": "device.Device", "line_number": 55, "usage_type": "call"}, {"api_name": "device.axes", "line_number": 56, "usage_type": "attribute"}, {"api_name": "device.balls", "line_number": 57, "usage_type": "attribute"}, {"api_name": "device.hats", "line_number": 58, "usage_type": "attribute"}, {"api_name": "device.buttons", "line_number": 59, "usage_type": "attribute"}, {"api_name": "device.name", "line_number": 60, "usage_type": "attribute"}, {"api_name": "device.id", "line_number": 61, "usage_type": "attribute"}, {"api_name": "device.type", "line_number": 62, "usage_type": "attribute"}, {"api_name": "device.Device.TYPE_JOYSTICK", "line_number": 62, "usage_type": "attribute"}, {"api_name": "device.Device", "line_number": 62, "usage_type": "name"}, {"api_name": "device.name", "line_number": 64, "usage_type": "attribute"}, {"api_name": "device.Device", "line_number": 68, "usage_type": "call"}, {"api_name": "device.name", "line_number": 69, "usage_type": "attribute"}, {"api_name": "device.id", "line_number": 70, "usage_type": "attribute"}, {"api_name": "device.type", "line_number": 71, "usage_type": "attribute"}, {"api_name": "device.Device.TYPE_KEYBOARD", "line_number": 71, "usage_type": "attribute"}, {"api_name": "device.Device", "line_number": 71, "usage_type": "name"}, {"api_name": "device.name", "line_number": 73, "usage_type": "attribute"}, {"api_name": "device.Device", "line_number": 77, "usage_type": "call"}, {"api_name": "device.name", "line_number": 78, "usage_type": "attribute"}, {"api_name": "device.id", "line_number": 79, "usage_type": "attribute"}, {"api_name": "device.type", "line_number": 80, "usage_type": "attribute"}, {"api_name": "device.Device.TYPE_MOUSE", "line_number": 80, "usage_type": "attribute"}, {"api_name": "device.Device", "line_number": 80, "usage_type": "name"}, {"api_name": "device.name", "line_number": 82, "usage_type": "attribute"}, {"api_name": "device.name", "line_number": 87, "usage_type": "attribute"}]} +{"seq_id": "8631914462", "text": "from datetime import datetime\n\n\nclass MinigunShotEffect():\n\n def __init__(self, origin_ship_id, target_ship_id, start_x, start_y, duration=100000, delay=0):\n self.origin_ship_id = origin_ship_id\n self.target_ship_id = target_ship_id\n self.current_animation_tick = 0\n self.done = False\n self.time_started = datetime.now()\n self.duration = duration\n self.x = start_x\n self.y = start_y\n self.delay = delay\n\n def tick(self, game):\n\n now = datetime.now()\n time_since_started = now - self.time_started\n\n if self.delay:\n if time_since_started.microseconds >= self.delay:\n self.delay = 0\n self.time_started = datetime.now()\n return\n\n if self.done:\n return\n\n if self.target_ship_id not in game.ships or self.origin_ship_id not in game.ships:\n self.done = True\n return\n\n origin_ship = game.ships[self.origin_ship_id]\n target_ship = game.ships[self.target_ship_id]\n\n proportion_done = min(1.0, time_since_started.microseconds / self.duration)\n\n if proportion_done == 0.0:\n self.x = origin_ship.x\n self.y = origin_ship.y\n return\n\n if proportion_done == 1.0:\n self.done = True\n self.x = target_ship.x\n self.y = target_ship.y\n else:\n total_x_dist = target_ship.x - origin_ship.x\n total_y_dist = target_ship.y - origin_ship.y\n\n self.x = origin_ship.x + (total_x_dist * proportion_done)\n self.y = origin_ship.y + (total_y_dist * proportion_done)", "repo_name": "lilrooness/space", "sub_path": "client/vfx/minigun_shot_effect.py", "file_name": "minigun_shot_effect.py", "file_ext": "py", "file_size_in_byte": 1670, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "datetime.datetime.now", "line_number": 11, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 11, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 19, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 25, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 25, "usage_type": "name"}]} +{"seq_id": "18627704299", "text": "import os\nimport sys\nimport pytesseract\nimport cv2\nimport pandas as pd\nimport numpy as np\nfrom Scripts import imagepreprocessing as ip\nfrom Scripts.RegionSelector import get_coordinate_and_types\n\nmyconfig = r\"--psm 6 --oem 3\"\nMAX_FEATURE = 1006\nKEEP_PERCENT = 0.24\n\n\ndef align_image(src_image, des_image, max_features, keeping_percentage):\n \"\"\"\n Used for image alignment\n :param src_image:\n :param des_image:\n :param max_features:\n :param keeping_percentage:\n :return: aligned image\n \"\"\"\n\n h, w, c = src_image.shape\n # Convert source and destination image to grayscale\n src_image = cv2.cvtColor(src_image, cv2.COLOR_BGR2GRAY)\n des_image = cv2.cvtColor(des_image, cv2.COLOR_BGR2GRAY)\n\n # Initialize the ORB detector\n orb = cv2.ORB_create(max_features)\n\n # Detect keypoints and compute the descriptors\n kp1, des1 = orb.detectAndCompute(src_image, None)\n kp2, des2 = orb.detectAndCompute(des_image, None)\n\n # Initialize the Matcher for matching keypoints and match the keypoints\n bf = cv2.BFMatcher(cv2.NORM_HAMMING)\n matches = bf.match(des2, des1)\n\n # Sort the matched keypoints according to the distance and keep given percent keypoints\n matches = sorted(matches, key=lambda x: x.distance)\n good = matches[:int(len(matches) * keeping_percentage)]\n\n src_points = np.float32([kp2[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)\n dst_points = np.float32([kp1[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)\n\n M, _ = cv2.findHomography(src_points, dst_points, cv2.RANSAC, 5.0)\n img_scan = cv2.warpPerspective(des_image, M, (w, h))\n return img_scan\n\n\ndef data_extractor(image, roi):\n \"\"\"\n Extract data from given image\n :param image:\n :return: data array\n \"\"\"\n # Get around with image dimension issue\n name = \"image01.jpg\"\n cv2.imwrite(name, image)\n input_image = cv2.imread(name)\n os.remove(name)\n\n img_show = input_image.copy()\n img_mask = np.zeros_like(img_show)\n\n data = []\n for x, r in enumerate(roi):\n cv2.rectangle(img_mask, (r[0][0], r[0][1]), (r[1][0], r[1][1]), (0, 255, 0), cv2.FILLED)\n\n img_show = cv2.addWeighted(img_show, 0.99, img_mask, 0.1, 0)\n img_crop = image[r[0][1]:r[1][1], r[0][0]:r[1][0]]\n\n name = \"temp/\" + r[2] + \".jpg\"\n cv2.imwrite(name, img_crop)\n img0 = cv2.imread(name)\n os.remove(name)\n\n img_crop_ = ip.imageBinarization(img0)\n img_crop_ = ip.imageThinner(img_crop_)\n\n text = pytesseract.image_to_string(img_crop_, config=myconfig)\n data.append(text.strip())\n return data\n\n\nif __name__ == '__main__':\n if len(sys.argv) == 1:\n ROI = [[(472, 52), (1112, 200), 'Part#'],\n [(246, 718), (302, 795), 'Mold'],\n [(374, 426), (842, 495), 'Lot#'],\n [(394, 624), (742, 697), 'Batch#'],\n [(208, 530), (346, 593), 'Qty']]\n elif len(sys.argv) > 1 and sys.argv[1] == 'ROI':\n ROI = get_coordinate_and_types()\n\n # Read images\n img_template = cv2.imread('ImageTemplate/image0.jpg')\n path = 'InputImages'\n image_list = os.listdir(path)\n data_list = []\n titles = []\n\n for title in ROI:\n titles.append(title[2])\n\n data_list.append(titles)\n\n for i in image_list:\n img = cv2.imread(path + \"/\" + i)\n aligned_image = align_image(img_template, img, MAX_FEATURE, KEEP_PERCENT)\n # cv2.imshow(\"IMG\", aligned_image)\n # cv2.waitKey(0)\n extracted_text = data_extractor(aligned_image, ROI)\n data_list.append(extracted_text)\n # print(data_list)\n\n df = pd.DataFrame(data_list[1:], columns=data_list[:1])\n df.to_csv(\"Data/data.csv\")\n print('Done!')\n\n", "repo_name": "thuyluu9595/textExtraction", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 3698, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "cv2.cvtColor", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 27, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 28, "usage_type": "attribute"}, {"api_name": "cv2.ORB_create", "line_number": 31, "usage_type": "call"}, {"api_name": "cv2.BFMatcher", "line_number": 38, "usage_type": "call"}, {"api_name": "cv2.NORM_HAMMING", "line_number": 38, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 46, "usage_type": "call"}, {"api_name": "cv2.findHomography", "line_number": 48, "usage_type": "call"}, {"api_name": "cv2.RANSAC", "line_number": 48, "usage_type": "attribute"}, {"api_name": "cv2.warpPerspective", "line_number": 49, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 61, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 62, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 66, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 70, "usage_type": "call"}, {"api_name": "cv2.FILLED", "line_number": 70, "usage_type": "attribute"}, {"api_name": "cv2.addWeighted", "line_number": 72, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 76, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 77, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 78, "usage_type": "call"}, {"api_name": "Scripts.imagepreprocessing.imageBinarization", "line_number": 80, "usage_type": "call"}, {"api_name": "Scripts.imagepreprocessing", "line_number": 80, "usage_type": "name"}, {"api_name": "Scripts.imagepreprocessing.imageThinner", "line_number": 81, "usage_type": "call"}, {"api_name": "Scripts.imagepreprocessing", "line_number": 81, "usage_type": "name"}, {"api_name": "pytesseract.image_to_string", "line_number": 83, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 89, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 95, "usage_type": "attribute"}, {"api_name": "Scripts.RegionSelector.get_coordinate_and_types", "line_number": 96, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 99, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 101, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 111, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 119, "usage_type": "call"}]} +{"seq_id": "22691027462", "text": "import logging\n\nlogger_name = \"scraper\"\n\n\ndef setup_logger():\n logger = logging.getLogger(logger_name)\n logger.setLevel(logging.DEBUG)\n\n formatter = logging.Formatter(\n \"%(levelname)s - %(asctime)s - %(name)s:%(filename)s - %(message)s\"\n )\n stream_handler = logging.StreamHandler()\n stream_handler.setLevel(logging.INFO)\n stream_handler.setFormatter(formatter)\n if not logger.handlers:\n logger.addHandler(stream_handler)\n return logger\n\n\nsetup_logger()\n\n\ndef get_logger():\n return logging.getLogger(logger_name)\n", "repo_name": "pabloesm/mnm", "sub_path": "scraper/logger.py", "file_name": "logger.py", "file_ext": "py", "file_size_in_byte": 556, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "logging.getLogger", "line_number": 7, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 8, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 10, "usage_type": "call"}, {"api_name": "logging.StreamHandler", "line_number": 13, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 14, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "41904621396", "text": "import os\nimport shutil\n\nimport maya.cmds as cmds\nimport maya.mel as mel\nimport webrImport as web\n\n#\natl = web.mod( \"atom_path_lib\" )\nplace = web.mod( \"atom_place_lib\" )\nstage = web.mod( 'atom_splineStage_lib' )\nmisc = web.mod( 'atom_miscellaneous_lib' )\nsfk = web.mod( 'atom_splineFk_lib' )\nanm = web.mod( \"anim_lib\" )\nvcl = web.mod( \"vehicle_lib\" )\nac = web.mod( \"animCurve_lib\" )\nffm = web.mod( \"ffMpg\" )\npb = web.mod( \"playblast_lib\" )\nz = web.mod( 'zero' )\n# atl.path(segments=5, size=0.05, length=10)\n\n\ndef cadillac():\n '''\n build car\n '''\n vcl.car( name = 'cadillac', geo_grp = 'car_grp', frontSolidAxle = False, backSolidAxle = False, chassisAxleLock = False, X = 6.0,\n ns = 'geo',\n ref_geo = 'P:\\\\UW2\\\\assets\\\\veh\\\\cadillac\\\\model\\\\maya\\\\scenes\\\\cadillac_model_v011.ma' )\n\n\ndef bake_dynamics():\n '''\n\n '''\n #\n cmds.playbackOptions( minTime = 970 )\n cmds.playbackOptions( animationStartTime = 970 )\n #\n transform = ['translateX', 'translateY', 'translateZ', 'rotateX', 'rotateY', 'rotateZ']\n cmds.select( clear = 1 )\n try:\n cmds.select( \"*:*:chassis_dynamicBase\" )\n except:\n cmds.select( \"*:chassis_dynamicBase\" ) # added for UW2\n #\n sel = cmds.ls( sl = 1 )\n qualified_rigs = []\n n = None\n # qualify\n if sel:\n for s in sel:\n ac.deleteAnim2( s, attrs = transform ) # dont need this but could affect end result if keys exist\n for i in transform:\n cmds.setAttr( s + '.' + i, 0 )\n #\n ref = s.rsplit( ':', 1 )[0]\n set_obj_dynamics( ref + ':chassis_dynamicTarget', on = True )\n qualified_rigs.append( ref + ':chassis_dynamicTarget' )\n # return\n #\n if qualified_rigs:\n print( qualified_rigs )\n cmds.select( qualified_rigs )\n sel = cmds.ls( sl = 1 )\n for s in sel:\n ac.deleteAnim2( s, attrs = transform )\n z.zero( s )\n # return\n # store\n n = anm.SpaceSwitchList()\n # restore\n for q in qualified_rigs:\n set_obj_dynamics( q, on = False )\n n.restore()\n #\n cmds.playbackOptions( minTime = 1001 )\n cmds.playbackOptions( animationStartTime = 1001 )\n\n\ndef set_for_animation():\n '''\n \n '''\n # dynamics\n try:\n cmds.select( \"*:*:chassis_dynamicTarget\" )\n sel = cmds.ls( sl = 1 )\n for s in sel:\n cmds.setAttr( s + '.dynamicParentOffOn', 0 )\n cmds.setAttr( s + '.enable', 0 )\n except:\n pass\n # tires\n try:\n cmds.select( \"*:move\" )\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n cmds.setAttr( s + '.tireGeo', 0 )\n cmds.setAttr( s + '.tireProxy', 1 )\n except:\n pass\n # nested\n try:\n cmds.select( \"*:*:move\" )\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n cmds.setAttr( s + '.tireGeo', 0 )\n cmds.setAttr( s + '.tireProxy', 1 )\n except:\n pass\n # nested 2x\n try:\n cmds.select( \"*:*:*:move\" )\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n cmds.setAttr( s + '.tireGeo', 0 )\n cmds.setAttr( s + '.tireProxy', 1 )\n except:\n pass\n # time\n cmds.playbackOptions( minTime = 1001 )\n cmds.playbackOptions( animationStartTime = 1001 )\n\n\ndef set_all_dynamics():\n '''\n \n '''\n # time\n cmds.playbackOptions( minTime = 970 )\n cmds.playbackOptions( animationStartTime = 970 )\n # dynamics\n cmds.select( clear = True )\n try:\n cmds.select( \"*:*:chassis_dynamicTarget\" )\n except:\n pass\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n cmds.setAttr( s + '.dynamicParentOffOn', 1 )\n cmds.setAttr( s + '.enable', 1 )\n cmds.setAttr( s + '.startFrame', 970 )\n\n\ndef set_obj_dynamics( obj = '', on = False ):\n '''\n \n '''\n if on:\n cmds.setAttr( obj + '.dynamicParentOffOn', 1 )\n cmds.setAttr( obj + '.enable', 1 )\n cmds.setAttr( obj + '.startFrame', 970 )\n else:\n cmds.setAttr( obj + '.dynamicParentOffOn', 0 )\n cmds.setAttr( obj + '.enable', 0 )\n cmds.setAttr( obj + '.startFrame', 970 )\n\n\ndef set_for_playblast( dynamics = False, tires = True ):\n '''\n \n '''\n # time\n cmds.playbackOptions( minTime = 1001 )\n cmds.playbackOptions( animationStartTime = 1001 )\n # dynamics\n if dynamics:\n # delete anim\n transform = ['translateX', 'translateY', 'translateZ', 'rotateX', 'rotateY', 'rotateZ']\n try:\n cmds.select( \"*:*:chassis_dynamicBase\" )\n sel = cmds.ls( sl = 1 )\n #\n if sel:\n for s in sel:\n ac.deleteAnim2( s, attrs = transform )\n for i in transform:\n cmds.setAttr( s + '.' + i, 0 )\n # set\n set_all_dynamics()\n except:\n pass\n # tires\n if tires:\n # tires\n try:\n cmds.select( \"*:move\" )\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n cmds.setAttr( s + '.tireGeo', 1 )\n cmds.setAttr( s + '.tireProxy', 0 )\n except:\n pass\n # nested 1\n try:\n cmds.select( \"*:*:move\" )\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n cmds.setAttr( s + '.tireGeo', 1 )\n cmds.setAttr( s + '.tireProxy', 0 )\n except:\n pass\n # nested 2\n try:\n cmds.select( \"*:*:*:move\" )\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n cmds.setAttr( s + '.tireGeo', 1 )\n cmds.setAttr( s + '.tireProxy', 0 )\n except:\n pass\n\n\ndef blast( bake_all_dynamics = False, burn_in = False, live_dynamics = False ):\n '''\n \n '''\n start = 1001\n # uw2 res\n cmds.setAttr( 'defaultResolution.width', 1920 )\n cmds.setAttr( 'defaultResolution.height', 1080 )\n #\n # cmds.setAttr( 'defaultResolution.width', 3840 )\n # cmds.setAttr( 'defaultResolution.height', 2160 )\n\n # bake\n if bake_all_dynamics:\n bake_dynamics()\n\n # blast\n set_for_playblast( dynamics = live_dynamics )\n\n #\n if burn_in:\n # blast\n cmds.select( clear = 1 )\n result = pb.blast( x = 1.0, format = \"image\", qlt = 100, compression = \"png\", offScreen = True, useGlobals = True, forceTemp = True, camStr = False, strp_r = True, subDir = 'precomp', play = False ) # blastPath, blastName\n # to mp4\n pathOut = result[0].replace( result[1], '' )\n pathOutName = result[1].replace( '_precomp', '____cam' ) # added cam string, burnin expects cam suffix\n #\n mp4 = ffm.imgToMp4( pathIn = result[0], image = result[1], start = start, pathOut = pathOut, pathOutName = pathOutName )\n # copy mp4 to image seq directory, matching name\n shutil.copyfile( mp4, os.path.join( result[0], result[1] + '.mp4' ) )\n # add burn in\n ffm.burn_in( filein = mp4, startFrame = start, size = 25, rndrFrames = False )\n # move precomp string in all image seq names, including new copied mp4\n pb.blastRenameSeq( result = result, splitStr = '_v', moveStr = '_precomp' )\n # beauty blast with qt\n '''\n renderLayerBlast()\n '''\n else:\n # expecting traffic shots from bridge\n result = pb.blast( x = 1.0, format = \"image\", qlt = 100, compression = \"png\", offScreen = True, useGlobals = True, forceTemp = True, camStr = False, strp_r = True, subDir = '', play = False ) # blastPath, blastNam\n source = result[0]\n print( source )\n path = cmds.file( query = True, exn = True )\n sht = path.rsplit( '/', 1 )[1].split( '.' )[0]\n print( sht )\n dest = path.split( 'maya' )[0]\n dest = os.path.join( dest, 'playblasts' )\n dest = os.path.join( dest, sht )\n print( dest )\n if os.path.isdir( dest ):\n shutil.rmtree( dest )\n shutil.copytree( source.replace( '\\\\', '/' ), dest.replace( '\\\\', '/' ) )\n\n # pb.blastRenameSeq( result = result, splitStr = '_v', moveStr = '_traffic' )\n #\n set_for_animation()\n\n\ndef refPathAndAttach():\n '''\n ref path and attach\n '''\n path = 'P:\\\\UW2\\\\assets\\\\util\\\\path\\\\rig\\\\maya\\\\scenes\\\\path_rig_v006.ma'\n cmds.file( path, reference = True, ns = 'path_rig' )\n cmds.select( ['cadillac_rig:move', 'path_rig:onPath_front' ] )\n vcl.car_to_path()\n\n\ndef selSets():\n vcl.create_geo_set_files( name = 'cadillac' )\n\n\ndef leafs():\n '''\n \n '''\n X = 5\n # main rig groups/controllers\n PreBuild = place.rigPrebuild( Top = 1, Ctrl = True, SknJnts = True, Geo = True, World = True, Master = True, OlSkool = False, Size = 7 * X )\n cmds.select( cl = True )\n CHARACTER = PreBuild[0]\n CONTROLS = PreBuild[1]\n SKIN_JOINTS = PreBuild[2]\n GEO = PreBuild[3]\n WORLD_SPACE = PreBuild[4]\n MasterCt = PreBuild[5]\n\n #\n geo_grp = 'Leaf_maple'\n geo_grps = [\n 'Leaf_maple5',\n 'Leaf_maple4',\n 'Leaf_maple3',\n 'Leaf_maple2',\n 'Leaf_maple1'\n ]\n # cmds.select( geo_grps )\n cmds.group( geo_grps, n = geo_grp )\n\n geo = [\n 'Leaf_maple1_leaf',\n 'Leaf_maple1_stem',\n 'Leaf_maple2_leaf',\n 'Leaf_maple2_stem',\n 'Leaf_maple3_stem',\n 'Leaf_maple3_leaf',\n 'Leaf_maple4_leaf',\n 'Leaf_maple4_stem',\n 'Leaf_maple5_leaf',\n 'Leaf_maple5_stem'\n ]\n\n #\n cmds.parent( geo_grp, GEO[0] )\n # cmds.setAttr( geo_grp + '.translateX', -1.789 )\n # cmds.setAttr( geo_grp + '.translateZ', -7.5 )\n # cmds.setAttr( geo_grp + '.rotateY', 1.98 )\n\n # bend\n cmds.select( geo )\n bendRy = cmds.nonLinear( type = 'bend', name = 'bendRy', curvature = 0.0 )\n cmds.select( geo )\n bendRx = cmds.nonLinear( type = 'bend', name = 'bendRx', curvature = 0.0 )\n # bendY deformer rotations\n cmds.setAttr( bendRy[1] + '.rotateX', -90 ) # [1] handle # [0] deformer\n cmds.setAttr( bendRy[1] + '.rotateY', -90 )\n # bendX deformer rotations\n cmds.setAttr( bendRx[1] + '.rotateY', -90 )\n cmds.parent( bendRy[1], geo_grp )\n cmds.parent( bendRx[1], geo_grp )\n\n # return None\n # lock geo - [lock, keyable], [visible, lock, keyable]\n place.setChannels( bendRy[1], [False, False], [False, False], [True, False], [False, False, False] )\n place.setChannels( bendRx[1], [False, False], [False, False], [True, False], [False, False, False] )\n\n # leaf #\n Leaf = 'leaf'\n leaf = place.Controller( Leaf, MasterCt[0], False, 'loc_ctrl', X * 1, 17, 8, 1, ( 0, 0, 1 ), True, True )\n LeafCt = leaf.createController()\n place.setRotOrder( LeafCt[0], 2, True )\n cmds.parent( LeafCt[0], CONTROLS )\n cmds.setAttr( LeafCt[0] + '.translateY', -8 )\n cmds.parentConstraint( MasterCt[4], LeafCt[0], mo = True )\n cmds.parentConstraint( LeafCt[4], geo_grp, mo = True )\n # cmds.parentConstraint( LeafCt[4], bendRy[1], mo = True )\n # cmds.parentConstraint( LeafCt[4], bendRx[1], mo = True )\n # return None\n\n # leafBendY #\n LeafBendY = 'leafBendY'\n leafBendY = place.Controller( LeafBendY, MasterCt[0], False, 'diamond_ctrl', X * 1, 17, 8, 1, ( 0, 0, 1 ), True, True )\n LeafBendYCt = leafBendY.createController()\n place.setRotOrder( LeafBendYCt[0], 2, True )\n cmds.parent( LeafBendYCt[0], CONTROLS )\n cmds.parentConstraint( LeafCt[4], LeafBendYCt[0], mo = True )\n cmds.parentConstraint( LeafBendYCt[4], bendRy[1], mo = True )\n place.hijackAttrs( bendRy[0] + 'HandleShape', LeafBendYCt[2], 'curvature', 'curvature', set = False, default = 0, force = True )\n\n # leafBendX #\n LeafBendX = 'leafBendX'\n leafBendX = place.Controller( LeafBendX, MasterCt[0], False, 'diamond_ctrl', X * 0.9, 17, 8, 1, ( 0, 0, 1 ), True, True )\n LeafBendXCt = leafBendX.createController()\n place.setRotOrder( LeafBendXCt[0], 2, True )\n cmds.parent( LeafBendXCt[0], CONTROLS )\n cmds.parentConstraint( LeafCt[4], LeafBendXCt[0], mo = True )\n cmds.parentConstraint( LeafBendXCt[4], bendRx[1], mo = True )\n place.hijackAttrs( bendRx[0] + 'HandleShape', LeafBendXCt[2], 'curvature', 'curvature', set = False, default = 0, force = True )\n\n # leaf up #\n Leaf_u = 'leaf_up'\n leaf_u = place.Controller( Leaf_u, MasterCt[0], False, 'loc_ctrl', X * 1, 17, 8, 1, ( 0, 0, 1 ), True, True )\n Leaf_u_Ct = leaf_u.createController()\n place.setRotOrder( Leaf_u_Ct[0], 2, True )\n cmds.parent( Leaf_u_Ct[0], CONTROLS )\n cmds.setAttr( Leaf_u_Ct[0] + '.translateZ', 8 / 2 )\n cmds.parentConstraint( MasterCt[4], Leaf_u_Ct[0], mo = True )\n\n # leaf tip #\n Leaf_t = 'leaf_tip'\n leaf_t = place.Controller( Leaf_t, MasterCt[0], False, 'loc_ctrl', X * 1, 17, 8, 1, ( 0, 0, 1 ), True, True )\n Leaf_t_Ct = leaf_t.createController()\n place.setRotOrder( Leaf_t_Ct[0], 2, True )\n cmds.parent( Leaf_t_Ct[0], CONTROLS )\n cmds.setAttr( Leaf_t_Ct[0] + '.translateY', 8 )\n cmds.parentConstraint( MasterCt[4], Leaf_t_Ct[0], mo = True )\n cmds.aimConstraint( Leaf_t_Ct[4], LeafCt[2], wut = 'object', wuo = Leaf_u_Ct[4], aim = [0, 1, 0], u = [0, 0, 1], mo = False )\n place.setChannels( LeafCt[2], [False, True], [True, False], [True, False], [True, False, False] )\n\n # scale\n mstr = 'master'\n uni = 'uniformScale'\n scl = ['.scaleX', '.scaleY', '.scaleZ']\n #\n misc.addAttribute( [mstr], [uni], 0.1, 20.0, True, 'float' )\n cmds.setAttr( mstr + '.' + uni, 1.0 )\n misc.scaleUnlock( '___CONTROLS', sx = True, sy = True, sz = True )\n #\n for s in scl:\n cmds.connectAttr( mstr + '.' + uni, '___CONTROLS' + s )\n misc.scaleUnlock( '___GEO', sx = True, sy = True, sz = True )\n for s in scl:\n cmds.connectAttr( mstr + '.' + uni, '___GEO' + s )\n\n\ndef createWrap( *args, **kwargs ):\n # print args\n influence = args[0]\n surface = args[1]\n\n shapes = cmds.listRelatives( influence, shapes = True )\n influenceShape = shapes[0]\n\n shapes = cmds.listRelatives( surface, shapes = True )\n surfaceShape = shapes[0]\n\n weightThreshold = kwargs.get( 'weightThreshold', 0.0 )\n maxDistance = kwargs.get( 'maxDistance', 1.0 )\n exclusiveBind = kwargs.get( 'exclusiveBind', False )\n autoWeightThreshold = kwargs.get( 'autoWeightThreshold', True )\n falloffMode = kwargs.get( 'falloffMode', 0 )\n\n wrapData = cmds.deformer( surface, type = 'wrap' )\n wrapNode = wrapData[0]\n\n cmds.setAttr( wrapNode + '.weightThreshold', weightThreshold )\n cmds.setAttr( wrapNode + '.maxDistance', maxDistance )\n cmds.setAttr( wrapNode + '.exclusiveBind', exclusiveBind )\n cmds.setAttr( wrapNode + '.autoWeightThreshold', autoWeightThreshold )\n cmds.setAttr( wrapNode + '.falloffMode', falloffMode )\n\n cmds.connectAttr( surface + '.worldMatrix[0]', wrapNode + '.geomMatrix' )\n\n duplicateData = cmds.duplicate( influence, name = influence + 'Base' )\n base = duplicateData[0]\n shapes = cmds.listRelatives( base, shapes = True )\n baseShape = shapes[0]\n cmds.hide( base )\n\n if not cmds.attributeQuery( 'dropoff', n = influence, exists = True ):\n cmds.addAttr( influence, sn = 'dr', ln = 'dropoff', dv = 4.0, min = 0.0, max = 20.0 )\n cmds.setAttr( influence + '.dr', k = True )\n\n if cmds.nodeType( influenceShape ) == 'mesh':\n if not cmds.attributeQuery( 'smoothness', n = influence, exists = True ):\n cmds.addAttr( influence, sn = 'smt', ln = 'smoothness', dv = 0.0, min = 0.0 )\n cmds.setAttr( influence + '.smt', k = True )\n\n if not cmds.attributeQuery( 'inflType', n = influence, exists = True ):\n cmds.addAttr( influence, at = 'short', sn = 'ift', ln = 'inflType', dv = 2, min = 1, max = 2 )\n\n cmds.connectAttr( influenceShape + '.worldMesh', wrapNode + '.driverPoints[0]' )\n cmds.connectAttr( baseShape + '.worldMesh', wrapNode + '.basePoints[0]' )\n cmds.connectAttr( influence + '.inflType', wrapNode + '.inflType[0]' )\n cmds.connectAttr( influence + '.smoothness', wrapNode + '.smoothness[0]' )\n\n if cmds.nodeType( influenceShape ) == 'nurbsCurve' or cmds.nodeType( influenceShape ) == 'nurbsSurface':\n if not cmds.attributeQuery( 'wrapSamples', n = influence, exists = True ):\n cmds.addAttr( influence, at = 'short', sn = 'wsm', ln = 'wrapSamples', dv = 10, min = 1 )\n cmds.setAttr( influence + '.wsm', k = True )\n\n cmds.connectAttr( influenceShape + '.ws', wrapNode + '.driverPoints[0]' )\n cmds.connectAttr( baseShape + '.ws', wrapNode + '.basePoints[0]' )\n cmds.connectAttr( influence + '.wsm', wrapNode + '.nurbsSamples[0]' )\n\n cmds.connectAttr( influence + '.dropoff', wrapNode + '.dropoff[0]' )\n return wrapNode\n\n\ndef leafABC():\n '''\n \n '''\n # os\n if os.name == 'posix':\n project = cmds.workspace( rd = True, q = True ).split( 'scenes/' )[0]\n else:\n project = cmds.workspace( rd = True, q = True )\n # cache poath\n dataDir = project + 'cache/'\n index = project[:-1].rindex( '/' )\n shotDir = project[:index] + '/'\n index = shotDir[:-1].rindex( '/' )\n # parse scene path to derive scene name to be used in folder\n s_string = cmds.file( sn = True, q = True )\n s_splitString = s_string.split( '/' )\n i_splitStringLength = len( s_splitString )\n s_filename = s_splitString[( i_splitStringLength - 1 )]\n # parse scene name to derive name\n s_splitFolder = s_filename.split( '.' )\n i_splitStringLengthFolder = len( s_splitFolder )\n s_foldername = s_splitFolder[( i_splitStringLengthFolder - 2 )]\n # specify the plate name here\n '''\n plate = shotDir[index + 1:-1] + '_plate_01'\n imageDir = shotDir + 'images/' + plate + '/'\n imageList = []\n # images = os.listdir(imageDir)\n # for i in images:\n # if 'plate' in i:\n # imageList.append(i)\n '''\n\n start = cmds.playbackOptions ( ast = True, q = True )\n end = cmds.playbackOptions ( aet = True, q = True )\n print( start )\n\n # set timeline to images\n # cmds.playbackOptions( ast = start, aet = end, min = start, max = end )\n\n # make geo caache directory\n geoCacheDir = dataDir + 'alembic/'\n print( geoCacheDir )\n if not os.path.exists( os.path.join( dataDir, 'alembic' ) ):\n os.mkdir( geoCacheDir )\n # make cache version directory\n versions = os.listdir( geoCacheDir )\n print( versions )\n if versions:\n nextVersion = s_foldername\n cacheVersionDir = geoCacheDir + s_foldername.replace( 'anim', 'abc' ) # modified this line to use scene name as folder name\n if not os.path.exists( cacheVersionDir ):\n os.mkdir( cacheVersionDir )\n else:\n cacheVersionDir = geoCacheDir + s_foldername.replace( 'anim', 'abc' ) # modified this line to use scene name as folder name\n os.mkdir( cacheVersionDir )\n print( cacheVersionDir )\n print( os.path.join( cacheVersionDir, s_filename.replace( 'anim', 'abc' ) ) )\n # return None\n leafs = cmds.ls( sl = True )\n print( leafs )\n #\n i = 1\n for leaf in leafs:\n leaf_stripped = leaf.split( ':' )[1]\n # print s_filename.replace( 'anim', 'abc__' + leaf_stripped + '_' )\n path = cacheVersionDir + '//' + s_filename.replace( 'anim', 'abc__' + leaf_stripped + '_' )\n path = path.replace( '.ma', '.abc' )\n if os.path.isfile( path ):\n path = path.replace( leaf_stripped, leaf_stripped + '_reuse' )\n print( path )\n m = 'AbcExport -j \"-frameRange ' + str( int( start ) ) + ' ' + str( int( end ) ) + ' ' + '-attr vrayUserString_id -uvWrite -worldSpace -writeVisibility -writeUVSets -dataFormat ogawa -root ' + leaf + ' -file ' + path + '\";'\n print( m )\n mel.eval( m )\n i = i + 1\n\n'''\n# with bake\nimport webrImport as web\nspdr = web.mod('assets_uw2')\nspdr.blast(bake_all_dynamics = True, burn_in = True, live_dynamics = False )\n\n# no bake\nimport webrImport as web\nspdr = web.mod('assets_uw2')\nspdr.blast(bake_all_dynamics = False, burn_in = True, live_dynamics = False ) \n'''\n", "repo_name": "boochos/work", "sub_path": "assets_uw2.py", "file_name": "assets_uw2.py", "file_ext": "py", "file_size_in_byte": 20316, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "webrImport.mod", "line_number": 9, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 10, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 11, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 12, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 13, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 14, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 15, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 16, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 17, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 18, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 19, "usage_type": "call"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 37, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 37, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 38, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 38, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 41, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 41, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 43, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 43, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 45, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 45, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 47, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 47, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 55, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 55, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 64, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 64, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 65, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 65, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 77, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 77, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 78, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 78, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 87, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 87, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 88, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 88, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 90, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 90, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 91, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 91, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 96, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 96, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 97, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 97, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 100, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 100, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 101, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 101, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 106, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 106, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 107, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 107, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 110, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 110, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 111, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 111, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 116, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 116, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 117, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 117, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 120, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 120, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 121, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 121, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 125, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 125, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 126, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 126, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 134, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 134, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 135, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 135, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 137, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 137, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 139, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 139, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 142, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 142, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 145, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 145, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 146, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 146, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 147, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 147, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 155, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 155, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 156, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 156, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 157, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 157, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 159, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 159, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 160, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 160, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 161, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 161, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 169, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 169, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 170, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 170, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 176, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 176, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 177, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 177, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 183, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 183, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 192, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 192, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 193, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 193, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 196, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 196, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 197, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 197, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 202, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 202, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 203, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 203, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 206, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 206, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 207, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 207, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 212, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 212, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 213, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 213, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 216, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 216, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 217, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 217, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 228, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 228, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 229, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 229, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 244, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 244, "usage_type": "name"}, {"api_name": "shutil.copyfile", "line_number": 252, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 252, "usage_type": "call"}, {"api_name": "os.path", "line_number": 252, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 266, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 266, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 270, "usage_type": "call"}, {"api_name": "os.path", "line_number": 270, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 271, "usage_type": "call"}, {"api_name": "os.path", "line_number": 271, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 273, "usage_type": "call"}, {"api_name": "os.path", "line_number": 273, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 274, "usage_type": "call"}, {"api_name": "shutil.copytree", "line_number": 275, "usage_type": "call"}, {"api_name": "maya.cmds.file", "line_number": 287, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 287, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 288, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 288, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 303, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 303, "usage_type": "name"}, {"api_name": "maya.cmds.group", "line_number": 321, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 321, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 337, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 337, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 343, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 343, "usage_type": "name"}, {"api_name": "maya.cmds.nonLinear", "line_number": 344, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 344, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 345, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 345, "usage_type": "name"}, {"api_name": "maya.cmds.nonLinear", "line_number": 346, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 346, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 348, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 348, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 349, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 349, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 351, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 351, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 352, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 352, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 353, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 353, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 365, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 365, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 366, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 366, "usage_type": "name"}, {"api_name": "maya.cmds.parentConstraint", "line_number": 367, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 367, "usage_type": "name"}, {"api_name": "maya.cmds.parentConstraint", "line_number": 368, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 368, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 378, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 378, "usage_type": "name"}, {"api_name": "maya.cmds.parentConstraint", "line_number": 379, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 379, "usage_type": "name"}, {"api_name": "maya.cmds.parentConstraint", "line_number": 380, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 380, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 388, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 388, "usage_type": "name"}, {"api_name": "maya.cmds.parentConstraint", "line_number": 389, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 389, "usage_type": "name"}, {"api_name": "maya.cmds.parentConstraint", "line_number": 390, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 390, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 398, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 398, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 399, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 399, "usage_type": "name"}, {"api_name": "maya.cmds.parentConstraint", "line_number": 400, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 400, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 407, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 407, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 408, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 408, "usage_type": "name"}, {"api_name": "maya.cmds.parentConstraint", "line_number": 409, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 409, "usage_type": "name"}, {"api_name": "maya.cmds.aimConstraint", "line_number": 410, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 410, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 419, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 419, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 423, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 423, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 426, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 426, "usage_type": "name"}, {"api_name": "maya.cmds.listRelatives", "line_number": 434, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 434, "usage_type": "name"}, {"api_name": "maya.cmds.listRelatives", "line_number": 437, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 437, "usage_type": "name"}, {"api_name": "maya.cmds.deformer", "line_number": 446, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 446, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 449, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 449, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 450, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 450, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 451, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 451, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 452, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 452, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 453, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 453, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 455, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 455, "usage_type": "name"}, {"api_name": "maya.cmds.duplicate", "line_number": 457, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 457, "usage_type": "name"}, {"api_name": "maya.cmds.listRelatives", "line_number": 459, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 459, "usage_type": "name"}, {"api_name": "maya.cmds.hide", "line_number": 461, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 461, "usage_type": "name"}, {"api_name": "maya.cmds.attributeQuery", "line_number": 463, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 463, "usage_type": "name"}, {"api_name": "maya.cmds.addAttr", "line_number": 464, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 464, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 465, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 465, "usage_type": "name"}, {"api_name": "maya.cmds.nodeType", "line_number": 467, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 467, "usage_type": "name"}, {"api_name": "maya.cmds.attributeQuery", "line_number": 468, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 468, "usage_type": "name"}, {"api_name": "maya.cmds.addAttr", "line_number": 469, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 469, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 470, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 470, "usage_type": "name"}, {"api_name": "maya.cmds.attributeQuery", "line_number": 472, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 472, "usage_type": "name"}, {"api_name": "maya.cmds.addAttr", "line_number": 473, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 473, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 475, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 475, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 476, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 476, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 477, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 477, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 478, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 478, "usage_type": "name"}, {"api_name": "maya.cmds.nodeType", "line_number": 480, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 480, "usage_type": "name"}, {"api_name": "maya.cmds.attributeQuery", "line_number": 481, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 481, "usage_type": "name"}, {"api_name": "maya.cmds.addAttr", "line_number": 482, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 482, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 483, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 483, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 485, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 485, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 486, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 486, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 487, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 487, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 489, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 489, "usage_type": "name"}, {"api_name": "os.name", "line_number": 498, "usage_type": "attribute"}, {"api_name": "maya.cmds.workspace", "line_number": 499, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 499, "usage_type": "name"}, {"api_name": "maya.cmds.workspace", "line_number": 501, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 501, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 508, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 508, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 527, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 527, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 528, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 528, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 537, "usage_type": "call"}, {"api_name": "os.path", "line_number": 537, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 537, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 538, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 540, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 545, "usage_type": "call"}, {"api_name": "os.path", "line_number": 545, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 546, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 549, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 551, "usage_type": "call"}, {"api_name": "os.path", "line_number": 551, "usage_type": "attribute"}, {"api_name": "maya.cmds.ls", "line_number": 553, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 553, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 562, "usage_type": "call"}, {"api_name": "os.path", "line_number": 562, "usage_type": "attribute"}, {"api_name": "maya.mel.eval", "line_number": 567, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 567, "usage_type": "name"}]} +{"seq_id": "16234290407", "text": "from typing import Tuple, Callable, Union\n\nimport numpy as np\n\n\n##############\n# Type Hints #\n##############\nMask = np.ndarray\nSpectrum = np.ndarray\nRange = Tuple[float, float]\nFFilter = Callable[[np.ndarray, Union[float, Range]], np.ndarray]\n\n\ndef lpf(img: np.ndarray, r: float) -> Mask:\n \"\"\"\n Band Pass Filter compute a binary mask where\n mask[i, j] = 1 if\n - (i - x0) ^ 2 + (j - y0) ^ 2 <= r ^ 2\n where x0 and y0 are thr coords of the center of the image\n\n :param img: image as 2-D numpy.ndarray\n :param r: radio for clean the high frequencies\n :return: the binary mask\n \"\"\"\n rows, cols = img.shape\n center = (rows // 2, cols // 2)\n\n mask = np.zeros((rows, cols), np.uint8)\n x, y = np.ogrid[:rows, :cols]\n mask_area = (x - center[0]) ** 2 + (y - center[1]) ** 2 <= r ** 2\n mask[mask_area] = 1\n\n return mask\n\n\ndef hpf(img: np.ndarray, r: float) -> Mask:\n \"\"\"\n Band Pass Filter compute a binary mask where\n mask[i, j] = 0 if\n - (i - x0) ^ 2 + (j - y0) ^ 2 <= r ^ 2\n where x0 and y0 are thr coords of the center of the image\n\n :param img: image as 2-D numpy.ndarray\n\n :param r: radio for clean the high frequencies\n\n :return: the binary mask\n \"\"\"\n\n rows, cols = img.shape\n center = (rows // 2, cols // 2)\n\n mask = np.ones((rows, cols), np.uint8)\n x, y = np.ogrid[:rows, :cols]\n mask_area = (x - center[0]) ** 2 + (y - center[1]) ** 2 <= r ** 2\n mask[mask_area] = 0\n\n return mask\n\n\ndef bpf(img: np.ndarray, r: Tuple[float, float]) -> Mask:\n \"\"\"\n Band Pass Filter compute a binary mask where\n mask[i, j] = 1 if\n - r2 ^ 2 >= (i - x0) ^ 2 + (j - y0) ^ 2 >= r ^ 2\n where x0 and y0 are thr coords of the center of the image\n\n :param img: image as 2-D numpy.ndarray\n\n :param r: 2-items tuple (inner_radio, outer_radio)\n\n :return: a 2-D binary mask as numpy.ndarray\n \"\"\"\n\n r1, r2 = r\n rows, cols = img.shape\n center = (rows // 2, cols // 2)\n\n mask = np.zeros((rows, cols), np.uint8)\n x, y = np.ogrid[:rows, :cols]\n mask_area = np.logical_and(\n ((x - center[0]) ** 2 + (y - center[1]) ** 2 >= r1 ** 2),\n ((x - center[0]) ** 2 + (y - center[1]) ** 2 <= r2 ** 2)\n )\n\n print(mask_area.shape)\n mask[mask_area] = 1\n\n return mask\n\n\ndef detect_edges(img: np.ndarray, ffilter: FFilter, r: Union[float, Range]) -> Tuple[np.ndarray, Tuple[Spectrum, Mask]]:\n \"\"\"\n Compute fft in the given image and filter the frequencies using the mask\n returned by ffilter function in the given radio or radio_range\n\n :param img: image as 2-D numpy.ndarray\n\n :param ffilter: one of the functions lpf, hpf, bpf\n\n :param r: if ffilter is lpf or hpf is a float representing the radio\n if ffilter is bpf is 2-items tuple with (inner_radio, outer_radio)\n\n :return: image as numpy.array with the applied filter\n \"\"\"\n \n mask: np.ndarray = ffilter(img, r)\n fft: np.ndarray = np.fft.fft2(np.float32(img))\n fft_shift: np.ndarray = np.fft.fftshift(fft)\n\n magnitude_spectrum: np.ndarray = 20 * np.log(np.abs(fft_shift))\n\n # apply a mask and inverse DFT\n fft_shift *= mask\n\n fshift_mask_mag = 2000 * np.log(np.abs(fft_shift))\n\n ifft_shift = np.fft.ifftshift(fft_shift)\n img_back = np.abs(np.fft.ifft2(ifft_shift))\n\n return img_back, (magnitude_spectrum, fshift_mask_mag)\n", "repo_name": "alejandroklever/detedge", "sub_path": "detedge.py", "file_name": "detedge.py", "file_ext": "py", "file_size_in_byte": 3370, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.ndarray", "line_number": 9, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 10, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 11, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 12, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 12, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 12, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 15, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 29, "usage_type": "attribute"}, {"api_name": "numpy.ogrid", "line_number": 30, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 37, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 54, "usage_type": "attribute"}, {"api_name": "numpy.ogrid", "line_number": 55, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 62, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 62, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 80, "usage_type": "attribute"}, {"api_name": "numpy.ogrid", "line_number": 81, "usage_type": "attribute"}, {"api_name": "numpy.logical_and", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 93, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 93, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 108, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 109, "usage_type": "attribute"}, {"api_name": "numpy.fft.fft2", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 109, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 110, "usage_type": "attribute"}, {"api_name": "numpy.fft.fftshift", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 110, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 112, "usage_type": "attribute"}, {"api_name": "numpy.log", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.fft.ifftshift", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 119, "usage_type": "attribute"}, {"api_name": "numpy.abs", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.fft.ifft2", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 120, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 93, "usage_type": "name"}]} +{"seq_id": "21247463109", "text": "# -*- coding:utf-8 -*-\n# author: Xiaoyu Xing & Zhijing Jin\n# datetime: 2020/6/3\n\nimport os\nimport argparse\nfrom strategies import revTgt,revNon,addDiff\n\n\ndef get_args():\n parser = argparse.ArgumentParser('Settings for ARTS Generation')\n parser.add_argument('-dataset_name', default='laptop',\n choices=['laptop', 'rest', 'mams'],\n help='Choose a dataset from: laptop, mams, rest (which means the restaurant dataset)')\n parser.add_argument('-strategy', default='revTgt',\n choices=['revTgt', 'revNon', 'addDiff'],\n help='Choose a strategy from: RevTgt, RevNon, addDiff')\n args = parser.parse_args()\n return args\n\n\nif __name__ == '__main__':\n args = get_args()\n\n dataset = args.dataset_name\n strategy = args.strategy\n\n data_folder='data/src_data/{}/'.format(dataset)\n input_file = os.path.join(data_folder, '2_test_sent.json')\n output_file = os.path.join(data_folder, 'test_adv.json')\n\n if strategy == 'revTgt':\n revTgt(data_folder,input_file, output_file)\n elif strategy == 'revNon':\n revNon(data_folder,input_file, output_file)\n elif strategy == 'addDiff':\n addDiff(dataset, os.path.join(data_folder, '2_train_sent.json'),\n os.path.join(data_folder, 'test_sent.json'), output_file)\n", "repo_name": "zhijing-jin/ARTS_TestSet", "sub_path": "code/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1350, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 40, "dataset": "github-code", "pt": "25", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path", "line_number": 30, "usage_type": "attribute"}, {"api_name": "strategies.revTgt", "line_number": 33, "usage_type": "call"}, {"api_name": "strategies.revNon", "line_number": 35, "usage_type": "call"}, {"api_name": "strategies.addDiff", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path", "line_number": 38, "usage_type": "attribute"}]} +{"seq_id": "73217738304", "text": "\"\"\"Testing Todo Enpoint.\"\"\"\n\nimport datetime\nfrom typing import Dict, List, Optional, Union\n\nimport pytest\nfrom app.models.todo import TodoCreate, TodoInDB, TodoPublic\nfrom app.models.user import UserInDB\nfrom databases.core import Database\nfrom fastapi import FastAPI, status\nfrom fastapi.encoders import jsonable_encoder\nfrom httpx import AsyncClient\n\n# decorate all test with @pytest.mark.asyncio\npytestmark = pytest.mark.asyncio\n\n\nclass TestTodosRoute:\n \"\"\"Testing Routes.\"\"\"\n\n async def test_routes_exist(self, app: FastAPI, client: AsyncClient) -> None:\n \"\"\"Test if routes exists.\"\"\"\n res = await client.post(app.url_path_for(\"todos:create-todo\"), json={})\n assert res.status_code != status.HTTP_404_NOT_FOUND\n res = await client.get(app.url_path_for(\"todos:get-todo-by-id\", todo_id=1))\n assert res.status_code != status.HTTP_404_NOT_FOUND\n res = await client.get(app.url_path_for(\"todos:list-all-user-todos\"))\n assert res.status_code != status.HTTP_404_NOT_FOUND\n res = await client.put(app.url_path_for(\"todos:update-todo-by-id\", todo_id=1))\n assert res.status_code != status.HTTP_404_NOT_FOUND\n res = await client.delete(app.url_path_for(\"todos:delete-todo-by-id\", todo_id=0))\n assert res.status_code != status.HTTP_404_NOT_FOUND\n\n async def test_invalid_input_raises_error(self, app: FastAPI, authorized_client: AsyncClient) -> None:\n \"\"\"Test invalid input to route raises error 422.\"\"\"\n res = await authorized_client.post(app.url_path_for(\"todos:create-todo\"), json={})\n assert res.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY\n\n\nclass TestCreateTodo:\n \"\"\"Test Create todo route.\"\"\"\n\n async def test_valid_input_create_todo(\n self,\n app: FastAPI,\n authorized_client: AsyncClient,\n test_user: UserInDB,\n new_todo: TodoCreate,\n ) -> None:\n \"\"\"Test valid input creates todo.\"\"\"\n res = await authorized_client.post(\n app.url_path_for(\"todos:create-todo\"),\n json={\"new_todo\": jsonable_encoder(new_todo.dict())},\n )\n assert res.status_code == status.HTTP_201_CREATED\n created_todo = TodoPublic(**res.json())\n assert created_todo.name == new_todo.name\n assert created_todo.priority == new_todo.priority\n assert created_todo.duedate == new_todo.duedate\n assert created_todo.owner == test_user.id\n\n async def test_unauthorized_user_unable_to_create_todo(\n self, app: FastAPI, client: AsyncClient, new_todo: TodoCreate\n ) -> None:\n \"\"\"Test unauthorized user can't create a todo.\"\"\"\n res = await client.post(\n app.url_path_for(\"todos:create-todo\"),\n json={\"new_todo\": jsonable_encoder(new_todo.dict())},\n )\n assert res.status_code == status.HTTP_401_UNAUTHORIZED\n\n @pytest.mark.parametrize(\n \"invalid_payload, status_code\",\n (\n (None, 422),\n ({}, 422),\n ({\"name\": \"test_name\"}, 422),\n ({\"priority\": \"critical\"}, 422),\n ({\"name\": \"test_name\", \"notes\": \"test notes\"}, 422),\n ),\n )\n async def test_invalid_input_raises_error(\n self,\n app: FastAPI,\n authorized_client: AsyncClient,\n invalid_payload: Dict[str, Union[str, float]],\n test_todo: TodoInDB,\n status_code: int,\n ) -> None:\n \"\"\"Test invalid inputs raises error.\"\"\"\n res = await authorized_client.post(\n app.url_path_for(\"todos:create-todo\"),\n json={\"new_todo\": jsonable_encoder(invalid_payload)},\n )\n assert res.status_code == status_code\n\n\nclass TestGetTodo:\n \"\"\"Test Get todo route.\"\"\"\n\n async def test_get_todo_by_id(self, app: FastAPI, authorized_client: AsyncClient, test_todo: TodoCreate) -> None:\n \"\"\"Test authorized client can get todo by id.\"\"\"\n res = await authorized_client.get(app.url_path_for(\"todos:get-todo-by-id\", todo_id=test_todo.id))\n assert res.status_code == status.HTTP_200_OK\n todo = TodoPublic(**res.json()).dict(exclude={\"owner\"})\n assert todo == test_todo.dict(exclude={\"owner\"})\n\n async def test_unauthorized_users_cant_get_access_todos(\n self, app: FastAPI, client: AsyncClient, test_todo: TodoCreate\n ) -> None:\n \"\"\"Test unauthorized client can not get todo by id.\"\"\"\n res = await client.get(app.url_path_for(\"todos:get-todo-by-id\", todo_id=test_todo.id))\n assert res.status_code == status.HTTP_401_UNAUTHORIZED\n\n @pytest.mark.parametrize(\n \"id, status_code\",\n (\n (500, 404),\n (-1, 422),\n (None, 422),\n ),\n )\n async def test_wrong_id_returns_error(\n self, app: FastAPI, authorized_client: AsyncClient, id: int, status_code: int\n ) -> None:\n \"\"\"Test authorized client error when wrnong id is entered.\"\"\"\n res = await authorized_client.get(app.url_path_for(\"todos:get-todo-by-id\", todo_id=id))\n assert res.status_code == status_code\n\n async def test_get_all_todos_return_valid_response(\n self, app: FastAPI, authorized_client: AsyncClient, test_todo: TodoInDB\n ) -> None:\n \"\"\"Test all todos are return to client.\"\"\"\n res = await authorized_client.get(app.url_path_for(\"todos:list-all-user-todos\"))\n assert res.status_code == status.HTTP_200_OK\n assert isinstance(res.json(), list)\n assert len(res.json()) > 0\n todos = [TodoInDB(**todo) for todo in res.json()]\n assert test_todo in todos\n\n async def test_get_all_todos_returns_only_to_do_owned_todos(\n self,\n app: FastAPI,\n authorized_client: AsyncClient,\n test_user: UserInDB,\n db: Database,\n test_todo: TodoInDB,\n test_todos_list: List[TodoInDB],\n ) -> None:\n \"\"\"Test only owned todo are returned to client.\"\"\"\n res = await authorized_client.get(app.url_path_for(\"todos:list-all-user-todos\"))\n assert res.status_code == status.HTTP_200_OK\n assert isinstance(res.json(), list)\n assert len(res.json()) > 0\n todos = [TodoInDB(**todo) for todo in res.json()]\n assert test_todo in todos\n for todo in todos:\n assert todo.owner == test_user.id\n assert all(todo not in todos for todo in test_todos_list)\n\n\nclass TestUpdateTodo:\n \"\"\"Testing update todo endpoint.\"\"\"\n\n @pytest.mark.parametrize(\n \"attrs_to_change, values\",\n (\n ([\"name\"], [\"new fake todo name\"]),\n ([\"notes\"], [\"new kind of todo list\"]),\n ([\"priority\"], [\"standard\"]),\n ([\"name\", \"notes\"], [\"some more todos\", \"some extra fake description\"]),\n ([\"as_task\"], [True]),\n (\n [\"duedate\", \"priority\"],\n [(datetime.date.today() + datetime.timedelta(days=5)), \"standard\"],\n ),\n ),\n )\n async def test_update_todo_with_valid_input(\n self,\n app: FastAPI,\n authorized_client: AsyncClient,\n test_todo: TodoInDB,\n attrs_to_change: List[str],\n values: List[str],\n ) -> None:\n \"\"\"Test updated todo is successful with valid inputs.\"\"\"\n todo_update = {\"todo_update\": {attrs_to_change[i]: values[i] for i in range(len(attrs_to_change))}}\n res = await authorized_client.put(\n app.url_path_for(\"todos:update-todo-by-id\", todo_id=test_todo.id),\n json=jsonable_encoder(todo_update),\n )\n assert res.status_code == status.HTTP_200_OK\n updated_todo = TodoInDB(**res.json()) # make sure it's the same todo\n for i in range(len(attrs_to_change)): # making sure that any attribute updated changed to the correct value\n assert getattr(updated_todo, attrs_to_change[i]) != getattr(test_todo, attrs_to_change[i])\n assert getattr(updated_todo, attrs_to_change[i]) == values[i]\n # making sure no attributes values have changed\n for attr, value in updated_todo.dict().items():\n if attr not in attrs_to_change and attr != \"updated_at\":\n assert getattr(test_todo, attr) == value\n\n async def test_user_gets_error_if_updating_other_users_todo(\n self,\n app: FastAPI,\n authorized_client: AsyncClient,\n test_todos_list: List[TodoInDB],\n ) -> None:\n \"\"\"Test error if todo updated does not belong to owner.\"\"\"\n res = await authorized_client.put(\n app.url_path_for(\"todos:update-todo-by-id\", todo_id=test_todos_list[0].id),\n json=jsonable_encoder({\"todo_update\": {\"priority\": \"standard\"}}),\n )\n assert res.status_code == status.HTTP_403_FORBIDDEN\n\n async def test_user_cant_change_ownership_of_todo(\n self,\n app: FastAPI,\n authorized_client: AsyncClient,\n test_todo: TodoInDB,\n test_user: UserInDB,\n test_user2: UserInDB,\n ) -> None:\n \"\"\"Test ownership of todo cant be changed.\"\"\"\n res = await authorized_client.put(\n app.url_path_for(\"todos:update-todo-by-id\", todo_id=test_todo.id),\n json=jsonable_encoder({\"todo_update\": {\"owner\": test_user2.id}}),\n )\n assert res.status_code == status.HTTP_200_OK\n todo = TodoPublic(**res.json())\n assert todo.owner == test_user.id\n\n @pytest.mark.parametrize(\n \"id, payload, status_code\",\n (\n (-1, {\"name\": \"test\"}, 422),\n (0, {\"name\": \"test2\"}, 422),\n (5000, {\"name\": \"test3\"}, 404),\n (1, None, 422),\n (1, {\"priority\": \"invalid priority type\"}, 422),\n (1, {\"priority\": None}, 400),\n ),\n )\n async def test_update_todo_with_invalid_input_throws_error(\n self,\n app: FastAPI,\n authorized_client: AsyncClient,\n id: int,\n payload: Dict[str, Optional[str]],\n status_code: int,\n ) -> None:\n \"\"\"Test updating to do with invalid input return an error.\"\"\"\n todo_update = {\"todo_update\": payload}\n res = await authorized_client.put(app.url_path_for(\"todos:update-todo-by-id\", todo_id=id), json=todo_update)\n assert res.status_code == status_code\n\n\nclass TestDeleteTodo:\n \"\"\"Testing delete todo endpoint.\"\"\"\n\n async def test_can_delete_todo_successfully(\n self, app: FastAPI, authorized_client: AsyncClient, test_todo: TodoInDB\n ) -> None:\n \"\"\"Testing existing todo can be deleted successfully.\"\"\"\n res = await authorized_client.delete(app.url_path_for(\"todos:delete-todo-by-id\", todo_id=test_todo.id))\n assert res.status_code == status.HTTP_200_OK\n # ensuring that todo is removed\n res = await authorized_client.get(app.url_path_for(\"todos:get-todo-by-id\", todo_id=test_todo.id))\n assert res.status_code == status.HTTP_404_NOT_FOUND\n\n async def test_user_cannot_delete_others_todo(\n self,\n app: FastAPI,\n authorized_client: AsyncClient,\n test_todos_list: List[TodoInDB],\n ) -> None:\n \"\"\"Tesing users cannot deleted another user's todo.\"\"\"\n res = await authorized_client.delete(app.url_path_for(\"todos:delete-todo-by-id\", todo_id=test_todos_list[0].id))\n assert res.status_code == status.HTTP_403_FORBIDDEN\n\n @pytest.mark.parametrize(\n \"id, status_code\",\n (\n (500, 404),\n (0, 422),\n (-1, 422),\n (None, 422),\n ),\n )\n async def test_can_delete_todo_invalid_throws_error(\n self,\n app: FastAPI,\n authorized_client: AsyncClient,\n test_todo: TodoInDB,\n id: int,\n status_code: int,\n ) -> None:\n \"\"\"Testing invalid input to todo delete endpoint throws an error.\"\"\"\n res = await authorized_client.delete(app.url_path_for(\"todos:delete-todo-by-id\", todo_id=id))\n assert res.status_code == status_code\n\n\n# class TestGetTodoTasks:\n# \"\"\"Testing get todotask endpoint.\"\"\"\n\n# async def test_can_get_all_task(\n# self,\n# app: FastAPI,\n# authorized_client: AsyncClient,\n# test_user: UserInDB,\n# test_todo: TodoInDB,\n# test_todos_list_as_task: List[TodoInDB],\n# ) -> None:\n# \"\"\"User can get all todo's with that are offered as task.\"\"\"\n# res = await authorized_client.get(app.url_path_for(\"todo_task:list-all-tasks\"))\n# assert res.status_code == status.HTTP_200_OK\n# assert isinstance(res.json(), list)\n# assert len(res.json()) > 0\n# todos = [TodoInDB(**todo) for todo in res.json()]\n# assert test_todo not in todos\n# for todo in todos:\n# assert todo.owner != test_user.id\n# assert todo.as_task is True\n# assert all(todo in todos for todo in test_todos_list_as_task)\n", "repo_name": "emilearthur/todo", "sub_path": "backend/tests/test_todos.py", "file_name": "test_todos.py", "file_ext": "py", "file_size_in_byte": 12855, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pytest.mark", "line_number": 15, "usage_type": "attribute"}, {"api_name": "fastapi.FastAPI", "line_number": 21, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 21, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 23, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 23, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_404_NOT_FOUND", "line_number": 24, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 24, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 25, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 25, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_404_NOT_FOUND", "line_number": 26, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 26, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 27, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 27, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_404_NOT_FOUND", "line_number": 28, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 28, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 29, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 29, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_404_NOT_FOUND", "line_number": 30, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 30, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 31, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 31, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_404_NOT_FOUND", "line_number": 32, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 32, "usage_type": "name"}, {"api_name": "fastapi.FastAPI", "line_number": 34, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 34, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 36, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 36, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_422_UNPROCESSABLE_ENTITY", "line_number": 37, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 37, "usage_type": "name"}, {"api_name": "fastapi.FastAPI", "line_number": 45, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 46, "usage_type": "name"}, {"api_name": "app.models.user.UserInDB", "line_number": 47, "usage_type": "name"}, {"api_name": "app.models.todo.TodoCreate", "line_number": 48, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 52, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 52, "usage_type": "name"}, {"api_name": "fastapi.encoders.jsonable_encoder", "line_number": 53, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_201_CREATED", "line_number": 55, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 55, "usage_type": "name"}, {"api_name": "app.models.todo.TodoPublic", "line_number": 56, "usage_type": "call"}, {"api_name": "fastapi.FastAPI", "line_number": 63, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 63, "usage_type": "name"}, {"api_name": "app.models.todo.TodoCreate", "line_number": 63, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 67, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 67, "usage_type": "name"}, {"api_name": "fastapi.encoders.jsonable_encoder", "line_number": 68, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_401_UNAUTHORIZED", "line_number": 70, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 70, "usage_type": "name"}, {"api_name": "fastapi.FastAPI", "line_number": 84, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 85, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 86, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 86, "usage_type": "name"}, {"api_name": "app.models.todo.TodoInDB", "line_number": 87, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 92, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 92, "usage_type": "name"}, {"api_name": "fastapi.encoders.jsonable_encoder", "line_number": 93, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 72, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 72, "usage_type": "attribute"}, {"api_name": "fastapi.FastAPI", "line_number": 101, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 101, "usage_type": "name"}, {"api_name": "app.models.todo.TodoCreate", "line_number": 101, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 103, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 103, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 104, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 104, "usage_type": "name"}, {"api_name": "app.models.todo.TodoPublic", "line_number": 105, "usage_type": "call"}, {"api_name": "fastapi.FastAPI", "line_number": 109, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 109, "usage_type": "name"}, {"api_name": "app.models.todo.TodoCreate", "line_number": 109, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 112, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 112, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_401_UNAUTHORIZED", "line_number": 113, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 113, "usage_type": "name"}, {"api_name": "fastapi.FastAPI", "line_number": 124, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 124, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 127, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 127, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 115, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 115, "usage_type": "attribute"}, {"api_name": "fastapi.FastAPI", "line_number": 131, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 131, "usage_type": "name"}, {"api_name": "app.models.todo.TodoInDB", "line_number": 131, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 134, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 134, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 135, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 135, "usage_type": "name"}, {"api_name": "app.models.todo.TodoInDB", "line_number": 138, "usage_type": "call"}, {"api_name": "fastapi.FastAPI", "line_number": 143, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 144, "usage_type": "name"}, {"api_name": "app.models.user.UserInDB", "line_number": 145, "usage_type": "name"}, {"api_name": "databases.core.Database", "line_number": 146, "usage_type": "name"}, {"api_name": "app.models.todo.TodoInDB", "line_number": 147, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 148, "usage_type": "name"}, {"api_name": "app.models.todo.TodoInDB", "line_number": 148, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 151, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 151, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 152, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 152, "usage_type": "name"}, {"api_name": "app.models.todo.TodoInDB", "line_number": 155, "usage_type": "call"}, {"api_name": "fastapi.FastAPI", "line_number": 181, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 182, "usage_type": "name"}, {"api_name": "app.models.todo.TodoInDB", "line_number": 183, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 184, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 185, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 190, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 190, "usage_type": "name"}, {"api_name": "fastapi.encoders.jsonable_encoder", "line_number": 191, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 193, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 193, "usage_type": "name"}, {"api_name": "app.models.todo.TodoInDB", "line_number": 194, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 165, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 165, "usage_type": "attribute"}, {"api_name": "datetime.date.today", "line_number": 175, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 175, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 175, "usage_type": "call"}, {"api_name": "fastapi.FastAPI", "line_number": 205, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 206, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 207, "usage_type": "name"}, {"api_name": "app.models.todo.TodoInDB", "line_number": 207, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 211, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 211, "usage_type": "name"}, {"api_name": "fastapi.encoders.jsonable_encoder", "line_number": 212, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_403_FORBIDDEN", "line_number": 214, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 214, "usage_type": "name"}, {"api_name": "fastapi.FastAPI", "line_number": 218, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 219, "usage_type": "name"}, {"api_name": "app.models.todo.TodoInDB", "line_number": 220, "usage_type": "name"}, {"api_name": "app.models.user.UserInDB", "line_number": 221, "usage_type": "name"}, {"api_name": "app.models.user.UserInDB", "line_number": 222, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 226, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 226, "usage_type": "name"}, {"api_name": "fastapi.encoders.jsonable_encoder", "line_number": 227, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 229, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 229, "usage_type": "name"}, {"api_name": "app.models.todo.TodoPublic", "line_number": 230, "usage_type": "call"}, {"api_name": "fastapi.FastAPI", "line_number": 246, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 247, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 249, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 249, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 254, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 254, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 233, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 233, "usage_type": "attribute"}, {"api_name": "fastapi.FastAPI", "line_number": 262, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 262, "usage_type": "name"}, {"api_name": "app.models.todo.TodoInDB", "line_number": 262, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 265, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 265, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 266, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 266, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 268, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 268, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_404_NOT_FOUND", "line_number": 269, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 269, "usage_type": "name"}, {"api_name": "fastapi.FastAPI", "line_number": 273, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 274, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 275, "usage_type": "name"}, {"api_name": "app.models.todo.TodoInDB", "line_number": 275, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 278, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 278, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_403_FORBIDDEN", "line_number": 279, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 279, "usage_type": "name"}, {"api_name": "fastapi.FastAPI", "line_number": 292, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 293, "usage_type": "name"}, {"api_name": "app.models.todo.TodoInDB", "line_number": 294, "usage_type": "name"}, {"api_name": "app.models.todo.url_path_for", "line_number": 299, "usage_type": "call"}, {"api_name": "app.models.todo", "line_number": 299, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 281, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 281, "usage_type": "attribute"}]} +{"seq_id": "71797417344", "text": "import torch\nimport torchvision\nfrom torchvision import transforms\nfrom PIL import Image\nfrom os import listdir\nimport random\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport os\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\n\n\n# import der libraries\n\nnormalize = transforms.Normalize(\n mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]\n)\ntransforms = transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(256),\n transforms.ToTensor(),\n normalize])\n\n\n# transformation der bilder => gleiche Ausgangslage\n\n\n#TARGET: [isCat, isDog]\ntrain_data_list = []\ntarget_list = []\ntrain_data = []\nwaited = False\nfiles = listdir('C:/Users/meame/Desktop/PetImages/training_data/')\nfor i in range(len(listdir('C:/Users/meame/Desktop/PetImages/training_data/'))):\n\n # zugreifen in den ordner mit den Bildern --> random pick (f)\n\n if len(train_data) == 58 and not waited:\n waited = True\n continue\n f = random.choice(files)\n files.remove(f)\n img = Image.open(\"C:/Users/meame/Desktop/PetImages/training_data/\" + f)\n img_tensor = transforms(img)#(3,256,256)\n train_data_list.append(img_tensor)\n isCat = 1 if 'cat' in f else 0\n isDog = 1 if 'dog' in f else 0\n target = [isCat, isDog]\n target_list.append(target)\n if len(train_data_list) >= 64:\n train_data.append((torch.stack(train_data_list), target_list))\n train_data_list = []\n target_list = []\n print('Loaded batch ', len(train_data), 'of ', int(len(listdir('C:/Users/meame/Desktop/PetImages/training_data/'))/64))\n print('Percentage Done: ', 100*len(train_data)/int(len(listdir('C:/Users/meame/Desktop/PetImages/training_data/'))/64), '%')\n if len(train_data) > 150:\n break\n\nclass Netz(nn.Module):\n def __init__(self):\n super(Netz, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, kernel_size=3)\n self.conv2 = nn.Conv2d(6, 12, kernel_size=3)\n self.conv3 = nn.Conv2d(12, 24, kernel_size=3)\n self.conv4 = nn.Conv2d(24, 48, kernel_size=3)\n self.conv5 = nn.Conv2d(48, 96, kernel_size=3)\n self.conv6 = nn.Conv2d(96, 192, kernel_size=3)\n self.dropout1 = nn.Dropout(p=0.3)\n self.dropout2 = nn.Dropout(p=0.3)\n self.fc1 = nn.Linear(768, 256)\n self.fc2 = nn.Linear(256, 2)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.max_pool2d(x,2)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.max_pool2d(x,2)\n x = F.relu(x)\n x = self.conv3(x)\n x = F.max_pool2d(x,2)\n x = F.relu(x)\n x = self.conv4(x)\n x = F.max_pool2d(x,2)\n x = F.relu(x)\n x = self.conv5(x)\n x = F.max_pool2d(x,2)\n x = F.relu(x)\n x = self.conv6(x)\n x = F.max_pool2d(x,2)\n x = F.relu(x)\n x = self.dropout1(x)\n x = x.view(-1,768)\n x = F.relu(self.dropout2(self.fc1(x)))\n x = self.fc2(x)\n return F.sigmoid(x)\n\nmodel = Netz()\nmodel.cuda()\n\n\nif os.path.isfile('meinNetz.pt'):\n model = torch.load('meinNetz.pt')\n\noptimizer = optim.RMSprop(model.parameters(), lr=1e-3)\n#optimizer = optim.Adam(model.parameters(), lr=0.01)\ndef train(epoch):\n model.train()\n batch_id = 0\n for data, target in train_data:\n data = data.cuda()\n target = torch.Tensor(target).cuda()\n data = Variable(data)\n target = Variable(target)\n optimizer.zero_grad()\n out = model(data)\n criterion = F.binary_cross_entropy\n loss = criterion(out, target)\n loss.backward()\n optimizer.step()\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_id * len(data), len(train_data),\n 100. * batch_id / len(train_data), loss.data[0]))\n batch_id = batch_id + 1\n\n\n# wir nehmen ein random bild --> bringen es in das richte Format --> laden es auf die Grafikkarte --> lassen die KI arbeiten --> zeigt das Bild und ob es ein Hund oder eine Katze ist\ndef test():\n model.eval()\n files = listdir('C:/Users/meame/Desktop/PetImages/test_data/')\n f = random.choice(files)\n img = Image.open('C:/Users/meame/Desktop/PetImages/test_data/' + f)\n img_eval_tensor = transforms(img)\n img_eval_tensor.unsqueeze_(0)\n data = Variable(img_eval_tensor.cuda())\n out = model(data)\n #print(str(f) + \": \" + str(out.data.max(1, keepdim=True)[1]))\n draw = ImageDraw.Draw(img)\n # font = ImageFont.truetype(, )\n font = ImageFont.truetype(\"Roboto-Bold.ttf\", 50)\n # draw.text((x, y),\"Sample Text\",(r,g,b))\n text = \"Cat\"\n print(out.data.max(1, keepdim=True)[1].cpu().numpy()[0] )\n if out.data.max(1, keepdim=True)[1].cpu().numpy()[0] != 0:\n text = \"Dog\"\n draw.text((0, 0), text, (255, 255, 255), font=font)\n img.show()\n #x = input('')\n\nfor epoch in range(1,30):\n train(epoch)\n test()\n torch.save(model, 'meinNetz.pt')", "repo_name": "DarkPasha/PSEMKI", "sub_path": "alte_versionen/catsanddogsv2.py", "file_name": "catsanddogsv2.py", "file_ext": "py", "file_size_in_byte": 5096, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "torchvision.transforms.Normalize", "line_number": 18, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 18, "usage_type": "name"}, {"api_name": "torchvision.transforms", "line_number": 22, "usage_type": "name"}, {"api_name": "torchvision.transforms.Compose", "line_number": 22, "usage_type": "call"}, {"api_name": "torchvision.transforms.Resize", "line_number": 22, "usage_type": "call"}, {"api_name": "torchvision.transforms.CenterCrop", "line_number": 23, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 23, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 24, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 24, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 36, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 37, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 44, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 46, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 46, "usage_type": "name"}, {"api_name": "torchvision.transforms", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 54, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 57, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 62, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 62, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 65, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 66, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 67, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 68, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 69, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 69, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 70, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 71, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 72, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 72, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 73, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 74, "usage_type": "name"}, {"api_name": "torch.nn.functional.max_pool2d", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 78, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 79, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 79, "usage_type": "name"}, {"api_name": "torch.nn.functional.max_pool2d", "line_number": 81, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 81, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 82, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 82, "usage_type": "name"}, {"api_name": "torch.nn.functional.max_pool2d", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 84, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 85, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 85, "usage_type": "name"}, {"api_name": "torch.nn.functional.max_pool2d", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 87, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 88, "usage_type": "name"}, {"api_name": "torch.nn.functional.max_pool2d", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 90, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 91, "usage_type": "name"}, {"api_name": "torch.nn.functional.max_pool2d", "line_number": 93, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 93, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 94, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 94, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 97, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 97, "usage_type": "name"}, {"api_name": "torch.nn.functional.sigmoid", "line_number": 99, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 99, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 105, "usage_type": "call"}, {"api_name": "os.path", "line_number": 105, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 106, "usage_type": "call"}, {"api_name": "torch.optim.RMSprop", "line_number": 108, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 108, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 115, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 116, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 117, "usage_type": "call"}, {"api_name": "torch.nn.functional.binary_cross_entropy", "line_number": 120, "usage_type": "attribute"}, {"api_name": "torch.nn.functional", "line_number": 120, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 133, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 134, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 135, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 135, "usage_type": "name"}, {"api_name": "torchvision.transforms", "line_number": 136, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 138, "usage_type": "call"}, {"api_name": "PIL.ImageDraw.Draw", "line_number": 141, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 141, "usage_type": "name"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 143, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 143, "usage_type": "name"}, {"api_name": "torch.save", "line_number": 156, "usage_type": "call"}]} +{"seq_id": "36285649937", "text": "#!/usr/bin/env python\nimport sys\nimport os\nimport subprocess\nimport datetime\nimport shutil\n\n\"\"\"\nRules for Trashinfo files to work\nThe format of trashinfo is similar to the format of a desktop entry file, as described in the Desktop Entry Specification.\nIts first line must be [Trash Info]. It also must have two lines that are key/value pairs as described in the Desktop Entry Specification:\nThe key “Path” contains the original location of the file/directory, as either an absolute pathname (starting with the slash character “/”) or a relative pathname (starting with any other character). \nA relative pathname is to be from the directory in which the trash directory resides (for example, from $XDG_DATA_HOME for the “home trash” directory); it MUST not include a “..” directory, and for files not “under” that directory, absolute pathnames must be used. \nThe system SHOULD support absolute pathnames only in the “home trash” directory, not in the directories under $topdir.\nThe value type for this key is “string”; it SHOULD store the file name as the sequence of bytes produced by the file system, with characters escaped as in URLs (as defined by RFC 2396, section 2). The key “DeletionDate” contains the date and time when the file/directory was trashed. \nThe date and time are to be in the YYYY-MM-DDThh:mm:ss format (see RFC 3339). The time zone should be the user's (or filesystem's) local time. The value type for this key is “string”.\n\"\"\"\n# First get the file to be deleted\nif len(sys.argv) == 2:\n filename = sys.argv[1]\nelse:\n print (\"Usage: trash.py filename\")\n exit(1)\n\n# Check if the file exist or it is creation of a fertile mind\nif os.path.exists(filename):\n print (\"Trashing the file/folder...\")\nelse:\n print (\"The file does not exist any more.\\nHave it been deleted already?\")\n exit(1)\n\n# Create file info file\ncasa = os.getenv('HOME')+\"/.local/share/Trash\"\nlocfile = os.path.realpath(filename)\nnow = datetime.datetime.now()\ndate = now.strftime(\"%Y%m%dT%H:%M:%S\")\n\nif os.path.exists(casa+\"/files\"):\n print (\"files folder ready\")\nelse:\n subprocess.call(\"mkdir -p %s/files\" %(casa), shell=True)\n subprocess.call(\"mkdir -p %s/info\" %(casa),shell=True)\n\nif os.path.isfile(filename):\n arq = subprocess.check_output(\"basename \\\"%s\\\"\" %(filename), shell=True)\n arq = arq.decode(\"utf-8\").rstrip(\"\\n\")\n print (arq)\nelif os.path.isdir(filename):\n arq = subprocess.check_output(\"basename \\\"%s\\\"\" %(filename), shell=True)\n arq = arq.decode(\"utf-8\").rstrip(\"\\n\")\n print (arq)\n\nwith open('%s/info/%s.trashinfo' % (casa,arq), 'w') as f:\n f.write(\"[Trash Info]\\n\")\n f.write(\"Path=%s\\n\" % locfile)\n f.write(\"DeletionDate=%s\\n\" % date)\n\n\n\n# Move the file to the trash\nshutil.move(locfile, casa+\"/files/\"+arq)\n\n", "repo_name": "mauricioph/myscripts", "sub_path": "trash.py", "file_name": "trash.py", "file_ext": "py", "file_size_in_byte": 2802, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sys.argv", "line_number": 19, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 20, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "os.getenv", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path.realpath", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 35, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 35, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path", "line_number": 38, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 41, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "subprocess.check_output", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path", "line_number": 48, "usage_type": "attribute"}, {"api_name": "subprocess.check_output", "line_number": 49, "usage_type": "call"}, {"api_name": "shutil.move", "line_number": 61, "usage_type": "call"}]} +{"seq_id": "14286966970", "text": "# _*_ coding utf-8 _*_\n# 开发人员: PC\n# 开发时间: 2021/2/1910:14\n# 开发工具: PyCharm\nfrom selenium import webdriver\nfrom selenium.webdriver import TouchActions\nfrom selenium.webdriver.common.by import By\n\n\n\nclass TestTouchAction():\n def setup(self):\n option=webdriver.ChromeOptions()\n option.add_experimental_option('w3c',False)\n self.driver=webdriver.Chrome(options=option)\n self.driver.implicitly_wait(5)\n self.driver.maximize_window()\n\n def teardown(self):\n self.driver.quit()\n\n def test_touchAction(self):\n self.driver.get(\"https://www.baidu.com\")\n element1=self.driver.find_element(By.ID,\"kw\")\n element1.send_keys(\"selenium测试\")\n element2=self.driver.find_element(By.ID,'su')\n action=TouchActions(self.driver)\n action.tap(element2)\n action.scroll_from_element(element1,0,10000)\n action.perform()\n\n", "repo_name": "jimanman09/pythonProjectdask1", "sub_path": "testselenium/test_touchAction.py", "file_name": "test_touchAction.py", "file_ext": "py", "file_size_in_byte": 941, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "selenium.webdriver.ChromeOptions", "line_number": 13, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 13, "usage_type": "name"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 15, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 15, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.ID", "line_number": 24, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 24, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.ID", "line_number": 26, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 26, "usage_type": "name"}, {"api_name": "selenium.webdriver.TouchActions", "line_number": 27, "usage_type": "call"}]} +{"seq_id": "5832802845", "text": "# from numpy import exp, abs, angle\r\nimport time\r\n# Import internal programs\r\n# Import Internal Programs\r\nimport L2_speed_control as sc\r\nimport L2_inverse_kinematics as inv\r\nimport L2_vector as vec\r\nimport L1_lidar\r\nimport rcpy\r\nimport rcpy.motor as motor\r\n# Import External programs\r\nimport time\r\n\r\nprint(\"loading libraries for color tracking...\")\r\nimport cv2 # For image capture and processing\r\nimport argparse # For fetching user arguments\r\nimport numpy as np # Kernel\r\n\r\nprint(\"loading rcpy.\")\r\nimport rcpy # Import rcpy library\r\nimport rcpy.motor as motor # Import rcpy motor module\r\n\r\nprint(\"finished loading libraries.\")\r\n# Camera\r\n\r\ncamera_input = 0 # Define camera input. Default=0. 0=/dev/video0\r\n\r\nsize_w = 240 # Resized image width. This is the image width in pixels.\r\nsize_h = 160 # Resized image height. This is the image height in pixels.\r\n\r\n# Color Range, described in HSV\r\n\r\n# pink for spray function (change to purple)\r\n# spray1_min = 155 # Minimum H value\r\n# spray2_min = 60 # Minimum S value\r\n# spray3_min = 45 # Minimum V value\r\n\r\n# spray1_max = 180 # Maximum H value\r\n# spray2_max = 195 # Maximum S value\r\n# spray3_max = 240 # Maximum V value\r\n\r\n# green for lift\r\nlift1_min = 30 # Minimum H value\r\nlift2_min = 90 # Minimum S value\r\nlift3_min = 130 # Minimum V value\r\n\r\nlift1_max = 70 # Maximum H value\r\nlift2_max = 190 # Maximum S value\r\nlift3_max = 205 # Maximum V value\r\n\r\nfilter = 'HSV' # Use HSV to describe pixel color values\r\n\r\n\r\ndef MotorUp(speed):\r\n motor.set(motor_up, speed)\r\n\r\n\r\ndef patrolling():\r\n blocker = 0\r\n initial = vec.getValid()\r\n print(initial)\r\n for Vec in initial:\r\n print(Vec)\r\n dist = Vec[0]\r\n angle = Vec[1]\r\n if dist <= 0.3 and dist > 0.005:\r\n blocker = blocker + 1\r\n print(blocker)\r\n\r\n if blocker > 0:\r\n print(\"false\") # something in the way, stop and wait\r\n myVelocities = np.array([0.0, 0]) # input your first pair\r\n myPhiDots = inv.convert(myVelocities)\r\n sc.driveOpenLoop(myPhiDots)\r\n else:\r\n print(\"True\") # nothing in front, move forward\r\n myVelocities = np.array([0.4, 0]) # input your first pair\r\n myPhiDots = inv.convert(myVelocities)\r\n sc.driveOpenLoop(myPhiDots)\r\n time.sleep(.5) # input your duration (s)\r\n dis_moved = dis_moved + 0.2\r\n\r\n\r\ndef deliver():\r\n x = 0\r\n if __name__ == \"__main__\":\r\n while rcpy.get_state() != rcpy.EXITING: # exit loop if rcpy not ready\r\n if rcpy.get_state() == rcpy.RUNNING: # execute loop when rcpy is ready\r\n if x == 0:\r\n print(\"motors.py: driving fwd\")\r\n # MotorL(0.6) # gentle speed for testing program. 0.3 PWM may not spin the wheels.\r\n # MotorR(0.6)\r\n MotorUp(-1)\r\n time.sleep(5) # run fwd for 4 seconds\r\n MotorUp(0)\r\n time.sleep(5)\r\n print(\"motors.py: driving reverse\")\r\n # MotorL(-0.6)\r\n # MotorR(-0.6)\r\n MotorUp(1)\r\n time.sleep(5) # run reverse for 4 seconds\r\n x = 1\r\n else:\r\n MotorUp(0)\r\n\r\n\r\ndef main():\r\n motor_r = 2 # Right Motor assigned to #2\r\n motor_l = 1 # Left Motor assigned to #1\r\n motor_up = 4 # Lift motor assigned to 4\r\n camera = cv2.VideoCapture(camera_input) # Define camera variable\r\n camera.set(3, size_w) # Set width of images that will be retrived from camera\r\n camera.set(4, size_h) # Set height of images that will be retrived from camera\r\n\r\n performFuncDist = 20 # close enough - Mimumum pixel size of object in order to perform function\r\n # targetSprayFar = 6 # Too Far - Minimum pixel size of object to track\r\n # targetSprayDist = 65 # Target Pixels - Target size of object to track\r\n # targetSprayClose = 70 # Too Close - Maximum pixel size of object to track\r\n targetLiftFar = 50 # Too Far - Minimum pixel size of object to track\r\n targetLiftDist = 130 # Target Pixels - Target size of object to track\r\n targetLiftClose = 170 # Too Close - Maximum pixel size of object to track\r\n\r\n band = 200 # range of x considered to be centered\r\n\r\n x = 0 # will describe target location left to right\r\n y = 0 # will describe target location bottom to top\r\n\r\n radius = 0 # estimates the radius of the detected target\r\n width = 0 # estimates the width of the detected target\r\n duty_l = 0 # initialize motor with zero duty cycle\r\n duty_r = 0 # initialize motor with zero duty cycle\r\n\r\n print(\"initializing rcpy...\")\r\n rcpy.set_state(rcpy.RUNNING) # initialize rcpy\r\n print(\"finished initializing rcpy.\")\r\n\r\n try:\r\n\r\n while rcpy.get_state() != rcpy.EXITING:\r\n\r\n if rcpy.get_state() == rcpy.RUNNING:\r\n cnts2 = 0\r\n scale_t = 0.8 # a scaling factor for speeds\r\n scale_d = 0.8 # a scaling factor for speeds\r\n\r\n motor_r = 2 # Right Motor assigned to #2\r\n motor_l = 1 # Left Motor assigned to #1\r\n motor_up = 4\r\n\r\n ret, image = camera.read() # Get image from camera\r\n\r\n height, width, channels = image.shape # Get size of image\r\n\r\n if not ret:\r\n break\r\n\r\n if filter == 'RGB': # If image mode is RGB switch to RGB mode\r\n frame_to_thresh = image.copy()\r\n else:\r\n frame_to_thresh = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # Otherwise continue reading in HSV\r\n # thresh\r\n # spray = cv2.inRange(frame_to_thresh, (spray1_min, spray2_min, spray3_min), (spray1_max, spray2_max, spray3_max)) # Find all pixels in color range\r\n lift = cv2.inRange(frame_to_thresh, (lift1_min, lift2_min, lift3_min),\r\n (lift1_max, lift2_max, lift3_max)) # Find all pixels in color range\r\n\r\n kernel = np.ones((5, 5), np.uint8) # Set gaussian blur strength.\r\n # mask1 = cv2.morphologyEx(spray, cv2.MORPH_OPEN, kernel) # Apply gaussian blur\r\n # mask1 = cv2.morphologyEx(mask1, cv2.MORPH_CLOSE, kernel)\r\n\r\n mask2 = cv2.morphologyEx(lift, cv2.MORPH_OPEN, kernel) # Apply gaussian blur\r\n mask2 = cv2.morphologyEx(mask2, cv2.MORPH_CLOSE, kernel)\r\n\r\n # cnts1 = cv2.findContours(mask1.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2] # Find closed shapes in image\r\n cnts2 = cv2.findContours(mask2.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[\r\n -2] # Find closed shapes in image\r\n center = None # Create variable to store point\r\n\r\n # For lifting functionality\r\n\r\n if len(cnts2) > 0: # If more than 0 closed shapes exist\r\n\r\n c = max(cnts2, key=cv2.contourArea) # Get the properties of the largest rectangle\r\n x, y, w, h = cv2.boundingRect(c) # Get properties of rectangle shape\r\n cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)\r\n rect = cv2.minAreaRect(c)\r\n box = cv2.boxPoints(rect)\r\n box = np.int0(box)\r\n cv2.drawContours(image, [box], 0, (0, 0, 255))\r\n w = round(w, 2) # Round width value to 2 decimals\r\n\r\n x = int(x) # Cast x value to an integer\r\n M = cv2.moments(c) # Gets area of circle contour\r\n center = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"])) # Get center x,y value of circle\r\n elif len(cnts2) == 1:\r\n x, y, w, h = cv2.boundingRect(cnts2) # Get properties of rectangle shape\r\n cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)\r\n rect = cv2.minAreaRect(c)\r\n box = cv2.boxPoints(rect)\r\n box = np.int0(box)\r\n cv2.drawContours(image, [box], 0, (0, 0, 255))\r\n w = round(w, 2) # Round width value to 2 decimals\r\n\r\n x = int(x) # Cast x value to an integer\r\n M = cv2.moments(c) # Gets area of circle contour\r\n center = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"])) # Get center x,y value of circle\r\n\r\n if len(\r\n cnts2) > 0: # perform spray function; the width pixel is within the target pixel range go perform task\r\n case = \"close enough\"\r\n dir = \"driving\"\r\n if x > ((width / 2) - (band / 2)) and x < ((width / 2) + (\r\n band / 2)): # If center point is centered;move to set distant based on pixel closeness\r\n\r\n if w >= targetLiftDist: # Too Close\r\n case = \"too close\"\r\n duty = -1 * ((w - targetLiftDist) / (targetLiftClose - targetLiftDist))\r\n if duty_l < 0.05 and duty_l > -0.05:\r\n case = \"lifting\"\r\n X = 0\r\n if X == 0:\r\n print(\"motors.py: driving fwd\")\r\n motor.set(motor_l, 0)\r\n motor.set(motor_r, 0)\r\n motor.set(motor_up, -1)\r\n time.sleep(5) # run fwd for 4 seconds\r\n motor.set(motor_up, 0)\r\n time.sleep(5)\r\n print(\"motors.py: driving reverse\")\r\n motor.set(motor_up, 1)\r\n time.sleep(5) # run reverse for 4 seconds\r\n X = 1\r\n else:\r\n motor.set(motor_up, 0)\r\n elif w < targetLiftDist: # Too Far\r\n case = \"too far from target\"\r\n\r\n duty = 1 - ((w - targetLiftFar) / (targetLiftDist - targetLiftFar))\r\n duty = scale_d * duty\r\n\r\n duty_r = duty\r\n duty_l = duty\r\n\r\n else:\r\n case = \"turning\" # center on the object\r\n duty_l = round((x - 0.5 * width) / (0.5 * width), 2) # Duty Left\r\n duty_l = duty_l * scale_t\r\n\r\n duty_r = round((0.5 * width - x) / (0.5 * width), 2) # Duty Right\r\n duty_r = duty_r * scale_t\r\n\r\n # Keep duty cycle within range\r\n\r\n if duty_r > 1:\r\n duty_r = 1\r\n\r\n elif duty_r < -1:\r\n duty_r = -1\r\n\r\n if duty_l > 1:\r\n duty_l = 1\r\n\r\n elif duty_l < -1:\r\n duty_l = -1\r\n\r\n # Round duty cycles\r\n duty_l = round(duty_l, 2)\r\n duty_r = round(duty_r, 2)\r\n\r\n # print(case, \"\\tradius: \", round(w,1), \"\\tx: \", round(x,0), \"\\t\\tL: \", duty_l, \"\\tR: \", duty_r)\r\n\r\n # Set motor duty cycles\r\n motor.set(motor_l, duty_l)\r\n motor.set(motor_r, duty_r)\r\n\r\n # return to main\r\n\r\n\r\n else: # to far away; keep patrolling (ryans's code here)\r\n print(\"patrolling\")\r\n blocker = 0\r\n initial = vec.getValid()\r\n print(initial)\r\n for Vec in initial:\r\n print(Vec)\r\n dist = Vec[0]\r\n angle = Vec[1]\r\n if dist <= 0.5 and dist > 0.005:\r\n blocker = blocker + 1\r\n print(blocker)\r\n if blocker > 10: # wall, turn around\r\n print(\"wall\") # something in the way, stop and wait\r\n duty = 0.6\r\n duty_r = duty\r\n duty_l = -duty\r\n motor.set(motor_l, duty_l)\r\n motor.set(motor_r, duty_r)\r\n time.sleep(3)\r\n elif blocker < 10 and blocker > 3: # person wait\r\n print(\"person\") # something in the way, stop and wait\r\n duty = 0.0\r\n else:\r\n print(\"True\") # nothing in front, move forward\r\n duty = 0.8\r\n\r\n duty_r = duty\r\n duty_l = duty\r\n motor.set(motor_l, duty_l)\r\n motor.set(motor_r, duty_r)\r\n if len(cnts2) > 0: # If more than 0 closed shapes exist\r\n print(case, \"\\tradius: \", round(w, 1), \"\\tx: \", round(x, 0), \"\\t\\tL: \", duty_l, \"\\tR: \", duty_r)\r\n # Set motor duty cycles\r\n motor.set(motor_l, duty_l)\r\n motor.set(motor_r, duty_r)\r\n\r\n elif rcpy.get_state() == rcpy.PAUSED:\r\n pass\r\n\r\n except KeyboardInterrupt: # condition added to catch a \"Ctrl-C\" event and exit cleanly\r\n rcpy.set_state(rcpy.EXITING)\r\n pass\r\n\r\n finally:\r\n\r\n rcpy.set_state(rcpy.EXITING)\r\n print(\"Exiting Color Tracking.\")\r\n\r\n\r\n# exiting program will automatically clean up cape\r\n\r\nif __name__ == '__main__':\r\n main()\r\n", "repo_name": "rlaba1/Scuttle-robot-waiter-", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 13945, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "rcpy.motor.set", "line_number": 55, "usage_type": "call"}, {"api_name": "rcpy.motor", "line_number": 55, "usage_type": "name"}, {"api_name": "L2_vector.getValid", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 72, "usage_type": "call"}, {"api_name": "L2_inverse_kinematics.convert", "line_number": 73, "usage_type": "call"}, {"api_name": "L2_speed_control.driveOpenLoop", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 77, "usage_type": "call"}, {"api_name": "L2_inverse_kinematics.convert", "line_number": 78, "usage_type": "call"}, {"api_name": "L2_speed_control.driveOpenLoop", "line_number": 79, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 80, "usage_type": "call"}, {"api_name": "rcpy.get_state", "line_number": 87, "usage_type": "call"}, {"api_name": "rcpy.EXITING", "line_number": 87, "usage_type": "attribute"}, {"api_name": "rcpy.get_state", "line_number": 88, "usage_type": "call"}, {"api_name": "rcpy.RUNNING", "line_number": 88, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 94, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 96, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 101, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 111, "usage_type": "call"}, {"api_name": "rcpy.set_state", "line_number": 134, "usage_type": "call"}, {"api_name": "rcpy.RUNNING", "line_number": 134, "usage_type": "attribute"}, {"api_name": "rcpy.get_state", "line_number": 139, "usage_type": "call"}, {"api_name": "rcpy.EXITING", "line_number": 139, "usage_type": "attribute"}, {"api_name": "rcpy.get_state", "line_number": 141, "usage_type": "call"}, {"api_name": "rcpy.RUNNING", "line_number": 141, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 160, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2HSV", "line_number": 160, "usage_type": "attribute"}, {"api_name": "cv2.inRange", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 166, "usage_type": "attribute"}, {"api_name": "cv2.morphologyEx", "line_number": 170, "usage_type": "call"}, {"api_name": "cv2.MORPH_OPEN", "line_number": 170, "usage_type": "attribute"}, {"api_name": "cv2.morphologyEx", "line_number": 171, "usage_type": "call"}, {"api_name": "cv2.MORPH_CLOSE", "line_number": 171, "usage_type": "attribute"}, {"api_name": "cv2.findContours", "line_number": 174, "usage_type": "call"}, {"api_name": "cv2.RETR_EXTERNAL", "line_number": 174, "usage_type": "attribute"}, {"api_name": "cv2.CHAIN_APPROX_SIMPLE", "line_number": 174, "usage_type": "attribute"}, {"api_name": "cv2.contourArea", "line_number": 182, "usage_type": "attribute"}, {"api_name": "cv2.boundingRect", "line_number": 183, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 184, "usage_type": "call"}, {"api_name": "cv2.minAreaRect", "line_number": 185, "usage_type": "call"}, {"api_name": "cv2.boxPoints", "line_number": 186, "usage_type": "call"}, {"api_name": "numpy.int0", "line_number": 187, "usage_type": "call"}, {"api_name": "cv2.drawContours", "line_number": 188, "usage_type": "call"}, {"api_name": "cv2.moments", "line_number": 192, "usage_type": "call"}, {"api_name": "cv2.boundingRect", "line_number": 195, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 196, "usage_type": "call"}, {"api_name": "cv2.minAreaRect", "line_number": 197, "usage_type": "call"}, {"api_name": "cv2.boxPoints", "line_number": 198, "usage_type": "call"}, {"api_name": "numpy.int0", "line_number": 199, "usage_type": "call"}, {"api_name": "cv2.drawContours", "line_number": 200, "usage_type": "call"}, {"api_name": "cv2.moments", "line_number": 204, "usage_type": "call"}, {"api_name": "rcpy.motor.set", "line_number": 222, "usage_type": "call"}, {"api_name": "rcpy.motor", "line_number": 222, "usage_type": "name"}, {"api_name": "rcpy.motor.set", "line_number": 223, "usage_type": "call"}, {"api_name": "rcpy.motor", "line_number": 223, "usage_type": "name"}, {"api_name": "rcpy.motor.set", "line_number": 224, "usage_type": "call"}, {"api_name": "rcpy.motor", "line_number": 224, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 225, "usage_type": "call"}, {"api_name": "rcpy.motor.set", "line_number": 226, "usage_type": "call"}, {"api_name": "rcpy.motor", "line_number": 226, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 227, "usage_type": "call"}, {"api_name": "rcpy.motor.set", "line_number": 229, "usage_type": "call"}, {"api_name": "rcpy.motor", "line_number": 229, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 230, "usage_type": "call"}, {"api_name": "rcpy.motor.set", "line_number": 233, "usage_type": "call"}, {"api_name": "rcpy.motor", "line_number": 233, "usage_type": "name"}, {"api_name": "rcpy.motor.set", "line_number": 272, "usage_type": "call"}, {"api_name": "rcpy.motor", "line_number": 272, "usage_type": "name"}, {"api_name": "rcpy.motor.set", "line_number": 273, "usage_type": "call"}, {"api_name": "rcpy.motor", "line_number": 273, "usage_type": "name"}, {"api_name": "L2_vector.getValid", "line_number": 281, "usage_type": "call"}, {"api_name": "rcpy.motor.set", "line_number": 295, "usage_type": "call"}, {"api_name": "rcpy.motor", "line_number": 295, "usage_type": "name"}, {"api_name": "rcpy.motor.set", "line_number": 296, "usage_type": "call"}, {"api_name": "rcpy.motor", "line_number": 296, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 297, "usage_type": "call"}, {"api_name": "rcpy.motor.set", "line_number": 307, "usage_type": "call"}, {"api_name": "rcpy.motor", "line_number": 307, "usage_type": "name"}, {"api_name": "rcpy.motor.set", "line_number": 308, "usage_type": "call"}, {"api_name": "rcpy.motor", "line_number": 308, "usage_type": "name"}, {"api_name": "rcpy.motor.set", "line_number": 312, "usage_type": "call"}, {"api_name": "rcpy.motor", "line_number": 312, "usage_type": "name"}, {"api_name": "rcpy.motor.set", "line_number": 313, "usage_type": "call"}, {"api_name": "rcpy.motor", "line_number": 313, "usage_type": "name"}, {"api_name": "rcpy.get_state", "line_number": 315, "usage_type": "call"}, {"api_name": "rcpy.PAUSED", "line_number": 315, "usage_type": "attribute"}, {"api_name": "rcpy.set_state", "line_number": 319, "usage_type": "call"}, {"api_name": "rcpy.EXITING", "line_number": 319, "usage_type": "attribute"}, {"api_name": "rcpy.set_state", "line_number": 324, "usage_type": "call"}, {"api_name": "rcpy.EXITING", "line_number": 324, "usage_type": "attribute"}]} +{"seq_id": "8611279477", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# The dataset we'll use describes Euro daily exchange rates between 1999 and 2021. The euro (symbolized with €) is the official currency in most of the countries of the European Union.\n# \n# If the exchange rate of the euro to the US dollar is 1.5, you get 1.5 US dollars if you pay 1.0 euro (one euro has more value than one US dollar at this exchange rate).\n# \n# Daria Chemkaeva put together the data set and made it available on Kaggle — the data source is the European Central Bank. Note that the dataset gets regular updates — we downloaded it on January 2021.\n\n# In[1]:\n\n\nimport pandas as pd\nexchange_rates = pd.read_csv('euro-daily-hist_1999_2020.csv')\npd.set_option('display.max_columns', None)\n\nprint (exchange_rates.head())\n\nexchange_rates.info()\n\nexchange_rates.tail()\n\n\n# In[2]:\n\n\nexchange_rates.rename(columns={'[US dollar ]': 'US_dollar','[UK pound sterling ]':'GBP','[Swiss franc ]':'CHF','[Mexican peso ]':'MXN', \n 'Period\\\\Unit:': 'Time'},\n inplace=True)\nexchange_rates['Time'] = pd.to_datetime(exchange_rates['Time'])\nexchange_rates.sort_values('Time', inplace=True)\nexchange_rates.reset_index(drop=True, inplace=True)\n\n\n# In[3]:\n\n\neuro_to_dollar = exchange_rates[[\"Time\", \"US_dollar\"]]\neuro_to_dollar.info()\n\n\n# In[4]:\n\n\neuro_to_dollar[\"US_dollar\"].value_counts()\n\n\n# In[5]:\n\n\neuro_to_dollar = euro_to_dollar.loc[euro_to_dollar[\"US_dollar\"] != '-']\neuro_to_dollar[\"US_dollar\"].value_counts()\n\n\n# In[6]:\n\n\neuro_to_dollar[\"US_dollar\"] = euro_to_dollar[\"US_dollar\"].astype(float)\neuro_to_dollar.info()\n\n\n# In[7]:\n\n\neuro_to_dollar['rolling_mean'] = euro_to_dollar[\"US_dollar\"].rolling(30).mean()\neuro_to_dollar.head()\n\n\n# In[8]:\n\n\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n#Enables Jupyter to display graphs\n\nplt.plot(euro_to_dollar['Time'],\n euro_to_dollar['rolling_mean'])\nplt.show()\n\n\n# We show comparatively how the euro-dollar rate changed before the 2008 crisis, and then how it behaved in 2008 when the crisis became worldwide, and then in 2009 when the crisis started to solve. We can use a line plot.\n\n# In[9]:\n\n\n### Defining time periods\ntoda_crisis = euro_to_dollar.copy(\n )[(euro_to_dollar['Time'].dt.year >= 2006) & (euro_to_dollar['Time'].dt.year < 2010)]\npre_crisis = toda_crisis.copy(\n )[toda_crisis['Time'].dt.year < 2008]\ncrisis = toda_crisis.copy(\n )[(toda_crisis['Time'].dt.year == 2008)]\npost_crisis = toda_crisis.copy(\n )[(toda_crisis['Time'].dt.year > 2008)]\n\n\nprint(pre_crisis.describe())\nprint(crisis.describe())\nprint(post_crisis.describe())\n\n\n# In[ ]:\n\n\n\n\n\n# In[10]:\n\n\neuro_to_pound = exchange_rates[[\"Time\", \"GBP\"]]\neuro_to_pound.info()\n\n\n# In[11]:\n\n\neuro_to_pound[\"GBP\"].value_counts()\n\n\n# In[12]:\n\n\neuro_to_pound = euro_to_pound.loc[euro_to_pound[\"GBP\"] != '-']\neuro_to_pound[\"GBP\"].value_counts()\n\n\n# In[13]:\n\n\neuro_to_pound['rolling_mean'] = euro_to_pound[\"GBP\"].rolling(30).mean()\neuro_to_pound.head()\n\n\n# In[14]:\n\n\nplt.plot(euro_to_pound['Time'],\n euro_to_pound['rolling_mean'])\nplt.show()\n\n\n# In[15]:\n\n\n### Defining time periods for pound vs euro\ntoda_crisisgbp = euro_to_pound.copy(\n )[(euro_to_pound['Time'].dt.year >= 2006) & (euro_to_pound['Time'].dt.year < 2010)]\npre_crisisgbp = toda_crisisgbp.copy(\n )[toda_crisisgbp['Time'].dt.year < 2008]\ncrisisgbp = toda_crisisgbp.copy(\n )[(toda_crisisgbp['Time'].dt.year == 2008)]\npost_crisisgbp = toda_crisisgbp.copy(\n )[(toda_crisisgbp['Time'].dt.year > 2008)& (toda_crisisgbp['Time'].dt.year < 2010) ]\n\n\nprint(pre_crisisgbp.describe())\nprint(crisisgbp.describe())\nprint(post_crisisgbp.describe())\n\n\n# In[ ]:\n\n\n\n\n\n# In[16]:\n\n\neuro_to_chf = exchange_rates[[\"Time\", \"CHF\"]]\neuro_to_chf.info()\n\n\n# In[17]:\n\n\neuro_to_chf[\"CHF\"].value_counts()\n\n\n# In[18]:\n\n\neuro_to_chf= euro_to_chf.loc[euro_to_chf[\"CHF\"] != '-']\neuro_to_chf[\"CHF\"].value_counts()\n\n\n# In[19]:\n\n\neuro_to_chf['rolling_mean'] = euro_to_chf[\"CHF\"].rolling(30).mean()\neuro_to_chf.head()\n\n\n# In[20]:\n\n\nplt.plot(euro_to_chf['Time'],\n euro_to_chf['rolling_mean'])\nplt.show()\n\n\n# In[21]:\n\n\n### Defining time periods for pound vs euro\ntoda_crisischf = euro_to_chf.copy(\n )[(euro_to_chf['Time'].dt.year >= 2006) & (euro_to_chf['Time'].dt.year < 2010)]\npre_crisischf = toda_crisischf.copy(\n )[toda_crisischf['Time'].dt.year < 2008]\ncrisischf = toda_crisischf.copy(\n )[(toda_crisischf['Time'].dt.year == 2008)]\npost_crisischf = toda_crisischf.copy(\n )[(toda_crisischf['Time'].dt.year > 2008)& (toda_crisischf['Time'].dt.year < 2010) ]\n\n\nprint(pre_crisischf.describe())\nprint(crisischf.describe())\nprint(post_crisischf.describe())\n\n\n# In[22]:\n\n\n\n### Adding the FiveThirtyEight style\nimport matplotlib.style as style\nstyle.use('fivethirtyeight')\n\n### Adding the subplots\nplt.figure(figsize=(12, 6))\nax1 = plt.subplot(2,3,1)\nax2 = plt.subplot(2,3,2)\nax3 = plt.subplot(2,3,3)\naxes = [ax1, ax2, ax3]\n\n### Changes to all the subplots\nfor ax in axes:\n ax.set_ylim(1.15, 1.65)\n ax.set_yticks([False])\n ax.grid(False)\n \n \n \n### Ax1: Pre-crisis\nax1.plot(pre_crisis['Time'], pre_crisis['rolling_mean'],\n color='#BF5FFF')\nax1.set_xticklabels([])\n#print(ax1.get_xticks())\n#print(ax1.get_yticks())\nax1.text(732463, 1.72, 'PRE- CRISIS', fontsize=18, weight='bold',\n color='#BF5FFF')\nax1.text(732453, 1.67, 'Mean 1.305298', weight='bold',\n alpha=0.3)\nax1.axhline(y=01.48, xmin=0.82, xmax=0.95, alpha=0.5, color ='grey',linestyle='dotted') \nax1.text(732793, 1.48, '1.47', weight= 'bold',\n alpha=0.8, color = '#BF5FFF')\nax1.axhline(y=01.17, xmin=0.1, xmax=0.25, alpha=0.5, color ='grey',linestyle='dotted') \nax1.text(732423, 1.17, '1.18', weight= 'bold',\n alpha=0.8, color = '#BF5FFF')\nax1.text(732493, 1.1, '2006-2007', weight= 'bold',\n alpha=0.8, color = 'grey')\n\n### Ax2: Crisis\nax2.plot(crisis['Time'], crisis['rolling_mean'],\n color='#ffa500')\nax2.set_xticklabels([])\n#print(ax2.get_xticks())\n#print(ax2.get_yticks())\nax2.text(733143, 1.72, 'CRISIS', fontsize=18, weight='bold',\n color='#ffa500')\nax2.text(733103, 1.67, 'Mean 1.476526', weight='bold',\n alpha=0.3)\nax2.axvspan(xmin=733153, xmax=733273, ymin=0, ymax=0.9,\n alpha=0.3, color='grey')\nax2.axhline(y=1.59, xmin=0.32, xmax=0.61, alpha=0.5, color ='grey',linestyle='dotted') \nax2.text(733183, 1.62, '1.58', weight= 'bold',\n alpha=0.8, color = '#ffa500')\nax2.axhline(y=1.26, xmin=0.85, xmax=0.95, alpha=0.5, color ='grey',linestyle='dotted') \nax2.text(733283, 1.25, '1.27', weight= 'bold',\n alpha=0.8, color = '#ffa500')\nax2.text(733173, 1.1, '2008', weight= 'bold',\n alpha=0.8, color = 'grey')\n\n### Ax3: Post-Crisis\nax3.plot(post_crisis['Time'], post_crisis['rolling_mean'],\n color='#00B2EE')\nax3.set_xticklabels([])\n#print(ax3.get_xticks())\n#print(ax3.get_yticks())\nax3.text(733497, 1.72, 'POST-CRISIS', fontsize=18, weight='bold',\n color='#00B2EE')\nax3.text(733497, 1.67, 'Mean 1.389154', weight='bold',\n alpha=0.3)\nax3.axhline(y=1.50, xmin=0.80, xmax=0.97, alpha=0.5, color ='grey',linestyle='dotted') \nax3.text(733657, 1.51, '1.49', weight= 'bold',\n alpha=0.8, color = '#00B2EE')\nax3.axhline(y=1.26, xmin=0.10, xmax=0.37, alpha=0.5, color ='grey',linestyle='dotted') \nax3.text(733547, 1.26, '1.27', weight= 'bold',\n alpha=0.8, color = '#00B2EE')\nax3.text(733577, 1.1, '2009', weight= 'bold',\n alpha=0.8, color = 'grey')\n\n\n### Adding a title and a subtitle\nax.text(732372, 1.95, 'EURO-USD rate behaved differently during crisis vs pre & post',\n fontsize=20, weight='bold')\nax.text(732372, 1.85, '''EURO-USD exchange rates Pre, During and Post 2008 crisis''',\n fontsize=16)\n\n### Adding a signature\nax.text(732372, 1, 'GM' + ' '*122 + 'Source: European Central Bank',\n color = '#f0f0f0', backgroundcolor = '#4d4d4d',\n size=14)\n\n\nplt.show()\n\n### Adding the subplots\nplt.figure(figsize=(12, 6))\nax1 = plt.subplot(2,3,1)\nax2 = plt.subplot(2,3,2)\nax3 = plt.subplot(2,3,3)\naxes = [ax1, ax2, ax3]\n\n### Changes to all the subplots\nfor ax in axes:\n ax.set_ylim(0.6, 1)\n ax.set_yticks([False])\n ax.grid(False)\n \n \n \n### Ax1: Pre-crisis\nax1.plot(pre_crisisgbp['Time'], pre_crisisgbp['rolling_mean'],\n color='#BF5FFF')\nax1.set_xticklabels([])\n#print(ax1.get_xticks())\n#print(ax1.get_yticks())\nax1.text(732463, 1.05, 'PRE- CRISIS', fontsize=18, weight='bold',\n color='#BF5FFF')\nax1.text(732453, 1, 'Mean 0.681875', weight='bold',\n alpha=0.3)\nax1.axhline(y=0.72, xmin=0.82, xmax=0.95, alpha=0.5, color ='grey',linestyle='dotted') \nax1.text(732793, 0.715, '0.72', weight= 'bold',\n alpha=0.8, color = '#BF5FFF')\nax1.axhline(y=0.65, xmin=0.40, xmax=0.55, alpha=0.5, color ='grey',linestyle='dotted') \nax1.text(732453, 0.63, '0.66', weight= 'bold',\n alpha=0.8, color = '#BF5FFF')\nax1.text(732493, 0.55, '2006-2007', weight= 'bold',\n alpha=0.8, color = 'grey')\n\n### Ax2: Crisis\nax2.plot(crisisgbp['Time'], crisisgbp['rolling_mean'],\n color='#ffa500')\nax2.set_xticklabels([])\n#print(ax2.get_xticks())\n#print(ax2.get_yticks())\nax2.text(733143, 1.05, 'CRISIS', fontsize=18, weight='bold',\n color='#ffa500')\nax2.text(733103, 1, 'Mean 0.785519', weight='bold',\n alpha=0.3)\nax2.axhline(y=0.89, xmin=0.85, xmax=0.95, alpha=0.5, color ='grey',linestyle='dotted') \nax2.text(733293, 0.885, '0.89', weight= 'bold',\n alpha=0.8, color = '#ffa500')\nax2.axhline(y=0.72, xmin=0.1, xmax=0.25, alpha=0.5, color ='grey',linestyle='dotted') \nax2.text(733133, 0.71, '0.72', weight= 'bold',\n alpha=0.8, color = '#ffa500')\nax2.text(733173, 0.55, '2008', weight= 'bold',\n alpha=0.8, color = 'grey')\n\n### Ax3: Post-Crisis\nax3.plot(post_crisisgbp['Time'], post_crisisgbp['rolling_mean'],\n color='#00B2EE')\nax3.set_xticklabels([])\n#print(ax3.get_xticks())\n#print(ax3.get_yticks())\nax3.text(733497, 1.05, 'POST-CRISIS', fontsize=18, weight='bold',\n color='#00B2EE')\nax3.text(733497, 1, 'Mean 0.891640', weight='bold',\n alpha=0.3)\nax3.axhline(y=0.93, xmin=0.1, xmax=0.25, alpha=0.5, color ='grey',linestyle='dotted') \nax3.text(733507, 0.925, '0.93', weight= 'bold',\n alpha=0.8, color = '#00B2EE')\nax3.axhline(y=0.86, xmin=0.3, xmax=0.55, alpha=0.5, color ='grey',linestyle='dotted') \nax3.text(733437, 0.86, '0.86', weight= 'bold',\n alpha=0.8, color = '#00B2EE')\nax3.text(733577, 0.58, '2009', weight= 'bold',\n alpha=0.8, color = 'grey')\n\n\n### Adding a title and a subtitle\nax.text(732372, 1.22, 'EURO-GBP rate behaved differently during crisis vs pre & post',\n fontsize=20, weight='bold')\nax.text(732372, 1.17, '''EURO-GBP exchange rates Pre, During and Post 2008 crisis''',\n fontsize=16)\n\n### Adding a signature\nax.text(732372, 0.45, 'GM' + ' '*122 + 'Source: European Central Bank',\n color = '#f0f0f0', backgroundcolor = '#4d4d4d',\n size=14)\n\n\nplt.show()\n\n\n### Adding the subplots\nplt.figure(figsize=(12, 6))\nax1 = plt.subplot(2,3,1)\nax2 = plt.subplot(2,3,2)\nax3 = plt.subplot(2,3,3)\naxes = [ax1, ax2, ax3]\n\n### Changes to all the subplots\nfor ax in axes:\n ax.set_ylim(1.3, 1.7)\n ax.set_yticks([False])\n ax.grid(False)\n\n### Ax1: Pre-crisis\nax1.plot(pre_crisischf['Time'], pre_crisischf['rolling_mean'],\n color='#BF5FFF')\nax1.set_xticklabels([])\n#print(ax1.get_xticks())\n#print(ax1.get_yticks())\nax1.text(732463, 1.8, 'PRE- CRISIS', fontsize=18, weight='bold',\n color='#BF5FFF')\nax1.text(732453, 1.75, 'Mean 1.604720', weight='bold',\n alpha=0.3)\nax1.axhline(y=1.545, xmin=0.1, xmax=0.25, alpha=0.5, color ='grey',linestyle='dotted') \nax1.text(732533, 1.535, '1.55', weight= 'bold',\n alpha=0.8, color = '#BF5FFF')\nax1.axhline(y=1.675, xmin=0.75, xmax=0.9, alpha=0.5, color ='grey',linestyle='dotted') \nax1.text(732753, 1.665, '1.67', weight= 'bold',\n alpha=0.8, color = '#BF5FFF')\nax1.text(732493, 1.4, '2006-2007', weight= 'bold',\n alpha=0.8, color = 'grey')\n\n### Ax2: Crisis\nax2.plot(crisischf['Time'], crisischf['rolling_mean'],\n color='#ffa500')\nax2.set_xticklabels([])\n#print(ax2.get_xticks())\n#print(ax2.get_yticks())\nax2.text(733143, 1.8, 'CRISIS', fontsize=18, weight='bold',\n color='#ffa500')\nax2.text(733103, 1.75, 'Mean 1.594302', weight='bold',\n alpha=0.3)\nax2.axhline(y=1.50, xmin=0.70, xmax=0.85, alpha=0.5, color ='grey',linestyle='dotted') \nax2.text(733223, 1.50, '1.50', weight= 'bold',\n alpha=0.8, color = '#ffa500')\nax2.axhline(y=1.661, xmin=0.05, xmax=0.2, alpha=0.5, color ='grey',linestyle='dotted') \nax2.text(733113, 1.655, '1.65', weight= 'bold',\n alpha=0.8, color = '#ffa500')\nax2.text(733173, 1.4, '2008', weight= 'bold',\n alpha=0.8, color = 'grey')\n\n### Ax3: Post-Crisis\nax3.plot(post_crisischf['Time'], post_crisischf['rolling_mean'],\n color='#00B2EE')\nax3.set_xticklabels([])\n#print(ax3.get_xticks())\n#print(ax3.get_yticks())\nax3.text(733497, 1.8, 'POST-CRISIS', fontsize=18, weight='bold',\n color='#00B2EE')\nax3.text(733497, 1.75, 'Mean 1.512066', weight='bold',\n alpha=0.3)\nax3.axhline(y=1.481, xmin=0.2, xmax=0.35, alpha=0.5, color ='grey',linestyle='dotted') \nax3.text(733557, 1.475, '1.48', weight= 'bold',\n alpha=0.8, color = '#00B2EE')\nax3.axhline(y=1.54, xmin=0.05, xmax=0.2, alpha=0.5, color ='grey',linestyle='dotted') \nax3.text(733477, 1.54, '1.54', weight= 'bold',\n alpha=0.8, color = '#00B2EE')\nax3.text(733577, 1.4, '2009', weight= 'bold',\n alpha=0.8, color = 'grey')\n\n\n### Adding a title and a subtitle\nax.text(732372, 1.95, 'EURO-CHF rate behaved differently during crisis vs pre & post',\n fontsize=20, weight='bold')\nax.text(732372, 1.9, '''EURO-CHF exchange rates Pre, During and Post 2008 crisis''',\n fontsize=16)\n\n### Adding a signature\nax.text(732372, 1.3, 'GM' + ' '*122 + 'Source: European Central Bank',\n color = '#f0f0f0', backgroundcolor = '#4d4d4d',\n size=14)\n\n\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n", "repo_name": "gmen68/gmen68", "sub_path": "Storytelling Data Visualization on Exchange Rates.py", "file_name": "Storytelling Data Visualization on Exchange Rates.py", "file_ext": "py", "file_size_in_byte": 14089, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pandas.read_csv", "line_number": 14, "usage_type": "call"}, {"api_name": "pandas.set_option", "line_number": 15, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 78, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 138, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 138, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 140, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 140, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 198, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 198, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 200, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 200, "usage_type": "name"}, {"api_name": "matplotlib.style.use", "line_number": 228, "usage_type": "call"}, {"api_name": "matplotlib.style", "line_number": 228, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 231, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 231, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 232, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 232, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 233, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 233, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 234, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 234, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 317, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 317, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 320, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 320, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 321, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 321, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 322, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 322, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 323, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 323, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 404, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 404, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 408, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 408, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 409, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 409, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 410, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 410, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 411, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 411, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 490, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 490, "usage_type": "name"}]} +{"seq_id": "8166385914", "text": "import pandas as pd\nimport os\nfrom rest_framework.response import Response\n\ndef error_simplification(error):\n file_path = 'C:/Users/Administrator/Documents/IntelCusEng/IntelCusEngProj/IntelCusApp/dataset.csv'\n # Use Pandas to read the Excel file\n df = pd.read_csv(file_path, encoding=\"cp1252\")\n # Process the data as needed\n # print(df) \n # Perform data comparison by iterating through the Excel file\n # for num in df.Response:\n matching_rows = df[df['Response'] == error]\n\n result = matching_rows['Preferred Interpretation'].values\n\n if len(result)>0:\n print(result[0])\n return Response(result[0])\n else:\n print(\"No match found for this error message!.\")\n return Response(\"No match found for this error message!.\")\n # if num == error:\n # print(num)\n\n \n # print(df.Response)\n # return Response(num)\n\n # matches = [],\n\n # for index, row in df.columns(row['Response Code'] == error):\n # print(row)\n # if row['Response Code'] == error:\n # matches.append(row)\n # return Response(row['Preferred Interpretation'])\n # else:\n # return Response(row['Preferred Interpretation'])\n \n\n # For testing purposes, you can convert the DataFrame to HTML and render it in a Django template\n # html_table = df.to_html()\n\n # return render(request, 'excel_data.html', {'html_table': html_table})\n # return Response(row['Preferred Interpretation'])\n # return Response(df) \n # else:\n # return Response(\"File path doesn't exist\")", "repo_name": "O-GDev/IntelCusEng", "sub_path": "IntelCusEngProj/IntelCusApp/simplifyerror.py", "file_name": "simplifyerror.py", "file_ext": "py", "file_size_in_byte": 1626, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pandas.read_csv", "line_number": 8, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 19, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 22, "usage_type": "call"}]} +{"seq_id": "18959273789", "text": "import evadb\nimport psycopg2\nimport pandas as pd\n\nparams = {\n \"user\": \"eva\",\n \"password\": \"2021\",\n \"host\": \"localhost\",\n \"port\": \"5432\",\n \"database\": \"postgres_data\"\n}\n\n# Load the CSV data into a Pandas DataFrame\ndf = pd.read_csv('content/btc_usd.csv')\n\n\n# Connect to PostgreSQL\nconnection = psycopg2.connect(**params)\ncursor = connection.cursor()\n\n# Create BTC_USD table if not exists\ncursor.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS BTC_USD(\n Currency VARCHAR(64), \n Date DATE, \n Closing FLOAT, \n Open FLOAT, \n High FLOAT, \n Low FLOAT\n )\n\"\"\")\n\n# Insert data from the DataFrame into the BTC_USD table\nfor index, row in df.iterrows():\n cursor.execute(\"INSERT INTO BTC_USD (Currency, Date, Closing, Open, High, Low) VALUES (%s, %s, %s, %s, %s, %s)\", \n (row['Currency'], row['Date'], row['Closing'], row['Open'], row['High'], row['Low']))\n\nconnection.commit()\ncursor.close()\nconnection.close()\n", "repo_name": "yunlingTao/Evadb_bitcoinpred", "sub_path": "newrandomfile.py", "file_name": "newrandomfile.py", "file_ext": "py", "file_size_in_byte": 962, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pandas.read_csv", "line_number": 14, "usage_type": "call"}, {"api_name": "psycopg2.connect", "line_number": 18, "usage_type": "call"}]} +{"seq_id": "14943047364", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Aug 1 19:47:04 2021\r\n\r\n@author: Admin\r\n\"\"\"\r\n\r\n# Regresión lineal múltiple \r\n\r\n# =============================================================================\r\n# Libraries\r\n# =============================================================================\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n#import matplotlib.pyplot as plt\r\nimport sklearn.preprocessing as sklp\r\nimport sklearn.model_selection as sklm\r\nimport sklearn.compose as sklc\r\nimport sklearn.linear_model as skllm\r\nimport statsmodels.api as sm\r\n\r\n# =============================================================================\r\n# Read data \r\n# =============================================================================\r\n\r\nstartup = pd.read_csv(\"data\\Startups.csv\")\r\n\r\nx = startup.iloc[:, :-1].values\r\ny = startup.iloc[:, 4].values\r\n\r\n\r\n# =============================================================================\r\n# Datos categoricos: variables dummy\r\n# =============================================================================\r\n\r\nlabel_encoder_x = sklp.LabelEncoder()\r\nx[:, 3] = label_encoder_x.fit_transform(x[:, 3])\r\nonehotencoder = sklc.make_column_transformer((sklp.OneHotEncoder(), [3]), \r\n remainder = \"passthrough\")\r\nx = onehotencoder.fit_transform(x)\r\n\r\n# Se ordenan alfabéticamente, en este caso: California, Florida, New York\r\n# Hay que eliinar una dummy, solo se necesitan 2 **Colinealidad**\r\nx = x[:, 1:] # quitamos Carolina\r\n\r\n# =============================================================================\r\n# Datos entrenamiento y validacion \r\n# =============================================================================\r\n\r\nx_train, x_test, y_train, y_test = sklm.train_test_split(x, \r\n y, \r\n test_size = 0.2,\r\n random_state = 0)\r\n\r\n# =============================================================================\r\n# Ajustar modelos de regresión\r\n# =============================================================================\r\n\r\nregresion = skllm.LinearRegression()\r\nregresion.fit(x_train, y_train)\r\n\r\ny_pred = regresion.predict(x_test)\r\n\r\n# =============================================================================\r\n# Selección hacia atrás\r\n# =============================================================================\r\n\r\n## Agregar el intercepto\r\n\r\nx = np.append(arr = np.ones((50, 1)).astype(int), values = x, axis = 1)\r\n\r\n# variables independientes estadísticamente significativas\r\nx_opt = x[:, [0, 1, 2, 3, 4, 5]].tolist()\r\nregresion_OLS = sm.OLS(endog = y, exog = x_opt).fit()\r\nregresion_OLS.summary()\r\n\r\n## Quitamos ambas dummy (tiene que ser una a una)\r\nx_opt = x[:, [0, 3, 4, 5]].tolist()\r\nregresion_OLS = sm.OLS(endog = y, exog = x_opt).fit()\r\nregresion_OLS.summary()\r\n\r\n## Quitamos 4 (Administracion)\r\nx_opt = x[:, [0, 3, 5]].tolist()\r\nregresion_OLS = sm.OLS(endog = y, exog = x_opt).fit()\r\nregresion_OLS.summary()\r\n\r\n## Quitamos 5 (Marketing Spend)\r\nx_opt = x[:, [0, 3]].tolist()\r\nregresion_OLS = sm.OLS(endog = y, exog = x_opt).fit()\r\nregresion_OLS.summary()", "repo_name": "StevenGGoni/Machine_learning", "sub_path": "02. Regresion lineal multiple.py", "file_name": "02. Regresion lineal multiple.py", "file_ext": "py", "file_size_in_byte": 3228, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pandas.read_csv", "line_number": 27, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.LabelEncoder", "line_number": 37, "usage_type": "call"}, {"api_name": "sklearn.preprocessing", "line_number": 37, "usage_type": "name"}, {"api_name": "sklearn.compose.make_column_transformer", "line_number": 39, "usage_type": "call"}, {"api_name": "sklearn.compose", "line_number": 39, "usage_type": "name"}, {"api_name": "sklearn.preprocessing.OneHotEncoder", "line_number": 39, "usage_type": "call"}, {"api_name": "sklearn.preprocessing", "line_number": 39, "usage_type": "name"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 51, "usage_type": "call"}, {"api_name": "sklearn.model_selection", "line_number": 51, "usage_type": "name"}, {"api_name": "sklearn.linear_model.LinearRegression", "line_number": 60, "usage_type": "call"}, {"api_name": "sklearn.linear_model", "line_number": 60, "usage_type": "name"}, {"api_name": "numpy.append", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 71, "usage_type": "call"}, {"api_name": "statsmodels.api.OLS", "line_number": 75, "usage_type": "call"}, {"api_name": "statsmodels.api", "line_number": 75, "usage_type": "name"}, {"api_name": "statsmodels.api.OLS", "line_number": 80, "usage_type": "call"}, {"api_name": "statsmodels.api", "line_number": 80, "usage_type": "name"}, {"api_name": "statsmodels.api.OLS", "line_number": 85, "usage_type": "call"}, {"api_name": "statsmodels.api", "line_number": 85, "usage_type": "name"}, {"api_name": "statsmodels.api.OLS", "line_number": 90, "usage_type": "call"}, {"api_name": "statsmodels.api", "line_number": 90, "usage_type": "name"}]} +{"seq_id": "41156387139", "text": "import tkinter as tk\r\nfrom PIL import Image\r\nimport cv2\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\n\r\nclass Interface(tk.Tk):\r\n def __init__(self, *args, **kwargs):\r\n tk.Tk.__init__(self, *args, **kwargs)\r\n self.title('Reconnaissance de chiffre')\r\n self.geometry('350x450')\r\n self.configure(bg='#EDD4EF')\r\n\r\n self.ecrire()\r\n self.commandes()\r\n\r\n\r\n def ecrire(self):\r\n frame_dessin = tk.Frame(self)\r\n frame_dessin.pack(pady=20)\r\n self.canvas = tk.Canvas(frame_dessin, width=300, height=300, bg='white')\r\n self.canvas.pack()\r\n self.canvas.bind( \"\", self.paint )\r\n\r\n\r\n def paint(self, event):\r\n x1, y1 = ( event.x - 1 ), ( event.y - 1 )\r\n x2, y2 = ( event.x + 1 ), ( event.y + 1 )\r\n self.canvas.create_oval( x1, y1, x2, y2, width=10) \r\n\r\n\r\n def commandes(self):\r\n frame_bouton = tk.Frame(self, bg='#EDD4EF')\r\n frame_bouton.pack()\r\n bouton_prediction = tk.Button(frame_bouton, text='Prédire', command=self.prediction)\r\n bouton_prediction.grid(row=0, column=0, padx=20)\r\n bouton_clean = tk.Button(frame_bouton, text='Nettoyer', command=self.clean)\r\n bouton_clean.grid(row=0, column=1, padx=20)\r\n self.label_prediction = tk.Label(frame_bouton, text='', bg='#EDD4EF')\r\n self.label_prediction.grid(row=1, columnspan=2)\r\n\r\n def prediction(self):\r\n self.canvas.postscript(file = f'number.eps')\r\n img = Image.open(f'number.eps')\r\n img.save(f'number' + '.png', 'png') \r\n image = cv2.imread(f'number.png', 0)\r\n image = cv2.resize(image, (28, 28))\r\n # cv2.imshow('Image', image) \r\n # cv2.waitKey(0)\r\n image = image.reshape(-1, 28, 28, 1)\r\n model = tf.keras.models.load_model('reco_chiffre')\r\n prediction = model.predict(image)\r\n prediction = np.argmax(prediction, axis=1)[0]\r\n self.label_prediction.configure(text=prediction, font=('Helvetica', 20))\r\n\r\n\r\n def clean(self):\r\n self.canvas.delete(\"all\")\r\n self.label_prediction.configure(text='')\r\n\r\n\r\napp = Interface()\r\napp.mainloop()", "repo_name": "PaulSabia/Classification-chiffre-manuscrit", "sub_path": "interface.py", "file_name": "interface.py", "file_ext": "py", "file_size_in_byte": 2182, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "tkinter.Tk", "line_number": 8, "usage_type": "attribute"}, {"api_name": "tkinter.Tk.__init__", "line_number": 10, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 10, "usage_type": "attribute"}, {"api_name": "tkinter.Frame", "line_number": 20, "usage_type": "call"}, {"api_name": "tkinter.Canvas", "line_number": 22, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 34, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 36, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 38, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 40, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 45, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 45, "usage_type": "name"}, {"api_name": "cv2.imread", "line_number": 47, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 48, "usage_type": "call"}, {"api_name": "tensorflow.keras.models.load_model", "line_number": 52, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 52, "usage_type": "attribute"}, {"api_name": "numpy.argmax", "line_number": 54, "usage_type": "call"}]} +{"seq_id": "23110914787", "text": "\nimport os\nimport caffe\nimport caffe_pb2\nfrom google.protobuf import text_format\n\nfrom op.input import input\nfrom op.convolution import convolution, saveConvolutionParam\nfrom op.deconvolution import deconvolution, saveDeconvolutionParam\nfrom op.relu import relu\nfrom op.pooling import pooling\nfrom op.concat import concat\nfrom op.softmax import softmax\nfrom op.eltwise import eltwise\nfrom op.lrn import lrn\nfrom op.innerproduct import innerproduct, saveInnerproductParam\nfrom op.scale import scale, saveScaleParam\nfrom op.activation import activation\nfrom op.reshape import reshape\nfrom op.tile import tile\n\n# openvino : caffe\nopenvino2caffe_layer_type_map = {\n \"Input\":\"Input\",\n #\"Input\":\"GlobalInput\",\n \"FullyConnected\":\"InnerProduct\",\n #\"Ignored..\":\"Dropout\",\n \"Convolution\":\"Convolution\",\n \"Deconvolution\":\"Deconvolution\",\n \"Pooling\":\"Pooling\",\n \"BatchNormalization\":\"BatchNorm\",\n \"Norm\":\"LRN\",\n \"Power\":\"Power\",\n \"ReLU\":\"ReLU\",\n \"ScaleShift\":\"Scale\",\n \"Concat\":\"Concat\",\n \"Eltwise\":\"Eltwise\",\n \"Flatten\":\"Flatten\",\n \"Reshape\":\"Reshape\",\n \"Slice\":\"Slice\",\n \"SoftMax\":\"Softmax\",\n \"Permute\":\"Permute\",\n \"ROIPooling\":\"ROIPooling\",\n #\"Reshape + Split + Permute + Concat\":\"ShuffleChannel\", #?\n #\"ScaleShift + Eltwise\":\"Axpy\", #?\n #\"ScaleShift\":\"BN\",\n \"DetectionOutput\":\"DetectionOutput\",\n \"StridedSlice\":\"StridedSlice\",\n #\"Eltwise\":\"Bias\", # operation=sum,\n}\n\ndef generateCaffe(openvino_model_info, output_model_name, output_dir):\n \n net_version_info, input_shape, layers_info, edges_info = openvino_model_info\n \n proto = caffe_pb2.NetParameter()\n \n proto.name = '-'.join([\n net_version_info['name'], \n \"openvino_model_optimizer_version:\"+ \n net_version_info['version']])\n \n temp_layers_info = {}\n for layer in layers_info:\n id = int(layer['id'])\n temp_layers_info[id] = layer\n \n for index, key in enumerate(temp_layers_info.keys()):\n \n cur_layers_info = temp_layers_info[key]\n \n proto.layer.add()\n \n cur_proto_layer = proto.layer[index]\n cur_proto_layer.name = cur_layers_info['name']\n \n openvino_type = cur_layers_info['type']\n caffe_type = openvino2caffe_layer_type_map[openvino_type] if openvino_type in openvino2caffe_layer_type_map else openvino_type\n \n cur_proto_layer.type = caffe_type\n \n #print(cur_proto_layer.type)\n \n if cur_proto_layer.type == 'Input':\n input(cur_proto_layer, input_shape)\n elif cur_proto_layer.type == 'Convolution':\n convolution(cur_proto_layer, temp_layers_info, edges_info)\n elif cur_proto_layer.type == 'ReLU':\n relu(cur_proto_layer, temp_layers_info, edges_info)\n elif cur_proto_layer.type == 'Pooling':\n pooling(cur_proto_layer, temp_layers_info, edges_info)\n elif cur_proto_layer.type == 'Concat':\n concat(cur_proto_layer, temp_layers_info, edges_info)\n elif cur_proto_layer.type == 'Softmax':\n softmax(cur_proto_layer, temp_layers_info, edges_info)\n elif cur_proto_layer.type == 'Eltwise':\n eltwise(cur_proto_layer, temp_layers_info, edges_info)\n elif cur_proto_layer.type == 'Deconvolution':\n deconvolution(cur_proto_layer, temp_layers_info, edges_info)\n elif cur_proto_layer.type == 'LRN':\n lrn(cur_proto_layer, temp_layers_info, edges_info)\n elif cur_proto_layer.type == 'InnerProduct':\n innerproduct(cur_proto_layer, temp_layers_info, edges_info)\n elif cur_proto_layer.type == 'Scale':\n scale(cur_proto_layer, temp_layers_info, edges_info)\n elif cur_proto_layer.type == 'Activation':\n activation(cur_proto_layer, temp_layers_info, edges_info)\n elif cur_proto_layer.type == 'Tile':\n tile(cur_proto_layer, temp_layers_info, edges_info)\n else:\n print(\"{} not support!\".format(cur_proto_layer.type))\n exit(0)\n \n #print(proto)\n #print(model)\n \n output_path = os.path.join(output_dir, output_model_name + \"-openvino\")\n output_proto_file = output_path + \".prototxt\"\n output_model_file = output_path + \".caffemodel\"\n \n with open(output_proto_file, \"w\") as file:\n file.write(text_format.MessageToString(proto))\n \n # model\n caffe.set_mode_cpu()\n output_net = caffe.Net(output_proto_file, caffe.TEST)\n output_params = output_net.params\n \n for index, key in enumerate(temp_layers_info.keys()):\n \n #print('-' * 80)\n \n cur_layers_info = temp_layers_info[key]\n \n cur_proto_layer = proto.layer[index]\n cur_proto_layer.name = cur_layers_info['name']\n \n openvino_type = cur_layers_info['type']\n caffe_type = openvino2caffe_layer_type_map[openvino_type] if openvino_type in openvino2caffe_layer_type_map else openvino_type\n \n cur_proto_layer.type = caffe_type\n \n #print(\"cur_proto_layer.name\", cur_proto_layer.name)\n #print(\"cur_proto_layer.type\", cur_proto_layer.type)\n \n if cur_proto_layer.type == 'Convolution':\n saveConvolutionParam(\n cur_proto_layer, \n temp_layers_info,\n output_params[cur_proto_layer.name])\n if cur_proto_layer.type == 'Deconvolution':\n saveDeconvolutionParam(\n cur_proto_layer, \n temp_layers_info,\n output_params[cur_proto_layer.name])\n elif cur_proto_layer.type == 'InnerProduct':\n saveInnerproductParam(\n cur_proto_layer, \n temp_layers_info,\n output_params[cur_proto_layer.name])\n elif cur_proto_layer.type == 'Scale':\n saveScaleParam(\n cur_proto_layer, \n temp_layers_info,\n output_params[cur_proto_layer.name])\n elif cur_proto_layer.type == 'BatchNorm':\n pass\n \n output_net.save(output_model_file)\n \n print(\"[FINISH] write to {}\".format(output_proto_file))\n print(\"[FINISH] write to {}\".format(output_model_file))\n \n return output_proto_file, output_model_file\n# end generateCaffe\n\ndef bn2caffe(running_mean, running_var, bn_param):\n bn_param[0].data[...] = running_mean.numpy()\n bn_param[1].data[...] = running_var.numpy()\n bn_param[2].data[...] = np.array([1.0])\n\n \n \n", "repo_name": "xiaoweiChen/OpenVINO_Model_Convert_Website", "sub_path": "utils/openvino2caffe/generate_caffe.py", "file_name": "generate_caffe.py", "file_ext": "py", "file_size_in_byte": 5948, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "caffe_pb2.NetParameter", "line_number": 56, "usage_type": "call"}, {"api_name": "op.input.input", "line_number": 85, "usage_type": "call"}, {"api_name": "op.convolution.convolution", "line_number": 87, "usage_type": "call"}, {"api_name": "op.relu.relu", "line_number": 89, "usage_type": "call"}, {"api_name": "op.pooling.pooling", "line_number": 91, "usage_type": "call"}, {"api_name": "op.concat.concat", "line_number": 93, "usage_type": "call"}, {"api_name": "op.softmax.softmax", "line_number": 95, "usage_type": "call"}, {"api_name": "op.eltwise.eltwise", "line_number": 97, "usage_type": "call"}, {"api_name": "op.deconvolution.deconvolution", "line_number": 99, "usage_type": "call"}, {"api_name": "op.lrn.lrn", "line_number": 101, "usage_type": "call"}, {"api_name": "op.innerproduct.innerproduct", "line_number": 103, "usage_type": "call"}, {"api_name": "op.scale.scale", "line_number": 105, "usage_type": "call"}, {"api_name": "op.activation.activation", "line_number": 107, "usage_type": "call"}, {"api_name": "op.tile.tile", "line_number": 109, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 117, "usage_type": "call"}, {"api_name": "os.path", "line_number": 117, "usage_type": "attribute"}, {"api_name": "google.protobuf.text_format.MessageToString", "line_number": 122, "usage_type": "call"}, {"api_name": "google.protobuf.text_format", "line_number": 122, "usage_type": "name"}, {"api_name": "caffe.set_mode_cpu", "line_number": 125, "usage_type": "call"}, {"api_name": "caffe.Net", "line_number": 126, "usage_type": "call"}, {"api_name": "caffe.TEST", "line_number": 126, "usage_type": "attribute"}, {"api_name": "op.convolution.saveConvolutionParam", "line_number": 147, "usage_type": "call"}, {"api_name": "op.deconvolution.saveDeconvolutionParam", "line_number": 152, "usage_type": "call"}, {"api_name": "op.innerproduct.saveInnerproductParam", "line_number": 157, "usage_type": "call"}, {"api_name": "op.scale.saveScaleParam", "line_number": 162, "usage_type": "call"}]} +{"seq_id": "19198947479", "text": "# coding=utf-8\nfrom sklearn.utils import resample\nimport numpy as np\n\n\ndef scalegirl(samples):\n count = 0.0\n total = samples.size\n for sex in samples:\n if (sex == 0):\n count += 1.0\n print(count)\n return count / (total - count)\n\n\nboy = (np.ones(1000))\ngirl = (np.zeros(800))\n\n# girl/boy=0.8\n\nprint(girl.shape)\nall = np.hstack((boy, girl))\nscale = 0.0\niter = 10000\nfor i in range(iter):\n bootstrapSamples = resample(all, n_samples=100, replace=1)\n print(bootstrapSamples)\n tempscale = scalegirl(bootstrapSamples)\n print(tempscale)\n scale += tempscale\nprint(scale / iter)\nprint(all)\n", "repo_name": "bird0554/pythonforGAN", "sub_path": "testbootstrp1.py", "file_name": "testbootstrp1.py", "file_ext": "py", "file_size_in_byte": 628, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.ones", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 22, "usage_type": "call"}, {"api_name": "sklearn.utils.resample", "line_number": 26, "usage_type": "call"}]} +{"seq_id": "6125993861", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 31 2018\n\nUseful functions for plotting using matplotlib and seaborn.\nSome functions from plotting_tools by Ami Tsuchida (atsuch@gmail.com)\n\n-plot_img_intensity_distribution: Image intensity histogram with mean, median, etc, for QC\n\n-QCtraceplot class: a class of traceplot object that can be used to generate linked traceplots\n -Initialized with;\n -out_dir: where plotted traces are saved as text files,\n -title (optional): title of the plot\n -figsize (optional): size of the combined plot (default:11x12)\n -Methods;\n -add_trace(): to add one or more traces for plotting\n -plot(): to plot all the traces added by add_trace()\n This code is largely based on MRIQC. When using, please cite the following:\n Esteban O, Birman D, Schaer M, Koyejo OO, Poldrack RA, Gorgolewski KJ; \n MRIQC: Advancing the Automatic Prediction of Image Quality in MRI from Unseen Sites; \n PLOS ONE 12(9):e0184661; doi:10.1371/journal.pone.0184661.\n\n@author: tsuchida\n\"\"\"\nimport os.path as op\nimport numpy as np\nimport matplotlib as mpl\nmpl.use('Agg')\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec as mgs\nimport seaborn as sns\nfrom seaborn import color_palette\nsns.set_style(\"whitegrid\")\nfrom textwrap import wrap\n\n\ndef get_lims(arr, delta=0.01):\n max_val = np.nanmax(arr)\n min_val = np.nanmin(arr)\n margin = np.absolute((max_val - min_val))* delta\n upper = max_val + margin\n lower = min_val - margin\n return (lower, upper)\n\n\ndef str_format_val(val, num_digits=3, signed=False):\n \"\"\"\n Function to return float or scientific format of the val.\n \n Returns float format if absolute(val) >= 0.1\n Returns scientifc format if absolute(val) < 0.1\n \"\"\"\n \n if np.absolute(val) >= 0.1:\n return '{1:+0.{0:d}f}'.format(num_digits, val) if signed else '{1:0.{0:d}f}'.format(num_digits, val)\n \n else:\n return '{1:+0.{0:d}e}'.format(num_digits, val) if signed else '{1:0.{0:d}e}'.format(num_digits, val)\n \n \ndef plot_img_intensity_distribution(img, mask, mask_label=None,\n color='royalblue', title=None,\n stats=['mean', 'median', 'min', 'max', '5p', '95p'],\n stats_style={'mean': {'line_style': ':',\n 'color': 'm',\n 'y_relpos': 0.8},\n 'median': {'line_style': '--',\n 'color': 'royalblue',\n 'y_relpos': 0.9},\n 'min': {'line_style': ':',\n 'color': 'slategray',\n 'y_relpos': 0.1},\n 'max': {'line_style': ':',\n 'color': 'slategray',\n 'y_relpos': 0.1},\n '5p': {'line_style': '--',\n 'color': 'royalblue',\n 'y_relpos': 0.2},\n '95p': {'line_style': '--',\n 'color': 'royalblue',\n 'y_relpos': 0.2}},\n out_plot=None,\n out_stats=None):\n \"\"\"\n Uses seaborn distplot to plot image intensity distribution within the mask.\n Along with the histogram and KDE plot, it will show image distribution stats\n that can be computed by summarize_img_intensity_distribution fxn. \n \n By default it will display the following values;\n -mean\n -median\n -min, max\n -5th and 95th percentile\n \n If out_stats is not None, it will save all available summary stats as a csv.\n \n \"\"\"\n import os\n import os.path as op\n import numpy as np\n import matplotlib.pyplot as plt\n import seaborn as sns\n from ginnipi_dwiqc.toolbox.image_utils import get_1d_dat, summarize_img_intensity_distribution\n sns.set_style(\"whitegrid\")\n\n masked_im_dat = get_1d_dat(img, mask=mask, mask_label=mask_label)\n\n cwd = os.getcwd()\n out_dir = op.abspath(cwd)\n if out_plot is None:\n out_plot = op.join(out_dir, 'img_intensity_distribution.png')\n else:\n out_plot = op.join(out_dir, out_plot)\n if out_stats is not None:\n out_stats = op.join(out_dir, out_stats)\n\n\n ## Plot \n ############################################\n # initialization\n title = title if title is not None else 'image intensity plot'\n\n fig, ax = plt.subplots(1, 1, figsize=(8, 6))\n sns.distplot(masked_im_dat, hist=True, kde=True, rug=False, color=color, ax=ax)\n ax.set_title(title)\n ax.set_xlabel(\"Image intensity\")\n ax.set_ylabel(\"Frequency\")\n ylim = ax.get_ylim()\n xlim = ax.get_xlim()\n\n # Get stat information of interest\n stat_summary = summarize_img_intensity_distribution(img,\n mask=mask,\n mask_label=mask_label,\n out=out_stats)\n if not np.nan in stat_summary.values():\n # Check if the automatic xlim exceeds 25p - 3IQR or 75p + 6IQR. If it does,\n # reset the xlim so that the histogram is not overly skewed.\n iqr = stat_summary['75p'] - stat_summary['25p']\n l_lim = stat_summary['25p'] - 6*iqr\n u_lim = stat_summary['75p'] + 6*iqr\n new_l_xlim = l_lim if xlim[0] < l_lim else xlim[0]\n new_u_xlim = u_lim if xlim[1] > u_lim else xlim[1]\n ax.set_xlim(new_l_xlim, new_u_xlim)\n\n # Annotation parameters\n bbox_style = 'round'\n bbox_linewidth = 0\n bbox_edgecolor = 'none'\n\n arrow_relativepos = (0.2, 0.5)\n\n # Add vline and annotation for each stat\n for stat in stats:\n # vline\n if stat_summary[stat] > new_l_xlim and stat_summary[stat] < new_u_xlim:\n ax.axvline(x=stat_summary[stat],\n linestyle=stats_style[stat]['line_style'],\n color=stats_style[stat]['color'], lw=1)\n\n # Annotation\n if stat_summary['median'] < 0.1 or iqr < 0.1 or stat_summary['median'] > 10 or iqr > 10:\n label = '{}={:.3e}'.format(stat, stat_summary[stat])\n else:\n label = '{}={:.3f}'.format(stat, stat_summary[stat])\n \n posy = ylim[0] + stats_style[stat]['y_relpos']*(ylim[1] - ylim[0])\n if stat_summary[stat] < new_l_xlim:\n posx = new_l_xlim\n xytext = (12, 0)\n arrow_style = 'wedge,tail_width=0'\n elif stat_summary[stat] > new_u_xlim:\n posx = new_u_xlim\n xytext = (-12, 0)\n arrow_style = 'wedge,tail_width=0'\n else:\n posx = stat_summary[stat]\n xytext = (12, 0)\n arrow_style = 'wedge,tail_width=1.'\n\n ax.annotate(label,\n xy=(posx, posy),\n xytext=xytext,\n textcoords='offset points',\n va='center',\n color='w',\n size=10,\n bbox=dict(boxstyle=bbox_style,\n fc=stats_style[stat]['color'],\n ec=bbox_edgecolor,\n lw=bbox_linewidth),\n arrowprops=dict(arrowstyle=arrow_style,\n lw=bbox_linewidth,\n patchA=None,\n patchB=None,\n fc=stats_style[stat]['color'],\n ec=bbox_edgecolor,\n relpos=arrow_relativepos))\n\n fig.savefig(out_plot)\n\n return out_plot, out_stats\n\n\nclass QCtraceplot(object):\n \"\"\"\n Generation of multiple linked traceplot\n \"\"\"\n\n def __init__(self, out_dir, title=None, figsize=(11, 12)):\n '''\n :param bval_per_frame: txt file containing intended bval for each frame\n :type bval_per_frame: str\n :param out_dir: output directory\n :type out_dir: str\n :param title: title of the summary plot\n :type title: str\n :param figsize: size of the output png\n :type figsize: tuple of float\n '''\n ## Set attributes\n ############################################\n\n # Working directory \n self.workingDir = out_dir\n\n ## Set plot\n ############################################\n # Figure size\n self.fig = plt.figure(figsize=figsize)\n\n # Font size\n mpl.rcParams['font.size'] = 7\n\n # Title\n if title is not None:\n self.fig.suptitle(title, fontsize=10)\n\n # Tab of traces that will be plotted\n # traceTab : one or more trace / plot\n\n self.traceTab = []\n self.plot_heightTab = []\n\n def add_trace(self, data, data_name, is_multi, kwargs):\n '''\n Add a trace to traceTab\n '''\n self.traceTab.append((data, kwargs))\n trace_height = 1 if is_multi else 0.3\n self.plot_heightTab.append(trace_height)\n out_dir = self.workingDir\n\n np.savetxt(op.join(out_dir, '{}.txt'.format(data_name)), data)\n\n def plot(self):\n ''' \n Plot traces that are in traceTab.\n \n trace : plot one or more trace in one plot \n '''\n\n # Length of the tab \n ntraceTab = len(self.traceTab)\n\n # Grid that organize the figure\n nrows = ntraceTab \n grid = mgs.GridSpec(nrows, 1, \n wspace=0.0, hspace=0.5,\n height_ratios = self.plot_heightTab) \n grid_id = 0\n\n # Plot trace ...\n for idx, (tseries, kwargs) in enumerate(self.traceTab):\n # plot\n self.traceplot(tseries, \n grid[grid_id], \n **kwargs) \n\n # update grid idx\n grid_id += 1\n\n setattr(self, 'grid', grid)\n\n def traceplot(self, tseries, gridpos, gs_dist=None, ylabel_name=None,\n trace_name=None, units=None, hide_x=True, pcolor=None,\n cutoff=None, cutoff_name=True, ylims=None,\n axvspan_d_list=None, annot_d_list=None):\n '''\n Plot one or more traces on a graph\n \n :param tseries: traces to plot\n :type tseries: list or ndarray \n :param gridpos: position of this subplot the plot grid \n :type gridpos: int\n :param gs_dist: \n :type gs_dist: \n :param name: name of the graph\n :type name: str\n :param normalize: \n :type normalize: boolean\n :param units: units of the tseries \n :type units: str\n :param hide_x: hide (or not) X axis on the subplot \n :type hide_x: boolean\n :param color: color of the trace\n :type color: color\n :param cutoff: cut-off value to plot\n :type cutoff: list of float \n :param cutoff_name: display cut-off value\n :type cutoff_name: boolean\n :param ylims: limits of the Y axis\n :type ylims: tuple of floats\n '''\n ## Variable initialization \n #############################################################################\n # Numpy array\n tseries = np.array(tseries)\n\n # reshape if tseries is one-dimensional\n if len(tseries.shape) == 1:\n tseries = tseries.reshape((-1, 1))\n\n (ntsteps, ntrace) = tseries.shape\n \n tseries_array = np.transpose(tseries)\n \n # Color palette\n if pcolor == None:\n pcolor = ['b'] * ntrace\n\n ## Plot\n #############################################################################\n # Define nested GridSpec\n gs = mgs.GridSpecFromSubplotSpec(1, 2, \n subplot_spec=gridpos,\n width_ratios=[1, 100], \n wspace=0.0)\n\n # Plot data \n ax_ts = plt.subplot(gs[1])\n for trace in range(ntrace):\n ax_ts.plot(tseries_array[trace], linewidth = 1, color=pcolor[trace])\n\n # Set subplot\n ax_ts.grid(False)\n for side in [\"top\", \"right\"]:\n ax_ts.spines[side].set_color('none')\n ax_ts.spines[side].set_visible(False)\n\n # Set X axis\n ax_ts.set_xlim((0, ntsteps - 1))\n if not hide_x:\n xtick_step = ntsteps / 5\n xticks = list(range(0, ntsteps)[::int(xtick_step)])\n ax_ts.set_xticks(xticks)\n ax_ts.set_xlabel('frame #')\n ax_ts.spines[\"bottom\"].set_position(('outward', 2))\n ax_ts.xaxis.set_ticks_position('bottom')\n else:\n ax_ts.set_xticklabels([])\n ax_ts.spines[\"bottom\"].set_color('none')\n ax_ts.spines[\"bottom\"].set_visible(False)\n\n # Set Y axis\n if ylabel_name is not None:\n var_label = ylabel_name\n if units is not None:\n var_label += (' [{}]').format(units)\n ax_ts.set_ylabel('\\n'.join(wrap(var_label, 15)))\n ax_ts.spines[\"left\"].set_position(('outward', 30))\n ax_ts.yaxis.set_ticks_position('left')\n def_ylims = [0.95 * tseries[~np.isnan(tseries)].min(),\n 1.1 * tseries[~np.isnan(tseries)].max()]\n if ylims is not None:\n if ylims[0] is not None:\n def_ylims[0] = ylims[0]\n if ylims[1] is not None:\n def_ylims[1] = ylims[1]\n ax_ts.set_ylim(def_ylims)\n yticks = sorted(def_ylims)\n ax_ts.set_yticks(yticks)\n ax_ts.set_yticklabels(['%.05f' % y for y in yticks])\n yrange = def_ylims[1] - def_ylims[0]\n\n # Add vspan if axvspan_d_list is provided\n if axvspan_d_list is not None:\n for axvspan_d in axvspan_d_list:\n ax_ts.axvspan(**axvspan_d)\n \n ## Annotate graph with cutoff and mean values\n #############################################################################\n # Annotation parameters\n fontsize = 7\n text_color = 'w'\n bbox_style = 'round'\n bbox_linewidth = 0\n bbox_edgecolor = 'none'\n arrow_style = 'wedge,tail_width=.9'\n arrow_linewidth = bbox_linewidth\n arrow_edgecolor = bbox_edgecolor\n\n # For each trace, add annoation and mean values\n ntrace_name = len(trace_name)\n if ntrace_name == ntrace:\n for trace in range(ntrace):\n # annotation\n xpos = trace*0.1\n label = trace_name[trace]\n position = (xpos, 1)\n text_offset = (xpos, 1)\n bbox_color = pcolor[trace]\n ax_ts.annotate(label, \n xy = position, \n xytext = text_offset, \n xycoords = 'axes fraction',\n textcoords = 'offset points', \n va = 'center', \n color = text_color,\n size = fontsize,\n bbox=dict(boxstyle = bbox_style,\n fc = bbox_color, \n ec = bbox_edgecolor,\n lw = bbox_linewidth))\n\n # mean value annotation and dotted line\n meanvalue = tseries_array[trace][~np.isnan(tseries_array)[trace]].mean() \n mean_label = r'$\\mu$=%.3f%s' % (meanvalue, units if units is not None else '')\n mean_position = (ntsteps - 1, meanvalue)\n mean_text_offset = (11, 0)\n ax_ts.annotate(mean_label, \n xy = mean_position, \n xytext = mean_text_offset,\n textcoords = 'offset points', \n va = 'center', \n color = text_color, \n size = fontsize,\n bbox=dict(boxstyle = bbox_style,\n fc = bbox_color, \n ec = bbox_edgecolor, \n lw = bbox_linewidth))\n # dotted line\n ax_ts.axhline(y=meanvalue,\n linewidth=.75,\n linestyle=':',\n color=bbox_color)\n \n \n else :\n print('Number of measure name : ' + str(ntrace_name) + ' is different from number of traces to plot : ' + str(ntrace))\n \n \n # Cutff values\n if cutoff is not None:\n for i, thr in enumerate(cutoff):\n \n # Plot as a dotted line\n x = (0, ntsteps - 1)\n y = [thr] * 2\n ax_ts.plot(x, y,\n linewidth = 1.,\n linestyle = '--',\n color = 'k')\n \n # Annotate the graph\n if cutoff_name : \n # Compute offset position (avoid conflict with other annotation boxes)\n y_off = [0.0, 0.0]\n for pth in cutoff[:i]:\n inc = abs(thr - pth)\n if inc < yrange:\n factor = (- (inc / yrange) + 1) ** 2\n if (thr - pth) < 0.0:\n y_off[0] -= factor * 20\n else:\n y_off[1] += factor * 20\n offset = y_off[0] if abs(y_off[0]) > y_off[1] else y_off[1]\n\n # Annotation parameters\n label = '{:.5f}{}'.format(thr, units if units is not None else '')\n position = (ntsteps - 1, thr)\n text_offset = (11, offset)\n bbox_color = 'dimgray'\n arrow_color = bbox_color\n arrow_relativepos = (.1, .5)\n\n # Annotate\n ax_ts.annotate(label, \n xy = position, \n xytext = text_offset,\n textcoords = 'offset points', \n va = 'center',\n color = text_color, \n size = fontsize,\n bbox=dict(boxstyle = bbox_style, \n fc = bbox_color, \n ec = bbox_edgecolor, \n lw = bbox_linewidth),\n arrowprops=dict(arrowstyle = arrow_style, \n lw = arrow_linewidth, \n patchA = None, \n patchB = None,\n fc = arrow_color, \n ec = arrow_edgecolor, \n relpos = arrow_relativepos))\n\n # Add any other annotation if provided:\n if annot_d_list is not None:\n for annot_d in annot_d_list:\n ax_ts.annotate(**annot_d)\n \n \n if not gs_dist is None:\n ax_dist = plt.subplot(gs_dist)\n sns.displot(tseries, vertical=True, ax=ax_dist)\n ax_dist.set_xlabel('Timesteps')\n ax_dist.set_ylim(ax_ts.get_ylim())\n ax_dist.set_yticklabels([])\n return [ax_ts, ax_dist], gs\n else:\n return ax_ts, gs\n", "repo_name": "atsuch/ginnipi_dwiqc", "sub_path": "toolbox/plotting_tools.py", "file_name": "plotting_tools.py", "file_ext": "py", "file_size_in_byte": 20839, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "matplotlib.use", "line_number": 29, "usage_type": "call"}, {"api_name": "seaborn.set_style", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.nanmax", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.nanmin", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.absolute", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.absolute", "line_number": 56, "usage_type": "call"}, {"api_name": "seaborn.set_style", "line_number": 106, "usage_type": "call"}, {"api_name": "ginnipi_dwiqc.toolbox.image_utils.get_1d_dat", "line_number": 108, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 110, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 111, "usage_type": "call"}, {"api_name": "os.path", "line_number": 111, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 113, "usage_type": "call"}, {"api_name": "os.path", "line_number": 113, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 115, "usage_type": "call"}, {"api_name": "os.path", "line_number": 115, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 117, "usage_type": "call"}, {"api_name": "os.path", "line_number": 117, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "seaborn.distplot", "line_number": 126, "usage_type": "call"}, {"api_name": "ginnipi_dwiqc.toolbox.image_utils.summarize_img_intensity_distribution", "line_number": 134, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 138, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 232, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 232, "usage_type": "name"}, {"api_name": "matplotlib.rcParams", "line_number": 235, "usage_type": "attribute"}, {"api_name": "numpy.savetxt", "line_number": 256, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 256, "usage_type": "call"}, {"api_name": "os.path", "line_number": 256, "usage_type": "name"}, {"api_name": "matplotlib.gridspec.GridSpec", "line_number": 270, "usage_type": "call"}, {"api_name": "matplotlib.gridspec", "line_number": 270, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 320, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 328, "usage_type": "call"}, {"api_name": "matplotlib.gridspec.GridSpecFromSubplotSpec", "line_number": 337, "usage_type": "call"}, {"api_name": "matplotlib.gridspec", "line_number": 337, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 343, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 343, "usage_type": "name"}, {"api_name": "textwrap.wrap", "line_number": 372, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 375, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 376, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 429, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 516, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 516, "usage_type": "name"}, {"api_name": "seaborn.displot", "line_number": 517, "usage_type": "call"}]} +{"seq_id": "2287694731", "text": "from PIL import Image, ImageFont, ImageDraw\n\n\ndef pixel(cm):\n return round(cm*28.347)\n\n\ndef separate(sentence):\n words = sentence.split()\n if len(sentence) <= 22:\n return [sentence]\n else:\n for i in range(len(words)-1,0,-1):\n left = ' '.join(words[:i])\n right = ' '.join(words[i:])\n if len(left) <= 22 and len(right) <= 22:\n return [left, right]\n return [sentence[:22], sentence[22:]]\n\ndef create_namecard(number, initial, name, nickname, sentence, R, G, B, output_filename, p=4):\n number = number.replace('-','')\n color_code = 'RGB(' + (str)(R) + ',' + (str)(G) + ',' + (str)(B) + ')'\n image = Image.new(\"RGBA\", (pixel(5.2*p), pixel(8.6*p)), color=\"RGB(230, 230, 230)\")\n draw = ImageDraw.Draw(image)\n font = ImageFont.truetype('NanumSquareRoundR.ttf', 7*p)\n font_small = ImageFont.truetype('NanumSquareRoundR.ttf', 5*p)\n kover = ImageFont.truetype('koverwatch.ttf', 60*p)\n draw.rectangle([(0, pixel(7*p)), (pixel(5.2*p), pixel(8.6*p))], fill=\"RGB(62,62,62)\")\n numbers = number[0:3] + initial + number[3:]\n for i in range(3):\n for j in range(4):\n fill = \"RGB(62,62,62)\" if i != 0 or j != 3 else color_code\n if numbers[i*4+j] == '1':\n draw.text((pixel(0.4*p)+j*pixel(1.2*p)+pixel(0.15*p), pixel(0.38*p)+i*pixel(2.2*p)), numbers[i*4+j], fill=fill, font=kover)\n else:\n draw.text((pixel(0.4*p)+j*pixel(1.2*p), pixel(0.38*p)+i*pixel(2.2*p)), numbers[i*4+j], fill=fill, font=kover)\n draw.text((pixel(1.47*p), pixel(7.37*p)), name + ' ' + nickname, fill=\"RGB(255, 255, 255)\", font=font)\n draw.line((pixel(1.47*p), pixel(7.7*p), pixel(1.47*p+0.22*p*len(name) + 0.08*p + 0.22*p*len(nickname)), pixel(7.7*p)), width = 0)\n for index, item in enumerate(separate(sentence)):\n if item[0] == ' ':\n item = item[1:]\n draw.text((pixel(1.47*p), pixel(7.82*p+index*0.25*p)), item, fill=\"RGB(255,255,255)\", font=font_small)\n draw.rectangle([(pixel(0.47*p), pixel(7.40*p)), (pixel(1.00*p), pixel(8.23*p))], fill=color_code)\n draw.rectangle([(pixel(0.40*p), pixel(7.33*p)), (pixel(1.00*p), pixel(8.23*p))], outline=\"RGB(255,255,255)\")\n draw.rectangle([(pixel(0.47*p), pixel(7.40*p)), (pixel(1.07*p), pixel(8.30*p))], outline=\"RGB(255,255,255)\")\n\n if not output_filename.endswith('.png'):\n output_filename += '.png'\n image.save(output_filename)\n", "repo_name": "nalida-dev/namecard", "sub_path": "card.py", "file_name": "card.py", "file_ext": "py", "file_size_in_byte": 2458, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "PIL.Image.new", "line_number": 23, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 23, "usage_type": "name"}, {"api_name": "PIL.ImageDraw.Draw", "line_number": 24, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 24, "usage_type": "name"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 25, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 25, "usage_type": "name"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 26, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 26, "usage_type": "name"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 27, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 27, "usage_type": "name"}]} +{"seq_id": "20093592985", "text": "import numpy as np\nimport torch\nfrom torch.autograd import Variable\nfrom torchfcn.utils import normalize_unit\nimport unittest\n\n\nclass MyTestCase(unittest.TestCase):\n def setUp(self):\n pass\n\n def test_normalize_unit(self):\n x = Variable(torch.rand(2, 5, 10))\n\n x_unit = normalize_unit(x, dim=2)\n np.testing.assert_array_almost_equal(torch.norm(x_unit, 2, 2, keepdim=True).data.numpy(), np.ones((2, 5, 1)))\n inner_product = torch.bmm(x_unit, x_unit.transpose(1, 2))\n for idx in range(0, x.size(0)):\n inner_product_diag = torch.diag(inner_product[idx, :, :].squeeze())\n np.testing.assert_array_almost_equal(inner_product_diag.data.numpy(), np.ones(5))\n\n x_unit = normalize_unit(x, dim=1)\n np.testing.assert_array_almost_equal(torch.norm(x_unit, 2, 1, keepdim=True).data.numpy(), np.ones((2, 1, 10)))\n inner_product = torch.bmm(x_unit.transpose(1, 2), x_unit)\n for idx in range(0, x.size(0)):\n inner_product_diag = torch.diag(inner_product[idx, :, :].squeeze())\n np.testing.assert_array_almost_equal(inner_product_diag.data.numpy(), np.ones(10))\n\n def test_normalize_unit_already_normalized(self):\n x_unit = Variable(torch.zeros(2, 5, 10).float())\n x_unit[:, :, 2] = 1.0\n x_renormalized = normalize_unit(x_unit, dim=2)\n np.testing.assert_array_almost_equal(x_unit.data.numpy(), x_renormalized.data.numpy())\n\n def test_normalize_assertions(self):\n x = Variable(torch.zeros(2, 5, 10).float())\n self.assertRaises(ValueError, normalize_unit, x)", "repo_name": "mbarnes1/pytorch-fcn", "sub_path": "torchfcn/test/test_normalize.py", "file_name": "test_normalize.py", "file_ext": "py", "file_size_in_byte": 1604, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "25", "api": [{"api_name": "unittest.TestCase", "line_number": 8, "usage_type": "attribute"}, {"api_name": "torch.autograd.Variable", "line_number": 13, "usage_type": "call"}, {"api_name": "torch.rand", "line_number": 13, "usage_type": "call"}, {"api_name": "torchfcn.utils.normalize_unit", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.testing.assert_array_almost_equal", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 16, "usage_type": "attribute"}, {"api_name": "torch.norm", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 16, "usage_type": "call"}, {"api_name": "torch.bmm", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.diag", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.testing.assert_array_almost_equal", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 20, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 20, "usage_type": "call"}, {"api_name": "torchfcn.utils.normalize_unit", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.testing.assert_array_almost_equal", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 23, "usage_type": "attribute"}, {"api_name": "torch.norm", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.bmm", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.diag", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.testing.assert_array_almost_equal", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 27, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 30, "usage_type": "call"}, {"api_name": "torchfcn.utils.normalize_unit", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.testing.assert_array_almost_equal", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 33, "usage_type": "attribute"}, {"api_name": "torch.autograd.Variable", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 36, "usage_type": "call"}, {"api_name": "torchfcn.utils.normalize_unit", "line_number": 37, "usage_type": "argument"}]} +{"seq_id": "40321093723", "text": "from typing import List\nfrom bs4 import BeautifulSoup\nimport httpx\n\n\nasync def get_jam_submissions_html(base_url: str, max_pages: int = 100) -> List[BeautifulSoup]:\n '''\n When provided a base_url, retrieves results pages until it runs out of pages or reaches the maximum number of pages\n specified by the max_pages parameter.\n Uses httpx library to enable asyncronous fetching of pages.\n Adds \"?page={page_num}\" to the end of base_url to retrieve the pages.\n '''\n if max_pages is None:\n max_pages = 100 \n webpages_html: List[BeautifulSoup] = []\n running = True\n page_num = 1\n\n async with httpx.AsyncClient() as client:\n while page_num <= max_pages and running:\n addon = f\"?page={page_num}\"\n html = await get_webpage_data(client, f\"{base_url}{addon}\")\n\n if html:\n webpages_html.append(html)\n print(f\"Page {page_num} results retrieved.\")\n page_num += 1\n continue\n else:\n running = False\n\n return webpages_html\n\n\nasync def get_webpage_data(client: httpx.AsyncClient, url: str) -> BeautifulSoup:\n '''\n Asynchronous function that retrieves a get request for the speicified page, and then returns a BeautifulSoup object of the \n requests html if the status code returned is 200, else None.\n Requires a AsyncClient be provided from the httpx module.\n '''\n result = await client.get(url)\n if result.status_code != 200:\n return None\n return BeautifulSoup(result.text, \"lxml\")\n\n\ndef check_webpage_exists(url: str):\n if url.strip()[:5] != \"https\":\n return False\n result = \"\"\n try:\n result = httpx.get(url)\n except httpx.ConnectError:\n print(\"Invalid website address provided. Did you enter the url correctly?\")\n if not result: return False\n if result.status_code == 200:\n return True\n return False\n", "repo_name": "aaFurze/Itch-GameJam-Results-Scraper", "sub_path": "src/scraper.py", "file_name": "scraper.py", "file_ext": "py", "file_size_in_byte": 1936, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.List", "line_number": 15, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 15, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 19, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 6, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 6, "usage_type": "name"}, {"api_name": "httpx.AsyncClient", "line_number": 35, "usage_type": "attribute"}, {"api_name": "bs4.BeautifulSoup", "line_number": 44, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 35, "usage_type": "name"}, {"api_name": "httpx.get", "line_number": 52, "usage_type": "call"}, {"api_name": "httpx.ConnectError", "line_number": 53, "usage_type": "attribute"}]} +{"seq_id": "32087151670", "text": "import os\nimport json\nimport VkDownloader\nimport yadisk\n\n\nvk_token = ''\nya_token = ''\n\ny = yadisk.YaDisk(token=ya_token)\ndownloader = VkDownloader.VkDownload(vk_token)\ndownloader.get_all_photos()\n\n#Получаю json файл и сохраяню его\ndata = downloader.get_photos()\ndef get_json(data):\n max_size_photo = {}\n photos = []\n for photo in data['response']['items']:\n max_size = 0\n photos_info = {}\n \n for size in photo['sizes']:\n if size['height'] >= max_size:\n max_size = size['height']\n if photo['likes']['count'] in max_size_photo:\n photos_info['file_name'] = f\"{photo['likes']['count']}+{photo['date']}.jpg\"\n else:\n photos_info['file_name'] = f\"{photo['likes']['count']}.jpg\"\n photos_info['size'] = size['type']\n photos.append(photos_info)\n\n with open(\"photos.json\", \"w\") as file:\n json.dump(photos, file, indent=4)\n\nget_json(data)\n\nphotos_list = os.listdir('images_vk')\n\n# Создаю на яндекс диске папку и загружаю туда фото\nif not y.exists('photo'):\n y.mkdir('photo')\nfor count, photo_name in enumerate(photos_list, start=1):\n y.upload(f'images_vk/{photo_name}', '/photo/'f'{photo_name}')\n print(f'Загружено фото: {count}')", "repo_name": "Asker0707/Course_work", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1327, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "yadisk.YaDisk", "line_number": 10, "usage_type": "call"}, {"api_name": "VkDownloader.VkDownload", "line_number": 11, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 34, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 38, "usage_type": "call"}]} +{"seq_id": "70846513987", "text": "\"\"\"Various functions that interact with Slack, e.g. posting messages.\"\"\"\nimport asyncio\nimport logging\nimport socket\nfrom pathlib import Path\nfrom typing import Union, Optional\n\nfrom slack_sdk.errors import SlackApiError\n\nfrom lsw_slackbot.plots import plot_resource_use\nfrom lsw_slackbot.resources import current_memory_fraction, _get_resource_usage_dataframe\nfrom lsw_slackbot.util import string_time\n\n\nasync def _send_message(client, channel: str, message: str):\n \"\"\"Sends a message to a channel, with basic logging & error handling.\"\"\"\n\n try:\n await client.chat_postMessage(channel=channel, text=message)\n\n # Handle various different errors, *some* of which are non-critical...\n except SlackApiError as e:\n logging.exception(f\"error from slack API when trying to send message: {e.response['error']}\")\n print(\"Encountered SlackApiError when trying to send message (see logs.)\")\n\n except AttributeError:\n logging.exception(\"suspected issue in Slack API when trying to send message. This bug has occured before!\")\n print(\"Encountered AttributeError when trying to send message (see logs.)\")\n\n\nasync def _send_file(client, channel: str, file: Union[Path, str], title):\n \"\"\"Sends a file to a channel, with basic logging & error handling.\"\"\"\n\n if isinstance(file, Path):\n file = str(file.absolute())\n\n try:\n await client.files_upload(channels=channel, file=file, title=title)\n\n # Handle various different errors, *some* of which are non-critical...\n except SlackApiError as e:\n logging.exception(f\"error from Slack API when trying to upload file: {e.response['error']}\")\n print(\"Encountered SlackApiError when trying to upload file (see logs.)\")\n\n except AttributeError:\n logging.exception(\"suspected issue in Slack API when trying to upload file. This bug has occured before!\")\n print(\"Encountered AttributeError when trying to upload file (see logs.)\")\n\n\nasync def hello_world(client, channel: str):\n \"\"\"Basic function to post an init message to a channel.\"\"\"\n # Todo: it would be really cool if hello_world also printed the latest commit message.\n # This could be done by running the command `git log -1` from Python?\n # See https://stackoverflow.com/questions/7293008/display-last-git-commit-comment\n logging.info(f\"Saying hello world in {channel}!\")\n system_name = socket.gethostname()\n await _send_message(\n client, channel, f\"Server time & date: {string_time()}\\nApp is running on system {system_name}.\")\n\n\nasync def send_resource_use_plot(client, channel: str, plot_kwargs: dict, title: Optional[str] = None):\n \"\"\"Sends a resource usage plot to a given channel.\"\"\"\n\n if title is None:\n title = f\"Resource usage plot generated at {string_time()}\"\n else:\n title = title + f\" (plot generated at {string_time()})\"\n\n # Firstly, let's generate a plot\n logging.info(\"Generating a resource usage plot\")\n logging.debug(f\"plot kwargs: {plot_kwargs}\")\n location_plot = await plot_resource_use(**plot_kwargs)\n\n # Now, let's try and send it to slack\n logging.info(f\"Sending to Slack in channel {channel}\")\n await _send_file(client, channel, location_plot, title)\n\n\n_LAST_MEMORY_FRACTION = 0.0\n\n\nasync def check_memory(client, channel: str, memory_warn_fraction=0.8, sleep_time=3600):\n \"\"\"Quick function for checking current server memory and sending a warning to a desired channel if it's\n too high.\"\"\"\n global _LAST_MEMORY_FRACTION # Sorry for using global variables =(\n\n current_usage = current_memory_fraction()\n\n # Only warn if we didn't warn before\n if _LAST_MEMORY_FRACTION < memory_warn_fraction:\n\n if current_usage > memory_warn_fraction:\n # Firstly, prioritise sending a basic warning\n await _send_message(client, channel, f\"WARNING: current memory usage at {current_usage:.2%}!\")\n\n # Next, grab info on currently running threads\n thread_df = await _get_resource_usage_dataframe(measurement_time=1.0)\n thread_df = thread_df.sort_values(\"memory\")\n\n # ... and format it into something we can send\n message = [\"Users with something currently running:\"]\n\n for i, a_row in thread_df.iterrows():\n message.append(f\"{a_row.name}: {a_row['cpu_percent']:.2f}% CPU \"\n f\"-- {a_row['memory']:.2f} GB\"\n f\"-- {a_row['threads']} threads\")\n\n message.append(f\"\\n(no further warnings will be sent for a sleep period of {sleep_time/60**2:.2f} hour(s))\")\n\n # Send it!\n await _send_message(client, channel, \"\\n\".join(message))\n\n # Sleep so we don't spam the chat\n await asyncio.sleep(sleep_time)\n\n _LAST_MEMORY_FRACTION = current_usage\n", "repo_name": "emilyhunt/lsw-slackbot", "sub_path": "lsw_slackbot/slack.py", "file_name": "slack.py", "file_ext": "py", "file_size_in_byte": 4849, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "slack_sdk.errors.SlackApiError", "line_number": 22, "usage_type": "name"}, {"api_name": "logging.exception", "line_number": 23, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 27, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 31, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 31, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 34, "usage_type": "argument"}, {"api_name": "slack_sdk.errors.SlackApiError", "line_number": 41, "usage_type": "name"}, {"api_name": "logging.exception", "line_number": 42, "usage_type": "call"}, {"api_name": "logging.exception", "line_number": 46, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 55, "usage_type": "call"}, {"api_name": "socket.gethostname", "line_number": 56, "usage_type": "call"}, {"api_name": "lsw_slackbot.util.string_time", "line_number": 58, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 61, "usage_type": "name"}, {"api_name": "lsw_slackbot.util.string_time", "line_number": 65, "usage_type": "call"}, {"api_name": "lsw_slackbot.util.string_time", "line_number": 67, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 70, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 71, "usage_type": "call"}, {"api_name": "lsw_slackbot.plots.plot_resource_use", "line_number": 72, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 75, "usage_type": "call"}, {"api_name": "lsw_slackbot.resources.current_memory_fraction", "line_number": 87, "usage_type": "call"}, {"api_name": "lsw_slackbot.resources._get_resource_usage_dataframe", "line_number": 97, "usage_type": "call"}, {"api_name": "asyncio.sleep", "line_number": 114, "usage_type": "call"}]} +{"seq_id": "20075077787", "text": "import os\n\nimport pytest\nimport tempfile\n\nfrom server.db import db\nfrom server import create_app\nfrom auth.models import User\n\n\n@pytest.fixture\ndef app():\n db_fd, db_path = tempfile.mkstemp()\n app = create_app({\n 'TESTING': True,\n 'DATABASE': db_path,\n 'SERVER_NAME': 'server'\n })\n\n with app.app_context():\n db.create_all()\n\n yield app\n\n with app.app_context():\n for table in reversed(db.metadata.sorted_tables):\n db.session.execute(table.delete())\n\n os.close(db_fd)\n os.unlink(db_path)\n\n\n@pytest.fixture\n@pytest.mark.usefixtures('app')\ndef client(app):\n return app.test_client()\n\n\n@pytest.fixture\n@pytest.mark.usefixtures('app')\ndef runner(app):\n app.test_cli_runner()\n\n\n@pytest.fixture\n@pytest.mark.usefixtures('app', 'faker')\ndef user(app, faker):\n with app.app_context():\n _user = User(\n username=faker.user_name(),\n password=faker.password()\n )\n\n db.session.add(_user)\n db.session.commit()\n return _user\n", "repo_name": "mrprfrm/flaskr", "sub_path": "server/conftest.py", "file_name": "conftest.py", "file_ext": "py", "file_size_in_byte": 1045, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "tempfile.mkstemp", "line_number": 13, "usage_type": "call"}, {"api_name": "server.create_app", "line_number": 14, "usage_type": "call"}, {"api_name": "server.db.db.create_all", "line_number": 21, "usage_type": "call"}, {"api_name": "server.db.db", "line_number": 21, "usage_type": "name"}, {"api_name": "server.db.db.metadata", "line_number": 26, "usage_type": "attribute"}, {"api_name": "server.db.db", "line_number": 26, "usage_type": "name"}, {"api_name": "server.db.db.session.execute", "line_number": 27, "usage_type": "call"}, {"api_name": "server.db.db.session", "line_number": 27, "usage_type": "attribute"}, {"api_name": "server.db.db", "line_number": 27, "usage_type": "name"}, {"api_name": "os.close", "line_number": 29, "usage_type": "call"}, {"api_name": "os.unlink", "line_number": 30, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 11, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 33, "usage_type": "attribute"}, {"api_name": "pytest.mark.usefixtures", "line_number": 34, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 34, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 39, "usage_type": "attribute"}, {"api_name": "pytest.mark.usefixtures", "line_number": 40, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 40, "usage_type": "attribute"}, {"api_name": "auth.models.User", "line_number": 49, "usage_type": "call"}, {"api_name": "server.db.db.session.add", "line_number": 54, "usage_type": "call"}, {"api_name": "server.db.db.session", "line_number": 54, "usage_type": "attribute"}, {"api_name": "server.db.db", "line_number": 54, "usage_type": "name"}, {"api_name": "server.db.db.session.commit", "line_number": 55, "usage_type": "call"}, {"api_name": "server.db.db.session", "line_number": 55, "usage_type": "attribute"}, {"api_name": "server.db.db", "line_number": 55, "usage_type": "name"}, {"api_name": "pytest.fixture", "line_number": 45, "usage_type": "attribute"}, {"api_name": "pytest.mark.usefixtures", "line_number": 46, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 46, "usage_type": "attribute"}]} +{"seq_id": "72893394624", "text": "import os\nfrom pathlib import Path\nimport shutil\nfrom typing import List\nimport logging\nfrom sys import platform\nfrom os import path\n\nfrom dotmanage.models.ConfigFile import OS, ConfigFile\nfrom dotmanage.fs import copy_files\n\nconfig_files: List[ConfigFile] = [\n ConfigFile(\"/Users/{user}/Library/Application Support/Code/User/settings.json\"),\n ConfigFile(\"/Users/{user}/Library/Application Support/Code/User/keybindings.json\"),\n ConfigFile(\"/Users/{user}/.tmux.conf\"),\n ConfigFile(\"/Library/Keyboard Layouts/Deutsch - Programming.icns\", os=OS.OSX),\n ConfigFile(\"/Library/Keyboard Layouts/Deutsch - Programming.keylayout\", os=OS.OSX), \n ConfigFile(\"/Users/{user}/.config/nvim\") ]\n\n\ndef get(user=\"kul\"):\n \"\"\"\n Replaces files in .config with files from current system\n \"\"\"\n logging.info(\"Importing system config\")\n if platform == \"darwin\":\n for config_file in config_files:\n if not config_file.os & OS.OSX:\n continue\n full_path = config_file.osx_path.format(user=user)\n destination_path = f\"./configfiles/{config_file.osx_path}\"\n copy_files(Path(full_path), Path(destination_path))\n elif platform == \"win32\":\n for config_file in config_files:\n if not config_file.os & OS.WIN:\n continue\n pass\n \n\ndef set(user=\"kul\"):\n \"\"\"\n Replaces system files with files from .config\n \"\"\"\n logging.info(\"Exporting config to system\")\n if platform == \"darwin\":\n for config_file in config_files:\n if not config_file.os & OS.OSX:\n continue\n source_path = f\"./configfiles/{config_file.osx_path}\"\n destination_path = config_file.osx_path.format(user=user)\n copy_files(Path(source_path), Path(destination_path))\n elif platform == \"win32\":\n # Handle windows\n pass\n", "repo_name": "kulgg/dotfiles", "sub_path": "dotmanage/commands.py", "file_name": "commands.py", "file_ext": "py", "file_size_in_byte": 1919, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.List", "line_number": 12, "usage_type": "name"}, {"api_name": "dotmanage.models.ConfigFile.ConfigFile", "line_number": 12, "usage_type": "name"}, {"api_name": "dotmanage.models.ConfigFile.ConfigFile", "line_number": 13, "usage_type": "call"}, {"api_name": "dotmanage.models.ConfigFile.ConfigFile", "line_number": 14, "usage_type": "call"}, {"api_name": "dotmanage.models.ConfigFile.ConfigFile", "line_number": 15, "usage_type": "call"}, {"api_name": "dotmanage.models.ConfigFile.ConfigFile", "line_number": 16, "usage_type": "call"}, {"api_name": "dotmanage.models.ConfigFile.OS.OSX", "line_number": 16, "usage_type": "attribute"}, {"api_name": "dotmanage.models.ConfigFile.OS", "line_number": 16, "usage_type": "name"}, {"api_name": "dotmanage.models.ConfigFile.ConfigFile", "line_number": 17, "usage_type": "call"}, {"api_name": "dotmanage.models.ConfigFile.OS.OSX", "line_number": 17, "usage_type": "attribute"}, {"api_name": "dotmanage.models.ConfigFile.OS", "line_number": 17, "usage_type": "name"}, {"api_name": "dotmanage.models.ConfigFile.ConfigFile", "line_number": 18, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 25, "usage_type": "call"}, {"api_name": "sys.platform", "line_number": 26, "usage_type": "name"}, {"api_name": "dotmanage.models.ConfigFile.OS.OSX", "line_number": 28, "usage_type": "attribute"}, {"api_name": "dotmanage.models.ConfigFile.OS", "line_number": 28, "usage_type": "name"}, {"api_name": "dotmanage.fs.copy_files", "line_number": 32, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 32, "usage_type": "call"}, {"api_name": "sys.platform", "line_number": 33, "usage_type": "name"}, {"api_name": "dotmanage.models.ConfigFile.OS.WIN", "line_number": 35, "usage_type": "attribute"}, {"api_name": "dotmanage.models.ConfigFile.OS", "line_number": 35, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 44, "usage_type": "call"}, {"api_name": "sys.platform", "line_number": 45, "usage_type": "name"}, {"api_name": "dotmanage.models.ConfigFile.OS.OSX", "line_number": 47, "usage_type": "attribute"}, {"api_name": "dotmanage.models.ConfigFile.OS", "line_number": 47, "usage_type": "name"}, {"api_name": "dotmanage.fs.copy_files", "line_number": 51, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 51, "usage_type": "call"}, {"api_name": "sys.platform", "line_number": 52, "usage_type": "name"}]} +{"seq_id": "33165728754", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('add_teacher', views.add_teacher, name='add_teacher'),\n path('view_teachers', views.view_teachers, name='view_teachers'),\n path('permission/', views.permission, name='permission')\n\n]\n", "repo_name": "anshadp/nuox_m_test", "sub_path": "school_admin/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 311, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.urls.path", "line_number": 5, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}]} +{"seq_id": "34485421077", "text": "import math\nimport pygame\nfrom Constants import *\nimport random\n\nxsize, ysize = None, None\n\nclass Hex:\n def __init__(self, color) -> None:\n self.blink = False\n self.color = color\n self.terrain = (color > 0)\n self.selected = False\n self.entity = 0\n self.security = 0\n self.security_providers = []\n self.hall_flag = False\n self.hall_loc = None\n self.land = []\n self.playable = False\n pass\n\ndef cursor_on_grid(old_pos):\n mouse = pygame.mouse.get_pos()\n x1, y1, x2, y2 = None, None, None, None\n # set 1\n if mouse[1]%72<45:\n x1 = math.floor(mouse[0]/48)\n y1 = 2*math.floor(mouse[1]/72)\n # set 2\n if (mouse[1]-36)%72<45:\n x2 = math.floor((mouse[0]-24)/48)\n y2 = 2*math.floor((mouse[1]-36)/72)+1\n\n if x1 is not None and x2 is not None:\n if (24+48*x1-mouse[0])^2 + (24+72*y1-mouse[1])^2 < (48+48*x2-mouse[0])^2 + (60+72*y2-mouse[1])^2: x,y = x1,y1\n else: x,y =x2,y2\n elif x1 is None: x,y =x2,y2\n else: x,y =x1,y1\n if x>xsize-1 or y>ysize-1 or x<0 or y<0: return old_pos, False\n return (x,y), True\n\ndef neighbours(x,y,distance):\n if distance==1:\n if y%2==1:\n return [(x,y+1),(x+1,y+1),(x-1,y),(x+1,y),(x,y-1),(x+1,y-1)]\n else:\n return [(x,y+1),(x-1,y+1),(x-1,y),(x+1,y),(x,y-1),(x-1,y-1)]\n if distance==2:\n if y%2==1:\n return [(x,y+1),(x+1,y+1),(x-1,y),(x+1,y),(x,y-1),(x+1,y-1),(x-1,y+2),(x,y+2),(x+1,y+2),(x-1,y+2),(x+2,y+1),(x-1,y+1),(x-2,y),(x+2,y),(x-1,y-2),(x,y-2),(x+1,y-2),(x-1,y-2),(x+2,y-1),(x-1,y-1)]\n else:\n return [(x,y+1),(x-1,y+1),(x-1,y),(x+1,y),(x,y-1),(x-1,y-1),(x-1,y+2),(x,y+2),(x+1,y+2),(x-1,y+2),(x-2,y+1),(x+1,y+1),(x-2,y),(x+2,y),(x-1,y-2),(x,y-2),(x+1,y-2),(x-1,y-2),(x-2,y-1),(x+1,y-1)]\n\ndef verify(array):\n verified = []\n for cell in array:\n if cell[0] < 0 or cell[1] < 0: continue\n if cell[0] >= xsize or cell[1] >= ysize: continue\n verified.append(cell)\n return verified\n\ndef getBorderingLand(hall_pos,grid):\n land = grid[hall_pos[0]][hall_pos[1]].land.copy()\n\n for x,y in grid[hall_pos[0]][hall_pos[1]].land:\n tmp = verify(neighbours(x,y,1))\n for cell in verify(neighbours(x,y,1)): \n if not grid[cell[0]][cell[1]].terrain: tmp.remove(cell)\n appendifnotAppended(land,tmp)\n\n return land\n\ndef color_aggregate(x,y,land,new,grid):\n new_this_call = []\n for neighbour in verify(neighbours(x,y,1)):\n if grid[neighbour[0]][neighbour[1]].color == grid[x][y].color and neighbour not in land and neighbour not in new:\n new.append(neighbour)\n new_this_call.append(neighbour)\n\n for neighbour in new_this_call:\n color_aggregate(neighbour[0],neighbour[1],land,new,grid)\n\n return\n\ndef getValidMoves(pos,grid,color,entity):\n valid = []\n capital = grid[pos[0]][pos[1]].hall_loc\n city_land = grid[capital[0]][capital[1]].land\n\n for location in verify(neighbours(pos[0],pos[1],2)):\n\n if not grid[location[0]][location[1]].terrain: continue\n\n if grid[location[0]][location[1]].color == color: \n if location in city_land and (grid[location[0]][location[1]].entity < TOWER or (grid[location[0]][location[1]].entity == entity and entity= entity-CITY: continue\n for neighbour in neighbours(location[0],location[1],1):\n\n if neighbour in city_land:\n valid.append(location)\n break\n\n valid.append(pos)\n return set(valid)\n\ndef getValidPlacementSpots(hall_pos,grid,entity):\n\n valid = []\n\n if entity != TOWER:\n land = getBorderingLand(hall_pos,grid)\n for loc in land:\n if grid[loc[0]][loc[1]].color == grid[hall_pos[0]][hall_pos[1]].color:\n if grid[loc[0]][loc[1]].entity <= GRAVE or (entity < KNIGHT and entity > CITY and grid[loc[0]][loc[1]].entity == entity): \n valid.append(loc)\n elif grid[loc[0]][loc[1]].security < entity-CITY: \n valid.append(loc)\n else:\n land = grid[hall_pos[0]][hall_pos[1]].land.copy()\n for loc in land:\n if grid[loc[0]][loc[1]].entity <= GRAVE: valid.append(loc)\n\n return valid\n\n# Returns list of adjacent cells to captured cell, that are allied and captured under a different city\ndef GetConnectingTerritories(mouse_pos,grid,color,selected_city):\n connecting = []\n for cell in verify(neighbours(mouse_pos[0],mouse_pos[1],1)):\n if (grid[cell[0]][cell[1]].color != color): continue\n if (cell in grid[selected_city[0]][selected_city[1]].land): continue\n if (grid[cell[0]][cell[1]].hall_loc is not None): connecting.append(cell)\n return connecting\n\ndef convertCity(grid,joining_city,selected_city):\n for cell in grid[joining_city[0]][joining_city[1]].land:\n grid[cell[0]][cell[1]].hall_loc = selected_city\n\n grid[selected_city[0]][selected_city[1]].wages += grid[joining_city[0]][joining_city[1]].wages\n grid[selected_city[0]][selected_city[1]].income += grid[joining_city[0]][joining_city[1]].income\n grid[selected_city[0]][selected_city[1]].net += grid[joining_city[0]][joining_city[1]].net\n grid[selected_city[0]][selected_city[1]].gold += grid[joining_city[0]][joining_city[1]].gold\n grid[selected_city[0]][selected_city[1]].land += grid[joining_city[0]][joining_city[1]].land\n\n grid[joining_city[0]][joining_city[1]].wages = None\n grid[joining_city[0]][joining_city[1]].income = None\n grid[joining_city[0]][joining_city[1]].net = None\n grid[joining_city[0]][joining_city[1]].gold = None\n grid[joining_city[0]][joining_city[1]].land = []\n grid[joining_city[0]][joining_city[1]].entity = 0\n\ndef moveHall(grid,old_pos,affected_cells,queued_security_updates):\n land = grid[old_pos[0]][old_pos[1]].land.copy()\n land.remove(old_pos)\n\n queued_security_updates.append(old_pos)\n appendifnotAppended(affected_cells,verify(neighbours(old_pos[0],old_pos[1],1)))\n appendifnotAppended(affected_cells,land)\n\n if len(land) < 2: \n for cell in land:\n grid[cell[0]][cell[1]].hall_loc = None\n if grid[cell[0]][cell[1]].entity > CITY: \n grid[cell[0]][cell[1]].entity = GRAVE\n grid[cell[0]][cell[1]].gravetime = 1\n SecurityUpdate(grid,cell)\n return None\n\n tmp = land.copy()\n rng = None\n\n while True:\n rng = tmp[random.randint(0,len(tmp)-1)]\n if grid[rng[0]][rng[1]].entity < TOWER:\n grid[rng[0]][rng[1]].entity = CITY\n grid[rng[0]][rng[1]].land = land\n grid[rng[0]][rng[1]].wages = grid[old_pos[0]][old_pos[1]].wages\n grid[rng[0]][rng[1]].income = grid[old_pos[0]][old_pos[1]].income - 1\n grid[rng[0]][rng[1]].net = grid[old_pos[0]][old_pos[1]].net - 1 - grid[old_pos[0]][old_pos[1]].gold\n grid[rng[0]][rng[1]].gold = 0\n \n for cell in land:\n grid[cell[0]][cell[1]].hall_loc = rng\n break\n else: tmp.remove(rng)\n\n if len(tmp) == 0: \n for cell in land:\n grid[cell[0]][cell[1]].hall_loc = None\n if grid[cell[0]][cell[1]].entity > CITY: \n grid[cell[0]][cell[1]].entity = GRAVE\n grid[cell[0]][cell[1]].gravetime = 1\n SecurityUpdate(grid,cell)\n rng = None\n break\n\n return rng # rng is the new position of the enemy city\n\ndef checkForDivide(hall_pos,grid):\n actual_land = [hall_pos]\n color_aggregate(hall_pos[0],hall_pos[1],actual_land,actual_land,grid)\n if len(actual_land) != len(grid[hall_pos[0]][hall_pos[1]].land): \n return True, actual_land\n return False, actual_land\n\ndef createCity(land,grid,affected_cells,queued_security_updates):\n\n if len(land)==1: \n grid[land[0][0]][land[0][1]].hall_loc = None\n if grid[land[0][0]][land[0][1]].entity > CITY: \n grid[land[0][0]][land[0][1]].entity = GRAVE\n grid[land[0][0]][land[0][1]].gravetime = 2\n grid[land[0][0]][land[0][1]].playable = False\n SecurityUpdate(grid,land[0])\n return\n\n tmp = land.copy()\n rng = None\n\n while True:\n rng = tmp[random.randint(0,len(tmp)-1)]\n if grid[rng[0]][rng[1]].entity < TOWER:\n grid[rng[0]][rng[1]].entity = CITY\n grid[rng[0]][rng[1]].land = land\n grid[rng[0]][rng[1]].wages = 0\n grid[rng[0]][rng[1]].income = 0\n grid[rng[0]][rng[1]].gold = 0\n \n for cell in land:\n grid[cell[0]][cell[1]].hall_loc = rng\n if grid[cell[0]][cell[1]].entity not in (TREE,PALM):\n grid[rng[0]][rng[1]].income += 1\n if grid[cell[0]][cell[1]].entity > CITY: grid[rng[0]][rng[1]].wages += math.floor(2*(3**(grid[cell[0]][cell[1]].entity- MAN)))\n\n grid[rng[0]][rng[1]].net = grid[rng[0]][rng[1]].income - grid[rng[0]][rng[1]].wages\n break\n\n else: tmp.remove(rng)\n\n if len(tmp) == 0: \n for cell in land:\n grid[cell[0]][cell[1]].hall_loc = None\n if grid[cell[0]][cell[1]].entity > CITY: \n grid[cell[0]][cell[1]].entity = GRAVE\n grid[cell[0]][cell[1]].gravetime = 1\n grid[cell[0]][cell[1]].playable = False\n SecurityUpdate(grid,cell)\n rng = None\n break\n\n if rng is not None: \n HandleSplits(grid,rng,affected_cells,queued_security_updates)\n return rng\n\ndef appendifnotAppended(array,items):\n for item in items:\n if item not in array: array.append(item)\n return\n\ndef HandleSplits(grid,original_hall,affected_cells,queued_security_updates):\n isDivide, actual_land = checkForDivide(original_hall,grid)\n if isDivide:\n\n if affected_cells is not None:\n appendifnotAppended(affected_cells,grid[original_hall[0]][original_hall[1]].land)\n\n if len(actual_land)>1:\n split_land = grid[original_hall[0]][original_hall[1]].land.copy()\n grid[original_hall[0]][original_hall[1]].land = actual_land\n grid[original_hall[0]][original_hall[1]].income = 0\n grid[original_hall[0]][original_hall[1]].wages = 0\n\n for land in actual_land:\n split_land.remove(land)\n if grid[land[0]][land[1]].entity not in (2,3):\n grid[original_hall[0]][original_hall[1]].income += 1\n if grid[land[0]][land[1]].entity > CITY: grid[original_hall[0]][original_hall[1]].wages += math.floor(2*(3**(grid[land[0]][land[1]].entity- MAN)))\n\n grid[original_hall[0]][original_hall[1]].net = grid[original_hall[0]][original_hall[1]].gold + grid[original_hall[0]][original_hall[1]].income - grid[original_hall[0]][original_hall[1]].wages\n else:\n split_land = grid[original_hall[0]][original_hall[1]].land.copy()\n split_land.remove(original_hall)\n grid[original_hall[0]][original_hall[1]].land = []\n grid[original_hall[0]][original_hall[1]].income = None\n grid[original_hall[0]][original_hall[1]].wages = None\n grid[original_hall[0]][original_hall[1]].net = None\n grid[original_hall[0]][original_hall[1]].hall_loc = None\n grid[original_hall[0]][original_hall[1]].entity = 0\n\n new_hall_loc = createCity(split_land,grid,affected_cells,queued_security_updates)\n if new_hall_loc is not None:\n queued_security_updates.append(new_hall_loc)\n appendifnotAppended(affected_cells,verify(neighbours(new_hall_loc[0],new_hall_loc[1],1)))\n \n return\n\ndef SecurityUpdate(grid,position):\n \n SecurityCalculate(grid,position)\n\n for cell in verify(neighbours(position[0],position[1],1)):\n if grid[cell[0]][cell[1]].terrain: SecurityCalculate(grid,cell)\n \n return\n\ndef SecurityCalculate(grid,pos):\n highest = 0\n color = grid[pos[0]][pos[1]].color\n grid[pos[0]][pos[1]].security_providers = []\n if grid[pos[0]][pos[1]].hall_loc is None: \n grid[pos[0]][pos[1]].security = 0\n return\n if grid[pos[0]][pos[1]].entity == TOWER: highest = TOWER_SECURITY\n elif grid[pos[0]][pos[1]].entity == CITY: highest = CITY_SECURITY\n elif grid[pos[0]][pos[1]].entity > CITY: highest = grid[pos[0]][pos[1]].entity-CITY\n\n for cell in verify(neighbours(pos[0],pos[1],1)):\n if grid[cell[0]][cell[1]].terrain and grid[cell[0]][cell[1]].color == color and grid[cell[0]][cell[1]].entity > GRAVE: \n if grid[cell[0]][cell[1]].entity == TOWER and highest <= TOWER_SECURITY:\n if highest != TOWER_SECURITY:\n grid[pos[0]][pos[1]].security_providers = [cell]\n else:\n grid[pos[0]][pos[1]].security_providers.append(cell)\n highest = TOWER_SECURITY\n\n elif grid[cell[0]][cell[1]].entity == CITY and highest <= CITY_SECURITY: \n if highest != CITY_SECURITY:\n grid[pos[0]][pos[1]].security_providers = [cell]\n else:\n grid[pos[0]][pos[1]].security_providers.append(cell)\n highest = CITY_SECURITY\n\n elif highest <= grid[cell[0]][cell[1]].entity-CITY:\n if highest != grid[cell[0]][cell[1]].entity-CITY:\n grid[pos[0]][pos[1]].security_providers = [cell]\n else:\n grid[pos[0]][pos[1]].security_providers.append(cell)\n highest = grid[cell[0]][cell[1]].entity-CITY\n\n grid[pos[0]][pos[1]].security = highest\n return\n\ndef fixHighlighting(grid,selected_city):\n if (selected_city is not None) and grid[selected_city[0]][selected_city[1]].entity != CITY: sel = None\n else: sel = selected_city\n for x in range (0,xsize):\n for y in range(0,ysize): \n grid[x][y].selected = False\n if sel is not None:\n if (x,y) in grid[sel[0]][sel[1]].land: \n grid[x][y].selected = True\n\n return sel\n", "repo_name": "shivenBajpai/Slay", "sub_path": "Slay_Client/Hex_Utils.py", "file_name": "Hex_Utils.py", "file_ext": "py", "file_size_in_byte": 14346, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pygame.mouse.get_pos", "line_number": 24, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 24, "usage_type": "attribute"}, {"api_name": "math.floor", "line_number": 28, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 29, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 32, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 33, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 177, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 225, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 237, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 281, "usage_type": "call"}]} +{"seq_id": "41314798547", "text": "import numpy as np\nimport os\nfrom torch.utils.data import Dataset, DataLoader\n\nclass PFDataset(Dataset):\n\t'''dataset for training DPF'''\n\tdef __init__(self):\n\t\tnum_traj = len(os.listdir(\"../data_rrt/\")) // 3\n\t\tactions = []\n\t\tmeasurements = []\n\t\tstates = []\n\t\tnext_states = []\n\t\tfor i in range(200):\n\t\t\taction = np.loadtxt(\"../data_rrt/action_%d.txt\" % i)\n\t\t\tmeasurement = np.loadtxt(\"../data_rrt/measure_%d.txt\" % i)\n\t\t\trollout = np.loadtxt(\"../data_rrt/rollout_%d.txt\" % i)\n\n\t\t\tactions.append(action.T)\n\t\t\tmeasurements.append(measurement[1:])\n\t\t\tstates.append(rollout[:, :-1].T)\n\t\t\tnext_states.append(rollout[:, 1:].T)\n\n\t\tself.actions = np.concatenate(actions, axis = 0)\n\t\tself.measurements = np.concatenate(measurements, axis = 0)\n\t\tself.states = np.concatenate(states, axis = 0)\n\t\tself.next_states = np.concatenate(next_states, axis = 0)\n\t\tself.deltas = (self.next_states - self.states)\n\t\tself.deltas[:, 2][self.deltas[:, 2] > np.pi] = self.deltas[:, 2][self.deltas[:, 2] > np.pi] - 2*np.pi\n\t\tself.deltas[:, 2][self.deltas[:, 2] < -np.pi] = self.deltas[:, 2][self.deltas[:, 2] < -np.pi] + 2*np.pi\n\t\t\n\t\t# scaling\n\t\tself.actions = self.actions / np.array([20., 1.0]) # [-1, 1]\n\t\tself.measurements = self.measurements / 4.0 # [0, 1]\n\t\tself.states = self.states / np.array([1788, 1240, 1.0]) # [0, 1]\n\t\tself.next_states = self.next_states / np.array([1788, 1240, 1.0]) # [0, 1]\n\t\tself.deltas = self.deltas / np.array([2, 2, 20/7.5*np.tan(1.0)*0.1]) # [-1, 1]\n\n\t\t# downsample\n\t\tself.states = self.states[::10]\n\t\tself.actions = self.actions[::10]\n\t\tself.measurements = self.measurements[::10]\n\t\tself.next_states = self.next_states[::10]\n\t\tself.deltas = self.deltas[::10]\n\n\tdef __len__(self):\n\t\treturn self.actions.shape[0]\n\n\tdef __getitem__(self, idx):\n\t\treturn (self.states[idx], self.actions[idx], self.measurements[idx], self.next_states[idx], self.deltas[idx])\n\nif __name__ == \"__main__\":\n\tdataset = PFDataset()\n", "repo_name": "tony23545/MotionPlanning", "sub_path": "DPF/PFDataset.py", "file_name": "PFDataset.py", "file_ext": "py", "file_size_in_byte": 1917, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "25", "api": [{"api_name": "torch.utils.data.Dataset", "line_number": 5, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 28, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 29, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.tan", "line_number": 36, "usage_type": "call"}]} +{"seq_id": "73472314625", "text": "#!/usr/bin/python\n#-*-coding:utf-8-*-\n\n# /**\n# * ================================================\n# * 作 者:若云\n# * 版 本:1.0.0\n# * 更新日期: 2018年02月28日\n# * 邮 箱:zyhdvlp@gmail.com\n# * ================================================\n# */\n\nimport os\nimport sys\nfrom config import config\nimport platform\nimport shutil\n\n#创建文件\ndef crateFile(path):\n #创建目录\n if not os.path.exists(path):\n os.mkdir(path)\n else:\n shutil.rmtree(path) # 删除文件夹及其下所有文件\n os.mkdir(path)\n\n#获取脚本文件的当前路径\ndef curFileDir():\n #获取脚本路径\n path = sys.path[0]\n #判断为脚本文件还是py2exe编译后的文件,\n #如果是脚本文件,则返回的是脚本的目录,\n #如果是编译后的文件,则返回的是编译后的文件路径\n if os.path.isdir(path):\n return path\n elif os.path.isfile(path):\n return os.path.dirname(path)\n\n#判断当前系统\ndef isWindows():\n sysstr = platform.system()\n if(\"Windows\" in sysstr):\n return 1\n else:\n return 0\n\n#兼容不同系统的路径分隔符\ndef getBackslash():\n\tif(isWindows() == 1):\n\t\treturn \"\\\\\"\n\telse:\n\t\treturn \"/\" \n\n#当前脚本文件所在目录\nparentPath = curFileDir() + getBackslash()\ntempPath = parentPath+\"temp\" +getBackslash()#临时文件保存目录\n\nlibPath = parentPath + \"lib\" + getBackslash()\nkeystorePath = config.keystorePath\nkeyAlias = config.keyAlias\nkeystorePassword = config.keystorePassword\nkeyPassword = config.keyPassword\nbuildToolsPath = config.sdkBuildToolPath + getBackslash()\ncheckAndroidV2SignaturePath = libPath + \"CheckAndroidV2Signature.jar\"\nwalleChannelWritterPath = libPath + \"walle-cli-all.jar\"\n\nt = []#创建一个唯一字符的集合\n#读文件,判断是否之后一个后缀为apk的文件\napkFiles= os.listdir(parentPath) #得到文件夹下的所有文件名称\nprint (\"**** 正在检测目录apk数量 ****\")\nfor apkFile in apkFiles:\n if \"apk\" in apkFile :\n t.append(apkFile)\n \nif len(t) == 0:\n print (\"**** 未发现apk,请把apk放入到当前目录中 ****\")\nelif len(t) > 1:\n print (\"**** 请删除多余的apk文件,仅保留现有的apk ****\")\nelse:\n print (\"**** 正常执行代码 ****\")\n protectedSourceApkName = t[0]\n protectedSourceApkPath = parentPath + protectedSourceApkName\n\n crateFile(tempPath)\n \n zipalignedApkPath = tempPath + protectedSourceApkName[0 : -4] + \"_aligned.apk\"\n #对齐\n zipalignShell = buildToolsPath + \"zipalign -v 4 \" + protectedSourceApkPath + \" \" + zipalignedApkPath\n os.system(zipalignShell)\n\n signedApkPath = zipalignedApkPath[0 : -4] + \"_signed.apk\"\n\n #签名\n signShell = buildToolsPath + \"apksigner sign --ks \"+ keystorePath + \" --ks-key-alias \" + keyAlias + \" --ks-pass pass:'\" + keystorePassword + \"' --key-pass pass:'\" + keyPassword + \"' --in \" + zipalignedApkPath + \" --out \" + signedApkPath\n os.system(signShell)\n\n #检查V2签名是否正确\n checkV2Shell = \"java -jar \" + checkAndroidV2SignaturePath + \" \" + signedApkPath;\n os.system(checkV2Shell)\n\n channelFilePath = parentPath+\"config\"+getBackslash()+\"channel.txt\"\n\n moveApkOutResGuardPath = parentPath+\"out\"+getBackslash()#输出文件\n crateFile(moveApkOutResGuardPath)\n \n #写入渠道\n writeChannelShell = \"java -jar \" + walleChannelWritterPath + \" batch -f \" + channelFilePath + \" \" + signedApkPath + \" \" + moveApkOutResGuardPath\n os.system(writeChannelShell)\n\n #读文件\n apkFiles= os.listdir(moveApkOutResGuardPath) #得到文件夹下的所有文件名称\n print (\"\\n**** 渠道号为: ****\\n\")\n for apkFile in apkFiles:\n if \"apk\" in apkFile :\n showChannelShell = \"java -jar \" + walleChannelWritterPath + \" show \" + moveApkOutResGuardPath + apkFile\n os.system(showChannelShell)\n\n print (\"\\n**** Finish! Please Check the 'out' Folder in your root Floder ! ****\\n\")\n\n #删除无用文件\n shutil.rmtree(tempPath) # 删除文件夹及其下所有文件\n #删除多余文件\n #os.remove(path)\n\n\n\n\n\n", "repo_name": "bugyun/ApkMultiChannel", "sub_path": "ApkResigner.py", "file_name": "ApkResigner.py", "file_ext": "py", "file_size_in_byte": 4160, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.path.exists", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 23, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 25, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 26, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path", "line_number": 38, "usage_type": "attribute"}, {"api_name": "platform.system", "line_number": 42, "usage_type": "call"}, {"api_name": "config.config.keystorePath", "line_number": 60, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 60, "usage_type": "name"}, {"api_name": "config.config.keyAlias", "line_number": 61, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 61, "usage_type": "name"}, {"api_name": "config.config.keystorePassword", "line_number": 62, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 62, "usage_type": "name"}, {"api_name": "config.config.keyPassword", "line_number": 63, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 63, "usage_type": "name"}, {"api_name": "config.config.sdkBuildToolPath", "line_number": 64, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 64, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 70, "usage_type": "call"}, {"api_name": "os.system", "line_number": 90, "usage_type": "call"}, {"api_name": "os.system", "line_number": 96, "usage_type": "call"}, {"api_name": "os.system", "line_number": 100, "usage_type": "call"}, {"api_name": "os.system", "line_number": 109, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 112, "usage_type": "call"}, {"api_name": "os.system", "line_number": 117, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 122, "usage_type": "call"}]} +{"seq_id": "15526922627", "text": "\"\"\"\n Problem 37: Subsets\n\n Question: Return all subsets from given list\n Source: leetcode 78 (https://leetcode.com/problems/subsets/\n\n\"\"\"\nfrom typing import List\nfrom common.common_function import test_result\n\n\n# Solution: Tree searching using DFS\ndef subsets(nums: List[int]) -> List[List[int]]:\n result = []\n\n def dfs(index, path):\n result.append(path)\n\n for i in range(index, len(nums)):\n dfs(i + 1, path + [nums[i]])\n\n dfs(0, [])\n return result\n\n\nfunction_list = [subsets]\n\n\nif __name__ == \"__main__\":\n num_list = [1, 2, 3]\n test_result('Number List', function_list, num_list)\n", "repo_name": "haeun87/Basic-Algorithm-Study", "sub_path": "python-algorithm-practice/graph/p37.py", "file_name": "p37.py", "file_ext": "py", "file_size_in_byte": 633, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.List", "line_number": 13, "usage_type": "name"}, {"api_name": "common.common_function.test_result", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "28503485152", "text": "import collections\nimport time\nimport warnings\nimport numpy as np\nfrom typing import Union\n\n# internal modules\nfrom geoarray import GeoArray\nfrom py_tools_ds.geo.map_info import mapinfo2geotransform, geotransform2mapinfo\nfrom py_tools_ds.geo.coord_grid import is_coord_grid_equal\nfrom py_tools_ds.geo.projection import prj_equal\nfrom py_tools_ds.geo.raster.reproject import warp_ndarray\nfrom py_tools_ds.numeric.vector import find_nearest\n\n__author__ = 'Daniel Scheffler'\n\n_dict_rspAlg_rsp_Int = {'nearest': 0, 'bilinear': 1, 'cubic': 2, 'cubic_spline': 3, 'lanczos': 4, 'average': 5,\n 'mode': 6, 'max': 7, 'min': 8, 'med': 9, 'q1': 10, 'q2': 11,\n 0: 'nearest', 1: 'bilinear', 2: 'cubic', 3: 'cubic_spline', 4: 'lanczos', 5: 'average',\n 6: 'mode', 7: 'max', 8: 'min', 9: 'med', 10: 'q1', 11: 'q2'}\n\n\nclass DESHIFTER(object):\n \"\"\"\n Class to deshift an image array or one of its products by applying previously the computed coregistration info.\n\n See help(DESHIFTER) for documentation.\n \"\"\"\n\n def __init__(self,\n im2shift: Union[GeoArray, str],\n coreg_results: dict,\n **kwargs\n ) -> None:\n \"\"\"Get an instance of DESHIFTER.\n\n :param im2shift:\n path of an image to be de-shifted or alternatively a GeoArray object\n\n :param dict coreg_results:\n the results of the co-registration as given by COREG.coreg_info or COREG_LOCAL.coreg_info\n\n :keyword int path_out:\n /output/directory/filename for coregistered results\n\n :keyword str fmt_out:\n raster file format for output file. ignored if path_out is None. can be any GDAL\n compatible raster file format (e.g. 'ENVI', 'GTIFF'; default: ENVI)\n\n :keyword list out_crea_options:\n GDAL creation options for the output image, e.g., [\"QUALITY=20\", \"REVERSIBLE=YES\", \"WRITE_METADATA=YES\"]\n\n :keyword int band2process:\n The index of the band to be processed within the given array (starts with 1),\n default = None (all bands are processed)\n\n :keyword float nodata:\n no data value of the image to be de-shifted\n\n :keyword float out_gsd:\n output pixel size in units of the reference coordinate system (default = pixel size of the input array),\n given values are overridden by match_gsd=True\n\n :keyword bool align_grids:\n True: align the input coordinate grid to the reference (does not affect the output pixel size as long as\n input and output pixel sizes are compatible (5:30 or 10:30 but not 4:30), default = False\n\n :keyword bool match_gsd:\n True: match the input pixel size to the reference pixel size, default = False\n\n :keyword list target_xyGrid:\n a list with an x-grid and a y-grid like [[15,45], [15,45]].\n This overrides 'out_gsd', 'align_grids' and 'match_gsd'.\n\n :keyword int min_points_local_corr:\n number of valid tie points, below which a global shift correction is performed instead of a local\n correction (global X/Y shift is then computed as the mean shift of the remaining points)\n (default: 5 tie points)\n\n :keyword str resamp_alg:\n the resampling algorithm to be used if neccessary\n (valid algorithms: nearest, bilinear, cubic, cubic_spline, lanczos, average, mode, max, min, med, q1, q3)\n\n :keyword bool cliptoextent:\n True: clip the input image to its actual bounds while deleting possible no data areas outside of the actual\n bounds, default = False\n\n :keyword list clipextent:\n xmin, ymin, xmax, ymax - if given the calculation of the actual bounds is skipped.\n The given coordinates are automatically snapped to the output grid.\n\n :keyword int CPUs:\n number of CPUs to use (default: None, which means 'all CPUs available')\n\n :keyword bool progress:\n show progress bars (default: True)\n\n :keyword bool v:\n verbose mode (default: False)\n\n :keyword bool q:\n quiet mode (default: False)\n \"\"\"\n # private attributes\n self._grids_alignable = None\n\n # store args / kwargs\n self.init_args = dict([x for x in locals().items() if x[0] != \"self\" and not x[0].startswith('__')])\n self.init_kwargs = self.init_args['kwargs']\n\n # unpack args\n self.im2shift = im2shift if isinstance(im2shift, GeoArray) else GeoArray(im2shift)\n self.GCPList = coreg_results['GCPList'] if 'GCPList' in coreg_results else None\n self.ref_gt = coreg_results['reference geotransform']\n self.ref_grid = coreg_results['reference grid']\n self.ref_prj = coreg_results['reference projection']\n\n # unpack kwargs\n self.path_out = kwargs.get('path_out', None)\n self.fmt_out = kwargs.get('fmt_out', 'ENVI')\n self.out_creaOpt = kwargs.get('out_crea_options', [])\n self.band2process = kwargs.get('band2process', None) # starts with 1 # FIXME why?\n self.band2process = \\\n self.band2process - 1 if self.band2process is not None else None # internally handled as band index\n self.nodata = kwargs.get('nodata', self.im2shift.nodata)\n self.align_grids = kwargs.get('align_grids', False)\n self.min_points_local_corr = kwargs.get('min_points_local_corr', 5)\n self.rspAlg = kwargs.get('resamp_alg', 'cubic') # TODO accept also integers\n self.cliptoextent = kwargs.get('cliptoextent', False)\n self.clipextent = kwargs.get('clipextent', None)\n self.CPUs = kwargs.get('CPUs', None)\n self.v = kwargs.get('v', False)\n self.q = kwargs.get('q', False) if not self.v else False # overridden by v\n self.progress = kwargs.get('progress', True) if not self.q else False # overridden by q\n\n self.im2shift.nodata = kwargs.get('nodata', self.im2shift.nodata)\n self.im2shift.q = self.q\n self.shift_prj = self.im2shift.projection\n self.shift_gt = list(self.im2shift.geotransform)\n\n # in case of local shift correction and local coreg results contain less points than min_points_local_corr:\n # force global correction based on mean X/Y shifts\n if 'GCPList' in coreg_results and len(coreg_results['GCPList']) < self.min_points_local_corr:\n warnings.warn('Only %s valid tie point(s) could be identified. A local shift correction is therefore not '\n 'reasonable and could cause artifacts in the output image. The target image is '\n 'corrected globally with the mean X/Y shift of %.3f/%.3f pixels.'\n % (len(self.GCPList), coreg_results['mean_shifts_px']['x'],\n coreg_results['mean_shifts_px']['y']))\n self.GCPList = None\n coreg_results['updated map info'] = coreg_results['updated map info means']\n\n # in case of global shift correction -> the updated map info from coreg_results already has the final map info\n # BUT: this will be updated in correct_shifts() if clipextent is given or warping is needed\n if not self.GCPList:\n mapI = coreg_results['updated map info']\n self.updated_map_info = mapI or geotransform2mapinfo(self.shift_gt, self.shift_prj)\n self.updated_gt = mapinfo2geotransform(self.updated_map_info) or self.shift_gt\n self.original_map_info = coreg_results['original map info']\n self.updated_projection = self.ref_prj\n\n self.out_grid = self._get_out_grid() # needs self.ref_grid, self.im2shift\n self.out_gsd = [abs(self.out_grid[0][1] - self.out_grid[0][0]),\n abs(self.out_grid[1][1] - self.out_grid[1][0])] # xgsd, ygsd\n\n # assertions\n assert self.rspAlg in _dict_rspAlg_rsp_Int.keys(), \\\n \"'%s' is not a supported resampling algorithm.\" % self.rspAlg\n if self.band2process is not None:\n assert self.im2shift.bands - 1 >= self.band2process >= 0, \\\n \"The %s '%s' has %s %s. So 'band2process' must be %s%s. Got %s.\" \\\n % (self.im2shift.__class__.__name__, self.im2shift.basename, self.im2shift.bands,\n 'bands' if self.im2shift.bands > 1 else 'band', 'between 1 and ' if self.im2shift.bands > 1 else '',\n self.im2shift.bands, self.band2process + 1)\n\n # set defaults for general class attributes\n self.is_shifted = False # this is not included in COREG.coreg_info\n self.is_resampled = False # this is not included in COREG.coreg_info\n self.tracked_errors = []\n self.arr_shifted = None # set by self.correct_shifts\n self.GeoArray_shifted = None # set by self.correct_shifts\n\n def _get_out_grid(self):\n # parse given params\n out_gsd = self.init_kwargs.get('out_gsd', None)\n match_gsd = self.init_kwargs.get('match_gsd', False)\n out_grid = self.init_kwargs.get('target_xyGrid', None)\n\n # assertions\n assert out_grid is None or (isinstance(out_grid, (list, tuple)) and len(out_grid) == 2)\n assert out_gsd is None or (isinstance(out_gsd, (int, tuple, list)) and len(out_gsd) == 2)\n\n ref_xgsd, ref_ygsd = (self.ref_grid[0][1] - self.ref_grid[0][0], abs(self.ref_grid[1][1] - self.ref_grid[1][0]))\n\n def get_grid(gt, xgsd, ygsd): return [[gt[0], gt[0] + xgsd], [gt[3], gt[3] - ygsd]]\n\n # get out_grid\n if out_grid:\n # output grid is given\n pass\n\n elif out_gsd:\n out_xgsd, out_ygsd = [out_gsd, out_gsd] if isinstance(out_gsd, int) else out_gsd\n\n if match_gsd and (out_xgsd, out_ygsd) != (ref_xgsd, ref_ygsd):\n warnings.warn(\"\\nThe parameter 'match_gsd is ignored because another output ground sampling distance \"\n \"was explicitly given.\")\n if self.align_grids and \\\n self._are_grids_alignable(self.im2shift.xgsd, self.im2shift.ygsd, out_xgsd, out_ygsd):\n # use grid of reference image with the given output gsd\n out_grid = get_grid(self.ref_gt, out_xgsd, out_ygsd)\n else: # no grid alignment\n # use grid of input image with the given output gsd\n out_grid = get_grid(self.im2shift.geotransform, out_xgsd, out_ygsd)\n\n elif match_gsd:\n if self.align_grids:\n # use reference grid\n out_grid = self.ref_grid\n else:\n # use grid of input image and reference gsd\n out_grid = get_grid(self.im2shift.geotransform, ref_xgsd, ref_ygsd)\n\n else:\n if self.align_grids and \\\n self._are_grids_alignable(self.im2shift.xgsd, self.im2shift.ygsd, ref_xgsd, ref_ygsd):\n # use origin of reference image and gsd of input image\n out_grid = get_grid(self.ref_gt, self.im2shift.xgsd, self.im2shift.ygsd)\n else:\n if not self.GCPList:\n # in case of global co-registration:\n # -> use the target image grid but update the origin (shift-correction without resampling)\n out_grid = get_grid(self.updated_gt, self.im2shift.xgsd, self.im2shift.ygsd)\n else:\n # in case of local co-registration:\n # -> use input image grid\n out_grid = get_grid(self.im2shift.geotransform, self.im2shift.xgsd, self.im2shift.ygsd)\n\n return out_grid\n\n @property\n def warping_needed(self):\n \"\"\"Return True if image warping is needed in consideration of the input parameters of DESHIFTER.\"\"\"\n assert self.out_grid, 'Output grid must be calculated before.'\n equal_prj = prj_equal(self.ref_prj, self.shift_prj)\n return \\\n False if (equal_prj and not self.GCPList and is_coord_grid_equal(self.updated_gt, *self.out_grid)) else True\n\n def _are_grids_alignable(self, in_xgsd, in_ygsd, out_xgsd, out_ygsd):\n \"\"\"Check if the input image pixel grid is alignable to the output grid.\n\n :param in_xgsd:\n :param in_ygsd:\n :param out_xgsd:\n :param out_ygsd:\n :return:\n \"\"\"\n if self._grids_alignable is None:\n def is_alignable(gsd1, gsd2):\n \"\"\"Check if pixel sizes are divisible.\"\"\"\n return max(gsd1, gsd2) % min(gsd1, gsd2) == 0\n\n self._grids_alignable = \\\n False if (not is_alignable(in_xgsd, out_xgsd) or not is_alignable(in_ygsd, out_ygsd)) else True\n\n if self._grids_alignable is False and not self.q:\n warnings.warn(\"\\nThe coordinate grid of %s cannot be aligned to the desired grid because their pixel \"\n \"sizes are not exact multiples of each other (input [X/Y]: %s/%s; desired [X/Y]: %s/%s). \"\n \"Therefore the original grid is chosen for the resampled output image. If you don´t like \"\n \"that you can use the 'out_gsd' or 'match_gsd' parameters to set an appropriate output \"\n \"pixel size or to allow changing the pixel size.\\n\"\n % (self.im2shift.basename, in_xgsd, in_ygsd, out_xgsd, out_ygsd))\n\n return self._grids_alignable\n\n def _get_out_extent(self):\n if self.clipextent is None:\n # no clip extent has been given\n if self.cliptoextent:\n # use actual image corners as clip extent\n self.clipextent = self.im2shift.footprint_poly.envelope.bounds\n else:\n # use outer bounds of the image as clip extent\n xmin, xmax, ymin, ymax = self.im2shift.box.boundsMap\n self.clipextent = xmin, ymin, xmax, ymax\n\n # snap clipextent to output grid\n # (in case of odd input coords the output coords are moved INSIDE the input array)\n xmin, ymin, xmax, ymax = self.clipextent\n x_tol, y_tol = float(np.ptp(self.out_grid[0]) / 2000), float(np.ptp(self.out_grid[1]) / 2000) # 2.000th pix\n xmin = find_nearest(self.out_grid[0], xmin, roundAlg='on', extrapolate=True, tolerance=x_tol)\n ymin = find_nearest(self.out_grid[1], ymin, roundAlg='on', extrapolate=True, tolerance=y_tol)\n xmax = find_nearest(self.out_grid[0], xmax, roundAlg='off', extrapolate=True, tolerance=x_tol)\n ymax = find_nearest(self.out_grid[1], ymax, roundAlg='off', extrapolate=True, tolerance=y_tol)\n return xmin, ymin, xmax, ymax\n\n def correct_shifts(self) -> collections.OrderedDict:\n if not self.q:\n print('Correcting geometric shifts...')\n\n t_start = time.time()\n\n if not self.warping_needed:\n \"\"\"NO RESAMPLING NEEDED\"\"\"\n\n self.is_shifted = True\n self.is_resampled = False\n xmin, ymin, xmax, ymax = self._get_out_extent()\n\n if not self.q:\n print(\"NOTE: The detected shift is corrected by updating the map info of the target image only, i.e., \"\n \"without any resampling. Set the 'align_grids' parameter to True if you need the target and the \"\n \"reference coordinate grids to be aligned.\")\n\n if self.cliptoextent:\n # TODO validate results\n # TODO -> output extent does not seem to be the requested one! (only relevant if align_grids=False)\n # get shifted array\n shifted_geoArr = GeoArray(self.im2shift[:], tuple(self.updated_gt), self.shift_prj)\n\n # clip with target extent\n # NOTE: get_mapPos() does not perform any resampling as long as source and target projection are equal\n self.arr_shifted, self.updated_gt, self.updated_projection = \\\n shifted_geoArr.get_mapPos((xmin, ymin, xmax, ymax),\n self.shift_prj,\n fillVal=self.nodata,\n band2get=self.band2process)\n\n self.updated_map_info = geotransform2mapinfo(self.updated_gt, self.updated_projection)\n\n else:\n # array keeps the same; updated gt and prj are taken from coreg_info\n self.arr_shifted = self.im2shift[:, :, self.band2process] \\\n if self.band2process is not None else self.im2shift[:]\n\n out_geoArr = GeoArray(self.arr_shifted, self.updated_gt, self.updated_projection, q=self.q)\n out_geoArr.nodata = self.nodata # equals self.im2shift.nodata after __init__()\n out_geoArr.metadata = self.im2shift.metadata[[self.band2process]] \\\n if self.band2process is not None else self.im2shift.metadata\n\n self.GeoArray_shifted = out_geoArr\n\n else: # FIXME equal_prj==False ist noch NICHT implementiert\n \"\"\"RESAMPLING NEEDED\"\"\"\n # FIXME avoid reading the whole band if clip_extent is passed\n\n in_arr = self.im2shift[:, :, self.band2process] \\\n if self.band2process is not None and self.im2shift.ndim == 3 else self.im2shift[:]\n\n if not self.GCPList:\n # apply XY-shifts to input image gt 'shift_gt' in order to correct the shifts before warping\n self.shift_gt[0], self.shift_gt[3] = self.updated_gt[0], self.updated_gt[3]\n\n # get resampled array\n out_arr, out_gt, out_prj = \\\n warp_ndarray(in_arr, self.shift_gt, self.shift_prj, self.ref_prj,\n rspAlg=_dict_rspAlg_rsp_Int[self.rspAlg],\n in_nodata=self.nodata,\n out_nodata=self.nodata,\n out_gsd=self.out_gsd,\n out_bounds=self._get_out_extent(), # always returns an extent snapped to the target grid\n gcpList=self.GCPList,\n # polynomialOrder=str(3),\n # options='-refine_gcps 500 1.9',\n # warpOptions=['-refine_gcps 500 1.9'],\n # options='-wm 10000',# -order 3',\n # options=['-order 3'],\n # options=['GDAL_CACHEMAX 800 '],\n # warpMemoryLimit=125829120, # 120MB\n CPUs=self.CPUs,\n progress=self.progress,\n q=self.q)\n\n out_geoArr = GeoArray(out_arr, out_gt, out_prj, q=self.q)\n out_geoArr.nodata = self.nodata # equals self.im2shift.nodata after __init__()\n out_geoArr.metadata = self.im2shift.metadata[[self.band2process]] \\\n if self.band2process is not None else self.im2shift.metadata\n\n self.arr_shifted = out_arr\n self.updated_gt = out_gt\n self.updated_projection = out_prj\n self.updated_map_info = geotransform2mapinfo(out_gt, out_prj)\n self.GeoArray_shifted = out_geoArr\n self.is_shifted = True\n self.is_resampled = True\n\n if self.path_out:\n out_geoArr.save(self.path_out, fmt=self.fmt_out, creationOptions=self.out_creaOpt)\n\n # validation\n if not is_coord_grid_equal(self.updated_gt, *self.out_grid, tolerance=1.e8):\n raise RuntimeError('DESHIFTER output dataset has not the desired target pixel grid. Target grid '\n 'was %s. Output geotransform is %s.' % (str(self.out_grid), str(self.updated_gt)))\n # TODO to be continued (extent, map info, ...)\n\n if self.v:\n print('Time for shift correction: %.2fs' % (time.time() - t_start))\n return self.deshift_results\n\n @property\n def deshift_results(self):\n deshift_results = collections.OrderedDict()\n deshift_results.update({\n 'band': self.band2process,\n 'is shifted': self.is_shifted,\n 'is resampled': self.is_resampled,\n 'updated map info': self.updated_map_info,\n 'updated geotransform': self.updated_gt,\n 'updated projection': self.updated_projection,\n 'arr_shifted': self.arr_shifted,\n 'GeoArray_shifted': self.GeoArray_shifted\n })\n return deshift_results\n\n\ndef deshift_image_using_coreg_info(im2shift: Union[GeoArray, str],\n coreg_results: dict,\n path_out: str = None,\n fmt_out: str = 'ENVI',\n q: bool = False):\n \"\"\"Correct a geometrically distorted image using previously calculated coregistration info.\n\n This function can be used for example to correct spatial shifts of mask files using the same transformation\n parameters that have been used to correct their source images.\n\n :param im2shift: path of an image to be de-shifted or alternatively a GeoArray object\n :param coreg_results: the results of the co-registration as given by COREG.coreg_info or\n COREG_LOCAL.coreg_info respectively\n :param path_out: /output/directory/filename for coregistered results. If None, no output is written - only\n the shift corrected results are returned.\n :param fmt_out: raster file format for output file. ignored if path_out is None. can be any GDAL\n compatible raster file format (e.g. 'ENVI', 'GTIFF'; default: ENVI)\n :param q: quiet mode (default: False)\n :return:\n \"\"\"\n deshift_results = DESHIFTER(im2shift, coreg_results).correct_shifts()\n\n if path_out:\n deshift_results['GeoArray_shifted'].save(path_out, fmt_out=fmt_out, q=q)\n\n return deshift_results\n", "repo_name": "GFZ/arosics", "sub_path": "arosics/DeShifter.py", "file_name": "DeShifter.py", "file_ext": "py", "file_size_in_byte": 22133, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 107, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.Union", "line_number": 31, "usage_type": "name"}, {"api_name": "geoarray.GeoArray", "line_number": 31, "usage_type": "name"}, {"api_name": "geoarray.GeoArray", "line_number": 112, "usage_type": "argument"}, {"api_name": "warnings.warn", "line_number": 144, "usage_type": "call"}, {"api_name": "py_tools_ds.geo.map_info.geotransform2mapinfo", "line_number": 156, "usage_type": "call"}, {"api_name": "py_tools_ds.geo.map_info.mapinfo2geotransform", "line_number": 157, "usage_type": "call"}, {"api_name": "warnings.warn", "line_number": 205, "usage_type": "call"}, {"api_name": "py_tools_ds.geo.projection.prj_equal", "line_number": 244, "usage_type": "call"}, {"api_name": "py_tools_ds.geo.coord_grid.is_coord_grid_equal", "line_number": 246, "usage_type": "call"}, {"api_name": "warnings.warn", "line_number": 266, "usage_type": "call"}, {"api_name": "numpy.ptp", "line_number": 289, "usage_type": "call"}, {"api_name": "py_tools_ds.numeric.vector.find_nearest", "line_number": 290, "usage_type": "call"}, {"api_name": "py_tools_ds.numeric.vector.find_nearest", "line_number": 291, "usage_type": "call"}, {"api_name": "py_tools_ds.numeric.vector.find_nearest", "line_number": 292, "usage_type": "call"}, {"api_name": "py_tools_ds.numeric.vector.find_nearest", "line_number": 293, "usage_type": "call"}, {"api_name": "time.time", "line_number": 300, "usage_type": "call"}, {"api_name": "geoarray.GeoArray", "line_number": 318, "usage_type": "call"}, {"api_name": "py_tools_ds.geo.map_info.geotransform2mapinfo", "line_number": 328, "usage_type": "call"}, {"api_name": "geoarray.GeoArray", "line_number": 335, "usage_type": "call"}, {"api_name": "py_tools_ds.geo.raster.reproject.warp_ndarray", "line_number": 355, "usage_type": "call"}, {"api_name": "geoarray.GeoArray", "line_number": 373, "usage_type": "call"}, {"api_name": "py_tools_ds.geo.map_info.geotransform2mapinfo", "line_number": 381, "usage_type": "call"}, {"api_name": "py_tools_ds.geo.coord_grid.is_coord_grid_equal", "line_number": 390, "usage_type": "call"}, {"api_name": "time.time", "line_number": 396, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 296, "usage_type": "attribute"}, {"api_name": "collections.OrderedDict", "line_number": 401, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 415, "usage_type": "name"}, {"api_name": "geoarray.GeoArray", "line_number": 415, "usage_type": "name"}]} +{"seq_id": "41338381689", "text": "from collections import OrderedDict, defaultdict, deque, Counter\nimport argparse\nimport dateutil.parser\nimport pathlib\nimport logging\nimport gzip\nimport json\nfrom math import sqrt\nfrom tqdm import tqdm\n\nimport pandas as pd\nimport numpy as np\nfrom scipy.optimize import curve_fit\n\nimport nltk\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\n\nnltk.download('puncts')\nnltk.download('stopwords')\nnltk.download('words')\n\ndef calcEntropy(path, nodepath, start_date, end_date, out_path):\n logging.info(f'Reading node file')\n with open(nodepath, 'r') as f:\n twt_nodes = f.read().strip().split('\\n')\n idx = pd.date_range(pd.to_datetime(start_date), pd.to_datetime(end_date) - pd.Timedelta(days=1))\n \n logging.info(f'Reading news articles')\n json_data = []\n with open(path, 'r') as f:\n for l in f:\n tmp = json.loads(l)\n try:\n if pd.to_datetime(tmp['date']) >= pd.to_datetime(start_date) and pd.to_datetime(tmp['date']) < pd.to_datetime(end_date):\n json_data.append(tmp)\n except:\n pass\n\n logging.info(f'Counting')\n articles = defaultdict(lambda: defaultdict(dict))\n for r in tqdm(json_data):\n if r['Leidos_infoids'] is not None and r['phrased_article'] is not None and r['phrased_article'] != '':\n for infoid in r['Leidos_infoids']:\n if r['phrased_title'] not in articles[infoid][pd.to_datetime(r['date']).date()]:\n articles[infoid][pd.to_datetime(r['date']).date()][r['phrased_title']] = [1, r['phrased_article']]\n else:\n articles[infoid][pd.to_datetime(r['date']).date()][r['phrased_title']][0] += 1\n\n logging.info(f'Calculating frequencies')\n tokens = defaultdict(dict)\n for k, v in articles.items():\n for kk, vv in tqdm(v.items(), total=len(v)):\n tokens[k][kk] = word_tokenize(' '.join([' '.join([vvv[1]] * int(sqrt(vvv[0]))) for vvv in vv.values()]))\n\n stop_words = set(stopwords.words('english') + pd.read_csv('news_stop.csv').term.to_list()) \n words = set(nltk.corpus.words.words())\n\n ctss = defaultdict(dict)\n for k, v in tokens.items():\n for kk, vv in tqdm(v.items(), total=len(v)):\n ctss[k][kk] = nltk.FreqDist([vvv.lower() for vvv in vv if len(vvv) > 3 and vvv.lower() not in stop_words and vvv.lower() in words])\n\n def recifunc(x, s, c):\n return (1 / np.power(x, s)) / np.sum([1 / np.power(i, s) for i in range(1, 101)]) + c\n\n logging.info(f'Fitting Zipf curve')\n etps2 = defaultdict(dict)\n for k1, v1 in ctss.items():\n for k, v in sorted(v1.items()):\n try:\n tmp = v.most_common(100)\n s = sum([x[1] for x in tmp])\n ps0 = [x[1] for x in tmp]\n ps = [x[1] / s for x in tmp]\n popt, pcov = curve_fit(recifunc, np.linspace(1, len(ps), len(ps)), ps)\n etps2[k1][k] = popt[0]\n except:\n print(k1, k, tmp)\n\n for k, v in etps2.items():\n if len(v) == 0:\n logging.info(f'\"{k}\" is empty')\n\n etps2_df = {}\n for k, v in etps2.items():\n tmpmean = np.mean(list(v.values()))\n tmp = pd.Series(v, dtype=float).reindex(idx, fill_value=tmpmean)\n tmp[tmp < 1e-3] = tmpmean\n etps2_df[k] =tmp\n\n for k in set(twt_nodes) - set(etps2_df.keys()):\n etps2_df[k] = pd.Series(dtype=float).reindex(idx, fill_value=1)\n\n logging.info(f'Writing to file')\n etps2_df_json = {k: v.to_json() for k, v in etps2_df.items()}\n with open(out_path, 'w') as f:\n f.write(json.dumps(etps2_df_json))\n \ndef main(args):\n calcEntropy(args.path, args.nodes, args.startdate, args.enddate, args.out)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Extract Zipf timeseries from annotated news articles.')\n parser.add_argument('-i', '--path', required=True, type=str, help='Path to the annotated news articles (.json)')\n parser.add_argument('-n', '--nodes', required=True, type=str, help='Path to the node file (.txt)')\n parser.add_argument('-s', '--startdate', required=True, type=dateutil.parser.isoparse, help='The Start Date (format YYYY-MM-DD)')\n parser.add_argument('-e', '--enddate', required=True, type=dateutil.parser.isoparse, help='The End Date (format YYYY-MM-DD (Exclusive))')\n parser.add_argument('-o', '--out', required=True, type=str, help='Path to save the Zipf timeseries (.json)')\n args = parser.parse_args()\n for arg in vars(args):\n print(f'{arg} = {getattr(args, arg)}')\n logging.basicConfig(level=logging.INFO)\n main(args)\n", "repo_name": "shj1987/DARPA-Predict-Model", "sub_path": "misc/entropy.py", "file_name": "entropy.py", "file_ext": "py", "file_size_in_byte": 4684, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "nltk.download", "line_number": 19, "usage_type": "call"}, {"api_name": "nltk.download", "line_number": 20, "usage_type": "call"}, {"api_name": "nltk.download", "line_number": 21, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 24, "usage_type": "call"}, {"api_name": "pandas.date_range", "line_number": 27, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 27, "usage_type": "call"}, {"api_name": "pandas.Timedelta", "line_number": 27, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 29, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 33, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 35, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 40, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 41, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 42, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 45, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 46, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 48, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 50, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 51, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 53, "usage_type": "call"}, {"api_name": "nltk.tokenize.word_tokenize", "line_number": 54, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 54, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 56, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 56, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 56, "usage_type": "call"}, {"api_name": "nltk.corpus.words.words", "line_number": 57, "usage_type": "call"}, {"api_name": "nltk.corpus", "line_number": 57, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 59, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 61, "usage_type": "call"}, {"api_name": "nltk.FreqDist", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 65, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 67, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 68, "usage_type": "call"}, {"api_name": "scipy.optimize.curve_fit", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 76, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 87, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 88, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 93, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 95, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 98, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 104, "usage_type": "call"}, {"api_name": "dateutil.parser.parser", "line_number": 107, "usage_type": "attribute"}, {"api_name": "dateutil.parser", "line_number": 107, "usage_type": "name"}, {"api_name": "dateutil.parser.parser", "line_number": 108, "usage_type": "attribute"}, {"api_name": "dateutil.parser", "line_number": 108, "usage_type": "name"}, {"api_name": "logging.basicConfig", "line_number": 113, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 113, "usage_type": "attribute"}]} +{"seq_id": "30535976528", "text": "\"\"\"\nHomework4.\nReplace 'pass' by your implementation.\n\"\"\"\n\n# Insert your package here\nfrom re import A\nimport numpy as np\nfrom numpy.lib.shape_base import apply_along_axis\nfrom util import refineF\nimport scipy.linalg\nimport scipy.ndimage\nimport cv2\n\n'''\nQ2.1: Eight Point Algorithm\n Input: pts1, Nx2 Matrix\n pts2, Nx2 Matrix\n M, a scalar parameter computed as max (imwidth, imheight)\n Output: F, the fundamental matrix\n'''\ndef eightpoint(pts1, pts2, M):\n # Replace pass by your implementatptsion\n U = np.empty((pts1.shape[0],9)) \n scale = [[1/M, 0, 0], [0, 1/M, 0], [0, 0, 1]]\n ones = np.ones((pts1.shape[0],1))\n aug_pts1 = np.hstack((pts1, ones))\n aug_pts2 = np.hstack((pts2, ones))\n \n norm_pts1 = scale @ aug_pts1.T\n norm_pts2 = scale @ aug_pts2.T\n\n for i in range(pts1.shape[0]):\n x1 = norm_pts1[0, i]\n y1 = norm_pts1[1, i]\n x2 = norm_pts2[0, i]\n y2 = norm_pts2[1, i]\n\n a = np.array([x1*x2, y1*x2, x2, x1*y2, y1*y2, y2, x1, y1, 1])\n U[i, :] = a\n \n u, sig, f_temp = scipy.linalg.svd(U)\n f = f_temp[-1, :]\n norm_F = f.reshape((3,3))\n F = np.transpose(scale) @ norm_F @ scale\n\n F = refineF(F, pts1, pts2)\n \n np.savez(\"../data/q2_1.npz\", F, M)\n\n return F\n\n\n\n'''\nQ3.1: Compute the essential matrix E.\n Input: F, fundamental matrix\n K1, internal camera calibration matrix of camera 1\n K2, internal camera calibration matrix of camera 2\n Output: E, the essential matrix\n'''\n\ndef essentialMatrix(F, K1, K2):\n # Replace pass by your implementation\n \n E = K1.T @ F @ K2\n\n\n np.savez(\"../data/q3_1.npz\", E)\n return E\n\n\n'''\nQ3.2: Triangulate a set of 2D coordinates in the image to a set of 3D points.\n Input: C1, the 3x4 camera matrix\n pts1, the Nx2 matrix with the 2D image coordinates per row\n C2, the 3x4 camera matrix\n pts2, the Nx2 matrix with the 2D image coordinates per row\n Output: P, the Nx3 matrix with the corresponding 3D points per row\n err, the reprojection error.\n'''\ndef triangulate(C1, pts1, C2, pts2):\n wpts = np.empty((pts1.shape[0],4))\n w = np.empty((pts1.shape[0],3))\n err1 = 0\n err2 = 0\n err = 0 \n\n for i in range(pts1.shape[0]):\n x1 = pts1[i, 0]\n y1 = pts1[i, 1]\n x2 = pts2[i, 0]\n y2 = pts2[i, 1]\n\n a = [C1[0,0]-C1[2,0]*x1, C1[0,1]-C1[2,1]*x1, C1[0,2]-C1[2,2]*x1, C1[0,3]-C1[2,3]*x1] \n b = [-C1[1,0]+C1[2,0]*y1, -C1[1,1]+C1[2,1]*y1, -C1[1,2]+C1[2,2]*y1, -C1[1,3]+C1[2,3]*y1]\n c = [C2[0,0]-C2[2,0]*x2, C2[0,1]-C2[2,1]*x2, C2[0,2]-C2[2,2]*x2, C2[0,3]-C2[2,3]*x2]\n d = [-C2[1,0]+C2[2,0]*y2, -C2[1,1]+C2[2,1]*y2, -C2[1,2]+C2[2,2]*y2, -C2[1,3]+C2[2,3]*y2]\n\n A = np.vstack((a,b,c,d))\n \n u, sig, c_temp = scipy.linalg.svd(A)\n wpts[i] = c_temp[-1, :] \n \n pts1_hat = C1 @ wpts[i]\n pts2_hat = C2 @ wpts[i]\n \n x1_hat = pts1_hat[0]/pts1_hat[2]\n y1_hat = pts1_hat[1]/pts1_hat[2]\n x2_hat = pts2_hat[0]/pts2_hat[2]\n y2_hat = pts2_hat[1]/pts2_hat[2]\n\n err1 += (pts1[i, 0] - x1_hat)**2 + (pts1[i, 1] - y1_hat)**2\n err2 += (pts2[i, 0] - x2_hat)**2 + (pts2[i, 1] - y2_hat)**2\n err = err1 + err2\n\n Px = wpts[i,0]/wpts[i,3]\n Py = wpts[i,1]/wpts[i,3]\n Pz = wpts[i,2]/wpts[i,3]\n\n w[i, 0] = Px\n w[i, 1] = Py\n w[i, 2] = Pz\n # print(A)\n # print(\"stop\")\n return w, err\n \n'''\nQ4.1: 3D visualization of the temple images.\n Input: im1, the first image\n im2, the second image\n F, the fundamental matrix\n x1, x-coordinates of a pixel on im1\n y1, y-coordinates of a pixel on im1\n Output: x2, x-coordinates of the pixel on im2\n y2, y-coordinates of the pixel on im2\n'''\n\ndef epipolarCorrespondence(im1, im2, F, x1, y1):\n # Replace pass by your implementation\n ones = np.ones((x1.shape[0],1))\n pts_im1 = np.transpose(np.hstack((x1, y1, ones)))\n temp = F @ pts_im1\n A = temp[0,:]\n B = temp[1,:]\n C = temp[2,:]\n # eplin = A*x2 + B*y2 + C = 0\n im1g = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY)\n im2g = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY)\n \n PATCH_SIZE = 40\n im2_y2 = np.arange(im2g.shape[0]+PATCH_SIZE) \n pad_im2g = np.pad(im2g, PATCH_SIZE)\n x2 = np.empty((x1.shape[0],1))\n y2 = np.empty((y1.shape[0],1))\n\n L= PATCH_SIZE*2\n SIGMA = 5 \n ax = np.linspace(-(L - 1) / 2., (L - 1) / 2., L)\n gauss = np.exp(-0.5 * np.square(ax) / np.square(SIGMA))\n kernel = np.outer(gauss, gauss)\n kernel = kernel / np.sum(kernel)\n\n \n for i in range(x1.shape[0]):\n x1min = np.asscalar(x1[i] - PATCH_SIZE)\n x1max = np.asscalar(x1[i] + PATCH_SIZE)\n y1min = np.asscalar(y1[i] - PATCH_SIZE)\n y1max = np.asscalar(y1[i] + PATCH_SIZE)\n im1g_patch = kernel*im1g[y1min:y1max, x1min:x1max]\n # print(\"stop\")\n ERRORMIN = 999999999999999\n ref = np.asscalar(y1[i])\n for j in range(ref-50, ref+50):\n im2_x2 = (-B[i]*im2_y2[j+PATCH_SIZE] - C[i])/A[i]\n im2_x2 = (np.rint(im2_x2)).astype(int)\n x2min = np.asscalar(im2_x2 - PATCH_SIZE)\n x2max = np.asscalar(im2_x2 + PATCH_SIZE)\n y2min = np.asscalar(im2_y2[j+PATCH_SIZE] - PATCH_SIZE)\n y2max = np.asscalar(im2_y2[j+PATCH_SIZE] + PATCH_SIZE)\n im2g_patch = kernel*pad_im2g[y2min:y2max, x2min:x2max]\n error = np.sum((im1g_patch - im2g_patch)**2)\n # print(im2_x2)\n \n if error < ERRORMIN:\n ERRORMIN = error\n x2[i] = (im2_x2).astype(int)\n y2[i] = (im2_y2[j+PATCH_SIZE]).astype(int)\n # print(i)\n # print(\"x2: \"+ str(x2[i]))\n # print(\"y2: \"+ str(y2[i]))\n \n # print(\"stop\")\n return x2, y2\n'''\nQ5.1: Extra Credit RANSAC method.\n Input: pts1, Nx2 Matrix\n pts2, Nx2 Matrix\n M, a scaler parameter\n Output: F, the fundamental matrix\n inliers, Nx1 bool vector set to true for inliers\n'''\ndef ransacF(pts1, pts2, M, nIters=1000, tol=0.42):\n # Replace pass by your implementation\n pass\n\n'''\nQ5.2:Extra Credit Rodrigues formula.\n Input: r, a 3x1 vector\n Output: R, a rotation matrix\n'''\ndef rodrigues(r):\n # Replace pass by your implementation\n pass\n\n'''\nQ5.2:Extra Credit Inverse Rodrigues formula.\n Input: R, a rotation matrix\n Output: r, a 3x1 vector\n'''\ndef invRodrigues(R):\n # Replace pass by your impplementation\n pass\n\n'''\nQ5.3: Extra Credit Rodrigues residual.\n Input: K1, the intrinsics of camera 1\n M1, the extrinsics of camera 1\n p1, the 2D coordinates of points in image 1\n K2, the intrinsics of camera 2\n p2, the 2D coordinates of points in image 2\n x, the flattened concatenationg of P, r2, and t2.\n Output: residuals, 4N x 1 vector, the difference between original and estimated projections\n'''\ndef rodriguesResidual(K1, M1, p1, K2, p2, x):\n # Replace pass by your implementation\n pass\n\n'''\nQ5.3 Extra Credit Bundle adjustment.\n Input: K1, the intrinsics of camera 1\n M1, the extrinsics of camera 1\n p1, the 2D coordinates of points in image 1\n K2, the intrinsics of camera 2\n M2_init, the initial extrinsics of camera 1\n p2, the 2D coordinates of points in image 2\n P_init, the initial 3D coordinates of points\n Output: M2, the optimized extrinsics of camera 1\n P2, the optimized 3D coordinates of points\n'''\ndef bundleAdjustment(K1, M1, p1, K2, M2_init, p2, P_init):\n # Replace pass by your implementation\n pass\n", "repo_name": "brucekimrokcmu/Computer-Vision-A", "sub_path": "binocular_stereo/submission.py", "file_name": "submission.py", "file_ext": "py", "file_size_in_byte": 7807, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.empty", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 39, "usage_type": "call"}, {"api_name": "scipy.linalg.linalg.svd", "line_number": 42, "usage_type": "call"}, {"api_name": "scipy.linalg.linalg", "line_number": 42, "usage_type": "attribute"}, {"api_name": "scipy.linalg", "line_number": 42, "usage_type": "name"}, {"api_name": "numpy.transpose", "line_number": 45, "usage_type": "call"}, {"api_name": "util.refineF", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.savez", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.savez", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 84, "usage_type": "call"}, {"api_name": "re.A", "line_number": 100, "usage_type": "name"}, {"api_name": "numpy.vstack", "line_number": 100, "usage_type": "call"}, {"api_name": "scipy.linalg.linalg.svd", "line_number": 102, "usage_type": "call"}, {"api_name": "re.A", "line_number": 102, "usage_type": "argument"}, {"api_name": "scipy.linalg.linalg", "line_number": 102, "usage_type": "attribute"}, {"api_name": "scipy.linalg", "line_number": 102, "usage_type": "name"}, {"api_name": "numpy.ones", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 142, "usage_type": "call"}, {"api_name": "re.A", "line_number": 144, "usage_type": "name"}, {"api_name": "cv2.cvtColor", "line_number": 148, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 148, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 149, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 149, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 153, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 159, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 160, "usage_type": "call"}, {"api_name": "numpy.square", "line_number": 160, "usage_type": "call"}, {"api_name": "numpy.outer", "line_number": 161, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.asscalar", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.asscalar", "line_number": 167, "usage_type": "call"}, {"api_name": "numpy.asscalar", "line_number": 168, "usage_type": "call"}, {"api_name": "numpy.asscalar", "line_number": 169, "usage_type": "call"}, {"api_name": "numpy.asscalar", "line_number": 173, "usage_type": "call"}, {"api_name": "re.A", "line_number": 175, "usage_type": "name"}, {"api_name": "numpy.rint", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.asscalar", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.asscalar", "line_number": 178, "usage_type": "call"}, {"api_name": "numpy.asscalar", "line_number": 179, "usage_type": "call"}, {"api_name": "numpy.asscalar", "line_number": 180, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 182, "usage_type": "call"}]} +{"seq_id": "6796390280", "text": "from datetime import date\nprint (\"Calculate Age in Second\")\ninp = input(\"Would you like calculate how many seconds have you been alive: Y / N \")\nif inp == \"Y\":\n print (\"How old are you?\")\n\n year = int(input(\"What year were you born in?:\"))\n month = int(input(\"What month were you born in? (write a number):\")) \n day= int(input(\"What day were you born in?:\"))\n your_birthday = date(year, month, day)\n print (your_birthday)\n today = date.today()\n print (today)\n age_days = today - your_birthday\n age_days = age_days.days\n print (\"you are {} days old.\".format(age_days))\n age_seconds=age_days*86400\n print (\"You are abour {} second old.\".format(age_seconds))\nelif inp == \"N\":\n print (\":( bye\")\n", "repo_name": "karkitko/python-learning-mini-projects", "sub_path": "CalculateAgeInSecond.py", "file_name": "CalculateAgeInSecond.py", "file_ext": "py", "file_size_in_byte": 733, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "datetime.date", "line_number": 10, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 12, "usage_type": "name"}]} +{"seq_id": "22522259492", "text": "from django.db import models\nfrom django.utils import timezone\n\nWOWCLASSES = ( \n ('DK', 'Death Knight'),\n ('DH', 'Demon Hunter'),\n ('MON', 'Monk'),\n ('SHA', 'Shaman'),\n ('PAL', 'Paladin'),\n ('PRI', 'Priest'),\n ('HUN', 'Hunter')\n)\n\nclass Post(models.Model):\n author = models.ForeignKey('auth.User')\n title = models.CharField(max_length=200)\n text = models.TextField()\n created_date = models.DateTimeField(\n default=timezone.now)\n published_date = models.DateTimeField(\n blank=True, null=True)\n wowclass = models.CharField(max_length=3, choices=WOWCLASSES, default='')\n\n def publish(self):\n self.published_date = timezone.now()\n self.save()\n\n def __str__(self):\n return self.title\n\n", "repo_name": "catalinabase/my-first-blog", "sub_path": "blog/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 769, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.db.models.Model", "line_number": 14, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 14, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 15, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 15, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 16, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 16, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 17, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 17, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 18, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 19, "usage_type": "attribute"}, {"api_name": "django.utils.timezone", "line_number": 19, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 20, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 20, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 22, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 22, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 25, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 25, "usage_type": "name"}]} +{"seq_id": "43733455623", "text": "\"\"\"\nWordleをseleniumで自動入力するファイル\n\"\"\"\n\nfrom settings import WORDLE_URL, WORDLE_ANSWER_TEXT\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom chrome import chrome_browser\nfrom edge import edge_browser\nimport time\nimport pandas as pd\nimport sys\n\n\nclass WordListEmptyError(Exception):\n \"\"\"入力単語候補がなくなったことを知らせる例外クラス\"\"\"\n pass\n\n\ndef generate_df_row():\n \"\"\"dfのrowをyieldして返す\"\"\"\n with open(WORDLE_ANSWER_TEXT, \"r\") as f:\n for word in f:\n word = word.strip()\n yield [word[0], word[1], word[2], word[3], word[4], word]\n\n\ndef create_df():\n \"\"\"dfを作成\"\"\"\n cols = ['char_1', 'char_2', 'char_3', 'char_4', 'char_5', 'char_full']\n values = [row for row in generate_df_row()]\n return pd.DataFrame(values, columns=cols)\n\n\ndef filter_correct(df, col_name, char):\n \"\"\"緑ヒントの時のフィルタ\"\"\"\n return df[df[col_name].str.contains(char)]\n\n\ndef filter_present(df, col_name, char):\n \"\"\"黄色ヒントの時のフィルタ\"\"\"\n df = df[~df[col_name].str.contains(char)]\n return df[df['char_full'].str.contains(char)]\n\n\ndef filter_absent(df, char):\n \"\"\"灰色ヒントの時のフィルタ\"\"\"\n return df[~df['char_full'].str.contains(char)]\n\n\ndef guess_word(df):\n \"\"\"\n dfから単語を返す\n todo ここで一番答えに近づく単語を返したい\n \"\"\"\n word = df['char_full'].values[0]\n return word\n\n\ndef open_wordle(browser):\n \"\"\"wordleページを開く処理\"\"\"\n browser.get(WORDLE_URL)\n # ここでモーダルが出現するのでちょっと待つ\n time.sleep(.5)\n # 一回クリックしてモーダルを消す\n elm = browser.find_element(By.CSS_SELECTOR, \"body\")\n elm.click()\n time.sleep(.5)\n\n\ndef find_game_rows(browser):\n \"\"\"game row elementsを返す\"\"\"\n host = browser.find_element(By.TAG_NAME, \"game-app\")\n board = browser.execute_script(\"return arguments[0].shadowRoot.getElementById('board')\", host)\n return board.find_elements(By.TAG_NAME, 'game-row')\n\n\ndef find_game_tiles(browser, game_row):\n \"\"\"タイル(文字入力マス)を返す\"\"\"\n row = browser.execute_script(\"return arguments[0].shadowRoot.querySelector('.row')\", game_row)\n return row.find_elements(By.TAG_NAME, 'game-tile')\n\n\ndef input_word(browser, word):\n \"\"\"Wordleサイトに単語を打ちこんでEnterキーを押す処理\"\"\"\n elm = browser.find_element(By.CSS_SELECTOR, \"body\")\n for char in word:\n elm.send_keys(char)\n time.sleep(1)\n elm.send_keys(Keys.ENTER)\n # パネルがひっくり返ってヒントが表示されている時間、長めに待つ\n time.sleep(2)\n\n\ndef stop_selenium(msg):\n \"\"\"\n seleniumが終了するとブラウザが閉じるので、inputで保持\n todo たぶんもっと良い方法があると思う\n \"\"\"\n print(msg)\n input('終了するには何かキーを押してください')\n sys.exit()\n\n\nclass Results:\n \"\"\"\n 例えば\n answer:ULTRA\n guess :MAMMA\n という場合に2番目のAは灰色(absent)、5番目のAは(correct)となる。\n この状態で単語リストをフィルターをすると推測リストが空になる。\n これを防ぐために、結果を整理して返すためのクラス\n つまり、この場合、2番目の灰色は除外する\n \"\"\"\n\n def __init__(self):\n self.results = []\n\n def add_result(self, col_name, char, hint):\n \"\"\"結��を加える\"\"\"\n self.results.append({'col_name': col_name,\n 'char': char,\n 'hint': hint})\n\n def is_char_has_other_hint(self, char, hint):\n \"\"\"文字が他のヒントを持っていないか調べる\"\"\"\n _results = self.results\n _results = list(filter(lambda x: x['char'] == char, _results))\n _results = list(filter(lambda x: x['hint'] != hint, _results))\n if _results:\n return True\n else:\n return False\n\n def get_result(self):\n \"\"\"結果を返す\"\"\"\n for result in self.results:\n col_name = result['col_name']\n char = result['char']\n hint = result['hint']\n # absentの時にその文字が他のヒントで使われていたらスキップ\n if hint == 'absent':\n if self.is_char_has_other_hint(char, hint):\n continue\n yield col_name, char, hint\n\n\ndef job(browser, first_input):\n \"\"\"メインジョブ\"\"\"\n\n # 単語リストデータ\n df = create_df()\n\n # wordleページを開く\n open_wordle(browser)\n\n # game rowsを取得\n # wordleの入力ボックスの部分、6行分がリストで取得される\n game_rows = find_game_rows(browser)\n\n for turn, game_row in enumerate(game_rows, 1):\n\n # 単語を画面に入力する\n if turn == 1:\n input_word(browser, first_input)\n\n # 2ターン目以降はdfから単語を取得\n else:\n if len(df) == 0:\n raise WordListEmptyError(f'単語リストがなくなりました。恐らく答えが{WORDLE_ANSWER_TEXT}にないです。')\n word = guess_word(df)\n input_word(browser, word)\n\n # tileを取得。文字を打ち込むマス。5マス文がリストで返る\n game_tiles = find_game_tiles(browser, game_row)\n\n # クリア判定で使用\n clear_flag = True\n\n # 結果整理クラス\n results = Results()\n\n # 1マスずつ繰り返して結果を保存していく\n for col_num, game_tile in enumerate(game_tiles, 1):\n tile = browser.execute_script(\"return arguments[0].shadowRoot.querySelector('.tile')\", game_tile)\n col_name = f'char_{col_num}'\n char = tile.text.lower()\n\n # 緑がcorrect,黄色がpresent,灰色がabsentで返る\n hint = tile.get_attribute(\"data-state\")\n results.add_result(col_name, char, hint)\n\n # correctじゃないのが一つでもあったらクリアではない\n if hint != 'correct':\n clear_flag = False\n\n if clear_flag:\n stop_selenium('GameClear')\n\n # 6ターン目でここまで来ていたらゲーム失敗\n if turn == 6:\n stop_selenium('GameOver')\n\n # 答えを次に向けて絞り込む\n for col_name, char, hint in results.get_result():\n if hint == 'correct':\n df = filter_correct(df, col_name, char)\n if hint == 'present':\n df = filter_present(df, col_name, char)\n if hint == 'absent':\n df = filter_absent(df, char)\n\n\nif __name__ == '__main__':\n # ブラウザを指定\n _browser = chrome_browser()\n # 最初の単語\n first = 'puppy'\n job(browser=_browser, first_input=first)\n", "repo_name": "qlitre/wordle-auto-input-selenium", "sub_path": "wordle_auto_solver.py", "file_name": "wordle_auto_solver.py", "file_ext": "py", "file_size_in_byte": 6995, "program_lang": "python", "lang": "ja", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "settings.WORDLE_ANSWER_TEXT", "line_number": 22, "usage_type": "argument"}, {"api_name": "pandas.DataFrame", "line_number": 32, "usage_type": "call"}, {"api_name": "settings.WORDLE_URL", "line_number": 62, "usage_type": "argument"}, {"api_name": "time.sleep", "line_number": 64, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.CSS_SELECTOR", "line_number": 66, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 66, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 68, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.TAG_NAME", "line_number": 73, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 73, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.TAG_NAME", "line_number": 75, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 75, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.TAG_NAME", "line_number": 81, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 81, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CSS_SELECTOR", "line_number": 86, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 86, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 89, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 90, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 90, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 92, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 102, "usage_type": "call"}, {"api_name": "settings.WORDLE_ANSWER_TEXT", "line_number": 170, "usage_type": "name"}, {"api_name": "chrome.chrome_browser", "line_number": 216, "usage_type": "call"}]} +{"seq_id": "11962944245", "text": "import os\r\nimport time\r\nimport pickle\r\nimport shutil\r\nimport time\r\nfrom collections import defaultdict\r\nfrom collections import deque\r\nfrom multiprocessing import Pool\r\nimport numpy as np\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.optim import lr_scheduler\r\n\r\nfrom prl_gym.program_env import ProgramEnv1\r\nfrom pretrain.misc_utils import log_record_dict, create_directory\r\nfrom rl import utils\r\nfrom rl.algo.ppo import PPO\r\nfrom rl.algo.a2c_acktr import A2C_ACKTR\r\nfrom rl.algo.reinforce import REINFORCE\r\nfrom rl.envs import make_vec_envs\r\nfrom rl.storage import RolloutStorage2\r\nfrom utils.misc_utils import HyperParameterScheduler\r\n\r\n\r\nclass BaseRLModel(object):\r\n\r\n def __init__(self, Net, program_vae_net, device, config, dummy_envs, dsl, logger, writer, global_logs, verbose):\r\n self.device = device\r\n self.config = config\r\n self.global_logs = global_logs\r\n self.verbose = verbose\r\n self.logger = logger\r\n self.writer = writer\r\n self.envs = dummy_envs\r\n self.dsl = dsl\r\n\r\n log_dir = os.path.expanduser(os.path.join(config['outdir'], 'openai'))\r\n eval_log_dir = log_dir + \"_eval\"\r\n utils.cleanup_log_dir(log_dir)\r\n utils.cleanup_log_dir(eval_log_dir)\r\n\r\n cfg_rl = config['rl']\r\n cfg_algo = cfg_rl['algo']\r\n cfg_envs = config['rl']['envs']\r\n\r\n custom = True if \"karel\" or \"CartPoleDiscrete\" in cfg_envs['executable']['name'] else False\r\n logger.info('Using environment: {}'.format(cfg_envs['executable']['name']))\r\n self.envs = make_vec_envs(cfg_envs['executable']['name'], config['seed'], cfg_rl['num_processes'],\r\n cfg_rl['gamma'], os.path.join(config['outdir'], 'openai'), device, False,\r\n custom_env=custom, custom_env_type='program', custom_kwargs={'config': config['args']})\r\n\r\n decoder_log_dir = os.path.expanduser(os.path.join(config['outdir'], 'openai_decoder'))\r\n decoder_eval_log_dir = decoder_log_dir + \"_eval\"\r\n utils.cleanup_log_dir(decoder_log_dir)\r\n utils.cleanup_log_dir(decoder_eval_log_dir)\r\n if self.config['algorithm'] == 'supervisedRL':\r\n self.decoder_envs = make_vec_envs(cfg_envs['executable']['name'], config['seed'], cfg_rl['num_processes'],\r\n cfg_rl['gamma'], os.path.join(config['outdir'], 'openai_decoder'), device,\r\n True, custom_env=custom, custom_env_type='program',\r\n custom_kwargs={'config': config['args'], 'metadata':{'alpha': 2}})\r\n self.decoder_envs.reset()\r\n\r\n exec_env_states = self.envs.render(mode='init_states')\r\n exec_env_state_shape = exec_env_states[0].shape if cfg_rl['num_processes'] == 1 else exec_env_states[0][1].shape\r\n\r\n gt_program_str = open(cfg_envs['executable']['task_file']).readlines()[0].strip()\r\n if cfg_envs['executable']['task_definition'] == 'program':\r\n logger.info('\\n=== Ground-truth program === \\n{}\\n'\r\n '============================'.format(gt_program_str))\r\n writer.add_text('program/gt', gt_program_str, 0)\r\n\r\n # build policy network\r\n if Net is not None:\r\n self.net = self.actor_critic = Net(self.envs, **config)\r\n else:\r\n self.net = self.actor_critic = program_vae_net\r\n self.actor_critic.to(device)\r\n logger.info('Policy Network:\\n{}'.format(self.actor_critic))\r\n logger.info('Policy Network total parameters: {}'.format(utils.count_parameters(self.actor_critic)))\r\n\r\n # Load parameters if available\r\n ckpt_path = config['net']['saved_params_path']\r\n sup_params_path = config['net']['saved_sup_params_path']\r\n if ckpt_path is not None:\r\n self.load_net(ckpt_path)\r\n if sup_params_path is not None:\r\n assert ckpt_path is None, 'conflict in loading weights from supervised training and previous RL training'\r\n self.load_net2(sup_params_path)\r\n\r\n if cfg_rl['algo']['name'] == 'a2c':\r\n cfg_a2c = config['rl']['algo']['a2c']\r\n self.agent = A2C_ACKTR(\r\n self.actor_critic,\r\n cfg_rl['algo']['value_loss_coef'],\r\n cfg_rl['algo']['entropy_coef'],\r\n lr=cfg_rl['algo']['lr'],\r\n eps=cfg_a2c['eps'],\r\n alpha=cfg_a2c['alpha'],\r\n max_grad_norm=cfg_algo['max_grad_norm'],\r\n use_recurrent_generator=cfg_rl['algo']['use_recurrent_generator'],\r\n writer=writer)\r\n elif cfg_rl['algo']['name'] == 'ppo':\r\n cfg_ppo = config['rl']['algo']['ppo']\r\n self.agent = PPO(\r\n self.actor_critic,\r\n cfg_ppo['clip_param'],\r\n cfg_ppo['ppo_epoch'],\r\n cfg_ppo['num_mini_batch'],\r\n cfg_rl['algo']['value_loss_coef'],\r\n cfg_rl['algo']['entropy_coef'],\r\n lr=cfg_rl['algo']['lr'],\r\n eps=cfg_ppo['eps'],\r\n max_grad_norm=cfg_algo['max_grad_norm'],\r\n use_recurrent_generator=cfg_rl['algo']['use_recurrent_generator'],\r\n decoder_rl_loss_coef=cfg_rl['loss']['decoder_rl_loss_coef'],\r\n condition_rl_loss_coef=cfg_rl['loss']['condition_rl_loss_coef'],\r\n latent_rl_loss_coef=cfg_rl['loss']['latent_rl_loss_coef'],\r\n setup=config['algorithm'],\r\n use_mean_only=cfg_rl['loss']['use_mean_only_for_latent_loss'],\r\n writer=writer)\r\n elif cfg_rl['algo']['name'] == 'acktr':\r\n cfg_acktr = config['rl']['algo']['acktr']\r\n self.agent = A2C_ACKTR(\r\n self.actor_critic,\r\n cfg_rl['algo']['value_loss_coef'],\r\n cfg_rl['algo']['entropy_coef'],\r\n use_recurrent_generator=cfg_rl['algo']['use_recurrent_generator'],\r\n writer=writer,\r\n acktr=True)\r\n elif cfg_rl['algo']['name'] == 'reinforce':\r\n cfg_reinforce = config['rl']['algo']['reinforce']\r\n self.agent = REINFORCE(\r\n self.actor_critic,\r\n cfg_reinforce['clip_param'],\r\n cfg_reinforce['reinforce_epoch'],\r\n cfg_reinforce['num_mini_batch'],\r\n cfg_rl['algo']['entropy_coef'],\r\n lr=cfg_rl['algo']['lr'],\r\n eps=cfg_reinforce['eps'],\r\n max_grad_norm=cfg_algo['max_grad_norm'],\r\n use_recurrent_generator=cfg_rl['algo']['use_recurrent_generator'],\r\n decoder_rl_loss_coef=cfg_rl['loss']['decoder_rl_loss_coef'],\r\n condition_rl_loss_coef=cfg_rl['loss']['condition_rl_loss_coef'],\r\n latent_rl_loss_coef=cfg_rl['loss']['latent_rl_loss_coef'],\r\n setup=config['algorithm'],\r\n use_mean_only=cfg_rl['loss']['use_mean_only_for_latent_loss'],\r\n writer=writer)\r\n\r\n self.rollouts = RolloutStorage2(cfg_rl['num_steps'], cfg_rl['num_processes'], self.envs.observation_space.shape,\r\n self.envs.action_space, self.recurrent_hidden_state_size,\r\n cfg_rl['policy']['execution_guided'],\r\n cfg_envs['executable']['num_demo_per_program'],\r\n cfg_envs['executable']['max_demo_length'], exec_env_state_shape,\r\n cfg_envs['executable']['dense_execution_reward'],\r\n future_rewards=cfg_rl['future_rewards'])\r\n\r\n obs = self.envs.reset()\r\n self.rollouts.obs[0].copy_(obs)\r\n self.rollouts.to(device)\r\n if config['net']['controller']['use_previous_programs']:\r\n self.rollouts.recurrent_hidden_states = config['net']['controller']['input_coef'] * torch.ones_like(\r\n self.rollouts.recurrent_hidden_states)\r\n\r\n self.episode_rewards = deque(maxlen=10)\r\n\r\n self.num_steps = cfg_rl['num_steps']\r\n self.num_processes = cfg_rl['num_processes']\r\n self.num_updates = int(cfg_rl['num_env_steps']) // cfg_rl['num_steps'] // cfg_rl['num_processes']\r\n\r\n final_entropy = cfg_algo['final_entropy_coef'] if cfg_algo['use_exp_ent_decay'] else cfg_algo['entropy_coef']\r\n self.ent_coef_sched = HyperParameterScheduler(initial_val=cfg_algo['entropy_coef'], num_updates=self.num_updates,\r\n final_val=final_entropy, func='exponential')\r\n\r\n # set simple moving average of program_embedding distances\r\n self.d_m = torch.zeros(self.num_processes, 1).to(self.device)\r\n # refer to NGU paper hyperparameters\r\n # self.s_m = (8/10) * (self.num_steps/2)\r\n self.s_m = (8 / 10)\r\n\r\n if self.config['debug']:\r\n self.net._debug = defaultdict(dict)\r\n\r\n def _get_condition_inputs(self):\r\n initial_states = self.envs.render(mode='init_states')\r\n initial_states = np.moveaxis(initial_states, [-1,-2,-3], [-3,-2,-1])\r\n # B x num_demo_per_program x 1 x c x w x h\r\n condition_inputs = torch.tensor(initial_states).to(self.device).float().unsqueeze(2)\r\n return condition_inputs\r\n\r\n def visualization_log(self, mode, record_dict, num):\r\n if num < 40000:\r\n masks = record_dict['original_masks'][:,:5,:].detach().cpu().numpy().tolist()\r\n vectors = record_dict['program_latent_vectors'][:,:5,:].detach().cpu().numpy().tolist()\r\n dist = record_dict['distribution_params'][:,:5,:,:].detach().cpu().numpy().tolist()\r\n programs = record_dict['program_preds'][:,:5,:].detach().cpu().numpy().tolist()\r\n log_record_dict(mode,\r\n {'original_masks': masks,\r\n 'program_latent_vectors': vectors,\r\n 'distribution_params': dist,\r\n 'program_preds': programs},\r\n self.global_logs)\r\n\r\n def _get_condition_policy_reward(self, agent_actions, agent_action_masks, infos):\r\n # agent_actions: batch_size x num_demp_per_program x max_demo_len-1\r\n gt_a_h_all = []\r\n gt_a_h_len_all = []\r\n for i, info in enumerate(infos):\r\n gt_a_h = info['exec_data']['gt_a_h']\r\n gt_a_h_len = info['exec_data']['gt_a_h_len']\r\n for j, a_h in enumerate(gt_a_h):\r\n if gt_a_h_len[j] == 0:\r\n gt_a_h_len[j] += 1\r\n gt_a_h[j][0] = self.config['dsl']['num_agent_actions'] - 1\r\n gt_a_h_all += [torch.tensor(gt_a_h[i], device=agent_actions.device) for i in range(gt_a_h.shape[0])]\r\n gt_a_h_len_all += gt_a_h_len.tolist()\r\n\r\n packed_gt_action_seq = torch.nn.utils.rnn.pack_sequence(gt_a_h_all, enforce_sorted=False)\r\n padded_gt_action_seq, _ = torch.nn.utils.rnn.pad_packed_sequence(packed_gt_action_seq, batch_first=True,\r\n padding_value=self.config['dsl'][\r\n 'num_agent_actions'] - 1,\r\n total_length=agent_actions.shape[-1])\r\n padded_gt_action_seq = padded_gt_action_seq.view(agent_actions.shape[0], agent_actions.shape[1], -1)\r\n\r\n gt_action_masks = padded_gt_action_seq != self.config['dsl']['num_agent_actions']-1\r\n action_masks = torch.max(agent_action_masks, gt_action_masks)\r\n condition_reward = utils.masked_mean(padded_gt_action_seq == agent_actions, action_masks, dim=-1, keepdim=True)\r\n return condition_reward\r\n\r\n def _add_debug_info(self, debug_data, location, update, step):\r\n current_update = 'u_{}_s_{}'.format(update, step)\r\n self.net._debug[location][current_update] = {}\r\n for key, val in debug_data.items():\r\n self.net._debug[location][current_update][key] = val\r\n\r\n keys = ['u_{}_s_{}_{}'.format(update, step, i) for i in range(debug_data['pred_programs'].shape[0])]\r\n self.net._debug[location][current_update]['ids'] = keys\r\n return current_update\r\n\r\n @staticmethod\r\n def temp_env_step(data):\r\n config, gt_program, pred_program, init_states = data\r\n env = ProgramEnv1(config, gt_program, init_states)\r\n env._max_episode_steps = config.max_episode_steps\r\n env.seed(config.seed)\r\n _, reward, done, info = env.step(pred_program)\r\n return (reward, done, info)\r\n\r\n def _supervisedRL_env_step(self, pred_programs, gt_programs, init_states):\r\n _, reward, done, infos = self.decoder_envs.step(\r\n torch.cat((gt_programs.long(), pred_programs), dim=-1).detach().cpu())\r\n\r\n return None, reward, done, infos\r\n\r\n def _get_latent_exploration_reward(self, program_embeddings):\r\n k = self.num_steps//2\r\n l2_norm = torch.norm(self.rollouts.program_embeddings - program_embeddings.unsqueeze(0), p=2, dim=-1)\r\n l2_norm = l2_norm.permute(1,0)\r\n d_k, d_k_idx = torch.topk(l2_norm, k, dim=-1, largest=False)\r\n\r\n # update moving average d_m**2\r\n current_avg_dist = torch.mean(d_k**2, dim=-1, keepdim=True)\r\n self.d_m = (self.d_m + current_avg_dist) / 2\r\n\r\n # normalize the distances with moving average\r\n d_n = d_k / self.d_m\r\n d_n = torch.clamp(d_n - 0.008, min=0)\r\n\r\n # compute the kernel\r\n K = 0.0001 / (d_n + 0.0001)\r\n s = torch.sqrt(torch.sum(K, dim=-1)) + 0.001\r\n\r\n s = s.detach().cpu().view(-1,1)\r\n return s\r\n\r\n def update_step(self, j, start, config, mode='train'):\r\n cfg_rl = config['rl']\r\n cfg_algo = config['rl']['algo']\r\n cfg_envs = config['rl']['envs']\r\n use_decoder_dist = config['net']['controller']['use_decoder_dist']\r\n\r\n t = time.time()\r\n if cfg_algo['use_linear_lr_decay']:\r\n # decrease learning rate linearly\r\n current_learning_rate = utils.update_linear_schedule(self.agent.optimizer, j, self.num_updates,\r\n cfg_algo['lr'])\r\n else:\r\n current_learning_rate = cfg_algo['lr']\r\n\r\n for step in range(self.num_steps):\r\n if config['algorithm'] != 'supervisedRL':\r\n condition_inputs = self._get_condition_inputs()\r\n else:\r\n condition_inputs = self.rollouts.agent_initial_states[step]\r\n\r\n # Sample actions\r\n with torch.no_grad():\r\n outputs = self.actor_critic.act(self.rollouts.obs[step],\r\n self.rollouts.recurrent_hidden_states[step],\r\n self.rollouts.masks[step],\r\n condition_inputs, deterministic=not use_decoder_dist)\r\n value, pred_programs, pred_programs_log_probs, recurrent_hidden_states, pred_program_masks, \\\r\n eop_pred_programs, agent_value, agent_actions, agent_action_log_probs, agent_action_masks, \\\r\n program_embeddings, distribution_params, _, _, latent_log_probs, _ = outputs\r\n\r\n \"\"\"program_env expects EOP token in action but two_head policy can't have it as part of action space\r\n so we manually add EOP token for two_head_policy over here\"\"\"\r\n if cfg_envs['program']['mdp_type'] == 'ProgramEnv1':\r\n alt_pred_programs = (self.actor_critic.num_program_tokens - 1) * torch.ones_like(pred_programs)\r\n pred_programs2 = torch.where(pred_program_masks > 0, pred_programs, alt_pred_programs) if \\\r\n cfg_rl['policy']['two_head'] else pred_programs\r\n else:\r\n pred_programs2 = pred_programs.clone()\r\n\r\n # add debug info\r\n if self.config['debug']:\r\n debug_id = self._add_debug_info({'pred_programs': pred_programs,\r\n 'pred_program_log_probs': pred_programs_log_probs,\r\n 'pred_program_masks': pred_program_masks,\r\n 'agent_actions': agent_actions,\r\n 'agent_action_log_probs': agent_action_log_probs,\r\n 'agent_action_masks': agent_action_masks,\r\n 'program_embeddings': program_embeddings,\r\n 'distribution_params': distribution_params},\r\n location='act',\r\n update=j,\r\n step=step)\r\n\r\n # Observation reward and next obs\r\n if self.config['algorithm'] != 'supervisedRL':\r\n obs, reward, done, infos = self.envs.step(pred_programs2)\r\n else:\r\n _, reward, done, infos = self._supervisedRL_env_step(pred_programs2, self.rollouts.obs[step],\r\n condition_inputs)\r\n obs = self.rollouts.obs[step + 1]\r\n\r\n # Add latent space exploration reward based on current memory\r\n reward_intrinsic = None\r\n reward_env = reward\r\n if cfg_envs['program']['intrinsic_reward']:\r\n beta = cfg_envs['program']['intrinsic_beta']\r\n s = self._get_latent_exploration_reward(program_embeddings)\r\n reward_intrinsic = 1/s\r\n reward = torch.where(s > self.s_m, reward, reward + beta * reward_intrinsic)\r\n\r\n if config['rl']['loss']['condition_rl_loss_coef'] > 0.0:\r\n if cfg_envs['executable']['task_definition'] == 'program':\r\n agent_action_done = done\r\n agent_action_reward = self._get_condition_policy_reward(agent_actions, agent_action_masks, infos)\r\n else:\r\n agent_action_obs, agent_action_reward, agent_action_done, agent_action_info = self.condition_envs.step(\r\n agent_actions)\r\n else:\r\n agent_action_reward = torch.zeros(\r\n (self.num_processes, cfg_envs['executable']['num_demo_per_program'], 1),\r\n device=agent_actions.device)\r\n\r\n # FIXME: There is no episode info in infos for supervisedRL\r\n for i, info in enumerate(infos):\r\n if 'episode' in info.keys():\r\n assert done[i]\r\n self.episode_rewards.append(info['episode']['r'])\r\n\r\n # If done then clean the history of observations.\r\n masks = torch.FloatTensor(\r\n [[0.0] if (done_ and config['rl']['use_all_programs']) else [1.0] for done_ in done])\r\n bad_masks = torch.FloatTensor(\r\n [[0.0] if 'bad_transition' in info.keys() else [1.0]\r\n for info in infos])\r\n orig_masks = torch.FloatTensor([[0.0] if done_ else [1.0] for done_ in done])\r\n debug_data = self.net._debug['act'][debug_id] if self.config['debug'] else None\r\n self.rollouts.insert(obs, recurrent_hidden_states, pred_programs, pred_programs_log_probs, value,\r\n reward, reward_intrinsic, reward_env, masks, bad_masks, pred_program_masks,\r\n eop_pred_programs, agent_value, agent_actions, agent_action_log_probs,\r\n agent_action_reward, agent_action_masks, program_embeddings, condition_inputs,\r\n distribution_params, orig_masks, latent_log_probs, debug_data)\r\n\r\n # logging\r\n cum_reward = self.rollouts.rewards.cpu().numpy()\r\n self.writer.add_scalar('agent/reward_sum', cum_reward.sum(), j)\r\n self.writer.add_scalar('agent/reward_max', cum_reward.max(), j)\r\n self.writer.add_scalar('agent/reward_min', cum_reward.min(), j)\r\n self.writer.add_scalar('agent/reward_mean', cum_reward.mean(), j)\r\n self.writer.add_scalar('agent/reward_intrinsic_mean', self.rollouts.rewards_intrinsic.cpu().numpy().mean(), j)\r\n self.writer.add_scalar('agent/reward_env_sum', self.rollouts.rewards_env.cpu().numpy().sum(), j)\r\n self.writer.add_scalar('agent/reward_env_mean', self.rollouts.rewards_env.cpu().numpy().mean(), j)\r\n self.writer.add_scalar('agent/reward_env_max', self.rollouts.rewards_env.cpu().numpy().max(), j)\r\n self.writer.add_scalar('agent/reward_env_min', self.rollouts.rewards_env.cpu().numpy().min(), j)\r\n self.writer.add_scalar('agent/learning_rate', current_learning_rate, j)\r\n self.writer.add_scalar('distribution/mean',\r\n torch.norm(self.rollouts.program_distribution_params[:, 0, :].detach(), dim=-1,\r\n p=2).mean().cpu().numpy(), j)\r\n self.writer.add_scalar('distribution/std',\r\n torch.norm(self.rollouts.program_distribution_params[:, 1, :].detach(), dim=-1,\r\n p=2).mean().cpu().numpy(), j)\r\n\r\n # FIXME: I don't think we need this if check anymore, but somebody gotta verify it\r\n if len(pred_programs.shape) == 1:\r\n pred_programs = pred_programs.reshape(1, -1)\r\n # pred program str\r\n if \"karel\" or \"CartPoleDiscrete-v0\" in cfg_envs['executable']['name']:\r\n if cfg_envs['program']['mdp_type'] == 'ProgramEnv1':\r\n pred_program_strs = [self.dsl.intseq2str(info['modified_action']) for info in infos]\r\n num_tokens = self.actor_critic.num_program_tokens\r\n if cfg_rl['policy']['two_head']:\r\n program_len = torch.sum(rollouts.pred_program_masks.view(-1, config['dsl']['max_program_len']),\r\n dim=1).float().cpu().numpy()\r\n else:\r\n program_len = config['dsl']['max_program_len'] - torch.sum(\r\n self.rollouts.actions.view(-1, config['dsl']['max_program_len']) == num_tokens - 1,\r\n dim=1).float().cpu().numpy()\r\n self.writer.add_scalar('agent/mean_program_len', program_len.mean(), j)\r\n for i, pred_program_str in enumerate(pred_program_strs):\r\n self.writer.add_text('program/pred_{}'.format(i),\r\n 'reward_env: {} program: {} '.format(reward_env[i].cpu().numpy(),\r\n pred_program_str), j)\r\n else:\r\n raise NotImplementedError('not yet implemented!')\r\n\r\n gamma = cfg_rl['gamma'] if cfg_rl['future_rewards'] else 0\r\n if cfg_algo['name'] == 'reinforce':\r\n self.rollouts.compute_returns(0, 0, False, gamma, None, False, cfg_algo['name'])\r\n else:\r\n with torch.no_grad():\r\n next_value, agent_next_value = self.actor_critic.get_value(\r\n self.rollouts.obs[-1], self.rollouts.recurrent_hidden_states[-1],\r\n self.rollouts.masks[-1], self.rollouts.agent_initial_states[-1],\r\n deterministic=not use_decoder_dist)\r\n\r\n self.rollouts.compute_returns(next_value, agent_next_value, cfg_rl['use_gae'], gamma, cfg_rl['gae_lambda'],\r\n cfg_rl['use_proper_time_limits'], cfg_algo['name'])\r\n\r\n # RL algorithm update\r\n value_loss, action_loss, dist_entropy = self.agent.update(self.rollouts, use_decoder_dist=use_decoder_dist)\r\n\r\n # log all items in dict\r\n record_dict = {'udpate_num': j, 'update_action_loss': action_loss,\r\n 'update_entropy': dist_entropy,\r\n 'update_reward_mean': self.rollouts.rewards.cpu().numpy().mean(),\r\n 'update_reward_sum': self.rollouts.rewards.cpu().numpy().sum(),\r\n 'update_reward_min': self.rollouts.rewards.cpu().numpy().min(),\r\n 'update_reward_max': self.rollouts.rewards.cpu().numpy().max(),\r\n 'update_reward_env_mean': self.rollouts.rewards_env.cpu().numpy().mean(),\r\n 'update_reward_env_sum': self.rollouts.rewards_env.cpu().numpy().sum(),\r\n 'update_reward_env_min': self.rollouts.rewards_env.cpu().numpy().min(),\r\n 'update_reward_env_max': self.rollouts.rewards_env.cpu().numpy().max(),\r\n }\r\n log_record_dict(mode, record_dict, self.global_logs)\r\n if self.config['algorithm'] == 'RL':\r\n self.visualization_log(mode, {'original_masks': self.rollouts.original_masks,\r\n 'program_latent_vectors': self.rollouts.program_embeddings,\r\n 'distribution_params': self.rollouts.program_distribution_params,\r\n 'program_preds': self.rollouts.actions}, j * self.num_steps)\r\n if self.verbose:\r\n self._print_record_dict(record_dict, j, self.num_updates, 'train', time.time() - t)\r\n\r\n self.writer.add_scalar('agent/mean_program_value_estimate_2', self.rollouts.value_preds.cpu().numpy().mean(), j)\r\n self.logger.info(\"PPO value_loss: {} policy_loss: {} dist_entropy: {}\".format(value_loss, action_loss, dist_entropy))\r\n\r\n self.rollouts.after_update()\r\n self.agent.entropy_coef = self.ent_coef_sched.step(j)\r\n\r\n # save for every interval-th episode or for the last epoch\r\n if (j % config['save_interval'] == 0\r\n or j == self.num_updates - 1) and config['outdir'] != \"\":\r\n save_path = os.path.join(config['outdir'], cfg_algo['name'])\r\n create_directory(save_path)\r\n self.save_net(os.path.join(save_path, cfg_envs['executable']['name'] + '_' + str(j) + \".pt\"))\r\n\r\n if j % config['log_interval'] == 0 and len(self.episode_rewards) > 1:\r\n total_num_steps = (j + 1) * self.num_processes * self.num_steps\r\n end = time.time()\r\n print(\r\n \"Updates {}, num timesteps {}, FPS {} \\n Last {} training episodes: mean/median reward {:.1f}/{:.1f}, \"\r\n \"min/max reward {:.1f}/{:.1f}\\n \"\r\n .format(j, total_num_steps,\r\n int(total_num_steps / (end - start)),\r\n len(self.episode_rewards), np.mean(self.episode_rewards),\r\n np.median(self.episode_rewards), np.min(self.episode_rewards),\r\n np.max(self.episode_rewards), dist_entropy, value_loss,\r\n action_loss))\r\n\r\n # Save results\r\n if j % (config['save_interval'] // 10) == 0:\r\n pickle.dump(self.global_logs,\r\n file=open(os.path.join(self.config['outdir'], self.config['record_file']), 'wb'))\r\n\r\n # FIXME: add evaluation code as in main repo\r\n\r\n return None\r\n\r\n def train(self, *args, **kwargs):\r\n start = time.time()\r\n config = self.config\r\n for j in range(self.num_updates):\r\n self.update_step(j, start, config)\r\n\r\n return None\r\n\r\n def save_net(self, filename):\r\n params = [self.actor_critic.state_dict(), getattr(utils.get_vec_normalize(self.envs), 'ob_rms', None)]\r\n torch.save(params, filename)\r\n self.logger.debug('params saved to {}'.format(filename))\r\n\r\n def load_net(self, filename):\r\n self.logger.debug('Loading params from {}'.format(filename))\r\n params = torch.load(filename, map_location=self.device)\r\n self.actor_critic.load_state_dict(params[0], strict=False)\r\n\r\n def load_net2(self, filename):\r\n self.logger.debug('Loading params from {}'.format(filename))\r\n params = torch.load(filename, map_location=self.device)\r\n self.actor_critic.program_vae.load_state_dict(params[0])\r\n\r\n def _print_record_dict(self, record_dict, current_update, total_updates, usage, t_taken):\r\n loss_str = ''\r\n for k, v in record_dict.items():\r\n loss_str = loss_str + ' {}: {:.8f}'.format(k, v)\r\n\r\n loss_str = 'update {}/{}: '.format(current_update, total_updates) + loss_str\r\n self.logger.debug('{}:{} took {:.3f}s'.format(usage, loss_str, t_taken))\r\n return None\r\n", "repo_name": "clvrai/leaps", "sub_path": "pretrain/BaseRLModel.py", "file_name": "BaseRLModel.py", "file_ext": "py", "file_size_in_byte": 28949, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 24, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.path.expanduser", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path", "line_number": 38, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 38, "usage_type": "call"}, {"api_name": "rl.utils.cleanup_log_dir", "line_number": 40, "usage_type": "call"}, {"api_name": "rl.utils", "line_number": 40, "usage_type": "name"}, {"api_name": "rl.utils.cleanup_log_dir", "line_number": 41, "usage_type": "call"}, {"api_name": "rl.utils", "line_number": 41, "usage_type": "name"}, {"api_name": "rl.envs.make_vec_envs", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path", "line_number": 53, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 53, "usage_type": "call"}, {"api_name": "rl.utils.cleanup_log_dir", "line_number": 55, "usage_type": "call"}, {"api_name": "rl.utils", "line_number": 55, "usage_type": "name"}, {"api_name": "rl.utils.cleanup_log_dir", "line_number": 56, "usage_type": "call"}, {"api_name": "rl.utils", "line_number": 56, "usage_type": "name"}, {"api_name": "rl.envs.make_vec_envs", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path", "line_number": 59, "usage_type": "attribute"}, {"api_name": "rl.utils.count_parameters", "line_number": 80, "usage_type": "call"}, {"api_name": "rl.utils", "line_number": 80, "usage_type": "name"}, {"api_name": "rl.algo.a2c_acktr.A2C_ACKTR", "line_number": 93, "usage_type": "call"}, {"api_name": "rl.algo.ppo.PPO", "line_number": 105, "usage_type": "call"}, {"api_name": "rl.algo.a2c_acktr.A2C_ACKTR", "line_number": 124, "usage_type": "call"}, {"api_name": "rl.algo.reinforce.REINFORCE", "line_number": 133, "usage_type": "call"}, {"api_name": "rl.storage.RolloutStorage2", "line_number": 150, "usage_type": "call"}, {"api_name": "torch.ones_like", "line_number": 162, "usage_type": "call"}, {"api_name": "collections.deque", "line_number": 165, "usage_type": "call"}, {"api_name": "utils.misc_utils.HyperParameterScheduler", "line_number": 172, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 176, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 182, "usage_type": "call"}, {"api_name": "numpy.moveaxis", "line_number": 186, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 188, "usage_type": "call"}, {"api_name": "pretrain.misc_utils.log_record_dict", "line_number": 197, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 215, "usage_type": "call"}, {"api_name": "torch.nn.utils.rnn.pack_sequence", "line_number": 218, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 218, "usage_type": "attribute"}, {"api_name": "torch.nn.utils.rnn.pad_packed_sequence", "line_number": 219, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 219, "usage_type": "attribute"}, {"api_name": "torch.max", "line_number": 226, "usage_type": "call"}, {"api_name": "rl.utils.masked_mean", "line_number": 227, "usage_type": "call"}, {"api_name": "rl.utils", "line_number": 227, "usage_type": "name"}, {"api_name": "prl_gym.program_env.ProgramEnv1", "line_number": 243, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 251, "usage_type": "call"}, {"api_name": "torch.norm", "line_number": 257, "usage_type": "call"}, {"api_name": "torch.topk", "line_number": 259, "usage_type": "call"}, {"api_name": "torch.mean", "line_number": 262, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 267, "usage_type": "call"}, {"api_name": "torch.sqrt", "line_number": 271, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 271, "usage_type": "call"}, {"api_name": "time.time", "line_number": 282, "usage_type": "call"}, {"api_name": "rl.utils.update_linear_schedule", "line_number": 285, "usage_type": "call"}, {"api_name": "rl.utils", "line_number": 285, "usage_type": "name"}, {"api_name": "torch.no_grad", "line_number": 297, "usage_type": "call"}, {"api_name": "torch.ones_like", "line_number": 309, "usage_type": "call"}, {"api_name": "torch.where", "line_number": 310, "usage_type": "call"}, {"api_name": "torch.where", "line_number": 344, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 354, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 365, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 367, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 370, "usage_type": "call"}, {"api_name": "torch.norm", "line_number": 391, "usage_type": "call"}, {"api_name": "torch.norm", "line_number": 394, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 406, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 409, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 424, "usage_type": "call"}, {"api_name": "pretrain.misc_utils.log_record_dict", "line_number": 448, "usage_type": "call"}, {"api_name": "time.time", "line_number": 455, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 466, "usage_type": "call"}, {"api_name": "os.path", "line_number": 466, "usage_type": "attribute"}, {"api_name": "pretrain.misc_utils.create_directory", "line_number": 467, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 468, "usage_type": "call"}, {"api_name": "os.path", "line_number": 468, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 472, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 478, "usage_type": "call"}, {"api_name": "numpy.median", "line_number": 479, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 479, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 480, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 485, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 486, "usage_type": "call"}, {"api_name": "os.path", "line_number": 486, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 493, "usage_type": "call"}, {"api_name": "rl.utils.get_vec_normalize", "line_number": 501, "usage_type": "call"}, {"api_name": "rl.utils", "line_number": 501, "usage_type": "name"}, {"api_name": "torch.save", "line_number": 502, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 507, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 512, "usage_type": "call"}]} +{"seq_id": "34172856544", "text": "import discord\r\nimport random\r\nimport copy\r\n\r\nclass Sokoban:\r\n\tdef __init__(self, ctx, *, play_forever=False, format_dict={}, board=None):\r\n\r\n\t\tfrom .. import resend_embed_list, end_game_list, ongoing_game_color, lost_game_color, won_game_color\r\n\t\tglobal resend_embed_list, end_game_list, ongoing_game_color, lost_game_color, won_game_color\r\n\r\n\t\tself.ctx = ctx\r\n\t\tself.board = board or self.create_board()\r\n\t\tself.controls = {'u':(-1,0), 'd':(1,0), 'l':(0,-1), 'r':(0,1)}\r\n\t\tself.format_dict = format_dict\r\n\t\tself.default_format_dict = {\r\n\t\t\t\t\t\t\t\t\t'p':'😳',\r\n\t\t\t\t\t\t\t\t\t'tp':'😳',\r\n\t\t\t\t\t\t\t\t\t't':'❎',\r\n\t\t\t\t\t\t\t\t\t'b':'🟫',\r\n\t\t\t\t\t\t\t\t\t'bt':'✅',\r\n\t\t\t\t\t\t\t\t\t' ':'⬛',\r\n\t\t\t\t\t\t\t\t\t'w':'⬜'\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\tself.play_forever = play_forever\r\n\t\tself.original_board = copy.deepcopy(self.board)\r\n\t\tself.winner = 0\r\n\r\n\tdef create_board(self):\r\n\t\tboard = [[' ' for _ in range(5)] for _ in range(5)]\r\n\t\tboard[random.randrange(len(board))][random.randrange(len(board[0]))] = 'p'\r\n\r\n\t\tparams = {\r\n\t\t\t't': (0, len(board)),\r\n\t\t\t'b':(1, len(board)-1)\r\n\t\t}\r\n\r\n\t\tfor i in ['t','b','t','b']:\r\n\t\t\tx = random.randrange(*params[i])\r\n\t\t\ty = random.randrange(*params[i])\r\n\t\t\twhile board[x][y] != ' ':\r\n\t\t\t\tx = random.randrange(*params[i])\r\n\t\t\t\ty = random.randrange(*params[i])\r\n\t\t\tboard[x][y] = i\r\n\t\treturn board\r\n\r\n\tdef get_player(self):\r\n\t\tfor x, row in enumerate(self.board):\r\n\t\t\tfor y, col in enumerate(row):\r\n\t\t\t\tif col == 'p' or col == 'tp':\r\n\t\t\t\t\treturn x,y\r\n\r\n\tdef move(self, direction, amount):\r\n\r\n\t\tx,y = self.get_player()\r\n\t\tif x+(direction[0]*amount) not in range(len(self.board)) or y+(direction[1]*amount) not in range(len(self.board[0])):\r\n\t\t\treturn\r\n\r\n\t\tfor _ in range(amount):\r\n\t\t\tp_x,p_y = self.get_player()\r\n\t\t\tsuccess = True\r\n\t\t\tboard_copy = copy.deepcopy(self.board)\r\n\t\t\tif (p_x+direction[0] in range(len(board_copy)) and p_y+direction[1] in range(len(board_copy[0]))):\r\n\r\n\t\t\t\tn_index = (p_x+direction[0],p_y+direction[1])\r\n\t\t\t\titem = board_copy[n_index[0]][n_index[1]]\r\n\t\t\t\tif item == \" \":\r\n\t\t\t\t\tif board_copy[p_x][p_y]=='tp':\r\n\t\t\t\t\t\tboard_copy[p_x][p_y] = 't'\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tboard_copy[p_x][p_y] = ' '\r\n\r\n\t\t\t\t\tif board_copy[n_index[0]][n_index[1]] == 't':\r\n\t\t\t\t\t\tboard_copy[n_index[0]][n_index[1]] = 'tp'\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tboard_copy[n_index[0]][n_index[1]] = 'p'\r\n\r\n\t\t\t\telif item[0] == 'b':\r\n\t\t\t\t\tb_direction = (direction[0]*2, direction[1]*2)\r\n\t\t\t\t\tif (p_x+b_direction[0] in range(len(board_copy)) and p_y+b_direction[1] in range(len(board_copy[0]))):\r\n\t\t\t\t\t\tb_index = [p_x+b_direction[0],p_y+b_direction[1]]\r\n\t\t\t\t\t\tif board_copy[b_index[0]][b_index[1]] not in ['b','bt','w']:\r\n\r\n\t\t\t\t\t\t\tif board_copy[p_x][p_y]=='tp':\r\n\t\t\t\t\t\t\t\tboard_copy[p_x][p_y] = 't'\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tboard_copy[p_x][p_y] = ' '\r\n\r\n\t\t\t\t\t\t\tif board_copy[n_index[0]][n_index[1]]=='bt':\r\n\t\t\t\t\t\t\t\tboard_copy[n_index[0]][n_index[1]] = 'tp'\r\n\t\t\t\t\t\t\telif board_copy[n_index[0]][n_index[1]]=='t':\r\n\t\t\t\t\t\t\t\tboard_copy[n_index[0]][n_index[1]] = 'tp'\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tboard_copy[n_index[0]][n_index[1]] = 'p'\r\n\r\n\t\t\t\t\t\t\tif board_copy[b_index[0]][b_index[1]]=='t':\r\n\t\t\t\t\t\t\t\tboard_copy[b_index[0]][b_index[1]] = 'bt'\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tboard_copy[b_index[0]][b_index[1]] = 'b'\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tsuccess = False\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tsuccess = False\r\n\r\n\t\t\t\telif item=='t':\r\n\t\t\t\t\tif board_copy[p_x][p_y]=='tp':\r\n\t\t\t\t\t\tboard_copy[p_x][p_y] = 't'\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tboard_copy[p_x][p_y] = ' '\r\n\t\t\t\t\tboard_copy[n_index[0]][n_index[1]] = 'tp'\r\n\t\t\t\telif item=='w':\r\n\t\t\t\t\tsuccess = False\r\n\t\t\telse:\r\n\t\t\t\tsuccess = False\r\n\r\n\t\t\tif success:\r\n\t\t\t\tself.board = board_copy\r\n\r\n\tdef format_board(self):\r\n\t\tlst = []\r\n\t\tfor row in self.board:\r\n\t\t\tlst.append(''.join(\r\n\t\t\t\t[\r\n\t\t\t\t\tself.format_dict.get(i, self.default_format_dict.get(i,i)) for i in row\r\n\t\t\t\t]\r\n\t\t\t))\r\n\t\treturn '\\n'.join(lst)\r\n\r\n\tdef has_won(self):\r\n\t\tfor row in self.board:\r\n\t\t\tfor col in row:\r\n\t\t\t\tif col == 't' or col == 'tp':\r\n\t\t\t\t\treturn False\r\n\t\tif self.winner == 0:\r\n\t\t\tself.winner = []\r\n\t\tself.winner.append(True)\r\n\t\treturn True\r\n\r\n\r\n\tasync def start(self, *, delete_input=False, end_game_option=False, resend_embed_option=False):\r\n\t\tembed = discord.Embed(title='Sokoban', description=self.format_board(), color=ongoing_game_color)\r\n\t\tself.msg = await self.ctx.send(embed=embed)\r\n\t\twhile True:\r\n\t\t\tinp = await self.ctx.bot.wait_for('message', check=lambda m: m.author == self.ctx.author and m.channel == self.ctx.channel)\r\n\r\n\t\t\tif delete_input:\r\n\t\t\t\ttry:\r\n\t\t\t\t\tawait inp.delete()\r\n\t\t\t\texcept discord.Fobidden:\r\n\t\t\t\t\tpass\r\n\r\n\t\t\ttry:\r\n\t\t\t\tif inp.content.lower() in ['re','reload','re-load']:\r\n\t\t\t\t\tself.board = self.original_board\r\n\t\t\t\t\tself.original_board = copy.deepcopy(self.board)\r\n\t\t\t\telif resend_embed_option and inp.content.lower() in resend_embed_list:\r\n\t\t\t\t\tembed = discord.Embed(title='Sokoban', description=self.format_board(), color=ongoing_game_color)\r\n\t\t\t\t\tself.msg = await self.ctx.send(embed=embed)\r\n\r\n\t\t\t\tdirection = self.controls[inp.content[0]]\r\n\t\t\t\tif inp.content[-1].isdigit():\r\n\t\t\t\t\tamount = int(inp.content[-1])\r\n\t\t\t\telse:\r\n\t\t\t\t\tamount = 1\r\n\t\t\t\tself.move(direction, amount)\r\n\t\t\t\tif self.has_won():\r\n\t\t\t\t\tif self.play_forever:\r\n\t\t\t\t\t\tself.board = self.create_board()\r\n\t\t\t\t\t\tself.original_board = copy.deepcopy(self.board)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tembed = discord.Embed(title='Sokoban', description=self.format_board(), color=won_game_color)\r\n\t\t\t\t\t\tawait self.msg.edit(content='You won!', embed=embed)\r\n\t\t\t\t\t\tbreak\r\n\t\t\texcept KeyError:\r\n\t\t\t\tif end_game_option and inp.content in end_game_list:\r\n\t\t\t\t\tif self.winner == 0:\r\n\t\t\t\t\t\tself.winner = []\r\n\t\t\t\t\tself.winner.append(False)\r\n\t\t\t\t\tembed = discord.Embed(title='Sokoban', description=self.format_board(), color=lost_game_color)\r\n\t\t\t\t\tawait self.msg.edit(content='Game ended!', embed=embed)\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\tembed = discord.Embed(title='Sokoban', description=self.format_board(), color=ongoing_game_color)\r\n\t\t\tawait self.msg.edit(embed=embed)\r\n\t\treturn self.winner", "repo_name": "andrewthederp/Disgames", "sub_path": "disgames/message_games/soko.py", "file_name": "soko.py", "file_ext": "py", "file_size_in_byte": 5920, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 13, "dataset": "github-code", "pt": "20", "api": [{"api_name": "copy.deepcopy", "line_number": 25, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 30, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 38, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 39, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 41, "usage_type": "call"}, {"api_name": "random.randrange", "line_number": 42, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 61, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 140, "usage_type": "call"}, {"api_name": "discord.Fobidden", "line_number": 148, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 154, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 156, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 168, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 170, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 178, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 182, "usage_type": "call"}]} +{"seq_id": "71293308226", "text": "from functools import lru_cache\nclass Solution:\n def minDistance(self, houses: List[int], k: int) -> int:\n houses.sort()\n n = len(houses)\n dp = [[float('inf')] * (n+1) for _ in range(k+1)]\n\n @lru_cache(None)\n def min_total(box, pre, j):\n return sum(abs(houses[x-1] - box) for x in range(pre + 1, j+1))\n \n # dp[i][j]: min-distance to have i groups for the first j houses\n for i in range(k+1):\n for j in range(i+1):\n dp[i][j] = 0\n for i in range(1, k+1):\n for j in range(i+1, n+1):\n for pre in range(j):\n # [1, ... pre], [pre + 1,.. j]\n first = dp[i-1][pre]\n box = houses[(pre + j - 1) // 2]\n second = min_total(box, pre, j)\n curr = first + second\n dp[i][j] = min(dp[i][j], curr)\n return dp[-1][-1]\n \n ", "repo_name": "dengl11/Leetcode", "sub_path": "problems/allocate_mailboxes/solution.py", "file_name": "solution.py", "file_ext": "py", "file_size_in_byte": 979, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "functools.lru_cache", "line_number": 8, "usage_type": "call"}]} +{"seq_id": "1432678321", "text": "from setuptools import setup, find_packages\nfrom lisereader.version import __version__\nfrom pathlib import Path\n\nthis_directory = Path(__file__).parent\nlong_description = (this_directory / 'README.md').read_text()\n\nclassifiers = [\n 'Programming Language :: Python :: 3',\n 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Topic :: Scientific/Engineering :: Physics'\n]\n\nsetup(\n name='LISEreader',\n packages=find_packages(),\n version=__version__,\n description='Reader of data files generated by LISE++.',\n long_description=long_description,\n long_description_content_type='text/markdown',\n author='gwgwhc',\n url='https://github.com/gwgwhc/lisereader',\n download_url=f'https://github.com/gwgwhc/lisereader/tarball/{__version__}',\n entry_points={\n 'console_scripts': [\n 'lisereader = lisereader.__main__:main'\n ]\n },\n license='GPLv3',\n keywords=['physics', 'data', 'LISE++', ],\n classifiers=classifiers\n)\n", "repo_name": "gwgwhc/lisereader", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 1074, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pathlib.Path", "line_number": 5, "usage_type": "call"}, {"api_name": "setuptools.setup", "line_number": 16, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 18, "usage_type": "call"}, {"api_name": "lisereader.version.__version__", "line_number": 19, "usage_type": "name"}, {"api_name": "lisereader.version.__version__", "line_number": 25, "usage_type": "name"}]} +{"seq_id": "70401569026", "text": "import isodate\nimport time\nimport urllib\nimport urllib.request\nimport os\nimport ssl\n\n\"\"\"\n This script creates a movie from an ADAGUC Web Map Service.\n The script will work out of the box with the sat dataset which can be\n configured in the tutorial as described inside the Readme of adaguc-server.\n\n You can also add overlays or baselayers if you configure these as layers in your service:\n\n \n \n \n \n \n \n grid10\n grid 10 degrees\n \n \n \n\n The movie can be displayed in a browser by using:\n $ firefox out.mp4\n\"\"\"\nbbox = \"BBOX=246032.58891774912,6415470.813887446,976823.012917749,7229569.237160173\"\n\n# Pick a WMS request and remoce the TIME key value pair\nurl = \"https://geoservices.knmi.nl/adagucserver?DATASET=RADAR&SERVICE=WMS&&SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=RAD_NL25_PCP_CM&WIDTH=926&HEIGHT=982&CRS=EPSG%3A3857&\" + \\\n bbox+\"&STYLES=&FORMAT=image/png&TRANSPARENT=TRUE&\"\n\n# URL with overlays\n# url=\"https://compute-test.c3s-magic.eu:8443//adagucserver?DATASET=sat&SERVICE=WMS&&SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=HRVIS,overlay,grid10&WIDTH=926&HEIGHT=982&CRS=EPSG%3A32661&BBOX=43923.30841535237,-5093568.6573570175,4865123.617713443,19194.521617847146&STYLES=hrvis_0till30000%2Fnearest&FORMAT=image/png32&TRANSPARENT=TRUE&\"\n\n# Specify the time range, it is start/stop/resolution, in this case 15 minutes.\n# This is the ISO8601 convention, check https://dev.knmi.nl/projects/adagucserver/wiki/ISO8601\nTIME = \"2021-10-12T22:45:00Z/2021-10-12T23:45:00Z/PT5M\"\n\n\n# Allow self signed certificates over HTTPS: Note, not secure!\nssl._create_default_https_context = ssl._create_unverified_context\n\n\ndef daterange(start_date, end_date, delta):\n d = start_date\n while d < end_date:\n yield d\n d += delta\n\n\nstart_date = isodate.parse_datetime(TIME.split(\"/\")[0])\nend_date = isodate.parse_datetime(TIME.split(\"/\")[1])\ntimeres = isodate.parse_duration(TIME.split(\"/\")[2])\n\ndatestodo = list(daterange(start_date, end_date, timeres))\n\nnum = 0\n\nfor date in datestodo:\n wmstime = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", date.timetuple())\n wmsurl = url+\"&time=\"+wmstime+\"&\"\n filetowrite = \"img%03d.png\" % (num)\n urllib.request.urlretrieve(wmsurl, filetowrite)\n print(wmsurl)\n print(\"Saving \"+str(num)+\"/\"+str(len(datestodo))+\": \"+filetowrite)\n num = num+1\n\n# ffmpeg -i img%03d.png -c:v libx264 -vf fps=25 -pix_fmt yuv420p out.mp4\n\n\nos.system(\"ffmpeg -y -i img%03d.png -c:v libx264 -vf fps=25 -pix_fmt yuv420p out.mp4\")\n", "repo_name": "KNMI/adaguc-server", "sub_path": "python/examples/others/createmovie.py", "file_name": "createmovie.py", "file_ext": "py", "file_size_in_byte": 3339, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 24, "dataset": "github-code", "pt": "25", "api": [{"api_name": "ssl._create_default_https_context", "line_number": 55, "usage_type": "attribute"}, {"api_name": "ssl._create_unverified_context", "line_number": 55, "usage_type": "attribute"}, {"api_name": "isodate.parse_datetime", "line_number": 65, "usage_type": "call"}, {"api_name": "isodate.parse_datetime", "line_number": 66, "usage_type": "call"}, {"api_name": "isodate.parse_duration", "line_number": 67, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 74, "usage_type": "call"}, {"api_name": "urllib.request.urlretrieve", "line_number": 77, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 77, "usage_type": "attribute"}, {"api_name": "os.system", "line_number": 85, "usage_type": "call"}]} +{"seq_id": "38980373419", "text": "import httplib2\nimport time\n\n\nfrom apiclient.discovery import build\nfrom oauth2client.client import OAuth2WebServerFlow\nfrom oauth2client import client\n\nclass Ohnoauth():\n \n def __init__(self):\n \n #Class Vars\n self.CLIENT_ID = '189438750868.apps.googleusercontent.com'\n self.CLIENT_SECRET = 'iNuKAa92i1NOgBIusK2rW5FL'\n self.OAUTH_SCOPE = 'https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/devstorage.full_control'\n self.REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'\n self.PROJECT = 189438750868\n self.ID = 13\n self.STORAGEDATALOCATION = 'cloudextender/m2.csv'\n self.SLEEP_TIME = 10\n\n def getAuthorizeURL(self):\n self.flow = OAuth2WebServerFlow(self.CLIENT_ID, self.CLIENT_SECRET, self.OAUTH_SCOPE, self.REDIRECT_URI)\n authorize_url = self.flow.step1_get_authorize_url()\n return authorize_url\n\n def auth(self, code):\n credentials = self.flow.step2_exchange(code)\n\n # Create an httplib2.Http object and authorize it with our credentials\n http = httplib2.Http()\n http = credentials.authorize(http)\n self.predict_service = build('prediction', 'v1.6', http=http)\n\n def getPrediction(self, strg):\n #gets query from prediction API\n try:\n papi = self.predict_service.trainedmodels()\n body = {'input': {'csvInstance': [strg]}}\n result = papi.predict(body=body, id=self.ID, project=self.PROJECT).execute()\n\n return result\n\n except client.AccessTokenRefreshError:\n print (\"The credentials have been revoked or expired, please re-run\"\n \"the application to re-authorize\")\n return\n \n def train(self):\n #trains Prediction API based on file at self.STORAGEDATALOCATION\n body = {'id': self.ID, 'storageDataLocation': self.STORAGEDATALOCATION}\n papi = self.predict_service.trainedmodels()\n papi.insert(body=body, project=self.PROJECT).execute()\n \n while True:\n status = papi.get(id=self.ID, project=self.PROJECT).execute()\n state = status['trainingStatus']\n if state == 'DONE':\n break\n elif state == 'RUNNING':\n time.sleep(self.SLEEP_TIME)\n continue\n else:\n raise Exception('Training Error: ' + state)\n break\n return\n \n ", "repo_name": "Hibiscusofxp/Cloud-extender", "sub_path": "filePredict.py", "file_name": "filePredict.py", "file_ext": "py", "file_size_in_byte": 2477, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "oauth2client.client.OAuth2WebServerFlow", "line_number": 24, "usage_type": "call"}, {"api_name": "httplib2.Http", "line_number": 32, "usage_type": "call"}, {"api_name": "apiclient.discovery.build", "line_number": 34, "usage_type": "call"}, {"api_name": "oauth2client.client.AccessTokenRefreshError", "line_number": 45, "usage_type": "attribute"}, {"api_name": "oauth2client.client", "line_number": 45, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 62, "usage_type": "call"}]} +{"seq_id": "41119563639", "text": "# This is basically a copy of object_detection_tutorial.ipynb with some minor\n# changes.\n\n\nfrom PIL import Image\nfrom collections import Counter\nfrom collections import defaultdict\nfrom io import StringIO\nimport os\nimport sys\nimport tarfile\nimport zipfile\n\nfrom matplotlib import pyplot as plt\n\nimport numpy as np\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import visualization_utils as vis_util\nimport tensorflow as tf\n\n\nflags = tf.app.flags\nflags.DEFINE_string('model_checkpoint', '', 'Path to frozen graph.pb file')\nflags.DEFINE_string('label_map_path', '', 'Path to label map proto')\nflags.DEFINE_string('input_image_glob', '', 'Glob to the image(s) to detect on')\nflags.DEFINE_string('output_path', '', 'Path to output')\nflags.DEFINE_bool('summary', False, 'If true, just prints summary info')\nFLAGS = flags.FLAGS\n\n\ndef load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n\ndef main(_):\n model_checkpoint = FLAGS.model_checkpoint\n label_map_path = FLAGS.label_map_path\n input_image_glob = FLAGS.input_image_glob\n output_path = FLAGS.output_path\n\n label_map = label_map_util.load_labelmap(label_map_path)\n NUM_CLASSES = len(label_map.item)\n categories = label_map_util.convert_label_map_to_categories(\n label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\n category_index = label_map_util.create_category_index(categories)\n\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(model_checkpoint, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n # Size, in inches, of the output images.\n IMAGE_SIZE = (12, 8)\n TEST_IMAGE_PATHS = tf.gfile.Glob(input_image_glob)\n\n with detection_graph.as_default():\n with tf.Session(graph=detection_graph) as sess:\n # Definite input and output Tensors for detection_graph\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n # Each box represents a part of the image where a particular object was detected.\n detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n # Each score represent how level of confidence for each of the objects.\n # Score is shown on the result image, together with the class label.\n detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')\n detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n\n for image_path in TEST_IMAGE_PATHS:\n image = Image.open(image_path)\n # the array based representation of the image will be used later in order to prepare the\n # result image with boxes and labels on it.\n try:\n image_np = load_image_into_numpy_array(image)\n except:\n print('Failed to load image:', image_path)\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n # Actual detection.\n (boxes, scores, classes, num) = sess.run(\n [detection_boxes, detection_scores, detection_classes, num_detections],\n feed_dict={image_tensor: image_np_expanded})\n\n accepted_indexes = [i for i, x in enumerate(scores[0]) if x > .5]\n det_classes = [category_index[classes[0][i]]['name'] for i in accepted_indexes]\n class_count = Counter(det_classes)\n\n orbs = [n for n in det_classes if 'orb' in n]\n portraits = [n for n in det_classes if n == 'portrait']\n found_board = 'board' in det_classes\n\n print('finished', image_path)\n if FLAGS.summary:\n print('found {} orbs, {} portraits, board={}'.format(\n len(orbs), len(portraits), found_board))\n continue\n\n print()\n print('found {} orbs'.format(len(orbs)))\n print('found {} portraits'.format(len(portraits)))\n print('found board: ', found_board)\n print()\n\n for item, count in sorted(class_count.items()):\n print(item, count)\n\n # Visualization of the results of a detection.\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n np.squeeze(boxes),\n np.squeeze(classes).astype(np.int32),\n np.squeeze(scores),\n category_index,\n use_normalized_coordinates=True,\n line_thickness=8,\n max_boxes_to_draw=100)\n plt.figure(figsize=IMAGE_SIZE)\n plt.imshow(image_np)\n plt.show()\n\n\nif __name__ == '__main__':\n tf.app.run()\n", "repo_name": "jordengit/pad-object-detection", "sub_path": "scripts/run_inference.py", "file_name": "run_inference.py", "file_ext": "py", "file_size_in_byte": 5304, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "tensorflow.app", "line_number": 22, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 34, "usage_type": "attribute"}, {"api_name": "object_detection.utils.label_map_util.load_labelmap", "line_number": 43, "usage_type": "call"}, {"api_name": "object_detection.utils.label_map_util", "line_number": 43, "usage_type": "name"}, {"api_name": "object_detection.utils.label_map_util.convert_label_map_to_categories", "line_number": 45, "usage_type": "call"}, {"api_name": "object_detection.utils.label_map_util", "line_number": 45, "usage_type": "name"}, {"api_name": "object_detection.utils.label_map_util.create_category_index", "line_number": 47, "usage_type": "call"}, {"api_name": "object_detection.utils.label_map_util", "line_number": 47, "usage_type": "name"}, {"api_name": "tensorflow.Graph", "line_number": 49, "usage_type": "call"}, {"api_name": "tensorflow.GraphDef", "line_number": 51, "usage_type": "call"}, {"api_name": "tensorflow.gfile.GFile", "line_number": 52, "usage_type": "call"}, {"api_name": "tensorflow.gfile", "line_number": 52, "usage_type": "attribute"}, {"api_name": "tensorflow.import_graph_def", "line_number": 55, "usage_type": "call"}, {"api_name": "tensorflow.gfile.Glob", "line_number": 59, "usage_type": "call"}, {"api_name": "tensorflow.gfile", "line_number": 59, "usage_type": "attribute"}, {"api_name": "tensorflow.Session", "line_number": 62, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 74, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 74, "usage_type": "name"}, {"api_name": "numpy.expand_dims", "line_number": 82, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 90, "usage_type": "call"}, {"api_name": "object_detection.utils.visualization_utils.visualize_boxes_and_labels_on_image_array", "line_number": 112, "usage_type": "call"}, {"api_name": "object_detection.utils.visualization_utils", "line_number": 112, "usage_type": "name"}, {"api_name": "numpy.squeeze", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 115, "usage_type": "attribute"}, {"api_name": "numpy.squeeze", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 121, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 122, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 122, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 123, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 123, "usage_type": "name"}, {"api_name": "tensorflow.app.run", "line_number": 127, "usage_type": "call"}, {"api_name": "tensorflow.app", "line_number": 127, "usage_type": "attribute"}]} +{"seq_id": "16685637439", "text": "# import matplotlib as mpl\n# from mpl_toolkits.mplot3d import Axes3D\n# import numpy as np\n# import matplotlib.pyplot as plt\n#\n# mpl.rcParams['legend.fontsize'] = 10\n#\n# fig = plt.figure()\n# ax = fig.gca(projection='3d')\n# theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)\n# z = np.linspace(-2, 2, 100)\n# r = z**2 + 1\n# x = r * np.sin(theta)\n# y = r * np.cos(theta)\n# ax.plot(x, y, z, label='parametric curve')\n# ax.legend()\n#\n# plt.show()\n\n\n#-----------------------------------------------------------\n#\n# from mpl_toolkits.mplot3d import Axes3D\n# import matplotlib.pyplot as plt\n# import numpy as np\n#\n#\n# def randrange(n, vmin, vmax):\n# '''\n# Helper function to make an array of random numbers having shape (n, )\n# with each number distributed Uniform(vmin, vmax).\n# '''\n# return (vmax - vmin)*np.random.rand(n) + vmin\n#\n# fig = plt.figure()\n# ax = fig.add_subplot(111, projection='3d')\n#\n# n = 100\n#\n# # For each set of style and range settings, plot n random points in the box\n# # defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].\n# for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:\n# xs = randrange(n, 23, 32)\n# ys = randrange(n, 0, 100)\n# zs = randrange(n, zlow, zhigh)\n#\n# ax.scatter(xs, ys, zs, c='r', marker='o')\n#\n#\n# ax.set_xlabel('X Label')\n# ax.set_ylabel('Y Label')\n# ax.set_zlabel('Z Label')\n#\n# plt.show()\n\n\n#-----------------------------------------------------------\n\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nimport numpy as np\n\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\n\n# Make data.\nX = np.arange(-5, 5, 0.25)\nY = np.arange(-5, 5, 0.25)\nX, Y = np.meshgrid(X, Y)\nR = np.sqrt(X**2 + Y**2)\nZ = np.sin(R)\n\n# Plot the surface.\nsurf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,\n linewidth=0, antialiased=False)\n\n# Customize the z axis.\nax.set_zlim(-1.01, 1.01)\nax.zaxis.set_major_locator(LinearLocator(10))\nax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n\n# Add a color bar which maps values to colors.\nfig.colorbar(surf, shrink=0.5, aspect=5)\n\nplt.show()\n", "repo_name": "julianaibiapina/Inteligencia-Computacional", "sub_path": "Trabalho 03/teste.py", "file_name": "teste.py", "file_ext": "py", "file_size_in_byte": 2192, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "matplotlib.pyplot.figure", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.cm.coolwarm", "line_number": 77, "usage_type": "attribute"}, {"api_name": "matplotlib.cm", "line_number": 77, "usage_type": "name"}, {"api_name": "matplotlib.ticker.LinearLocator", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.ticker.FormatStrFormatter", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 88, "usage_type": "name"}]} +{"seq_id": "3491061009", "text": "from PyForgeAPI import Routes, Request, Response\n\nimport json\n\nroutes = Routes(debug=True)\n\n@routes.get(\"/\")\nasync def home(req: Request, res: Response):\n with open(\"person.json\", \"r+\") as f:\n person = json.load(f)\n f.close()\n\n _person = []\n\n for i in person:\n if i[\"age\"] >= int(req.query['age']):\n _person.append(i)\n\n res.status(200).json(_person).send()\n\n@routes.post(\"/person\")\nasync def person(req: Request, res: Response):\n with open(\"person.json\", \"r+\") as f:\n person = json.load(f)\n person.append(req.body.json)\n f.seek(0)\n json.dump(person, f, indent=2)\n f.close()\n\n res.sendStatus(200)\n\nroutes.run(host=\"localhost\", port=3000)", "repo_name": "luisviniciuslv/PyForgeAPI", "sub_path": "examples/Person API/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 671, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 13, "dataset": "github-code", "pt": "25", "api": [{"api_name": "PyForgeAPI.Routes", "line_number": 5, "usage_type": "call"}, {"api_name": "PyForgeAPI.Request", "line_number": 8, "usage_type": "name"}, {"api_name": "PyForgeAPI.Response", "line_number": 8, "usage_type": "name"}, {"api_name": "json.load", "line_number": 10, "usage_type": "call"}, {"api_name": "PyForgeAPI.Request", "line_number": 22, "usage_type": "name"}, {"api_name": "PyForgeAPI.Response", "line_number": 22, "usage_type": "name"}, {"api_name": "json.load", "line_number": 24, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 27, "usage_type": "call"}]} +{"seq_id": "16685599779", "text": "import math\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport itertools\n\ndata = np.loadtxt('./Trabalho 02/aerogerador.dat')\nx_treino = data[0:, 0:1] # velociade do vento\nx_treino = x_treino.reshape((1, 2250)) # transforma em um vetor de N colunas\nones = np.ones(x_treino.shape)\nx_treino = np.vstack((ones, x_treino)) # acrescenta uma linha de 1's\n\ny_treino = data[0:, 1:] # potência\ny_treino = y_treino.reshape((1, 2250)) # transforma em um vetor de N colunas\n\n# número de neurônios da camada oculta\nq1 = 1\nq2 = 2\nq3 = 3\nq4 = 4\np = 1 # número de variáveis de entrada\n\n#---------------------------------- 1 NEURÔNIO\n\n# vetor de pesos da camada oculta\nW1 = np.random.rand(q1, p+1) * 0.1# matriz de pesos onde cada elemento varia num intervalo de (0,1) em uma distribuição uniforme\n\n# ativações dos neurônios da camada oculta\nu1 = np.matmul(W1, x_treino)\n\nZ1 = np.array([[]]) # um neurônios\n\n# percorrer todas as N colunas de u\nfor i in range(0, u1.shape[1]):\n z1 = np.array([[(1 / (1 + (math.exp(-1 * u1[0:1, i:i+1][0][0]))))]])\n Z1 = np.hstack((Z1,z1))\n\n# vetor Z1 que é a entrada da camada de saída\nones = np.ones((1, Z1.shape[1]))\nZ1 = np.vstack((ones, Z1)) # acrescenta uma linha de 1's\n\n# vetor M1 de pesos da camada de saída\naux = np.matmul(y_treino, Z1.transpose())\naux2 = np.linalg.inv(np.matmul(Z1, Z1.transpose()))\nM1 = np.matmul(aux, aux2)\n\n# vetor final com os resultados da camasda de saída\ny1 = np.matmul(M1,Z1)\n\n\n#---------------------------------- 2 NEURÔNIOS\n\n# vetor de pesos da camada oculta\nW = np.random.rand(q2, p+1) * 0.1 # matriz de pesos onde cada elemento varia num intervalo de (0,1) em uma distribuição uniforme\n\n# ativações dos neurônios da camada oculta\nu = np.matmul(W, x_treino)\n\nZ = np.array([[],[]]) # dois neurônios\n#percorrer todas as N colunas de u\nfor i in range(0, u.shape[1]):\n z = np.array([[(1 / (1 + (math.exp(-1 * u[0:1, i:i+1][0][0]))))], [(1 / (1 + (math.exp(-1 * u[1:2, i:i+1][0][0]))))]])\n Z = np.hstack((Z,z))\n\n# vetor Z que é a entrada da camada de saída\nones = np.ones((1, Z.shape[1]))\nZ = np.vstack((ones, Z)) # acrescenta uma linha de 1's\n\n\n# vetor M de pesos da camada de saída\naux = np.matmul(y_treino, Z.transpose())\naux2 = np.linalg.inv(np.matmul(Z, Z.transpose()))\nM = np.matmul(aux, aux2)\nprint(M.shape)\n\n# vetor final com os resultados da camada de saída\ny = np.matmul(M,Z)\n\n#---------------------------------- 3 NEURÔNIOS\n\n# vetor de pesos da camada oculta\nW3 = np.random.rand(q3, p+1) * 0.1 # matriz de pesos onde cada elemento varia num intervalo de (0,1) em uma distribuição uniforme\n\n# ativações dos neurônios da camada oculta\nu3 = np.matmul(W3, x_treino)\n\nZ3 = np.array([[], [], []]) # três neurônios\n\n# percorrer todas as N colunas de u\nfor i in range(0, u3.shape[1]):\n z3 = np.array([[(1 / (1 + (math.exp(-1 * u3[0:1, i:i+1][0][0]))))], [(1 / (1 + (math.exp(-1 * u3[1:2, i:i+1][0][0]))))], [(1 / (1 + (math.exp(-1 * u3[2:3, i:i+1][0][0]))))]])\n Z3 = np.hstack((Z3,z3))\n\n# vetor Z1 que é a entrada da camada de saída\nones = np.ones((1, Z3.shape[1]))\nZ3 = np.vstack((ones, Z3)) # acrescenta uma linha de 1's\n\n# vetor M1 de pesos da camada de saída\naux = np.matmul(y_treino, Z3.transpose())\naux2 = np.linalg.inv(np.matmul(Z3, Z3.transpose()))\nM3 = np.matmul(aux, aux2)\n\n# vetor final com os resultados da camasda de saída\ny3 = np.matmul(M3,Z3)\n\n#---------------------------------- 4 NEURÔNIOS\n\n# vetor de pesos da camada oculta\nW4 = np.random.rand(q4, p+1) * 0.1 # matriz de pesos onde cada elemento varia num intervalo de (0,1) em uma distribuição uniforme\n\n# ativações dos neurônios da camada oculta\nu4 = np.matmul(W4, x_treino)\n\nZ4 = np.array([[], [], [], []]) # quatro neurônios\n\n# percorrer todas as N colunas de u\nfor i in range(0, u4.shape[1]):\n z4 = np.array([[(1 / (1 + (math.exp(-1 * u4[0:1, i:i+1][0][0]))))], [(1 / (1 + (math.exp(-1 * u4[1:2, i:i+1][0][0]))))], [(1 / (1 + (math.exp(-1 * u4[2:3, i:i+1][0][0]))))], [(1 / (1 + (math.exp(-1 * u4[3:4, i:i+1][0][0]))))]])\n Z4 = np.hstack((Z4,z4))\n\n# vetor Z1 que é a entrada da camada de saída\nones = np.ones((1, Z4.shape[1]))\nZ4 = np.vstack((ones, Z4)) # acrescenta uma linha de 1's\n\n# vetor M1 de pesos da camada de saída\naux = np.matmul(y_treino, Z4.transpose())\naux2 = np.linalg.inv(np.matmul(Z4, Z4.transpose()))\nM4 = np.matmul(aux, aux2)\n\n# vetor final com os resultados da camasda de saída\ny4 = np.matmul(M4,Z4)\n\n#---------------------------------- Cálculo de R^2\nprint('--> Cálculo do coeficiente de determinação \\n--> q é o número de neurônios na camada o culta')\n# variáveis auxiliares\nsoma1 = 0\nsoma2 = 0\nmedia_y = np.mean(y_treino) # média das amostras\n\n# q = 1\nR2_1N = 0\nfor aux1,aux2 in itertools.zip_longest(y_treino.reshape((2250, 1)), y1.reshape((2250, 1))):\n soma1 += (aux1 - aux2) ** 2\n soma2 += (aux1 - media_y) ** 2\nR2_1N = 1 - (soma1 / soma2)\nprint('q = 1 -> R_2 = %f' % (R2_1N))\n\n# q = 2\nfor aux1,aux2 in itertools.zip_longest(y_treino.reshape((2250, 1)), y.reshape((2250, 1))):\n soma1 += (aux1 - aux2) ** 2\n soma2 += (aux1 - media_y) ** 2\nR2_2N = 1 - (soma1 / soma2)\nprint('q = 2 -> R_2 = %f' % (R2_2N))\n\n# q = 3\nfor aux1,aux2 in itertools.zip_longest(y_treino.reshape((2250, 1)), y3.reshape((2250, 1))):\n soma1 += (aux1 - aux2) ** 2\n soma2 += (aux1 - media_y) ** 2\nR2_3N = 1 - (soma1 / soma2)\nprint('q = 3 -> R_2 = %f' % (R2_3N))\n\n# q = 4\nfor aux1,aux2 in itertools.zip_longest(y_treino.reshape((2250, 1)), y4.reshape((2250, 1))):\n soma1 += (aux1 - aux2) ** 2\n soma2 += (aux1 - media_y) ** 2\nR2_4N = 1 - (soma1 / soma2)\nprint('q = 4 -> R_2 = %f' % (R2_4N))\n\n#---------------------------------- Gráficos\n\n# 1 NEURÔNIO\nplt.figure(2)\nplt.scatter(data[0:, 0:1], data[0:, 1:]) # amostras\nplt.plot(data[0:, 0:1], y1.transpose(), color = 'red') # rede neural\nplt.ylabel('Potência')\nplt.xlabel('Velocidade do Vento')\nplt.title('Um neurônio na camada oculta')\nplt.grid(True)\n# 2 NEURÔNIOS\nplt.figure(1)\nplt.scatter(data[0:, 0:1], data[0:, 1:]) # amostras\nplt.plot(data[0:, 0:1], y.transpose(), color = 'red') # rede neural\nplt.ylabel('Potência')\nplt.xlabel('Velocidade do Vento')\nplt.title('Dois neurônios na camada oculta')\nplt.grid(True)\n# 3 NEURÔNIOS\nplt.figure(3)\nplt.scatter(data[0:, 0:1], data[0:, 1:]) # amostras\nplt.plot(data[0:, 0:1], y3.transpose(), color = 'red') # rede neural\nplt.ylabel('Potência')\nplt.xlabel('Velocidade do Vento')\nplt.title('Três neurônios na camada oculta')\nplt.grid(True)\n# 4 NEURÔNIOS\nplt.figure(4)\nplt.scatter(data[0:, 0:1], data[0:, 1:]) # amostras\nplt.plot(data[0:, 0:1], y4.transpose(), color = 'red') # rede neural\nplt.ylabel('Potência')\nplt.xlabel('Velocidade do Vento')\nplt.title('Quatro neurônios na camada oculta')\nplt.grid(True)\n\n#plt.show()\n", "repo_name": "julianaibiapina/Inteligencia-Computacional", "sub_path": "Trabalho 02/01-redeELM.py", "file_name": "01-redeELM.py", "file_ext": "py", "file_size_in_byte": 6778, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.loadtxt", "line_number": 7, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 26, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 35, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 44, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 54, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 62, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 72, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 82, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 91, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 100, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 109, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 118, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 127, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 131, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 138, "usage_type": "call"}, {"api_name": "itertools.zip_longest", "line_number": 142, "usage_type": "call"}, {"api_name": "itertools.zip_longest", "line_number": 149, "usage_type": "call"}, {"api_name": "itertools.zip_longest", "line_number": 156, "usage_type": "call"}, {"api_name": "itertools.zip_longest", "line_number": 163, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 172, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 172, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 173, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 173, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 174, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 174, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 175, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 175, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 176, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 176, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 177, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 177, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 178, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 178, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 180, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 180, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 181, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 181, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 182, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 182, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 183, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 183, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 184, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 184, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 185, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 185, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 186, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 186, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 188, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 188, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 189, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 189, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 190, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 190, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 191, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 191, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 192, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 192, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 193, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 193, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 194, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 194, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 196, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 196, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 197, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 197, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 198, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 198, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 199, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 199, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 200, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 200, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 201, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 201, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 202, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 202, "usage_type": "name"}]} +{"seq_id": "25851898512", "text": "import os.path\nimport datetime\nimport pickle\nimport tkinter as tk\nimport cv2\nfrom PIL import Image, ImageTk\nimport face_recognition\nimport util\nfrom test import test\n\nclass App:\n def __init__(self):\n self.main_window = tk.Tk()\n self.main_window.geometry(\"1200x520+350+100\") # Window maken\n self.main_window.title(\"Inloggen\")\n \n self.login_button_main_window = util.get_button(self.main_window, 'Inloggen', 'green', self.login) # Login knop maken\n self.login_button_main_window.place(x=750, y=300)\n \n self.register_new_user_button_main_window = util.get_button(self.main_window, 'Registreer gebruiker', 'gray', self.register_new_user, fg='black') # Nieuw gezicht knop maken\n self.register_new_user_button_main_window.place(x=750, y=400)\n \n self.webcam_label = util.get_img_label(self.main_window) # Locatie voor webcam\n self.webcam_label.place(x=10, y=0, width=700, height=500)\n \n self.add_webcam(self.webcam_label) # Voeg de webcam toe aan de locatie voor de webcam\n \n self.db_dir = './db'\n if not os.path.exists(self.db_dir): # Kijken of de opslaglocatie voor de afbeeldingen van gezichten al bestaat\n os.mkdir(self.db_dir)\n \n self.log_path = './log.txt'\n \n def add_webcam(self, label): # Webcam openen\n if 'cap' not in self.__dict__:\n self.cap = cv2.VideoCapture(0)\n\n self._label = label\n self.process_webcam()\n \n def process_webcam(self): # Zet de webcam in de locatie voor de webcam\n ret, frame = self.cap.read()\n\n self.most_recent_capture_arr = frame\n img_ = cv2.cvtColor(self.most_recent_capture_arr, cv2.COLOR_BGR2RGB)\n self.most_recent_capture_pil = Image.fromarray(img_)\n imgtk = ImageTk.PhotoImage(image=self.most_recent_capture_pil)\n self._label.imgtk = imgtk\n self._label.configure(image=imgtk)\n \n self._label.after(20, self.process_webcam) # Elke 20 miliseconden wordt een nieuwe afbeelding toegevoegd waardoor het een video beeld wordt\n \n def login(self):\n \n label = test( # Kijken of het gezicht in de meest recente afbeelding echt is\n image=self.most_recent_capture_arr,\n model_dir='C:/Users/Marti/Downloads/face-attendance-system-with-livenessdetection/Silent-Face-Anti-Spoofing-master/resources/anti_spoof_models',\n device_id=0\n )\n \n if label == 1: # Als het gezciht echt is gaat het programma verder met het herkennen van het gezicht\n \n name = util.recognize(self.most_recent_capture_arr, self.db_dir)\n \n if name in ['unknown_person', 'no_persons_found']:\n util.msg_box('Oh nee...', 'Onbekende gebruiker. Registreer een nieuwe gebruiker of probeer het opnieuw.') # Als de persoon niet herkend is krijgt hij een bericht\n \n else:\n util.msg_box('Welkom!', 'Welkom, {}.'.format(name)) # Welkom bericht\n with open(self.log_path, 'a') as f: # Houd een log bestand bij die bijhoudt wie en wanneer iemand is ingelogt\n f.write('{},{}\\n'.format(name, datetime.datetime.now()))\n f.close()\n self.ingelogd_menu() # NIEUW!\n \n else:\n util.msg_box('Oh nee...', 'Dat is geen echt gezicht, mij houdt je niet voor de gek!') # De gebruiker krijgt een bericht dat het gezicht niet echt is\n \n def ingelogd_menu(self):\n name = util.recognize(self.most_recent_capture_arr, self.db_dir)\n \n self.ingelogd_menu_window = tk.Toplevel(self.main_window)\n self.ingelogd_menu_window.geometry(\"1200x520+350+100\")\n self.ingelogd_menu_window.title(\"Welkom\")\n \n self.text_label_ingelogd_menu = util.get_text_label(self.ingelogd_menu_window, 'Welkom {}'.format(name))\n self.text_label_ingelogd_menu.place(x=100, y=75)\n \n self.logout_button_ingelogd_menu_window = util.get_button(self.ingelogd_menu_window, 'Uitloggen', 'red', self.logout_ingelogd_menu)\n self.logout_button_ingelogd_menu_window.place(x=100, y=300)\n \n def logout_ingelogd_menu(self):\n self.ingelogd_menu_window.destroy()\n \n def register_new_user(self):\n self.register_new_user_window = tk.Toplevel(self.main_window)\n self.register_new_user_window.geometry(\"1200x520+370+120\") # Een nieuwe pagina wordt gemaakt voor het opslaan van een nieuw gezicht\n self.register_new_user_window.title(\"registreer gebruiker\")\n \n self.accept_button_register_new_user_window = util.get_button(self.register_new_user_window, 'Accepteren', 'green', self.accept_register_new_user) # Accepteer knop maken\n self.accept_button_register_new_user_window.place(x=750, y=300)\n \n self.try_again_button_register_new_user_window = util.get_button(self.register_new_user_window, 'Opnieuw proberen', 'red', self.try_again_register_new_user) # Try again knop maken\n self.try_again_button_register_new_user_window.place(x=750, y=400)\n \n self.capture_label = util.get_img_label(self.register_new_user_window) # Foto die wordt gebruikt voor gezichtsherkenning wordt laten zien om te accepteren of opnieuw te proberen\n self.capture_label.place(x=10, y=0, width=700, height=500)\n \n self.add_img_to_label(self.capture_label)\n \n self.entry_text_register_new_user = util.get_entry_text(self.register_new_user_window) # Tekst bij tekstvak om te vertellen dat de gebruiker zijn naam daar moet invullen\n self.entry_text_register_new_user.place(x=750, y=150)\n \n self.text_label_register_new_user = util.get_text_label(self.register_new_user_window, 'Vul a.u.b, \\nuw gebruikersnaam in:') # Tekstvak voor de naam van de gebruiker\n self.text_label_register_new_user.place(x=750, y=70)\n \n def try_again_register_new_user(self): # Wanneer op try again wordt geklikt ga je terug naar het hoofdmenu\n self.register_new_user_window.destroy()\n \n def add_img_to_label(self, label): # De foto die wordt genomen voor de gezichtsherkenning wordt in het frame geplaatst\n imgtk = ImageTk.PhotoImage(image=self.most_recent_capture_pil)\n label.imgtk = imgtk\n label.configure(image=imgtk)\n \n self.register_new_user_capture = self.most_recent_capture_arr.copy()\n \n def start(self):\n self.main_window.mainloop() # Window starten\n\n def accept_register_new_user(self):\n name = self.entry_text_register_new_user.get(1.0, \"end-1c\")\n \n embeddings = face_recognition.face_encodings(self.register_new_user_capture)[0]\n file = open(os.path.join(self.db_dir, '{}.pickle'.format(name)), 'wb')\n pickle.dump(embeddings, file) # Afbeelding wordt opgeslagen\n\n util.msg_box('Succes!','De gebruiker is succesvol geregistreerd!') # Melding dat alles goed is gegaan\n \n self.register_new_user_window.destroy() # Pagina om nieuwe gebruiker te registreren wordt gesloten\n\nif __name__ == \"__main__\":\n app = App()\n app.start() # App starten", "repo_name": "MartijnC-05/PWS-Face-Recognition", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 9887, "program_lang": "python", "lang": "nl", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "tkinter.Tk", "line_number": 13, "usage_type": "call"}, {"api_name": "util.get_button", "line_number": 17, "usage_type": "call"}, {"api_name": "util.get_button", "line_number": 20, "usage_type": "call"}, {"api_name": "util.get_img_label", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path.path.exists", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 29, "usage_type": "name"}, {"api_name": "os.path.mkdir", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path", "line_number": 30, "usage_type": "name"}, {"api_name": "cv2.VideoCapture", "line_number": 36, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 45, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 45, "usage_type": "attribute"}, {"api_name": "PIL.Image.fromarray", "line_number": 46, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 46, "usage_type": "name"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 47, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 47, "usage_type": "name"}, {"api_name": "test.test", "line_number": 55, "usage_type": "call"}, {"api_name": "util.recognize", "line_number": 63, "usage_type": "call"}, {"api_name": "util.msg_box", "line_number": 66, "usage_type": "call"}, {"api_name": "util.msg_box", "line_number": 69, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 71, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 71, "usage_type": "attribute"}, {"api_name": "util.msg_box", "line_number": 76, "usage_type": "call"}, {"api_name": "util.recognize", "line_number": 79, "usage_type": "call"}, {"api_name": "tkinter.Toplevel", "line_number": 81, "usage_type": "call"}, {"api_name": "util.get_text_label", "line_number": 85, "usage_type": "call"}, {"api_name": "util.get_button", "line_number": 88, "usage_type": "call"}, {"api_name": "tkinter.Toplevel", "line_number": 95, "usage_type": "call"}, {"api_name": "util.get_button", "line_number": 99, "usage_type": "call"}, {"api_name": "util.get_button", "line_number": 102, "usage_type": "call"}, {"api_name": "util.get_img_label", "line_number": 105, "usage_type": "call"}, {"api_name": "util.get_entry_text", "line_number": 110, "usage_type": "call"}, {"api_name": "util.get_text_label", "line_number": 113, "usage_type": "call"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 120, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 120, "usage_type": "name"}, {"api_name": "face_recognition.face_encodings", "line_number": 132, "usage_type": "call"}, {"api_name": "os.path.path.join", "line_number": 133, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 133, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 133, "usage_type": "name"}, {"api_name": "pickle.dump", "line_number": 134, "usage_type": "call"}, {"api_name": "util.msg_box", "line_number": 136, "usage_type": "call"}]} +{"seq_id": "31780881722", "text": "import subprocess\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n\n def add_arguments(self, parser):\n parser.add_argument('queue', nargs='?', default='default', help='Name of the worker [default=default].')\n parser.add_argument('-c', type=int, default=1, help='Concurrency for the worker.')\n\n def handle(self, *args, **options):\n concurrency = str(options['c'])\n\n queue = options['queue']\n hostname = '%s_%s@%%h' % (settings.DAIQUIRI_APP, options['queue'])\n\n args = [\n 'celery',\n '-A', 'config',\n 'worker',\n '-Q', queue,\n '-c', concurrency,\n '-n', hostname,\n '-l', 'info'\n ]\n\n subprocess.call(args)\n", "repo_name": "UCBerkeleySETI/daiquiri", "sub_path": "daiquiri/core/management/commands/runworker.py", "file_name": "runworker.py", "file_ext": "py", "file_size_in_byte": 807, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.core.management.base.BaseCommand", "line_number": 7, "usage_type": "name"}, {"api_name": "django.conf.settings.DAIQUIRI_APP", "line_number": 17, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 17, "usage_type": "name"}, {"api_name": "subprocess.call", "line_number": 29, "usage_type": "call"}]} +{"seq_id": "14214651791", "text": "\"\"\"\nОтмена работающих запросов при возникновении исключения\n\"\"\"\nimport logging\nimport asyncio\nfrom aiohttp import ClientSession\nfrom util import async_timed\nfrom chapter_4 import fetch_status\n\n\n@async_timed()\nasync def main():\n async with ClientSession() as session:\n fetches = [\n asyncio.create_task(fetch_status(session, 'python://bad')),\n asyncio.create_task(fetch_status(session, 'https://www.example.com', delay=3)),\n asyncio.create_task(fetch_status(session, 'https://www.example.com', delay=3))\n ]\n done, pending = await asyncio.wait(fetches, return_when=asyncio.FIRST_EXCEPTION)\n print(f'Число завершившихся задач: {len(done)}')\n print(f'Число ожидающих задач: {len(pending)}')\n\n for done_task in done:\n if done_task.exception():\n logging.error('При выполнении запроса возникло исключение', exc_info=done_task.exception())\n else:\n print(done_task.result())\n\n for pending_task in pending:\n pending_task.cancel()\n\n\nif __name__ == '__main__':\n asyncio.get_event_loop().run_until_complete(main())\n", "repo_name": "yura702007/asincioProject", "sub_path": "chapter_4/listing_4_12.py", "file_name": "listing_4_12.py", "file_ext": "py", "file_size_in_byte": 1282, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "aiohttp.ClientSession", "line_number": 13, "usage_type": "call"}, {"api_name": "asyncio.create_task", "line_number": 15, "usage_type": "call"}, {"api_name": "chapter_4.fetch_status", "line_number": 15, "usage_type": "call"}, {"api_name": "asyncio.create_task", "line_number": 16, "usage_type": "call"}, {"api_name": "chapter_4.fetch_status", "line_number": 16, "usage_type": "call"}, {"api_name": "asyncio.create_task", "line_number": 17, "usage_type": "call"}, {"api_name": "chapter_4.fetch_status", "line_number": 17, "usage_type": "call"}, {"api_name": "asyncio.wait", "line_number": 19, "usage_type": "call"}, {"api_name": "asyncio.FIRST_EXCEPTION", "line_number": 19, "usage_type": "attribute"}, {"api_name": "logging.error", "line_number": 25, "usage_type": "call"}, {"api_name": "util.async_timed", "line_number": 11, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 34, "usage_type": "call"}]} +{"seq_id": "31917571283", "text": "import pygame\nimport math\n\nfrom brain import Brain\nfrom colors import *\nfrom helpers import add, dist, limit\n\n\nclass Dot:\n\n RADIUS = 5\n _MAX_VEL = 2\n\n\n def __init__(self, goal, start=None):\n width, height = pygame.display.get_surface().get_size()\n self._pos = start if start is not None else (width / 2, height - 50)\n self._vel = (0, 0)\n self._acc = (0, 0)\n\n self._start = start\n self._goal = goal\n self.brain = Brain(1500)\n\n self.isdead = False\n self.atgoal = False\n self.champion = False\n\n\n def _move(self):\n self._acc = add(self._acc, self.brain.dirs[self.brain.step])\n self.brain.step += 1\n self._vel = add(self._vel, self._acc)\n self._vel = limit(self._vel, Dot._MAX_VEL)\n self._pos = add(self._pos, self._vel)\n\n\n def _ingoal(self):\n return dist(self._pos, self._goal.pos) < 10\n\n\n def _insurf(self):\n width, height = pygame.display.get_surface().get_size()\n return Dot.RADIUS < self._pos[0] < width - self.RADIUS \\\n and Dot.RADIUS < self._pos[1] < height - self.RADIUS\n\n\n def _inobstacle(self, obstacles=None):\n if obstacles is None:\n return False\n return any([obstacle.collide(self._pos) for obstacle in obstacles])\n\n\n def update(self, obstacles=None):\n if not self.isdead and not self.atgoal:\n if self.brain.step < len(self.brain.dirs):\n self._move()\n else:\n self.isdead = True\n\n if not self._insurf() or self._inobstacle(obstacles):\n self.isdead = True\n if self._ingoal():\n self.atgoal = True\n\n\n def draw(self):\n surface = pygame.display.get_surface()\n color = GREEN if self.champion else BLACK\n pygame.draw.circle(surface, color, self._pos, Dot.RADIUS)\n\n\n def fitness(self):\n if self.atgoal:\n return 2 + 1 / (self.brain.step ** 2)\n else:\n return 1 / (dist(self._pos, self._goal.pos) ** 2)\n\n\n def clone(self):\n dot = Dot(self._goal, self._start)\n dot.brain = self.brain.clone()\n return dot\n\n\n def mutate(self, minimum=0):\n dot = Dot(self._goal, self._start)\n dot.brain = self.brain.mutate(minimum)\n return dot\n", "repo_name": "Borroot/goodot", "sub_path": "src/dot.py", "file_name": "dot.py", "file_ext": "py", "file_size_in_byte": 2328, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pygame.display.get_surface", "line_number": 16, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 16, "usage_type": "attribute"}, {"api_name": "brain.Brain", "line_number": 23, "usage_type": "call"}, {"api_name": "helpers.add", "line_number": 31, "usage_type": "call"}, {"api_name": "helpers.add", "line_number": 33, "usage_type": "call"}, {"api_name": "helpers.limit", "line_number": 34, "usage_type": "call"}, {"api_name": "helpers.add", "line_number": 35, "usage_type": "call"}, {"api_name": "helpers.dist", "line_number": 39, "usage_type": "call"}, {"api_name": "pygame.display.get_surface", "line_number": 43, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 43, "usage_type": "attribute"}, {"api_name": "pygame.display.get_surface", "line_number": 68, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 68, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 70, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 70, "usage_type": "attribute"}, {"api_name": "helpers.dist", "line_number": 77, "usage_type": "call"}]} +{"seq_id": "73659166144", "text": "import json\nimport random\nimport jieba\nimport pypinyin\nimport zhconv\n\nfrom typing import Callable\nfrom constants import SPECIAL_CHARACTERS, PINYIN_PROBABILITY, ZH_PROBABILITY\n\n\ndef replacement_processor(text: str, quest_func: Callable[[str], bool],\n resource: str = 'resources/replacement.json') -> str:\n if quest_func('Would you like to apply replacements in {}?'.format(resource)):\n with open(resource, encoding='utf-8') as file:\n replacements = json.loads(file.read())\n ans = text\n for replacement in replacements:\n if quest_func('Would you like to replace all \"{}\" with \"{}\"?'.format(replacement[0], replacement[1])):\n ans = ans.replace(replacement[0], replacement[1])\n return ans\n else:\n return text\n\n\ndef special_char_processor(text: str, quest_func: Callable[[str], bool]) -> str:\n if quest_func('Would you like to insert special characters?'):\n seg_list = list(jieba.cut(text, cut_all=False))\n for i in range(0, len(seg_list)):\n chars = list(seg_list[i])\n s = ''\n for c in chars:\n s += c\n s += random.choice(SPECIAL_CHARACTERS)\n s = s[0:-1]\n seg_list[i] = s\n text = ''.join(seg_list)\n\n return text\n\n\ndef pinyin_processor(text: str, quest_func: Callable[[str], bool]) -> str:\n if quest_func('Would you like to convert to Pin Yin?'):\n ans = ''\n for c in text:\n if random.random() < PINYIN_PROBABILITY:\n piny = pypinyin.pinyin(c)[0][0]\n if c != piny:\n piny = piny\n ans += piny\n else:\n ans += c\n return ans\n return text\n\n\ndef zh_processor(text: str, quest_func: Callable[[str], bool]) -> str:\n if quest_func('Would you like to convert to Traditional Chinese?'):\n ans = ''\n for c in text:\n if random.random() < ZH_PROBABILITY:\n ans += zhconv.convert(c, 'zh-tw')\n else:\n ans += c\n return ans\n return text\n", "repo_name": "dingwen07/Goodbye-Avalon", "sub_path": "text_processors.py", "file_name": "text_processors.py", "file_ext": "py", "file_size_in_byte": 2129, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.Callable", "line_number": 11, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 15, "usage_type": "call"}, {"api_name": "typing.Callable", "line_number": 25, "usage_type": "name"}, {"api_name": "jieba.cut", "line_number": 27, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 33, "usage_type": "call"}, {"api_name": "constants.SPECIAL_CHARACTERS", "line_number": 33, "usage_type": "argument"}, {"api_name": "typing.Callable", "line_number": 41, "usage_type": "name"}, {"api_name": "random.random", "line_number": 45, "usage_type": "call"}, {"api_name": "constants.PINYIN_PROBABILITY", "line_number": 45, "usage_type": "name"}, {"api_name": "pypinyin.pinyin", "line_number": 46, "usage_type": "call"}, {"api_name": "typing.Callable", "line_number": 56, "usage_type": "name"}, {"api_name": "random.random", "line_number": 60, "usage_type": "call"}, {"api_name": "constants.ZH_PROBABILITY", "line_number": 60, "usage_type": "name"}, {"api_name": "zhconv.convert", "line_number": 61, "usage_type": "call"}]} +{"seq_id": "32114223732", "text": "\"\"\"from multiprocessing import Pool\n\ndef f(x):\n return x*x\n\nif __name__ == '__main__':\n with Pool(5) as p:\n print(p.map(f, [1, 2, 3]))\n\n\"\"\"\n\nfrom multiprocessing import Process, Pool\nimport os, time\n\n\ndef main_map(i):\n result = i * i\n time.sleep(1)\n return result\n\n\nif __name__ == '__main__':\n inputs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n # 設定處理程序數量\n pool = Pool(4)\n\n # 運行多處理程序\n pool_outputs = pool.map(main_map, inputs)\n\n # 輸出執行結果\n print(pool_outputs)\n\n\n\n\"\"\"import multiprocessing\nimport time\n \ndef square(x):\n return x * x\n \npool = multiprocessing.Pool()\ninputs = [0,1,2,3,4]\noutputs_async = pool.map_async(square, inputs)\noutputs = outputs_async.get()\nprint(\"Output: {}\".format(outputs))\"\"\"", "repo_name": "taiwanfifi/modeling", "sub_path": "multi.py", "file_name": "multi.py", "file_ext": "py", "file_size_in_byte": 786, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "time.sleep", "line_number": 18, "usage_type": "call"}, {"api_name": "multiprocessing.Pool", "line_number": 26, "usage_type": "call"}]} +{"seq_id": "41107910715", "text": "from __future__ import print_function\nfrom collections import defaultdict\nfrom itertools import count\nimport numpy as np\nimport math\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.distributions\nfrom torch.autograd import Variable\nimport matplotlib.pyplot as plt\n\nclass Environment(object):\n \"\"\"\n The Tic-Tac-Toe Environment\n \"\"\"\n # possible ways to win\n win_set = frozenset([(0,1,2), (3,4,5), (6,7,8), # horizontal\n (0,3,6), (1,4,7), (2,5,8), # vertical\n (0,4,8), (2,4,6)]) # diagonal\n # statuses\n STATUS_VALID_MOVE = 'valid'\n STATUS_INVALID_MOVE = 'inv'\n STATUS_WIN = 'win'\n STATUS_TIE = 'tie'\n STATUS_LOSE = 'lose'\n STATUS_DONE = 'done'\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n \"\"\"Reset the game to an empty board.\"\"\"\n self.grid = np.array([0] * 9) # grid\n self.turn = 1 # whose turn it is\n self.done = False # whether game is done\n return self.grid\n\n def render(self):\n \"\"\"Print what is on the board.\"\"\"\n map = {0:'.', 1:'x', 2:'o'} # grid label vs how to plot\n print(''.join(map[i] for i in self.grid[0:3]))\n print(''.join(map[i] for i in self.grid[3:6]))\n print(''.join(map[i] for i in self.grid[6:9]))\n print('====')\n\n def check_win(self):\n \"\"\"Check if someone has won the game.\"\"\"\n for pos in self.win_set:\n s = set([self.grid[p] for p in pos])\n if len(s) == 1 and (0 not in s):\n return True\n return False\n\n def step(self, action):\n \"\"\"Mark a point on position action.\"\"\"\n assert type(action) == int and action >= 0 and action < 9\n # done = already finished the game\n if self.done:\n return self.grid, self.STATUS_DONE, self.done\n # action already have something on it\n if self.grid[action] != 0:\n return self.grid, self.STATUS_INVALID_MOVE, self.done\n # play move\n self.grid[action] = self.turn\n if self.turn == 1:\n self.turn = 2\n else:\n self.turn = 1\n # check win\n if self.check_win():\n self.done = True\n return self.grid, self.STATUS_WIN, self.done\n # check tie\n if all([p != 0 for p in self.grid]):\n self.done = True\n return self.grid, self.STATUS_TIE, self.done\n return self.grid, self.STATUS_VALID_MOVE, self.done\n\n def random_step(self):\n \"\"\"Choose a random, unoccupied move on the board to play.\"\"\"\n pos = [i for i in range(9) if self.grid[i] == 0]\n move = random.choice(pos)\n return self.step(move)\n\n def play_against_random(self, action):\n \"\"\"Play a move, and then have a random agent play the next move.\"\"\"\n state, status, done = self.step(action)\n\n # if status == self.STATUS_INVALID_MOVE:\n # print(\"invalid move\")\n\n if not done and self.turn == 2:\n state, s2, done = self.random_step()\n if done:\n if s2 == self.STATUS_WIN:\n status = self.STATUS_LOSE\n elif s2 == self.STATUS_TIE:\n status = self.STATUS_TIE\n else:\n raise ValueError(\"???\")\n return state, status, done\n\nclass Policy(nn.Module):\n \"\"\"\n The Tic-Tac-Toe Policy\n \"\"\"\n def __init__(self, input_size=27, hidden_size=512, output_size=9):\n super(Policy, self).__init__()\n self.hiddenlayer = nn.Sequential(\n nn.Linear(input_size, hidden_size),\n #nn.Dropout(),\n nn.ReLU(),\n nn.Linear(hidden_size, output_size),\n nn.Softmax(dim=-1)\n )\n\n def forward(self, x):\n return self.hiddenlayer(x)\n\n\ndef select_action(policy, state):\n \"\"\"Samples an action from the policy at the state.\"\"\"\n state = torch.from_numpy(state).long().unsqueeze(0)\n state = torch.zeros(3,9).scatter_(0,state,1).view(1,27)\n pr = policy(Variable(state))\n try:\n m = torch.distributions.Categorical(pr)\n action = m.sample()\n except:\n print(\"except\")\n print(pr)\n print(m)\n quit()\n log_prob = torch.sum(m.log_prob(action))\n return action.data[0], log_prob\n\ndef compute_returns(rewards, gamma=1.0):\n \"\"\"\n Compute returns for each time step, given the rewards\n @param rewards: list of floats, where rewards[t] is the reward\n obtained at time step t\n @param gamma: the discount factor\n @returns list of floats representing the episode's returns\n G_t = r_t + \\gamma r_{t+1} + \\gamma^2 r_{t+2} + ... \n\n >>> compute_returns([0,0,0,1], 1.0)\n [1.0, 1.0, 1.0, 1.0]\n >>> compute_returns([0,0,0,1], 0.9)\n [0.7290000000000001, 0.81, 0.9, 1.0]\n >>> compute_returns([0,-0.5,5,0.5,-10], 0.9)\n [-2.5965000000000003, -2.8850000000000002, -2.6500000000000004, -8.5, -10.0]\n \"\"\"\n res = [0]\n\n for i in range(len(rewards)):\n res[0] += rewards[i]*(gamma**i)\n\n for i in range(1, len(rewards)):\n res.append((res[i-1]-rewards[i-1])/float(gamma))\n\n return res\n\n\ndef finish_episode(saved_rewards, saved_logprobs, gamma=1.0):\n \"\"\"Samples an action from the policy at the state.\"\"\"\n policy_loss = []\n returns = compute_returns(saved_rewards, gamma)\n returns = torch.Tensor(returns)\n # subtract mean and std for faster training\n # returns = (returns - returns.mean()) / (returns.std() +\n # np.finfo(np.float32).eps)\n for log_prob, reward in zip(saved_logprobs, returns):\n policy_loss.append(-log_prob * reward)\n policy_loss = torch.cat(policy_loss).sum()\n policy_loss.backward(retain_graph=True)\n # note: retain_graph=True allows for multiple calls to .backward()\n # in a single step\n\ndef get_reward(status):\n \"\"\"Returns a numeric given an environment status.\"\"\"\n return {\n Environment.STATUS_VALID_MOVE : 0,\n Environment.STATUS_INVALID_MOVE: -10,\n Environment.STATUS_WIN : 1,\n Environment.STATUS_TIE : 0,\n Environment.STATUS_LOSE : -1\n }[status]\n\ndef train(policy, env, gamma=1.0, log_interval=1000, max_iters=50000):\n \"\"\"Train policy gradient.\"\"\"\n optimizer = optim.Adam(policy.parameters(), lr=0.001)\n scheduler = torch.optim.lr_scheduler.StepLR(\n optimizer, step_size=4500, gamma=0.7)\n running_reward = 0\n\n res_x = []\n res_y = []\n wins = 0\n ties = 0\n losses = 0\n invalids = 0\n moves = 0\n\n # for i_episode in count(1):\n for i_episode in range(max_iters):\n saved_rewards = []\n saved_logprobs = []\n state = env.reset()\n done = False\n while not done:\n action, logprob = select_action(policy, state)\n state, status, done = env.play_against_random(action)\n reward = get_reward(status)\n saved_logprobs.append(logprob)\n saved_rewards.append(reward)\n # Testing Code\n if status == 'inv':\n invalids += 1\n moves += 1\n\n R = compute_returns(saved_rewards, gamma)[0]\n running_reward += R\n\n finish_episode(saved_rewards, saved_logprobs, gamma)\n\n # Testing Code\n if status == 'win':\n wins += 1\n elif status == 'lose':\n losses += 1\n else:\n ties += 1\n\n if i_episode % log_interval == 0:\n print('Episode {}\\tAverage return: {:.2f}'.format(\n i_episode,\n running_reward / log_interval))\n print('--Win: {} Tie: {} Loss: {} InvMove: {:.3f}'.format(\n wins/float(log_interval),\n ties/float(log_interval),\n losses/float(log_interval),\n invalids/float(moves)\n ))\n res_x.append(i_episode)\n res_y.append(running_reward/log_interval)\n running_reward = 0\n wins = 0\n losses = 0\n ties = 0\n invalids = 0\n moves = 0\n\n if i_episode % (log_interval) == 0:\n torch.save(policy.state_dict(),\n \"ttt/policy-%d.pkl\" % i_episode)\n\n if i_episode % 1 == 0: # batch_size\n optimizer.step()\n scheduler.step()\n optimizer.zero_grad()\n\n return res_x, res_y\n\n\ndef first_move_distr(policy, env):\n \"\"\"Display the distribution of first moves.\"\"\"\n state = env.reset()\n state = torch.from_numpy(state).long().unsqueeze(0)\n state = torch.zeros(3,9).scatter_(0,state,1).view(1,27)\n pr = policy(Variable(state))\n return pr.data\n\n\ndef load_weights(policy, episode):\n \"\"\"Load saved weights\"\"\"\n weights = torch.load(\"ttt/policy-%d.pkl\" % episode)\n policy.load_state_dict(weights)\n\n\nif __name__ == '__main__':\n import sys\n np.random.seed(0)\n torch.manual_seed(0)\n random.seed(0)\n\n policy = Policy()\n env = Environment()\n\n if len(sys.argv) == 1:\n # `python tictactoe.py` to train the agent\n res_x, res_y = train(policy, env, gamma=0.99, max_iters=1000000)\n\n plt.plot(res_x[1:], res_y[1:])\n plt.ylabel(\"Average Return\")\n plt.xlabel(\"Episode Number\")\n plt.title(\"Training Curve for TicTacToe Policy Gradient\")\n plt.axis([0,70000,-6,1])\n plt.show()\n else:\n # `python tictactoe.py ` to print the first move distribution\n # using weightt checkpoint at episode int()\n ep = int(sys.argv[1])\n load_weights(policy, ep)\n print(\"-----------First Move-----------\")\n print(first_move_distr(policy, env))\n print(\"-----------100 games------------\")\n win, loss, tie = 0,0,0\n for i in range(100):\n state = env.reset()\n done = False\n while not done:\n action, logprob = select_action(policy, state)\n state, status, done = env.play_against_random(action)\n if done:\n if status == \"win\":\n win += 1\n elif status == \"loss\":\n loss += 1\n else:\n tie += 1\n print(\"Of 100 games: {} Wins {} Losses {} Ties\".format(win, loss, tie))\n print(\"----------Display 5 games----------\")\n print(\"Move | State\")\n for i in range(5):\n state = env.reset()\n done = False\n moves = \"\"\n while not done:\n action, logprob = select_action(policy, state)\n state, status, done = env.play_against_random(action)\n print(str(action) + \" | \" + str(state))\n if done:\n print(\"-----\" + status + \"-----\")\n print(\"-----------Winrates of all episodes-----------\")\n wins, losses, ties = [],[],[]\n x = []\n for j in range(0,70000, 1000):\n load_weights(policy, j)\n win, loss, tie = 0,0,0\n for i in range(100):\n state = env.reset()\n done = False\n while not done:\n action, logprob = select_action(policy, state)\n state, status, done = env.play_against_random(action)\n if done:\n if status == \"win\":\n win += 1\n elif status == \"loss\":\n loss += 1\n else:\n tie += 1\n # print(\"{}: Of 100 games: {} Wins {} Losses {} Ties\".format(j, win, loss, tie))\n wins.append(win)\n losses.append(loss)\n ties.append(tie)\n x.append(j)\n x = np.array(x)\n plt.plot(x, np.array(wins),label='Wins')\n plt.plot(x, np.array(losses),label=\"Losses\")\n plt.plot(x, np.array(ties), label=\"Ties\")\n plt.ylabel(\"W/L/T of 100\")\n plt.xlabel(\"Episode Number\")\n plt.legend(loc=\"best\")\n plt.title(\"Win/Loss/Tie per Episode\")\n plt.show()\n print(\"----------First move as a fn of training----------\")\n highestFirstMove = []\n for j in range(0, 70000, 1000):\n load_weights(policy, j)\n highestFirstMove.append(np.argmax(first_move_distr(policy, env)))\n plt.plot(x, np.array(highestFirstMove), label = \"Cell\")\n plt.ylabel(\"Cell selected\")\n plt.xlabel(\"Episode Number\")\n plt.legend(loc=\"best\")\n plt.title(\"Cell selected per Episode\")\n plt.show()\n", "repo_name": "bBusker/CSC411", "sub_path": "Project4/tictactoe.py", "file_name": "tictactoe.py", "file_ext": "py", "file_size_in_byte": 12778, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.array", "line_number": 36, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 85, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 106, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 106, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 112, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 112, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 113, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 113, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 115, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 115, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 116, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 116, "usage_type": "name"}, {"api_name": "torch.nn.Softmax", "line_number": 117, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 117, "usage_type": "name"}, {"api_name": "torch.from_numpy", "line_number": 126, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 127, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 128, "usage_type": "call"}, {"api_name": "torch.distributions.Categorical", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.distributions", "line_number": 130, "usage_type": "attribute"}, {"api_name": "torch.sum", "line_number": 137, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 171, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 177, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 194, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 194, "usage_type": "name"}, {"api_name": "torch.optim.lr_scheduler.StepLR", "line_number": 195, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 195, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 257, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 271, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 272, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 273, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 279, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 285, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 285, "usage_type": "attribute"}, {"api_name": "torch.manual_seed", "line_number": 286, "usage_type": "call"}, {"api_name": "random.seed", "line_number": 287, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 292, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 296, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 296, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 297, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 297, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 298, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 298, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 299, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 299, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 300, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 300, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 301, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 301, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 305, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 361, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 362, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 362, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 362, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 363, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 363, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 363, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 364, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 364, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 364, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 365, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 365, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 366, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 366, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 367, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 367, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 368, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 368, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 369, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 369, "usage_type": "name"}, {"api_name": "numpy.argmax", "line_number": 374, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 375, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 375, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 375, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 376, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 376, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 377, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 377, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 378, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 378, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 379, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 379, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 380, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 380, "usage_type": "name"}]} +{"seq_id": "32951900586", "text": "\"\"\"Setup for pip package.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom setuptools import Extension\nfrom setuptools import find_packages\nfrom setuptools import setup\nfrom setuptools.command.install import install\nfrom setuptools.dist import Distribution\n\n\nclass InstallPlatlib(install):\n def finalize_options(self):\n install.finalize_options(self)\n self.install_lib = self.install_platlib\n\n\nclass BinaryDistribution(Distribution):\n \"\"\"This class is needed in order to create OS specific wheels.\"\"\"\n\n def has_ext_modules(self):\n return True\n\n def is_pure(self):\n return False\n\n\nsetup(\n name=\"tf-locality-aware-nms\",\n version=\"0.0.1\",\n description=\"Locality-Aware NMS as a Tensorflow op.\",\n long_description=\"\"\"\n An implementation of Locality-Aware NMS as described in \n EAST: An Efficient and Accurate Scene Text detector (https://arxiv.org/abs/1704.03155)\n as a Tensorflow op meaning it can be used as any other Tensorflow function. It can also \n be included in a Tensorflow Serving build to make it available for serving.\n \"\"\",\n author=\"John Pertoft\",\n author_email=\"john.pertoft@gmail.com\",\n url=\"https://github.com/johnPertoft/locality-aware-nms\",\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n distclass=BinaryDistribution,\n cmdclass={\"install\": InstallPlatlib},\n)\n", "repo_name": "johnPertoft/locality-aware-nms", "sub_path": "pip_package/setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 1444, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "setuptools.command.install.install", "line_number": 13, "usage_type": "name"}, {"api_name": "setuptools.command.install.install.finalize_options", "line_number": 15, "usage_type": "call"}, {"api_name": "setuptools.command.install.install", "line_number": 15, "usage_type": "name"}, {"api_name": "setuptools.dist.Distribution", "line_number": 19, "usage_type": "name"}, {"api_name": "setuptools.setup", "line_number": 29, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 42, "usage_type": "call"}]} +{"seq_id": "5660927986", "text": "from brownie import accounts, config\nfrom web3 import Web3\n# from eth_utils import from_wei\n\n\nw3 = Web3(Web3.HTTPProvider(config[\"provider\"][\"http\"]))\n\nwith open(\"./contract_data/address.txt\") as file_a:\n contract_address = file_a.read()\n\nwith open(\"./contract_data/abi.json\") as file_b:\n contract_abi = file_b.read()\n\n# initialising the contract instance\ncontract_instance = w3.eth.contract(address=contract_address, abi=contract_abi)\n\n\ndef main():\n # initialising my account\n account = config[\"wallets\"][\"from_key\"][\"account\"]\n account_address = config[\"addresses\"][\"account_address\"]\n\n print(f\"The coffee contract address is {contract_instance.address}\\n\")\n\n print(\"Getting the owner of the contract..\\n\")\n\n owner = contract_instance.functions.owner().call({\"from\": account_address})\n\n print(f\"The owner of the contract is {owner}\\n\")\n\n print(f\"My address is {account_address}\\n\")\n\n if owner == account_address:\n print(\"You ARE the owner of the contract. \\n\")\n else:\n print(\"You are NOT the owner of the contract.\\n\")\n \n", "repo_name": "Okiki-Olugunna/BuyMeACoffee-V2.1", "sub_path": "scripts/get_owner_of_contract.py", "file_name": "get_owner_of_contract.py", "file_ext": "py", "file_size_in_byte": 1076, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "25", "api": [{"api_name": "web3.Web3", "line_number": 6, "usage_type": "call"}, {"api_name": "web3.Web3.HTTPProvider", "line_number": 6, "usage_type": "call"}, {"api_name": "brownie.config", "line_number": 6, "usage_type": "name"}, {"api_name": "brownie.config", "line_number": 20, "usage_type": "name"}, {"api_name": "brownie.config", "line_number": 21, "usage_type": "name"}]} +{"seq_id": "31917310453", "text": "# pylint: disable=C0413\n\"\"\"\nHoplite game AI\n\"\"\"\n\nimport os\nos.environ[\"PYGAME_HIDE_SUPPORT_PROMPT\"] = \"hide\"\nimport argparse\nimport logging\nimport hoplite\nimport hoplite.utils\nimport hoplite.game.terrain\nimport hoplite.game.moves\nimport hoplite.game.state\nimport hoplite.vision.observer\nimport hoplite.controller\nimport hoplite.monkey_runner\nimport hoplite.actuator\nimport hoplite.brain\n\n\ndef check(path):\n \"\"\"Check a game log for errors in predicted state.\n \"\"\"\n print(\"Checking %s\\n\" % os.path.realpath(path))\n with open(path, \"r\") as file:\n lines = file.readlines()\n total, errors = 0, 0\n for prev_line, next_line in zip(lines[:-1], lines[1:]):\n if prev_line.split(\"\\t\")[1] != \"move\":\n continue\n if next_line.split(\"\\t\")[1] != \"move\":\n continue\n prev_state = hoplite.game.state.GameState.from_string(prev_line.split(\"\\t\")[2])\n groundtruth = hoplite.game.state.GameState.from_string(next_line.split(\"\\t\")[2])\n if prev_state.depth != groundtruth.depth:\n continue\n total += 1\n move = hoplite.game.moves.PlayerMove.from_string(prev_line.split(\"\\t\")[3])\n prediction = move.apply(prev_state)\n prediction.status.cooldown = max(0, prediction.status.cooldown - 1)\n prediction_errors = list()\n if prediction.status != groundtruth.status:\n prediction_errors.append(\n (\"Status\", prediction.status, groundtruth.status))\n if prediction.terrain.player != groundtruth.terrain.player:\n prediction_errors.append(\n (\"Player position\", prediction.terrain.player, groundtruth.terrain.player))\n if len(prediction_errors) > 0:\n print(\"-\" * 120)\n print(\"Found error(s) from turn %d to %d\" %\n (int(prev_line.split(\"\\t\")[0]), int(next_line.split(\"\\t\")[0])))\n print(\"State:\", repr(prev_state))\n print(\"Move:\", move)\n for error_name, predicted, expected in prediction_errors:\n print(\"%s expected %s but got %s\" % (\n error_name,\n repr(expected),\n repr(predicted)\n ))\n print(\"-\" * 120 + \"\\n\")\n errors += 1\n print(\"Check run found %d errors out of %d predictions.\" % (errors, total))\n\n\ndef play(serial: str, prayers, record):\n \"\"\"Play with the monkey runner interface.\n \"\"\"\n mr_if = hoplite.ppadb_runner.PurePythonAdbInterface(serial)\n observer = hoplite.vision.observer.Observer(mr_if)\n actuator = hoplite.actuator.Actuator(mr_if)\n brain = hoplite.brain.Brain()\n starting_prayers = list()\n for prayer in prayers.strip().split(\",\"):\n if prayer == \"\":\n continue\n starting_prayers.append(hoplite.game.status.Prayer(int(prayer)))\n recorder = None\n if record:\n recorder = hoplite.controller.Recorder(observer)\n recorder.start()\n controller = hoplite.controller.Controller(observer, actuator, brain,\n starting_prayers,\n recorder=recorder)\n mr_if.open()\n try:\n controller.run()\n except KeyboardInterrupt:\n logging.warning(\"Interrupting with keyboard\")\n finally:\n try:\n mr_if.close()\n except KeyboardInterrupt:\n pass\n\n\ndef parse(args):\n \"\"\"Parse a game state to perform some analysis.\n \"\"\"\n if os.path.isfile(args.input):\n parser = hoplite.vision.observer.ScreenParser(save_parts=args.save_parts)\n stream = parser.read_stream(args.input)\n interface = hoplite.vision.classifiers.interface(stream)\n if interface == hoplite.game.state.Interface.ALTAR:\n altar = parser.observe_altar(stream)\n print(\"Found an altar with the following prayers:\", altar)\n return\n game = parser.observe_game(stream)\n else:\n game = hoplite.game.state.GameState.from_string(args.input)\n for prayer in args.prayers.strip().split(\",\"):\n if prayer != \"\":\n game.status.add_prayer(hoplite.game.status.Prayer(int(prayer)), False)\n if \"move_type\" in args:\n move_class = {\n \"walk\": hoplite.game.moves.WalkMove,\n \"leap\": hoplite.game.moves.LeapMove,\n \"bash\": hoplite.game.moves.BashMove,\n \"throw\": hoplite.game.moves.ThrowMove\n }[args.move_type]\n player_move = move_class(hoplite.utils.HexagonalCoordinates(args.x, args.y))\n game = player_move.apply(game)\n print(repr(game))\n if args.evaluate:\n brain = hoplite.brain.Brain()\n print(\"evaluation:\\t%f\" % brain.evaluate(game))\n print(\"best move:\\t%s\" % brain.pick_move(game))\n if args.render:\n game.terrain.render(show_ranges=args.show_ranges)\n\n\ndef main():\n \"\"\"Argument parsing and action taking.\n \"\"\"\n description = \"\\n\".join((\n \"Hoplite AI version %s.\" % hoplite.__version__,\n \"Check repository at https://github.com/ychalier/hoplite\"\n ))\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument(\n \"-serial\",\n type=str,\n help=\"adb serial of device\",\n default=None\n )\n parser.add_argument(\n \"-v\", \"--verbose\",\n action=\"store_true\",\n help=\"see debug messages\"\n )\n parser.add_argument(\n \"-q\", \"--quiet\",\n action=\"store_true\",\n help=\"only see warnings and errors\"\n )\n parser.add_argument(\n \"-s\", \"--silent\",\n action=\"store_true\",\n help=\"no logging output\"\n )\n subparsers = parser.add_subparsers(dest=\"action\", required=True)\n play_parser = subparsers.add_parser(\"play\")\n play_parser.add_argument(\n \"--prayers\",\n type=str,\n help=\"comma separated prayer index\",\n default=\"\",\n )\n play_parser.add_argument(\n \"-r\", \"--record\",\n action=\"store_true\",\n help=\"record the game\"\n )\n parse_parser = subparsers.add_parser(\"parse\")\n parse_parser.add_argument(\n \"-i\", \"--input\",\n type=str,\n help=\"game state notation or path to a screenshot\"\n )\n parse_subparsers = parse_parser.add_subparsers()\n parse_parser.add_argument(\n \"-p\", \"--prayers\",\n type=str,\n help=\"comma separated prayer indices\",\n default=\"\"\n )\n parse_parser.add_argument(\n \"-r\", \"--render\",\n action=\"store_true\",\n help=\"render the terrain using a PyGame window\"\n )\n parse_parser.add_argument(\n \"-sp\", \"--save-parts\",\n action=\"store_true\",\n help=\"save parts extracted during the screenshot observation to the disk\"\n )\n parse_parser.add_argument(\n \"-sr\", \"--show-ranges\",\n action=\"store_true\",\n help=\"when rendering, render demon ranges\"\n )\n parse_parser.add_argument(\n \"-ev\", \"--evaluate\",\n action=\"store_true\",\n help=\"evaluate the input game state\"\n )\n move_parser = parse_subparsers.add_parser(\"move\")\n move_parser.add_argument(\n \"move_type\",\n type=str,\n choices=[\"walk\", \"leap\", \"bash\", \"throw\"],\n help=\"move to perform within the input state\"\n )\n move_parser.add_argument(\n \"x\",\n type=int,\n help=\"move target x\"\n )\n move_parser.add_argument(\n \"y\",\n type=int,\n help=\"move target y\"\n )\n check_parser = subparsers.add_parser(\"check\")\n check_parser.add_argument(\"-i\", \"--input\", type=str, help=\"path to the log file to check\")\n args = parser.parse_args()\n log_level = logging.INFO\n if args.verbose:\n log_level = logging.DEBUG\n elif args.quiet:\n log_level = logging.WARNING\n elif args.silent:\n log_level = logging.CRITICAL\n logging.basicConfig(level=log_level)\n if args.action == \"play\":\n play(args.serial, args.prayers, args.record)\n elif args.action == \"parse\":\n parse(args)\n elif args.action == \"check\":\n check(args.input)\n\n\nmain()\n", "repo_name": "ychalier/hoplite", "sub_path": "hoplite/__main__.py", "file_name": "__main__.py", "file_ext": "py", "file_size_in_byte": 8064, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.environ", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "hoplite.game.state.GameState.from_string", "line_number": 34, "usage_type": "call"}, {"api_name": "hoplite.game", "line_number": 34, "usage_type": "attribute"}, {"api_name": "hoplite.game.state.GameState.from_string", "line_number": 35, "usage_type": "call"}, {"api_name": "hoplite.game", "line_number": 35, "usage_type": "attribute"}, {"api_name": "hoplite.game.moves.PlayerMove.from_string", "line_number": 39, "usage_type": "call"}, {"api_name": "hoplite.game", "line_number": 39, "usage_type": "attribute"}, {"api_name": "hoplite.ppadb_runner.PurePythonAdbInterface", "line_number": 69, "usage_type": "call"}, {"api_name": "hoplite.ppadb_runner", "line_number": 69, "usage_type": "attribute"}, {"api_name": "hoplite.vision.observer.Observer", "line_number": 70, "usage_type": "call"}, {"api_name": "hoplite.vision", "line_number": 70, "usage_type": "attribute"}, {"api_name": "hoplite.actuator.Actuator", "line_number": 71, "usage_type": "call"}, {"api_name": "hoplite.actuator", "line_number": 71, "usage_type": "attribute"}, {"api_name": "hoplite.brain.Brain", "line_number": 72, "usage_type": "call"}, {"api_name": "hoplite.brain", "line_number": 72, "usage_type": "attribute"}, {"api_name": "hoplite.game.status.Prayer", "line_number": 77, "usage_type": "call"}, {"api_name": "hoplite.game", "line_number": 77, "usage_type": "attribute"}, {"api_name": "hoplite.controller.Recorder", "line_number": 80, "usage_type": "call"}, {"api_name": "hoplite.controller", "line_number": 80, "usage_type": "attribute"}, {"api_name": "hoplite.controller.Controller", "line_number": 82, "usage_type": "call"}, {"api_name": "hoplite.controller", "line_number": 82, "usage_type": "attribute"}, {"api_name": "logging.warning", "line_number": 89, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 100, "usage_type": "call"}, {"api_name": "os.path", "line_number": 100, "usage_type": "attribute"}, {"api_name": "hoplite.vision.observer.ScreenParser", "line_number": 101, "usage_type": "call"}, {"api_name": "hoplite.vision", "line_number": 101, "usage_type": "attribute"}, {"api_name": "hoplite.vision.classifiers.interface", "line_number": 103, "usage_type": "call"}, {"api_name": "hoplite.vision", "line_number": 103, "usage_type": "attribute"}, {"api_name": "hoplite.game", "line_number": 104, "usage_type": "attribute"}, {"api_name": "hoplite.game.state.GameState.from_string", "line_number": 110, "usage_type": "call"}, {"api_name": "hoplite.game", "line_number": 110, "usage_type": "attribute"}, {"api_name": "hoplite.game.status.Prayer", "line_number": 113, "usage_type": "call"}, {"api_name": "hoplite.game", "line_number": 113, "usage_type": "attribute"}, {"api_name": "hoplite.game", "line_number": 116, "usage_type": "attribute"}, {"api_name": "hoplite.game", "line_number": 117, "usage_type": "attribute"}, {"api_name": "hoplite.game", "line_number": 118, "usage_type": "attribute"}, {"api_name": "hoplite.game", "line_number": 119, "usage_type": "attribute"}, {"api_name": "hoplite.utils.HexagonalCoordinates", "line_number": 121, "usage_type": "call"}, {"api_name": "hoplite.utils", "line_number": 121, "usage_type": "attribute"}, {"api_name": "hoplite.brain.Brain", "line_number": 125, "usage_type": "call"}, {"api_name": "hoplite.brain", "line_number": 125, "usage_type": "attribute"}, {"api_name": "hoplite.__version__", "line_number": 136, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 139, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 227, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 229, "usage_type": "attribute"}, {"api_name": "logging.WARNING", "line_number": 231, "usage_type": "attribute"}, {"api_name": "logging.CRITICAL", "line_number": 233, "usage_type": "attribute"}, {"api_name": "logging.basicConfig", "line_number": 234, "usage_type": "call"}]} +{"seq_id": "33611421243", "text": "\nfrom django.shortcuts import render,redirect\nfrom django.http import HttpResponse\nfrom leads.forms import LeadForm,LeadModelForm\nfrom leads.models import *\n\n# Create your views here.\n\ndef lead_list(request):\n leads=Lead.objects.all()\n context={\n 'leads':leads\n \n }\n return render(request,'lead_list.html',context)\n\n#this is rajkumar.\nprint(\"this is venkat\")\ndef lead_detail(request,pk):\n lead=Lead.objects.get(id=pk)\n context={\n 'lead':lead\n }\n \n return render(request,'lead_detail.html',context)\n\n\n# def lead_update(request,pk):\n \n# form=LeadForm()\n# lead=Lead.objects.get(id=pk)\n# print(request.POST)\n# if request.method=='POST':\n# print('receiving post request')\n# form=LeadForm(request.POST)\n# if form.is_valid():\n# print('form is valid')\n# print(form.cleaned_data)\n\n# first_name=form.cleaned_data['first_name']\n# last_name=form.cleaned_data['last_name']\n# age=form.cleaned_data['age']\n \n \n# lead.first_name=first_name\n# lead.last_name=last_name\n# lead.age=age\n# lead.save()\n \n \n# print('The lead has been created')\n# return redirect('/')\n# context={\n# 'form':form,\n# 'lead':lead\n# }\n\n \n# return render(request,'lead_update.html',context)\n\ndef lead_update(request,pk):\n lead=Lead.objects.get(id=pk)\n form=LeadModelForm(instance=lead)\n if request.method=='POST':\n form=LeadModelForm(request.POST,instance=lead)\n if form.is_valid():\n form.save()\n return redirect('/')\n context={\n 'form':form,\n 'lead':lead\n }\n return render(request,'lead_update.html',context)\n\n\ndef lead_delete(request,pk):\n lead=Lead.objects.get(id=pk)\n lead.delete()\n return redirect('/')\n\n\n\n\n\n\n\n\n\n\n\n# def lead_create(request):\n# form=LeadForm()\n# # print(request.POST)\n# if request.method=='POST':\n# print('receiving post request')\n# form=LeadForm(request.POST)\n# if form.is_valid():\n# print('form is valid')\n# print(form.cleaned_data)\n\n# first_name=form.cleaned_data['first_name']\n# last_name=form.cleaned_data['last_name']\n# age=form.cleaned_data['age']\n# agent=Agent.objects.first()\n# Lead.objects.create(\n# first_name=first_name,\n# last_name=last_name,\n# age=age,\n# agent=agent\n# )\n# print('The lead has been created')\n# return redirect('/')\n\n\n# context={\n# 'form':form\n# }\n# return render(request, 'lead_create.html',context)\n\ndef lead_create(request):\n form=LeadModelForm()\n # print(request.POST)\n if request.method=='POST':\n print('receiving post request')\n form=LeadModelForm(request.POST)\n if form.is_valid():\n # print('form is valid')\n # print(form.cleaned_data)\n\n # first_name=form.cleaned_data['first_name']\n # last_name=form.cleaned_data['last_name']\n # age=form.cleaned_data['age']\n # agent=form.cleaned_data['agent']\n # Lead.objects.create(\n # first_name=first_name,\n # last_name=last_name,\n # age=age,\n # agent=agent\n # )\n # the above commented code is equal to\n form.save()\n\n\n print('The lead has been created')\n return redirect('/')\n\n\n context={\n 'form':form\n }\n return render(request, 'lead_create.html',context)\n\n\n\n\n ", "repo_name": "yattapuRajkumar/Practice", "sub_path": "leads/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 3769, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "leads.forms", "line_number": 10, "usage_type": "name"}, {"api_name": "leads.forms", "line_number": 12, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 15, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 25, "usage_type": "call"}, {"api_name": "leads.forms.LeadModelForm", "line_number": 63, "usage_type": "call"}, {"api_name": "leads.forms.LeadModelForm", "line_number": 65, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 68, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 73, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 79, "usage_type": "call"}, {"api_name": "leads.forms.LeadModelForm", "line_number": 121, "usage_type": "call"}, {"api_name": "leads.forms.LeadModelForm", "line_number": 125, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 145, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 151, "usage_type": "call"}]} +{"seq_id": "74548712065", "text": "# Tk_demo_03_slider.py\n# TKinter demo\n# Play a sinusoid using Pyaudio. Use two sliders to adjust the frequency and gain.\n\nfrom math import cos, pi \nimport pyaudio\nimport struct\nimport sys\nimport numpy as np\n\nif sys.version_info[0] < 3:\n\t# for Python 2\n\timport Tkinter as Tk\nelse:\n\t# for Python 3\n\timport tkinter as Tk \t\n\ndef fun_quit():\n global PLAY\n print('I quit')\n PLAY = False\n\nFs = 8000 # rate (samples/second)\ngain = 0.2 * 2**15\n\n# Define Tkinter root\ntop = Tk.Tk()\n\n# Define Tk variables\nf1 = Tk.DoubleVar()\ngain = Tk.DoubleVar()\n\n# Initialize Tk variables\nf1.set(200) # f1 : frequency of sinusoid (Hz)\ngain.set(0.2 * 2**15)\n\n# Define buttons\nS_freq = Tk.Scale(top, label = 'Frequency', variable = f1, from_ = 100, to = 400, tickinterval = 100)\nS_gain = Tk.Scale(top, label = 'Gain', variable = gain, from_ = 0, to = 2**15-1)\nBquit = Tk.Button(top, text = 'Quit', command = fun_quit)\nMAXVALUE = 2**15-1\n\n# Place buttons\nBquit.pack(side = Tk.BOTTOM, fill = Tk.X)\nS_freq.pack(side = Tk.LEFT)\nS_gain.pack(side = Tk.LEFT)\n\n# Create Pyaudio object\np = pyaudio.PyAudio()\nstream = p.open(\n format = pyaudio.paInt16, \n channels = 1, \n rate = Fs,\n input = False, \n output = True,\n frames_per_buffer = 128) \n # specify low frames_per_buffer to reduce latency\n\ntheta = 0\nPLAY = True\n\nBLOCKLEN = 256\noutput_block = [0 for n in range(0, BLOCKLEN)]\nnew_output_block = [0 for n in range(0, BLOCKLEN)]\nFinal_output = [0 for n in range(0, BLOCKLEN)]\n \n\nprint('* Start')\nwhile PLAY: \n o_gain = gain.get()\n top.update()\n\n n_gain = gain.get() \n\n om1 = 2.0 * pi * f1.get() / Fs\n if (n_gain != o_gain):\n diff = n_gain - o_gain\n for i in range(0, BLOCKLEN):\n theta = theta + om1\n \n o_gain = o_gain + (diff / BLOCKLEN)\n output_block[i] = int(o_gain * cos(theta)) \n output_block[i] = np.clip(output_block[i], -MAXVALUE, +MAXVALUE)\n output_block[i] = output_block[i].astype(int)\n\n else: \n for i in range(0, BLOCKLEN):\n theta = theta + om1\n \n output_block[i] = int(n_gain * cos(theta)) \n output_block[i] = np.clip(output_block[i], -MAXVALUE, +MAXVALUE)\n output_block[i] = output_block[i].astype(int)\n\n if theta > pi:\n theta = theta - 2.0 * pi\n binary_data = struct.pack('h' * BLOCKLEN, *output_block) # 'h' for 16 bits\n stream.write(binary_data)\nprint('* Finished')\n\nstream.stop_stream()\nstream.close()\np.terminate()\n", "repo_name": "debugger1809/DSP_LAB_Waveform_properties", "sub_path": "Tk_demo_03_slider_new.py", "file_name": "Tk_demo_03_slider_new.py", "file_ext": "py", "file_size_in_byte": 2412, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sys.version_info", "line_number": 11, "usage_type": "attribute"}, {"api_name": "tkinter.Tk", "line_number": 27, "usage_type": "call"}, {"api_name": "tkinter.DoubleVar", "line_number": 30, "usage_type": "call"}, {"api_name": "tkinter.DoubleVar", "line_number": 31, "usage_type": "call"}, {"api_name": "tkinter.Scale", "line_number": 38, "usage_type": "call"}, {"api_name": "tkinter.Scale", "line_number": 39, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 40, "usage_type": "call"}, {"api_name": "tkinter.BOTTOM", "line_number": 44, "usage_type": "attribute"}, {"api_name": "tkinter.X", "line_number": 44, "usage_type": "attribute"}, {"api_name": "tkinter.LEFT", "line_number": 45, "usage_type": "attribute"}, {"api_name": "tkinter.LEFT", "line_number": 46, "usage_type": "attribute"}, {"api_name": "pyaudio.PyAudio", "line_number": 49, "usage_type": "call"}, {"api_name": "pyaudio.paInt16", "line_number": 51, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 75, "usage_type": "name"}, {"api_name": "math.cos", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 83, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 91, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 94, "usage_type": "name"}, {"api_name": "math.pi", "line_number": 95, "usage_type": "name"}, {"api_name": "struct.pack", "line_number": 96, "usage_type": "call"}]} +{"seq_id": "14624454458", "text": "# -*- coding: UTF-8 -*-\n# 使用爬虫直接访问 http://www.bilibili.com/video/douga-else-1.html 时获取的网页并没有内容\n# 经过分析后发现浏览器请求 http://www.bilibili.com/list/default-27-1-2015-10-04~2015-10-11.html 这样的链接后将内容整体添加到页面之上\nimport requests\nimport time\nimport Queue\nfrom bs4 import BeautifulSoup\nimport threading\n\n\ndef url_generate(n):\n start_date = time.localtime(time.time() - 60 * 60 * 24 * 7)\n url = 'http://www.bilibili.com/list/default-27-' + str(n) + '-' + time.strftime(\"%Y-%m-%d\", start_date) + '~' + \\\n time.strftime(\"%Y-%m-%d\", time.localtime()) + '.html'\n return url\n\n\ndef get_page(q):\n for x in xrange(10):\n url = url_generate(x + 1)\n q.put(requests.get(url).content)\n\n\ndef parse_page(q):\n for x in xrange(10):\n page = q.get(True)\n tree = BeautifulSoup(page, 'lxml')\n items = tree.find_all('div', class_='l-item')\n result = []\n for item in items:\n title = item.find('div', class_='info').text\n view = item.find('i', class_='gk').text\n store = item.find('i', class_='sc').text\n barrage = item.find('i', class_='dm').text\n user_name = item.find('i', class_='up r10000').text\n date = item.find('i', class_='date').text\n res = user_name + u' ' + date + u'\\n' + view + u' ' + store \\\n + u' ' + barrage + u'\\n' + title + u'\\n'\n result.append(res.encode('utf-8'))\n with open('result.txt', 'a') as f:\n f.write('\\n'.join(result) + '\\n')\n f.close()\n\n\ndef multithread_scraping():\n queue = Queue.Queue()\n t1 = threading.Thread(target=get_page, args=(queue,))\n t2 = threading.Thread(target=parse_page, args=(queue,))\n t1.start()\n t2.start()\n t1.join()\n t2.join()\n\n\nif __name__ == '__main__':\n multithread_scraping()\n", "repo_name": "Mrfuture1/qunar_scraping", "sub_path": "other/bilibili_scraping.py", "file_name": "bilibili_scraping.py", "file_ext": "py", "file_size_in_byte": 1921, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "time.localtime", "line_number": 12, "usage_type": "call"}, {"api_name": "time.time", "line_number": 12, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 13, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 14, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 14, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 21, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 27, "usage_type": "call"}, {"api_name": "Queue.Queue", "line_number": 46, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 47, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 48, "usage_type": "call"}]} +{"seq_id": "9675825549", "text": "from collections import Counter\nfrom datetime import datetime\n\nfrom django.test import TestCase\n\nfrom .models import Artist, Album, Track\n\n\nclass TestManagers(TestCase):\n def setUp(self):\n self.track_ix = 0\n self.album_ix = 0\n self.artist_ix = 0\n\n\n def test_00_tracks_with_five_stars(self):\n track1 = self.create_track(rating=5)\n track2 = self.create_track(rating=4)\n track3 = self.create_track(rating=5)\n\n self.assertItemsEqual(\n [track1, track3],\n Track.objects.with_five_stars()\n )\n\n\n def test_01_tracks_with_more_than_twenty_listens(self):\n track1 = self.create_track(listens=19)\n track2 = self.create_track(listens=20)\n track3 = self.create_track(listens=21)\n\n self.assertItemsEqual(\n [track3],\n Track.objects.with_more_than_twenty_listens()\n )\n\n\n def test_02_albums_earliest_released(self):\n album1 = self.create_album(release_date=datetime(2013, 1, 1))\n album2 = self.create_album(release_date=datetime(2014, 1, 1))\n album3 = self.create_album(release_date=datetime(2012, 1, 1))\n\n self.assertEqual(album3, Album.objects.earliest_released())\n\n\n def test_03_tracks_n_most_listened_to(self):\n track1 = self.create_track(listens=19)\n track2 = self.create_track(listens=20)\n track3 = self.create_track(listens=21)\n\n self.assertItemsEqual(\n [track3],\n Track.objects.n_most_listened_to(1)\n )\n\n self.assertItemsEqual(\n [track3, track2],\n Track.objects.n_most_listened_to(2)\n )\n\n\n def test_04_tracks_about_love(self):\n track1 = self.create_track(title='All you need is love')\n track2 = self.create_track(title='Love me do')\n track3 = self.create_track(title='Yesterday')\n\n self.assertItemsEqual(\n [track1, track2],\n Track.objects.about_love()\n )\n\n\n def test_05_tracks_not_about_love(self):\n track1 = self.create_track(title='All you need is love')\n track2 = self.create_track(title='Love me do')\n track3 = self.create_track(title='Yesterday')\n\n self.assertItemsEqual(\n [track3],\n Track.objects.not_about_love()\n )\n\n\n def test_06_albums_with_tracks_about_love(self):\n album1 = self.create_album()\n album2 = self.create_album()\n self.create_track(title='All you need is love', album=album1)\n self.create_track(title='Yesterday', album=album2)\n\n self.assertItemsEqual(\n [album1],\n Album.objects.with_tracks_about_love()\n )\n\n\n def test_07_artists_with_tracks_about_love(self):\n artist1 = self.create_artist()\n artist2 = self.create_artist()\n album1 = self.create_album(artists=[artist1])\n album2 = self.create_album(artists=[artist2])\n self.create_track(title='All you need is love', album=album1)\n self.create_track(title='Yesterday', album=album2)\n\n self.assertItemsEqual(\n [artist1],\n Artist.objects.with_tracks_about_love()\n )\n\n\n def test_08_albums_released_in_month(self):\n album1 = self.create_album(release_date=datetime(2014, 1, 1))\n album2 = self.create_album(release_date=datetime(2014, 2, 1))\n album3 = self.create_album(release_date=datetime(2014, 3, 1))\n\n self.assertItemsEqual(\n [album2],\n Album.objects.released_in_month(2)\n )\n\n\n def test_09_tracks_with_one_star_or_zero_listens(self):\n track1 = self.create_track(listens=0, rating=3)\n track2 = self.create_track(listens=10, rating=3)\n track3 = self.create_track(listens=10, rating=1)\n\n self.assertItemsEqual(\n [track1, track3],\n Track.objects.with_one_star_or_zero_listens()\n )\n\n\n def test_10_albums_purchased_on_day_of_release(self):\n album1 = self.create_album(\n release_date=datetime(2014, 1, 1),\n purchase_date=datetime(2014, 2, 1)\n )\n album2 = self.create_album(\n release_date=datetime(2014, 2, 1),\n purchase_date=datetime(2014, 2, 1)\n )\n album3 = self.create_album(\n release_date=datetime(2014, 3, 1),\n purchase_date=datetime(2014, 3, 2)\n )\n\n self.assertItemsEqual(\n [album2],\n Album.objects.purchased_on_day_of_release()\n )\n\n\n def test_11_albums_purchased_after_day_of_release(self):\n album1 = self.create_album(\n release_date=datetime(2014, 1, 1),\n purchase_date=datetime(2014, 2, 1)\n )\n album2 = self.create_album(\n release_date=datetime(2014, 2, 1),\n purchase_date=datetime(2014, 2, 1)\n )\n album3 = self.create_album(\n release_date=datetime(2014, 3, 1),\n purchase_date=datetime(2014, 3, 2)\n )\n\n self.assertItemsEqual(\n [album1, album3],\n Album.objects.purchased_after_day_of_release()\n )\n\n\n def test_12_albums_with_more_than_one_artist(self):\n artist1 = self.create_artist()\n artist2 = self.create_artist()\n album1 = self.create_album(artists=[artist1])\n album2 = self.create_album(artists=[artist1, artist2])\n album3 = self.create_album(artists=[artist2])\n\n self.assertItemsEqual(\n [album2],\n Album.objects.with_more_than_one_artist()\n )\n\n\n def test_13_album_with_highest_rating(self):\n album1 = self.create_album(rating=3)\n album2 = self.create_album(rating=5)\n album3 = self.create_album(rating=4)\n\n self.assertEqual(\n album2,\n Album.objects.with_highest_rating()\n )\n\n\n def test_14_album_with_highest_average_track_rating(self):\n album1 = self.create_album()\n album2 = self.create_album()\n self.create_track(album=album1, rating=2)\n self.create_track(album=album1, rating=3)\n self.create_track(album=album2, rating=3)\n self.create_track(album=album2, rating=4)\n\n self.assertEqual(\n album2,\n Album.objects.with_highest_average_track_rating()\n )\n\n\n def create_track(self, **extra_params):\n params = {\n 'title': self.get_next_track_title(),\n 'rating': 3,\n 'listens': 10,\n }\n\n params.update(extra_params)\n\n if 'album' not in params:\n params['album'] = self.create_album()\n\n track = Track(**params)\n track.save()\n return track\n\n\n def create_album(self, **extra_params):\n params = {\n 'name': self.get_next_album_name(),\n 'rating': 3,\n 'release_date': datetime(2014, 6, 1),\n 'purchase_date': datetime(2014, 6, 2),\n }\n\n params.update(extra_params)\n\n if 'artists' in params:\n artists = params.pop('artists')\n else:\n artists = None\n\n album = Album(**params)\n album.save()\n\n if artists is not None:\n album.artists = artists\n album.save()\n\n return album\n\n\n def create_artist(self, **extra_params):\n params = {\n 'name': self.get_next_artist_name(),\n }\n\n params.update(extra_params)\n artist = Artist(**params)\n artist.save()\n return artist\n\n\n def get_next_track_title(self):\n self.track_ix += 1\n return 'Track {}'.format(self.track_ix)\n\n\n def get_next_album_name(self):\n self.album_ix += 1\n return 'Album {}'.format(self.album_ix)\n\n\n def get_next_artist_name(self):\n self.artist_ix += 1\n return 'Artist {}'.format(self.artist_ix)\n\n\n def assertItemsEqual(self, lhs, rhs):\n '''This method was removed from Python 3.'''\n if Counter(lhs) != Counter(rhs):\n raise AssertionError('Expected {} to equal {}'.format(lhs, rhs))\n\n", "repo_name": "inglesp/django-katas", "sub_path": "django_katas/tests.py", "file_name": "tests.py", "file_ext": "py", "file_size_in_byte": 8030, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.test.TestCase", "line_number": 9, "usage_type": "name"}, {"api_name": "models.Track.objects.with_five_stars", "line_number": 23, "usage_type": "call"}, {"api_name": "models.Track.objects", "line_number": 23, "usage_type": "attribute"}, {"api_name": "models.Track", "line_number": 23, "usage_type": "name"}, {"api_name": "models.Track.objects.with_more_than_twenty_listens", "line_number": 34, "usage_type": "call"}, {"api_name": "models.Track.objects", "line_number": 34, "usage_type": "attribute"}, {"api_name": "models.Track", "line_number": 34, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 40, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 41, "usage_type": "call"}, {"api_name": "models.Album.objects.earliest_released", "line_number": 43, "usage_type": "call"}, {"api_name": "models.Album.objects", "line_number": 43, "usage_type": "attribute"}, {"api_name": "models.Album", "line_number": 43, "usage_type": "name"}, {"api_name": "models.Track.objects.n_most_listened_to", "line_number": 53, "usage_type": "call"}, {"api_name": "models.Track.objects", "line_number": 53, "usage_type": "attribute"}, {"api_name": "models.Track", "line_number": 53, "usage_type": "name"}, {"api_name": "models.Track.objects.n_most_listened_to", "line_number": 58, "usage_type": "call"}, {"api_name": "models.Track.objects", "line_number": 58, "usage_type": "attribute"}, {"api_name": "models.Track", "line_number": 58, "usage_type": "name"}, {"api_name": "models.Track.objects.about_love", "line_number": 69, "usage_type": "call"}, {"api_name": "models.Track.objects", "line_number": 69, "usage_type": "attribute"}, {"api_name": "models.Track", "line_number": 69, "usage_type": "name"}, {"api_name": "models.Track.objects.not_about_love", "line_number": 80, "usage_type": "call"}, {"api_name": "models.Track.objects", "line_number": 80, "usage_type": "attribute"}, {"api_name": "models.Track", "line_number": 80, "usage_type": "name"}, {"api_name": "models.Album.objects.with_tracks_about_love", "line_number": 92, "usage_type": "call"}, {"api_name": "models.Album.objects", "line_number": 92, "usage_type": "attribute"}, {"api_name": "models.Album", "line_number": 92, "usage_type": "name"}, {"api_name": "models.Artist.objects.with_tracks_about_love", "line_number": 106, "usage_type": "call"}, {"api_name": "models.Artist.objects", "line_number": 106, "usage_type": "attribute"}, {"api_name": "models.Artist", "line_number": 106, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 111, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 112, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 113, "usage_type": "call"}, {"api_name": "models.Album.objects.released_in_month", "line_number": 117, "usage_type": "call"}, {"api_name": "models.Album.objects", "line_number": 117, "usage_type": "attribute"}, {"api_name": "models.Album", "line_number": 117, "usage_type": "name"}, {"api_name": "models.Track.objects.with_one_star_or_zero_listens", "line_number": 128, "usage_type": "call"}, {"api_name": "models.Track.objects", "line_number": 128, "usage_type": "attribute"}, {"api_name": "models.Track", "line_number": 128, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 134, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 135, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 138, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 139, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 142, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 143, "usage_type": "call"}, {"api_name": "models.Album.objects.purchased_on_day_of_release", "line_number": 148, "usage_type": "call"}, {"api_name": "models.Album.objects", "line_number": 148, "usage_type": "attribute"}, {"api_name": "models.Album", "line_number": 148, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 154, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 155, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 158, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 159, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 162, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 163, "usage_type": "call"}, {"api_name": "models.Album.objects.purchased_after_day_of_release", "line_number": 168, "usage_type": "call"}, {"api_name": "models.Album.objects", "line_number": 168, "usage_type": "attribute"}, {"api_name": "models.Album", "line_number": 168, "usage_type": "name"}, {"api_name": "models.Album.objects.with_more_than_one_artist", "line_number": 181, "usage_type": "call"}, {"api_name": "models.Album.objects", "line_number": 181, "usage_type": "attribute"}, {"api_name": "models.Album", "line_number": 181, "usage_type": "name"}, {"api_name": "models.Album.objects.with_highest_rating", "line_number": 192, "usage_type": "call"}, {"api_name": "models.Album.objects", "line_number": 192, "usage_type": "attribute"}, {"api_name": "models.Album", "line_number": 192, "usage_type": "name"}, {"api_name": "models.Album.objects.with_highest_average_track_rating", "line_number": 206, "usage_type": "call"}, {"api_name": "models.Album.objects", "line_number": 206, "usage_type": "attribute"}, {"api_name": "models.Album", "line_number": 206, "usage_type": "name"}, {"api_name": "models.Track", "line_number": 222, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 231, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 232, "usage_type": "call"}, {"api_name": "models.Album", "line_number": 242, "usage_type": "call"}, {"api_name": "models.Artist", "line_number": 258, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 280, "usage_type": "call"}]} +{"seq_id": "5611673931", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('utils', '0018_auto_20150505_1817'),\n ('knowledgehubs', '0004_auto_20150505_1817'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='knowledgehub',\n name='SubCategory',\n field=models.ForeignKey(related_name=b'knowledgehubs',null=True,blank=True, to='utils.SubCategory'),\n preserve_default=True,\n ),\n ]\n", "repo_name": "pharingee/OuroilMoney", "sub_path": "ouroilmoney/apps/knowledgehubs/migrations/0005_knowledgehub_subcategory.py", "file_name": "0005_knowledgehub_subcategory.py", "file_ext": "py", "file_size_in_byte": 560, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 7, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 15, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 15, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 18, "usage_type": "name"}]} +{"seq_id": "43284209422", "text": "import keras\nimport argparse\n# from keras.utils.generic_utils import CustomObjectScope\nimport coremltools\n\n\ndef gen_argparser():\n parser = argparse.ArgumentParser(description=\"Convert a Keras Model to a CoreML model\")\n parser.add_argument(\"path\", type=str)\n parser.add_argument(\"out\", type=str)\n return parser\n\n\ndef main():\n parser = gen_argparser()\n args = parser.parse_args()\n\n converted_model = coremltools.converters.keras.convert(args.path,\n input_names=\"image\",\n image_input_names=\"image\",\n class_labels=[\"facebook\", \"notes\", \"other\", \"whatsapp\", \"tinder\", \"reddit\", \"youtube\", \"siri\", \"twitter\", \"settings\"],\n output_names=\"classLabelProbs\",\n image_scale=1/255.0)\n\n converted_model.save(args.out)\n\n\nif __name__ == \"__main__\":\n main()\n", "repo_name": "Irvel/Actionable-Screenshots", "sub_path": "convert_keras_to_mlmodel.py", "file_name": "convert_keras_to_mlmodel.py", "file_ext": "py", "file_size_in_byte": 1058, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 8, "usage_type": "call"}, {"api_name": "coremltools.converters.keras.convert", "line_number": 18, "usage_type": "call"}, {"api_name": "coremltools.converters", "line_number": 18, "usage_type": "attribute"}]} +{"seq_id": "74270282946", "text": "from datetime import datetime\nfrom typing import Optional, Tuple, List\n\nfrom PIL import Image\nfrom ximea import xiapi\n\nfrom .device import Device, check_initialized\n\n# Unsure how cooperative xiapi.Camera is so did not use multiple inheritance\n# will need to figure out the method resolution order if using multiple inheritance\nclass XimeaCamera(Device):\n save_directory = 'data/imaging/'\n\n def __init__(self, name: str):\n super().__init__(name)\n self.cam = xiapi.Camera()\n # defaults, changeable for each instance\n # could use dictionary but lose IDE hinting\n # could consider a namedtuple to keep descriptive context of each param while still being able to use an iterative\n # for now, individual params\n self._default_imgdataformat = 'XI_RGB24'\n self._default_exposure_time = 50000\n self._default_gain = 0.0\n # default wb coeffs below technically constants, leaving uncaptilaized\n self._default_wb_kr = 1.531\n self._default_wb_kg = 1.0\n self._default_wb_kb = 1.305\n # self.set_default_params() # done in initalize because cam is not yet open here\n\n # no setter for imgdataformat at the moment\n @property\n def default_imgdataformat(self) -> str:\n return self._default_imgdataformat\n \n @property\n def default_exposure_time(self) -> int:\n return self._default_exposure_time\n \n @default_exposure_time.setter\n def default_exposure_time(self, exposure_time: int):\n if exposure_time > 0:\n self._default_exposure_time = int(exposure_time)\n\n @property\n def default_gain(self) -> float:\n return self._default_gain\n\n @default_gain.setter\n def default_gain(self, gain: float):\n # there is an upper limit for this but not 100% sure what it is\n if gain >= 0.0:\n self._default_gain = gain\n \n # no setter for default wb coeffs\n @property\n def default_wb_kr(self) -> float:\n return self._default_wb_kr\n\n @property\n def default_wb_kg(self) -> float:\n return self._default_wb_kg\n\n @property\n def default_wb_kb(self) -> float:\n return self._default_wb_kb\n\n def set_default_params(self):\n self.cam.set_imgdataformat(self._default_imgdataformat)\n self.cam.set_exposure(self._default_exposure_time)\n self.cam.set_gain(self._default_gain)\n self.cam.set_wb_kr(self._default_wb_kr)\n self.cam.set_wb_kg(self._default_wb_kg)\n self.cam.set_wb_kb(self._default_wb_kb)\n\n def initialize(self, set_defaults: bool = True) -> Tuple[bool, str]:\n try:\n self.cam.open_device()\n # set defaults if flag is True. This should be True the very first time in order to set the default params, but not enforced\n if set_defaults:\n self.set_default_params()\n self._is_initialized = True\n except xiapi.Xi_error as inst:\n self._is_initialized = False\n return (False, \"Failed to connect and initialize: \" + str(inst))\n \n if set_defaults:\n return (True, \"Successfully initialized camera by opening communications and setting defaults.\")\n else:\n return (True, \"Successfully intitialized camera by opening communications.\")\n\n def deinitialize(self, reset_init_flag: bool = True) -> Tuple[bool, str]:\n try:\n self.cam.stop_acquisition()\n self.cam.close_device()\n except xiapi.Xi_error as inst:\n return (False, \"Failed to deinitialize the camera: \" + str(inst))\n\n if reset_init_flag:\n self._is_initialized = False\n\n return (True, \"Successfully deinitialized camera, communication closed.\")\n\n @check_initialized\n def get_image(\n self, \n save_to_file: bool = True, \n filename: str = None, \n exposure_time: Optional[int] = None, \n gain: Optional[float] = None, \n show_pop_up: bool = False) -> Tuple[bool, str]:\n # if not self._is_initialized:\n # return (False, \"Camera is not initialized\")\n\n if exposure_time is None:\n exposure_time = self._default_exposure_time\n if gain is None:\n gain = self._default_gain\n\n try:\n self.cam.set_exposure(exposure_time)\n self.cam.set_gain(gain)\n\n img = xiapi.Image()\n self.cam.start_acquisition()\n # exposure time is in microsec, timeout is in millisec, timeout is set to double the exposure time\n self.cam.get_image(img, timeout=(int(exposure_time / 1000 * 2)))\n self.cam.stop_acquisition()\n except xiapi.Xi_error as inst:\n return (False, \"Error while getting image: \" + str(inst))\n\n data = img.get_image_data_numpy(invert_rgb_order=True)\n img = Image.fromarray(data, 'RGB')\n\n if save_to_file:\n \n if filename is None:\n timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')\n filename = timestamp\n fullfilename = self.save_directory + filename\n img.save(fullfilename + '.bmp')\n\n settings = [\"image data format = \" + self.cam.get_imgdataformat() + \"\\n\",\n \"exposure (us) = \" + str(self.cam.get_exposure()) + \"\\n\",\n \"gain = \" + str(self.cam.get_gain()) + \"\\n\",\n \"wb_kr = \" + str(self.cam.get_wb_kr()) + \"\\n\",\n \"wb_kg = \" + str(self.cam.get_wb_kg()) + \"\\n\",\n \"wb_kb = \" + str(self.cam.get_wb_kb()) + \"\\n\"]\n with open(fullfilename + '.txt', 'w') as file:\n file.writelines(settings) \n\n return (True, \"Successfully saved image and settings to \" + str(fullfilename) + \".bmp\")\n\n if show_pop_up:\n img.show()\n\n return (True, \"Successfully took image but did not save.\") \n\n @check_initialized\n def update_white_balance(self, exposure_time: int = None, gain: Optional[float] = None) -> Tuple[bool, str]:\n # if not self._is_initialized:\n # return (False, \"Camera is not initialized\")\n \n try:\n self.cam.set_manual_wb(1)\n except xiapi.Xi_error as inst:\n return (False, \"Failed to set white balance: \" + str(inst))\n\n was_successful, result_message = self.get_image(save_to_file=False, filename=None, exposure_time=exposure_time, gain=gain)\n\n if not was_successful:\n return (was_successful, result_message)\n\n return (True, \"Successfully updated white balance coefficients with image: wb_kr, wb_kg, wb_kb = \" + str(self.get_white_balance_rgb_coeffs()))\n \n @check_initialized # is this necessary\n def set_white_balance_manually(self, wb_kr: Optional[float] = None, wb_kg: Optional[float] = None, wb_kb: Optional[float] = None) -> Tuple[bool, str]:\n # if not self._is_initialized:\n # return (False, \"Camera is not initialized\")\n \n if wb_kr is None and wb_kg is None and wb_kb is None:\n return (True, \"No white balance coefficients were changed. Coefficients are currently: wb_kr, wb_kg, wb_kb = \" + str(self.get_white_balance_rgb_coeffs()))\n try:\n if wb_kr is not None:\n self.cam.set_wb_kr(wb_kr)\n if wb_kg is not None:\n self.cam.set_wb_kg(wb_kg)\n if wb_kb is not None:\n self.cam.set_wb_kb(wb_kb)\n except:\n return (False, \"Error in setting white balance coefficients. Coefficients are currently: wb_kr, wb_kg, wb_kb = \" + str(self.get_white_balance_rgb_coeffs()))\n \n return (True, \"Successfully set white balance coefficients manually: wb_kr, wb_kg, wb_kb = \" + str(self.get_white_balance_rgb_coeffs()))\n \n @check_initialized # is this necessary\n def reset_white_balance_rgb_coeffs(self) -> Tuple[bool, str]:\n self.cam.set_wb_kr(self._default_wb_kr)\n self.cam.set_wb_kg(self._default_wb_kg)\n self.cam.set_wb_kb(self._default_wb_kb)\n return (True, \"Successfully reset white balance coefficients to defaults. Coefficients are currently: wb_kr, wb_kg, wb_kb = \" + str(self.get_white_balance_rgb_coeffs()))\n\n @check_initialized # is this necessary\n def get_white_balance_rgb_coeffs(self) -> List[float]:\n wb = []\n wb.append(self.cam.get_wb_kr())\n wb.append(self.cam.get_wb_kg())\n wb.append(self.cam.get_wb_kb())\n return wb\n\n\n\n", "repo_name": "JustinJKwok/Lab-Automation", "sub_path": "devices/ximea_camera.py", "file_name": "ximea_camera.py", "file_ext": "py", "file_size_in_byte": 8500, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "device.Device", "line_number": 11, "usage_type": "name"}, {"api_name": "ximea.xiapi.Camera", "line_number": 16, "usage_type": "call"}, {"api_name": "ximea.xiapi", "line_number": 16, "usage_type": "name"}, {"api_name": "ximea.xiapi.Xi_error", "line_number": 82, "usage_type": "attribute"}, {"api_name": "ximea.xiapi", "line_number": 82, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 75, "usage_type": "name"}, {"api_name": "ximea.xiapi.Xi_error", "line_number": 95, "usage_type": "attribute"}, {"api_name": "ximea.xiapi", "line_number": 95, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 91, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 108, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 109, "usage_type": "name"}, {"api_name": "ximea.xiapi.Image", "line_number": 123, "usage_type": "call"}, {"api_name": "ximea.xiapi", "line_number": 123, "usage_type": "name"}, {"api_name": "ximea.xiapi.Xi_error", "line_number": 128, "usage_type": "attribute"}, {"api_name": "ximea.xiapi", "line_number": 128, "usage_type": "name"}, {"api_name": "PIL.Image.fromarray", "line_number": 132, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 132, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 137, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 137, "usage_type": "name"}, {"api_name": "device.check_initialized", "line_number": 103, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 110, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 159, "usage_type": "name"}, {"api_name": "ximea.xiapi.Xi_error", "line_number": 165, "usage_type": "attribute"}, {"api_name": "ximea.xiapi", "line_number": 165, "usage_type": "name"}, {"api_name": "device.check_initialized", "line_number": 158, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 159, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 176, "usage_type": "name"}, {"api_name": "device.check_initialized", "line_number": 175, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 176, "usage_type": "name"}, {"api_name": "device.check_initialized", "line_number": 194, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 195, "usage_type": "name"}, {"api_name": "device.check_initialized", "line_number": 201, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 202, "usage_type": "name"}]} +{"seq_id": "30123400466", "text": "import numpy as np\nfrom keras.layers import Input, Add, Dense, Activation, ZeroPadding2D,\\\nBatchNormalization, Flatten, Conv2D, AveragePooling2D,\\\nMaxPooling2D, GlobalMaxPooling2D\nfrom keras.models import Model\nfrom keras.preprocessing import image\nfrom keras.utils import layer_utils\nfrom keras.applications.imagenet_utils import preprocess_input\nfrom keras.preprocessing.image import ImageDataGenerator\nimport pydot\nfrom IPython.display import SVG\nfrom keras.utils.vis_utils import model_to_dot\nfrom keras.utils import plot_model\nfrom keras.initializers import glorot_uniform\nimport scipy.misc\nfrom matplotlib.pyplot import imshow\nfrom glob import glob\nimport keras.backend as K\n\ndef identity_block(X, f, filters, stage, block):\n conv_name_base = 'res'+str(stage)+block+'_branch'\n bn_name_base = 'bn'+str(stage)+block+'_branch'\n \n F1, F2, F3 = filters\n \n X_shortcut = X\n \n # First component of main path\n X = Conv2D(filters=F1, kernel_size=(1,1), strides=(1,1), padding='valid',\n name=conv_name_base+'2a', kernel_initializer= glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis=3, name=bn_name_base+'2a')(X)\n X = Activation('relu')(X)\n \n # Second component\n X = Conv2D(filters=F2, kernel_size=(f,f), strides=(1,1), padding='same', \n name=conv_name_base+'2b', kernel_initializer= glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis=3, name=bn_name_base+'2b')(X)\n X = Activation('relu')(X)\n \n # Third component\n X = Conv2D(filters=F3, kernel_size=(1,1), strides=(1,1), padding='valid', \n name=conv_name_base+'2c', kernel_initializer= glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis=3, name=bn_name_base+'2c')(X)\n \n # Add shortcut value\n X = Add()([X, X_shortcut])\n X = Activation('relu')(X)\n \n return X\n\ndef convolutional_block(X, f, filters, stage, block, s=2):\n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n \n # Retrieve Filters\n F1, F2, F3 = filters\n \n # Save the input value\n X_shortcut = X\n \n # First component\n X = Conv2D(F1, kernel_size=(1,1), strides=(s,s), name=conv_name_base+'2a', kernel_initializer=glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis=3, name=bn_name_base+'2a')(X)\n X = Activation('relu')(X)\n\n # Second component\n X = Conv2D(F2, kernel_size=(f,f), strides=(1,1), padding='same', name=conv_name_base+'2b', kernel_initializer=glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis=3, name=bn_name_base+'2b')(X)\n X = Activation('relu')(X)\n\n # Third component\n X = Conv2D(F3, kernel_size=(1,1), strides=(1,1), padding='valid', name=conv_name_base+'2c', kernel_initializer=glorot_uniform(seed=0))(X)\n X = BatchNormalization(axis=3, name=bn_name_base+'2c')(X)\n\n # Shortcut path\n X_shortcut = Conv2D(F3, kernel_size=(1,1), strides=(s,s), padding='valid', name=conv_name_base+'1', kernel_initializer=glorot_uniform(seed=0))(X_shortcut)\n X_shortcut = BatchNormalization(axis=3, name=bn_name_base+'1')(X_shortcut)\n print(X_shortcut.shape)\n X = Add()([X, X_shortcut])\n X = Activation('relu')(X)\n \n return X\n\ndef ResNet50(input_shape=(64, 64, 3), classes=6):\n X_input = Input(input_shape)\n X = ZeroPadding2D((3,3))(X_input)\n \n # Stage 1\n X = Conv2D(64, (7,7), strides=(2,2), name='conv1')(X)\n X = BatchNormalization(axis=3, name='bn_conv1')(X)\n X = Activation('relu')(X)\n X = MaxPooling2D((3,3), strides=(2,2))(X)\n \n # Stage 2\n X = convolutional_block(X, f=3, filters=[64, 64, 256], stage=2, block='a', s=1)\n X = identity_block(X, 3, [64, 64, 256], stage=2, block='b')\n X = identity_block(X, 3, [64, 64, 256], stage=2, block='c')\n \n \n # Stage 3\n X = convolutional_block(X, f=3, filters=[128, 128, 512], stage=3, block='a', s=2)\n X = identity_block(X, 3, [128, 128, 512], stage=3, block='b')\n X = identity_block(X, 3, [128, 128, 512], stage=3, block='c')\n X = identity_block(X, 3, [128, 128, 512], stage=3, block='d')\n \n # stage 4\n X = convolutional_block(X, f=3, filters=[256, 256, 1024], stage=4, block='a', s=2)\n X = identity_block(X, 3, [256, 256, 1024], stage=4, block='b')\n X = identity_block(X, 3, [256, 256, 1024], stage=4, block='c')\n X = identity_block(X, 3, [256, 256, 1024], stage=4, block='d')\n X = identity_block(X, 3, [256, 256, 1024], stage=4, block='e')\n X = identity_block(X, 3, [256, 256, 1024], stage=4, block='f')\n \n # Stage 5\n X = convolutional_block(X, f=3, filters=[512, 512, 2048], stage=5, block='a', s=2)\n X = identity_block(X, 3, [512, 512, 2048], stage=5, block='b')\n X = identity_block(X, 3, [512, 512, 2048], stage=5, block='c')\n\n # AVGPOOL \n X = AveragePooling2D((2,2), name=\"avg_pool\")(X)\n\n\n # output layer\n X = Flatten()(X)\n X = Dense(classes, activation='softmax', name='fc' + str(classes))(X)\n \n \n # Create model\n model = Model(inputs = X_input, outputs = X, name='ResNet50')\n\n return model\n\n\nmodel = ResNet50(classes=6)\nmodel.compile(optimizer='adam', \n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n\n\n# MAking Dataset\n\nIMAGE_SIZE = [64,64]\nepochs=10\nbatch_size=32\n\ntrain_path = 'small_dataset/Training'\nvalid_path = 'small_dataset/Validation'\n\nimage_files = glob(train_path + '/*/*.jp*g')\nvalid_image_files = glob(valid_path + '/*/*.jp*g')\n\nfolders = glob(train_path+'/*')\n\ngen = ImageDataGenerator(\n rotation_range=20,\n width_shift_range=0.1,\n height_shift_range=0.1,\n shear_range=0.1,\n zoom_range=0.2,\n horizontal_flip=True,\n vertical_flip=True,\n preprocessing_function=preprocess_input\n)\n\n\ntest_gen = gen.flow_from_directory(valid_path, target_size=IMAGE_SIZE)\nprint(test_gen.class_indices)\nlabels = [None] * len(test_gen.class_indices)\nfor k,v in test_gen.class_indices.items():\n labels[v] = k\n\n\ntrain_generator = gen.flow_from_directory(\n train_path,\n target_size=IMAGE_SIZE,\n shuffle=True,\n batch_size=batch_size\n)\n\nvalid_generator = gen.flow_from_directory(\n valid_path,\n target_size=IMAGE_SIZE,\n shuffle=True,\n batch_size=batch_size\n)\n\nr = model.fit_generator(\n train_generator,\n validation_data=valid_generator,\n epochs=epochs,\n steps_per_epoch=len(image_files)//batch_size,\n validation_steps=len(valid_image_files)//batch_size\n)\nplot_model(model, to_file='model.png')\nSVG(model_to_dot(model).create(prog='dot', format='svg'))", "repo_name": "Tanzeel0651/Resnet", "sub_path": "resnet_yourself.py", "file_name": "resnet_yourself.py", "file_ext": "py", "file_size_in_byte": 6594, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "keras.layers.Conv2D", "line_number": 29, "usage_type": "call"}, {"api_name": "keras.initializers.glorot_uniform", "line_number": 30, "usage_type": "call"}, {"api_name": "keras.layers.BatchNormalization", "line_number": 31, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 32, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 35, "usage_type": "call"}, {"api_name": "keras.initializers.glorot_uniform", "line_number": 36, "usage_type": "call"}, {"api_name": "keras.layers.BatchNormalization", "line_number": 37, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 38, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 41, "usage_type": "call"}, {"api_name": "keras.initializers.glorot_uniform", "line_number": 42, "usage_type": "call"}, {"api_name": "keras.layers.BatchNormalization", "line_number": 43, "usage_type": "call"}, {"api_name": "keras.layers.Add", "line_number": 46, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 47, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 62, "usage_type": "call"}, {"api_name": "keras.initializers.glorot_uniform", "line_number": 62, "usage_type": "call"}, {"api_name": "keras.layers.BatchNormalization", "line_number": 63, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 64, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 67, "usage_type": "call"}, {"api_name": "keras.initializers.glorot_uniform", "line_number": 67, "usage_type": "call"}, {"api_name": "keras.layers.BatchNormalization", "line_number": 68, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 69, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 72, "usage_type": "call"}, {"api_name": "keras.initializers.glorot_uniform", "line_number": 72, "usage_type": "call"}, {"api_name": "keras.layers.BatchNormalization", "line_number": 73, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 76, "usage_type": "call"}, {"api_name": "keras.initializers.glorot_uniform", "line_number": 76, "usage_type": "call"}, {"api_name": "keras.layers.BatchNormalization", "line_number": 77, "usage_type": "call"}, {"api_name": "keras.layers.Add", "line_number": 79, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 80, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 85, "usage_type": "call"}, {"api_name": "keras.layers.ZeroPadding2D", "line_number": 86, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 89, "usage_type": "call"}, {"api_name": "keras.layers.BatchNormalization", "line_number": 90, "usage_type": "call"}, {"api_name": "keras.layers.Activation", "line_number": 91, "usage_type": "call"}, {"api_name": "keras.layers.MaxPooling2D", "line_number": 92, "usage_type": "call"}, {"api_name": "keras.layers.AveragePooling2D", "line_number": 120, "usage_type": "call"}, {"api_name": "keras.layers.Flatten", "line_number": 124, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 125, "usage_type": "call"}, {"api_name": "keras.models.Model", "line_number": 129, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 150, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 151, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 153, "usage_type": "call"}, {"api_name": "keras.preprocessing.image.ImageDataGenerator", "line_number": 155, "usage_type": "call"}, {"api_name": "keras.applications.imagenet_utils.preprocess_input", "line_number": 163, "usage_type": "name"}, {"api_name": "keras.utils.plot_model", "line_number": 195, "usage_type": "call"}, {"api_name": "IPython.display.SVG", "line_number": 196, "usage_type": "call"}, {"api_name": "keras.utils.vis_utils.model_to_dot", "line_number": 196, "usage_type": "call"}]} +{"seq_id": "41075883419", "text": "\"\"\"\r\nThis script expands upon our previous GTSAM scripts; this time, using GTSAM's landmark\r\nfactors and having GTSAM solve for the camera position, instead of using dt_apriltag's\r\npositional estimates to calculate our position.\r\n\"\"\"\r\nimport gtsam\r\nimport gtsam.utils.plot as gtplot\r\nimport numpy as np\r\nimport json\r\nfrom matplotlib import pyplot as plt\r\nimport cv2\r\nfrom apriltag_baseline import set_axes_equal, fx, fy, cx, cy\r\nfrom dt_apriltags import Detector\r\nfrom collections import defaultdict\r\n\r\n\r\ndef main():\r\n cap = cv2.VideoCapture(\"videos/tagtest_4tag_fig8.mp4\")\r\n detector = Detector(families='tagStandard41h12',\r\n nthreads=16)\r\n graph = gtsam.NonlinearFactorGraph()\r\n initial_guesses = gtsam.Values()\r\n tag_locations = {}\r\n pts = defaultdict(list)\r\n\r\n timestep_num = 0\r\n while cap.isOpened():\r\n frame = cap.read()[1]\r\n if frame is None:\r\n break\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n detections = detector.detect(gray, estimate_tag_pose=True, tag_size=0.192,\r\n camera_params=(fx, fy, cx, cy))\r\n if len(detections) != 4:\r\n continue\r\n\r\n # One variable for the current camera pos:\r\n cam_sym = gtsam.symbol('x', timestep_num)\r\n # Add factors for each tag's position\r\n for det in detections:\r\n # Convert apriltag pose to camera pose\r\n camera_pose = det.pose_R.T @ -det.pose_t\r\n camera_pose = camera_pose.flatten() # \"world coordinates\" of camera\r\n if det.tag_id not in tag_locations:\r\n tag_locations[det.tag_id] = camera_pose\r\n\r\n camera_pose = camera_pose - tag_locations[det.tag_id]\r\n pts[det.tag_id].append(camera_pose)\r\n\r\n\r\n # Make up a noise model based on reported tag error\r\n # (this is a pretty bad way to do it, but it's a start)\r\n err_scale = 1e5\r\n det_noise = gtsam.noiseModel.Diagonal.Sigmas(np.array([det.pose_err * err_scale] * 3))\r\n print(det.pose_err * err_scale)\r\n # Add the factor\r\n graph.add(gtsam.PriorFactorPoint3(cam_sym, gtsam.Point3(camera_pose), det_noise))\r\n # draw tag detections\r\n cv2.polylines(frame, [np.int32(det.corners)], True, (0, 255, 0), 2)\r\n\r\n # Add initial estimate for camera pose - just use the pose of the last tag\r\n initial_guesses.insert(cam_sym, gtsam.Point3(camera_pose))\r\n\r\n cv2.imshow(\"frame\", frame)\r\n cv2.waitKey(1)\r\n timestep_num += 1\r\n\r\n\r\n # Solve graph\r\n params = gtsam.LevenbergMarquardtParams()\r\n params.setVerbosityLM(\"SUMMARY\")\r\n optimizer = gtsam.LevenbergMarquardtOptimizer(graph, initial_guesses, params)\r\n result = optimizer.optimize()\r\n marginals = gtsam.Marginals(graph, result)\r\n\r\n # Plot 1: Compare raw data to GTSAM; plot in 2D,\r\n # with confidence circles\r\n fig = plt.figure()\r\n ax = fig.add_subplot(121)\r\n ax.title.set_text(\"Original\")\r\n for tag_id, poses in pts.items():\r\n arr = np.array(poses)\r\n ax.scatter(arr[:, 0], arr[:, 1], label=tag_id)\r\n # error circles\r\n # for pose in poses:\r\n # ax.add_artist(plt.Circle(pose[:2], 0.1, color='r', fill=False))\r\n # make axes same scale\r\n ax.set_aspect('equal', adjustable='box')\r\n ax2 = fig.add_subplot(122)\r\n ax2.title.set_text(\"GTSAM, basic independent variables\")\r\n result_pts = []\r\n for i in range(timestep_num - 1):\r\n result_pts.append(result.atPoint3(gtsam.symbol('x', i)))\r\n result_pts = np.array(result_pts)\r\n ax2.scatter(result_pts[:, 0], result_pts[:, 1])\r\n # error circles\r\n for i, pose in enumerate(result_pts):\r\n gtplot.plot_covariance_ellipse_2d(ax2, pose[:2], marginals.marginalCovariance(gtsam.symbol('x', i))[:2, :2])\r\n # make axes same scale\r\n ax2.set_aspect('equal', adjustable='box')\r\n\r\n # Compare mean of raw data vs. GTSAM result\r\n fig = plt.figure()\r\n ax = fig.add_subplot(121)\r\n ax.title.set_text(\"Mean of raw data\")\r\n mean_pts = np.mean(np.array(list(pts.values())), axis=0)\r\n ax.scatter(mean_pts[:, 0], mean_pts[:, 1])\r\n ax.set_aspect('equal', adjustable='box')\r\n ax2 = fig.add_subplot(122)\r\n ax2.title.set_text(\"GTSAM landmarks\")\r\n ax2.scatter(result_pts[:, 0], result_pts[:, 1])\r\n ax2.set_aspect('equal', adjustable='box')\r\n plt.show()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n", "repo_name": "DylanJones/gtsam-experiment", "sub_path": "gtsam_basic_noise.py", "file_name": "gtsam_basic_noise.py", "file_ext": "py", "file_size_in_byte": 4483, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "cv2.VideoCapture", "line_number": 18, "usage_type": "call"}, {"api_name": "dt_apriltags.Detector", "line_number": 19, "usage_type": "call"}, {"api_name": "gtsam.NonlinearFactorGraph", "line_number": 21, "usage_type": "call"}, {"api_name": "gtsam.Values", "line_number": 22, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 24, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 31, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 31, "usage_type": "attribute"}, {"api_name": "apriltag_baseline.fx", "line_number": 33, "usage_type": "name"}, {"api_name": "apriltag_baseline.fy", "line_number": 33, "usage_type": "name"}, {"api_name": "apriltag_baseline.cx", "line_number": 33, "usage_type": "name"}, {"api_name": "apriltag_baseline.cy", "line_number": 33, "usage_type": "name"}, {"api_name": "gtsam.symbol", "line_number": 38, "usage_type": "call"}, {"api_name": "gtsam.noiseModel.Diagonal.Sigmas", "line_number": 54, "usage_type": "call"}, {"api_name": "gtsam.noiseModel", "line_number": 54, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 54, "usage_type": "call"}, {"api_name": "gtsam.PriorFactorPoint3", "line_number": 57, "usage_type": "call"}, {"api_name": "gtsam.Point3", "line_number": 57, "usage_type": "call"}, {"api_name": "cv2.polylines", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 59, "usage_type": "call"}, {"api_name": "gtsam.Point3", "line_number": 62, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 64, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 65, "usage_type": "call"}, {"api_name": "gtsam.LevenbergMarquardtParams", "line_number": 70, "usage_type": "call"}, {"api_name": "gtsam.LevenbergMarquardtOptimizer", "line_number": 72, "usage_type": "call"}, {"api_name": "gtsam.Marginals", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 78, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 82, "usage_type": "call"}, {"api_name": "gtsam.symbol", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 94, "usage_type": "call"}, {"api_name": "gtsam.utils.plot.plot_covariance_ellipse_2d", "line_number": 98, "usage_type": "call"}, {"api_name": "gtsam.utils.plot", "line_number": 98, "usage_type": "name"}, {"api_name": "gtsam.symbol", "line_number": 98, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 103, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 103, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 113, "usage_type": "name"}]} +{"seq_id": "33687865756", "text": "from collections import deque\nimport time\nclass MinQueue:\n\tdef __init__(self,p_size):\n\t\tself.size = p_size\n\t\tself.deque=deque()\n\t\tself.timeDeque=deque()\n\n\tdef peek(self,p_deque):\n\t\tval = p_deque.pop()\n\t\tp_deque.append(val)\n\t\treturn val\n\n\tdef peekleft(self ,p_deque):\n\t\tval = p_deque.popleft()\n\t\tp_deque.appendleft(val)\n\t\treturn val\n\tdef push(self,p_value):\n\t\tself.updateTime()\n\t\twhile len(self.deque) !=0 and self.peek(self.deque) > p_value:\n\t\t\tself.deque.pop();\n\t\t\tself.timeDeque.pop();\n\t\tself.deque.append(p_value)\n\t\tself.timeDeque.append((int)(time.time()))\n\tdef printMessage(self):\n\t\tsize = len(self.deque)\n\t\tindex=0\n\t\twhile( index3:\n\t\t\tself.deque.popleft()\n\t\t\tself.timeDeque.popleft()\n\nif __name__=='__main__':\n\tobj = MinQueue(10)\n\tobj.push(3)\n\ttime.sleep(1)\n\tobj.push(1)\n\ttime.sleep(1)\n\tobj.push(4)\n\ttime.sleep(1)\n\tobj.push(5)\n\ttime.sleep(1)\n\tobj.push(6)\n\tobj.printMessage()\n", "repo_name": "wuaiu/PythonTools", "sub_path": "MinQueue.py", "file_name": "MinQueue.py", "file_ext": "py", "file_size_in_byte": 1302, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "collections.deque", "line_number": 6, "usage_type": "call"}, {"api_name": "collections.deque", "line_number": 7, "usage_type": "call"}, {"api_name": "time.time", "line_number": 24, "usage_type": "call"}, {"api_name": "time.time", "line_number": 36, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 47, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 49, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 51, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 53, "usage_type": "call"}]} +{"seq_id": "35639038433", "text": "'''\n253. Meeting Rooms II\nhttps://leetcode.com/problems/meeting-rooms-ii/\n\nGiven an array of meeting time intervals intervals where intervals[i] = [starti, endi],\n\nreturn the minimum number of conference rooms required.\n\ne.g. intervals = [[0, 30], [5, 10], [15, 20]] --> 2\ne.g. intervals = [[7, 10], [2, 4]] --> 1\n\n'''\n\n\nfrom typing import List\n\n\nclass Solution:\n # the maximum number of overlapping meetings at any given point in time\n \n # time complexity: O(nlogn)\n # space complexity: O(n)\n def minMeetingRooms(self, intervals: List[List[int]]) -> int:\n \n start = sorted([i for i, j in intervals])\n end = sorted([j for i, j in intervals])\n i = j = count = maxCount = 0\n while i < len(start):\n if start[i] < end[j]:\n count += 1\n i += 1\n maxCount = max(count, maxCount)\n else:\n count -= 1\n j += 1\n return maxCount\n", "repo_name": "ellieko/algorithms", "sub_path": "top100/medium/253_MeetingRoomsII.py", "file_name": "253_MeetingRoomsII.py", "file_ext": "py", "file_size_in_byte": 996, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.List", "line_number": 23, "usage_type": "name"}]} +{"seq_id": "37414963042", "text": "import sqlite3\n\ndef read_order_desc(db_name, field):\n with sqlite3.connect(\"{0}.db\".format(db_name)) as connection:\n cursor = connection.cursor()\n sentence = f\"SELECT * FROM ranking\"\n cursor.execute(sentence)\n data = cursor.fetchall()\n connection.commit()\n return data\n\n\n\nlista = read_order_desc(\"all_score\", \"score\")\nprint(lista)", "repo_name": "ThiagoVilani/Juego-Examen-", "sub_path": "delete_after_this.py", "file_name": "delete_after_this.py", "file_ext": "py", "file_size_in_byte": 375, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sqlite3.connect", "line_number": 4, "usage_type": "call"}]} +{"seq_id": "13445389803", "text": "import json\nimport argparse\nimport os.path as path\nimport os\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nfrom utils import *\n\nparser = argparse.ArgumentParser(description='This script analysis the runescape stats and formulates emails to send out.')\nparser.add_argument('--bucket-url', dest='bucket_url', default=None, required=False, help='S3 bucket url to store images in for graphs in emails. If this is not defined image links will just default to local links.')\nparser.add_argument('--files', nargs='+', dest='files', required=True, help='1 or more files to parse')\nargs = parser.parse_args()\n\naverage_daily_xp_all_time = {}\naverage_daily_xp_all_time\nplayer_stats = {}\ndaily_stat_gains = {}\nimages_to_upload = []\ndate_string = None\ntimestamp = int(datetime.utcnow().timestamp())\n\n\ndef createDateString(previous_day, current_day):\n global date_string\n current_day_time = datetime.utcfromtimestamp(current_day['timestamp'])\n previous_day_time = datetime.utcfromtimestamp(previous_day['timestamp'])\n date_string = concat_vals(\n elem('p', f'Daily stats update for {current_day_time.strftime(\"%A %d %Y\")}'),\n elem('p', f'Daily stats are for the period {previous_day_time.strftime(\"%A %d: %H:%M\")} => {current_day_time.strftime(\"%A %d: %H:%M\")}')\n )\n\n\ndef create_image_link(image_name):\n if(args.bucket_url): return f'{args.bucket_url}/{image_name}'\n return image_name\n\n\n# Adds more information to the most recent data point\ndef enrich_current_day(player_name, player_data):\n previous_day = player_data[len(player_data)-2]\n current_day = player_data[len(player_data)-1]\n player_stats[player_name] = current_day\n \n for key in current_day['skills'].keys():\n current_day['skills'][key]['previous_xp'] = previous_day['skills'][key]['xp']\n current_day['skills'][key]['daily_xp_gain'] = int(current_day['skills'][key]['xp']) - int(previous_day['skills'][key]['xp'])\n current_day['skills'][key]['previous_level'] = int(previous_day['skills'][key]['level'])\n \n if not date_string: createDateString(previous_day, current_day)\n\n\ndef compute_daily_xp_gains(player_name, player_data):\n global daily_stat_gains\n global player_stats\n current_day = player_stats[player_name]\n \n daily_xp_gained_skills = [x for x in current_day['skills'].keys() if current_day['skills'][x]['daily_xp_gain'] > 0]\n if len(daily_xp_gained_skills) == 0:\n return\n daily_xp_gained_skills.sort(key=lambda x:-1*current_day['skills'][x]['daily_xp_gain'])\n\n daily_stat_gains[player_name] = daily_xp_gained_skills\n\n\ndef plot_graph(x_vals, y_vals, title, filename): \n fig = plt.figure()\n ax=fig.add_subplot(111)\n ax.set_title(title)\n ax.bar(x_vals, y_vals)\n plt.xticks(range(len(x_vals)), x_vals, rotation='vertical')\n plt.tight_layout()\n plt.savefig(f'temp/{filename}')\n\n\ndef create_daily_stats_table(player_name):\n def daily_stat_row(skill):\n xp_gain = player_stats[player_name][\"skills\"][skill][\"daily_xp_gain\"]\n xp_gain = \"{:,}\".format(xp_gain)\n level_gain = int(player_stats[player_name][\"skills\"][skill][\"level\"]) - int(player_stats[player_name][\"skills\"][skill][\"previous_level\"])\n level_diff = f'{player_stats[player_name][\"skills\"][skill][\"previous_level\"]} => {player_stats[player_name][\"skills\"][skill][\"level\"]}' if level_gain else '-'\n level_gain = level_gain if level_gain else '-'\n \n return elem('tr', elems('td', skill, xp_gain, level_gain, level_diff))\n\n return elem('table', \\\n elem('tr', \n elems('th', 'Skill', 'XP Gain', 'Level Gain', 'Level Diff')), \n *(daily_stat_row(x) for x in daily_stat_gains[player_name])\n )\n\n \ndef overall_daily_xp_gains():\n image_name = f'{timestamp}_overall_daily_xp.png'\n images_to_upload.append(image_name)\n\n players = sorted(daily_stat_gains.keys(), key=lambda x:-1*player_stats[x]['skills']['overall']['daily_xp_gain'])[::-1]\n xp_vals = [player_stats[x]['skills']['overall']['daily_xp_gain'] for x in players]\n plot_graph(players, xp_vals, f'Total XP gained previous day', image_name) \n \n yield elem('h2', 'Overall XP gains')\n yield elem('img', src=create_image_link(image_name))\n yield elem('hr')\n\n\ndef daily_stats_email_segment():\n players_sorted_by_xp_gain = sorted(daily_stat_gains.keys(), key=lambda x:-1*player_stats[x]['skills']['overall']['daily_xp_gain'])\n\n yield elem('h2', 'Per Player daily XP Gains (sorted by highest overall gains)')\n\n def get_segment_for_player(player_name):\n image_name = f'{timestamp}_{player_name}_daily_xp.png'\n images_to_upload.append(image_name)\n\n daily_xp_values = [player_stats[player_name]['skills'][x]['daily_xp_gain'] for x in daily_stat_gains[player_name][::-1]]\n plot_graph(daily_stat_gains[player_name][::-1], daily_xp_values, f'{player_name} XP gained previous day', image_name)\n \n yield elem('h3', f'{player_name} daily XP gains')\n yield elem('img', src=create_image_link(image_name))\n yield create_daily_stats_table(player_name)\n \n\n for player_name in players_sorted_by_xp_gain:\n yield from get_segment_for_player(player_name)\n\n#=======================================#\n#========== COMPUTE STATS ==============#\n#=======================================#\n\ntry: os.mkdir('temp')\nexcept: True\n\nfor file in args.files:\n with open(file, 'r') as read_file:\n data = json.load(read_file)\n \n if(not isinstance(data, list) or len(data) < 2 ):\n print(f'Skipping file: {file} as there are not enough data points')\n continue \n \n player_name = os.path.split(file)[1].replace('.json','')\n enrich_current_day(player_name, data)\n compute_daily_xp_gains(player_name, data)\n \n\n#=======================================#\n#=========== BUILD EMAIL ===============#\n#=======================================#\n\nwith open('email_header.html', 'r') as read_file:\n email_header = read_file.read()\n\n\ndef email_body():\n yield elem('h1', 'Daily OSRS stats update!')\n yield date_string\n yield '
     '\n if(len(daily_stat_gains.keys()) > 0):\n yield from overall_daily_xp_gains()\n yield from daily_stats_email_segment()\n\n\ndef email():\n yield ''\n yield ''\n yield f'{email_header}'\n yield ''\n yield from email_body()\n yield ''\n yield ''\n\n\nfinal_email = concat_iterable(email())\n\nwith open('temp/email_content.html', 'w') as f:\n f.write(final_email)\n\nwith open('temp/images_to_upload.json', 'w') as f:\n json.dump(images_to_upload, f)\n", "repo_name": "vaalkor/osrs-stats", "sub_path": "analysis.py", "file_name": "analysis.py", "file_ext": "py", "file_size_in_byte": 6824, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 9, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 20, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 20, "usage_type": "name"}, {"api_name": "datetime.datetime.utcfromtimestamp", "line_number": 25, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 25, "usage_type": "name"}, {"api_name": "datetime.datetime.utcfromtimestamp", "line_number": 26, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 70, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 70, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "os.mkdir", "line_number": 129, "usage_type": "call"}, {"api_name": "json.load", "line_number": 134, "usage_type": "call"}, {"api_name": "os.path.split", "line_number": 140, "usage_type": "call"}, {"api_name": "os.path", "line_number": 140, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 178, "usage_type": "call"}]} +{"seq_id": "16929647172", "text": "\"\"\"command line arguments are handled here\"\"\"\n\nimport argparse\n\n\nclass Argument:\n \"\"\"This class handles command line arguments\"\"\"\n\n def __init__(self):\n self.command_line_arguments = None\n\n def get_command_line_arguments(self):\n \"\"\"command line arguments are parsed using the argparse library\"\"\"\n\n parser = argparse.ArgumentParser()\n group = parser.add_mutually_exclusive_group()\n\n group.add_argument(\n '-e',\n action = 'store_true',\n help = 'flag for given year highest temperature, lowest temperature, maximum humidity'\n )\n group.add_argument(\n '-a',\n action = 'store_true',\n help = 'flag for given month average highest temperature, lowest temperature, humidity'\n )\n group.add_argument(\n '-c',\n action = 'store_true',\n help = 'two bar charts for the highest and lowest temperature on each day'\n )\n group.add_argument(\n '-d',\n action = 'store_true',\n help = 'one bar chart for the highest and lowest temperature on each day'\n )\n\n parser.add_argument('date', help = 'Date argument')\n parser.add_argument('file_path', help = 'File path argument')\n\n self.command_line_arguments = parser.parse_args()\n", "repo_name": "Talha-Rizwan/weatherman-python", "sub_path": "argument_class.py", "file_name": "argument_class.py", "file_ext": "py", "file_size_in_byte": 1344, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 15, "usage_type": "call"}]} +{"seq_id": "113079990", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[15]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom celluloid import Camera\nimport matplotlib.animation as animation\nget_ipython().run_line_magic('matplotlib', 'inline')\nNx = 128\nNy = 128\nc = np.zeros([Nx,Ny])\n\nfor i in range(Nx):\n for j in range(Ny):\n c[i,j] = 0.5 + 0.1*(0.5-np.random.rand())\n\nfig = plt.figure()\ncamera = Camera(fig)\nX,Y = np.meshgrid(range(Nx),range(Ny))\nplt.contourf(X,Y,c,cmap = 'plasma')\n#plt.colorbar()\n#plt.show()\ncamera.snap()\n\ndt = 0.5\ncnew = c\ndelkx = 2*np.pi/Nx\ndelky = 2*np.pi/Ny\nA = 1\nM = 1\nkappa = 1\n\n#plt.ion()\nplt.figure(1)\nfor m in range(30):\n for n in range(10):\n mult = np.multiply(1-cnew,1-2*cnew)\n g = 2*A*np.multiply(cnew,mult)\n ghat = np.fft.fft2(g)\n chat = np.fft.fft2(cnew)\n\n for i in range(Nx):\n if i <= Nx/2:\n kx = i*delkx\n else:\n kx = (i-Nx)*delkx\n for j in range(Ny):\n if j <= Ny/2:\n ky = j*delky\n else:\n ky = (j-Ny)*delky\n\n k2 = kx**2 + ky**2\n k4 = k2**2\n chat[i,j] = (chat[i,j] - M*dt*k2*ghat[i,j])/(1+2*M*kappa*k4*dt)\n\n cnew = np.fft.ifft2(chat).real\n\n X,Y = np.meshgrid(range(Nx),range(Ny))\n #plt.clf()\n plt.contourf(X,Y,cnew,cmap = 'plasma')\n #plt.colorbar()\n #plt.show()\n camera.snap()\n\n\n# In[16]:\n\n\nani = camera.animate(interval = 1000)\nwritergif = animation.PillowWriter()\nani.save('spinodal.gif',writer=writergif)\n", "repo_name": "gaurav-mapari/Spinodal_python", "sub_path": "spinodal2Dgif.py", "file_name": "spinodal2Dgif.py", "file_ext": "py", "file_size_in_byte": 1574, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.zeros", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 18, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "celluloid.Camera", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.contourf", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 30, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 31, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "numpy.multiply", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.multiply", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.fft.fft2", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 42, "usage_type": "attribute"}, {"api_name": "numpy.fft.fft2", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 43, "usage_type": "attribute"}, {"api_name": "numpy.fft.ifft2", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.fft", "line_number": 60, "usage_type": "attribute"}, {"api_name": "numpy.meshgrid", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.contourf", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}, {"api_name": "matplotlib.animation.PillowWriter", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.animation", "line_number": 74, "usage_type": "name"}]} +{"seq_id": "41904605256", "text": "import glob\nimport imp\nimport os\nimport shutil\nimport time\n\n# from pymel.core import *\n\nfrom atom_face_lib import skn\nimport maya.cmds as cmds\nimport maya.mel as mel\nimport webrImport as web\n\n#\nplace = web.mod( \"atom_place_lib\" )\nstage = web.mod( 'atom_splineStage_lib' )\nmisc = web.mod( 'atom_miscellaneous_lib' )\njnt = web.mod( 'atom_joint_lib' )\nanm = web.mod( \"anim_lib\" )\nvhl = web.mod( 'vehicle_lib' )\napp = web.mod( \"atom_appendage_lib\" )\nss = web.mod( \"selectionSet_lib\" )\npb = web.mod( \"playblast_lib\" )\nac = web.mod( \"animCurve_lib\" )\nffm = web.mod( \"ffMpg\" )\ncas = web.mod( \"cache_abc_sil\" )\nds = web.mod( \"display_lib\" )\ntp = web.mod( \"togglePlate\" )\n\n\ndef message( what = '', maya = True, warning = False ):\n what = '-- ' + what + ' --'\n if '\\\\' in what:\n what = what.replace( '\\\\', '/' )\n if warning:\n cmds.warning( what )\n else:\n if maya:\n mel.eval( 'print \\\"' + what + '\\\";' )\n else:\n print( what )\n\n\ndef fix_normals( del_history = False ):\n '''\n after skinning geo gets weird normals\n '''\n geo = get_geo_list( all = True )\n cmds.select( geo )\n cmds.polyNormalPerVertex( unFreezeNormal = True )\n for g in geo:\n cmds.select( g )\n cmds.polySoftEdge( angle = 45 )\n if del_history:\n cmds.delete( geo, ch = True )\n\n\ndef mirror_jnts():\n '''\n \n '''\n # jnts - new joints for pivots\n mirrorj = [\n 'front_L_jnt',\n 'back_L_jnt',\n 'propeller_01_L_jnt'\n ]\n # mirror\n for j in mirrorj:\n jnt.mirror( j , mirrorBehavior = False )\n\n\ndef ferry( name = 'ferry', geo_grp = 'ferry_grp', X = 1.1, ns = 'geo', ref_geo = 'P:\\\\MDLN\\\\assets\\\\veh\\\\ferry\\\\model\\\\maya\\\\scenes\\\\ferry_model_v011.ma' ):\n '''\n build ferry\n '''\n # ref geo\n if ns and ref_geo:\n vhl.reference_geo( ns = ns, path = ref_geo )\n # return\n #\n mirror_jnts()\n # return\n\n # hide\n # name = 'boat'\n hide = [\n 'steer_TopGrp'\n ]\n\n # [MasterCt[4], MoveCt[4], SteerCt[4]]\n # SteerCt[4] = returned only if given as argument, otherwise this is returned: MasterCt[4], MoveCt[4]\n master_move_controls = vhl.vehicle_master( masterX = X * 8, moveX = X * 10, geo_grp = '' )\n # return\n\n #\n chassis_jnt = 'chassis_jnt'\n prop_l_jnt = 'propeller_02_L_jnt'\n prop_r_jnt = 'propeller_02_R_jnt'\n\n # skin\n chassis_geo = get_geo_list( name = name, ns = ns, chassis = True )\n vhl.skin( chassis_jnt, chassis_geo )\n prop_l = get_geo_list( name = name, ns = ns, prop_l = True )\n vhl.skin( prop_l_jnt, prop_l )\n prop_r = get_geo_list( name = name, ns = ns, prop_r = True )\n vhl.skin( prop_r_jnt, prop_r )\n # return\n # pivot_controls = [frontl, frontr, backl, backr, front, back] # entire controller hierarchy [0-4]\n pivot_controls = vhl.four_point_pivot( name = '', parent = master_move_controls[1], center = chassis_jnt, front = 'front_jnt', frontL = 'front_L_jnt', frontR = 'front_R_jnt', back = 'back_jnt', backL = 'back_L_jnt', backR = 'back_R_jnt', up = 'up_jnt', chassis_geo = '', X = X * 2, shapes = 'squareYup_ctrl' )\n # return\n #\n props( chassis_jnt = chassis_jnt, X = X * 14 )\n # return\n #\n # rudders( chassis_jnt = chassis_jnt, X = X * 14 )\n #\n for h in hide:\n cmds.setAttr( h + '.visibility', 0 )\n\n # scale\n # geo = 'caterpillar_c_geo_lod_0'\n mstr = 'master'\n uni = 'uniformScale'\n scl = ['.scaleX', '.scaleY', '.scaleZ']\n #\n misc.addAttribute( [mstr], [uni], 0.1, 100.0, True, 'float' )\n cmds.setAttr( mstr + '.' + uni, 1.0 )\n # misc.addAttribute( [mstr], [uni], 0.1, 10.0, True, 'float' )\n scl = ['.scaleX', '.scaleY', '.scaleZ']\n misc.scaleUnlock( '___CONTROLS', sx = True, sy = True, sz = True )\n for s in scl:\n cmds.connectAttr( mstr + '.' + uni, '___CONTROLS' + s )\n misc.scaleUnlock( '___SKIN_JOINTS', sx = True, sy = True, sz = True )\n for s in scl:\n cmds.connectAttr( mstr + '.' + uni, '___SKIN_JOINTS' + s )\n # uncommenting since no tires, should work, will find out when geo is ready\n misc.scaleUnlock( '___GEO', sx = True, sy = True, sz = True )\n for s in scl:\n cmds.connectAttr( mstr + '.' + uni, ns + ':' + geo_grp + s ) # geo is referenced\n # cmds.connectAttr( mstr + '.' + uni, '___GEO' + s ) ns = ns, path = ref_geo # geo group parented under ___GEO\n # cmds.connectAttr( mstr + '.' + uni, 'deltaMush1' + s ) # set scale, apply deltaMush, add scale connection for deltaMush\n '''\n # HACK :\n # REF MODEL GROUP, LEAVE ALL GEO HEIRARCHY AS IS\n # TIRES GEO MUST BE IN WORLD SPACE, THEY ARE BEING DEFORMED VIA BLENDSHAPE\n # INSTEAD OF SCALING ENTIRE GROUP WITH RIG, SCALE INDIVIDUAL OBJECTS...\n all_geo = get_geo_list( name = name, ns = ns, all = True )\n tires = []\n # print( get_geo_list( name = name, tire_front_l = True ) )\n tires.append( get_geo_list( name = name, ns = ns, tire_front_l = True )[0] )\n tires.append( get_geo_list( name = name, ns = ns, tire_front_r = True )[0] )\n tires.append( get_geo_list( name = name, ns = ns, tire_back_l = True )[0] )\n tires.append( get_geo_list( name = name, ns = ns, tire_back_r = True )[0] )\n # add dynamic parts\n # all_geo.append( Ct[1][0] ) # target control\n # all_geo.append( Ct[3] ) # follicle groupo\n #\n for geo in all_geo:\n if geo not in tires:\n for s in scl:\n cmds.connectAttr( mstr + '.' + uni, geo + s )\n '''\n\n\ndef props( chassis_jnt = '', X = 1.0 ):\n '''\n \n '''\n #\n # left\n clr = 'blue'\n j = 'propeller_02_L_jnt'\n nm = j.split( '_' )[0]\n vhl.rotate_part( name = nm, suffix = 'L', obj = j, objConstrain = True, parent = chassis_jnt, rotations = [0, 0, 1], X = X, shape = 'facetZup_ctrl', color = clr )\n # right\n clr = 'red'\n j = 'propeller_02_R_jnt'\n nm = j.split( '_' )[0]\n vhl.rotate_part( name = nm, suffix = 'R', obj = j, objConstrain = True, parent = chassis_jnt, rotations = [0, 0, 1], X = X, shape = 'facetZup_ctrl', color = clr )\n\n\ndef rudders( chassis_jnt = '', X = 1.0 ):\n '''\n \n '''\n #\n # left\n clr = 'blue'\n j = 'rudder_02_L_jnt'\n nm = j.split( '_' )[0]\n vhl.rotate_part( name = nm, suffix = 'L', obj = j, objConstrain = True, parent = chassis_jnt, rotations = [0, 0, 1], X = X, shape = 'squareXup_ctrl', color = clr )\n # right\n clr = 'red'\n j = 'rudder_02_R_jnt'\n nm = j.split( '_' )[0]\n vhl.rotate_part( name = nm, suffix = 'R', obj = j, objConstrain = True, parent = chassis_jnt, rotations = [0, 0, 1], X = X, shape = 'squareXup_ctrl', color = clr )\n\n\ndef get_geo_list( name = '', ns = '', chassis = False,\n prop_l = False, rudder_l = False,\n prop_r = False, rudder_r = False,\n all = False ):\n '''\n geo members via selection set\n '''\n geos = []\n geo_sets = []\n\n # chassis\n if chassis or all:\n geo_list = process_geo_list( name = name + '_' + 'chassis' )\n geo_sets.append( geo_list )\n\n # back l\n if prop_l or all:\n geo_list = process_geo_list( name = name + '_' + 'prop_l' )\n geo_sets.append( geo_list )\n '''\n if rudder_l or all:\n geo_list = process_geo_list( name = name + '_' + 'rudder_l' )\n geo_sets.append( geo_list )\n '''\n # back r\n if prop_r or all:\n geo_list = process_geo_list( name = name + '_' + 'prop_r' )\n geo_sets.append( geo_list )\n '''\n if rudder_r or all:\n geo_list = process_geo_list( name = name + '_' + 'rudder_r' )\n geo_sets.append( geo_list )\n '''\n\n # build list\n for geo_set in geo_sets:\n for geo in geo_set:\n if ns:\n geos.append( ns + ':' + geo )\n else:\n geos.append( geo )\n\n return geos\n\n\ndef process_geo_list( name = '' ):\n '''\n \n '''\n s = []\n setDict = ss.loadDict( os.path.join( ss.defaultPath(), name + '.sel' ) )\n # print( setDict )\n for obj in setDict.values():\n s.append( obj )\n # print( s )\n return s\n\n\ndef passengers( X = 1 ):\n '''\n master with individual controls for each passenger\n add scale\n '''\n #\n PreBuild = place.rigPrebuild( Top = 0, Ctrl = True, SknJnts = True, Geo = True, World = True, Master = True, OlSkool = False, Size = X )\n CHARACTER = PreBuild[0]\n CONTROLS = PreBuild[1]\n SKIN_JOINTS = PreBuild[2]\n GEO = PreBuild[3]\n WORLD_SPACE = PreBuild[4]\n MasterCt = PreBuild[5]\n #\n root = 'root_jnt'\n place.cleanUp( root, SknJnts = True )\n cmds.parentConstraint( MasterCt[4], root, mo = True )\n #\n color = 'yellow'\n shape = 'facetYup_ctrl'\n shapeH = 'facetZup_ctrl'\n #\n jnts = [\n 'Peter_root_jnt',\n 'Paula_root_jnt',\n 'Vojta_root_jnt',\n 'Filip_root_jnt'\n ]\n names = [\n 'Peter',\n 'Paula',\n 'Vojta',\n 'Filip'\n ]\n geo_vis = [\n 'geo:GTP_EMan_Peter_20_Stt_Drvg_Adl_Ccs_Gry',\n 'geo:GTP_CWman_Paula_18_Stt_Clp_Obs_Sd_Adl_Asn',\n 'geo:GTP_CMan_Vojta_03_Stt_Lsn_Adl_Ccs_Mgr',\n 'geo:GTP_CMan_Filip_10_Stt_Exp_Adl_Ccs_Adl_Ccs_Mgr'\n ]\n # loop\n for i in range( len( jnts ) ):\n name = names[i]\n jnt = jnts[i]\n # butt\n name_Ct = place.Controller2( name, jnt, True, shape, X * 0.8, 12, 8, 1, ( 0, 0, 1 ), True, True, colorName = color ).result\n place.cleanUp( name_Ct[0], Ctrl = True )\n cmds.parentConstraint( name_Ct[4], jnt, mo = True )\n cmds.parentConstraint( MasterCt[4], name_Ct[0], mo = False )\n # head\n head_Ct = place.Controller2( name + '_head', name + '_3_jnt', True, shapeH, X * 0.4, 12, 8, 1, ( 0, 0, 1 ), True, True, colorName = color ).result\n place.cleanUp( head_Ct[0], Ctrl = True )\n cmds.pointConstraint( name + '_3_jnt', head_Ct[0], mo = True )\n cmds.orientConstraint( MasterCt[4], head_Ct[0], mo = True )\n cmds.orientConstraint( head_Ct[4], name + '_3_jnt', mo = True )\n # pose\n place.hijackAttrs( name + '_1_jnt', name_Ct[2], 'rotateX', 'kneeBend', set = False, default = 60, force = True )\n place.hijackScaleMerge( name + '_root_jnt', name_Ct[2], mergeAttr = 'Scale' )\n cmds.setAttr( name_Ct[2] + '.Scale', 0.83 )\n # visibility\n place.hijackAttrs( geo_vis[i], name_Ct[2], 'visibility', 'geoVis', set = False, default = 1, force = True )\n\n\ndef ref_cars( ref = False ):\n '''\n ref things\n '''\n #\n path = 'P:\\\\MDLN\\\\assets\\\\set\\\\setCorolla\\\\rig\\\\maya\\\\scenes\\\\setCorolla_rigCombined_v006.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'setCorolla' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\set\\\\setHyundaiTucson\\\\rig\\\\maya\\\\scenes\\\\setHyundaiTucson_rigCombined_v003.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'setHyundaiTucson' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\set\\\\setMazda3\\\\rig\\\\maya\\\\scenes\\\\setMazda3_rigCombined_v004.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'setMazda3' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\set\\\\setMazdaCX7\\\\rig\\\\maya\\\\scenes\\\\setMazdaCX7_rigCombined_v004.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'setMazdaCX7' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\set\\\\setMercedesC63\\\\rig\\\\maya\\\\scenes\\\\setMercedesC63_rigCombined_v005.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'setMercedesC63' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\set\\\\setToyotaRav4\\\\rig\\\\maya\\\\scenes\\\\setToyotaRav4_rigCombined_v003.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'setToyotaRav4' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\set\\\\setVolkswagenPassat\\\\rig\\\\maya\\\\scenes\\\\setVolkswagenPassat_rigCombined_v008.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'setVolkswagenPassat' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\veh\\\\2019ToyotaRav4\\\\rig\\\\maya\\\\scenes\\\\2019ToyotaRav4_rigCombined_v004.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = '2019ToyotaRav4' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\veh\\\\AcuraMdx\\\\rig\\\\maya\\\\scenes\\\\AcuraMdx_rigCombined_v004.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'AcuraMdx' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\veh\\\\MazdaCx5\\\\rig\\\\maya\\\\scenes\\\\MazdaCx5_rigCombined_v005.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'MazdaCx5' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\veh\\\\MercedesSprinter\\\\rig\\\\maya\\\\scenes\\\\MercedesSprinter_rigCombined_v006.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'MercedesSprinter' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\veh\\\\Toyota4runner\\\\rig\\\\maya\\\\scenes\\\\Toyota4runner_rigCombined_v005.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'Toyota4runner' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\veh\\\\Truck\\\\rig\\\\maya\\\\scenes\\\\Truck_rigCombined_v005.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'Truck' )\n else:\n print( 'no___', path )\n\n\ndef ref_cars_passengers( ref = False ):\n '''\n ref things\n '''\n #\n path = 'P:\\\\MDLN\\\\assets\\\\set\\\\setCorolla\\\\rig\\\\maya\\\\scenes\\\\setCorolla_rigPassengers_v006.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'setCorolla' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\set\\\\setHyundaiTucson\\\\rig\\\\maya\\\\scenes\\\\setHyundaiTucson_rigPassengers_v003.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'setHyundaiTucson' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\set\\\\setMazda3\\\\rig\\\\maya\\\\scenes\\\\setMazda3_rigPassengers_v004.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'setMazda3' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\set\\\\setMazdaCX7\\\\rig\\\\maya\\\\scenes\\\\setMazdaCX7_rigPassengers_v004.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'setMazdaCX7' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\set\\\\setMercedesC63\\\\rig\\\\maya\\\\scenes\\\\setMercedesC63_rigPassengers_v005.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'setMercedesC63' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\set\\\\setToyotaRav4\\\\rig\\\\maya\\\\scenes\\\\setToyotaRav4_rigPassengers_v003.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'setToyotaRav4' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\set\\\\setVolkswagenPassat\\\\rig\\\\maya\\\\scenes\\\\setVolkswagenPassat_rigPassengers_v008.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'setVolkswagenPassat' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\veh\\\\2019ToyotaRav4\\\\rig\\\\maya\\\\scenes\\\\2019ToyotaRav4_rigPassengers_v004.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = '2019ToyotaRav4' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\veh\\\\AcuraMdx\\\\rig\\\\maya\\\\scenes\\\\AcuraMdx_rigPassengers_v004.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'AcuraMdx' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\veh\\\\MazdaCx5\\\\rig\\\\maya\\\\scenes\\\\MazdaCx5_rigPassengers_v005.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'MazdaCx5' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\veh\\\\MercedesSprinter\\\\rig\\\\maya\\\\scenes\\\\MercedesSprinter_rigPassengers_v006.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'MercedesSprinter' )\n else:\n print( 'no___', path )\n #\n path = 'P:\\\\MDLN\\\\assets\\\\veh\\\\Toyota4runner\\\\rig\\\\maya\\\\scenes\\\\Toyota4runner_rigPassengers_v005.ma'\n if os.path.isfile( path ):\n print( path )\n if ref:\n cmds.file( path, reference = True, namespace = 'Toyota4runner' )\n else:\n print( 'no___', path )\n\n\ndef set_for_animation():\n '''\n \n '''\n # dynamics\n try:\n cmds.select( \"*:*:chassis_dynamicTarget\" )\n sel = cmds.ls( sl = 1 )\n for s in sel:\n cmds.setAttr( s + '.dynamicParentOffOn', 0 )\n cmds.setAttr( s + '.enable', 0 )\n except:\n pass\n # tires\n try:\n cmds.select( \"*:*:move\" )\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n cmds.setAttr( s + '.tireGeo', 0 )\n cmds.setAttr( s + '.tireProxy', 1 )\n except:\n pass\n # traffic tires\n try:\n cmds.select( \"*:*:*:move\" )\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n cmds.setAttr( s + '.tireGeo', 0 )\n cmds.setAttr( s + '.tireProxy', 1 )\n except:\n pass\n # time\n cmds.playbackOptions( minTime = 1001 )\n cmds.playbackOptions( animationStartTime = 1001 )\n\n\ndef set_all_dynamics():\n '''\n \n '''\n # time\n cmds.playbackOptions( minTime = 970 )\n cmds.playbackOptions( animationStartTime = 970 )\n # dynamics\n cmds.select( clear = True )\n try:\n cmds.select( \"*:*:chassis_dynamicTarget\" )\n except:\n pass\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n cmds.setAttr( s + '.dynamicParentOffOn', 1 )\n cmds.setAttr( s + '.enable', 1 )\n cmds.setAttr( s + '.startFrame', 970 )\n\n\ndef set_obj_dynamics( obj = '', on = False ):\n '''\n \n '''\n if on:\n cmds.setAttr( obj + '.dynamicParentOffOn', 1 )\n cmds.setAttr( obj + '.enable', 1 )\n cmds.setAttr( obj + '.startFrame', 970 )\n else:\n cmds.setAttr( obj + '.dynamicParentOffOn', 0 )\n cmds.setAttr( obj + '.enable', 0 )\n cmds.setAttr( obj + '.startFrame', 970 )\n\n\ndef set_for_playblast( dynamics = False, tires = False ):\n '''\n \n '''\n # time\n cmds.playbackOptions( minTime = 1001 )\n cmds.playbackOptions( animationStartTime = 1001 )\n # dynamics\n if dynamics:\n # delete anim\n transform = ['translateX', 'translateY', 'translateZ', 'rotateX', 'rotateY', 'rotateZ']\n try:\n cmds.select( \"*:*:chassis_dynamicBase\" )\n sel = cmds.ls( sl = 1 )\n #\n if sel:\n for s in sel:\n if rig_qualified_to_bake( s ):\n ac.deleteAnim2( s, attrs = transform )\n for i in transform:\n cmds.setAttr( s + '.' + i, 0 )\n # set\n set_all_dynamics()\n except:\n pass\n # tires\n if tires:\n try:\n cmds.select( \"*:*:move\" )\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n cmds.setAttr( s + '.tireGeo', 1 )\n cmds.setAttr( s + '.tireProxy', 0 )\n except:\n pass\n # traffic tires\n try:\n cmds.select( \"*:*:*:move\" )\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n cmds.setAttr( s + '.tireGeo', 1 )\n cmds.setAttr( s + '.tireProxy', 0 )\n except:\n pass\n\n\ndef renderLayerBlast():\n '''\n using animPublish file\n *:*:geo:*\n '''\n # clear selection\n cmds.select( cl = 1 )\n\n path = cmds.file( query = True, exn = True )\n print( path )\n subDir = ''\n cars = False\n if '101_001' in path or '101_027' in path:\n # ferry shot\n subDir = 'ferryAnimBty'\n else:\n # bridge shot\n subDir = 'carAnimBty'\n cars = True\n #\n if '_animPublish_' in path:\n path = path.replace( '_animPublish_', '_anim_' )\n # rename the current file\n cmds.file( path, rn = path )\n\n # rename the current file\n # cmds.file( path, rn = path )\n\n # geo\n go = True\n geoAll = []\n if cars:\n # env\n cmds.select( 'Bridge:*' )\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n geoAll.append( s )\n else:\n print( 'no sel, env' )\n cmds.setAttr( '____env.visibility', 1 )\n # hero cars\n cmds.select( clear = 1 )\n try:\n cmds.select( '*:*:geo:*' )\n except:\n pass\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n if ':geo:' in s and 'f[' not in s:\n geoAll.append( s )\n else:\n print( 'no sel, hero cars' )\n # traffic cars\n cmds.select( clear = 1 )\n try:\n cmds.select( '*:*:*:geo:*' )\n except:\n pass\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n if ':geo:' in s and 'f[' not in s:\n geoAll.append( s )\n else:\n print( 'no sel, traffic cars' )\n else:\n # ferry\n cmds.select( '*:geo:ferry_grp' )\n cmds.select( 'directionalLight1', add = True )\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n geoAll.append( s )\n\n #\n if geoAll:\n #\n existing_layers = cmds.ls( type = 'renderLayer' )\n if subDir not in existing_layers:\n cmds.select( geoAll )\n lyr = cmds.createRenderLayer( name = subDir, makeCurrent = True )\n cmds.select( cl = 1 )\n else:\n cmds.editRenderLayerGlobals( crl = subDir )\n #\n pnl = cmds.getPanel( withFocus = True )\n try:\n cmds.editRenderLayerGlobals( crl = subDir )\n except:\n go = False\n #\n if go:\n set_for_playblast( dynamics = False, tires = True )\n cmds.setFocus( pnl )\n cmds.currentTime( 1002 )\n cmds.currentTime( 1001 )\n cmds.select( clear = 1 )\n result = pb.blast( x = 0.5, format = \"image\", qlt = 100, compression = \"png\", offScreen = True, useGlobals = True, forceTemp = True, camStr = False, strp_r = True, subDir = subDir, play = False )\n print( result ) # [u'C:/Users/sebas/Documents/maya/__PLAYBLASTS__\\\\101_009_0100_animPublish_v014\\\\101_009_0100_animPublish_v014_carAnimBty', u'101_009_0100_animPublish_v014_carAnimBty']\n mp4 = ffm.imgToMp4( pathIn = result[0], image = result[1], start = 1001, pathOut = result[0], pathOutName = result[1] )\n pb.blastRenameSeq( result = result, splitStr = '_v', moveStr = '_' + subDir )\n\n #\n cmds.editRenderLayerGlobals( currentRenderLayer = 'defaultRenderLayer' )\n cmds.delete( lyr )\n else:\n message( 'go == False, skipping shot', warning = True )\n else:\n message( 'no car geo found, skipping shot', warning = True )\n\n\ndef witness_camera():\n '''\n \n '''\n #\n result = cmds.ls( type = 'camera', o = 1 )\n for r in result:\n p = cmds.listRelatives( r, parent = 1 )\n if p:\n if ':witness_cam' in p[0]:\n return p[0]\n\n\ndef witness_plate( on = True ):\n '''\n \n '''\n cam = camName()\n #\n st = 0\n if on:\n st = 3\n #\n if cam:\n #\n connections = cmds.listConnections( cam, sh = True, t = 'imagePlane' )\n print( connections )\n #\n if connections:\n connections = list( set( connections ) )\n plates = platesOnly( connections )\n #\n for plate in plates:\n p = plate.split( '->' )[1]\n if ':' not in p:\n cmds.setAttr( p + '.displayMode', st )\n cmds.setAttr( p + '.frameCache', 0 )\n else:\n message( 'No plates' )\n else:\n message( 'Not a camera' )\n\n\ndef camName():\n pnl = cmds.getPanel( withFocus = True )\n typ = cmds.getPanel( typeOf = pnl )\n if typ == 'modelPanel':\n cam = cmds.modelPanel( pnl, q = True, cam = True )\n if cam:\n typ = cmds.objectType( cam )\n if typ == 'camera':\n return cam\n else:\n if typ == 'transform':\n trans = PyNode( cam )\n # get the transform's shape, aka the camera node\n cam = trans.getShape()\n return str( cam )\n else:\n # print 'no model returned', cam\n pass\n else:\n # print 'not model panel', pnl\n pass\n\n\ndef platesOnly( connections ):\n plates = []\n for item in connections:\n if cmds.nodeType( item ) == 'imagePlane':\n plates.append( item )\n return plates\n\n\ndef witness_blast():\n '''\n for ferry, prfile view\n using animPublish file\n *:*:geo:*\n '''\n # clear selection\n cmds.select( cl = 1 )\n\n path = cmds.file( query = True, exn = True )\n print( path )\n subDir = ''\n cars = False\n if '101_001' in path:\n # ferry shot\n subDir = 'ferryWitness'\n #\n if '_animPublish_' in path:\n path = path.replace( '_animPublish_', '_anim_' )\n # rename the current file\n cmds.file( path, rn = path )\n\n # geo\n go = True\n geoAll = []\n\n # ferry\n cmds.select( clear = True )\n cmds.select( '*:geo:ferry_grp' )\n cmds.select( 'directionalLight1', add = True )\n cmds.select( '*:witness_cam', add = True )\n cmds.select( '*:cam_grp', add = True )\n sel = cmds.ls( sl = 1 )\n if sel:\n for s in sel:\n geoAll.append( s )\n\n #\n lyr = None\n if geoAll:\n #\n existing_layers = cmds.ls( type = 'renderLayer' )\n if subDir not in existing_layers:\n cmds.select( geoAll )\n lyr = cmds.createRenderLayer( name = subDir, makeCurrent = True )\n cmds.select( cl = 1 )\n else:\n lyr = subDir\n cmds.editRenderLayerGlobals( crl = subDir )\n #\n pnl = cmds.getPanel( withFocus = True )\n cam = cmds.modelPanel( pnl, q = True, camera = True )\n wit_cam = witness_camera()\n cmds.setAttr( wit_cam + '.nearClipPlane', 100 )\n cmds.modelPanel( pnl, e = True, cam = wit_cam )\n mel.eval( 'modelEditor -e -udm true ' + pnl + ';' )\n mel.eval( 'modelEditor -e -dl \"default\" ' + pnl + ';' )\n try:\n cmds.editRenderLayerGlobals( crl = subDir )\n except:\n go = False\n #\n if go:\n set_for_playblast( dynamics = False, tires = True )\n cmds.setFocus( pnl )\n cmds.currentTime( 1002 )\n cmds.currentTime( 1001 )\n cmds.select( clear = 1 )\n result = pb.blast( x = 0.5, format = \"image\", qlt = 100, compression = \"png\", offScreen = True, useGlobals = True, forceTemp = True, camStr = False, strp_r = True, subDir = subDir, play = False )\n print( result ) # [u'C:/Users/sebas/Documents/maya/__PLAYBLASTS__\\\\101_009_0100_animPublish_v014\\\\101_009_0100_animPublish_v014_carAnimBty', u'101_009_0100_animPublish_v014_carAnimBty']\n mp4 = ffm.imgToMp4( pathIn = result[0], image = result[1], start = 1001, pathOut = result[0], pathOutName = result[1] )\n result = pb.blastRenameSeq( result = result, splitStr = '_v', moveStr = '_' + subDir )\n #\n source = result[0]\n print( source )\n path = cmds.file( query = True, exn = True )\n sht = path.rsplit( '/', 1 )[1].split( '.' )[0]\n sht = sht.replace( '_anim_', '_anim_' + subDir + '_' )\n print( sht )\n dest = path.split( 'maya' )[0]\n dest = os.path.join( dest, 'playblasts' )\n dest = os.path.join( dest, sht )\n print( dest )\n if os.path.isdir( dest ):\n shutil.rmtree( dest )\n shutil.copytree( source.replace( '\\\\', '/' ), dest.replace( '\\\\', '/' ) )\n shutil.rmtree( source.replace( '\\\\', '/' ) )\n\n #\n cmds.modelPanel( pnl, e = True, cam = cam )\n mel.eval( 'modelEditor -e -udm false ' + pnl + ';' )\n mel.eval( 'modelEditor -e -dl \"all\" ' + pnl + ';' )\n cmds.editRenderLayerGlobals( currentRenderLayer = 'defaultRenderLayer' )\n cmds.delete( lyr )\n else:\n message( 'go == False, skipping shot', warning = True )\n else:\n message( 'no ferry geo found, skipping shot', warning = True )\n\n\ndef blast( dynamics = False, burn_in = True ):\n '''\n \n '''\n start = 1001\n\n # res\n special_shot = '101_009_1000'\n special_shot2 = '101_001_'\n special_shot3 = '101_027_'\n special_shot4 = '101_009_0310'\n path = cmds.file( query = True, exn = True )\n # resolution\n if special_shot in path or special_shot2 in path or special_shot3 in path or special_shot4 in path:\n cmds.setAttr( 'defaultResolution.width', 3840 )\n cmds.setAttr( 'defaultResolution.height', 2160 )\n else:\n cmds.setAttr( 'defaultResolution.width', 4448 )\n cmds.setAttr( 'defaultResolution.height', 3096 )\n # ferry or bridge\n if special_shot2 in path or special_shot3 in path:\n special_shot2 = True\n else:\n special_shot2 = False\n\n # blast\n set_for_playblast( dynamics = dynamics )\n\n #\n # witness_plate( on = False )\n '''\n if special_shot2:\n witness_blast()'''\n # return\n\n #\n if burn_in:\n # blast\n #\n #\n if special_shot2:\n # witness_plate( on = True )\n result = pb.blast( x = 0.5, format = \"image\", qlt = 100, compression = \"png\", offScreen = True, useGlobals = True, forceTemp = True, camStr = False, strp_r = True, subDir = 'precomp', play = False ) # blastPath, blastName\n # to mp4\n pathOut = result[0].replace( result[1], '' )\n pathOutName = result[1].replace( '_precomp', '____cam' ) # added cam string, burnin expects cam suffix\n mp4 = ffm.imgToMp4( pathIn = result[0], image = result[1], start = start, pathOut = pathOut, pathOutName = pathOutName )\n # copy mp4 to image seq directory, matching name\n shutil.copyfile( mp4, os.path.join( result[0], result[1] + '.mp4' ) )\n print( result[0] )\n shutil.rmtree( result[0] )\n # add burn in\n ffm.burn_in( filein = mp4, startFrame = start, size = 35, rndrFrames = False )\n # witness_plate( on = False )\n #\n #\n # return\n cmds.select( clear = 1 )\n result = pb.blast( x = 0.5, format = \"image\", qlt = 100, compression = \"png\", offScreen = True, useGlobals = True, forceTemp = True, camStr = False, strp_r = True, subDir = 'precomp', play = False ) # blastPath, blastName\n # to mp4\n if not special_shot2:\n pathOut = result[0].replace( result[1], '' )\n pathOutName = result[1].replace( '_precomp', '____cam' ) # added cam string, burnin expects cam suffix\n else:\n pathOut = result[0]\n pathOutName = result[1]\n mp4 = ffm.imgToMp4( pathIn = result[0], image = result[1], start = start, pathOut = pathOut, pathOutName = pathOutName )\n if not special_shot2:\n # copy mp4 to image seq directory, matching name\n shutil.copyfile( mp4, os.path.join( result[0], result[1] + '.mp4' ) )\n # add burn in\n ffm.burn_in( filein = mp4, startFrame = start, size = 35, rndrFrames = False )\n # move precomp string in all image seq names, including new copied mp4\n pb.blastRenameSeq( result = result, splitStr = '_v', moveStr = '_precomp' )\n # beauty blast with qt\n renderLayerBlast()\n # witness_plate( on = True )\n else:\n # expecting traffic shots from bridge\n result = pb.blast( x = 0.5, format = \"image\", qlt = 100, compression = \"png\", offScreen = True, useGlobals = True, forceTemp = True, camStr = False, strp_r = True, subDir = '', play = False ) # blastPath, blastNam\n source = result[0]\n print( source )\n path = cmds.file( query = True, exn = True )\n sht = path.rsplit( '/', 1 )[1].split( '.' )[0]\n print( sht )\n dest = path.split( 'maya' )[0]\n dest = os.path.join( dest, 'playblasts' )\n dest = os.path.join( dest, sht )\n print( dest )\n if os.path.isdir( dest ):\n shutil.rmtree( dest )\n shutil.copytree( source.replace( '\\\\', '/' ), dest.replace( '\\\\', '/' ) )\n\n # pb.blastRenameSeq( result = result, splitStr = '_v', moveStr = '_traffic' )\n #\n set_for_animation()\n\n\ndef rig_qualified_to_bake( obj = '' ):\n '''\n if object moving on path, qualified\n '''\n pth = 'pth'\n ns = obj.split( \":\", 1 )[0]\n onPath_front = ns + ':' + pth + ':onPath_front'\n if cmds.objExists( onPath_front ):\n animCurves = cmds.findKeyframe( onPath_front, c = True )\n if animCurves:\n # print( 'bake', ns )\n return True\n else:\n # print( 'no bake', ns )\n return False\n else:\n return False\n\n\ndef shot_qualified_to_bake( path = '' ):\n '''\n \n '''\n shots = [ '101_009_0300', '101_009_0400', '101_009_0500', '101_009_0700']\n for s in shots:\n if s in path:\n return True\n return False\n\n\ndef bake_dynamics():\n '''\n\n '''\n #\n cmds.playbackOptions( minTime = 970 )\n cmds.playbackOptions( animationStartTime = 970 )\n #\n transform = ['translateX', 'translateY', 'translateZ', 'rotateX', 'rotateY', 'rotateZ']\n cmds.select( clear = 1 )\n try:\n cmds.select( \"*:*:chassis_dynamicBase\" )\n except:\n pass\n sel = cmds.ls( sl = 1 )\n qualified_rigs = []\n n = None\n # qualify\n if sel:\n for s in sel:\n if rig_qualified_to_bake( s ):\n ac.deleteAnim2( s, attrs = transform )\n for i in transform:\n cmds.setAttr( s + '.' + i, 0 )\n #\n ref = s.rsplit( ':', 1 )[0]\n set_obj_dynamics( ref + ':chassis_dynamicTarget', on = True )\n qualified_rigs.append( ref + ':chassis_dynamicTarget' )\n #\n if qualified_rigs:\n print( qualified_rigs )\n cmds.select( qualified_rigs )\n # store\n n = anm.SpaceSwitchList()\n # restore\n for q in qualified_rigs:\n set_obj_dynamics( q, on = False )\n n.restore()\n #\n cmds.playbackOptions( minTime = 1001 )\n cmds.playbackOptions( animationStartTime = 1001 )\n\n\ndef load_offloaded( find = '' ):\n '''\n pplRN\n '''\n #\n rfs = cmds.ls( typ = 'reference' )\n for ref in rfs:\n stt = True\n try:\n stt = cmds.referenceQuery( ref, isLoaded = True )\n except:\n pass\n if not stt:\n if find:\n if find in ref:\n cmds.file( lr = ref, lrd = 'all' )\n else:\n cmds.file( lr = ref, lrd = 'all' )\n\n\ndef offload_loaded( find = '' ):\n '''\n pplRN\n '''\n #\n rfs = cmds.ls( typ = 'reference' )\n for ref in rfs:\n stt = False\n try:\n stt = cmds.referenceQuery( ref, isLoaded = True )\n except:\n pass\n if stt:\n if find:\n if find in ref:\n cmds.file( ur = ref )\n else:\n cmds.file( ur = ref )\n\n\ndef save_publish( find = '_anim_', addSuffix = '_animPublish_' ):\n '''\n add suffix to scene, save\n '''\n # current name, path\n path = cmds.file( query = True, exn = True )\n print( path )\n if find in path:\n path = path.replace( find, addSuffix )\n print( path )\n #\n # get the current file type\n if cmds.file( sn = True , q = True ):\n fileType = cmds.file( query = True, typ = True )\n else:\n fileType = ['mayaAscii']\n # add the file about to be saved to the recent files menu\n mel.eval( 'addRecentFile \"' + path + '\" ' + fileType[0] + ';' )\n # rename the current file\n cmds.file( path, rn = path )\n # save it\n cmds.file( save = True, typ = fileType[0] )\n\n\ndef publish( full = True ):\n '''\n publish: playblast and save maya scene version\n '''\n # start timer\n start = time.time()\n\n # publish layout, cam, proxies\n success = publish_layout()\n\n #\n ferry = False\n special_shot = '101_001_'\n path = cmds.file( query = True, exn = True )\n if special_shot in path:\n ferry = True\n\n #\n if success and full:\n\n if not ferry:\n # bake dynamics\n if shot_qualified_to_bake( path ):\n bake_dynamics()\n #\n load_offloaded() # all\n offload_loaded( find = 'pplRN' ) # remove people\n blast()\n set_for_playblast( tires = True )\n else:\n blast()\n save_publish()\n if cmds.objExists( 'directionalLight1' ):\n cmds.setAttr( 'directionalLight1.visibility', 0 )\n\n # end timer\n end = time.time()\n elapsed = end - start\n print( 'Publish time: ' + str( elapsed / 60 ) + ' min' )\n\n\ndef publish_layout():\n '''\n \n '''\n #\n setProxies = 'setProxies'\n special_shot = '101_001_'\n special_shot1 = '101_027_'\n path = cmds.file( query = True, exn = True )\n if special_shot in path or special_shot1 in path:\n setProxies = 'cam_grp'\n #\n cams = publish_cameras()\n if cams:\n ns = cams[0].split( ':' )[0]\n proxy = ns + ':' + setProxies\n if cmds.objExists( proxy ):\n publish_proxies( proxies = [proxy] )\n return True\n else:\n print( 'proxy fail: ', proxy )\n else:\n print( 'cams fail: ', cams )\n return False\n\n\ndef publish_cameras():\n '''\n \n '''\n exclude = ['front', 'persp', 'side', 'top']\n cams = []\n result = cmds.ls( type = 'camera', o = 1 )\n for r in result:\n p = cmds.listRelatives( r, parent = 1 )\n if p:\n if p[0] not in exclude and 'cam_follow' not in p[0] and 'witness_cam' not in p[0]:\n cams.append( p[0] )\n print( cams )\n for cam in cams:\n cmds.select( cam )\n cas.cache_abc( framePad = 5, frameSample = 0.25, forceType = False, camera = True, forceOverwrite = True )\n return cams\n\n\ndef publish_proxies( proxies = [] ):\n '''\n \n '''\n for p in proxies:\n cmds.select( p )\n cas.cache_abc( framePad = 5, frameSample = 1.0, forceType = False, camera = False, forceOverwrite = True )\n cmds.select( clear = 1 )\n\n\ndef publish_all_layouts( publish_layouts = False, publish_full = False ):\n '''\n find latest files in assumed shots, publish cameras and proxies \n '''\n # start timer\n start = time.time()\n\n shots = [\n 'P:\\\\MDLN\\\\101\\\\101_009_0100\\\\anim\\\\maya\\\\',\n 'P:\\\\MDLN\\\\101\\\\101_009_0200\\\\anim\\\\maya\\\\',\n 'P:\\\\MDLN\\\\101\\\\101_009_0300\\\\anim\\\\maya\\\\',\n 'P:\\\\MDLN\\\\101\\\\101_009_0400\\\\anim\\\\maya\\\\',\n 'P:\\\\MDLN\\\\101\\\\101_009_0500\\\\anim\\\\maya\\\\',\n 'P:\\\\MDLN\\\\101\\\\101_009_0700\\\\anim\\\\maya\\\\',\n 'P:\\\\MDLN\\\\101\\\\101_009_0800\\\\anim\\\\maya\\\\',\n 'P:\\\\MDLN\\\\101\\\\101_009_0900\\\\anim\\\\maya\\\\',\n 'P:\\\\MDLN\\\\101\\\\101_009_1000\\\\anim\\\\maya\\\\'\n ]\n '''\n shots = [\n 'P:\\\\MDLN\\\\101\\\\101_009_0100\\\\anim\\\\maya\\\\'\n ]'''\n # cache\n for project_path in shots:\n project_path = project_path.replace( '\\\\', '/' )\n # set project\n mel_command = ( 'setProject \"' + project_path + '\";' )\n mel.eval( mel_command )\n mel.eval( 'print \\\" -- Project set to -- ' + project_path + ' -- \\\";' )\n # latest scene\n scenes_path = os.path.join( project_path, 'scenes' )\n list_of_files = glob.glob( os.path.join( scenes_path, '*.ma' ) ) # * means all if need specific format then *.csv\n filtered_list = []\n for f in list_of_files:\n if 'Traffic' not in f and 'Publish' not in f:\n filtered_list.append( f )\n latest_file = max( filtered_list, key = os.path.getctime )\n # print( latest_file )\n # open latest\n latest_file_path = os.path.join( scenes_path, latest_file )\n print( latest_file_path )\n # publish type\n if publish_layouts and not publish_full:\n # file existance\n if os.path.isfile( latest_file_path ):\n cmds.file( latest_file_path, open = True, force = True )\n publish( full = False )\n elif publish_full and not publish_layouts:\n # file existance\n if os.path.isfile( latest_file_path ):\n cmds.file( latest_file_path, open = True, force = True )\n # find camera for playblast before starting full publish\n camera = look_through_publish_camera()\n if camera:\n publish( full = True )\n else:\n print( 'Quitting. Couldnt find camera for scene: ', latest_file_path )\n break\n else:\n if os.path.isfile( latest_file_path ):\n print( 'is file... options not set to publish.' )\n\n # end timer\n end = time.time()\n elapsed = end - start\n print( 'Shots Publish time: ' + str( elapsed / 60 ) + ' min' )\n\n\ndef look_through_publish_camera():\n '''\n \n '''\n exclude = ['front', 'persp', 'side', 'top']\n cams = []\n result = cmds.ls( type = 'camera', o = 1 )\n for r in result:\n p = cmds.listRelatives( r, parent = 1 )\n if p:\n if p[0] not in exclude and 'cam_follow' not in p[0] and 'renderCam' not in p[0] and ':' in p[0]:\n cams.append( p[0] )\n if len( cams ) == 1:\n cmds.lookThru( 'perspView', cams[0] )\n ds.toggleObjectDisplay( purpose = 'cam' )\n tp.platesAllOn()\n print( 'playblast camera: ', cams[0] )\n return cams[0]\n else:\n print( 'too many cameras' )\n print( cams )\n return None\n\n\n#\ngeo_grps = [\n 'setCorolla_grp',\n 'setHyundaiTuscon_grp',\n 'mazda3_grp',\n 'mazda_cx_7_grp',\n 'merc_grp',\n 'toyotaRav4_grp',\n 'setVolkswagenPassat_grp',\n 'Toyota_RAV4',\n 'acuraMdx_grp',\n 'mazdaCx5_grp',\n 'mercedesSprinter_grp',\n 'Toyota4Runner_grp',\n 'Truck_grp'\n ]\n#\n'''\n# people off\ncmds.select('*:*:*:driver_grp')\nsel = cmds.ls(sl=1)\nfor s in sel:\n cmds.setAttr(s + '.visibility', 0)\n# people on\ncmds.select('*:*:*:driver_grp')\nsel = cmds.ls(sl=1)\nfor s in sel:\n cmds.setAttr(s + '.visibility', 1)\n\n\n# select path masters\ncmds.select('*:pth:master')\n\n\n\nimp.reload( web )\nsymd = web.mod( \"assets_symd\" )\nsymd.king_air()\n'''\n#\n", "repo_name": "boochos/work", "sub_path": "assets_mdln.py", "file_name": "assets_mdln.py", "file_ext": "py", "file_size_in_byte": 44613, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "webrImport.mod", "line_number": 15, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 16, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 17, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 18, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 19, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 20, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 21, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 22, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 23, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 24, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 25, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 26, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 27, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 28, "usage_type": "call"}, {"api_name": "maya.cmds.warning", "line_number": 36, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 36, "usage_type": "name"}, {"api_name": "maya.cmds", "line_number": 38, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 39, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 39, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 49, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 49, "usage_type": "name"}, {"api_name": "maya.cmds.polyNormalPerVertex", "line_number": 50, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 50, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 52, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 52, "usage_type": "name"}, {"api_name": "maya.cmds.polySoftEdge", "line_number": 53, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 53, "usage_type": "name"}, {"api_name": "maya.cmds.delete", "line_number": 55, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 55, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 119, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 119, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 128, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 128, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 133, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 133, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 136, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 136, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 140, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 140, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 250, "usage_type": "call"}, {"api_name": "os.path", "line_number": 250, "usage_type": "attribute"}, {"api_name": "maya.cmds.parentConstraint", "line_number": 274, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 274, "usage_type": "name"}, {"api_name": "maya.cmds.parentConstraint", "line_number": 305, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 305, "usage_type": "name"}, {"api_name": "maya.cmds.parentConstraint", "line_number": 306, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 306, "usage_type": "name"}, {"api_name": "maya.cmds.pointConstraint", "line_number": 310, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 310, "usage_type": "name"}, {"api_name": "maya.cmds.orientConstraint", "line_number": 311, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 311, "usage_type": "name"}, {"api_name": "maya.cmds.orientConstraint", "line_number": 312, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 312, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 316, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 316, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 327, "usage_type": "call"}, {"api_name": "os.path", "line_number": 327, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 330, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 330, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 335, "usage_type": "call"}, {"api_name": "os.path", "line_number": 335, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 338, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 338, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 343, "usage_type": "call"}, {"api_name": "os.path", "line_number": 343, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 346, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 346, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 351, "usage_type": "call"}, {"api_name": "os.path", "line_number": 351, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 354, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 354, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 359, "usage_type": "call"}, {"api_name": "os.path", "line_number": 359, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 362, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 362, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 367, "usage_type": "call"}, {"api_name": "os.path", "line_number": 367, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 370, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 370, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 375, "usage_type": "call"}, {"api_name": "os.path", "line_number": 375, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 378, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 378, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 383, "usage_type": "call"}, {"api_name": "os.path", "line_number": 383, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 386, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 386, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 391, "usage_type": "call"}, {"api_name": "os.path", "line_number": 391, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 394, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 394, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 399, "usage_type": "call"}, {"api_name": "os.path", "line_number": 399, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 402, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 402, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 407, "usage_type": "call"}, {"api_name": "os.path", "line_number": 407, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 410, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 410, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 415, "usage_type": "call"}, {"api_name": "os.path", "line_number": 415, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 418, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 418, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 423, "usage_type": "call"}, {"api_name": "os.path", "line_number": 423, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 426, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 426, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 437, "usage_type": "call"}, {"api_name": "os.path", "line_number": 437, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 440, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 440, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 445, "usage_type": "call"}, {"api_name": "os.path", "line_number": 445, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 448, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 448, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 453, "usage_type": "call"}, {"api_name": "os.path", "line_number": 453, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 456, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 456, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 461, "usage_type": "call"}, {"api_name": "os.path", "line_number": 461, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 464, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 464, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 469, "usage_type": "call"}, {"api_name": "os.path", "line_number": 469, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 472, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 472, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 477, "usage_type": "call"}, {"api_name": "os.path", "line_number": 477, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 480, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 480, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 485, "usage_type": "call"}, {"api_name": "os.path", "line_number": 485, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 488, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 488, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 493, "usage_type": "call"}, {"api_name": "os.path", "line_number": 493, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 496, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 496, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 501, "usage_type": "call"}, {"api_name": "os.path", "line_number": 501, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 504, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 504, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 509, "usage_type": "call"}, {"api_name": "os.path", "line_number": 509, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 512, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 512, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 517, "usage_type": "call"}, {"api_name": "os.path", "line_number": 517, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 520, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 520, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 525, "usage_type": "call"}, {"api_name": "os.path", "line_number": 525, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 528, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 528, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 539, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 539, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 540, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 540, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 542, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 542, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 543, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 543, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 548, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 548, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 549, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 549, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 552, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 552, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 553, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 553, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 558, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 558, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 559, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 559, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 562, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 562, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 563, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 563, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 567, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 567, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 568, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 568, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 576, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 576, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 577, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 577, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 579, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 579, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 581, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 581, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 584, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 584, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 587, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 587, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 588, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 588, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 589, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 589, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 597, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 597, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 598, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 598, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 599, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 599, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 601, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 601, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 602, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 602, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 603, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 603, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 611, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 611, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 612, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 612, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 618, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 618, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 619, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 619, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 626, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 626, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 634, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 634, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 635, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 635, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 638, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 638, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 639, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 639, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 644, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 644, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 645, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 645, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 648, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 648, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 649, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 649, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 660, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 660, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 662, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 662, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 677, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 677, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 687, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 687, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 688, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 688, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 694, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 694, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 696, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 696, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 698, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 698, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 701, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 701, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 709, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 709, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 711, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 711, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 714, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 714, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 723, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 723, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 724, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 724, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 725, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 725, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 733, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 733, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 735, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 735, "usage_type": "name"}, {"api_name": "maya.cmds.createRenderLayer", "line_number": 736, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 736, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 737, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 737, "usage_type": "name"}, {"api_name": "maya.cmds.editRenderLayerGlobals", "line_number": 739, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 739, "usage_type": "name"}, {"api_name": "maya.cmds.getPanel", "line_number": 741, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 741, "usage_type": "name"}, {"api_name": "maya.cmds.editRenderLayerGlobals", "line_number": 743, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 743, "usage_type": "name"}, {"api_name": "maya.cmds.setFocus", "line_number": 749, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 749, "usage_type": "name"}, {"api_name": "maya.cmds.currentTime", "line_number": 750, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 750, "usage_type": "name"}, {"api_name": "maya.cmds.currentTime", "line_number": 751, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 751, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 752, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 752, "usage_type": "name"}, {"api_name": "maya.cmds.editRenderLayerGlobals", "line_number": 759, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 759, "usage_type": "name"}, {"api_name": "maya.cmds.delete", "line_number": 760, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 760, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 772, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 772, "usage_type": "name"}, {"api_name": "maya.cmds.listRelatives", "line_number": 774, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 774, "usage_type": "name"}, {"api_name": "maya.cmds.listConnections", "line_number": 792, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 792, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 802, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 802, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 803, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 803, "usage_type": "name"}, {"api_name": "maya.cmds.getPanel", "line_number": 811, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 811, "usage_type": "name"}, {"api_name": "maya.cmds.getPanel", "line_number": 812, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 812, "usage_type": "name"}, {"api_name": "maya.cmds.modelPanel", "line_number": 814, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 814, "usage_type": "name"}, {"api_name": "maya.cmds.objectType", "line_number": 816, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 816, "usage_type": "name"}, {"api_name": "maya.cmds.nodeType", "line_number": 836, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 836, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 848, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 848, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 850, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 850, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 861, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 861, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 868, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 868, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 869, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 869, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 870, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 870, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 871, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 871, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 872, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 872, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 873, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 873, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 882, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 882, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 884, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 884, "usage_type": "name"}, {"api_name": "maya.cmds.createRenderLayer", "line_number": 885, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 885, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 886, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 886, "usage_type": "name"}, {"api_name": "maya.cmds.editRenderLayerGlobals", "line_number": 889, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 889, "usage_type": "name"}, {"api_name": "maya.cmds.getPanel", "line_number": 891, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 891, "usage_type": "name"}, {"api_name": "maya.cmds.modelPanel", "line_number": 892, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 892, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 894, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 894, "usage_type": "name"}, {"api_name": "maya.cmds.modelPanel", "line_number": 895, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 895, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 896, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 896, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 897, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 897, "usage_type": "name"}, {"api_name": "maya.cmds.editRenderLayerGlobals", "line_number": 899, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 899, "usage_type": "name"}, {"api_name": "maya.cmds.setFocus", "line_number": 905, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 905, "usage_type": "name"}, {"api_name": "maya.cmds.currentTime", "line_number": 906, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 906, "usage_type": "name"}, {"api_name": "maya.cmds.currentTime", "line_number": 907, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 907, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 908, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 908, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 916, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 916, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 921, "usage_type": "call"}, {"api_name": "os.path", "line_number": 921, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 922, "usage_type": "call"}, {"api_name": "os.path", "line_number": 922, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 924, "usage_type": "call"}, {"api_name": "os.path", "line_number": 924, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 925, "usage_type": "call"}, {"api_name": "shutil.copytree", "line_number": 926, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 927, "usage_type": "call"}, {"api_name": "maya.cmds.modelPanel", "line_number": 930, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 930, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 931, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 931, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 932, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 932, "usage_type": "name"}, {"api_name": "maya.cmds.editRenderLayerGlobals", "line_number": 933, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 933, "usage_type": "name"}, {"api_name": "maya.cmds.delete", "line_number": 934, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 934, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 952, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 952, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 955, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 955, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 956, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 956, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 958, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 958, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 959, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 959, "usage_type": "name"}, {"api_name": "shutil.copyfile", "line_number": 989, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 989, "usage_type": "call"}, {"api_name": "os.path", "line_number": 989, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 991, "usage_type": "call"}, {"api_name": "maya.cmds.select", "line_number": 998, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 998, "usage_type": "name"}, {"api_name": "shutil.copyfile", "line_number": 1010, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1010, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1010, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 1023, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1023, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 1027, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1027, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 1028, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1028, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 1030, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1030, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 1031, "usage_type": "call"}, {"api_name": "shutil.copytree", "line_number": 1032, "usage_type": "call"}, {"api_name": "maya.cmds.objExists", "line_number": 1046, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1046, "usage_type": "name"}, {"api_name": "maya.cmds.findKeyframe", "line_number": 1047, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1047, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 1074, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1074, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 1075, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1075, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 1078, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1078, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 1080, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1080, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 1083, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1083, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 1092, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1092, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 1100, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1100, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 1108, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1108, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 1109, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1109, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 1117, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1117, "usage_type": "name"}, {"api_name": "maya.cmds.referenceQuery", "line_number": 1121, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1121, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 1127, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1127, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 1129, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1129, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 1137, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1137, "usage_type": "name"}, {"api_name": "maya.cmds.referenceQuery", "line_number": 1141, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1141, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 1147, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1147, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 1149, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1149, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 1157, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1157, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 1164, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1164, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 1165, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1165, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 1169, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 1169, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 1171, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1171, "usage_type": "name"}, {"api_name": "maya.cmds.file", "line_number": 1173, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1173, "usage_type": "name"}, {"api_name": "time.time", "line_number": 1181, "usage_type": "call"}, {"api_name": "maya.cmds.file", "line_number": 1189, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1189, "usage_type": "name"}, {"api_name": "maya.cmds.objExists", "line_number": 1208, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1208, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 1209, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1209, "usage_type": "name"}, {"api_name": "time.time", "line_number": 1212, "usage_type": "call"}, {"api_name": "maya.cmds.file", "line_number": 1225, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1225, "usage_type": "name"}, {"api_name": "maya.cmds.objExists", "line_number": 1233, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1233, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 1249, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1249, "usage_type": "name"}, {"api_name": "maya.cmds.listRelatives", "line_number": 1251, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1251, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 1257, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1257, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 1267, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1267, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 1269, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1269, "usage_type": "name"}, {"api_name": "time.time", "line_number": 1277, "usage_type": "call"}, {"api_name": "maya.mel.eval", "line_number": 1299, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 1299, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 1300, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 1300, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 1302, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1302, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 1303, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1303, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1303, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 1308, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 1311, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1311, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 1316, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1316, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 1317, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1317, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 1321, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1321, "usage_type": "attribute"}, {"api_name": "maya.cmds.file", "line_number": 1322, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1322, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 1331, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1331, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 1335, "usage_type": "call"}, {"api_name": "maya.cmds.ls", "line_number": 1346, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1346, "usage_type": "name"}, {"api_name": "maya.cmds.listRelatives", "line_number": 1348, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1348, "usage_type": "name"}, {"api_name": "maya.cmds.lookThru", "line_number": 1353, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 1353, "usage_type": "name"}]} +{"seq_id": "41362312021", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 13 16:41:50 2017\n\n@author: James\n\"\"\"\n\nfrom sqlalchemy import create_engine\n\nimport pandas as pd\n\nengine = create_engine('sqlite:///Chinook.sqlite')\n\ndf = pd.read_sql_query(\"SELECT * FROM Customer\", engine)\n\n#Hello world of SQL Queries\n# Execute query and store records in DataFrame: df\ndf = pd.read_sql_query('SELECT * FROM Album', engine)\n\n# Print head of DataFrame\nprint(df.head())\n\n# Open engine in context manager\n# Perform query and save results to DataFrame: df1\nwith engine.connect() as con:\n rs = con.execute(\"SELECT * FROM Album\")\n df1 = pd.DataFrame(rs.fetchall())\n df1.columns = rs.keys()\n\n# Confirm that both methods yield the same result: does df = df1 ?\nprint(df.equals(df1))\n\n#Complex query\n# Execute query and store records in DataFrame: df\ndf = pd.read_sql_query('SELECT * FROM Employee WHERE EmployeeID >= 6 ORDER BY BirthDate', engine)\n\n# Print head of DataFrame\nprint(df.head())\n\n#inner join\n# Open engine in context manager\n# Perform query and save results to DataFrame: df\nwith engine.connect() as con:\n rs = con.execute('SELECT Title, Name FROM Album INNER JOIN Artist on Album.ArtistID=Artist.ArtistID')\n df = pd.DataFrame(rs.fetchall())\n df.columns = rs.keys()\n\n# Print head of DataFrame df\nprint(df.head())", "repo_name": "jameschenmech/GettingData", "sub_path": "pandas_sql_query.py", "file_name": "pandas_sql_query.py", "file_ext": "py", "file_size_in_byte": 1297, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sqlalchemy.create_engine", "line_number": 12, "usage_type": "call"}, {"api_name": "pandas.read_sql_query", "line_number": 14, "usage_type": "call"}, {"api_name": "pandas.read_sql_query", "line_number": 18, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 27, "usage_type": "call"}, {"api_name": "pandas.read_sql_query", "line_number": 35, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 45, "usage_type": "call"}]} +{"seq_id": "21420976247", "text": "from typing import List, Tuple\n\ntask_file=open('taskfiles/task2.txt', 'r')\npackages: List[Tuple[int, int, int]] = [ ]\ntotal_wrap=0\ntotal_ribbon=0\n\nfor line in task_file:\n pkg = line.rstrip()\n # print(pkg.split('x'))\n packages.append(pkg.split('x'))\n\n\ndef package_wrap(l=0, w=0, h=0):\n l=int(l)\n w=int(w)\n h=int(h)\n area = (2*l*w + 2*w*h + 2*h*l)\n# print(\"Area of the thing is {0}\".format(area))\n sides = []\n sides.append(int(l*w))\n sides.append(int(l*h))\n sides.append(int(w*h))\n# print(\"Smallest side is {0}\".format(min(sides)))\n# print(\"Total sqft needed for package is: {0}\".format(area+min(sides)))\n return(area+min(sides))\n\n\n\ndef package_ribbon(l=0, w=0, h=0):\n l=int(l)\n w=int(w)\n h=int(h)\n sides = []\n sides.append(int(l))\n sides.append(int(h))\n sides.append(int(w))\n# biggest=max(sides)\n sides.remove(max(sides))\n return( 2*sides[0] + 2*sides[1] + l*w*h )\n# print(\"Popping {0} from line and now left with {1}\".format(biggest,sides))\n# length=( 2*sides[0] + 2*sides[1] + l*w*h )\n# print(\"Ribbonlength is {0}\".format(length))\n# return(length)\n\n\n\nfor dims in packages:\n total_wrap+=package_wrap(*dims)\n total_ribbon+=package_ribbon(*dims)\nprint(\"Wrapping paper needed is: {0}, and ribbon needed is: {1}\".format(total_wrap, total_ribbon))", "repo_name": "benprov718/AdventOfCode2015", "sub_path": "day02a.py", "file_name": "day02a.py", "file_ext": "py", "file_size_in_byte": 1338, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.List", "line_number": 4, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 4, "usage_type": "name"}]} +{"seq_id": "21628420817", "text": "import logging\nimport multiprocessing\nimport time\nfrom multiprocessing import (Array, Barrier, Condition, Event, Lock, Manager,\n Pipe, Process, Queue, RLock, Semaphore, Value)\n\nlogging.basicConfig(\n level=logging.DEBUG, format=\"%(processName)s >> %(message)s\"\n)\n\n\ndef worker_thread_1(num: int) -> None:\n logging.debug('start')\n print(num)\n time.sleep(10)\n logging.debug(\"end\")\n\n\ndef worker_thread_2(num: int) -> None:\n logging.debug('start')\n print(num)\n logging.debug(\"end\")\n\n\nif __name__ == \"__main__\":\n \"\"\"\n execute flow:\n\n t1(start) -> t2(start) -> t1(end) -> t2(end)\n \"\"\"\n i = 10\n\n t1 = multiprocessing.Process(target=worker_thread_1, args=(i,))\n t1.daemon = True\n t2 = multiprocessing.Process(target=worker_thread_2,\n name=\"unknown_process\", args=(i,))\n\n for t in (t1, t2):\n t.start()\n t.join() # twait until exit\n", "repo_name": "zkfmapf123/parallelization", "sub_path": "multi-process/multi-process.py", "file_name": "multi-process.py", "file_ext": "py", "file_size_in_byte": 954, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "logging.basicConfig", "line_number": 7, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 8, "usage_type": "attribute"}, {"api_name": "logging.debug", "line_number": 13, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 15, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 16, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 20, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 22, "usage_type": "call"}, {"api_name": "multiprocessing.Process", "line_number": 33, "usage_type": "call"}, {"api_name": "multiprocessing.Process", "line_number": 35, "usage_type": "call"}]} +{"seq_id": "21545057879", "text": "from collections import defaultdict\nimport heapq\n\n\nclass Graph:\n ''' data structure to store weighted directed graph in the form of \n adjecency list\n '''\n def __init__(self): \n self.edges = defaultdict(list)\n self.distances = {}\n\n def add_edge(self, from_node, to_node, distance):\n \"adds weighted directed edges to the graph\"\n self.edges[from_node].append(to_node)\n self.distances[(from_node, to_node)] = distance\n\n\n def dijkstra(self, start, end):\n ''' Returns min distance if there exists a shortest path \n from start to end; Otherwise, return None '''\n\n if start == end:\n return float(0)\n Q = [] # priority queue of items; note item is mutable.\n d = {start: 0} # vertex -> minimal distance\n Qd = {} # vertex -> [d[v], parent_v, v]\n previous = {} # previous vertex \n visited_set = set([start])\n\n adj = self.edges # adjecency list\n distances = self.distances # distances or costs\n\n # initialize for the starting vertex\n for neighbour in adj.get(start, []):\n distance = distances[start, neighbour]\n item = [distance, start, neighbour]\n d[neighbour] = distance\n heapq.heappush(Q, item)\n Qd[neighbour] = item\n \n while Q:\n distance, parent, cur = heapq.heappop(Q)\n if cur not in visited_set: # for vertices not visited\n previous[cur] = parent\n visited_set.add(cur)\n if cur == end: # found destination\n return d[cur]\n for v in adj.get(cur, []):\n if d.get(v):\n if d[v] > distances[cur, v] + d[cur]:\n d[v] = distances[cur, v] + d[cur]\n Qd[v][0] = d[v] # decrease key\n Qd[v][1] = cur # update previous\n heapq._siftdown(Q, 0, Q.index(Qd[v]))\n else:\n d[v] = distances[cur, v] + d[cur]\n item = [d[v], cur, v]\n heapq.heappush(Q, item)\n Qd[v] = item\n\n return None\n", "repo_name": "neel1104/cloud-cover-assignment", "sub_path": "Graph.py", "file_name": "Graph.py", "file_ext": "py", "file_size_in_byte": 2269, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "collections.defaultdict", "line_number": 10, "usage_type": "call"}, {"api_name": "heapq.heappush", "line_number": 39, "usage_type": "call"}, {"api_name": "heapq.heappop", "line_number": 43, "usage_type": "call"}, {"api_name": "heapq._siftdown", "line_number": 55, "usage_type": "call"}, {"api_name": "heapq.heappush", "line_number": 59, "usage_type": "call"}]} +{"seq_id": "4136017939", "text": "import unittest\nimport os\nimport subprocess\nimport requests\nimport threading\nfrom time import sleep\nimport json\n\nclass Runner(threading.Thread):\n\n def __init__(self):\n threading.Thread.__init__(self)\n self.process = None\n\n def run(self):\n print(\"Starting \" + self.name)\n e = os.environ.copy()\n e['DATABASE_URL'] = \"sqlite://test.db\"\n cmd = ['python', 'lopputili.py']\n self.process = p = subprocess.Popen(cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n env=e)\n for line in iter(p.stdout.readline, b''):\n print(\"-------> \" + str(line.rstrip()))\n print(\"Exiting \" + self.name)\n\n def stop(self):\n print(\"Trying to stop thread \")\n if self.process is not None:\n self.process.terminate()\n self.process = None\n\n\ntestDBpath = \"test.db\"\nheaders = {\"content-type\":\"application/json\"}\n\nserver_path = \"http://localhost:3000\"\n\nclass apiTest(unittest.TestCase):\n\t@classmethod\n\tdef setUpClass(cls):\n\t\tcls.sr = Runner()\n\t\tcls.sr.start()\n\t\tsleep(4)\n\t\tr = requests.post(server_path+'/login', data={\"username\":\"test\", \"password\":\"test\"})\n\t\tcls.auth_cookies = r.cookies\n\n\t@classmethod\n\tdef tearDownClass(cls):\n\t\tcls.sr.stop()\n\n\tdef test_is_server_up(self):\n\t\tr = requests.get(server_path+'/login')\n\t\tself.assertEqual(r.status_code, 200)\n\n\tdef test_if_cannot_access_without_credientials(self):\n\t\tr = requests.get(server_path+'/api/receipts')\n\t\tself.assertEqual(r.status_code, 403)\n\t\t\n\tdef test_object_not_found(self):\n\t\tr = requests.get(server_path+'/api/receipts/96', cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 404)\n\t\t\n\n\tdef test_receipts_crud(self):\n\t\tmodel = 'receipts'\n\t\tr = requests.get(server_path+'/api/'+model+'', cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tself.assertEqual(r.json(), {\"data\":[]})\n\t\tobj = {\n\t\t\t\"rid\":1001,\n\t\t\t\"owner\": 1,\n\t\t\t\"commit_date\": \"2015-02-11T11:46:30.670Z\",\n\t\t\t\"description\": \"Kuvaus kirjanpitotapahtumasta\"\n\t\t\t}\n\t\tr = requests.post(server_path+'/api/'+model+'', data=json.dumps(obj), headers=headers, cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 201)\n\t\tr = requests.get(server_path+'/api/'+model+'', cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tshouldbe = {'data': [{\n\t\t\t'commit_date': '2015-02-11T11:46:30.670000Z',\n 'description': 'Kuvaus kirjanpitotapahtumasta',\n 'owner': 1,\n 'pk': 1,\n 'rid': 1001\n }]}\n\t\tself.assertEqual(r.json(), shouldbe)\n\t\tr = requests.get(server_path+'/api/'+model+'/1', cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tself.assertEqual(r.json(), shouldbe['data'][0])\n\t\tshouldbe['data'][0]['description'] = \"Uusi kuvaus\"\n\t\tr = requests.put(server_path+'/api/'+model+'/1', cookies=self.auth_cookies, data=json.dumps(shouldbe['data'][0]), headers=headers)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tself.assertEqual(r.json(), shouldbe['data'][0])\n\t\tr = requests.get(server_path+'/api/'+model+'/1', cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tself.assertEqual(r.json(), shouldbe['data'][0])\n\t\tr = requests.delete(server_path+'/api/'+model+'/1', cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tr = requests.get(server_path+'/api/'+model+'', cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tself.assertEqual(r.json(), {\"data\":[]})\n\n\tdef test_wrong_data(self):\n\t\tobj = {\n\t\t\t\"address\":\"Vain osoite\"\n\t\t\t}\n\t\tr = requests.post(server_path+'/api/contacts', data=json.dumps(obj), headers=headers, cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 400)\n\n\tdef test_contacts_crud(self):\n\t\tmodel = 'contacts'\n\t\tr = requests.get(server_path+'/api/'+model+'', cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tself.assertEqual(r.json(), {\"data\":[]})\n\t\tobj = {\n\t\t\t\"name\":\"Testi Yhteystieto\"\n\t\t\t}\n\t\tr = requests.post(server_path+'/api/'+model+'', data=json.dumps(obj), headers=headers, cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 201)\n\t\tr = requests.get(server_path+'/api/'+model+'', cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tshouldbe = {'data': [{\n\t\t\t'pk': 1,\n\t\t\t'owner': 1,\n\t\t\t'name': \"Testi Yhteystieto\",\n\t\t\t'address': None,\n\t\t\t'zip_code': None,\n\t\t\t'city': None,\n\t\t\t'email': None\n }]}\n\t\tself.assertEqual(r.json(), shouldbe)\n\t\tr = requests.get(server_path+'/api/'+model+'/1', cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tself.assertEqual(r.json(), shouldbe['data'][0])\n\t\tshouldbe['data'][0]['address'] = \"Osoite 12\"\n\t\tr = requests.put(server_path+'/api/'+model+'/1', cookies=self.auth_cookies, data=json.dumps(shouldbe['data'][0]), headers=headers)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tself.assertEqual(r.json(), shouldbe['data'][0])\n\t\tr = requests.get(server_path+'/api/'+model+'/1', cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tself.assertEqual(r.json(), shouldbe['data'][0])\n\t\tr = requests.delete(server_path+'/api/'+model+'/1', cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tr = requests.get(server_path+'/api/'+model+'', cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tself.assertEqual(r.json(), {\"data\":[]})\n\n\n\n\tdef test_is_accounts_empty(self):\n\t\tr = requests.get(server_path+'/api/accounts', cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tself.assertEqual(r.json(), {\"data\":[]})\n\n\tdef test_is_commits_empty(self):\n\t\tr = requests.get(server_path+'/api/commits', cookies=self.auth_cookies)\n\t\tself.assertEqual(r.status_code, 200)\n\t\tself.assertEqual(r.json(), {\"data\":[]})\n\nif __name__ == '__main__':\n\tunittest.main()", "repo_name": "theikkila/lopputili", "sub_path": "tests/test_api.py", "file_name": "test_api.py", "file_ext": "py", "file_size_in_byte": 5742, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "threading.Thread", "line_number": 9, "usage_type": "attribute"}, {"api_name": "threading.Thread.__init__", "line_number": 12, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 12, "usage_type": "attribute"}, {"api_name": "os.environ.copy", "line_number": 17, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 17, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 20, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 21, "usage_type": "attribute"}, {"api_name": "subprocess.STDOUT", "line_number": 22, "usage_type": "attribute"}, {"api_name": "unittest.TestCase", "line_number": 40, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 45, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 46, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 54, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 58, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 62, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 68, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 77, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 77, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 79, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 89, "usage_type": "call"}, {"api_name": "requests.put", "line_number": 93, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 93, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 96, "usage_type": "call"}, {"api_name": "requests.delete", "line_number": 99, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 101, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 109, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 109, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 114, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 120, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 120, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 122, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 134, "usage_type": "call"}, {"api_name": "requests.put", "line_number": 138, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 138, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 141, "usage_type": "call"}, {"api_name": "requests.delete", "line_number": 144, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 146, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 153, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 158, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 163, "usage_type": "call"}]} +{"seq_id": "73232077186", "text": "import sys\n\nfrom django.contrib.auth.models import User\nfrom django.db.models import Sum, F\nfrom django.db.models.functions import Coalesce\nfrom django.utils import timezone\nfrom rest_framework import serializers\nfrom rest_framework.exceptions import ValidationError\n\nfrom puntos_venta.models import PuntoVenta, PuntoVentaTurno\nfrom contabilidad_cuentas.models import CuentaContable\n\n\ndef punto_venta_crear_actualizar(\n tipo: int,\n nombre: str,\n bodega_id: int = None,\n cuenta_contable_caja_id: int = None,\n punto_venta_id: int = None,\n) -> PuntoVenta:\n if punto_venta_id is not None:\n punto_venta = PuntoVenta.objects.get(pk=punto_venta_id)\n else:\n punto_venta = PuntoVenta()\n punto_venta.bodega_id = bodega_id\n cuenta_contable_caja = CuentaContable.objects.get(pk=cuenta_contable_caja_id)\n if cuenta_contable_caja.tipo != 'D':\n raise ValidationError(\n {'_error': 'La cuenta contable de la caja debería ser de tipo detalle y no lo es y no lo es'})\n if cuenta_contable_caja.naturaleza != 'D':\n raise ValidationError({'_error': 'La cuenta contable de la caja debería ser de naturaleza débito y no lo es'})\n punto_venta.cuenta_contable_caja_id = cuenta_contable_caja_id\n punto_venta.nombre = nombre\n punto_venta.tipo = tipo\n punto_venta.save()\n return punto_venta\n\n\ndef punto_venta_set_operacion_caja_en_cierre(\n punto_venta_id: int,\n concepto_operacion_caja_id: int,\n en_cierre: bool\n) -> PuntoVenta:\n from cajas.models import ConceptoOperacionCaja\n punto_venta = PuntoVenta.objects.get(pk=punto_venta_id)\n concepto_operacion_caja = ConceptoOperacionCaja(pk=concepto_operacion_caja_id)\n conceptos_operaciones_caja = punto_venta.conceptos_operaciones_caja_punto_venta.filter(\n concepto_operacion_caja_id=concepto_operacion_caja_id)\n if not conceptos_operaciones_caja.exists():\n raise ValidationError({\n '_error': 'Este puento de venta no tiene relacionado el concepto de cierre de caja %s' % concepto_operacion_caja.descripcion})\n concepto = conceptos_operaciones_caja.first()\n concepto.para_cierre_caja = en_cierre\n concepto.save()\n return PuntoVenta.objects.get(pk=punto_venta_id)\n\n\ndef punto_venta_set_metodo_pago_activo(\n punto_venta_id: int,\n metodo_pago_id: int,\n activo: bool\n) -> PuntoVenta:\n from contabilidad_metodos_pago.models import MetodoPago\n punto_venta = PuntoVenta.objects.get(pk=punto_venta_id)\n metodo_pago = MetodoPago(pk=metodo_pago_id)\n metodos_pago_punto_venta = punto_venta.metodos_pagos_punto_venta.filter(\n metodo_pago_id=metodo_pago_id)\n if not metodos_pago_punto_venta.exists():\n raise ValidationError({\n '_error': 'Este puento de venta no tiene relacionado el método de pago %s %s' % (\n metodo_pago.tipo, metodo_pago.nombre)})\n concepto = metodos_pago_punto_venta.first()\n concepto.activo = activo\n concepto.save()\n return PuntoVenta.objects.get(pk=punto_venta_id)\n\n\ndef punto_venta_relacionar_concepto_operacion_caja(\n punto_venta_id: int,\n concepto_operacion_caja_id: int\n) -> PuntoVenta:\n from cajas.models import ConceptoOperacionCaja\n from cajas.models import ConceptoOperacionCajaPuntoVenta\n punto_venta = PuntoVenta.objects.get(pk=punto_venta_id)\n existe_concepto = punto_venta.conceptos_operaciones_caja.filter(pk=concepto_operacion_caja_id).exists()\n concepto_operacion_caja = ConceptoOperacionCaja.objects.get(pk=concepto_operacion_caja_id)\n if not existe_concepto:\n ConceptoOperacionCajaPuntoVenta.objects.create(\n punto_venta_id=punto_venta_id,\n concepto_operacion_caja_id=concepto_operacion_caja_id,\n para_cierre_caja=False\n )\n else:\n raise serializers.ValidationError(\n {'_error': 'Este punto de venta ya tiene asociado el concepto %s' % concepto_operacion_caja.descripcion})\n return PuntoVenta.objects.get(pk=punto_venta_id)\n\n\ndef punto_venta_quitar_concepto_operacion_caja(\n punto_venta_id: int,\n concepto_operacion_caja_id: int\n) -> PuntoVenta:\n from cajas.models import ConceptoOperacionCaja\n punto_venta = PuntoVenta.objects.get(pk=punto_venta_id)\n concepto_operacion_caja = ConceptoOperacionCaja.objects.get(pk=concepto_operacion_caja_id)\n conceptos_punto_venta = punto_venta.conceptos_operaciones_caja_punto_venta.filter(\n concepto_operacion_caja_id=concepto_operacion_caja_id)\n if conceptos_punto_venta.exists():\n conceptos_punto_venta.delete()\n else:\n raise serializers.ValidationError(\n {'_error': 'Este punto de venta no tiene asociado el concepto %s' % concepto_operacion_caja.descripcion})\n return PuntoVenta.objects.get(pk=punto_venta_id)\n\n\ndef punto_venta_relacionar_metodo_pago(\n punto_venta_id: int,\n metodo_pago_id: int\n) -> PuntoVenta:\n from contabilidad_metodos_pago.models import MetodoPagoPuntoVenta, MetodoPago\n punto_venta = PuntoVenta.objects.get(pk=punto_venta_id)\n existe_concepto = punto_venta.metodos_pago.filter(pk=metodo_pago_id)\n metodo_pago = MetodoPago.objects.get(pk=metodo_pago_id)\n if not existe_concepto:\n MetodoPagoPuntoVenta.objects.create(\n punto_venta_id=punto_venta_id,\n metodo_pago_id=metodo_pago_id,\n activo=True\n )\n else:\n raise serializers.ValidationError(\n {'_error': 'Este punto de venta ya tiene asociado el método de pago %s %s' % (\n metodo_pago.tipo, metodo_pago.nombre)})\n return PuntoVenta.objects.get(pk=punto_venta_id)\n\n\ndef punto_venta_quitar_metodo_pago(\n punto_venta_id: int,\n metodo_pago_id: int\n) -> PuntoVenta:\n from contabilidad_metodos_pago.models import MetodoPago\n punto_venta = PuntoVenta.objects.get(pk=punto_venta_id)\n metodo_pago = MetodoPago.objects.get(pk=metodo_pago_id)\n metodos_pago_punto_venta = punto_venta.metodos_pagos_punto_venta.filter(\n metodo_pago_id=metodo_pago_id)\n if metodos_pago_punto_venta.exists():\n metodos_pago_punto_venta.delete()\n else:\n raise serializers.ValidationError(\n {'_error': 'Este punto de venta no tiene asociado el método de pago %s %s' % (\n metodo_pago.tipo, metodo_pago.nombre)})\n return PuntoVenta.objects.get(pk=punto_venta_id)\n\n\ndef punto_venta_abrir(\n usuario_pv_id: int,\n base_inicial_efectivo: float,\n punto_venta_id: int,\n) -> [PuntoVenta, PuntoVentaTurno]:\n punto_venta = PuntoVenta.objects.get(pk=punto_venta_id)\n usuario = User.objects.get(pk=usuario_pv_id)\n if punto_venta.abierto and usuario != punto_venta.usuario_actual:\n raise serializers.ValidationError({'_error': 'Este punto de venta ya esta abierto'})\n if punto_venta.usuario_actual and punto_venta.usuario_actual.id != usuario_pv_id:\n raise serializers.ValidationError(\n {'_error': 'Este punto de venta ya esta abierto por %s' % punto_venta.usuario_actual.username})\n if not hasattr(usuario, 'tercero'):\n raise serializers.ValidationError({'_error': 'No se puede abrir un punto de venta a un usuario sin tercero'})\n if not usuario.tercero.es_colaborador:\n raise serializers.ValidationError(\n {'_error': 'No se puede abrir un punto de venta a alguien que no sea colaborador'}\n )\n if not usuario.tercero.presente:\n raise serializers.ValidationError(\n {'_error': 'No se puede abrir un punto de venta a un colaborador que no este presente'}\n )\n # TODO: Validar si esta en la lista de los colaboradores validos para este punto venta\n\n punto_venta_turno = usuario.tercero.turno_punto_venta_abierto\n if punto_venta_turno and punto_venta_turno.punto_venta != punto_venta:\n raise serializers.ValidationError(\n {\n '_error': 'Este usuario ya tiene un turno abierto y debe cerrarlo primero antes de abrir otro turno. El turno esta abierto en el punto de venta %s' % punto_venta_turno.punto_venta.nombre}\n )\n if not punto_venta_turno:\n if hasattr(usuario, 'tercero'):\n punto_venta_turno_anterior = PuntoVentaTurno.objects.filter(usuario=usuario).last()\n punto_venta_turno = PuntoVentaTurno.objects.create(\n usuario=usuario,\n punto_venta=punto_venta,\n diferencia_cierre_caja_anterior=punto_venta_turno_anterior.diferencia_cierre_caja if punto_venta_turno_anterior else 0,\n turno_anterior=punto_venta_turno_anterior,\n base_inicial_efectivo=base_inicial_efectivo\n )\n if base_inicial_efectivo > 0:\n from cajas.services import transaccion_caja_registrar_ingreso_base_inicial_apertura_caja\n transaccion_caja_registrar_ingreso_base_inicial_apertura_caja(\n punto_venta_turno_id=punto_venta_turno.id,\n valor_efectivo=base_inicial_efectivo\n )\n\n punto_venta.abierto = True\n punto_venta.usuario_actual = User.objects.get(pk=usuario_pv_id)\n punto_venta.save()\n return punto_venta, punto_venta_turno\n\n\nfrom cajas.models import ArqueoCaja\n\n\ndef punto_venta_cerrar(\n usuario_pv_id: int,\n entrega_efectivo_dict: dict,\n operaciones_caja_dict,\n entrega_base_dict: dict,\n valor_tarjeta: float,\n nro_vauchers: int,\n valor_dolares: float,\n tasa_dolar: float,\n) -> [PuntoVenta, ArqueoCaja]:\n usuario = User.objects.get(pk=usuario_pv_id)\n if hasattr(usuario, 'tercero'):\n tercero = usuario.tercero\n punto_venta_turno = tercero.turno_punto_venta_abierto\n if punto_venta_turno:\n from cajas.models import (\n ArqueoCaja,\n EfectivoEntregaDenominacion,\n BaseDisponibleDenominacion\n )\n from cajas.services import (\n transaccion_caja_registrar_egreso_entrega_base_cierre_caja,\n transaccion_caja_registrar_egreso_entrega_efectivo_cierre_caja,\n operacion_caja_crear\n )\n\n from cajas.models import ConceptoOperacionCaja\n for operacion_caja in operaciones_caja_dict:\n id_concepto = int(operacion_caja.get('id'))\n concepto = ConceptoOperacionCaja.objects.get(pk=id_concepto)\n valor = float(operacion_caja.get('valor'))\n\n if valor > 0:\n operacion_caja_crear(\n concepto_id=id_concepto,\n usuario_pdv_id=usuario_pv_id,\n valor=valor,\n observacion='Desde cierre de caja'\n )\n\n # region Valores Transacciones\n transacciones_egresos = punto_venta_turno.transacciones_caja.filter(\n punto_venta_turno_id=punto_venta_turno.id,\n tipo='E'\n )\n transacciones_ingresos = punto_venta_turno.transacciones_caja.filter(\n punto_venta_turno_id=punto_venta_turno.id,\n tipo='I'\n )\n\n total_ingreso_efectivo = transacciones_ingresos.aggregate(\n total=Coalesce(Sum('valor_efectivo'), 0)\n )['total']\n\n total_ingreso_tarjeta = transacciones_ingresos.aggregate(\n total=Coalesce(Sum('valor_tarjeta'), 0)\n )['total']\n\n total_egreso_efectivo = -transacciones_egresos.aggregate(\n total=Coalesce(Sum('valor_efectivo'), 0)\n )['total']\n\n total_egreso_tarjeta = -transacciones_egresos.aggregate(\n total=Coalesce(Sum('valor_tarjeta'), 0)\n )['total']\n\n cantidad_ventas_tarjeta = transacciones_ingresos.aggregate(\n cantidad=Coalesce(Sum('nro_vauchers'), 0)\n )['cantidad']\n\n total_a_recibir_efectivo = total_ingreso_efectivo - total_egreso_efectivo\n total_a_recibir_tarjeta = total_ingreso_tarjeta - total_egreso_tarjeta\n\n # endregion\n arqueo = ArqueoCaja.objects.create(\n punto_venta_turno_id=punto_venta_turno.id,\n valor_pago_efectivo_a_entregar=total_a_recibir_efectivo,\n valor_pago_tarjeta_a_entregar=total_a_recibir_tarjeta,\n nro_voucher_a_entregar=cantidad_ventas_tarjeta,\n dolares_tasa=tasa_dolar,\n valor_dolares_entregados=valor_dolares,\n valor_tarjeta_entregados=valor_tarjeta,\n nro_voucher_entregados=nro_vauchers\n )\n\n for denominacion in entrega_efectivo_dict:\n cantidad = int(denominacion.get('cantidad'))\n valor = float(denominacion.get('valor'))\n valor_total = cantidad * valor\n if cantidad > 0:\n EfectivoEntregaDenominacion.objects.create(\n arqueo_caja=arqueo,\n valor_total=valor_total,\n **denominacion\n )\n for denominacion in entrega_base_dict:\n cantidad = int(denominacion.get('cantidad'))\n valor = float(denominacion.get('valor'))\n valor_total = cantidad * valor\n if cantidad > 0:\n BaseDisponibleDenominacion.objects.create(\n arqueo_caja=arqueo,\n valor_total=valor_total,\n **denominacion\n )\n\n if 'test' in sys.argv:\n print('-----------------DATOS ARQUEO CAJA-------------------------')\n print('Arqueo dinero entrega efectivo %s' % arqueo.valor_entrega_efectivo)\n print('Arqueo dinero entrega base efectivo %s' % arqueo.valor_base_dia_siguiente)\n print('Arqueo dinero entrega dolares %s' % arqueo.valor_dolares_en_pesos)\n print('Arqueo dinero entrega efectivo total %s' % arqueo.valor_entrega_efectivo_total)\n\n print('-----------------------------------------------------------')\n print('Valor ingresos totales %s' % (total_ingreso_efectivo + total_ingreso_tarjeta))\n print('Valor egresos totales %s' % (total_egreso_efectivo + total_egreso_tarjeta))\n print('Valor ingreso transacciones en efectivo %s' % total_ingreso_efectivo)\n print('Valor ingreso transacciones en tarjeta %s' % total_ingreso_tarjeta)\n print('Valor egresos transacciones en efectivo %s' % total_egreso_efectivo)\n print('Valor egresos transacciones en tarjeta %s' % total_egreso_tarjeta)\n print('Valor a recibir transacciones en efectivo %s' % total_a_recibir_efectivo)\n\n total_entrega_efectivo = arqueo.valor_entrega_efectivo_total\n\n transaccion_caja_registrar_egreso_entrega_efectivo_cierre_caja(\n punto_venta_turno_id=punto_venta_turno.id,\n valor_efectivo=total_entrega_efectivo\n )\n transaccion_caja_registrar_egreso_entrega_base_cierre_caja(\n punto_venta_turno_id=punto_venta_turno.id,\n valor_efectivo=arqueo.valor_base_dia_siguiente\n )\n\n total_entrega_tarjeta = arqueo.valor_tarjeta_entregados\n\n descuadre_efectivo = total_a_recibir_efectivo - total_entrega_efectivo\n descuadre_tarjeta = total_a_recibir_tarjeta - total_entrega_tarjeta\n\n if 'test' in sys.argv:\n print('-----------------------------------------------------------')\n print('Descuadre por efectivo %s' % descuadre_efectivo)\n print('Descuadre por tarjeta %s' % descuadre_tarjeta)\n\n punto_venta = punto_venta_turno.punto_venta\n punto_venta.abierto = False\n punto_venta.usuario_actual = None\n punto_venta.save()\n punto_venta_turno.finish = timezone.now()\n punto_venta_turno.saldo_cierre_caja = arqueo.diferencia\n punto_venta_turno.save()\n if 'test' in sys.argv:\n print('el saldo es %s' % punto_venta_turno.diferencia_cierre_caja)\n else:\n raise serializers.ValidationError(\n {'_error': 'Este tercero no posee ningún punto de venta abierto actualmente'}\n )\n else:\n raise serializers.ValidationError(\n {\n '_error': 'El usuario no tiene un tercero relacionado, por ende, no tiene ningún punto de venta que cerrar'}\n )\n return punto_venta, arqueo\n", "repo_name": "fagsoft1/dr_amor_app", "sub_path": "puntos_venta/services.py", "file_name": "services.py", "file_ext": "py", "file_size_in_byte": 16723, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "puntos_venta.models.PuntoVenta.objects.get", "line_number": 22, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects", "line_number": 22, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 22, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 24, "usage_type": "call"}, {"api_name": "contabilidad_cuentas.models.CuentaContable.objects.get", "line_number": 26, "usage_type": "call"}, {"api_name": "contabilidad_cuentas.models.CuentaContable.objects", "line_number": 26, "usage_type": "attribute"}, {"api_name": "contabilidad_cuentas.models.CuentaContable", "line_number": 26, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.ValidationError", "line_number": 28, "usage_type": "call"}, {"api_name": "rest_framework.exceptions.ValidationError", "line_number": 31, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 20, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta.objects.get", "line_number": 45, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects", "line_number": 45, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 45, "usage_type": "name"}, {"api_name": "cajas.models.ConceptoOperacionCaja", "line_number": 46, "usage_type": "call"}, {"api_name": "rest_framework.exceptions.ValidationError", "line_number": 50, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects.get", "line_number": 55, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects", "line_number": 55, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 55, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 43, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta.objects.get", "line_number": 64, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects", "line_number": 64, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 64, "usage_type": "name"}, {"api_name": "contabilidad_metodos_pago.models.MetodoPago", "line_number": 65, "usage_type": "call"}, {"api_name": "rest_framework.exceptions.ValidationError", "line_number": 69, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects.get", "line_number": 75, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects", "line_number": 75, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 75, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 62, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta.objects.get", "line_number": 84, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects", "line_number": 84, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 84, "usage_type": "name"}, {"api_name": "cajas.models.ConceptoOperacionCaja.objects.get", "line_number": 86, "usage_type": "call"}, {"api_name": "cajas.models.ConceptoOperacionCaja.objects", "line_number": 86, "usage_type": "attribute"}, {"api_name": "cajas.models.ConceptoOperacionCaja", "line_number": 86, "usage_type": "name"}, {"api_name": "cajas.models.ConceptoOperacionCajaPuntoVenta.objects.create", "line_number": 88, "usage_type": "call"}, {"api_name": "cajas.models.ConceptoOperacionCajaPuntoVenta.objects", "line_number": 88, "usage_type": "attribute"}, {"api_name": "cajas.models.ConceptoOperacionCajaPuntoVenta", "line_number": 88, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 94, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 94, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta.objects.get", "line_number": 96, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects", "line_number": 96, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 96, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 81, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta.objects.get", "line_number": 104, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects", "line_number": 104, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 104, "usage_type": "name"}, {"api_name": "cajas.models.ConceptoOperacionCaja.objects.get", "line_number": 105, "usage_type": "call"}, {"api_name": "cajas.models.ConceptoOperacionCaja.objects", "line_number": 105, "usage_type": "attribute"}, {"api_name": "cajas.models.ConceptoOperacionCaja", "line_number": 105, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 111, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 111, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta.objects.get", "line_number": 113, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects", "line_number": 113, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 113, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 102, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta.objects.get", "line_number": 121, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects", "line_number": 121, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 121, "usage_type": "name"}, {"api_name": "contabilidad_metodos_pago.models.MetodoPago.objects.get", "line_number": 123, "usage_type": "call"}, {"api_name": "contabilidad_metodos_pago.models.MetodoPago.objects", "line_number": 123, "usage_type": "attribute"}, {"api_name": "contabilidad_metodos_pago.models.MetodoPago", "line_number": 123, "usage_type": "name"}, {"api_name": "contabilidad_metodos_pago.models.MetodoPagoPuntoVenta.objects.create", "line_number": 125, "usage_type": "call"}, {"api_name": "contabilidad_metodos_pago.models.MetodoPagoPuntoVenta.objects", "line_number": 125, "usage_type": "attribute"}, {"api_name": "contabilidad_metodos_pago.models.MetodoPagoPuntoVenta", "line_number": 125, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 131, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 131, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta.objects.get", "line_number": 134, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects", "line_number": 134, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 134, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 119, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta.objects.get", "line_number": 142, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects", "line_number": 142, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 142, "usage_type": "name"}, {"api_name": "contabilidad_metodos_pago.models.MetodoPago.objects.get", "line_number": 143, "usage_type": "call"}, {"api_name": "contabilidad_metodos_pago.models.MetodoPago.objects", "line_number": 143, "usage_type": "attribute"}, {"api_name": "contabilidad_metodos_pago.models.MetodoPago", "line_number": 143, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 149, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 149, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta.objects.get", "line_number": 152, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects", "line_number": 152, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 152, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 140, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta.objects.get", "line_number": 160, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVenta.objects", "line_number": 160, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 160, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 161, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 161, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 161, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 163, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 163, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 165, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 165, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 168, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 168, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 170, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 170, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 174, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 174, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 181, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 181, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVentaTurno.objects.filter", "line_number": 187, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVentaTurno.objects", "line_number": 187, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVentaTurno", "line_number": 187, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVentaTurno.objects.create", "line_number": 188, "usage_type": "call"}, {"api_name": "puntos_venta.models.PuntoVentaTurno.objects", "line_number": 188, "usage_type": "attribute"}, {"api_name": "puntos_venta.models.PuntoVentaTurno", "line_number": 188, "usage_type": "name"}, {"api_name": "cajas.services.transaccion_caja_registrar_ingreso_base_inicial_apertura_caja", "line_number": 197, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 203, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 203, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 203, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 159, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVentaTurno", "line_number": 159, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 221, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 221, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 221, "usage_type": "name"}, {"api_name": "cajas.models.ConceptoOperacionCaja.objects.get", "line_number": 240, "usage_type": "call"}, {"api_name": "cajas.models.ConceptoOperacionCaja.objects", "line_number": 240, "usage_type": "attribute"}, {"api_name": "cajas.models.ConceptoOperacionCaja", "line_number": 240, "usage_type": "name"}, {"api_name": "cajas.services.operacion_caja_crear", "line_number": 244, "usage_type": "call"}, {"api_name": "django.db.models.functions.Coalesce", "line_number": 262, "usage_type": "call"}, {"api_name": "django.db.models.Sum", "line_number": 262, "usage_type": "call"}, {"api_name": "django.db.models.functions.Coalesce", "line_number": 266, "usage_type": "call"}, {"api_name": "django.db.models.Sum", "line_number": 266, "usage_type": "call"}, {"api_name": "django.db.models.functions.Coalesce", "line_number": 270, "usage_type": "call"}, {"api_name": "django.db.models.Sum", "line_number": 270, "usage_type": "call"}, {"api_name": "django.db.models.functions.Coalesce", "line_number": 274, "usage_type": "call"}, {"api_name": "django.db.models.Sum", "line_number": 274, "usage_type": "call"}, {"api_name": "django.db.models.functions.Coalesce", "line_number": 278, "usage_type": "call"}, {"api_name": "django.db.models.Sum", "line_number": 278, "usage_type": "call"}, {"api_name": "cajas.models.ArqueoCaja.objects.create", "line_number": 285, "usage_type": "call"}, {"api_name": "cajas.models.ArqueoCaja.objects", "line_number": 285, "usage_type": "attribute"}, {"api_name": "cajas.models.ArqueoCaja", "line_number": 285, "usage_type": "name"}, {"api_name": "cajas.models.EfectivoEntregaDenominacion.objects.create", "line_number": 301, "usage_type": "call"}, {"api_name": "cajas.models.EfectivoEntregaDenominacion.objects", "line_number": 301, "usage_type": "attribute"}, {"api_name": "cajas.models.EfectivoEntregaDenominacion", "line_number": 301, "usage_type": "name"}, {"api_name": "cajas.models.BaseDisponibleDenominacion.objects.create", "line_number": 311, "usage_type": "call"}, {"api_name": "cajas.models.BaseDisponibleDenominacion.objects", "line_number": 311, "usage_type": "attribute"}, {"api_name": "cajas.models.BaseDisponibleDenominacion", "line_number": 311, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 317, "usage_type": "attribute"}, {"api_name": "cajas.services.transaccion_caja_registrar_egreso_entrega_efectivo_cierre_caja", "line_number": 335, "usage_type": "call"}, {"api_name": "cajas.services.transaccion_caja_registrar_egreso_entrega_base_cierre_caja", "line_number": 339, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 349, "usage_type": "attribute"}, {"api_name": "django.utils.timezone.now", "line_number": 358, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 358, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 361, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 364, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 364, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 368, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 368, "usage_type": "name"}, {"api_name": "puntos_venta.models.PuntoVenta", "line_number": 220, "usage_type": "name"}, {"api_name": "cajas.models.ArqueoCaja", "line_number": 220, "usage_type": "name"}]} +{"seq_id": "38714577366", "text": "from cartola import fs\nimport unittest\nimport firenado.conf\nfrom importlib import reload\nfrom tests import chdir_app\nimport logging\nimport os\n\n\nclass ApplicationComponentTestCase(unittest.TestCase):\n \"\"\" Case that tests an Firenado application after being loaded from its\n configuration file.\n \"\"\"\n\n def test_conf_root(self):\n \"\"\" Test if Firenado root matches the upper directory relative to the\n current one. \"\"\"\n current_path = os.path.dirname(os.path.realpath(__file__))\n firenado_root = (\"%s\" % os.sep).join(current_path.split(os.sep)[:-1])\n firenado_root = os.path.join(firenado_root, \"firenado\")\n self.assertEqual(firenado_root, firenado.conf.ROOT)\n\n def test_firenado_config_file_default_value(self):\n \"\"\" Test if the default Firenado config file value will be \"firenado\".\n \"\"\"\n self.assertEqual(\"firenado\", firenado.conf.FIRENADO_CONFIG_FILE)\n\n def test_firenado_config_file_custom_value(self):\n \"\"\" Test if Firenado config file value will be changed setting\n FIRENADO_CONFIG_FILE env variable.\n \"\"\"\n custom_file_name = \"custom_file\"\n os.environ['FIRENADO_CONFIG_FILE'] = custom_file_name\n reload(firenado.conf)\n self.assertEqual(firenado.conf.FIRENADO_CONFIG_FILE, custom_file_name)\n del os.environ['FIRENADO_CONFIG_FILE']\n reload(firenado.conf)\n\n def test_system_config_path_default_value(self):\n \"\"\" Test if the default system config path is /etc/firenado\n \"\"\"\n self.assertEqual(firenado.conf.SYS_CONFIG_PATH, \"/etc/firenado\")\n\n def test_system_config_path_custom_value(self):\n \"\"\" Test if the default system config path will be changed setting the\n FIRENADO_SYS_CONFIG_PATH env variable\n \"\"\"\n custom_sys_config_path = \"/etc/anotherplace\"\n os.environ['FIRENADO_SYS_CONFIG_PATH'] = custom_sys_config_path\n reload(firenado.conf)\n self.assertEqual(firenado.conf.SYS_CONFIG_PATH, custom_sys_config_path)\n del os.environ['FIRENADO_SYS_CONFIG_PATH']\n reload(firenado.conf)\n\n def test_only_framework_stack(self):\n \"\"\" Tests is only the framework config stack was loaded.\n No app config is provided.\n \"\"\"\n self.assertEqual(firenado.conf.stack[0],\n firenado.conf.LIB_CONFIG_FILE)\n\n def test_app_stack(self):\n \"\"\" Application config is provided. Test if the app config file was\n loaded.\n \"\"\"\n chdir_app(\"yml\", \"conf\")\n self.assertEqual(firenado.conf.stack[0],\n firenado.conf.LIB_CONFIG_FILE)\n self.assertEqual(firenado.conf.stack[1],\n firenado.conf.APP_CONFIG_FILE)\n\n def test_sys_stack(self):\n \"\"\" System config path is provided. Test if the system config file was\n loaded.\n \"\"\"\n os.environ['FIRENADO_SYS_CONFIG_PATH'] = os.path.join(\n os.path.dirname(__file__), \"resources\", \"conf\", \"sys_config\")\n reload(firenado.conf)\n self.assertEqual(firenado.conf.stack[0],\n firenado.conf.LIB_CONFIG_FILE)\n self.assertEqual(firenado.conf.stack[1],\n firenado.conf.SYS_CONFIG_FILE)\n self.assertEqual(\"%(asctime)s - %(message)s\",\n firenado.conf.log['format'])\n self.assertEqual(logging.DEBUG, firenado.conf.log['level'])\n del os.environ['FIRENADO_SYS_CONFIG_PATH']\n reload(firenado.conf)\n\n def test_app_addresses_default(self):\n \"\"\" If no addresses are provided to the application we default to\n ipv4 and ipv6 loopbacks.\n \"\"\"\n # There is no addresses configured into the conf/yml firenado.yml\n chdir_app(\"yml\", \"conf\")\n self.assertTrue(firenado.conf.app['socket'] is None)\n self.assertEqual(len(firenado.conf.app['addresses']), 2)\n self.assertEqual(firenado.conf.app['addresses'][0], \"::\")\n self.assertEqual(firenado.conf.app['addresses'][1], \"0.0.0.0\")\n\n def test_app_addresses_from_conf(self):\n \"\"\" Getting localhost defined into the configuration.\n \"\"\"\n # At the conf/root_url app.addresses has only localhost\n chdir_app(\"root_url\", \"conf\")\n self.assertTrue(firenado.conf.app['socket'] is None)\n self.assertEqual(len(firenado.conf.app['addresses']), 1)\n self.assertEqual(firenado.conf.app['addresses'][0], \"localhost\")\n\n def test_app_port(self):\n \"\"\" Checks if the app port is set correctly.\n \"\"\"\n # Loading file from test/resources/session/file/conf/firenado.yml\n chdir_app(\"file\", \"session\")\n self.assertTrue(firenado.conf.app['socket'] is None)\n self.assertEqual(firenado.conf.app['port'], 8887)\n\n def test_app_pythonpath(self):\n \"\"\" Checks if the pythonpath is set on the application config file.\n \"\"\"\n chdir_app(\"file\", \"session\")\n self.assertEqual(firenado.conf.app['pythonpath'], \"..\")\n\n def test_yml_loaded(self):\n \"\"\" On an application with a yml and yaml config files the yml should\n be loaded.\n \"\"\"\n chdir_app(\"yml\", \"conf\")\n self.assertEqual(\"yml\", fs.get_file_extension(\n firenado.conf.APP_CONFIG_FILE))\n\n def test_settings_empty(self):\n \"\"\" If no app settings is defined an empty dict is set.\n \"\"\"\n chdir_app(\"yml\", \"conf\")\n self.assertDictEqual({}, firenado.conf.app['settings'])\n\n def test_settings(self):\n \"\"\" If no app settings is defined an empty dict is set.\n \"\"\"\n chdir_app(\"settings\", \"conf\")\n settings_dict = {\n 'cookie_secret': \"cookie---secret\",\n 'debug': True,\n 'xsrf_cookies': True\n }\n self.assertDictEqual(settings_dict, firenado.conf.app['settings'])\n\n def test_static_path(self):\n \"\"\" If static path is defined on the app configuration.\n \"\"\"\n chdir_app(\"yml\", \"conf\")\n self.assertEqual(\"yml_static_path\", firenado.conf.app['static_path'])\n\n def test_root_url(self):\n \"\"\" Test if the root path was set on the app configuration.\n \"\"\"\n chdir_app(\"root_url\", \"conf\")\n self.assertEqual(\"a_root_url\", firenado.conf.app['url_root_path'])\n\n def test_root_url_slash_in_front(self):\n \"\"\" Test if the root path with a slash in the front will be returned\n without it was set on the app configuration.\n \"\"\"\n chdir_app(\"root_url_slash_in_front\", \"conf\")\n self.assertEqual(\"a_root_url\", firenado.conf.app['url_root_path'])\n\n def test_root_url_slash_none(self):\n \"\"\" Test if the root path with a slash in the front will be returned\n without it was set on the app configuration.\n \"\"\"\n chdir_app(\"root_url_slash_none\", \"conf\")\n self.assertEqual(None, firenado.conf.app['url_root_path'])\n\n def test_static_url_prefix(self):\n \"\"\" If static url prefix is defined on the app configuration.\n \"\"\"\n chdir_app(\"yml\", \"conf\")\n self.assertEqual(\"yml_static_url_prefix\",\n firenado.conf.app['static_url_prefix'])\n\n def test_session_type_file(self):\n \"\"\" Checks if the session is enabled and the type is file\n \"\"\"\n chdir_app(\"file\", \"session\")\n self.assertEqual(firenado.conf.session['enabled'], True)\n self.assertEqual(firenado.conf.session['type'], \"file\")\n\n def test_session_name_default(self):\n \"\"\" Checks if the session name is default, FIRENADOSESSID\n \"\"\"\n chdir_app(\"file\", \"session\")\n self.assertEqual(firenado.conf.session['enabled'], True)\n self.assertEqual(firenado.conf.session['name'], \"FIRENADOSESSID\")\n\n def test_session_type_redis(self):\n \"\"\" Checks if the session is enabled and the type is redis\n \"\"\"\n chdir_app(\"redis\", \"session\")\n self.assertEqual(firenado.conf.session['enabled'], True)\n self.assertEqual(firenado.conf.session['type'], \"redis\")\n\n def test_session_name_custom(self):\n \"\"\" Checks if the session name will be defined as in the config file\n \"\"\"\n chdir_app(\"redis\", \"session\")\n self.assertEqual(firenado.conf.session['enabled'], True)\n self.assertEqual(firenado.conf.session['name'], \"REDISSESSID\")\n\n def test_data_source_pool(self):\n \"\"\" Checks if the data source pool is set correctly\n \"\"\"\n chdir_app(\"data\", \"conf\")\n self.assertEqual(\n firenado.conf.data['sources']['mysql']['pool']['size'],\n 10)\n self.assertEqual(\n firenado.conf.data['sources']['mysql']['pool']['max_overflow'],\n 10)\n self.assertEqual(\n firenado.conf.data['sources']['mysql']['pool']['isolation_level'],\n \"REPEATABLE READ\")\n\n\nclass MultiAppTestCase(unittest.TestCase):\n \"\"\" Case that tests multi app configuration.\n \"\"\"\n\n def test_multi_app_true(self):\n \"\"\" Checks if the application is multi app\n \"\"\"\n chdir_app(\"multiapp\")\n self.assertTrue(firenado.conf.is_multi_app)\n\n def test_multi_app_false(self):\n \"\"\" Checks if the application isn't multi app\n \"\"\"\n chdir_app(\"tornadoweb\")\n self.assertFalse(firenado.conf.is_multi_app)\n", "repo_name": "candango/firenado", "sub_path": "tests/conf_test.py", "file_name": "conf_test.py", "file_ext": "py", "file_size_in_byte": 9356, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 11, "dataset": "github-code", "pt": "25", "api": [{"api_name": "unittest.TestCase", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path", "line_number": 18, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 18, "usage_type": "call"}, {"api_name": "os.sep", "line_number": 19, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "firenado.conf.conf", "line_number": 21, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 21, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 26, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 26, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 33, "usage_type": "attribute"}, {"api_name": "importlib.reload", "line_number": 34, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 34, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 34, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 35, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 35, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 36, "usage_type": "attribute"}, {"api_name": "importlib.reload", "line_number": 37, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 37, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 37, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 42, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 42, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 49, "usage_type": "attribute"}, {"api_name": "importlib.reload", "line_number": 50, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 50, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 50, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 51, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 51, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 52, "usage_type": "attribute"}, {"api_name": "importlib.reload", "line_number": 53, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 53, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 53, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 59, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 59, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 60, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 60, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 66, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 67, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 67, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 68, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 68, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 69, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 69, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 70, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 70, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 76, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path", "line_number": 76, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path", "line_number": 77, "usage_type": "attribute"}, {"api_name": "importlib.reload", "line_number": 78, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 78, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 78, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 79, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 79, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 80, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 80, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 81, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 81, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 82, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 82, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 84, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 84, "usage_type": "name"}, {"api_name": "logging.DEBUG", "line_number": 85, "usage_type": "attribute"}, {"api_name": "firenado.conf.conf", "line_number": 85, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 85, "usage_type": "name"}, {"api_name": "os.environ", "line_number": 86, "usage_type": "attribute"}, {"api_name": "importlib.reload", "line_number": 87, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 87, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 87, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 94, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 95, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 95, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 96, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 96, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 97, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 97, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 98, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 98, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 104, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 105, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 105, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 106, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 106, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 107, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 107, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 113, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 114, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 114, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 115, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 115, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 120, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 121, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 121, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 127, "usage_type": "call"}, {"api_name": "cartola.fs.get_file_extension", "line_number": 128, "usage_type": "call"}, {"api_name": "cartola.fs", "line_number": 128, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 129, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 129, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 134, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 135, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 135, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 140, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 146, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 146, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 151, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 152, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 152, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 157, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 158, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 158, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 164, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 165, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 165, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 171, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 172, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 172, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 177, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 179, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 179, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 184, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 185, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 185, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 186, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 186, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 191, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 192, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 192, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 193, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 193, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 198, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 199, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 199, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 200, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 200, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 205, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 206, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 206, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 207, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 207, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 212, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 214, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 214, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 217, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 217, "usage_type": "name"}, {"api_name": "firenado.conf.conf", "line_number": 220, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 220, "usage_type": "name"}, {"api_name": "unittest.TestCase", "line_number": 224, "usage_type": "attribute"}, {"api_name": "tests.chdir_app", "line_number": 231, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 232, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 232, "usage_type": "name"}, {"api_name": "tests.chdir_app", "line_number": 237, "usage_type": "call"}, {"api_name": "firenado.conf.conf", "line_number": 238, "usage_type": "attribute"}, {"api_name": "firenado.conf", "line_number": 238, "usage_type": "name"}]} +{"seq_id": "41618825036", "text": "from flask import Blueprint\nfrom watson_developer_cloud import PersonalityInsightsV3\n\nimport credentials\nfrom db import *\n\napp_admin_ibm = Blueprint('app_admin_ibm', __name__)\n\n#################################################################################\n# /app_admin_ibm\n# Only needed to be run once.\n# Runs each concatenated course review (reviews.json) through Watson to generate\n# am average personality insights for each class - dump to insights.json\n###################################################################################\n@app_admin_ibm.route(\"/admin_ibm\", methods=['GET', 'POST'])\ndef admin_ibm():\n log = \"
    \"\n    temp_insights = []\n    our_insights = {}\n\n    conn = sqlite3.connect(DATABASE)\n    cur = conn.cursor()\n\n\n    with open('reviews.json') as f:\n        data = json.load(f)\n\n    print(credentials)\n    personality_insights = PersonalityInsightsV3(\n        version='2016-10-20',\n        username= credentials.username,\n        password= credentials.password)\n\n    # personality_insights.set_url('https://gateway-fra.watsonplatform.net/personality-insights/api')\n    # personalityInsights.set_detailed_response(True)\n\n\n\n    for key, value in data.iteritems():\n\n        ## -run personality insight on review on value\n        profile = personality_insights.profile( value, content_type=\"text/plain;charset=utf-8\")\n        for category in ['needs', 'personality', 'values']:\n        # for category in ['needs']:\n            for trait in profile[category]:\n                temp_insights.append( {trait['name']:trait['percentile']} )\n\n        our_insights[key] = temp_insights\n        temp_insights = []\n\n    ## Write all insight results to json file\n    with open('insights.json', 'w+') as outfile:\n        json.dump(our_insights, outfile, indent=4, sort_keys=True)\n\n    return log\n\n\n\n\n\n\n", "repo_name": "rylew2/SenseCourse", "sub_path": "controller/admin_ibm.py", "file_name": "admin_ibm.py", "file_ext": "py", "file_size_in_byte": 1820, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "flask.Blueprint", "line_number": 7, "usage_type": "call"}, {"api_name": "watson_developer_cloud.PersonalityInsightsV3", "line_number": 29, "usage_type": "call"}, {"api_name": "credentials.username", "line_number": 31, "usage_type": "attribute"}, {"api_name": "credentials.password", "line_number": 32, "usage_type": "attribute"}]}
    +{"seq_id": "73263153985", "text": "\"\"\"Modelo de cita medica\"\"\"\n\n# Django\nfrom django.db import models\n\n# Utilidades\nfrom apis.utils.models import ModelUtil\n\n\nclass MedicalAppoinmentModels(ModelUtil):\n    \"\"\"Modelo de citas medicas\"\"\"\n\n    pacient = models.ForeignKey('pacient.Pacient', on_delete=models.CASCADE)\n    medic = models.ForeignKey('medic.Medic', on_delete=models.CASCADE)\n\n    date_appoinment = models.DateField(null=False)\n    url_webex = models.URLField()\n    symptoms = models.TextField(max_length=250)\n\n    def __str__(self):\n        \"\"\"Regresa los detalles de la cita\"\"\"\n        return f'{self.pacient} tiene una cita medica con {self.medic} el dia {self.date_appoinment}, el paciente ' \\\n               f'presenta los siguientes sintomas {self.symptoms} '\n\n\n", "repo_name": "sango09/senasoft", "sub_path": "backend/apis/medical_appoinment/models/medical_appoinment.py", "file_name": "medical_appoinment.py", "file_ext": "py", "file_size_in_byte": 740, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "apis.utils.models.ModelUtil", "line_number": 10, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 13, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 13, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 13, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 14, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 14, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 14, "usage_type": "attribute"}, {"api_name": "django.db.models.DateField", "line_number": 16, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 16, "usage_type": "name"}, {"api_name": "django.db.models.URLField", "line_number": 17, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 17, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 18, "usage_type": "name"}]}
    +{"seq_id": "2176877485", "text": "import scipy.io\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom PIL import Image\r\nfrom scipy.signal import hilbert\r\nfrom scipy.fft import fft, ifft\r\n\r\n\r\nFanImage_org = 'Fan.png'\r\nFanImage_linear = 'FanImage_linear.png'\r\n\r\n\r\ndef get_b_mode():\r\n\r\n    data = scipy.io.loadmat('rf2017.mat')\r\n\r\n    img = data['rf_signal']\r\n    img = np.transpose(img)\r\n    aline = 300\r\n    dataLength = 5000\r\n    samplingRate = 1000000000  # 1GHz\r\n    interval = 0.00005  # 50 um\r\n    vpp = 200\r\n\r\n    samplePoint = 4096\r\n\r\n    for index in range(60, 66):\r\n        t = np.arange(0, dataLength, 1)\r\n        fig, axs = plt.subplots()\r\n        axs.set_title(\"Image of Time domain A-line \"+str(index))\r\n        axs.plot(t, img[index], color='C0')\r\n        axs.set_xlabel(\"Time(μs)\")\r\n        axs.set_ylabel(\"Amplitute(mV)\")\r\n        plt.axis('on')\r\n        plt.savefig('Image of Time domain A-line '+str(index) +\r\n                    ' frequency ', bbox_inches='tight', pad_inches=0.0)\r\n        plt.plot(t, img[index])\r\n        plt.show()\r\n    distance = interval * aline * 1000                    # mm\r\n    depth = dataLength / samplingRate / 2 * 1540 * 1000   # mm\r\n\r\n    spectrum = abs(hilbert(img))\r\n\r\n    cal = spectrum/(np.min(spectrum))\r\n    compression = 20*np.log10(cal)\r\n\r\n    compressed_signal = compression-(np.max(compression))\r\n    us_image = (compressed_signal+42)/42*255\r\n\r\n    img = np.transpose(us_image)\r\n    fig, ax = plt.subplots(figsize=(8, 3))\r\n    im = ax.imshow(img, cmap=plt.gray(), vmin=0, vmax=255,\r\n                   aspect='auto', extent=[0, distance, depth, 0])\r\n    plt.axis('off')\r\n    plt.savefig('B-mode', bbox_inches='tight', pad_inches=0.0)\r\n\r\n    ax.set_aspect('equal')\r\n    ax.set_xlabel('Distance of Imaging (mm)')\r\n    ax.set_ylabel('Depth of Imaging (mm)')\r\n    ax.set_title('B-mode')\r\n    fig.colorbar(im, orientation='vertical')\r\n    plt.axis('on')\r\n    plt.savefig('B-mode(legend)', bbox_inches='tight', pad_inches=0.0)\r\n\r\n\r\ndef change_square_to_fan(inputFileName: str, outputFileName: str, angle: int):\r\n    im = Image.open(inputFileName)\r\n\r\n    mode = im.mode\r\n    w, h = im.size\r\n    rows, cols = int(np.ceil(h)), int(\r\n        np.ceil(2 * h * np.sin(np.radians(angle))))\r\n    cols += cols % 2\r\n    padding = 2\r\n\r\n    im_squ = np.array(im)\r\n    # im_fan = np.zeros((rows,cols,im_squ.shape[2]),dtype=np.uint8)\r\n    im_fan = np.zeros((rows + padding, cols + padding,\r\n                      im_squ.shape[2]), dtype=np.uint8)\r\n\r\n    alpha = np.radians(np.linspace(-angle, angle, w))\r\n    for i in range(w):\r\n        d = np.cos(alpha[i]) * rows\r\n        lats = np.int_(np.linspace(0, d, h)).astype(np.int)\r\n        d = np.sin(alpha[i]) * rows\r\n        lons = np.int_(np.linspace(cols / 2, cols / 2 + d, h)).astype(np.int)\r\n        im_fan[(lats, lons)] = im_squ[:, i]\r\n\r\n    im = Image.fromarray(im_fan, mode=mode)\r\n    im.save('BeforeInterpolate_rf_' + outputFileName)\r\n\r\n    for row in range(rows):\r\n        ps, pe = 0, 0\r\n        for col in range(cols):\r\n            if im_fan[row, col, 3] > 0:\r\n                if ps == 0:\r\n                    ps, pe = col, col\r\n                else:\r\n                    pe = col\r\n        for col in range(ps - 1, pe):\r\n            if im_fan[row, col, 3] == 0:\r\n                im_fan[row, col] = im_fan[row, col - 1]\r\n\r\n    im = Image.fromarray(im_fan, mode=mode)\r\n    im.save('AfterInterpolate_rf_' + outputFileName)\r\n\r\n\r\ndef linear_inter(fn_squ: str, fn_fan, angle: int,\r\n                 r0=0, k=2, top=True,\r\n                 rotate=0):\r\n    im_pil = Image.open(fn_squ)\r\n    im = np.array(im_pil)\r\n    h, w, d = im.shape\r\n    print('k', k)\r\n    if r0 > 0:\r\n        bg = np.ones((r0, w, d), dtype=np.uint8)\r\n        im = np.append(bg, im, axis=0) if top else np.append(im, bg, axis=0)\r\n\r\n    h, w, d = im.shape\r\n    r = 2*h-1\r\n    im_fan = np.zeros((r, r, d), dtype=np.uint8)\r\n    idx = np.arange(h) if top else np.arange(h)[::-1]\r\n    alpha = np.radians(np.linspace(-angle/2, angle/2, k*w))\r\n    for i in range(k*w):\r\n        rows = ((np.ceil(np.cos(alpha[i])*idx)) + r/2).astype('int')\r\n        cols = (np.int32(np.ceil(np.sin(alpha[i])*idx)) + r/2).astype('int')\r\n        im_fan[(rows, cols)] = im[:, i//k]\r\n    if 360 > angle and angle > 180:\r\n        im_fan = im_fan[int(h*(1-np.sin(np.radians((angle/2-90))))):]\r\n\r\n    if not top:\r\n        im_fan = im_fan[::-1]\r\n    im_out = Image.fromarray(im_fan, mode=im_pil.mode)\r\n    im_out.save(fn_fan)\r\n    img = Image.open(fn_fan)\r\n    dst = img.rotate(rotate)\r\n    dst.save(fn_fan)\r\n\r\n\r\nif __name__ == '__main__':\r\n    get_b_mode()\r\n    change_square_to_fan('B-mode.png', FanImage, 60)\r\n    linear_inter('B-mode.png', FanImage_linear, 120, 1, 200, False)\r\n", "repo_name": "NeroHin/ultrasound-singal-to-image", "sub_path": "b-mode-ultraosund-imaging.py", "file_name": "b-mode-ultraosund-imaging.py", "file_ext": "py", "file_size_in_byte": 4678, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "scipy.io.io.loadmat", "line_number": 15, "usage_type": "call"}, {"api_name": "scipy.io.io", "line_number": 15, "usage_type": "attribute"}, {"api_name": "scipy.io", "line_number": 15, "usage_type": "name"}, {"api_name": "numpy.transpose", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "scipy.signal.hilbert", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gray", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 67, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 67, "usage_type": "name"}, {"api_name": "numpy.ceil", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.radians", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 79, "usage_type": "attribute"}, {"api_name": "numpy.radians", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.int_", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.int", "line_number": 84, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.int_", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.int", "line_number": 86, "usage_type": "attribute"}, {"api_name": "PIL.Image.fromarray", "line_number": 89, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 89, "usage_type": "name"}, {"api_name": "PIL.Image.fromarray", "line_number": 104, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 104, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 111, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 111, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 116, "usage_type": "attribute"}, {"api_name": "numpy.append", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 121, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.radians", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.radians", "line_number": 129, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 133, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 133, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 135, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 135, "usage_type": "name"}]}
    +{"seq_id": "40780255109", "text": "import types\nfrom collections import namedtuple\nfrom importlib import import_module\n\nfrom sanic.blueprints import Blueprint as BP\n\nfrom trellio2.conf import settings\n\nRoute = namedtuple('Route', 'uri handler methods')\n\n\nclass Blueprint(BP):\n    _instances = []\n\n    def __init__(self, *args, **kwargs):\n        super(Blueprint, self).__init__(*args, **kwargs)\n        self._instances.append(self)\n\n    def url(self, uri, handler, methods=None, **kwargs):\n\n        strict_slashes = getattr(settings, 'STRICT_SLASHES', False)\n\n        if isinstance(handler, list):\n            for _ in handler:\n                for each in _:\n                    self.add_route(handler=each.handler, uri=each.uri, methods=each.methods,\n                                   strict_slashes=strict_slashes)\n\n        elif isinstance(handler, types.FunctionType):\n            if isinstance(methods, str):\n                methods = [methods.upper()]\n            elif isinstance(methods, list):\n                methods = [m.upper() for m in methods]\n            self.add_route(handler=handler, uri=uri, methods=methods, strict_slashes=strict_slashes)\n\n\ndef url(uri, handler, methods=None, **kwargs):\n    routes = []\n    if isinstance(handler, list):\n        for _ in handler:\n            for each in _:\n                routes.append(Route(uri=uri + each.uri, handler=each.handler, methods=each.methods))\n\n    elif isinstance(handler, types.FunctionType):\n        if isinstance(methods, str):\n            methods = [methods.upper()]\n        elif isinstance(methods, list):\n            methods = [m.upper() for m in methods]\n        routes.append(Route(uri=uri, handler=handler, methods=methods))\n    return routes\n\n\nclass Include:\n    def __call__(self, url_module):\n        mod = import_module(url_module)\n        return getattr(mod, 'urlpatterns', [])\n\n\ninclude = Include()\n", "repo_name": "technomaniac/trellio2", "sub_path": "trellio2/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 1847, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "collections.namedtuple", "line_number": 9, "usage_type": "call"}, {"api_name": "sanic.blueprints.Blueprint", "line_number": 12, "usage_type": "name"}, {"api_name": "trellio2.conf.settings", "line_number": 21, "usage_type": "argument"}, {"api_name": "types.FunctionType", "line_number": 29, "usage_type": "attribute"}, {"api_name": "types.FunctionType", "line_number": 44, "usage_type": "attribute"}, {"api_name": "importlib.import_module", "line_number": 55, "usage_type": "call"}]}
    +{"seq_id": "72418393345", "text": "import argparse\nfrom currency_converter_core import currency_converter\nfrom json import dumps\nimport sys\n\n#create parser and all necessary arguments\nparser = argparse.ArgumentParser(description='Currency converter')\n\n#create all arguments needed for conversion\nparser.add_argument('--amount' ,type = float, default = 1.1, help = 'Insert an amount you wish to convert.')\nparser.add_argument('--input_currency', type = str, help = 'Insert currency you wish to convert.')\nparser.add_argument('--output_currency', type = str, help = 'Insert currency you wish to convert into.')\n\ntry:\n    #get all input arguments\n    args = parser.parse_args()\nexcept:\n    print('Correct request is : python3 currency_converter.py --amount  --input_currency  [--output_currency ]')\n    sys.exit(1)\n    \nif __name__ == '__main__':   \n    #call main function with main converting logic and print it to console\n    print(dumps(currency_converter(args.amount, args.input_currency, args.output_currency), indent=4, sort_keys=True))", "repo_name": "domchiq/currency_converter", "sub_path": "currency_converter.py", "file_name": "currency_converter.py", "file_ext": "py", "file_size_in_byte": 1046, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 7, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 19, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 23, "usage_type": "call"}, {"api_name": "currency_converter_core.currency_converter", "line_number": 23, "usage_type": "call"}]}
    +{"seq_id": "7078393736", "text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\"\"\"\nTocoStickにPythonからコマンドを送るスクリプト\nref.\nhttp://tocos-wireless.com/jp/products/TWE-Lite-USB/control.html\n\"\"\"\n\nimport serial\nimport time\nimport sys\n\nclass Toco:\n\tdef __init__(self,port):\n\t\tself.HIGH = 1\n\t\tself.LOW = 0\n\t\tself.serial = serial.Serial(\n\t\t\tport=port,\n\t\t\tbaudrate=115200)\n\n\tdef digitalWrite(self,pin,value):\n\t\tcmd = ':788001'\n\t\tif pin == 1:\n\t\t\tif value == self.HIGH:\n\t\t\t\tcmd = cmd + '0101'+'FFFFFFFFFFFFFFFF'\n\t\t\tif value == self.LOW:\n\t\t\t\tcmd = cmd + '0001'+'FFFFFFFFFFFFFFFF'\n\t\tif pin == 2:\n\t\t\tif value == self.HIGH:\n\t\t\t\tcmd = cmd + '0202'+'FFFFFFFFFFFFFFFF'\n\t\t\tif value == self.LOW:\n\t\t\t\tcmd = cmd + '0002'+'FFFFFFFFFFFFFFFF'\n\t\tif pin == 3:\n\t\t\tif value == self.HIGH:\n\t\t\t\tcmd = cmd + '0404'+'FFFFFFFFFFFFFFFF'\n\t\t\tif value == self.LOW:\n\t\t\t\tcmd = cmd + '0004'+'FFFFFFFFFFFFFFFF'\n\t\tif pin == 4:\n\t\t\tif value == self.HIGH:\n\t\t\t\tcmd = cmd + '0808'+'FFFFFFFFFFFFFFFF'\n\t\t\tif value == self.LOW:\n\t\t\t\tcmd = cmd + '0008'+'FFFFFFFFFFFFFFFF'\n\t\tcmd = cmd + 'XX\\r\\n'\n\t\tself.serial.write(cmd)\n\t\ttime.sleep(0.1)\n\t\treturn cmd\n\n\tdef analogWrite(self,pin,value):\n\t\tcmd = ':7880010000'\n\t\tif pin == 1:\n\t\t\tcmd = cmd + ''+self.hex4(value)+'FFFFFFFFFFFF'\n\t\tif pin == 2:\n\t\t\tcmd = cmd + 'FFFF'+self.hex4(value)+'FFFFFFFF'\n\t\tif pin == 3:\n\t\t\tcmd = cmd + 'FFFFFFFF'+self.hex4(value)+'FFFF'\n\t\tif pin == 4:\n\t\t\tcmd = cmd + 'FFFFFFFFFFFF'+self.hex4(value)+''\n\t\tcmd = cmd + 'XX\\r\\n'\n\t\tself.serial.write(cmd)\n\t\ttime.sleep(0.1)\n\t\treturn cmd\n\n\tdef hex4(self,value):\n\t\treturn \"{0:x}\".format(value).zfill(4).upper()\n\nif __name__ == '__main__':\n\n\ttoco = Toco('/dev/tty.usbserial-AHXMUX35')\n\n\twhile True:\n\n\t\ttoco.analogWrite(1,0)\n\t\ttoco.digitalWrite(1,toco.LOW)\n\t\ttime.sleep(1)\n\n\t\ttoco.analogWrite(1,1024)\n\t\ttoco.digitalWrite(1,toco.HIGH)\n\t\ttime.sleep(1)\n", "repo_name": "usop4/tocotika", "sub_path": "tocotika.py", "file_name": "tocotika.py", "file_ext": "py", "file_size_in_byte": 1795, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "serial.Serial", "line_number": 18, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 46, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 61, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 75, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 79, "usage_type": "call"}]}
    +{"seq_id": "25850814380", "text": "#Inferring mRAN from Protein\n\nimport sys\nfrom collections import defaultdict\n\ndef stringRead(inpath):\n    with open(inpath) as infile:\n        strs = infile.read().split('\\n')\n    return strs\n\ncodon_table={\"UUU\":\"F\",\"CUU\":\"L\",\"AUU\":\"I\",\"GUU\":\"V\",\"UUC\":\"F\",\"CUC\":\"L\",\"AUC\":\"I\",\"GUC\":\"V\",\"UUA\":\"L\",\"CUA\":\"L\",\"AUA\":\"I\",\"GUA\":\"V\",\"UUG\":\"L\",\"CUG\":\"L\",\"AUG\":\"M\",\"GUG\":\"V\",\"UCU\":\"S\",\"CCU\":\"P\",\"ACU\":\"T\",\"GCU\":\"A\",\"UCC\":\"S\",\"CCC\":\"P\",\"ACC\":\"T\",\"GCC\":\"A\",\"UCA\":\"S\",\"CCA\":\"P\",\"ACA\":\"T\",\"GCA\":\"A\",\"UCG\":\"S\",\"CCG\":\"P\",\"ACG\":\"T\",\"GCG\":\"A\",\"UAU\":\"Y\",\"CAU\":\"H\",\"AAU\":\"N\",\"GAU\":\"D\",\"UAC\":\"Y\",\"CAC\":\"H\",\"AAC\":\"N\",\"GAC\":\"D\",\"UAA\":\"Stop\",\"CAA\":\"Q\",\"AAA\":\"K\",\"GAA\":\"E\",\"UAG\":\"Stop\",\"CAG\":\"Q\",\"AAG\":\"K\",\"GAG\":\"E\",\"UGU\":\"C\",\"CGU\":\"R\",\"AGU\":\"S\",\"GGU\":\"G\",\"UGC\":\"C\",\"CGC\":\"R\",\"AGC\":\"S\",\"GGC\":\"G\",\"UGA\":\"Stop\",\"CGA\":\"R\",\"AGA\":\"R\",\"GGA\":\"G\",\"UGG\":\"W\",\"CGG\":\"R\",\"AGG\":\"R\",\"GGG\":\"G\"}\n\nreverse_table=defaultdict(list)\nfor ckey in codon_table:\n    reverse_table[codon_table[ckey]].append(ckey)\n\nif __name__=='__main__':\n    infile = sys.argv[1]\n    outfile = sys.argv[2]\n    protein=stringRead(infile)[0]\n    combination=1\n    for aa in protein:\n        combination*=len(reverse_table[aa])\n    combination*=len(reverse_table['Stop'])\n    with open(outfile,'w') as handle:\n        handle.write(str(combination%1000000)+'\\n')", "repo_name": "naonaox/math.practice", "sub_path": "bioinfoStronghold/mrna.py", "file_name": "mrna.py", "file_ext": "py", "file_size_in_byte": 1293, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "collections.defaultdict", "line_number": 13, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 18, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 19, "usage_type": "attribute"}]}
    +{"seq_id": "472851349", "text": "import dill\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\n\ndef dist(x, y, k):\n    return math.sqrt(k(x, x) + k(y, y) - 2 * k(x, y))\n\n\ndef dist_from_mean(x, y, k):\n    m = len(y)\n    temp = 0\n    s_dist = k(x, x)\n    for i in range(m):\n        for j in range(m):\n            temp += k(y[i], y[j])\n    s_dist += temp / (m * m)\n    temp = 0\n    for i in range(m):\n        temp += k(x, y[i])\n    s_dist -= 2 * temp / m\n    s_dist = max(0, s_dist)\n\n    dist = math.sqrt(s_dist)\n    return dist\n\n\ndef main():\n    filename = 'kernel_4a.pkl'\n    input_file = open(filename, 'rb')\n    k = dill.loads(dill.load(input_file))\n    d = 10\n    e = np.identity(d)\n\n    # PART A\n    D = np.zeros((d, d))\n    sum_D = 0\n    for i in range(d):\n        for j in range(d):\n            D[i][j] = dist(e[i], e[j], k)\n            sum_D += D[i][j]\n    print('Part A. Sum = ', sum_D)\n\n    # PART B\n    D = [dist_from_mean(e[i], e, k) for i in range(d)]\n    print('Part B. Sum = ', sum(D))\n\n    # PART C\n    print('Part C')\n    X = np.load('data.npy')\n    n = X.shape[0]\n\n    # plt.scatter(X[:, 0], X[:, 1])\n    # plt.show()\n\n    c = [0] * n\n    c1 = [np.random.rand(1, 2)]\n    c2 = [np.random.rand(1, 2)]\n    while True:\n\n        if len(c1) == 0:\n            c1 = [X[np.random.randint(0, n)]]\n        if len(c2) == 0:\n            c2 = [X[np.random.randint(0, n)]]\n\n        changed = False\n        for i in range(n):\n            if dist_from_mean(X[i], c1, k) <= dist_from_mean(X[i], c2, k):\n                if c[i] != 1:\n                    changed = True\n                    c[i] = 1\n            else:\n                if c[i] != 2:\n                    changed = True\n                    c[i] = 2\n\n        if not changed:\n            print('not changed')\n            break\n        c1 = [X[i] for i in range(n) if c[i] == 1]\n        c2 = [X[i] for i in range(n) if c[i] == 2]\n\n    c1 = np.array(c1)\n    c2 = np.array(c2)\n    plt.scatter(c1[:, 0], c1[:, 1], color='r')\n    plt.scatter(c2[:, 0], c2[:, 1], color='g')\n    plt.show()\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "shamnastv/ML-Kernel", "sub_path": "Q4/Q4.py", "file_name": "Q4.py", "file_ext": "py", "file_size_in_byte": 2060, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "math.sqrt", "line_number": 8, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 25, "usage_type": "call"}, {"api_name": "dill.loads", "line_number": 32, "usage_type": "call"}, {"api_name": "dill.load", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.identity", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 58, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 59, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 63, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 65, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 86, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 87, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 88, "usage_type": "name"}]}
    +{"seq_id": "3113823318", "text": "import os\nimport time\nimport subprocess\nfrom datetime import datetime\nfrom typing import Callable, Literal, Optional, Union, Tuple\n\nPipeType = Union[Literal[\"stdout\"], Literal[\"stderr\"]]\n\n\nclass StdoutTracer:\n    def __init__(\n        self,\n        process: subprocess.Popen,\n        timeout: int = 30,\n        interval: int = 0.1,\n        on_output: Callable[[PipeType, str], None] = lambda: None,\n    ):\n        self.process: subprocess.Popen = process\n        self.timeout: int = timeout\n        self.interval: int = interval\n        self.last_output: datetime = None\n        self.on_output: Callable[[PipeType, str], None] = on_output\n\n    def nonblock(self):\n        os.set_blocking(self.process.stdout.fileno(), False)\n        os.set_blocking(self.process.stderr.fileno(), False)\n\n    def get_output(self, pipe: PipeType) -> str:\n        output = None\n        if pipe == \"stdout\":\n            output = self.process.stdout.read()\n        elif pipe == \"stderr\":\n            output = self.process.stderr.read()\n\n        if output:\n            decoded = output.decode()\n            self.on_output(pipe, decoded)\n            self.last_output = datetime.now()\n            return decoded\n        return \"\"\n\n    def last_output_passed(self, seconds: int) -> bool:\n        return (datetime.now() - self.last_output).seconds > seconds\n\n    def wait_until_stop_or_exit(self) -> Tuple[Optional[int], str]:\n        self.nonblock()\n        self.last_output = datetime.now()\n        output = \"\"\n        exitcode = None\n        while True:\n            new_stdout = self.get_output(\"stdout\")\n            if new_stdout:\n                output += new_stdout\n\n            new_stderr = self.get_output(\"stderr\")\n            if new_stderr:\n                output += new_stderr\n\n            if self.process.poll() is not None:\n                exitcode = self.process.poll()\n                break\n\n            if self.last_output_passed(self.timeout):\n                self.process.kill()\n                break\n\n            time.sleep(self.interval)\n\n        return (exitcode, output)\n", "repo_name": "corca-ai/EVAL", "sub_path": "core/tools/terminal/stdout.py", "file_name": "stdout.py", "file_ext": "py", "file_size_in_byte": 2066, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 844, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.Union", "line_number": 7, "usage_type": "name"}, {"api_name": "typing.Literal", "line_number": 7, "usage_type": "name"}, {"api_name": "subprocess.Popen", "line_number": 13, "usage_type": "attribute"}, {"api_name": "typing.Callable", "line_number": 16, "usage_type": "name"}, {"api_name": "subprocess.Popen", "line_number": 18, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 21, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 22, "usage_type": "name"}, {"api_name": "os.set_blocking", "line_number": 25, "usage_type": "call"}, {"api_name": "os.set_blocking", "line_number": 26, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 38, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 38, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 43, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 43, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 47, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 47, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 67, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 45, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 45, "usage_type": "name"}]}
    +{"seq_id": "36541264334", "text": "import math\nimport time\nimport numpy as np\nfrom tqdm.auto import tqdm\nfrom warnings import warn\nfrom bcd_helper import backtracking_list\nimport sys\n#sys.path.append('../../../')\nfrom bcd_helper import imshow, imshow_scatter\nimport matplotlib.pyplot as plt\nimport geopandas as gpd\nfrom skimage.draw import polygon\nimport matplotlib\n#from common_helpers import get_all_area_maps, get_random_coords, get_area_map\n\ndef visit(matrix, x, y, memory,obstacle):\n    matrix[(x,y)] = obstacle[0] # 150 == visited\n    memory.append((x, y))\n    return x,y\ndef is_bounded(coord, shape):\n    \"\"\"\n    Checks if a coord (x,y) is within bounds.\n    \"\"\"\n    x,y = coord\n    g,h = shape\n    lesser = x < 0 or y < 0\n    greater = x >= g or y >= h\n    if lesser or greater:\n        return False\n    return True\ndef is_valid(coord, area_map, obstacle = -1):\n    \"\"\"\n    Check is a coord (x,y) is bounded and not\n    on an obstacle.\n    \"\"\"\n    coord = tuple(coord)\n    is_b = is_bounded(coord, area_map.shape)\n    if is_b:\n        is_on_obs = False\n        if isinstance(obstacle, list):\n            for obs in obstacle:\n                is_on_obs |= area_map[coord] == obs\n        else:\n            is_on_obs  = area_map[coord] == obstacle\n        if not is_on_obs:\n            return True\n    return False\n\ndef boustrophedon(matrix, diameter, x, y, memory,direction, obstacle):\n    # TODO :: Variable diameter support\n    udlr = {\n        \"u\": lambda x,y : (x-diameter,y),\n        \"d\": lambda x,y : (x+diameter,y),  # FQ comment \n        \"l\": lambda x,y : (x,y-diameter),\n        \"r\": lambda x,y : (x,y+diameter),\n    }\n    udlr = {\n        \"u\": lambda x,y : (x,y+diameter),\n        \"d\": lambda x,y : (x,y-diameter),  # FQ comment \n        \"l\": lambda x,y : (x-diameter,y),\n        \"r\": lambda x,y : (x+diameter,y),\n    }\n    u = \"u\";d = \"d\";r = \"r\";l = \"l\"\n    visit(matrix, x, y, memory,obstacle)\n    while True:\n        if direction=='UP':\n            dir_ = [u,d,r,l]\n            fdir=l\n        else:\n            dir_ = [r,l,u,d]\n            fdir=d\n            #dir_ = [u,d,r,l]\n        while len(dir_) > 0:\n            d_ = dir_.pop(0)   \n            x_, y_ = udlr[d_](x,y)\n            if is_valid((x_,y_), matrix, obstacle):\n                x, y = visit(matrix, x_, y_, memory,obstacle)\n                break\n            elif d_ == fdir:    # FQ comment \n                return x, y\n            \ndef Redirect(matrix,cover,start_point,obstacle):\n    x,y=np.where(matrix==cover)\n    xi=min(x)\n    xx=max(x)\n    #print(f\"see {cover} {x,y}\")\n    if abs(start_point[0]-xi)0:\n    #     end_point = coverage_path[-1]\n    #     x,y = np.array(coverage_path).T\n    #     #Display \n    #     # for i in range(int(len(x)/400)):\n    #     #      imshow(matrix, figsize=(8, 8), cmap=\"cividis\")   \n    #     #      imshow_scatter([start_point],color=\"lightgreen\")\n    #     #      imshow_scatter([end_point],color=\"red\")\n    #     #      # imshow_scatter(critical, alpha=0.4, color=\"red\",s=20)\n    #     #      # imshow_scatter(cri_end, alpha=0.4, color=\"black\",s=50)\n    #     #      imshow_scatter(coverage_path, alpha=0.4, color=\"black\",s=5)\n    #     #      plt.plot(x[0:i*400+2],y[0:i*400+2])\n    #     #      plt.show()\n    #     imshow(matrix, figsize=(8, 8), cmap=\"cividis\")   \n    #     imshow_scatter(critical, alpha=0.4, color=\"red\",s=20)\n    #     imshow_scatter(cri_end, alpha=0.4, color=\"black\",s=50)\n    #     plt.plot(x,y)\n    #     plt.show()\n    plt.rcParams['font.family'] = 'serif'\n    plt.rcParams['font.serif'] = ['Times New Roman'] + plt.rcParams['font.serif']\n    plt.rcParams.update({'font.size': 13})\n    inittime=0\n    Grid_map=np.full((5,7),0)\n    Grid_map[0,0]=0\n    Grid_map[1,0]=1\n    Grid_map[1,1]=1\n    Grid_map[3,1]=0\n    Grid_map[2,1]=1\n    #Grid_map[3,2]=1\n    # imshow(Grid_map)\n    # plt.show()\n    cmap = plt.cm.gray\n    cmap.set_bad((1, 0, 0, 1))\n    ax=plt.axes(projection='3d')\n\n    FOV=10\n    z=1\n    WPC=[]\n    x=0\n    while x <50: \n        y=0\n        while y <70: \n             xc=x+FOV/2\n             yc=y+FOV/2\n             WPC.append((xc,yc,z))\n             y=y+FOV\n        x=x+FOV\n    ax.scatter([w[0] for w in WPC], [w[1] for w in WPC],[w[2] for w in WPC])\n    WPC=[]\n    FOV=20\n    x=0\n    z=2\n    while x <50: \n        y=0\n        while y <70: \n             xc=x+FOV/2\n             yc=y+FOV/2\n             WPC.append((xc,yc,z))\n             y=y+FOV\n        x=x+FOV\n    fig=plt.figure()\n    #ax.plot3D([i[0] for i in self.waypointSeq], [i[1] for i in self.waypointSeq],[i[2] for i in self.waypointSeq])\n    #ax.scatter([i[0] for i in self.waypointSeq], [i[1] for i in self.waypointSeq],[i[2] for i in self.waypointSeq])\n    ax.scatter([w[0] for w in WPC], [w[1] for w in WPC],[w[2] for w in WPC])\n    ax.set_zlim3d(0,2.5)\n    #conw=[w for w in self.waypointSeq ]\n    #plt.show()\n    \n    # Create a path \n    print(WPC)\n    iniw=(0,0,0)\n    def Distance(w1,w2):\n        dis=np.sqrt(((w1[0]-w2[0]))**2+((w1[1]-w2[1]))**2+((w1[2]-w2[2]))**2)\n        return dis\n    tt=0\n    SQ=[iniw]\n    ww=iniw\n    while tt<15 and len(WPC)>0:\n        wn=[(w, Distance(w,ww)) for w in WPC]\n        short=min(tmp[1] for tmp in wn)\n        print(short,wn)\n\n        wcc=[i[0] for i in wn if int(i[1])==int(short)]\n        print(wcc,short, [i[1]==short for i in wn])\n        if len(wcc)>1:\n            #www=[i[0] for i in wcc]\n            wttmp=[(k, (k[0]-ww[0])**2) for k in wcc]\n            \n            short=min([i[1] for i in wttmp])\n            print(wttmp,short)\n            wcc=[i[0] for i in wttmp if i[1]==short]\n        print(wcc)\n        SQ.append(wcc[0])\n        WPC.remove(wcc[0])\n        ww=wcc[0]\n        tt=tt+1\n    SQ.append(iniw)\n    print(SQ)\n    ax.set_xlabel('x')\n    ax.set_ylabel('y')\n    ax.set_zlabel('z');\n    ax.plot3D([w[0] for w in SQ], [w[1] for w in SQ],[w[2] for w in SQ])\n    \n    plt.show()\n    \n    \n    #plt.imshow(Grid_map,cmap=cmap,interpolation='nearest')#, vmin=0, vmax=255)\n    #plt.grid( linestyle = '--', linewidth = 1)\n    #plt.figure()\n    #im=plt.imshow(Grid_map, origin='lower',interpolation='none',cmap = matplotlib.colors.ListedColormap(['green', 'red']))\n    \n    # ax = plt.gca();\n    # ax.set_xticks(np.arange(0, 7, 1))\n    # ax.set_yticks(np.arange(0, 5, 1))\n    # # Minor ticks\n    # ax.set_xticks(np.arange(-.5, 6, 1), minor=True)\n    # ax.set_yticks(np.arange(-.5, 4, 1), minor=True)\n    # ax.grid(which='minor', color='w', linestyle='-', linewidth=2)\n    #\n    # plt.show()\n    #\n\n        \n        \n        \n        ", "repo_name": "Fangqierin/Drone_Rxfire", "sub_path": "cpp_algorithms/coverage_path/bcd/FQ_test.py", "file_name": "FQ_test.py", "file_ext": "py", "file_size_in_byte": 11152, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.where", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 91, "usage_type": "call"}, {"api_name": "bcd_helper.backtracking_list", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 175, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 175, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 186, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 187, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 188, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 191, "usage_type": "call"}, {"api_name": "numpy.int64", "line_number": 193, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 194, "usage_type": "call"}, {"api_name": "numpy.int64", "line_number": 195, "usage_type": "call"}, {"api_name": "skimage.draw.polygon", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.full", "line_number": 197, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 237, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 237, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 238, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 238, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.rcParams.update", "line_number": 239, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 239, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 239, "usage_type": "name"}, {"api_name": "numpy.full", "line_number": 241, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 250, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 250, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axes", "line_number": 252, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 252, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 279, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 279, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 291, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 322, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 322, "usage_type": "name"}]}
    +{"seq_id": "36169033057", "text": "# coding: utf-8\n\nfrom time import time\nimport struct\nfrom typing import Union\n\nfrom .inout import InOut\nfrom .._global import OptionalModule\ntry:\n  from pymodbus.client.sync import ModbusTcpClient\nexcept (ModuleNotFoundError, ImportError):\n  ModbusTcpClient = OptionalModule(\"pymodbus\", \"Cannot use KollMorgenVariator\")\n\n\ndef float32_to_data(num):\n  return struct.unpack(\"=HH\", struct.pack(\"=f\", num))[::-1]\n\n\ndef data_to_float32(data):\n  assert len(data) == 2, \"float32 expects 2 registers\"\n  return struct.unpack(\"=f\", struct.pack(\"=HH\", *data[::-1]))[0]\n\n\nclass KollMorgenVariator:\n  \"\"\"Main class to test communication with kollmorgen variator.\n\n  Every variable and its address has been defined in the Kollmorgen Integrated\n  Suite.\n\n  To add or remove some, update the dictionaries of :meth:`__init__`.\n\n  There are 3 motors, so the tens are for each motor, the units for the\n  address.\n  \"\"\"\n\n  def __init__(self,\n               host: str = '192.168.0.109',\n               port: int = 502) -> None:\n    \"\"\"Sets the variator and defines the bits.\n\n    Args:\n      host (:obj:`str`, optional): Variator's IP address.\n      port (:obj:`int`, optional): Port for modbus communication\n    \"\"\"\n\n    self.variator = ModbusTcpClient(host=host, port=port)\n    assert self.variator.connect(), \"ERROR: could not connect to variator.\"\n\n    self.motor_addresses = [1, 2, 3, 4]\n\n    # R/W bits: coils\n    self.coil_addresses = {\n      'power': 0,\n      'move_abs': 1,\n      'move_rel': 2,\n      'move_vel': 3,\n      'stop': 4,\n      'ack_error': 5}\n\n    # R/W int32: holding registers\n    self.hldreg_addresses = {\n      'position': 0,\n      'distance': 2,\n      'velocity': 4,\n      'acc': 5,\n      'dec': 6,\n      'fstdec': 7,\n      'direction': 8}\n\n    # R bits: input bits, not used.\n    # R int32: input registers.\n\n    self.inpreg_addresses = {\n      'act_speed': 0,\n      'act_position': 2,\n      'axis_state': 4\n    }\n\n  def toggle_power(self, motor: int) -> None:\n    \"\"\"Toggles power of given motor. Maybe not the most intelligent way to\n    handle power, though...\"\"\"\n\n    address = int(str(motor) + str(self.coil_addresses[\"power\"]))\n    state = self.variator.read_coils(address)\n    self.variator.write_coil(address, not state.bits[0])\n\n  def clear_errors(self) -> None:\n    \"\"\"If errors occurred, it must be clear in order to continue the program.\n    \"\"\"\n\n    axis_states = self.variator.read_input_registers(address=1, count=3)\n\n    for index, err in enumerate(axis_states.registers):\n      if not err == 1:\n        motor = index + 1\n        address = int(str(motor) + str(self.coil_addresses[\"ack_error\"]))\n        self.variator.write_coil(address, True)\n        print('Cleared error (AxisState %i) in motor %i' % (err, motor))\n\n  def set_speed(self, motor: int, speed: float) -> None:\n    \"\"\"Writes to variator desired speed (signed), and its direction. Applies to\n    every motor movement (rotations, positioning...).\"\"\"\n\n    address_hld = int(str(motor) + str(self.hldreg_addresses[\"velocity\"]))\n    self.variator.write_register(address_hld, abs(speed))\n    address_hld_direction = int(str(motor) + str(self.hldreg_addresses[\n      \"direction\"]))\n    if speed > 0:\n      self.variator.write_register(address_hld_direction, 0)\n    else:\n      self.variator.write_register(address_hld_direction, 1)\n\n  def set_accelerations(self, motor: int, **kwargs) -> None:\n    \"\"\"To set acceleration, deceleration (for positioning) and fast\n    deceleration (boolean stop).\"\"\"\n\n    for address, value in kwargs.items():\n      self.variator.write_register(int(str(motor) +\n                                       str(self.hldreg_addresses[address])),\n                                   value)\n\n  def start_rotation(self, motor: int) -> None:\n    \"\"\"Sets the rotation of specified motor at specified speed (signed).\"\"\"\n\n    address_coil = int(str(motor) + str(self.coil_addresses[\"move_vel\"]))\n    self.variator.write_coil(address_coil, True)\n\n  def stop(self, motor: int) -> None:\n    \"\"\"Stops the motor movement.\"\"\"\n\n    address = int(str(motor) + str(self.coil_addresses[\"stop\"]))\n    self.variator.write_coil(address, True)\n\n  def set_rotation(self, motor: int, rotation: float) -> None:\n    \"\"\"To set a rotation (in degrees) of the motor axis. Rotation is signed.\"\"\"\n\n    address_coil = int(str(motor) + str(self.coil_addresses[\"move_rel\"]))\n    address_hld = int(str(motor) + str(self.hldreg_addresses[\"distance\"]))\n\n    data = float32_to_data(rotation)\n    self.variator.write_registers(address_hld, data)\n    self.variator.write_coil(address_coil, True)\n\n  def set_position(self, motor: int, position: float) -> None:\n    \"\"\"To set a position (in degrees), absolute value.\"\"\"\n\n    address_coil = int(str(motor) + str(self.coil_addresses[\"move_abs\"]))\n    address_hld = int(str(motor) + str(self.hldreg_addresses[\"position\"]))\n\n    data = float32_to_data(position)\n    self.variator.write_registers(address_hld, data)\n    self.variator.write_coil(address_coil, True)\n\n  def read_position(self, motor: Union[str, int]) -> list:\n    \"\"\"To read position of motor. Returns a :obj:`float`.\"\"\"\n\n    if not motor == \"all\":\n      # If 1 axis is needed\n      address_inpreg = int(str(motor) + str(self.inpreg_addresses[\n        \"act_position\"]))\n      read = self.variator.read_input_registers(address_inpreg, 2)\n      converted = data_to_float32(read.registers)\n    else:\n      converted = []\n      # Reads 40 first addresses, and then extracts values from the length 40\n      #  list. Much more efficient, limits communication time.\n      read = self.variator.read_input_registers(0, 44)\n      for motor_adr in self.motor_addresses:\n        address_inpreg = int(str(motor_adr) + str(self.inpreg_addresses[\n         \"act_position\"]))\n\n        data = read.registers[address_inpreg:address_inpreg + 2]\n        converted.append(data_to_float32(data))\n    return converted\n\n  def read_speed(self, motor: Union[str, int]) -> list:\n    \"\"\"Reads speed of each motor.\"\"\"\n\n    if not motor == \"all\":\n      address_inpreg = int(str(motor) + str(self.inpreg_addresses[\n          \"act_speed\"]))\n      read = self.variator.read_input_registers(address_inpreg, 2)\n      converted = data_to_float32(read.registers)\n\n    else:\n      converted = []\n      read = self.variator.read_input_registers(0, 44)\n      for motor_adr in self.motor_addresses:\n        address_inpreg = int(str(motor_adr) + str(self.inpreg_addresses[\n          \"act_speed\"]))\n\n        data = read.registers[address_inpreg:address_inpreg + 2]\n        converted.append(data_to_float32(data))\n    return converted\n\n\nclass Koll(InOut):\n  \"\"\"Class to communicate to Kollmorgen devices via Crappy.\"\"\"\n\n  def __init__(self,\n               data: str = 'position',\n               axis: Union[str, int] = 'all',\n               speed: float = 360,\n               acc: float = 3600,\n               decc: float = 3600,\n               labels: list = None,\n               host: str = '192.168.0.109',\n               port: int = 502) -> None:\n    InOut.__init__(self)\n\n    self.data = data\n    self.axis = axis\n    self.speed = speed\n    self.acc = acc\n    self.decc = decc\n\n    if self.axis == \"all\":\n      default_label = [\"t(s)\"] + [str(i) for i in range(1, 4)]\n    else:\n      default_label = [\"t(s)\", str(self.axis)]\n\n      # NB: I have trouble defining default args for labels. It seems that if\n      #  kwargs doesn't contain \"labels\", I cannot put another default value\n      # than (\"t(s)\", \"1\") as defined in InOut parent class...\n\n    self.labels = default_label if labels is None else labels\n    self.variator = KollMorgenVariator(host=host, port=port)\n\n  def open(self) -> None:\n    pass\n\n  def get_data(self) -> Union[list, None]:\n    if self.data == \"speed\":\n      if not self.axis == \"all\":\n        ret = [time(), self.variator.read_speed(self.axis)]\n      else:\n        ret = [time()] + self.variator.read_speed(self.axis)\n\n    elif self.data == \"position\":\n      if not self.axis == \"all\":\n        ret = [time(), self.variator.read_position(self.axis)]\n      else:\n        ret = [time()] + self.variator.read_position(self.axis)\n    else:\n      return\n    return ret\n\n  def close(self) -> None:\n    pass\n", "repo_name": "ElsevierSoftwareX/SOFTX-D-21-00120", "sub_path": "crappy/inout/kollmorgen.py", "file_name": "kollmorgen.py", "file_ext": "py", "file_size_in_byte": 8155, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "25", "api": [{"api_name": "pymodbus.client.sync.ModbusTcpClient", "line_number": 12, "usage_type": "name"}, {"api_name": "_global.OptionalModule", "line_number": 12, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 16, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 16, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 21, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 21, "usage_type": "call"}, {"api_name": "pymodbus.client.sync.ModbusTcpClient", "line_number": 46, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 154, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 176, "usage_type": "name"}, {"api_name": "inout.InOut", "line_number": 197, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 202, "usage_type": "name"}, {"api_name": "inout.InOut.__init__", "line_number": 209, "usage_type": "call"}, {"api_name": "inout.InOut", "line_number": 209, "usage_type": "name"}, {"api_name": "time.time", "line_number": 235, "usage_type": "call"}, {"api_name": "time.time", "line_number": 237, "usage_type": "call"}, {"api_name": "time.time", "line_number": 241, "usage_type": "call"}, {"api_name": "time.time", "line_number": 243, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 232, "usage_type": "name"}]}
    +{"seq_id": "42234687155", "text": "#!/usr/bin/env python3\n\nfrom .imagenet import _ImageNetBase\nfrom typing import Literal, TypeVar\n\n\n__all__ = ['ImageNet64C', 'ImageNet64P', 'TinyImageNetC', 'TinyImageNetP']\n\n\nCDistortionCategoryType = Literal['main', 'extra']\nPDistortionCategoryType = Literal['noise', 'blur', 'weather', 'digital', 'validation',\n                                  'harder_noise', 'harder_noise_validation']\n# DistortionCategoryType = TypeVar('DistortionCategoryType', bound=str)\nDistortionCategoryType = TypeVar('DistortionCategoryType', CDistortionCategoryType, PDistortionCategoryType)\n\n\nclass _DownsampleImageNetC(_ImageNetBase[CDistortionCategoryType]):\n    _DISTORTIONS = {\n        'main': [],\n        'extra': [],\n    }\n\n\nclass _DownsampleImageNetP(_ImageNetBase[PDistortionCategoryType]):\n    _DISTORTIONS = {\n        'noise': ['gaussian_noise', 'impulse_noise'],\n        'blur': ['motion_blur', 'zoom_blur'],\n        'weather': ['brightness', 'snow'],\n        'digital': ['translate', 'rotate', 'tilt', 'scale'],\n        'validation': ['speckle_noise', 'gaussian_blur', 'spatter', 'shear'],\n        # 'harder_noise': ['harder_noise'],\n        # 'harder_noise_validation': ['harder_noise_validation'],\n    }\n\n\nclass _TinyImageNet:\n    def __len__(self) -> int:\n        return 10_000\n\n\nclass ImageNet64C(_DownsampleImageNetC):\n    _RESOURCES = {\n        'main': dict(\n            id='18x8idy9RESFkqpgnT46elpRjsGk3Vsg_',\n            file_name='main.tar',\n        ),\n        'extra': dict(\n            id='1ehu5KSeibDngSkcTFtN1_9avlN6qom3n',\n            file_name='extra.tar',\n        ),\n    }\n\n\nclass ImageNet64P(_DownsampleImageNetP):\n    _RESOURCES = {\n        'noise': dict(\n            id='181tBUE9RZWFUCYRm2GrBz7BGEnW9fFmA',\n            file_name='noise.tar',\n        ),\n        'blur': dict(\n            id='1BglhnU8XEzHB2VK5RJm64AsMgS5qqGYf',\n            file_name='blur.tar',\n        ),\n        'weather': dict(\n            id='1NbchhteXFetua2dA91vjoWHjtteB9pwd',\n            file_name='weather.tar',\n        ),\n        'digital': dict(\n            id='1Lz5kH4ufoMQoGuY7sLpnVMezZs5QVUo7',\n            file_name='digital.tar',\n        ),\n        'validation': dict(\n            id='1XjlmEFAp0CNEOjvmIOwxd4WikA3gpRUe',\n            file_name='validation.tar',\n        ),\n        'harder_noise': dict(\n            id='1LcH_k0esNtuYY_ELzMl6g-uWXGvYA5-_',\n            file_name='harder_noise.tar',\n        ),\n        'harder_noise_validation': dict(\n            id='1LLqTm-lIrqWN7vhfk9ZT73O8pF6Gt7nt',\n            file_name='harder_noise_validation.tar',\n        ),\n    }\n\n\nclass TinyImageNetC(_DownsampleImageNetC, _TinyImageNet):\n    _RESOURCES = {\n        'main': dict(\n            id='1iclQ0wFBqIs9lFIBDRFWHlLNags8P0_q',\n            file_name='main.tar',\n        ),\n        'extra': dict(\n            id='1qVIcHBdCP4Xiossv_LfoAOafC13_AHPw',\n            file_name='extra.tar',\n        ),\n    }\n\n\nclass TinyImageNetP(_DownsampleImageNetP, _TinyImageNet):\n    _RESOURCES = {\n        'noise': dict(\n            id='1NcZBYqNY963vMgyswcd78hnNVh6ztwYx',\n            file_name='noise.tar',\n        ),\n        'blur': dict(\n            id='1eZQYjjLgjeSwfTbnjOXktratOevmcyoX',\n            file_name='blur.tar',\n        ),\n        'weather': dict(\n            id='1QsA7UPgnuzqB8zFmKFfhztCgau4Marp6',\n            file_name='weather.tar',\n        ),\n        'digital': dict(\n            id='1W4clbDYR_G4qdHfaMiu9E0vU34ns0bBc',\n            file_name='digital.tar',\n        ),\n        'validation': dict(\n            id='1x7d14mRe456sD0G5QcZdJWatWMY8Bnfg',\n            file_name='validation.tar',\n        ),\n        'harder_noise': dict(\n            id='1bq7mv-p_dORgP2mHlN0COojZl9SwxPmI',\n            file_name='harder_noise.tar',\n        ),\n        'harder_noise_validation': dict(\n            id='1bXd1_ymIlzCSTRdIsup_0Ddu8LzEOPSH',\n            file_name='harder_noise_validation.tar',\n        ),\n    }\n", "repo_name": "ain-soph/trojanzoo", "sub_path": "trojanvision/utils/datasets/prototype/downsample_imagenet.py", "file_name": "downsample_imagenet.py", "file_ext": "py", "file_size_in_byte": 3885, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 254, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.Literal", "line_number": 10, "usage_type": "name"}, {"api_name": "typing.Literal", "line_number": 11, "usage_type": "name"}, {"api_name": "typing.TypeVar", "line_number": 14, "usage_type": "call"}, {"api_name": "imagenet._ImageNetBase", "line_number": 17, "usage_type": "name"}, {"api_name": "imagenet._ImageNetBase", "line_number": 24, "usage_type": "name"}]}
    +{"seq_id": "70462562947", "text": "from selenium import webdriver\n\nbrowser = webdriver.Chrome(executable_path=\"C:/Users/Kazut/Desktop/chromedriver_win32/chromedriver.exe\")\nurl = 'http://wav.tv/actresses/'\n\nPAGER_NEXT = \"a.m-pagination--next.is-last.step\"  # Next button\nPOSTS = \"div.m-actress-wrap\"  # このdivは名前と画像をまとめたもの\nACTRESS_NAME = \".m-actress--title\"  # actresses' names\nIMAGE = \".m-actress--thumbnail-img img\"  # actresses' images\n\nbrowser.get(url)\nposts = browser.find_elements_by_css_selector(POSTS)  # 女優divのエレメントを探す\nprint(posts)", "repo_name": "knose24/hentai_hakase", "sub_path": "len_function_test.py", "file_name": "len_function_test.py", "file_ext": "py", "file_size_in_byte": 555, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "selenium.webdriver.Chrome", "line_number": 3, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 3, "usage_type": "name"}]}
    +{"seq_id": "32089669505", "text": "from django.db import models\nfrom django.forms import ModelForm\nfrom django.contrib.auth.models import User\nfrom django import forms\n\n\n\n\n# Create your models here.\nclass Due(models.Model):\n    person = models.ForeignKey(User, default=1, related_name='person', on_delete=models.CASCADE)\n    amount = models.IntegerField()\n    description = models.CharField(null=True, blank=True, max_length=30)\n    to = models.ForeignKey(User, default=1, related_name='to', on_delete=models.CASCADE)\n    status = models.BooleanField(default=False)\n    query = models.DateField(null=True, blank=True)\n    payment = models.DateField(null=True, blank=True)\n\n    def __str__(self):\n        return self.person.username\n\n\nclass DueForm(ModelForm):\n    class Meta:\n        model = Due\n        fields = ['to','person', 'amount', 'description', 'query']\n        labels  = {\n        'to':\"I am\",\n        'person':'Dude who owes me', \n        'amount':'Amount', \n        'description':'Description', \n        'query':\"Date\"\n        }\n        widgets = {\n        'to': forms.Select(attrs={'class':'form-control'}),\n        'person': forms.Select(attrs={'class':'form-control'}),\n        'amount': forms.NumberInput(attrs={'class':'form-control'}),\n        'description': forms.TextInput(attrs={'class':'form-control'}),\n        'query': forms.HiddenInput(),\n        } ", "repo_name": "nelsonksh/Records", "sub_path": "website/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 1339, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.db.models.Model", "line_number": 10, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 10, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 11, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User", "line_number": 11, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 11, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 11, "usage_type": "attribute"}, {"api_name": "django.db.models.IntegerField", "line_number": 12, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 12, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 13, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 13, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 14, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User", "line_number": 14, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 14, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 14, "usage_type": "attribute"}, {"api_name": "django.db.models.BooleanField", "line_number": 15, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 15, "usage_type": "name"}, {"api_name": "django.db.models.DateField", "line_number": 16, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 16, "usage_type": "name"}, {"api_name": "django.db.models.DateField", "line_number": 17, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 17, "usage_type": "name"}, {"api_name": "django.forms.ModelForm", "line_number": 23, "usage_type": "name"}, {"api_name": "django.forms.Select", "line_number": 35, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 35, "usage_type": "name"}, {"api_name": "django.forms.Select", "line_number": 36, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 36, "usage_type": "name"}, {"api_name": "django.forms.NumberInput", "line_number": 37, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 37, "usage_type": "name"}, {"api_name": "django.forms.TextInput", "line_number": 38, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 38, "usage_type": "name"}, {"api_name": "django.forms.HiddenInput", "line_number": 39, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 39, "usage_type": "name"}]}
    +{"seq_id": "34498424626", "text": "\"\"\"\nDefines a simple Bayesian linear regression model.\n\"\"\"\n\nimport pyro\nimport pyro.distributions as dist\nfrom pyro.nn import PyroModule, PyroSample\n\n\nclass RegressionModel(PyroModule):\n    def __init__(self):\n        super().__init__()\n        self.coef = PyroSample(dist.Normal(0., 2.))\n        self.bias = PyroSample(dist.Normal(0., 2.))\n\n    def forward(self, X, y=None):\n        sigma = pyro.sample(\"sigma\", dist.Uniform(0., 10.))\n        y_hat = self.coef * X + self.bias\n\n        with pyro.plate(\"data\", X.shape[0]):\n            obs = pyro.sample(\"obs\", dist.Normal(y_hat.squeeze(-1), sigma), obs=y)\n\n        return y_hat\n", "repo_name": "standardgalactic/bayesian-erp", "sub_path": "berp/models/basic.py", "file_name": "basic.py", "file_ext": "py", "file_size_in_byte": 629, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "25", "api": [{"api_name": "pyro.nn.PyroModule", "line_number": 10, "usage_type": "name"}, {"api_name": "pyro.nn.PyroSample", "line_number": 13, "usage_type": "call"}, {"api_name": "pyro.distributions.Normal", "line_number": 13, "usage_type": "call"}, {"api_name": "pyro.distributions", "line_number": 13, "usage_type": "name"}, {"api_name": "pyro.nn.PyroSample", "line_number": 14, "usage_type": "call"}, {"api_name": "pyro.distributions.Normal", "line_number": 14, "usage_type": "call"}, {"api_name": "pyro.distributions", "line_number": 14, "usage_type": "name"}, {"api_name": "pyro.sample", "line_number": 17, "usage_type": "call"}, {"api_name": "pyro.distributions.Uniform", "line_number": 17, "usage_type": "call"}, {"api_name": "pyro.distributions", "line_number": 17, "usage_type": "name"}, {"api_name": "pyro.plate", "line_number": 20, "usage_type": "call"}, {"api_name": "pyro.sample", "line_number": 21, "usage_type": "call"}, {"api_name": "pyro.distributions.Normal", "line_number": 21, "usage_type": "call"}, {"api_name": "pyro.distributions", "line_number": 21, "usage_type": "name"}]}
    +{"seq_id": "2642535412", "text": "import torch\nimport gc\nfrom PIL import Image\nfrom pathlib import Path\nfrom prompts import prompt_getter\nfrom diffusers import StableDiffusionDepth2ImgPipeline\n\n\nclass ImageGenerator:\n    def __init__(self):\n        self.pipe = StableDiffusionDepth2ImgPipeline.from_pretrained(\n            \"stabilityai/stable-diffusion-2-depth\",\n            torch_dtype=torch.float16,\n        ).to(\"cuda\")\n\n    def generate_image(self, original_image, prompt):\n        torch.cuda.empty_cache()\n        gc.collect()\n\n        strength = 0.45\n        new_image =self.pipe(prompt=\"A photo, \" + prompt, image=original_image,\n                             negative_prompt=\"Cartoon, Disfigured, blurry, unrealistic\", strength=strength).images[0]\n\n        return new_image\n\n    def generate_variations(self, original_image, image_file_name, run_over_existing_images=False):\n\n        image_dir = Path.cwd() / 'dataset_images' / image_file_name\n        image_dir.mkdir(exist_ok=True)\n\n        for transformation, prompt in prompt_getter.items():\n            transformed_image = self.generate_image(original_image, prompt)\n\n            transformed_image_path = image_dir / f'{transformation}.png'\n\n            if transformed_image_path.exists() and not run_over_existing_images:\n                continue\n\n            transformed_image.save(transformed_image_path)\n\n    def generate_all_images(self):\n\n        original_images_path = Path.cwd() / 'kaggle_images'\n\n        # Iterate over files and directories in the kaggle_images directory\n        for item in original_images_path.iterdir():\n\n            if item.is_file():\n                # Load the image using PIL\n                original_image = Image.open(item.resolve()).convert(\"RGB\")\n                self.generate_variations(original_image, item.name, run_over_existing_images=True)\n\n            else:\n                raise IsADirectoryError(\"Should only find images_orig in the kaggle_images directory\")\n\n\nif __name__ == \"__main__\":\n    image_gen = ImageGenerator()\n    image_gen.generate_all_images()\n", "repo_name": "ozgranit/traffic-diffusion", "sub_path": "diffusionImageGenerator/create_images.py", "file_name": "create_images.py", "file_ext": "py", "file_size_in_byte": 2030, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "diffusers.StableDiffusionDepth2ImgPipeline.from_pretrained", "line_number": 11, "usage_type": "call"}, {"api_name": "diffusers.StableDiffusionDepth2ImgPipeline", "line_number": 11, "usage_type": "name"}, {"api_name": "torch.float16", "line_number": 13, "usage_type": "attribute"}, {"api_name": "torch.cuda.empty_cache", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 17, "usage_type": "attribute"}, {"api_name": "gc.collect", "line_number": 18, "usage_type": "call"}, {"api_name": "pathlib.Path.cwd", "line_number": 28, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 28, "usage_type": "name"}, {"api_name": "prompts.prompt_getter.items", "line_number": 31, "usage_type": "call"}, {"api_name": "prompts.prompt_getter", "line_number": 31, "usage_type": "name"}, {"api_name": "pathlib.Path.cwd", "line_number": 43, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 43, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 50, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 50, "usage_type": "name"}]}
    +{"seq_id": "13020221759", "text": "from django.contrib import admin\nfrom django.urls import path,re_path\nfrom Myapp.views import *\nurlpatterns = [\n    path('admin/', admin.site.urls),\n    path('project_list/',project_list),\n    re_path('del_project/(?P.+)/',del_project), # 添加删除项目的url\n    path('add_project/',add_project),\n    path('save_project/',save_project), #保存项目\n    path('project_data/', project_data),  # 获取项目所有数据\n    path('',project_list), # 进入项目首页\n\n    path('login/',login),\n    path('sign_in/',sign_in),\n    path('sign_up/',sign_up),\n    path('accounts/login/',login),\n    path('logout/',logout),\n    path('reset_password/',reset_password),\n    path('send_email_pwd/',send_email_pwd),\n\n\n    re_path('mock_list/(?P.+)/', mock_list),  # 进入项目详情页(mock列表页)\n    re_path('add_mock/(?P.+)/', add_mock),  # 新增单元\n    re_path('del_mock/(?P.+)/', del_mock),  # 删除单元\n    path('save_mock/',save_mock), #保存单元\n    path('get_mock/',get_mock), #获取单元\n    re_path('mock_on/(?P.+)/',mock_on), #启用单元\n    re_path('mock_off/(?P.+)/',mock_off),#禁用单元\n    ##### 测试调试\n    # path('demo_span/',demo_span), # 调试用接口\n    re_path('server_on/(?P.+)/', server_on),  # 启用服务\n    re_path('server_off/(?P.+)/', server_off),  # 禁用服务\n    path('get_catch_log/',get_catch_log),\n    path('import_catch/', import_catch),  # 导入服务\n]\n", "repo_name": "rainbowzhouj/AppMock", "sub_path": "AppMock/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 1501, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.urls.path", "line_number": 5, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 5, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 5, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "django.urls.re_path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 14, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 16, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 17, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 18, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 19, "usage_type": "call"}, {"api_name": "django.urls.re_path", "line_number": 22, "usage_type": "call"}, {"api_name": "django.urls.re_path", "line_number": 23, "usage_type": "call"}, {"api_name": "django.urls.re_path", "line_number": 24, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 25, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 26, "usage_type": "call"}, {"api_name": "django.urls.re_path", "line_number": 27, "usage_type": "call"}, {"api_name": "django.urls.re_path", "line_number": 28, "usage_type": "call"}, {"api_name": "django.urls.re_path", "line_number": 31, "usage_type": "call"}, {"api_name": "django.urls.re_path", "line_number": 32, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 33, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 34, "usage_type": "call"}]}
    +{"seq_id": "34161432187", "text": "import os\nimport glob\nimport pandas as pd\nimport xml.etree.ElementTree as ET\nimport argparse\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--folder',\n\t\t\t\t\t\t\t\t\t\t'-f',\n\t\t\t\t\t\t\t\t\t\thelp='Folder input path containing images that will be augmented. Make sure the folder has both a test and train path',\n\t\t\t\t\t\t\t\t\t\trequired=True,\n\t\t\t\t\t\t\t\t\t\ttype=str\n\t\t\t\t\t\t\t\t\t\t)\n\nparser.add_argument('--dest',\n\t\t\t\t\t\t\t\t\t\t'-d',\n\t\t\t\t\t\t\t\t\t\thelp='Folder destination for augmented image. (default: [folder input path])',\n\t\t\t\t\t\t\t\t\t\ttype=str,\n\t\t\t\t\t\t\t\t\t\tdefault=None\n\t\t\t\t\t\t\t\t\t\t)\n\nparser.add_argument('--pixel',\n\t\t\t\t\t\t\t\t\t\t'-p',\n\t\t\t\t\t\t\t\t\t\thelp='Convert to pixel format. (default: decimal format)',\n\t\t\t\t\t\t\t\t\t\taction='store_true',\n\t\t\t\t\t\t\t\t\t\tdefault=None\n\t\t\t\t\t\t\t\t\t\t)\t\n\nargs = parser.parse_args()\n\nif not args.dest:\n\targs.dest = args.folder\n\nimageIds = {}\n\ndef convert_to_decimal(size, value):\n\tif args.pixel: return value\n\t# return float(\"%.2f\" % round((value/size), 2))\n\treturn float(value/size)\n\t\ndef xml_to_csv(path):\n    xml_list = []\n    for xml_file in glob.glob(path + '/*.xml'):\n        tree = ET.parse(xml_file)\n        root = tree.getroot()\n        for member in root.findall('object'):\n            width = int(root.find('size')[0].text)\n            height = int(root.find('size')[1].text)\n\n            imageid = root.find('filename').text\n            source = 'labelimg'\n            labelname = '/m/06nrc'\n            confidence = 1\n            xmin = convert_to_decimal(width, int(member[4][0].text))\n            xmax = convert_to_decimal(width, int(member[4][2].text))\n            ymin = convert_to_decimal(height, int(member[4][1].text))\n            ymax = convert_to_decimal(height, int(member[4][3].text))\n            isoccluded = 0\n            istruncated = int(member[2].text)\n            isgroupof = 0\n            isdepiction = 0\n            isinside = 0\n            id = labelname\n            classname = member[0].text\n\n            if labelname not in imageIds:\n              imageIds[labelname] = classname\n\n            value = (imageid, source, labelname, confidence, xmin, xmax, ymin, ymax, isoccluded, istruncated, isgroupof, isdepiction, isinside, id, classname)\n            xml_list.append(value)\n    column_name = [\n\t\t\t'ImageID',\t'Source',\t'LabelName',\t'Confidence',\t'XMin',\t'XMax',\t'YMin',\t'YMax',\t'IsOccluded',\t'IsTruncated',\t'IsGroupOf',\t'IsDepiction',\t'IsInside',\t'id',\t'ClassName'\n\t\t]\n    xml_df = pd.DataFrame(xml_list, columns=column_name)\n    return xml_df\n\n\ndef main():\n\t'''\n    for directory in ['train','testing']:\n        image_path = os.path.join(os.getcwd(), 'images/{}'.format(directory).format(directory))\n        xml_df = xml_to_csv(image_path)\n        xml_df.to_csv('data/{}_labels.csv'.format(directory), index=None)\n        print('Successfully converted xml to csv.')\n\t''' \n\t# Train Annotations\n\timage_path = os.path.join(os.getcwd(), f\"{args.folder}/train\")\n\txml_df = xml_to_csv(image_path)\n\txml_df.to_csv(f\"{args.dest}/sub-train-annotations-bbox.csv\", index=None)\n\n\t# Test Annotations\n\timage_path = os.path.join(os.getcwd(), f\"{args.folder}/test\")\n\txml_df = xml_to_csv(image_path)\n\txml_df.to_csv(f\"{args.dest}/sub-test-annotations-bbox.csv\",index=None)\n\n\t# Class Descriptions\n\tclass_description_column_name = [\n\t\t\t'classid',\t'classname'\n\t]\n\t\n\t# class_description_column_name = []\n\tclass_description_xml_list = []\n\tfor key in imageIds:\n\t\t# class_description_column_name = [key, imageIds[key]]\n\t\tclass_description_xml_list.append((key, imageIds[key]))\n    \n\tclass_description_xml_df = pd.DataFrame(class_description_xml_list, columns=class_description_column_name)\n\tclass_description_xml_df.to_csv(f\"{args.dest}/class-descriptions-boxable.csv\",index=None)\nmain()", "repo_name": "ahadcove/TrashBot", "sub_path": "ML/utils/xml2csv.py", "file_name": "xml2csv.py", "file_ext": "py", "file_size_in_byte": 3681, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "25", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 7, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 44, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 45, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 45, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 88, "usage_type": "call"}, {"api_name": "os.path", "line_number": 88, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 88, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 93, "usage_type": "call"}, {"api_name": "os.path", "line_number": 93, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 93, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 108, "usage_type": "call"}]}
    +{"seq_id": "41904683266", "text": "import os\n\nimport maya.cmds as cmds\nimport maya.mel as mel\nimport webrImport as web\n\n#\n# web\n# place = web.mod('atom_placement_lib')\nmisc = web.mod( 'atom_miscellaneous_lib' )\nui = web.mod( 'atom_ui_lib' )\n\n# place Clusters on CV derived from 'curve' variable\n# curve\n# curve from which to make clusters\n# clstrSuffix\n# suffix for cluster\n\n\ndef clstrOnCV( curve, clstrSuffix ):\n    clstr = []\n    i = 0\n    num = cmds.getAttr( ( curve + '.cv[*]' ) )\n    for item in num:\n        c = cmds.cluster( ( curve + '.cv[' + str( i ) + ']' ), n = ( clstrSuffix + str( i ) ), envelope = True )[1]\n        i = i + 1\n        clstr.append( c )\n    return clstr\n\n# places curve on points derived from selection\n\n\ndef curve( name, points ):\n    '''\\n\n    name = name...\n    points = list of objects from which xfrom can be derived\n    '''\n    pos = []\n    if len( points ) > 2:\n        for item in points:\n            x = cmds.xform( item, q = True, t = True, ws = True )\n            pos.append( x )\n        curve = cmds.curve( p = pos, name = ( name ), d = 2 )\n        return curve\n    else:\n        mel.eval( 'warning \\\"' + '////... select 3 objects ...////' + '\\\";' )\n        return None\n\n# place joints on positions derived from selection\n# order(boolean) = placement order\n# 0 = first to last selected object\n# 1 = last to first selected object\n# jntSuffix\n# suffix for joints\n\n\ndef joint( order, jntSuffix, pad = 2, rpQuery = True ):\n    sel = cmds.ls( sl = True, fl = True, l = True )\n    if len( sel ) > 0:\n        if order == 0:\n            jnt = []\n            cmds.select( cl = True )\n            i = 1\n            for item in sel:\n                if rpQuery == True:\n                    pos = cmds.xform( item, q = True, rp = True, ws = True )\n                else:\n                    pos = cmds.xform( item, q = True, t = True, ws = True )\n                plc = cmds.joint( name = ( jntSuffix + '_' + str( ( '%0' + str( pad ) + 'd' ) % ( i ) ) ), p = pos )\n                jnt.append( plc )\n                i = i + 1\n            cmds.select( sel )\n            return jnt\n        elif order == 1:\n            rvrsSel = []\n            for i in range( len( sel ), 0, -1 ):  # (reverse order loop - range(size of(array),stop@,increment by)\n                rvrsSel.append( sel[i - 1] )\n            sel = list( rvrsSel )\n            jnt = []\n            cmds.select( cl = True )\n            for item in sel:\n                if rpQuery == True:\n                    pos = cmds.xform( item, q = True, rp = True, ws = True )\n                else:\n                    pos = cmds.xform( item, q = True, t = True, ws = True )\n                plc = cmds.joint( name = ( jntSuffix + '#' ), p = pos )\n                jnt.append( plc )\n            cmds.select( sel )\n            return jnt\n    else:\n        mel.eval( 'warning \\\"' + '////... select at least one object ...////' + '\\\";' )\n        return None\n\n# place locators on positions derived from selection\n# locSuffix\n# suffix for spaceLocators\n\n\ndef loc( locSuffix, obj = None ):\n    sel = []\n    if obj == None:\n        sel = cmds.ls( sl = True, fl = True, l = True )\n    else:\n        sel.append( obj )\n    if len( sel ) > 0:\n        loc = []\n        cmds.select( cl = True )\n        for item in sel:\n            pos = cmds.xform( item, q = True, t = True, ws = True )\n            rot = cmds.xform( item, q = True, ro = True, ws = True )\n            n = cmds.spaceLocator( name = locSuffix )[0]\n            cmds.xform( n, t = ( pos ), ro = ( rot ) )\n            loc.append( n )\n        cmds.select( sel )\n        # returns list\n        return loc\n    else:\n        mel.eval( 'warning \\\"' + '////... select at least one object ...////' + '\\\";' )\n        return None\n\n# place nulls on positions derived from selection\n# nllSuffix\n# suffix for null\n\n\ndef null( nllSuffix, order = None ):\n    sel = cmds.ls( sl = True, fl = True, l = True )\n    if len( sel ) > 0:\n        null = []\n        cmds.select( cl = True )\n        for item in sel:\n            pos = cmds.xform( item, q = True, rp = True, ws = True )\n            rot = cmds.xform( item, q = True, ro = True, ws = True )\n            n = cmds.group( name = nllSuffix, em = True )\n            if order != None:\n                cmds.xform( n, roo = order )\n            cmds.xform( n, t = pos, ro = rot )\n            null.append( n )\n        cmds.select( sel )\n        return null\n\n    else:\n        mel.eval( 'warning \\\"' + '////... select at least one object ...////' + '\\\";' )\n        return None\n\n\ndef circle( name, obj, shape, size, color, sections = 8, degree = 1, normal = ( 0, 0, 1 ), orient = True ):\n    '''\n    place circle\n    name     = name of circle\n    obj      = object whose position to match\n    shape    = shape of circle to import(name of text file)\n    sections = number of CVs\n    degree   = Linear(1) or Cubic(3) ,has to be int\n    normal   = plane on which to build circle\n    '''\n    path = os.path.expanduser( '~' ) + '/GitHub/controlShapes/'\n    Circle = []\n    if type( obj ) != list:\n        pos = cmds.xform( obj, q = True, rp = True, ws = True )\n        rot = cmds.xform( obj, q = True, ro = True, ws = True )\n        n = cmds.circle( name = name, center = ( 0, 0, 0 ), normal = normal, sweep = 360, radius = 1, degree = degree, sections = sections, constructionHistory = 1 )[0]\n        cmds.xform( n, t = pos )\n        if orient:\n            cmds.xform( n, ro = rot )\n        else:\n            print( 'no orient' )\n        Circle.append( n )\n        # import shape\n        cmds.select( n )\n        ui.importCurveShape( shape, path, size, color )\n        return Circle\n    elif len( obj ) > 0:\n        for item in obj:\n            pos = cmds.xform( item, q = True, rp = True, ws = True )\n            rot = cmds.xform( item, q = True, ro = True, ws = True )\n            n = cmds.circle( name = name, center = ( 0, 0, 0 ), normal = normal, sweep = 360, radius = 1, degree = degree, sections = sections, constructionHistory = 1 )[0]\n            cmds.xform( n, t = pos, ro = rot )\n            Circle.append( n )\n            cmds.select( n )\n            ui.importCurveShape( shape, path, size, color )\n        return Circle\n\n    else:\n        mel.eval( 'warning \\\"' + '////... No object specified under \\'obj\\' variable ...////' + '\\\";' )\n        return None\n\n# Version 2 (no selection required, state object(s) to match as variable \"obj\")\n# place nulls on positions derived from selection\n# nllSuffix\n# suffix for null\n\n\ndef null2( nllSuffix, obj, orient = True ):\n    null = []\n    if type( obj ) != list:\n        pos = cmds.xform( obj, q = True, rp = True, ws = True )\n        rot = cmds.xform( obj, q = True, ro = True, ws = True )\n        n = cmds.group( name = nllSuffix, em = True )\n        cmds.xform( n, t = pos, ro = rot, ws = True )\n        if orient == False:\n            cmds.xform( n, ro = ( 0, 0, 0 ) )\n        null.append( n )\n        return null\n    elif len( obj ) > 0:\n        for item in obj:\n            pos = cmds.xform( item, q = True, rp = True, ws = True )\n            rot = cmds.xform( item, q = True, ro = True, ws = True )\n            n = cmds.group( name = nllSuffix, em = True )\n            cmds.xform( n, t = pos, ro = rot, ws = True )\n            if orient == False:\n                cmds.xform( n, ro = ( 0, 0, 0 ) )\n            null.append( n )\n        return null\n    else:\n        mel.eval( 'warning \\\"' + '////... \\\"obj\\\" variable must be a single object or list type ...////' + '\\\";' )\n        return None\n\n# places controller object(controller, controllerOffset, group)\n\n\nclass Controller():\n    # initialize\n\n    def __init__( self, name, obj, orient = True, shape = 'diamond_ctrl', size = 1, color = 8, sections = 8, degree = 1, normal = ( 0, 0, 1 ), setChannels = True, groups = False ):\n        self.name = name\n        self.obj = obj\n        self.orient = orient\n        self.shape = shape\n        self.size = size\n        self.color = color\n        self.sections = sections\n        self.degree = degree\n        self.normal = normal\n        self.setChannels = setChannels\n        self.groups = groups\n\n    # conditions\n    def condition( self ):\n        if type( self.obj ) == list:\n            if len( self.obj ) == 1:\n                self.createController()\n            else:\n                mel.eval( 'warning \\\"' + '////... \\'obj\\' variable has to be only item in list ...////' + '\\\";' )\n        elif len( self.obj ) > 0:\n            self.createController()\n        else:\n            mel.eval( 'warning \\\"' + '////... \\'obj\\' variable can only be one object...////' + '\\\";' )\n\n    # create\n    def createController( self ):\n        ct = circle( self.name, self.obj, self.shape, self.size * ( 0.3 ), self.color, self.sections, self.degree, self.normal )[0]\n        ctO = circle( self.name + '_Offset', self.obj, self.shape, self.size * ( 0.25 ), self.color, self.sections, self.degree, self.normal )[0]\n        gp = null2( self.name + '_Grp', self.obj )[0]\n        if self.groups == True:\n            ctgp = null2( self.name + '_CtGrp', self.obj )[0]\n            topgp = null2( self.name + '_TopGrp', self.obj )[0]\n            cmds.parent( ct, ctgp )\n            cmds.parent( ctgp, topgp )\n            if self.setChannels == True:\n                misc.setChannels( ctgp, translate = [False, True], rotate = [False, True], scale = [True, False], visibility = [True, False, False], other = [False, True] )\n                misc.setChannels( topgp, translate = [False, True], rotate = [False, True], scale = [True, False], visibility = [True, False, False], other = [False, True] )\n\n        # parent\n        cmds.parent( gp, ctO )\n        cmds.parent( ctO, ct )\n        # align orient query\n        if self.orient == False:\n            if self.groups == True:\n                cmds.setAttr( topgp + '.rotate', 0, 0, 0 )\n            else:\n                cmds.setAttr( ct + '.rotate', 0, 0, 0 )\n        elif self.orient != False and self.orient != True:\n            rot = cmds.xform( self.orient, query = True, ws = True, ro = True )\n            if self.groups == True:\n                cmds.setAttr( topgp + '.rotate', rot[0], rot[1], rot[2] )\n            else:\n                cmds.setAttr( ct + '.rotate', rot[0], rot[1], rot[2] )\n        # attrs\n        # ct\n        attr = 'Offset_Vis'\n        misc.addAttribute( ct, 'Offset_Vis', 0, 1, False, 'long' )\n        # ctO\n        cmds.connectAttr( ct + '.' + attr, ctO + '.visibility' )\n        # gp\n        # Done\n        cmds.select( cl = True )\n        if self.setChannels == True:\n            misc.setChannels( ct, translate = [False, True], rotate = [False, True], scale = [True, False], visibility = [True, False, False], other = [False, True] )\n            misc.setChannels( ctO, translate = [False, True], rotate = [False, True], scale = [True, False], visibility = [False, False, False], other = [False, True] )\n            misc.setChannels( gp, translate = [False, True], rotate = [False, True], scale = [True, False], visibility = [True, False, False], other = [False, True] )\n            cmds.setAttr( ctO + '.visibility', cb = False )\n            i = cmds.getAttr( ctO + '.visibility', cb = True )\n\n        if self.groups == True:\n            return topgp, ctgp, ct, ctO, gp\n        else:\n            return ct, ctO, gp\n\n\ndef twoJointPV( name, ik, distance = 1, constrain = True, size = 1 ):\n    sj = cmds.ikHandle( ik, q = True, sj = True )\n    Gp = null2( name + '_PvGrp', sj, False )[0]\n    Pv = circle( name + '_PV', sj, 'diamond_ctrl', size * 1, 17, 8, 1, ( 0, 0, 1 ) )[0]\n    cmds.parent( Pv, Gp )\n    X = cmds.getAttr( ik + '.poleVectorX' )\n    Y = cmds.getAttr( ik + '.poleVectorY' )\n    Z = cmds.getAttr( ik + '.poleVectorZ' )\n    cmds.setAttr( Pv + '.translateX', distance * X )\n    cmds.setAttr( Pv + '.translateY', distance * Y )\n    cmds.setAttr( Pv + '.translateZ', distance * Z )\n    if constrain == True:\n        cmds.poleVectorConstraint( Pv, ik )\n    return Gp, Pv\n\n\ndef controllerDownChain( root, name, pad = 2, base = None, parent = None, shape = 'loc_ctrl',\n                        color = 17, size = 10, groups = True, orient = False, suffix = None,\n                        scale = True, setChannel = True, clone = False, fk = False ):\n    '''\\n\n\n    '''\n    result = []\n    control_chain = []\n    clone_chain = []\n    cmds.select( root, hi = True )\n    sel = cmds.ls( sl = True, typ = 'transform' )\n    i = 1\n    for obj in sel:\n        if pad > 0:\n            num = '_' + str( ( '%0' + str( pad ) + 'd' ) % ( i ) )\n        else:\n            num = ''\n        # SUFFIX\n        if suffix != None:\n            ctrl = Controller( name + num + '_' + suffix, obj, shape = shape, color = color, size = size, groups = groups, orient = orient )\n        else:\n            ctrl = Controller( name + num, obj, shape = shape, color = color, size = size, groups = groups, orient = orient )\n        Control = ctrl.createController()\n        control_chain.append( Control )\n        # CLONE\n        if clone == False:\n            cmds.parentConstraint( Control[4], obj, mo = True )\n        else:\n            clone_parent = null2( Control[2] + '_CloneTopGrp', obj, orient )[0]\n            clone_child = null2( Control[2] + '_CloneCtGrp', obj, orient )[0]\n            clone_offset = null2( Control[2] + '_CloneOffstGrp', obj, orient )[0]\n            cmds.parentConstraint( clone_offset, obj, mo = True )\n            clone_set = [clone_parent, clone_child, clone_offset]\n            clone_chain.append( clone_set )\n            cmds.parent( clone_offset, clone_child )\n            cmds.parent( clone_child, clone_parent )\n            misc.hijack( clone_offset, Control[3], scale = False, visibility = False )\n            misc.hijack( clone_child, Control[2], scale = False, visibility = False )\n        # BASE\n        if base != None:\n            cmds.parentConstraint( base, Control[0], mo = True )\n        # PARENT\n        if parent != None:\n            cmds.parent( Control[0], parent )\n        # SETCHANNEL\n        if setChannel != True:\n            for item in Control:\n                misc.setChannels( item, translate = [False, True], rotate = [False, True], scale = [False, True], visibility = [True, False, False] )\n        # SCALE\n        if scale == True:\n            if clone == False:\n                misc.hijackScale( obj, Control[2] )\n            else:\n                misc.hijackScale( obj, clone_child )\n                misc.hijackScale( clone_child, Control[2] )\n                misc.scaleUnlock( Control[2] )\n        i = i + 1\n    # FK\n    if fk == True:\n        num = len( control_chain )\n        j = 1\n        for item in control_chain:\n            if num > j:\n                cmds.parent( control_chain[j][0], item[2] )\n                cmds.parentConstraint( item[3], control_chain[j][0], mo = True )\n                if clone == True:\n                    cmds.parent( clone_chain[j][0], clone_chain[j - 1][2] )\n            j = j + 1\n    return control_chain, clone_chain\n\n'''\n# likely isn't used anywhere\ndef match(obj1, obj2, p=True, r=True):\n    if p == True:\n        pos1 = cmds.xform(obj1, q=True, t=True, ws=True)\n        print 'from', pos1\n        pos2 = cmds.xform(obj2, q=True, t=True, ws=True)\n        print 'to', pos2\n        cmds.xform(obj2, t=(pos1))\n        pos2 = cmds.xform(obj2, q=True, t=True, ws=True)\n        print 'to', pos2\n    if r == True:\n        rot = cmds.xform(obj1, q=True, ro=True, ws=True)\n        cmds.xform(obj2, ro=(rot))\n'''\n", "repo_name": "boochos/work", "sub_path": "atom_placement_lib.py", "file_name": "atom_placement_lib.py", "file_ext": "py", "file_size_in_byte": 15402, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "webrImport.mod", "line_number": 10, "usage_type": "call"}, {"api_name": "webrImport.mod", "line_number": 11, "usage_type": "call"}, {"api_name": "maya.cmds.getAttr", "line_number": 23, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 23, "usage_type": "name"}, {"api_name": "maya.cmds.cluster", "line_number": 25, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 25, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 41, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 41, "usage_type": "name"}, {"api_name": "maya.cmds.curve", "line_number": 43, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 43, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 46, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 46, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 58, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 58, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 62, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 62, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 66, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 66, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 68, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 68, "usage_type": "name"}, {"api_name": "maya.cmds.joint", "line_number": 69, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 69, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 72, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 72, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 80, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 80, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 83, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 83, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 85, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 85, "usage_type": "name"}, {"api_name": "maya.cmds.joint", "line_number": 86, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 86, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 88, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 88, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 91, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 91, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 102, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 102, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 107, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 107, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 109, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 109, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 110, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 110, "usage_type": "name"}, {"api_name": "maya.cmds.spaceLocator", "line_number": 111, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 111, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 112, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 112, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 114, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 114, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 118, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 118, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 127, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 127, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 130, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 130, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 132, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 132, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 133, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 133, "usage_type": "name"}, {"api_name": "maya.cmds.group", "line_number": 134, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 134, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 136, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 136, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 137, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 137, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 139, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 139, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 143, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 143, "usage_type": "name"}, {"api_name": "os.path.expanduser", "line_number": 157, "usage_type": "call"}, {"api_name": "os.path", "line_number": 157, "usage_type": "attribute"}, {"api_name": "maya.cmds.xform", "line_number": 160, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 160, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 161, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 161, "usage_type": "name"}, {"api_name": "maya.cmds.circle", "line_number": 162, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 162, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 163, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 163, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 165, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 165, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 170, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 170, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 175, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 175, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 176, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 176, "usage_type": "name"}, {"api_name": "maya.cmds.circle", "line_number": 177, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 177, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 178, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 178, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 180, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 180, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 185, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 185, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 197, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 197, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 198, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 198, "usage_type": "name"}, {"api_name": "maya.cmds.group", "line_number": 199, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 199, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 200, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 200, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 202, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 202, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 207, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 207, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 208, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 208, "usage_type": "name"}, {"api_name": "maya.cmds.group", "line_number": 209, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 209, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 210, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 210, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 212, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 212, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 216, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 216, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 244, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 244, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 248, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 248, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 258, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 258, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 259, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 259, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 265, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 265, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 266, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 266, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 270, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 270, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 272, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 272, "usage_type": "name"}, {"api_name": "maya.cmds.xform", "line_number": 274, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 274, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 276, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 276, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 278, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 278, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 284, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 284, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 287, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 287, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 292, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 292, "usage_type": "name"}, {"api_name": "maya.cmds.getAttr", "line_number": 293, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 293, "usage_type": "name"}, {"api_name": "maya.cmds.ikHandle", "line_number": 302, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 302, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 305, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 305, "usage_type": "name"}, {"api_name": "maya.cmds.getAttr", "line_number": 306, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 306, "usage_type": "name"}, {"api_name": "maya.cmds.getAttr", "line_number": 307, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 307, "usage_type": "name"}, {"api_name": "maya.cmds.getAttr", "line_number": 308, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 308, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 309, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 309, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 310, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 310, "usage_type": "name"}, {"api_name": "maya.cmds.setAttr", "line_number": 311, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 311, "usage_type": "name"}, {"api_name": "maya.cmds.poleVectorConstraint", "line_number": 313, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 313, "usage_type": "name"}, {"api_name": "maya.cmds.select", "line_number": 326, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 326, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 327, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 327, "usage_type": "name"}, {"api_name": "maya.cmds.parentConstraint", "line_number": 343, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 343, "usage_type": "name"}, {"api_name": "maya.cmds.parentConstraint", "line_number": 348, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 348, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 351, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 351, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 352, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 352, "usage_type": "name"}, {"api_name": "maya.cmds.parentConstraint", "line_number": 357, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 357, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 360, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 360, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 380, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 380, "usage_type": "name"}, {"api_name": "maya.cmds.parentConstraint", "line_number": 381, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 381, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 383, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 383, "usage_type": "name"}]}
    +{"seq_id": "1159325898", "text": "import heapq\nfrom collections import defaultdict\nfrom statistics import mean\nfrom typing import Iterator, List, TypedDict\n\nfrom log_analyzer.parsing import LogEntry\n\n\nclass UrlStats(TypedDict):\n    url: str\n    count: int\n    time_sum: float\n    time_perc: float\n    time_avg: float\n    time_max: float\n    time_med: float\n\n\nUrlRunningStats = TypedDict(\"UrlRunningStats\", {\"items\": List[float], \"time_sum\": float})\n\n\nclass LogStats:\n    def __init__(self) -> None:\n        self.stats: dict[str, UrlRunningStats] = defaultdict(lambda: {\"items\": [], \"time_sum\": 0.0})\n        self.total_time = 0.0\n\n    def consume_log_iter(self, it: Iterator[LogEntry]) -> None:\n        for log_entry in it:\n            e = self.stats[log_entry.url]\n            e[\"items\"].append(log_entry.request_time)\n            e[\"time_sum\"] += log_entry.request_time\n            self.total_time += log_entry.request_time\n\n    def _compute_final_url_stats(self, url: str, s: UrlRunningStats) -> UrlStats:\n        s[\"items\"].sort()\n        non_empty = len(s[\"items\"]) > 0\n\n        return {\n            \"url\": url,\n            \"count\": len(s[\"items\"]),\n            \"time_sum\": round(s[\"time_sum\"], 3),\n            \"time_avg\": round(mean(s[\"items\"]), 3) if non_empty else 0,\n            \"time_max\": round(s[\"items\"][-1], 3) if non_empty else 0,\n            \"time_med\": round(s[\"items\"][len(s[\"items\"]) // 2], 3) if non_empty else 0,\n            \"time_perc\": round(s[\"time_sum\"] / self.total_time, 3) if self.total_time > 0 else 0,\n        }\n\n    def top_urls_report(self, n: int) -> List[UrlStats]:\n        # _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1))\n        top_urls = heapq.nlargest(n, self.stats.items(), key=lambda x: x[1][\"time_sum\"])\n        return [self._compute_final_url_stats(url, stats) for url, stats in top_urls]\n", "repo_name": "viexps/log-analyzer", "sub_path": "log_analyzer/stats.py", "file_name": "stats.py", "file_ext": "py", "file_size_in_byte": 1808, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.TypedDict", "line_number": 9, "usage_type": "name"}, {"api_name": "typing.TypedDict", "line_number": 19, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 19, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 24, "usage_type": "call"}, {"api_name": "typing.Iterator", "line_number": 27, "usage_type": "name"}, {"api_name": "log_analyzer.parsing.LogEntry", "line_number": 27, "usage_type": "name"}, {"api_name": "statistics.mean", "line_number": 42, "usage_type": "call"}, {"api_name": "heapq.nlargest", "line_number": 50, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 48, "usage_type": "name"}]}
    +{"seq_id": "4485153195", "text": "from trainer import Trainer\nfrom utils import Paramset\nfrom sklearn.metrics import log_loss\nfrom sklearn.model_selection import StratifiedKFold\nimport numpy as np\nfrom lightgbm import LGBMClassifier\nfrom xgboost import XGBClassifier\nfrom neuralnetwork import NNClassifier\nimport optuna\n\n\nclass Objective:\n     \n    '''\n    # Usage\n    obj = Objective(LGBMRegressor(), X, y)\n    study = optuna.create_study(\n        sampler=optuna.samplers.RandomSampler(seed=123))\n    study.optimize(obj, n_trials=10, n_jobs=-1)\n    '''\n\n    def __init__(self, model, x, y):\n        self.model = model\n        self.model_type = type(self.model).__name__\n        self.x = x\n        self.y = y\n        self.n_splits = 3\n        self.random_state = 1214\n        self.early_stopping_rounds = 20\n        paramset = Paramset(self.model)\n        paramset.swiching_lr('params_search')\n        self.PARAMS = paramset.generate_params()\n    \n    def __call__(self, trial):\n        if self.model_type == 'LGBMClassifier':\n            SPACE = {\n                'num_leaves': trial.suggest_int(\n                'num_leaves', 8, 31),\n                'subsample': trial.suggest_uniform('subsample', 0.60, 0.80),\n                'colsample_bytree': trial.suggest_uniform(\n                    'colsample_bytree', 0.60, 0.80),\n                'bagging_freq': trial.suggest_int(\n                    'bagging_freq', 1, 51, 5),\n                'min_child_weight': trial.suggest_loguniform(\n                    'min_child_weight', 1, 32),\n                'min_child_samples': int(trial.suggest_discrete_uniform(\n                    'min_child_samples', 5, 50, 5)),\n                'min_split_gain': trial.suggest_loguniform(\n                    'min_split_gain', 1e-5, 1e-1)\n            }\n            self.PARAMS.update(SPACE)\n            # cross validation\n            skf = StratifiedKFold(n_splits=self.n_splits,\n            random_state=self.random_state, shuffle=True)\n            LOGLOSS = []\n            for tr_idx, va_idx in skf.split(self.x, self.y):\n                clf = Trainer(LGBMClassifier(**self.PARAMS))\n                clf.fit(\n                    self.x[tr_idx],\n                    self.y[tr_idx],\n                    self.x[va_idx],\n                    self.y[va_idx],\n                    self.early_stopping_rounds\n                )\n                y_pred = clf.predict_proba(self.x[va_idx])  # best_iteration\n                logloss = log_loss(self.y[va_idx], y_pred)\n                LOGLOSS.append(logloss)\n            return np.mean(LOGLOSS)\n        elif self.model_type == 'XGBClassifier':\n            SPACE = {\n                'subsample': trial.suggest_uniform(\n                    'subsample', 0.65, 0.85),\n                'colsample_bytree': trial.suggest_uniform(\n                    'colsample_bytree', 0.65, 0.80),\n                'gamma': trial.suggest_loguniform(\n                    'gamma', 1e-8, 1.0),\n                'min_child_weight': trial.suggest_loguniform(\n                    'min_child_weight', 1, 32)\n            }\n            self.PARAMS.update(SPACE)\n            # cross validation\n            skf = StratifiedKFold(n_splits=self.n_splits,\n            random_state=self.random_state, shuffle=True)\n            LOGLOSS = []\n            for tr_idx, va_idx in skf.split(self.x, self.y):\n                clf = Trainer(XGBClassifier(**self.PARAMS))\n                clf.fit(\n                    self.x[tr_idx],\n                    self.y[tr_idx],\n                    self.x[va_idx],\n                    self.y[va_idx],\n                    self.early_stopping_rounds\n                )\n                y_pred = clf.predict_proba(self.x[va_idx])  # best_iteration\n                logloss = log_loss(self.y[va_idx], y_pred)\n                LOGLOSS.append(logloss)\n            return np.mean(LOGLOSS)\n        elif self.model_type == 'NNClassifier':\n            self.PARAMS['input_shape'] = self.x.shape[1]\n            SPACE = {\n                \"input_dropout\": trial.suggest_uniform(\n                    \"input_dropout\", 0.2, 1.0),\n                \"hidden_layers\": trial.suggest_int(\n                    \"hidden_layers\", 1, 2),\n                'hidden_units': int(trial.suggest_discrete_uniform(\n                    'hidden_units', 8, 64, 8)),\n                'hidden_dropout': trial.suggest_uniform(\n                    'hidden_dropout', 0.2, 1.0),\n                'batch_norm': trial.suggest_categorical(\n                'batch_norm', ['before_act', 'non']),\n                'batch_size': int(trial.suggest_discrete_uniform(\n                    'batch_size', 16, 64, 16))\n            }\n            self.PARAMS.update(SPACE)\n            # cross validation\n            skf = StratifiedKFold(n_splits=self.n_splits,\n            random_state=self.random_state, shuffle=True)\n            LOGLOSS = []\n            for tr_idx, va_idx in skf.split(self.x, self.y):\n                clf = Trainer(NNClassifier(**self.PARAMS))\n                clf.fit(\n                    self.x[tr_idx],\n                    self.y[tr_idx],\n                    self.x[va_idx],\n                    self.y[va_idx],\n                    self.early_stopping_rounds\n                )\n                y_pred = clf.predict_proba(self.x[va_idx])\n                logloss = log_loss(self.y[va_idx], y_pred) # best weghts\n                LOGLOSS.append(logloss)\n            return np.mean(LOGLOSS)\n            \ndef optuna_search(obj, n_trials, n_jobs, random_state):\n    study = optuna.create_study(\n        sampler=optuna.samplers.RandomSampler(seed=random_state))\n    study.optimize(obj, n_trials=n_trials, n_jobs=n_jobs)\n    return study.best_params\n\n\nif __name__ == \"__main__\":\n    pass", "repo_name": "TeddyGlass/ML_Classification_Pipeline", "sub_path": "src/optimizer.py", "file_name": "optimizer.py", "file_ext": "py", "file_size_in_byte": 5651, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "utils.Paramset", "line_number": 30, "usage_type": "call"}, {"api_name": "sklearn.model_selection.StratifiedKFold", "line_number": 53, "usage_type": "call"}, {"api_name": "trainer.Trainer", "line_number": 57, "usage_type": "call"}, {"api_name": "lightgbm.LGBMClassifier", "line_number": 57, "usage_type": "call"}, {"api_name": "sklearn.metrics.log_loss", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 68, "usage_type": "call"}, {"api_name": "sklearn.model_selection.StratifiedKFold", "line_number": 82, "usage_type": "call"}, {"api_name": "trainer.Trainer", "line_number": 86, "usage_type": "call"}, {"api_name": "xgboost.XGBClassifier", "line_number": 86, "usage_type": "call"}, {"api_name": "sklearn.metrics.log_loss", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 97, "usage_type": "call"}, {"api_name": "sklearn.model_selection.StratifiedKFold", "line_number": 116, "usage_type": "call"}, {"api_name": "trainer.Trainer", "line_number": 120, "usage_type": "call"}, {"api_name": "neuralnetwork.NNClassifier", "line_number": 120, "usage_type": "call"}, {"api_name": "sklearn.metrics.log_loss", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 131, "usage_type": "call"}, {"api_name": "optuna.create_study", "line_number": 134, "usage_type": "call"}, {"api_name": "optuna.samplers.RandomSampler", "line_number": 135, "usage_type": "call"}, {"api_name": "optuna.samplers", "line_number": 135, "usage_type": "attribute"}]}
    +{"seq_id": "40250728761", "text": "from flask import Flask\nfrom config import DevConfig\nimport psycopg2\nfrom psycopg2.extras import Json as pgJson\nimport datetime\n\n\nclass DBcontext():\n    def __init__(self, app):\n        self.connectionstring = app.config['PG_DB_CONNECTION_STRING']\n\n    def run_query(self, query):\n        conn = psycopg2.connect(self.connectionstring)\n\n        q = conn.cursor()\n        q.execute(query)\n\n        res = q.fetchone()\n        conn.close()\n        return (res)\n\n\napp = Flask(__name__)\napp.config.from_object(\n    DevConfig(r\"C:\\repos\\github\\AndreyQC\\web-flask\\poc\\config.yaml\"))\ndbcontext = DBcontext(app)\n\n\nclass User_Factory():\n\n\n    def __init__(self, dbcontext):\n        self.db = dbcontext\n        self.db_function_create = \"api.fun_user_create\"\n        self.db_function_update = \"api.fun_user_update\"\n        self.db_function_get_list = \"api.fun_user_get_list\"\n        self.db_function_delete = \"not implemented\"\n        self.db_function_get_by_id = \"api.fun_user_get_by_id\"\n\n    def get_by_id(self, user_id):\n        u = self.User({})\n        res = dict()\n        try:\n            conn = psycopg2.connect(self.db.connectionstring)\n            q = conn.cursor()\n            \n            p_json_user = pgJson({\"id\":user_id})\n            p_json_current_user= pgJson({})\n            p_json_current_session = pgJson({})\n\n            q.execute(f\"select * from  {self.db_function_get_by_id} ({p_json_user},{p_json_current_user},{p_json_current_session} );\")\n            result = q.fetchall()\n\n            for row in result:\n                res = row[0]\n            \n\n        except (Exception, psycopg2.DatabaseError) as error:\n            print(\"Error while connecting to PostgreSQL\", error)            \n\n\n        finally:\n            \n            # closing database connection.\n            if conn:\n                q.close()\n                conn.close()\n                print(\"PostgreSQL connection is closed\")\n            # _jobdef = {'id': 1, 'name': 'product', 'amount': 230}\n            # cur.execute(\"SELECT mrp_sp_insert_jobdef( %s )\", (Json(_jobdef),) )    \n            # \n        u.user_id = res.get('id', 0)\n        u.user_name = res.get('user_name', 'unknown'),\n        u.changed_at = res.get('changed_at', datetime.datetime.now())\n        u.updated_at = res.get('updated_at', datetime.datetime.now())\n        u.saved_in_database = res.get('saved_in_database', False) \n        return (u)   \n\n    class User():\n        def __init__(self, user_dict):\n            if user_dict:\n                self.user_name = user_dict.get('user_name', 'unknown')\n                self.user_id = user_dict.get('id', 0)\n                self.changed_at = user_dict.get('changed_at', datetime.now())\n                self.updated_at = user_dict.get('updated_at', datetime.now())\n                if self.user_id == 0:\n                    self.saved_in_database = False\n                else:\n                    self.saved_in_database = True\n\n        def __repr__(self):\n            return f\"\"\n\n\n@app.route('/')\ndef home():\n    return '

    Hello World! {{ app.config[\"PG_DB_CONNECTION_STRING\"] }}

    '\n\n\nif __name__ == '__main__':\n users = User_Factory(dbcontext)\n user = users.get_by_id(82)\n print(user)\n # user = users.User(id=0, user_name=\"fdf\")\n\n # print(app.config)\n # print(app.config['PG_DB_CONNECTION_STRING'])\n # print(db.connectionstring)\n # res = db.run_query(\"\"\"select\n # lng.id,\n # json_build_object(\n # 'id', lng.id,\n # 'language_name', lng.language_name,\n # 'language_shortname', lng.language_shortname,\n # 'created_at', lng.created_at,\n # 'changed_at', lng.changed_at\n # )\n # FROM words.\"language\" as lng;\"\"\"\n # )\n # print(res)\n # app.run()\n", "repo_name": "AndreyQC/web-flask", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 3815, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "psycopg2.connect", "line_number": 13, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 23, "usage_type": "call"}, {"api_name": "config.DevConfig", "line_number": 25, "usage_type": "call"}, {"api_name": "psycopg2.connect", "line_number": 44, "usage_type": "call"}, {"api_name": "psycopg2.extras.Json", "line_number": 47, "usage_type": "call"}, {"api_name": "psycopg2.extras.Json", "line_number": 48, "usage_type": "call"}, {"api_name": "psycopg2.extras.Json", "line_number": 49, "usage_type": "call"}, {"api_name": "psycopg2.DatabaseError", "line_number": 58, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 74, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 74, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 75, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 75, "usage_type": "attribute"}, {"api_name": "datetime.now", "line_number": 84, "usage_type": "call"}, {"api_name": "datetime.now", "line_number": 85, "usage_type": "call"}]} +{"seq_id": "25748502831", "text": "#Program 6 - update.py\ndef display():\n result = col.find()\n print(\"All documents in movies collection:\")\n for document in result:\n print(document)\n\ndef dropCollections():\n db.drop_collection(\"movies\")\n \ndef insert_doc():\n col.insert_one({\"_id\":1, \"title\":\"Johnny Maths\", \"genre\":\"comedy1\"}) \n col.insert_one({\"title\":\"Star Walls\", \"genre\":\"science fiction\"})\n col.insert_one({\"title\":\"Detection\"}) #no genre\n list_to_add = []\n list_to_add.append({\"title\":\"Badman\", \"genre\":\"adventure1\", \"year\":2015}) #\n list_to_add.append({\"title\":\"Averages\", \"genre\":[\"science fiction\",\"adventure1\"], \"year\":2017}) #\n list_to_add.append({\"title\":\"Octopus Man\", \"genre\":\"adventure1\", \"year\":2017}) #\n list_to_add.append({\"title\":\"Fantastic Bees\", \"genre\":\"adventure1\", \"year\":2018}) #\n list_to_add.append({\"title\":\"Underground\", \"genre\":\"horror\", \"year\":2014}) #\n\n list_to_add.append({\"title\":\"A\", \"genre\":['adventure'], \"year\":2014}) #\n list_to_add.append({\"title\":\"B\", \"genre\":['adventure', 'comedy', 'horror'], \"year\":2014}) #\n list_to_add.append({\"title\":\"C\", \"genre\":\"adventure\", \"year\":2014}) #\n list_to_add.append({\"title\":\"D\", \"genre\":['comedy', 'adventure'], \"year\":2014}) #\n list_to_add.append({\"title\":\"E\", \"genre\":['adventure', 'comedy'], \"year\":2014}) #\n list_to_add.append({\"title\":\"F\", \"genre\":[['adventure', 'comedy'], 'apple'], \"year\":2014})\n col.insert_many(list_to_add)\n print(\"Insertion complete!\")\n#-----main program-----\nimport pymongo\nclient = pymongo.MongoClient(\"127.0.0.1\", 27017)\ndb = client.get_database(\"entertainment\")\ncollections = db.collection_names()\nif 'movies' in collections:\n dropCollections()\nprint(\"Existing collection(s):\", collections)\ncol = db.get_collection(\"movies\")\ninsert_doc()\ndisplay()\n#updates the value 2015 to the 'year' field of the first returned doc that satisfies the search filter\nsearch = {'year':{'$gt':2016}}\nupdate = {'$set':{'year':2015}} #$set can assign value into a field\ncol.update_one(search, update) #title \"Averages\" will have 'year' : 2015\n\n#col.update_many(search, update)#'titles': \"Octopus Man\", \"Fantastic Bees\" will have 'year':2015\n\n\n##search = { 'year' : { '$eq' : 2018 } }\n##update = { '$unset' : { 'year' : 0 } } #$unset will remove the field 'year' from the doc entirely\n##col.update_many(search, update)\n\n#update doc that do not have the field 'year' to have 'year': 2019\n##search = { 'year' : { '$exists' : False } } #look for doc that do not have the field 'year'\n##update = { '$set' : { 'year' : 2019 } } #$set can assign both field and value into a doc\n##col.update_many(search, update)\n\n\n#return values of fields 'title', 'genre' and 'year' of a\n#doc that has 'title': 'Fantastic Bees' and 'genre' : 'adventure'\n\n\nquery = { '$and': [ {'title' : { '$eq' : 'Fantastic Bees' }},\n {'genre' : { '$eq' : 'adventure'}}\n ]\n }\nprojection = {'title' : 1, 'genre' : 1, 'year' : 1, '_id' : 0}\nresult = col.find(query, projection)\nfor i in result:\n print(i)\n\n\n\n#-----------------delete---------------\n# .delete_one(query) --> removes the one entire document that fulfils query\n# .delete_many(query) --> removes all documents that fulfil query\n\n#delete all documents that have 'genre': 'adventure' OR if they have 'year' less than 2015\n##query = {'$or' : [ { 'genre' : { '$eq' : 'adventure'} },\n## { 'year': { '$lt' : 2015 }}\n## ]\n## }\n##\n##col.delete_many(query)\n\n\n\n\n\n\nclient.close()\n", "repo_name": "MCoolguy/H2-Computing-All", "sub_path": "Computing Revision 2/NoSql/21S23/21S23 Program 6 - update.py", "file_name": "21S23 Program 6 - update.py", "file_ext": "py", "file_size_in_byte": 3512, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pymongo.MongoClient", "line_number": 32, "usage_type": "call"}]} +{"seq_id": "975512818", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 17 17:11:57 2019\n\n@author: Asif Towheed\n\"\"\"\n\nimport datetime\nfrom sklearn import svm\nfrom PIL import Image\nimport os\nimport re\nimport numpy as np\nfrom scipy.fftpack import dct\nimport cv2\nimport pickle\nimport matplotlib.pyplot as plt\nfrom time import time\nimport math\n\n\n\nwidth, height = (640, 480)\n\nLABELS = []\nLABELS_ALL = []\nTRAINING_STATUS = False\n\nPATH = os.getcwd().replace('\\\\','/')\nPATH_SURF = PATH + '/SURF'\nSUBJECTNAME = \"\"\nSUBJECTPATH = \"\"\nFINALPATH = \"\"\nINDEX = 0\n\nwidth, height = (640, 480)\n\nXDELTA = []\nYDELTA = []\nKILLTHREAD = False\nSTATUSBOOL = False\nSTATUSARR = []\nNUMPYLIST = []\n\ntInit = time()\n\n\nclass SURF_Histogram:\n \n def __init__(self):\n self.xdelta = []\n self.ydelta = []\n self.range = (-1,1)\n self.bins = 30\n self.density = True\n self.rwidth = 0.90\n self.FVec = []\n \n def addx(self, xdelta):\n self.xdelta += xdelta\n\n def addy(self, ydelta):\n self.ydelta += ydelta\n \n def resetx(self):\n self.xdelta = []\n\n def resety(self):\n self.ydelta = []\n\n def resetfvec(self):\n self.FVec = []\n \n def getfeaturevec(self):\n xcounts, xbins, xbars = plt.hist(self.xdelta, range = self.range, density=self.density, rwidth = self.rwidth, bins=self.bins)\n ycounts, ybins, ybars = plt.hist(self.ydelta, range = self.range, density=self.density, rwidth = self.rwidth, bins=self.bins)\n self.FVec = np.append(xcounts, ycounts, axis = 0)\n #self.FVec.append(xcounts)\n #self.FVec.append(ycounts)\n return self.FVec\n \n def loadhist(location):\n infile = open(location + '/histogram.pkl','rb')\n loaded = pickle.load(infile)\n return loaded\n\n def loadfvec(location):\n infile = open(location + '/fvec.pkl','rb')\n loaded = pickle.load(infile)\n return loaded\n \n def savehist(self, location):\n print('saving histogram')\n savefile = open(location + '/histogram.pkl', 'wb')\n savefile2 = open(location + '/fvec.pkl', 'wb')\n pickle.dump(self, savefile)\n pickle.dump(self.FVec, savefile2)\n savefile.close()\n\n \n\nHISTOGRAM = SURF_Histogram()\n\n\n################################################################################\n## GET AN INDIVIDUAL DIFFERENCE IMAGE\n################################################################################\ndef SURF_FindMatches(kp1, kp2, desc1, desc2, n, i0, i1):\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=False)\n \n matches = bf.match(desc1,desc2)\n \n matches = sorted(matches, key = lambda x:x.distance)\n #matches[len(matches)-1].distance --> will give the greatest displacement\n newmatches = []\n \n # Error correction --> only consider the points with a correct match\n for match in matches:\n if abs(kp1[match.queryIdx].pt[1] - kp2[match.trainIdx].pt[1]) < 50:\n newmatches.append(match)\n \n \n #img3 = cv2.drawMatches(i0,kp,i1,kp2,newmatches[:], None, (0,255,0), flags=2)\n #img4 = cv2.drawMatches(i0,kp,i1,kp2,matches[:], None, (0,255,0), flags=2)\n #print('m', len(matches))\n #plt.imshow(img3),plt.show()\n \n #im = Image.fromarray(img3)\n #im.save('linesdrawn.jpeg')\n \n xmax1 = 0\n ymax1 = 0\n xmin1 = 640\n ymin1 = 480\n \n xmax2 = 0\n ymax2 = 0\n xmin2 = 640\n ymin2 = 480\n \n # the indexes of the 2 pics that have matches\n pic1idxs = []\n pic2idxs = []\n # lists to store the points\n pic1points = []\n pic2points = []\n # the delta x and y\n xdelta = []\n ydelta = []\n \n for i in newmatches:\n pic1idxs.append(i.queryIdx)\n pic2idxs.append(i.trainIdx)\n \n #print('pic1idxs',pic1idxs)\n #print('pic2idxs',pic2idxs)\n \n #find max x,y and min x,y in pic1\n for i in kp1:\n if i.pt[0] > xmax1: #max x\n xmax1 = i.pt[0]\n if i.pt[1] > ymax1: #max y\n ymax1 = i.pt[1]\n if i.pt[0] < xmin1: #min x\n xmin1 = i.pt[0]\n if i.pt[1] < ymin1: #min y\n ymin1 = i.pt[1]\n \n #find max x,y and min x,y in pic2\n for i in kp2:\n if i.pt[0] > xmax2:\n xmax2 = i.pt[0] #max x\n if i.pt[1] > ymax2:\n ymax2 = i.pt[1] #max y\n if i.pt[0] < xmin2:\n xmin2 = i.pt[0] #min x\n if i.pt[1] < ymin2:\n ymin2 = i.pt[1] #min y\n \n # print out all the max(s) and min(s)\n# print('xmax1', xmax1)\n# print('ymax1', ymax1)\n# print('xmax2', xmax2)\n# print('ymax2', ymax2)\n# print('xmin1', xmin1)\n# print('ymin1', ymin1)\n# print('xmin2', xmin2)\n# print('ymin2', ymin2)\n \n # NORMALIZATION\n #print('pic1idxs',pic1idxs)\n for i in pic1idxs:\n# print('kp1[i].pt[0]', kp1[i].pt[0])\n a = kp1[i].pt[0]/(xmax1 - xmin1 + 1)\n# print('a1', a)\n# print('kp1[i].pt[1]', kp1[i].pt[1])\n b = kp1[i].pt[1]/(ymax1 - ymin1 + 1)\n# print('b1', b)\n pic1points.append((a,b))\n \n #print('pic2idxs',pic2idxs)\n #print('kp2', kp2)\n #print('len(kp2)', len(kp2))\n #print(kp2[i].pt[0])\n #print(kp2[i].pt[1])\n try:\n for i in pic2idxs:\n #print('i', i)\n# print('kp2[i].pt[0]', kp2[i].pt[0])\n a = kp2[i].pt[0]/(xmax2 - xmin2 + 1)\n# print('a2', a)\n# print('kp2[i].pt[1]', kp2[i].pt[1])\n b = kp2[i].pt[1]/(ymax2 - ymin2 + 1)\n# print('b2', b)\n pic2points.append((a,b))\n except:\n img3 = cv2.drawMatches(i0,kp1,i1,kp2,newmatches[:], None, (0,255,0), flags=2)\n img4 = cv2.drawMatches(i0,kp1,i1,kp2,matches[:], None, (0,255,0), flags=2)\n# print('m', len(newmatches))\n# for match in newmatches:\n# print('query', match.queryIdx)\n# print('train', match.trainIdx)\n plt.imshow(img3),plt.show()\n plt.imshow(img4),plt.show()\n while True:\n cv2.imshow('i0', i0)\n cv2.imshow('i1', i1)\n cv2.imshow('img3', img3)\n cv2.imshow('img4', img4)\n k = cv2.waitKey(1)\n if k & 0xFF == ord(\"q\"): # Exit condition\n cv2.destroyAllWindows()\n break\n\n \n # FOR THE DELTA, SHOULD WE TAKE THE ABSOLUTE VALUE??\n for i in range(len(newmatches)):\n if -1 < (pic1points[i][0] - pic2points[i][0]) < 1:\n xdelta.append(pic1points[i][0] - pic2points[i][0])\n if -1 < (pic1points[i][1] - pic2points[i][1]) < 1:\n ydelta.append(pic1points[i][1] - pic2points[i][1])\n\n \n return xdelta, ydelta\n\n##------------------------------------------------------------------------------- (DONE)\n \n\n\n\n\n\n\n\n################################################################################\n## GET THE DIFFERENCES --> SAVE THE INDIVIDUAL DIFFERENCE IMAGES\n################################################################################\ndef SURF_AddToHistograms(xdelta, ydelta):\n \n global HISTOGRAM\n \n HISTOGRAM.addx(xdelta)\n HISTOGRAM.addy(ydelta) \n##------------------------------------------------------------------------------- (DONE)\n\n\n\n################################################################################\n## BEGIN TRAINING FOR NEW SUBJECT --> CREATE A DIRECTORY WITH THEIR NAME\n################################################################################\ndef SURF_Begin():\n \n ## Getting Directories\n ##=============================================================================\n global LABELS, LABELS_ALL\n\n PATH = os.getcwd().replace('\\\\', '/')\n print('PATH:\\t\\t', PATH)\n \n SURF_PATH = PATH + '/SURF'\n print('SURF_PATH:\\t', SURF_PATH)\n \n for filename in os.listdir(PATH_SURF):\n\n# if not re.match('trained-model', filename):\n# LABELS.append(filename)\n\n if re.match('.*_untrained', filename):\n LABELS.append(filename)\n elif not re.match('trained-model', filename):\n LABELS_ALL.append(filename)\n \n \n # Training on frames\n #=============================================================================\n \n for i in LABELS: # open each recorded person\n global SUBJECTNAME, KILLTHREAD\n SUBJECTNAME = i\n print('now for',SUBJECTNAME,'killthread',KILLTHREAD)\n if KILLTHREAD:\n print('Entered1')\n return\n SURF_GenerateHistograms(SUBJECTNAME)\n ts = time()\n timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') + '\\n'\n file = open(PATH + '/history.txt', 'r+')\n contents_as_string = file.read()\n newtext = SUBJECTNAME.split('_untrained')[0] + ' was trained for SURF: ' + timestamp + contents_as_string\n file2 = open(PATH + '/history.txt', 'w')\n file2.write(newtext)\n file.close()\n file2.close()\n #-----------------------------------------------------------------------------\n##-------------------------------------------------------------------------------\n \n##print(LABELS_W)\n##print(LABELS)\n#\n##***\n## By now, we have all the labels split into the arrays based on depthwhite or gray frames\n##***\n###-----------------------------------------------------------------------------\n#\n##print('---------------------')\n#\n#\n#\n#\n## Training on Depthwhite frames\n##=============================================================================\n\ndef SURF_GenerateHistograms(SUBJECTNAME): # open each depthwhite recorded person\n walks = [] # array to store how many times they have walked\n SUBJECTPATH = PATH_SURF + '/' + SUBJECTNAME # path to that person\n for walk in os.listdir(SUBJECTPATH):\n global INDEX, STATUSBOOL, STATUSARR, NUMPYLIST\n print('SURF for ' + str(walk) + ' for ' + str(SUBJECTNAME))\n walks.append(walk) # get each walk\n walk_path = SUBJECTPATH + '/' + walk # path to that walk\n \n INDEX = walk[-1]\n\n STATUSBOOL = False\n STATUSARR = []\n\n \n NUMPYLIST = []\n \n global FINALDIFFPATH, FINALORIGINALPATH, PADDEDPATH, PREPATH, KILLTHREAD\n FINALORIGINALPATH = SUBJECTPATH + '/WALK' + str(INDEX) + \"/ORIGINAL\" \n \n for frame in os.listdir(FINALORIGINALPATH):\n #print(frame)\n openednumpyImage = cv2.imread(FINALORIGINALPATH + '/' + str(frame))\n NUMPYLIST.append(openednumpyImage)\n \n HISTOGRAM.resetx()\n HISTOGRAM.resety()\n HISTOGRAM.resetfvec()\n \n surf = cv2.ORB_create(nfeatures = 100)\n \n STATUSBOOL = True\n \n for i in range(len(NUMPYLIST) - 1):\n if KILLTHREAD:\n return\n #print(i, 'called')\n \n kp1, desc1 = surf.detectAndCompute(NUMPYLIST[i], None)\n kp2, desc2 = surf.detectAndCompute(NUMPYLIST[i+1], None)\n \n i0 = cv2.drawKeypoints(NUMPYLIST[i], kp1, None, (255,0,0), 4)\n i1 = cv2.drawKeypoints(NUMPYLIST[i+1], kp2, None, (255,0,0), 4)\n \n xdelta, ydelta = SURF_FindMatches(kp1, kp2, desc1, desc2, i, i0, i1)\n \n SURF_AddToHistograms(xdelta, ydelta)\n \n #print('Pair finished-----------------------')\n STATUSARR.append(1)\n \n fvec = HISTOGRAM.getfeaturevec()\n #print(fvec)\n #print('Walk finished-----------------------')\n HISTOGRAM.savehist(walk_path)\n\n print('SUBJECTPATH', SUBJECTPATH)\n# os.rename(SUBJECTPATH, SUBJECTPATH.split('_untrained')[0])\n MID_SURF_RESET()\n##-----------------------------------------------------------------------------\n\n\n\n################################################################################\n## GET THE FEATURE VECTOR --> PRODUCE THE DCT IMAGE\n################################################################################\ndef SURF_GetStatus():\n global IMAGELIST, NUMPYLIST, STATUSBOOL, FINALDIFFPATH, STATUSARR, PAUSE\n \n if not STATUSBOOL:\n return 0\n# elif PAUSE:\n# return 20\n else:\n #print('len(STATUSARR)', len(STATUSARR))\n #print('(len(IMAGELIST)-1)', (len(IMAGELIST)-1))\n #print('len(STATUSARR)/(len(IMAGELIST)-1) * 20',len(STATUSARR)/(len(IMAGELIST)-1) * 20)\n return int(math.ceil(len(STATUSARR)/(len(NUMPYLIST)-1) * 20))\n##-------------------------------------------------------------------------------\n\n\n\ndef SURF_GetWalkNumber():\n return int(INDEX)\n\ndef getStatus2(timeinit):\n tfinal = time()\n global TRAINING_STATUS\n if not TRAINING_STATUS:\n return str(tfinal-timeinit) + 's; Processing walk ' + str(INDEX) + ' for ' + str(SUBJECTNAME) + '...'\n else:\n return 'Training the classifier...'\n\n\n\n\n################################################################################\n## GET THE FEATURE VECTOR --> PRODUCE THE DCT IMAGE\n################################################################################\ndef TerminateDifferences():\n global KILLTHREAD\n KILLTHREAD = True\n##-------------------------------------------------------------------------------\n\n################################################################################\n## GET THE DIFFERENCES --> SAVE THE INDIVIDUAL DIFFERENCE IMAGES\n################################################################################\ndef SURF_RESET():\n global PATH, PATH_AD, SUBJECTNAME, SUBJECTPATH, FINALORIGINALPATH, FINALDIFFPATH, INDEX, IND_DIFF_IMG, ACC_DIFF_IMG, FEATUREVEC, KILLTHREAD\n PATH = os.getcwd().replace('\\\\','/')\n PATH_AD = PATH + '/AD'\n SUBJECTNAME = \"\"\n SUBJECTPATH = \"\"\n FINALORIGINALPATH = \"\"\n FINALDIFFPATH = \"\"\n INDEX = None\n \n IND_DIFF_IMG = np.zeros([height, width], dtype=np.uint8) # to store the individual differences\n ACC_DIFF_IMG = np.zeros([height, width], dtype=np.uint8)\n FEATUREVEC = []\n KILLTHREAD = False\n print('RESET CALLED', str(KILLTHREAD))\n##-------------------------------------------------------------------------------\n################################################################################\n## GET THE DIFFERENCES --> SAVE THE INDIVIDUAL DIFFERENCE IMAGES\n################################################################################\ndef MID_SURF_RESET():\n global PATH, PATH_AD, SUBJECTNAME, SUBJECTPATH, FINALORIGINALPATH, FINALDIFFPATH, INDEX, IND_DIFF_IMG, ACC_DIFF_IMG, FEATUREVEC, KILLTHREAD, STATUSBOOL, STATUSARR\n\n FEATUREVEC = []\n KILLTHREAD = False\n STATUSBOOL = False\n STATUSARR = []\n INDEX = 0\n\n print('MID-RESET CALLED', str(KILLTHREAD))\n##-------------------------------------------------------------------------------\n\n\n\n\n\n \ndef checkPlain(im):\n count = 0\n for w in range(width):\n for h in range(height):\n if int(im[h,w]) > 0:\n count += 1\n if count >= 5000:\n return False\n return True\n \n\n\ndef SURF_train():\n global TRAINING_STATUS\n TRAINING_STATUS = True\n first = True\n second = True\n traininglabels = []\n mainvec = []\n firstvec = None\n secondvec = None\n for i in LABELS: # open each depthwhite recorded person\n walks = [] # array to store how many times they have walked\n label_path = PATH_SURF + '/' + i # path to that person\n \n \n \n for walk in os.listdir(label_path):\n walks.append(walk) # get each walk\n walk_path = label_path + '/' + walk # path to that walk\n \n FVec = SURF_Histogram.loadfvec(walk_path)\n \n FVec = np.array(FVec)\n FVec = FVec.reshape(1,-1)\n\n \n #global first, second, firstvec, secondvec, mainvec\n if first and second:\n firstvec = FVec\n first = False\n elif second:\n secondvec = FVec\n mainvec = np.append(firstvec, secondvec, axis = 0)\n second = False\n else:\n mainvec = np.append(mainvec, FVec, axis = 0)\n traininglabels.append(i)\n clf = svm.SVC(kernel='linear', C = 1)\n clf.fit(mainvec, traininglabels)\n savefile = open(PATH_SURF + '/trained-model.pkl', 'wb')\n pickle.dump(clf, savefile)\n savefile.close()\n TRAINING_STATUS = False\n\n\n\n", "repo_name": "asiftowheed/Gait_recognition-depth_vision-SVM", "sub_path": "SURF_Functions_2.py", "file_name": "SURF_Functions_2.py", "file_ext": "py", "file_size_in_byte": 16749, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.getcwd", "line_number": 29, "usage_type": "call"}, {"api_name": "time.time", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "numpy.append", "line_number": 77, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 84, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 89, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 96, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 97, "usage_type": "call"}, {"api_name": "cv2.BFMatcher", "line_number": 109, "usage_type": "call"}, {"api_name": "cv2.NORM_HAMMING", "line_number": 109, "usage_type": "attribute"}, {"api_name": "cv2.drawMatches", "line_number": 217, "usage_type": "call"}, {"api_name": "cv2.drawMatches", "line_number": 218, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 223, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 223, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 223, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 224, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 224, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 224, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 226, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 227, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 228, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 229, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 230, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 232, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 277, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 283, "usage_type": "call"}, {"api_name": "re.match", "line_number": 288, "usage_type": "call"}, {"api_name": "re.match", "line_number": 290, "usage_type": "call"}, {"api_name": "time.time", "line_number": 305, "usage_type": "call"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 306, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 306, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 336, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 353, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 355, "usage_type": "call"}, {"api_name": "cv2.ORB_create", "line_number": 362, "usage_type": "call"}, {"api_name": "cv2.drawKeypoints", "line_number": 374, "usage_type": "call"}, {"api_name": "cv2.drawKeypoints", "line_number": 375, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 410, "usage_type": "call"}, {"api_name": "time.time", "line_number": 419, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 442, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 450, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 450, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 451, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 451, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 503, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 509, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 519, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 522, "usage_type": "call"}, {"api_name": "sklearn.svm.SVC", "line_number": 524, "usage_type": "call"}, {"api_name": "sklearn.svm", "line_number": 524, "usage_type": "name"}, {"api_name": "pickle.dump", "line_number": 527, "usage_type": "call"}]} +{"seq_id": "39343709181", "text": "# -*- coding: utf-8 -*-\r\n\r\nimport glob\r\nimport numpy as np\r\nimport cv2\r\nimport pickle\r\nimport chainer\r\nimport chainer.functions as F\r\n\r\ndropout_ratio = 0.1\r\n\r\ndirList = glob.glob('hiragana73/*')\r\nwordList = {}\r\nimageList = {}\r\n\r\ncount = 1\r\nfor dirName in dirList:\r\n print(dirName)\r\n fileList = glob.glob(dirName + '/*')\r\n matrix = np.zeros((48, 48, len(fileList)))\r\n matrixColor = np.zeros((48, 48, 3, len(fileList)))\r\n for i in range(len(fileList)):\r\n fname = fileList[i]\r\n img = cv2.imread(fname, cv2.IMREAD_COLOR)\r\n matrixColor[:, :, :, i] = img\r\n img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\r\n matrix[:, :, i] = img\r\n wordList[str(count)] = matrix\r\n imageList[str(count)] = matrixColor\r\n count += 1\r\n \r\nmodel = pickle.load(open('latest.model', 'rb'))\r\n\r\n# テスト用バッチ作成\r\ndef make_batch(num):\r\n batch = np.zeros((73, 1, 48, 48))\r\n batch = batch.astype(np.float32)\r\n output = np.zeros((73))\r\n output = output.astype(np.int32)\r\n for i in range(73):\r\n dataList = wordList[str(i+1)]\r\n index = num\r\n data = dataList[:, :, index]\r\n data /= np.max(data)\r\n batch[i, :, :, :] = data\r\n output[i] = i\r\n return batch, output\r\n\r\n\"\"\"\r\ni = 0\r\nbatch, output = make_batch(i)\r\nx = chainer.Variable(batch)\r\nt = chainer.Variable(output)\r\nx = F.max_pooling_2d(F.relu(model.conv1(x)), 2)\r\nx = F.max_pooling_2d(F.relu(model.conv2(x)), 2)\r\nx = F.relu(model.conv3(x))\r\nx = F.dropout(F.relu(model.l1(x)), ratio=dropout_ratio, train=False)\r\ny = model.l2(x)\r\nacc = F.accuracy(y, t)\r\ny = F.softmax(y).data\r\n\"\"\"\r\n\r\nresultMatrix = []\r\naccMatrix = []\r\nfor i in range(100):\r\n batch, output = make_batch(i)\r\n x = chainer.Variable(batch)\r\n t = chainer.Variable(output)\r\n x = F.max_pooling_2d(F.relu(model.conv1(x)), 2)\r\n x = F.max_pooling_2d(F.relu(model.conv2(x)), 2)\r\n x = F.relu(model.conv3(x))\r\n x = F.dropout(F.relu(model.l1(x)), ratio=dropout_ratio, train=False)\r\n y = model.l2(x)\r\n acc = F.accuracy(y, t).data\r\n y = F.softmax(y).data\r\n \r\n accMatrix.append(acc)\r\n resultMatrix.append(y)\r\n\r\naccSum = 0\r\nfor i in range(100):\r\n accSum += accMatrix[i]", "repo_name": "fujitch/ocr-master", "sub_path": "sample_hiragana.py", "file_name": "sample_hiragana.py", "file_ext": "py", "file_size_in_byte": 2198, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "glob.glob", "line_number": 12, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 21, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 24, "usage_type": "call"}, {"api_name": "cv2.IMREAD_COLOR", "line_number": 24, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2GRAY", "line_number": 26, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 37, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 39, "usage_type": "attribute"}, {"api_name": "numpy.max", "line_number": 44, "usage_type": "call"}, {"api_name": "chainer.Variable", "line_number": 67, "usage_type": "call"}, {"api_name": "chainer.Variable", "line_number": 68, "usage_type": "call"}, {"api_name": "chainer.functions.max_pooling_2d", "line_number": 69, "usage_type": "call"}, {"api_name": "chainer.functions", "line_number": 69, "usage_type": "name"}, {"api_name": "chainer.functions.relu", "line_number": 69, "usage_type": "call"}, {"api_name": "chainer.functions.max_pooling_2d", "line_number": 70, "usage_type": "call"}, {"api_name": "chainer.functions", "line_number": 70, "usage_type": "name"}, {"api_name": "chainer.functions.relu", "line_number": 70, "usage_type": "call"}, {"api_name": "chainer.functions.relu", "line_number": 71, "usage_type": "call"}, {"api_name": "chainer.functions", "line_number": 71, "usage_type": "name"}, {"api_name": "chainer.functions.dropout", "line_number": 72, "usage_type": "call"}, {"api_name": "chainer.functions", "line_number": 72, "usage_type": "name"}, {"api_name": "chainer.functions.relu", "line_number": 72, "usage_type": "call"}, {"api_name": "chainer.functions.accuracy", "line_number": 74, "usage_type": "call"}, {"api_name": "chainer.functions", "line_number": 74, "usage_type": "name"}, {"api_name": "chainer.functions.softmax", "line_number": 75, "usage_type": "call"}, {"api_name": "chainer.functions", "line_number": 75, "usage_type": "name"}]} +{"seq_id": "39538080354", "text": "\n# coding: utf-8\n\n# In[1]:\n\n\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\n\n\n# In[2]:\n\n\ntransform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\ntrainset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=4,\n shuffle=True, num_workers=2)\n\ntestset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=4,\n shuffle=False, num_workers=2)\n\nclasses = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n\n# In[3]:\n\n\nimport matplotlib.pyplot as plt\nget_ipython().magic('matplotlib inline')\nimport numpy as np\n\n\n# In[4]:\n\n\ndef imshow(img):\n img = img/2+0.5\n npimg = img.numpy()\n plt.imshow(np.transpose(npimg,(1,2,0)))\n\n\n# In[5]:\n\n\ndataiter = iter(trainloader)\nimages,labels = dataiter.next()\nimshow(torchvision.utils.make_grid(images))\nprint(' '.join('%5s' % classes[labels[j]] for j in range(4)))\n\n\n# In[6]:\n\n\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n\n# In[10]:\n\n\ndef train_test(cnn,eta,ep):\n loss = nn.CrossEntropyLoss()\n optimiser = optim.Adam(cnn.parameters(),lr=eta)\n\n for epoch in range(10):\n\n l_tr= 0.0\n for i,data in enumerate(trainloader,0):\n\n inputs,labels = data\n print(labels)\n inputs,labels = Variable(inputs),Variable(labels)\n optimiser.zero_grad()\n\n preds = cnn(inputs)\n print(preds)\n loss_tr = loss(preds,labels)\n loss_tr.backward()\n optimiser.step()\n\n l_tr += loss_tr.data[0]\n if i % 2000 == 1999: # print every 2000 mini-batches\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, l_tr / 2000))\n l_tr = 0.0\n print ('finished training')\n \n correct = 0\n total = 0\n for data in testloader:\n images, labels = data\n outputs = cnn(Variable(images))\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum()\n\n print('Accuracy of the network on the 10000 test images: %d %%' % (\n 100 * correct / total))\n \n class_correct = list(0. for i in range(10))\n class_total = list(0. for i in range(10))\n for data in testloader:\n images, labels = data\n outputs = cnn(Variable(images))\n _, predicted = torch.max(outputs.data, 1)\n c = (predicted == labels).squeeze()\n for i in range(4):\n label = labels[i]\n class_correct[label] += c[i]\n class_total[label] += 1\n\n\n for i in range(10):\n print('Accuracy of %5s : %2d %%' % (\n classes[i], 100 * class_correct[i] / class_total[i]))\n\n\n# In[11]:\n\n\nclass rosnet_11_3(nn.Module):\n def __init__(self):\n super(rosnet_11_3,self).__init__()\n self.conv1 = nn.Conv2d(3,6,3,2,1)\n self.conv2 = nn.Conv2d(6,12,3,1,1)\n self.conv3 = nn.Conv2d(12,24,3,1,1)\n self.conv4 = nn.Conv2d(24,48,3,1,1)\n self.conv5 = nn.Conv2d(48,96,3,1,1)\n self.conv6 = nn.Conv2d(96,192,3,1,1)\n self.pool = nn.MaxPool2d(2,2)\n self.fc1 = nn.Linear(192*2*2,256)\n self.fc2 = nn.Linear(256,64)\n self.fc3 = nn.Linear(64,10)\n \n def forward(self,x):\n x = F.relu(self.conv1(x))\n x = self.pool(F.relu(self.conv2(x)))\n x = F.relu(self.conv3(x))\n x = self.pool(F.relu(self.conv4(x)))\n x = F.relu(self.conv5(x))\n x = self.pool(F.relu(self.conv6(x)))\n x = x.view(-1,192*2*2)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\n# In[12]:\n\n\ncnn = rosnet_11_3()\ntrain_test(cnn,0.001,10)\n\n\n# In[ ]:\n\n\nclass rosnet_11_3x(nn.Module):\n def __init__(self):\n super(rosnet_11_3x,self).__init__()\n self.conv1 = nn.Conv2d(3,6,3,2,1, bias=True)\n torch.nn.init.xavier_normal(self.conv1.weight)\n self.conv2 = nn.Conv2d(6,12,3,1,1, bias=True)\n torch.nn.init.xavier_normal(self.conv2.weight)\n self.conv3 = nn.Conv2d(12,24,3,1,1, bias=True)\n torch.nn.init.xavier_normal(self.conv3.weight)\n self.conv4 = nn.Conv2d(24,48,3,1,1,bias=True)\n torch.nn.init.xavier_normal(self.conv4.weight)\n self.conv5 = nn.Conv2d(48,96,3,1,1,bias=True)\n torch.nn.init.xavier_normal(self.conv5.weight)\n self.conv6 = nn.Conv2d(96,192,3,1,1,bias=True)\n torch.nn.init.xavier_normal(self.conv6.weight)\n self.pool = nn.MaxPool2d(2,2)\n self.fc1 = nn.Linear(192*2*2,256)\n torch.nn.init.xavier_normal(self.fc1.weight)\n self.fc2 = nn.Linear(256,64)\n torch.nn.init.xavier_normal(self.fc2.weight)\n self.fc3 = nn.Linear(64,10)\n torch.nn.init.xavier_normal(self.fc3.weight)\n \n def forward(self,x):\n x = F.relu(self.conv1(x))\n x = self.pool(F.relu(self.conv2(x)))\n x = F.relu(self.conv3(x))\n x = self.pool(F.relu(self.conv4(x)))\n x = F.relu(self.conv5(x))\n x = self.pool(F.relu(self.conv6(x)))\n x = x.view(-1,192*2*2)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\n# In[ ]:\n\n\ncnn2 = rosnet_11_3x()\ncnn2.cuda\ntrain_test(cnn2,0.001,10)\n\n\n# In[ ]:\n\n\nclass rosnet_1_2bx(nn.Module):\n def __init__(self):\n super(rosnet_1_2bx,self).__init__()\n self.conv1 = nn.Conv2d(3,8,5,2,1, bias=True)\n torch.nn.init.xavier_normal(self.conv1.weight)\n self.bn1 = nn.BatchNorm2d(8)\n self.pool = nn.MaxPool2d(2,2)\n self.fc1 = nn.Linear(8*7*7,256)\n torch.nn.init.xavier_normal(self.fc1.weight)\n self.bn2 = nn.BatchNorm1d(256)\n self.fc2 = nn.Linear(256,10)\n torch.nn.init.xavier_normal(self.fc2.weight)\n \n \n def forward(self,x):\n x = self.conv1(x)\n x = self.pool(F.relu(self.bn1(x)))\n x = x.view(-1,8*7*7)\n x = self.fc1(x)\n x = self.fc2(F.relu(self.bn2(x)))\n return x\n\n\n# In[ ]:\n\n\ncnn3 = rosnet_1_2bx()\n\n", "repo_name": "sparshgupta8130/Pytorch_Cifar10_TransferVGG_Caltech", "sub_path": "Rosnets.py", "file_name": "Rosnets.py", "file_ext": "py", "file_size_in_byte": 6495, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "torchvision.transforms.Compose", "line_number": 15, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 15, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 16, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 16, "usage_type": "name"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 17, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 17, "usage_type": "name"}, {"api_name": "torchvision.datasets.CIFAR10", "line_number": 19, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 19, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 21, "usage_type": "attribute"}, {"api_name": "torchvision.datasets.CIFAR10", "line_number": 24, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 24, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 26, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "numpy.transpose", "line_number": 47, "usage_type": "call"}, {"api_name": "torchvision.utils.make_grid", "line_number": 55, "usage_type": "call"}, {"api_name": "torchvision.utils", "line_number": 55, "usage_type": "attribute"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 72, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 72, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 73, "usage_type": "name"}, {"api_name": "torch.autograd.Variable", "line_number": 82, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 102, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 103, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 114, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 115, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 131, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 131, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 134, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 134, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 135, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 135, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 136, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 136, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 137, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 137, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 138, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 138, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 139, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 139, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 140, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 140, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 141, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 141, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 142, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 142, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 143, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 143, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 146, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 146, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 147, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 148, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 148, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 149, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 149, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 150, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 150, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 151, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 151, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 153, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 153, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 154, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 154, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 169, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 169, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 172, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 172, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_normal", "line_number": 173, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 173, "usage_type": "attribute"}, {"api_name": "torch.nn.Conv2d", "line_number": 174, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 174, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_normal", "line_number": 175, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 175, "usage_type": "attribute"}, {"api_name": "torch.nn.Conv2d", "line_number": 176, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 176, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_normal", "line_number": 177, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 177, "usage_type": "attribute"}, {"api_name": "torch.nn.Conv2d", "line_number": 178, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 178, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_normal", "line_number": 179, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 179, "usage_type": "attribute"}, {"api_name": "torch.nn.Conv2d", "line_number": 180, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 180, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_normal", "line_number": 181, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 181, "usage_type": "attribute"}, {"api_name": "torch.nn.Conv2d", "line_number": 182, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 182, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_normal", "line_number": 183, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 183, "usage_type": "attribute"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 184, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 184, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 185, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 185, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_normal", "line_number": 186, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 186, "usage_type": "attribute"}, {"api_name": "torch.nn.Linear", "line_number": 187, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 187, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_normal", "line_number": 188, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 188, "usage_type": "attribute"}, {"api_name": "torch.nn.Linear", "line_number": 189, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 189, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_normal", "line_number": 190, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 190, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.relu", "line_number": 193, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 193, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 194, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 194, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 195, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 195, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 196, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 196, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 197, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 197, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 198, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 198, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 200, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 200, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 201, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 201, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 217, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 217, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 220, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 220, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_normal", "line_number": 221, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 221, "usage_type": "attribute"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 222, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 222, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 223, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 223, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 224, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 224, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_normal", "line_number": 225, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 225, "usage_type": "attribute"}, {"api_name": "torch.nn.BatchNorm1d", "line_number": 226, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 226, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 227, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 227, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_normal", "line_number": 228, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 228, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.relu", "line_number": 233, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 233, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 236, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 236, "usage_type": "name"}]} +{"seq_id": "21407924206", "text": "\"\"\"\nCreated on Thu Sep 9 2021\n\nmain\n\n@author: Ray\n\"\"\"\nfrom __future__ import print_function\nfrom argparse import ArgumentParser, RawTextHelpFormatter\nimport os, sys\nfrom pix2pix import *\nfrom utils import *\n\nparser = ArgumentParser(usage=None, formatter_class=RawTextHelpFormatter, description=\"Image translation using pix2pix: \\n \\n\"\n \"This code provides a pix2pix model from training to testing. \"\n \"Users can apply it for image translation tasks. \\n\"\n \"------------------------------Parameters & data format------------------------------ \\n\"\n \"txt format (train): , \\n\"\n \"txt format (test): \\n\"\n \"Epoch: default=400 \\n\"\n \"Batch size: default=1 \\n\"\n \"Save path: Path to save testing result, default='.\\result' \\n\")\n\nparser.add_argument(\"filename\", help=\"txt file which includes image directions\")\nparser.add_argument(\"mode\", help=\"train or test\")\nparser.add_argument(\"-e\", \"--epoch\", type=int, default=200, dest=\"epoch\")\nparser.add_argument(\"-b\", \"--batch_size\", type=int, default=1, dest=\"batch_size\")\nparser.add_argument(\"-s\", \"--save_path\", type=str, default=None, dest=\"save_path\")\nparser.add_argument(\"-r\", \"--do_resize\", type=bool, default=False, dest=\"do_resize\")\nargs = parser.parse_args()\n\ndef main():\n \n image_path = args.filename if os.path.isfile(args.filename) else sys.exit(\"Incorrect file\")\n \n if args.mode.lower() == 'train':\n with open(image_path) as f: \n image_lists = f.read().splitlines()\n\n for i in image_lists:\n g_train, d_train = i.split(', ')\n sys.exit(\"Found wrong path or wrong format\") if os.path.isfile(d_train) == False else None\n sys.exit(\"Found wrong path or wrong format\") if os.path.isfile(g_train) == False else None\n\n print(\"All images are loaded\")\n \n with tf.Session() as sess:\n model = pix2pix(sess, args)\n model.train(image_lists)\n \n elif args.mode.lower() == 'test':\n with open(image_path) as f: \n image_lists = f.read().splitlines()\n \n for i in image_lists:\n sys.exit(\"Found wrong path or wrong format\") if os.path.isfile(i) == False else None\n print(\"All images are loaded\")\n \n with tf.Session() as sess:\n model = pix2pix(sess, args)\n g_imgs, o_imgs = model.test(image_lists)\n output_path = save_data(g_imgs, o_imgs, args.save_path)\n print('Saved in {}'.format(output_path))\n \n else:\n sys.exit(\"Incorrect mode\")\n \nif __name__ == '__main__':\n main()", "repo_name": "Rayhchs/Pix2pix-tensorflow-implementation", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2684, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 14, "usage_type": "call"}, {"api_name": "argparse.RawTextHelpFormatter", "line_number": 14, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path", "line_number": 42, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path", "line_number": 43, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path", "line_number": 56, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 56, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 66, "usage_type": "call"}]} +{"seq_id": "72027922626", "text": "import sys\nimport re\nimport collections\n\nfrom .output import Output\nfrom .exceptions import ParseError, ValidationError\nfrom ._compat import iteritems\n\n\n# Time types\nMINUTE = \"minute\"\nHOUR = \"hour\"\nDAY = \"day of month\"\nMONTH = \"month\"\nWEEK = \"day of week\"\n\nMONTH_MAP = {\n \"jan\": \"1\",\n \"feb\": \"2\",\n \"mar\": \"3\",\n \"apr\": \"4\",\n \"may\": \"5\",\n \"jun\": \"6\",\n \"jul\": \"7\",\n \"aug\": \"8\",\n \"sep\": \"9\",\n \"oct\": \"10\",\n \"nov\": \"11\",\n \"dec\": \"12\"\n}\nWEEK_MAP = {\n \"sun\": \"0\",\n \"mon\": \"1\",\n \"tue\": \"2\",\n \"wed\": \"3\",\n \"thu\": \"4\",\n \"fri\": \"5\",\n \"sat\": \"6\"\n}\n\nCRON_TIME_SYNTAX_RE = re.compile(r\"^.+\\s+.+\\s+.+\\s+.+\\s+.+$\")\nPREDEFINED_DEFINITIONS = set([\"yearly\", \"annually\", \"monthly\", \"weekly\",\n \"daily\", \"hourly\", \"reboot\"])\n\n\ndef is_month(time):\n \"\"\"Tell whether time is one of the month names.\n\n :param time: a string of time.\n \"\"\"\n return time[:3].lower() in MONTH_MAP\n\n\ndef is_week(time):\n \"\"\"Tell whether time is one of the days of week.\n\n :param time: a string of time.\n \"\"\"\n return time[:3].lower() in WEEK_MAP or \\\n time.lower() in ('weekday', 'weekend')\n\n\ndef get_frequency(every):\n \"\"\"Get frequency value from one every type value:\n\n >>> get_frequency('3.day')\n 3\n\n :param every: One every type value.\n \"\"\"\n return int(every[:every.find('.')])\n\n\ndef get_moment(at):\n \"\"\"Get moment value from one at type value:\n\n >>> get_moment('minute.1')\n 1\n\n :param at: One at type value.\n \"\"\"\n return int(at[at.find('.') + 1:])\n\n\nclass Job(object):\n \"\"\"The plan job base class.\n\n :param task: this is what the job does.\n :param every: how often does the job run.\n :param at: when does the job run.\n :param path: the path you want to run the task on,\n default to be current working directory.\n :param environment: the environment you want to run the task under.\n :param output: the output redirection for the task.\n \"\"\"\n\n def __init__(self, task, every, at=None, path=None,\n environment=None, output=None):\n self.task = task\n self.every = every\n self.at = at\n self.path = path\n self.environment = environment\n self.output = str(Output(output))\n\n @property\n def env(self):\n if not self.environment:\n return ''\n kv_pairs = []\n for k, v in iteritems(self.environment):\n kv_pairs.append('='.join((k, v)))\n return ' '.join(kv_pairs)\n\n @property\n def main_template(self):\n \"\"\"The main job template.\n \"\"\"\n return \"{task}\"\n\n def task_template(self):\n \"\"\"The task template. You should implement this in your own job type.\n The default template is::\n\n 'cd {path} && {environment} {task} {output}'\n \"\"\"\n return 'cd {path} && {environment} {task} {output}'\n\n def process_template(self, template):\n \"\"\"Process template content. Drop multiple spaces in a row and strip\n it.\n \"\"\"\n template = re.sub(r'\\s+', r' ', template)\n template = template.strip()\n return template\n\n def produce_frequency_time(self, frequency, maximum, start=0):\n \"\"\"Translate frequency into comma separated times.\n \"\"\"\n # how many units one time type have\n length = maximum - start + 1\n # if every is the same with unit length\n if frequency == length:\n return str(start)\n # else if every is one unit, we use '*'\n elif frequency == 1:\n return '*'\n # otherwise, we make steps comma separated\n else:\n times = list(range(start, maximum + 1, frequency))\n if length % frequency:\n del times[0]\n times = map(str, times)\n return ','.join(times)\n\n def parse_month(self, month):\n \"\"\"Parses month into month numbers. Month can only occur in\n every value.\n\n :param month: this parameter can be the following values:\n\n jan feb mar apr may jun jul aug sep oct nov dec\n and all of those full month names(case insenstive)\n or .month\n \"\"\"\n if '.' in month:\n frequency = get_frequency(month)\n return self.produce_frequency_time(frequency, 12, 1)\n else:\n month = month[:3].lower()\n return MONTH_MAP[month]\n\n def parse_week(self, week):\n \"\"\"Parses day of week name into week numbers.\n\n :param week: this parameter can be the following values:\n\n sun mon tue wed thu fri sat\n sunday monday tuesday wednesday thursday friday\n saturday\n weekday weekend(case insenstive)\n \"\"\"\n if week.lower() == \"weekday\":\n return \"1,2,3,4,5\"\n elif week.lower() == \"weekend\":\n return \"6,0\"\n else:\n week = week[:3].lower()\n return WEEK_MAP[week]\n\n def parse_every(self):\n \"\"\"Parse every value.\n\n :return: every_type.\n \"\"\"\n every = self.every\n\n if '.minute' in every:\n every_type, frequency = MINUTE, get_frequency(every)\n if frequency not in range(1, 61):\n raise ParseError(\"Your every value %s is invalid, out of\"\n \" minute range[1-60]\" % every)\n elif '.hour' in every:\n every_type, frequency = HOUR, get_frequency(every)\n if frequency not in range(1, 25):\n raise ParseError(\"Your every value %s is invalid, out of\"\n \" hour range[1-24]\" % every)\n elif '.day' in every:\n every_type, frequency = DAY, get_frequency(every)\n if frequency not in range(1, 32):\n raise ParseError(\"Your every value %s is invalid, out of\"\n \" month day range[1-31]\" % every)\n elif '.month' in every or is_month(every):\n every_type = MONTH\n if '.' in every:\n frequency = get_frequency(every)\n if frequency not in range(1, 13):\n raise ParseError(\"Your every value %s is invalid, out of\"\n \" month range[1-12]\" % every)\n elif '.year' in every:\n every_type, frequency = MONTH, get_frequency(every)\n if frequency not in range(1, 2):\n raise ParseError(\"Your every value %s is invalid, out of\"\n \" year range[1]\" % every)\n # Just handle months internally\n self.every = \"12.months\"\n elif is_week(every):\n every_type = WEEK\n else:\n raise ParseError(\"Your every value %s is invalid\" % every)\n\n return every_type\n\n def preprocess_at(self, at):\n \"\"\"Do preprocess for at value, just modify \"12:12\" style moment into\n \"hour.12 minute.12\" style moment value.\n\n :param at: The at value you want to do preprocess.\n \"\"\"\n ats = at.split(' ')\n processed_ats = []\n for at in ats:\n if ':' in at:\n hour, minute = at.split(':')[:2]\n if minute.startswith('0') and len(minute) >= 2:\n minute = minute[1]\n hour = 'hour.' + hour\n minute = 'minute.' + minute\n processed_ats.append(hour)\n processed_ats.append(minute)\n else:\n processed_ats.append(at)\n return ' '.join(processed_ats)\n\n def parse_at(self):\n \"\"\"Parse at value into (at_type, moment) pairs.\n \"\"\"\n pairs = dict()\n if not self.at:\n return pairs\n\n processed_at = self.preprocess_at(self.at)\n ats = processed_at.split(' ')\n at_map = collections.defaultdict(list)\n\n # Parse at value into (at_type, moments_list) pairs.\n # One same at_type can have multiple moments like:\n # at = \"minute.5 minute.10 hour.2\"\n for at in ats:\n if 'minute.' in at:\n at_type, moment = MINUTE, get_moment(at)\n if moment not in range(60):\n raise ParseError(\"Your at value %s is invalid\"\n \" out of minute range[0-59]\" % self.at)\n elif 'hour.' in at:\n at_type, moment = HOUR, get_moment(at)\n if moment not in range(24):\n raise ParseError(\"Your at value %s is invalid\"\n \" out of hour range[0-23]\" % self.at)\n elif 'day.' in at:\n at_type, moment = DAY, get_moment(at)\n if moment not in range(1, 32):\n raise ParseError(\"Your at value %s is invalid\"\n \" out of month day range[1-31]\" % self.at)\n elif 'month.' in at or 'year.' in at:\n raise ParseError(\"Your at value %s is invalid\"\n \" can not set month or year\" % self.at)\n elif is_week(at):\n at_type = WEEK\n moment = self.parse_week(at)\n else:\n raise ParseError(\"Your at value %s is invalid\" % self.at)\n if moment not in at_map[at_type]:\n at_map[at_type].append(moment)\n\n # comma seperate same at_type moments\n for at_type, moments in iteritems(at_map):\n moments = map(str, moments)\n pairs[at_type] = ','.join(moments)\n\n return pairs\n\n def validate_time(self):\n \"\"\"Validate every and at value.\n\n every can be::\n\n [1-60].minute [1-24].hour [1-31].day\n [1-12].month [1].year\n jan feb mar apr may jun jul aug sep oct nov dec\n sun mon tue wed thu fri sat weekday weekend\n or any fullname of month names and day of week names\n (case insensitive)\n\n at::\n\n when every is minute, can not be set\n when every is hour, can be minute.[0-59]\n when every is day of month, can be minute.[0-59], hour.[0-23]\n when every is month, can be day.[1-31], day of week,\n minute.[0-59], hour.[0-23]\n when every is day of week, can be minute.[0-59], hour.[0-23]\n\n at can also be multiple at values seperated by one space.\n \"\"\"\n every_type, every = self.parse_every(), self.every\n ats = self.parse_at()\n if every_type == MINUTE:\n if ats:\n raise ValidationError(\"at can not be set when every is\"\n \" minute related\")\n elif every_type == HOUR:\n for at_type in ats:\n if at_type not in (MINUTE):\n raise ValidationError(\"%s can not be set when every is\"\n \" hour related\" % at_type)\n elif every_type == DAY:\n for at_type in ats:\n if at_type not in (MINUTE, HOUR):\n raise ValidationError(\"%s can not be set when every is\"\n \" month day related\" % at_type)\n elif every_type == MONTH:\n for at_type in ats:\n if at_type not in (MINUTE, HOUR, DAY, WEEK):\n raise ValidationError(\"%s can not be set when every is\"\n \" month related\" % at_type)\n elif every_type == WEEK:\n for at_type in ats:\n if at_type not in (MINUTE, HOUR):\n raise ValidationError(\"%s can not be set when every is\"\n \" week day related\" % at_type)\n\n return every_type, every, ats\n\n def parse_time(self):\n \"\"\"Parse every and at into cron time syntax::\n\n # * * * * * command to execute\n # ┬ ┬ ┬ ┬ ┬\n # │ │ │ │ │\n # │ │ │ │ │\n # │ │ │ │ └─── day of week (0 - 7) (0 to 6 are Sunday to Saturday)\n # │ │ │ └───── month (1 - 12)\n # │ │ └─────── day of month (1 - 31)\n # │ └───────── hour (0 - 23)\n # └─────────── minute (0 - 59)\n\n \"\"\"\n every_type, every, ats = self.validate_time()\n time = ['*'] * 5\n\n if every_type == MINUTE:\n frequency = get_frequency(every)\n time[0] = self.produce_frequency_time(frequency, 59)\n elif every_type == HOUR:\n frequency = get_frequency(every)\n time[0] = ats.get(MINUTE, '0')\n time[1] = self.produce_frequency_time(frequency, 23)\n elif every_type == DAY:\n frequency = get_frequency(every)\n time[0] = ats.get(MINUTE, '0')\n time[1] = ats.get(HOUR, '0')\n time[2] = self.produce_frequency_time(frequency, 31, 1)\n elif every_type == MONTH:\n time[0] = ats.get(MINUTE, '0')\n time[1] = ats.get(HOUR, '0')\n time[2] = ats.get(DAY, '1')\n time[3] = self.parse_month(every)\n time[4] = ats.get(WEEK, '*')\n else:\n time[0] = ats.get(MINUTE, '0')\n time[1] = ats.get(HOUR, '0')\n time[4] = self.parse_week(every)\n\n return ' '.join(time)\n\n @property\n def task_in_cron_syntax(self):\n \"\"\"Cron content task part.\n \"\"\"\n kwargs = {\n \"path\": self.path,\n \"environment\": self.env,\n \"task\": self.task,\n \"output\": self.output\n }\n task = self.task_template().format(**kwargs)\n task = self.process_template(task)\n main = self.main_template.format(task=task)\n return self.process_template(main)\n\n @property\n def time_in_cron_syntax(self):\n \"\"\"Cron content time part.\n \"\"\"\n if CRON_TIME_SYNTAX_RE.match(self.every):\n return self.every\n elif self.every in PREDEFINED_DEFINITIONS:\n return \"@%s\" % self.every\n else:\n return self.parse_time()\n\n @property\n def cron(self):\n \"\"\"Job in cron syntax.\"\"\"\n return ' '.join([self.time_in_cron_syntax, self.task_in_cron_syntax])\n\n\nclass CommandJob(Job):\n \"\"\"The command job.\n \"\"\"\n\n def task_template(self):\n \"\"\"Template::\n\n '{task} {output}'\n \"\"\"\n return '{task} {output}'\n\n\nclass ScriptJob(Job):\n \"\"\"The script job.\n \"\"\"\n\n def task_template(self):\n \"\"\"Template::\n\n 'cd {path} && {environment} %s {task} {output}' % sys.executable\n \"\"\"\n return 'cd {path} && {environment} %s {task} {output}' % sys.executable\n\n\nclass ModuleJob(Job):\n \"\"\"The module job.\n \"\"\"\n\n def task_template(self):\n \"\"\"Template::\n\n '{environment} %s -m {task} {output}' % sys.executable\n \"\"\"\n return '{environment} %s -m {task} {output}' % sys.executable\n\n\nclass RawJob(Job):\n \"\"\"The raw job.\n \"\"\"\n\n def task_template(self):\n \"\"\"Template::\n\n '{task}'\n \"\"\"\n return '{task}'\n", "repo_name": "fengsp/plan", "sub_path": "plan/job.py", "file_name": "job.py", "file_ext": "py", "file_size_in_byte": 15342, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1169, "dataset": "github-code", "pt": "25", "api": [{"api_name": "re.compile", "line_number": 41, "usage_type": "call"}, {"api_name": "output.Output", "line_number": 104, "usage_type": "call"}, {"api_name": "_compat.iteritems", "line_number": 111, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 133, "usage_type": "call"}, {"api_name": "exceptions.ParseError", "line_number": 201, "usage_type": "call"}, {"api_name": "exceptions.ParseError", "line_number": 206, "usage_type": "call"}, {"api_name": "exceptions.ParseError", "line_number": 211, "usage_type": "call"}, {"api_name": "exceptions.ParseError", "line_number": 218, "usage_type": "call"}, {"api_name": "exceptions.ParseError", "line_number": 223, "usage_type": "call"}, {"api_name": "exceptions.ParseError", "line_number": 230, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 264, "usage_type": "call"}, {"api_name": "exceptions.ParseError", "line_number": 273, "usage_type": "call"}, {"api_name": "exceptions.ParseError", "line_number": 278, "usage_type": "call"}, {"api_name": "exceptions.ParseError", "line_number": 283, "usage_type": "call"}, {"api_name": "exceptions.ParseError", "line_number": 286, "usage_type": "call"}, {"api_name": "exceptions.ParseError", "line_number": 292, "usage_type": "call"}, {"api_name": "_compat.iteritems", "line_number": 297, "usage_type": "call"}, {"api_name": "exceptions.ValidationError", "line_number": 330, "usage_type": "call"}, {"api_name": "exceptions.ValidationError", "line_number": 335, "usage_type": "call"}, {"api_name": "exceptions.ValidationError", "line_number": 340, "usage_type": "call"}, {"api_name": "exceptions.ValidationError", "line_number": 345, "usage_type": "call"}, {"api_name": "exceptions.ValidationError", "line_number": 350, "usage_type": "call"}, {"api_name": "sys.executable", "line_number": 450, "usage_type": "attribute"}, {"api_name": "sys.executable", "line_number": 462, "usage_type": "attribute"}]} +{"seq_id": "12201913154", "text": "#!/usr/bin/env python3\n#? --------------------------GSLogger v1.7.1-Beta-------------------------- #\n#! - Simple Application that Scrapes/Optionally Logs URLs Using Google's Search Engine.\n#! - EST. 1/14/21\n\n#TODO ================== :TO-DO: ==================== TODO#\n#* Implement easier way to open urls in browser.\n#* Add options to configure chunk sizes (number of urls per read).\n#* Add options to configure total desired number of results per query.\n#* Add options to configured rate limits (time between reads).\n\n#?----------------------------Modules & Libraries----------------------------#\nfrom datetime import datetime as time\nimport secrets\nfrom os import chdir as cwd\nfrom os.path import abspath\nfrom os.path import dirname as folder\nfrom webbrowser import open as url_open\nimport PySimpleGUI as sg\nfrom googlesearch import search as gSearch\n\n#$ Set working directory to install location:\ncwd(folder(folder(__file__)))\n#?---------------------------------------------------------------------------#\n\n\ndef googleURLs(query: str, logURLs: bool) -> None:\n \"\"\"Search google for the query entered, and scrape resulting URLs.\n\n - As of now, function returns 3 URLs every second broken up into 5 \"chunks\".\n - If desired, you can log the URLs returned by the search engine by checking the \"Log URLs\" field.\n - Saves each URL in a separate file located in the logs directory:\n - `'GSLogger/logs/'`\n\n ### BE WARNED:\n - Use sparingly, otherwise Google may *BLOCK YOUR IP*, temporarily disallowing any and all future experimentation/google searches entirely.\n\n Parameters:\n :param query: topic to search for.\n :type query: str\n :param logURLs: toggle saving a text-log of retrieved URLs upon each search.\n :type logURLs: bool\n :return: URLs from user search paramaters are printed to output window.\n :rtype: None\n \"\"\"\n if logURLs:\n file_uid: str = secrets.token_urlsafe(5)\n with open(fr'./logs/logFile_{file_uid}.log', 'x') as fh:\n fh.write(\n f'> Time of Search:\\n{time.now().strftime(\"> %Y-%m-%d %H:%M:%S\")}\\n\\n> Search Query:\\n\"{query}\"\\n\\n'\n )\n print(\n f'> Time of Search:\\n{time.now().strftime(\"> %Y-%m-%d %H:%M:%S\")}\\n\\n> Search Query:\\n\"{query}\"\\n'\n )\n for url in gSearch(query, tld=\"com\", num=3, stop=15, pause=1.0):\n fh.write(f'> {url}\\n\\n')\n print(f'\\n> {url}')\n return print(\n f'\\n\\n\\t\\t- Process Complete! -\\n- Search log saved within the \"logs\" directory as:\\n\"{abspath(f\"./logs/logFile_{file_uid}.log\")}\"\\n'\n )\n else:\n print(\n f'> Time of Search:\\n{time.now().strftime(\"> %Y-%m-%d %H:%M:%S\")}\\n\\n> Search Query:\\n\"{query}\"\\n'\n )\n\n for url in gSearch(query, tld=\"com\", num=3, stop=15, pause=1.0):\n print(f'\\n> {url}')\n return print('\\n\\n>> Process Complete! <<\\n')\n\n\ndef openUrl(url: str) -> bool:\n \"\"\"Opens URL within user's default browser.\n\n If a browser window is already open, a new tab will be created within the window.\n\n Parameters:\n :param url: URL link to be opened in browser.\n :type url: str\n :return: Opens website in default web-browser.\n :rtype: bool\n \"\"\"\n return url_open(url, 2)\n\n\n#> Color Scheme of window:\nsg.theme('DarkGrey')\n\n#& Window Element Design/Layout:\nmainLayout = [\n #@ Row 1 - Text/Log URLs Option\n [\n sg.Text('Enter a Search Query Below'),\n sg.Checkbox(\n 'Log URLs',\n k='-URL Logging-',\n tooltip='Check to enable search-result logging upon each query.')\n ],\n [ #@ Row 2 - Input/Search\n sg.InputText(do_not_clear=False,\n size=(80, 1),\n tooltip='Enter a search query to look up on Google.',\n k='-User Search Query-'),\n sg.ReadButton('Search',\n tooltip='Click to confirm search query.',\n k='-Submit Query-')\n ],\n [ #@ Row 3 - Output\n sg.Output(\n k='-Output Element-',\n background_color='DarkGrey',\n text_color='Black',\n size=(91, 15),\n tooltip=\n 'Highlight a URL with your cursor and use Ctrl+C to copy a link, then use Ctrl+V to paste a link into the search bar.'\n )\n ],\n #@ Row 4 - Text\n [sg.Text('Copy/Paste URL to Open in Browser')],\n [ #@ Row 5 - URL Input/Browse\n sg.InputText(\n size=(80, 1),\n do_not_clear=False,\n k='-Browse URL-',\n tooltip=\n 'Copy & Paste a URL using Ctrl+C while highlighting a URL and click \"Open URL\" to view the web-page in your browser.'\n ),\n sg.ReadButton('Open URL',\n tooltip='Opens the entered URL in a web browser.',\n k='-Open-')\n ],\n #@ Row 6 - Exit\n [sg.Exit(tooltip='Click to Exit Application.')]\n]\n\n#$ Main Window Properties:\nmainWindow = sg.Window(\n 'GSLogger - v1.7.0b',\n mainLayout,\n auto_size_text=True,\n auto_size_buttons=False,\n text_justification='Center',\n margins=(2, 2), #! pixels\n)\n\n#~ =============== Process Window Events: =============== ~#\nwhile True:\n #NOTE - #? Passes button press events and corresponding input values to the \"event/values\" variables:\n event, values = mainWindow.read()\n #print(event, values) #NOTE - #@ Enable to display window events in console (default=OFF).\n\n #NOTE - #! Closes window upon exit button, or clicking the x.\n if event in [sg.WIN_CLOSED, 'Exit']:\n break\n #& ===== Search Query Events ===== &#\n if event == '-Submit Query-':\n if values['-User Search Query-'] == '':\n sg.popup_ok('\\t- ERROR -',\n 'Entry cannot be blank',\n keep_on_top=True)\n else:\n googleURLs(query=values['-User Search Query-'],\n logURLs=values['-URL Logging-'])\n #& ===== Open URL Events ===== &#\n if event == '-Open-':\n if values['-Browse URL-'] == '':\n sg.popup_ok('\\t- ERROR -',\n '-Entry cannot be blank-',\n keep_on_top=True)\n else:\n openUrl(values['-Browse URL-'])\n\nmainWindow.close()\n", "repo_name": "schlopp96/GSLogger", "sub_path": "src/GSLogger.pyw", "file_name": "GSLogger.pyw", "file_ext": "pyw", "file_size_in_byte": 6364, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.chdir", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 23, "usage_type": "call"}, {"api_name": "secrets.token_urlsafe", "line_number": 47, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 50, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 50, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 53, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 53, "usage_type": "name"}, {"api_name": "googlesearch.search", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 59, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 63, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 63, "usage_type": "name"}, {"api_name": "googlesearch.search", "line_number": 66, "usage_type": "call"}, {"api_name": "webbrowser.open", "line_number": 82, "usage_type": "call"}, {"api_name": "PySimpleGUI.theme", "line_number": 86, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 92, "usage_type": "call"}, {"api_name": "PySimpleGUI.Checkbox", "line_number": 93, "usage_type": "call"}, {"api_name": "PySimpleGUI.InputText", "line_number": 99, "usage_type": "call"}, {"api_name": "PySimpleGUI.ReadButton", "line_number": 103, "usage_type": "call"}, {"api_name": "PySimpleGUI.Output", "line_number": 108, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 118, "usage_type": "call"}, {"api_name": "PySimpleGUI.InputText", "line_number": 120, "usage_type": "call"}, {"api_name": "PySimpleGUI.ReadButton", "line_number": 127, "usage_type": "call"}, {"api_name": "PySimpleGUI.Exit", "line_number": 132, "usage_type": "call"}, {"api_name": "PySimpleGUI.Window", "line_number": 136, "usage_type": "call"}, {"api_name": "PySimpleGUI.WIN_CLOSED", "line_number": 152, "usage_type": "attribute"}, {"api_name": "PySimpleGUI.popup_ok", "line_number": 157, "usage_type": "call"}, {"api_name": "PySimpleGUI.popup_ok", "line_number": 166, "usage_type": "call"}]} +{"seq_id": "42578036160", "text": "# -*- coding: utf-8 -*-\nimport codecs\nimport os\nimport subprocess\nimport sys\nfrom shutil import rmtree\n\nfrom setuptools import setup, find_packages, Command\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n__version__ = None\nexec(open(f\"{here}/slack_sdk/version.py\").read())\n\nlong_description = \"\"\nwith codecs.open(os.path.join(here, \"README.md\"), encoding=\"utf-8\") as readme:\n long_description = readme.read()\n\nvalidate_dependencies = [\n \"pytest>=6.2.5,<7\",\n \"pytest-asyncio<1\", # for async\n \"Flask-Sockets>=0.2,<1\",\n \"Flask>=1,<2\", # TODO: Flask-Sockets is not yet compatible with Flask 2.x\n \"Werkzeug<2\", # TODO: Flask-Sockets is not yet compatible with Flask 2.x\n \"itsdangerous==1.1.0\", # TODO: Flask-Sockets is not yet compatible with Flask 2.x\n \"Jinja2==3.0.3\", # https://github.com/pallets/flask/issues/4494\n \"pytest-cov>=2,<3\",\n \"flake8>=5,<6\",\n \"black==22.8.0\",\n \"click==8.0.4\", # black is affected by https://github.com/pallets/click/issues/2225\n \"psutil>=5,<6\",\n # used only under slack_sdk/*_store\n \"boto3<=2\",\n # TODO: Upgrade to v2\n \"moto>=3,<4\", # For AWS tests\n]\ncodegen_dependencies = [\n \"black==22.10.0\",\n]\n\nneeds_pytest = {\"pytest\", \"test\", \"ptr\"}.intersection(sys.argv)\npytest_runner = [\"pytest-runner\"] if needs_pytest else []\n\n\nclass BaseCommand(Command):\n user_options = []\n\n @staticmethod\n def status(s):\n \"\"\"Prints things in bold.\"\"\"\n print(\"\\033[1m{0}\\033[0m\".format(s))\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def _run(self, s, command):\n try:\n self.status(s + \"\\n\" + \" \".join(command))\n subprocess.check_call(command)\n except subprocess.CalledProcessError as error:\n sys.exit(error.returncode)\n\n\nclass UploadCommand(BaseCommand):\n \"\"\"Support setup.py upload. Thanks @kennethreitz!\"\"\"\n\n description = \"Build and publish the package.\"\n\n def run(self):\n self._run(\n \"Installing upload dependencies ...\",\n [sys.executable, \"-m\", \"pip\", \"install\", \"wheel\"],\n )\n try:\n self.status(\"Removing previous builds ...\")\n rmtree(os.path.join(here, \"dist\"))\n rmtree(os.path.join(here, \"build\"))\n except OSError:\n pass\n\n self._run(\n \"Building Source and Wheel (universal) distribution ...\",\n [sys.executable, \"setup.py\", \"sdist\", \"bdist_wheel\", \"--universal\"],\n )\n self._run(\n \"Installing Twine dependency ...\",\n [sys.executable, \"-m\", \"pip\", \"install\", \"twine\"],\n )\n self._run(\n \"Uploading the package to PyPI via Twine ...\",\n [sys.executable, \"-m\", \"twine\", \"upload\", \"dist/*\"],\n )\n\n\nclass CodegenCommand(BaseCommand):\n def run(self):\n self._run(\n \"Installing required dependencies ...\",\n [sys.executable, \"-m\", \"pip\", \"install\"] + codegen_dependencies,\n )\n\n header = (\n \"# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\"\n \"#\\n\"\n \"# *** DO NOT EDIT THIS FILE ***\\n\"\n \"#\\n\"\n \"# 1) Modify slack_sdk/web/client.py\\n\"\n \"# 2) Run `python setup.py codegen`\\n\"\n \"#\\n\"\n \"# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\"\n \"\\n\"\n )\n with open(f\"{here}/slack_sdk/web/client.py\", \"r\") as original:\n source = original.read()\n import re\n\n async_source = header + source\n async_source = re.sub(\" def \", \" async def \", async_source)\n async_source = re.sub(\"from asyncio import Future\\n\", \"\", async_source)\n async_source = re.sub(\"return self.api_call\\(\", \"return await self.api_call(\", async_source)\n async_source = re.sub(\"-> SlackResponse\", \"-> AsyncSlackResponse\", async_source)\n async_source = re.sub(\n \"from .base_client import BaseClient, SlackResponse\",\n \"from .async_base_client import AsyncBaseClient, AsyncSlackResponse\",\n async_source,\n )\n # from slack_sdk import WebClient\n async_source = re.sub(\n \"class WebClient\\(BaseClient\\):\",\n \"class AsyncWebClient(AsyncBaseClient):\",\n async_source,\n )\n async_source = re.sub(\n \"from slack_sdk import WebClient\",\n \"from slack_sdk.web.async_client import AsyncWebClient\",\n async_source,\n )\n async_source = re.sub(\"= WebClient\\(\", \"= AsyncWebClient(\", async_source)\n async_source = re.sub(\n \" self.files_getUploadURLExternal\\(\",\n \" await self.files_getUploadURLExternal(\",\n async_source,\n )\n async_source = re.sub(\n \" self.files_completeUploadExternal\\(\",\n \" await self.files_completeUploadExternal(\",\n async_source,\n )\n async_source = re.sub(\n \" self.files_info\\(\",\n \" await self.files_info(\",\n async_source,\n )\n async_source = re.sub(\n \"_attach_full_file_metadata\",\n \"_attach_full_file_metadata_async\",\n async_source,\n )\n async_source = re.sub(\n \" _attach_full_file_metadata_async\\(\",\n \" await _attach_full_file_metadata_async(\",\n async_source,\n )\n with open(f\"{here}/slack_sdk/web/async_client.py\", \"w\") as output:\n output.write(async_source)\n\n legacy_source = header + \"from asyncio import Future\\n\" + source\n legacy_source = re.sub(\"-> SlackResponse\", \"-> Union[Future, SlackResponse]\", legacy_source)\n legacy_source = re.sub(\n \"from .base_client import BaseClient, SlackResponse\",\n \"from .legacy_base_client import LegacyBaseClient, SlackResponse\",\n legacy_source,\n )\n legacy_source = re.sub(\n \"class WebClient\\(BaseClient\\):\",\n \"class LegacyWebClient(LegacyBaseClient):\",\n legacy_source,\n )\n legacy_source = re.sub(\n \"from slack_sdk import WebClient\",\n \"from slack_sdk.web.legacy_client import LegacyWebClient\",\n legacy_source,\n )\n legacy_source = re.sub(\"= WebClient\\(\", \"= LegacyWebClient(\", legacy_source)\n with open(f\"{here}/slack_sdk/web/legacy_client.py\", \"w\") as output:\n output.write(legacy_source)\n\n self._run(\n \"Running black (code formatter) ... \",\n [sys.executable, \"-m\", \"black\", f\"{here}/slack_sdk\"],\n )\n\n\nclass ValidateCommand(BaseCommand):\n \"\"\"Support setup.py validate.\"\"\"\n\n description = \"Run Python static code analyzer (flake8), formatter (black) and unit tests (pytest).\"\n\n user_options = [(\"test-target=\", \"i\", \"tests/{test-target}\")]\n\n def initialize_options(self):\n self.test_target = \"\"\n\n def run(self):\n self._run(\n \"Installing test dependencies ...\",\n [sys.executable, \"-m\", \"pip\", \"install\"] + validate_dependencies,\n )\n self._run(\"Running black ...\", [sys.executable, \"-m\", \"black\", f\"{here}/slack\"])\n self._run(\"Running black ...\", [sys.executable, \"-m\", \"black\", f\"{here}/slack_sdk\"])\n self._run(\"Running flake8 for legacy packages ...\", [sys.executable, \"-m\", \"flake8\", f\"{here}/slack\"])\n self._run(\"Running flake8 for slack_sdk package ...\", [sys.executable, \"-m\", \"flake8\", f\"{here}/slack_sdk\"])\n\n target = self.test_target.replace(\"tests/\", \"\", 1)\n self._run(\n \"Running unit tests ...\",\n [\n sys.executable,\n \"-m\",\n \"pytest\",\n \"--cov-report=xml\",\n f\"--cov={here}/slack_sdk\",\n f\"tests/{target}\",\n ],\n )\n\n\nclass UnitTestsCommand(BaseCommand):\n \"\"\"Support setup.py validate.\"\"\"\n\n description = \"Run unit tests (pytest).\"\n user_options = [(\"test-target=\", \"i\", \"tests/{test-target}\")]\n\n def initialize_options(self):\n self.test_target = \"\"\n\n def run(self):\n target = self.test_target.replace(\"tests/\", \"\", 1)\n self._run(\n \"Running unit tests ...\",\n [\n sys.executable,\n \"-m\",\n \"pytest\",\n f\"tests/{target}\",\n ],\n )\n\n\nclass IntegrationTestsCommand(BaseCommand):\n \"\"\"Support setup.py run_integration_tests\"\"\"\n\n description = \"Run integration tests (pytest).\"\n\n user_options = [\n (\"test-target=\", \"i\", \"integration_tests/{test-target}\"),\n ]\n\n def initialize_options(self):\n self.test_target = \"\"\n self.legacy = \"\"\n\n def run(self):\n target = self.test_target.replace(\"integration_tests/\", \"\", 1)\n path = f\"integration_tests/{target}\"\n self._run(\n \"Running integration tests ...\",\n [\n sys.executable,\n \"-m\",\n \"pytest\",\n path,\n ],\n )\n\n\nsetup(\n name=\"slack_sdk\",\n version=__version__,\n description=\"The Slack API Platform SDK for Python\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/slackapi/python-slack-sdk\",\n author=\"Slack Technologies, LLC\",\n author_email=\"opensource@slack.com\",\n python_requires=\">=3.6.0\",\n include_package_data=True,\n license=\"MIT\",\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Developers\",\n \"Topic :: Communications :: Chat\",\n \"Topic :: System :: Networking\",\n \"Topic :: Office/Business\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: 3.10\",\n \"Programming Language :: Python :: 3.11\",\n \"Programming Language :: Python :: 3.12\",\n ],\n keywords=\"slack slack-api web-api slack-rtm websocket chat chatbot chatops\",\n packages=find_packages(\n exclude=[\n \"docs\",\n \"docs-src\",\n \"docs-v2\",\n \"docs-src-v2\",\n \"docs-v3\",\n \"docs-src-v3\",\n \"integration_tests\",\n \"integration_tests_legacy\",\n \"tests\",\n \"tests.*\",\n \"tutorial\",\n ]\n ),\n install_requires=[],\n extras_require={\n # pip install -e \".[testing]\"\n \"testing\": validate_dependencies,\n # pip install -e \".[optional]\"\n \"optional\": [\n # async modules depend on aiohttp\n \"aiodns>1.0\",\n # We recommend using 3.7.1+ for RTMClient\n # https://github.com/slackapi/python-slack-sdk/issues/912\n \"aiohttp>=3.7.3,<4\",\n # used only under slack_sdk/*_store\n \"boto3<=2\",\n # InstallationStore/OAuthStateStore\n # Since v3.20, we no longer support SQLAlchemy 1.3 or older.\n # If you need to use a legacy version, please add our v3.19.5 code to your project.\n \"SQLAlchemy>=1.4,<3\",\n # Socket Mode\n # websockets 9 is not compatible with Python 3.10\n \"websockets>=10,<11\" if sys.version_info.minor > 6 else \"websockets>=9.1,<10\",\n \"websocket-client>=1,<2\",\n ],\n },\n setup_requires=pytest_runner,\n test_suite=\"tests\",\n tests_require=validate_dependencies,\n cmdclass={\n \"upload\": UploadCommand,\n \"codegen\": CodegenCommand,\n \"validate\": ValidateCommand,\n \"unit_tests\": UnitTestsCommand,\n \"integration_tests\": IntegrationTestsCommand,\n },\n)\n", "repo_name": "slackapi/python-slack-sdk", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 12274, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3729, "dataset": "github-code", "pt": "27", "api": [{"api_name": "os.path.abspath", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 10, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path", "line_number": 16, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 41, "usage_type": "attribute"}, {"api_name": "setuptools.Command", "line_number": 45, "usage_type": "name"}, {"api_name": "subprocess.check_call", "line_number": 62, "usage_type": "call"}, {"api_name": "subprocess.CalledProcessError", "line_number": 63, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 64, "usage_type": "call"}, {"api_name": "sys.executable", "line_number": 75, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 79, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 79, "usage_type": "call"}, {"api_name": "os.path", "line_number": 79, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path", "line_number": 80, "usage_type": "attribute"}, {"api_name": "sys.executable", "line_number": 86, "usage_type": "attribute"}, {"api_name": "sys.executable", "line_number": 90, "usage_type": "attribute"}, {"api_name": "sys.executable", "line_number": 94, "usage_type": "attribute"}, {"api_name": "sys.executable", "line_number": 102, "usage_type": "attribute"}, {"api_name": "re.sub", "line_number": 121, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 122, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 123, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 124, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 125, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 131, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 136, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 141, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 142, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 147, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 152, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 157, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 162, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 171, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 172, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 177, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 182, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 187, "usage_type": "call"}, {"api_name": "sys.executable", "line_number": 193, "usage_type": "attribute"}, {"api_name": "sys.executable", "line_number": 210, "usage_type": "attribute"}, {"api_name": "sys.executable", "line_number": 212, "usage_type": "attribute"}, {"api_name": "sys.executable", "line_number": 213, "usage_type": "attribute"}, {"api_name": "sys.executable", "line_number": 214, "usage_type": "attribute"}, {"api_name": "sys.executable", "line_number": 215, "usage_type": "attribute"}, {"api_name": "sys.executable", "line_number": 221, "usage_type": "attribute"}, {"api_name": "sys.executable", "line_number": 245, "usage_type": "attribute"}, {"api_name": "sys.executable", "line_number": 272, "usage_type": "attribute"}, {"api_name": "setuptools.setup", "line_number": 280, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 310, "usage_type": "call"}, {"api_name": "sys.version_info", "line_number": 344, "usage_type": "attribute"}]} +{"seq_id": "8269211004", "text": "#!/usr/bin/env python\r\n# _*_ coding: utf-8 _*_\r\n\r\nimport sys\r\nfrom PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QDesktopWidget, QLabel, QHBoxLayout, QMessageBox, QAction, QFileDialog)\r\nfrom PyQt5.QtGui import QIcon, QFont, QPixmap, QCloseEvent, QDesktopServices\r\nfrom PyQt5.QtCore import Qt, QUrl\r\nfrom util import Modules, InputDialog, PlotWidgets, MachineLearning\r\nimport iLearnPlusBasic, iLearnPlusEstimator, iLearnPlusAutoML, iLearnPlusLoadModel\r\nimport qdarkstyle\r\nimport threading\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nclass MainWindow(QMainWindow):\r\n def __init__(self):\r\n super(MainWindow, self).__init__()\r\n self.initUI()\r\n\r\n def initUI(self):\r\n # initialize GUI\r\n self.setWindowTitle('iLearnPlus')\r\n # self.resize(750, 500)\r\n self.setMaximumSize(600, 400)\r\n self.setMinimumSize(600, 400)\r\n self.setWindowIcon(QIcon('images/logo.ico'))\r\n self.setFont(QFont('Arial'))\r\n bar = self.menuBar()\r\n app = bar.addMenu('Applications')\r\n basic = QAction('iLearnPlus Basic', self)\r\n basic.triggered.connect(self.openBasicWindow)\r\n estimator = QAction('iLearnPlus Estimator', self)\r\n estimator.triggered.connect(self.openEstimatorWindow)\r\n autoML = QAction('iLearnPlus AutoML', self)\r\n autoML.triggered.connect(self.openMLWindow)\r\n loadModel = QAction('Load model(s)', self)\r\n loadModel.triggered.connect(self.openLoadModelWindow)\r\n quit = QAction('Exit', self)\r\n quit.triggered.connect(self.closeEvent)\r\n app.addAction(basic)\r\n app.addAction(estimator)\r\n app.addAction(autoML)\r\n app.addSeparator()\r\n app.addAction(loadModel)\r\n app.addSeparator()\r\n app.addAction(quit)\r\n\r\n visual = bar.addMenu('Visualization')\r\n roc = QAction('Plot ROC curve', self)\r\n roc.triggered.connect(lambda: self.plotCurve('ROC'))\r\n prc = QAction('Plot PRC curve', self)\r\n prc.triggered.connect(lambda: self.plotCurve('PRC'))\r\n boxplot = QAction('Boxplot', self)\r\n boxplot.triggered.connect(self.drawBoxplot)\r\n heatmap = QAction('Heatmap', self)\r\n heatmap.triggered.connect(self.drawHeatmap)\r\n scatterPlot = QAction('Scatter plot', self)\r\n scatterPlot.triggered.connect(self.scatterPlot)\r\n data = QAction('Distribution visualization', self)\r\n data.triggered.connect(self.displayHist)\r\n visual.addActions([roc, prc, boxplot, heatmap, scatterPlot, data])\r\n\r\n tools = bar.addMenu('Tools') \r\n fileTF = QAction('File format transformation', self)\r\n fileTF.triggered.connect(self.openFileTF)\r\n mergeFile = QAction('Merge feature set files into one', self)\r\n mergeFile.triggered.connect(self.mergeCodingFiles)\r\n tools.addActions([fileTF, mergeFile])\r\n\r\n help = bar.addMenu('Help')\r\n document = QAction('Document', self)\r\n document.triggered.connect(self.openDocumentUrl)\r\n about = QAction('About', self)\r\n about.triggered.connect(self.openAbout)\r\n help.addActions([document, about])\r\n\r\n # move window to center\r\n self.moveCenter()\r\n\r\n self.widget = QWidget()\r\n hLayout = QHBoxLayout(self.widget)\r\n hLayout.setAlignment(Qt.AlignCenter)\r\n label = QLabel()\r\n # label.setMaximumWidth(600)\r\n label.setPixmap(QPixmap('images/logo.png'))\r\n hLayout.addWidget(label)\r\n self.setCentralWidget(self.widget)\r\n\r\n def moveCenter(self):\r\n screen = QDesktopWidget().screenGeometry()\r\n size = self.geometry()\r\n newLeft = (screen.width() - size.width()) / 2\r\n newTop = (screen.height() - size.height()) / 2\r\n self.move(int(newLeft), int(newTop))\r\n\r\n def openBasicWindow(self):\r\n self.basicWin = iLearnPlusBasic.ILearnPlusBasic()\r\n self.basicWin.setFont(QFont('Arial', 10))\r\n self.basicWin.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\r\n self.basicWin.close_signal.connect(self.recover)\r\n self.basicWin.show()\r\n self.setDisabled(True)\r\n self.setVisible(False)\r\n\r\n def openEstimatorWindow(self):\r\n self.estimatorWin = iLearnPlusEstimator.ILearnPlusEstimator()\r\n self.estimatorWin.setFont(QFont('Arial', 10))\r\n self.estimatorWin.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\r\n self.estimatorWin.close_signal.connect(self.recover)\r\n self.estimatorWin.show()\r\n self.setDisabled(True)\r\n self.setVisible(False)\r\n\r\n def openMLWindow(self):\r\n self.mlWin = iLearnPlusAutoML.ILearnPlusAutoML()\r\n self.mlWin.setFont(QFont('Arial', 10))\r\n self.mlWin.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\r\n self.mlWin.close_signal.connect(self.recover)\r\n self.mlWin.show()\r\n self.setDisabled(True)\r\n self.setVisible(False)\r\n\r\n def openLoadModelWindow(self):\r\n self.loadWin = iLearnPlusLoadModel.iLearnPlusLoadModel()\r\n # self.loadWin.setFont(QFont('Arial', 10))\r\n self.loadWin.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\r\n self.loadWin.close_signal.connect(self.recover)\r\n self.loadWin.show()\r\n self.setDisabled(True)\r\n self.setVisible(False)\r\n\r\n def closeEvent(self, event):\r\n reply = QMessageBox.question(self, 'Confirm Exit', 'Are you sure want to quit iLearnPlus?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\r\n if reply == QMessageBox.Yes:\r\n sys.exit(0)\r\n else:\r\n if event:\r\n event.ignore()\r\n\r\n def plotCurve(self, curve='ROC'):\r\n self.curveWin = Modules.PlotCurve(curve)\r\n self.curveWin.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\r\n self.curveWin.show()\r\n\r\n def displayHist(self):\r\n self.hist = Modules.Hist()\r\n self.hist.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\r\n self.hist.show()\r\n\r\n def scatterPlot(self):\r\n self.scatter = Modules.ScatterPlot()\r\n self.scatter.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\r\n self.scatter.show()\r\n\r\n def openFileTF(self):\r\n try:\r\n fileName, ok = InputDialog.QFileTransformation.getValues()\r\n if ok:\r\n kw = {}\r\n TFData = MachineLearning.ILearnMachineLearning(kw) \r\n TFData.load_data(fileName, target='Training')\r\n if not TFData.training_dataframe is None:\r\n saved_file, ok = QFileDialog.getSaveFileName(self, 'Save to', './data', 'CSV Files (*.csv);;TSV Files (*.tsv);;SVM Files(*.svm);;Weka Files (*.arff)')\r\n if ok:\r\n ok1 = TFData.save_coder(saved_file, 'training')\r\n if not ok1:\r\n QMessageBox.critical(self, 'Error', str(self.TFData.error_msg), QMessageBox.Ok | QMessageBox.No, QMessageBox.Ok)\r\n except Exception as e:\r\n QMessageBox.critical(self, 'Error', str(e), QMessageBox.Ok | QMessageBox.No, QMessageBox.Ok)\r\n\r\n def mergeCodingFiles(self):\r\n try:\r\n coding_files, ok = QFileDialog.getOpenFileNames(self, 'Open coding files (more file can be selected)', './data', 'CSV Files (*.csv);;TSV Files (*.tsv);;SVM Files(*.svm);;Weka Files (*.arff)')\r\n merged_codings = None\r\n labels = None\r\n if len(coding_files) > 0:\r\n dataframe, datalabel = None, None\r\n for file in coding_files:\r\n if file.endswith('.tsv'):\r\n df = pd.read_csv(file, sep='\\t', header=None)\r\n dataframe = df.iloc[:, 1:]\r\n dataframe.index=['Sample_%s'%i for i in range(dataframe.values.shape[0])]\r\n dataframe.columns = ['F_%s'%i for i in range(dataframe.values.shape[1])]\r\n datalabel = np.array(df.iloc[:, 0]).astype(int)\r\n elif file.endswith('.csv'):\r\n df = pd.read_csv(file, sep=',', header=None)\r\n dataframe = df.iloc[:, 1:]\r\n dataframe.index=['Sample_%s'%i for i in range(dataframe.values.shape[0])]\r\n dataframe.columns = ['F_%s'%i for i in range(dataframe.values.shape[1])]\r\n datalabel = np.array(df.iloc[:, 0]).astype(int)\r\n elif file.endswith('.svm'):\r\n with open(file) as f:\r\n record = f.read().strip()\r\n record = re.sub('\\d+:', '', record)\r\n array = np.array([[i for i in item.split()] for item in record.split('\\n')])\r\n dataframe = pd.DataFrame(array[:, 1:], dtype=float)\r\n dataframe.index=['Sample_%s'%i for i in range(dataframe.values.shape[0])]\r\n dataframe.columns = ['F_%s'%i for i in range(dataframe.values.shape[1])]\r\n datalabel = array[:, 0].astype(int)\r\n else:\r\n with open(file) as f:\r\n record = f.read().strip().split('@')[-1].split('\\n')[1:]\r\n array = np.array([item.split(',') for item in record])\r\n dataframe = pd.DataFrame(array[:, 0:-1], dtype=float)\r\n dataframe.index=['Sample_%s'%i for i in range(dataframe.values.shape[0])]\r\n dataframe.columns = ['F_%s'%i for i in range(dataframe.values.shape[1])]\r\n label = []\r\n for i in array[:, -1]:\r\n if i == 'yes':\r\n label.append(1)\r\n else:\r\n label.append(0)\r\n datalabel = np.array(label)\r\n \r\n if merged_codings is None:\r\n merged_codings = np.hstack((datalabel.reshape((-1, 1)), dataframe.values))\r\n else:\r\n merged_codings = np.hstack((merged_codings, dataframe.values))\r\n if merged_codings is not None:\r\n saved_file, ok = QFileDialog.getSaveFileName(self, 'Save to', './data', 'CSV Files (*.csv);;TSV Files (*.tsv);;SVM Files(*.svm);;Weka Files (*.arff)')\r\n data = merged_codings\r\n if saved_file.endswith('.csv'):\r\n np.savetxt(saved_file, data, fmt=\"%s\", delimiter=',')\r\n if saved_file.endswith('.tsv'):\r\n np.savetxt(saved_file, data, fmt=\"%s\", delimiter='\\t')\r\n if saved_file.endswith('.svm'):\r\n with open(saved_file, 'w') as f:\r\n for line in data:\r\n f.write('%s' % line[0])\r\n for i in range(1, len(line)):\r\n f.write(' %d:%s' % (i, line[i]))\r\n f.write('\\n')\r\n if saved_file.endswith('.arff'):\r\n with open(saved_file, 'w') as f:\r\n f.write('@relation descriptor\\n\\n')\r\n for i in range(1, len(data[0])):\r\n f.write('@attribute f.%d numeric\\n' % i)\r\n f.write('@attribute play {yes, no}\\n\\n')\r\n f.write('@data\\n')\r\n for line in data:\r\n for fea in line[1:]:\r\n f.write('%s,' % fea)\r\n if int(line[0]) == 1:\r\n f.write('yes\\n')\r\n else:\r\n f.write('no\\n')\r\n except Exception as e:\r\n QMessageBox.critical(self, 'Error', str(e), QMessageBox.Ok | QMessageBox.No, QMessageBox.Ok)\r\n\r\n def openDocumentUrl(self):\r\n QDesktopServices.openUrl(QUrl('https://ilearnplus.erc.monash.edu/docs/iLearnPlus_manual.pdf'))\r\n\r\n def openAbout(self):\r\n QMessageBox.information(self, 'iLearnPlus', 'Version: 1.0\\nAuthor: Zhen Chen\\nE-mail: chenzhen-win2009@163.com', QMessageBox.Ok | QMessageBox.No, QMessageBox.Ok)\r\n\r\n def drawBoxplot(self):\r\n try:\r\n x, y, data, ok = InputDialog.QBoxPlotInput.getValues()\r\n if ok:\r\n self.boxWin = PlotWidgets.CustomSingleBoxplotWidget(data, x, y)\r\n self.boxWin.show()\r\n except Exception as e:\r\n QMessageBox.critical(self, 'Error', str(e), QMessageBox.Ok | QMessageBox.No, QMessageBox.Ok)\r\n\r\n def drawHeatmap(self):\r\n try:\r\n x, y, data, ok = InputDialog.QHeatmapInput.getValues()\r\n if ok:\r\n self.heatWin = PlotWidgets.CustomHeatmapWidget(data, x, y)\r\n self.heatWin.show()\r\n except Exception as e:\r\n QMessageBox.critical(self, 'Error', str(e), QMessageBox.Ok | QMessageBox.No, QMessageBox.Ok)\r\n\r\n def recover(self, module):\r\n try:\r\n if module == 'Basic': \r\n del self.basicWin \r\n elif module == 'Estimator':\r\n del self.estimatorWin\r\n elif module == 'AutoML':\r\n del self.mlWin\r\n elif module == 'LoadModel':\r\n del self.loadWin\r\n else:\r\n pass\r\n except Exception as e:\r\n pass\r\n self.setDisabled(False)\r\n self.setVisible(True)\r\n\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n window = MainWindow()\r\n window.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\r\n window.show()\r\n sys.exit(app.exec_())\r\n", "repo_name": "Superzchen/iLearnPlus", "sub_path": "iLearnPlus.py", "file_name": "iLearnPlus.py", "file_ext": "py", "file_size_in_byte": 13786, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 78, "dataset": "github-code", "pt": "25", "api": [{"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 15, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 26, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 27, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 30, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 32, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 34, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 36, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 38, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 49, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 51, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 53, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 55, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 57, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 59, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 64, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 66, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 71, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 73, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 80, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QHBoxLayout", "line_number": 81, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.AlignCenter", "line_number": 82, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 82, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 83, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 85, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QDesktopWidget", "line_number": 90, "usage_type": "call"}, {"api_name": "iLearnPlusBasic.ILearnPlusBasic", "line_number": 97, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 98, "usage_type": "call"}, {"api_name": "qdarkstyle.load_stylesheet_pyqt5", "line_number": 99, "usage_type": "call"}, {"api_name": "iLearnPlusEstimator.ILearnPlusEstimator", "line_number": 106, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 107, "usage_type": "call"}, {"api_name": "qdarkstyle.load_stylesheet_pyqt5", "line_number": 108, "usage_type": "call"}, {"api_name": "iLearnPlusAutoML.ILearnPlusAutoML", "line_number": 115, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 116, "usage_type": "call"}, {"api_name": "qdarkstyle.load_stylesheet_pyqt5", "line_number": 117, "usage_type": "call"}, {"api_name": "iLearnPlusLoadModel.iLearnPlusLoadModel", "line_number": 124, "usage_type": "call"}, {"api_name": "qdarkstyle.load_stylesheet_pyqt5", "line_number": 126, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.question", "line_number": 133, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 133, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Yes", "line_number": 133, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.No", "line_number": 133, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Yes", "line_number": 134, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 134, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 135, "usage_type": "call"}, {"api_name": "util.Modules.PlotCurve", "line_number": 141, "usage_type": "call"}, {"api_name": "util.Modules", "line_number": 141, "usage_type": "name"}, {"api_name": "qdarkstyle.load_stylesheet_pyqt5", "line_number": 142, "usage_type": "call"}, {"api_name": "util.Modules.Hist", "line_number": 146, "usage_type": "call"}, {"api_name": "util.Modules", "line_number": 146, "usage_type": "name"}, {"api_name": "qdarkstyle.load_stylesheet_pyqt5", "line_number": 147, "usage_type": "call"}, {"api_name": "util.Modules.ScatterPlot", "line_number": 151, "usage_type": "call"}, {"api_name": "util.Modules", "line_number": 151, "usage_type": "name"}, {"api_name": "qdarkstyle.load_stylesheet_pyqt5", "line_number": 152, "usage_type": "call"}, {"api_name": "util.InputDialog.QFileTransformation.getValues", "line_number": 157, "usage_type": "call"}, {"api_name": "util.InputDialog.QFileTransformation", "line_number": 157, "usage_type": "attribute"}, {"api_name": "util.InputDialog", "line_number": 157, "usage_type": "name"}, {"api_name": "util.MachineLearning.ILearnMachineLearning", "line_number": 160, "usage_type": "call"}, {"api_name": "util.MachineLearning", "line_number": 160, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getSaveFileName", "line_number": 163, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 163, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.critical", "line_number": 167, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 167, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 167, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.No", "line_number": 167, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.critical", "line_number": 169, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 169, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 169, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.No", "line_number": 169, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getOpenFileNames", "line_number": 173, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 173, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 180, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 184, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 186, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 190, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 195, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 203, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 204, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 213, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 216, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 218, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getSaveFileName", "line_number": 220, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 220, "usage_type": "name"}, {"api_name": "numpy.savetxt", "line_number": 223, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 225, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.critical", "line_number": 248, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 248, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 248, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.No", "line_number": 248, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QDesktopServices.openUrl", "line_number": 251, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QDesktopServices", "line_number": 251, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QUrl", "line_number": 251, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.information", "line_number": 254, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 254, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 254, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.No", "line_number": 254, "usage_type": "attribute"}, {"api_name": "util.InputDialog.QBoxPlotInput.getValues", "line_number": 258, "usage_type": "call"}, {"api_name": "util.InputDialog.QBoxPlotInput", "line_number": 258, "usage_type": "attribute"}, {"api_name": "util.InputDialog", "line_number": 258, "usage_type": "name"}, {"api_name": "util.PlotWidgets.CustomSingleBoxplotWidget", "line_number": 260, "usage_type": "call"}, {"api_name": "util.PlotWidgets", "line_number": 260, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.critical", "line_number": 263, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 263, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 263, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.No", "line_number": 263, "usage_type": "attribute"}, {"api_name": "util.InputDialog.QHeatmapInput.getValues", "line_number": 267, "usage_type": "call"}, {"api_name": "util.InputDialog.QHeatmapInput", "line_number": 267, "usage_type": "attribute"}, {"api_name": "util.InputDialog", "line_number": 267, "usage_type": "name"}, {"api_name": "util.PlotWidgets.CustomHeatmapWidget", "line_number": 269, "usage_type": "call"}, {"api_name": "util.PlotWidgets", "line_number": 269, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.critical", "line_number": 272, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 272, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 272, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.No", "line_number": 272, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 293, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 293, "usage_type": "attribute"}, {"api_name": "qdarkstyle.load_stylesheet_pyqt5", "line_number": 295, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 297, "usage_type": "call"}]} +{"seq_id": "31367396345", "text": "\"\"\"\nprbrown 20201109 16:22\n\nNotes to user:\n--------------\n* This script loops over files in runs/{}/inputs_case/ and projects them forward\nbased on the directions given in inputs/userinput/futurefiles.csv.\nIf new files have been added to inputs_case, you'll need to add rows with \nprocessing directions to futurefiles.csv. \nThe column names should be self-explanatory; most likely there's also at least\none similarly-formatted file in inputs_case that you can copy the settings for.\n\"\"\"\n\n#%%########\n### IMPORTS\nimport gdxpds\nimport pandas as pd\nimport numpy as np\nimport os, sys, csv, pickle, shutil\nimport argparse\nfrom glob import glob\nfrom warnings import warn\n# Time the operation of this script\nfrom ticker import toc, makelog\nimport datetime\ntic = datetime.datetime.now()\n\n#%%#################\n### FIXED INPUTS ###\ndecimals = 6\n\n#%%###############################\n### Functions and dictionaries ###\nthe_unnamer = {'Unnamed: {}'.format(i): '' for i in range(1000)}\n\ndef interpolate_missing_years(df, method='linear'):\n \"\"\"\n Inputs\n ------\n df : pd.DataFrame with columns as integer years\n method : interpolation method [default = 'linear']\n \"\"\"\n dfinterp = (\n df\n ### Switch column names from integer years to timestamps\n .rename(columns={c: pd.Timestamp(str(c)) for c in df.columns})\n ### Add empty columns at year-starts between existing data \n ### (mean doesn't do anything)\n .resample('YS', axis=1).mean()\n ### Interpolate linearly to fill the new columns\n ### (interpolate only works on rows, so pivot, interpolate, pivot again)\n .T.interpolate(method).T\n )\n ### Switch back to integer-year column names\n dfout = dfinterp.rename(columns={c: c.year for c in dfinterp.columns})\n return dfout\n\ndef forecast(\n dfi, lastdatayear, addyears, forecast_fit,\n clip_min=None, clip_max=None):\n \"\"\"\n Project additional year columns and add to df based on directions in forecast_fit.\n forecast_fit can be in ['constant','linear_X','yoy_X','cagr_X','log_X'],\n where 'X' is the number of years to use for the fit.\n 'linear' projects linearly, while 'yoy','cagr','log' (all the same) projects\n a constant compound annual growth rate.\n \"\"\"\n dfo = dfi.copy()\n if forecast_fit == 'constant':\n ### Assign each future year to last data year\n for addyear in addyears:\n dfo[addyear] = dfo[lastdatayear].copy()\n elif forecast_fit.startswith('linear'):\n ### Get the number of years to fit from the futurefiles entry\n fitlength = int(forecast_fit.split('_')[1])\n fityears = list(range(lastdatayear-fitlength, lastdatayear+1))\n ### Fit each row individually\n slope, intercept = {}, {}\n for row in dfo.index:\n slope[row], intercept[row] = np.polyfit(\n x=fityears, y=dfo.loc[row, fityears].values, deg=1)\n ### Apply the row-specific fits\n for addyear in addyears:\n ### Clip if desired, otherwise just project the fit\n if (clip_min is not None) or (clip_max is not None):\n dfo[addyear] = (\n dfo.index.map(intercept) + dfo.index.map(slope) * addyear\n ).values.clip(clip_min,clip_max)\n else:\n dfo[addyear] = dfo.index.map(intercept) + dfo.index.map(slope) * addyear\n elif (forecast_fit.startswith('cagr') \n or forecast_fit.startswith('yoy') \n or forecast_fit.startswith('log')):\n ### Get the number of years to fit from the futurefiles entry\n fitlength = int(forecast_fit.split('_')[1])\n fityears = list(range(lastdatayear-fitlength, lastdatayear+1))\n ### Fit each row individually. By taking the exp() of the fit to log(y)\n ### we get the compound annual growth rate (cagr) + 1.\n cagr = {}\n for row in dfo.index:\n cagr[row] = np.exp(np.polyfit(\n x=fityears, y=np.log(dfo.loc[row, fityears].values), deg=1)[0])\n ### Apply the row-specific fits\n for addyear in addyears:\n ### Clip if desired, otherwise just project the fit\n if (clip_min is not None) or (clip_max is not None):\n dfo[addyear] = (\n dfo[lastdatayear] * (dfo.index.map(cagr) ** (addyear - lastdatayear))\n ).values.clip(clip_min,clip_max)\n else:\n dfo[addyear] = (\n dfo[lastdatayear] * (dfo.index.map(cagr) ** (addyear - lastdatayear)))\n else:\n raise Exception(\n 'forecast_fit == {} is not implemented; try constant, linear, or cagr'.format(\n forecast_fit))\n return dfo\n\n#%%##############\n### PROCEDURE ###\nif __name__ == '__main__':\n\n #%%####################\n ### ARGUMENT INPUTS ###\n parser = argparse.ArgumentParser(description='Extend inputs to arbitrary future year')\n parser.add_argument('reeds_path', help='path to ReEDS directory')\n parser.add_argument('inputs_case', help='path to inputs_case directory')\n\n args = parser.parse_args()\n reeds_path = args.reeds_path\n inputs_case = os.path.join(args.inputs_case, '')\n\n # #%%#########################\n # ### Settings for testing ###\n # reeds_path = os.path.expanduser('~/github/ReEDS-2.0')\n # inputs_case = os.path.join(reeds_path,'runs','v20220411_prmM0_USA2060','inputs_case')\n\n #%% Set up logger\n log = makelog(scriptname=__file__, logpath=os.path.join(inputs_case,'..','gamslog.txt'))\n\n #%% Inputs from switches\n sw = pd.read_csv(\n os.path.join(inputs_case, 'switches.csv'), header=None, index_col=0, squeeze=True)\n endyear = int(sw.endyear)\n distpvscen = sw.distpvscen\n ###### Inputs related to debugging\n ### Set debug == True to write to a new folder (inputs_case/future/), leaving original files\n ### intact. If debug == False (default), the original files are overwritten.\n debug = False\n ### missing: 'raise' or 'warn'\n missing = 'raise'\n ### verbose: 0, 1, 2\n verbose = 2\n\n #%%####################################\n ### If endyear <= 2050, exit the script\n if endyear <= 2050:\n print('endyear = {} <= 2050, so skip forecast.py'.format(endyear))\n quit()\n else:\n print('Starting forecast.py', flush=True)\n\n #%%###################\n ### Derived inputs ###\n\n ### Get the case name (ReEDS-2.0/runs/{casename}/inputscase/)\n casename = inputs_case.split(os.sep)[-3]\n\n ### DEBUG: Make the outputs directory\n if debug:\n outpath = os.path.join(inputs_case, 'future', '')\n os.makedirs(outpath, exist_ok=True)\n else:\n outpath = inputs_case\n ### Get the modeled years\n tmodel_new = pd.read_csv(\n os.path.join(inputs_case,'modeledyears.csv')).columns.astype(int).values\n\n ### Get the settings file\n futurefiles = pd.read_csv(\n os.path.join(reeds_path, 'inputs', 'userinput', 'futurefiles.csv'),\n dtype={\n 'header':'category', 'ignore':int, 'wide':int,\n 'year_col':str, 'fix_cols':str, 'clip_min':str, 'clip_max':str,\n }\n )\n ### Fill in the missing parts of filenames\n futurefiles.filename = futurefiles.filename.map(\n lambda x: x.format(casename=casename, distpvscen=distpvscen)\n )\n ### If any files are missing, stop and alert the user\n inputfiles = [os.path.basename(f) for f in glob(os.path.join(inputs_case,'*'))]\n missingfiles = [\n f for f in inputfiles if ((f not in futurefiles.filename.values) and ('.' in f))]\n if any(missingfiles):\n if missing == 'raise':\n raise Exception(\n 'Missing future projection method for:\\n{}\\n'\n '>>> Need to add entries for these files to futurefiles.csv'\n .format('\\n'.join(missingfiles))\n )\n else:\n from warnings import warn\n warn(\n 'Missing future directions for:\\n{}\\n'\n '>>> For this run, these files are copied without modification'\n .format('\\n'.join(missingfiles))\n )\n for filename in missingfiles:\n shutil.copy(os.path.join(inputs_case, filename), os.path.join(outpath, filename))\n print('copied {}, which is missing from futurefiles.csv'.format(filename),\n flush=True)\n\n #%% Loop it\n for i in futurefiles.index:\n filename = futurefiles.loc[i, 'filename']\n if futurefiles.loc[i,'ignore'] == 0:\n pass\n ### if ignore == 1, just copy the file to outpath and skip the rest\n elif futurefiles.loc[i, 'ignore'] == 1:\n if debug:\n shutil.copy(os.path.join(inputs_case, filename), os.path.join(outpath, filename))\n if verbose > 1:\n print('ignored: {}'.format(filename), flush=True)\n continue\n ### if ignore == 2, need to project for EFS or copy otherwise\n elif futurefiles.loc[i, 'ignore'] == 2:\n ### Read the file to determine if it's formatted for default or EFS load\n dftest = pd.read_csv(os.path.join(inputs_case, filename), header=0, nrows=20)\n ### If it has more than 10 columns (indicating EFS), follow the directions\n if dftest.shape[1] > 10:\n pass\n ### Otherwise (indicating default), just copy it\n else:\n if debug:\n shutil.copy(os.path.join(inputs_case, filename), os.path.join(outpath, filename))\n if verbose > 1:\n print('EFS special case: {}'.format(filename), flush=True)\n continue\n\n ### If the file isn't in inputs_case, skip it\n if filename not in inputfiles:\n if verbose > 1:\n print('skipped since not in inputs_case: {}'.format(filename))\n continue\n\n #%% Settings\n ### header: 0 if file has column labels, otherwise 'None'\n header = (None if futurefiles.loc[i,'header'] == 'None'\n else 'keepindex' if futurefiles.loc[i,'header'] == 'keepindex'\n else int(futurefiles.loc[i,'header']))\n ### year_col: usually 't' or 'year', or 'wide' if file uses years as columns\n year_col = futurefiles.loc[i, 'year_col']\n ### forecast_fit: '{method}_{fityears}' or 'constant', with method in \n ### ['linear','cagr'] and fityears indicating the number of historical years\n ### (counting backwards from the last data year) to use for the projection.\n ### If set to 'constant', will use the value from the last data year for\n ### all future years.\n forecast_fit = futurefiles.loc[i, 'forecast_fit']\n ### fix_cols: indicate columns to use as for fields that should be projected\n ### independently to future years (e.g. r, szn, tech)\n fix_cols = futurefiles.loc[i, 'fix_cols']\n fix_cols = (list() if fix_cols == 'None' else fix_cols.split(','))\n ### wide: 1 if any parameters are in wide format, otherwise 0\n wide = futurefiles.loc[i, 'wide']\n ### clip_min, clip_max: Indicate min and max values for projected data.\n ### In general, costs should have clip_min = 0 (so they don't go negative)\n clip_min, clip_max = futurefiles.loc[i,['clip_min','clip_max']]\n clip_min = (None if clip_min.lower()=='none' else int(clip_min))\n clip_max = (None if clip_max.lower()=='none' else int(clip_max))\n filetype = futurefiles.loc[i, 'filetype']\n ### key: only used for gdx files, indicating the parameter name. \n ### gdx files need a separate line in futurefiles.csv for each parameter.\n key = futurefiles.loc[i, 'key']\n efs = False\n\n ### Load it\n if filetype in ['.csv', '.csv.gz']:\n dfin = pd.read_csv(os.path.join(inputs_case, filename), header=header,)\n elif filetype == '.h5':\n ### Currently load.h5 is the only h5 file we need to project forward, so the\n ### procedure is currently specific to that file\n dfin = pd.read_hdf(os.path.join(inputs_case, filename))\n if header == 'keepindex':\n indexnames = list(dfin.index.names)\n dfin.reset_index(inplace=True)\n ### We only need to do the projection for load.h5 if we're using EFS load,\n ### which has a (year,hour) multiindex (which we reset above to columns). \n ### If dfin doesn't have 'year' and 'hour' columns, we can therefore skip this file.\n if (('year' in dfin.columns) and ('hour' in dfin.columns)):\n efs = True\n else:\n if debug:\n shutil.copy(os.path.join(inputs_case, filename), os.path.join(outpath, filename))\n if verbose > 1:\n print('ignored: {}'.format(filename), flush=True)\n continue\n elif filetype == '.txt':\n dfin = pd.read_csv(os.path.join(inputs_case, filename), header=header, sep=' ')\n ### Remove parentheses and commas\n for col in [0,1]:\n dfin[col] = dfin[col].map(\n lambda x: x.replace('(','').replace(')','').replace(',',''))\n ### Split the index column on periods\n num_indices = len(dfin.loc[0,0].split('.'))\n indexcols = ['i{}'.format(index) for index in range(num_indices)]\n for index in range(num_indices):\n dfin['i{}'.format(index)] = dfin[0].map(lambda x: x.split('.')[index])\n ### Make the data column numeric\n dfin[1] = dfin[1].astype(float)\n ### Reorder and rename the columns\n dfin = dfin[indexcols + [1]].copy()\n dfin.columns = list(range(num_indices+1))\n elif filetype == '.gdx':\n ### Read in the full gdx file, but only change the 'key' parameter\n ### given in futurefiles. That's wasteful, but there are currently no\n ### active gdx files.\n dfall = gdxpds.to_dataframes(os.path.join(inputs_case, filename))\n dfin = dfall[key]\n else:\n raise Exception('Unsupported filetype: {}'.format(filename))\n\n dfin.rename(columns={c:str(c) for c in dfin.columns}, inplace=True)\n columns = dfin.columns.tolist()\n\n #%% Reshape to wide format with year as column\n if (len(fix_cols) == 0) and (wide == 0):\n ### File is simply (year,data)\n ### So just set year as index and transpose\n df = dfin.set_index(year_col).T\n elif (len(fix_cols) > 0) and (year_col == 'wide'):\n ### File has some fixed columns and then years in wide format\n ### Easy - just set the fix_cols as indices and keep years as columns\n df = dfin.set_index(fix_cols)\n elif (wide) and (year_col != 'wide') and (len(fix_cols) == 0):\n ### Some value other than year is in wide format\n ### So set years as index and transpose\n df = dfin.set_index(year_col).T\n elif (wide) and (year_col != 'wide') and (len(fix_cols) > 0):\n ### Some value other than year is in wide format\n ### So set years (and other fix_cols) as index and transpose\n df = (dfin.melt(id_vars=[year_col]+fix_cols, ignore_index=False)\n .set_index([year_col]+fix_cols+['variable'])\n .unstack(year_col))\n ### Get the value name (in this case for the non-year wide column), then drop it\n valuename = df.columns.get_level_values(0).unique().tolist()\n if len(valuename) > 1:\n raise Exception('Too many data columns: {}'.format(valuename))\n valuename = valuename[0]\n df = df[valuename].copy()\n elif (len(fix_cols) > 0) and (year_col != 'wide') and (not wide):\n ### Tidy format - fix the fix_cols and unstack the year_col\n ### same as `df = dfin.pivot(index=fix_cols, columns=year_col)`, but \n ### pivot modifies fix_cols for some reason\n df = dfin.set_index(fix_cols+[year_col]).unstack(year_col)#.droplevel(0, axis=1)\n ### Get the value name, then drop it\n valuename = df.columns.get_level_values(0).unique().tolist()\n if len(valuename) > 1:\n raise Exception('Too many data columns: {}'.format(valuename))\n valuename = valuename[0]\n df = df[valuename].copy()\n else:\n raise Exception('Unknown data type for {}'.format(filename))\n\n #%% All columns should now be years\n df.rename(columns={c: int(c) for c in df.columns}, inplace=True)\n lastdatayear = max([int(c) for c in df.columns])\n ### Interpolate to make sure we have data at yearly frequency\n df = interpolate_missing_years(df)\n ### Get indices for projection\n addyears = list(range(lastdatayear+1, endyear+1))\n ### If file is for EFS hourlyload, only project for years in tmodel_new to save time\n if efs:\n addyears = [y for y in addyears if y in tmodel_new]\n\n #%% Do the projection\n df = forecast(\n dfi=df, lastdatayear=lastdatayear, addyears=addyears, \n forecast_fit=forecast_fit, clip_min=clip_min, clip_max=clip_max)\n\n ## #%% Would be nice to keep only the years in tmodel_new, but\n ## #%% createmodel breaks when the following line is active (not sure why)\n ## df.drop([y for y in df.columns if y not in tmodel_new], axis=1, inplace=True)\n\n #%% Put back in original format\n if (len(fix_cols) == 0) and (wide == 0):\n dfout = df.T.reset_index()\n elif (len(fix_cols) > 0) and (year_col == 'wide'):\n dfout = df.reset_index()\n elif (wide) and (year_col != 'wide') and (len(fix_cols) == 0):\n dfout = df.T.reset_index()\n elif (wide) and (year_col != 'wide') and (len(fix_cols) > 0):\n dfout = df.stack().unstack('variable').reset_index()[columns]\n elif (len(fix_cols) > 0) and (year_col != 'wide') and (not wide):\n dfout = df.stack().rename(valuename).dropna().reset_index()\n\n ### Unname any unnamed columns\n dfout.rename(columns=the_unnamer, inplace=True)\n\n #%% Write it\n if filetype in ['.csv','.csv.gz']:\n dfout.round(decimals).to_csv(\n os.path.join(outpath, filename),\n header=(False if header is None else True),\n index=False,\n )\n elif filetype == '.h5':\n if header == 'keepindex':\n dfwrite = dfout.sort_values(indexnames).set_index(indexnames)\n dfwrite.columns.name = None\n else:\n dfwrite = dfout\n dfwrite.round(decimals).to_hdf(os.path.join(outpath, filename), key='data', complevel=4)\n elif filetype == '.txt':\n dfwrite = dfout.sort_index(axis=1)\n ### Make the GAMS-readable index\n dfwrite.index = dfwrite.apply(\n lambda row: '(' + '.'.join([str(row[str(c)]) for c in range(num_indices)]) + ')',\n axis=1\n )\n ### Downselect to data column\n dfwrite = dfwrite[str(num_indices)].round(decimals)\n ### Add commas to data column, remove from last entry\n dfwrite = dfwrite.astype(str) + ','\n dfwrite.iloc[-1] = dfwrite.iloc[-1].replace(',','')\n ### Write it\n dfwrite.to_csv(\n os.path.join(outpath, filename),\n header=(False if header is None else True),\n index=True, sep=' ',\n )\n elif filetype == '.gdx':\n ### Overwrite the projected parameter\n dfall[key] = dfout.round(decimals)\n ### Write the whole file\n gdxpds.to_gdx(dfall, outpath+filename)\n\n if verbose > 1:\n print(\n 'projected from {} to {}: {}'.format(lastdatayear, endyear, filename), \n flush=True)\n\n toc(tic=tic, year=0, process='input_processing/forecast.py', \n path=os.path.join(inputs_case,'..'))\n print('Finished forecast.py')\n\n## ##############################\n## ### Initial one-time setup ###\n## infiles = pd.DataFrame(\n## {'filename': [os.path.basename(f) for f in glob(os.path.join(inputs_case,'*'))]})\n## infiles['filetype'] = infiles.filename.map(lambda x: os.path.splitext(x)[1])\n## infiles.sort_values(['filetype','filename'], inplace=True)\n## infiles.to_csv(\n## os.path.join(reeds_path, 'inputs', 'userinput', 'futurefiles.csv'),\n## index=False\n## )", "repo_name": "NREL/ReEDS-2.0", "sub_path": "input_processing/forecast.py", "file_name": "forecast.py", "file_ext": "py", "file_size_in_byte": 20726, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 90, "dataset": "github-code", "pt": "25", "api": [{"api_name": "datetime.datetime.now", "line_number": 26, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 26, "usage_type": "attribute"}, {"api_name": "pandas.Timestamp", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.polyfit", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.polyfit", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 102, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 125, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 131, "usage_type": "call"}, {"api_name": "os.path", "line_number": 131, "usage_type": "attribute"}, {"api_name": "ticker.makelog", "line_number": 139, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 139, "usage_type": "call"}, {"api_name": "os.path", "line_number": 139, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 142, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 143, "usage_type": "call"}, {"api_name": "os.path", "line_number": 143, "usage_type": "attribute"}, {"api_name": "os.sep", "line_number": 167, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 171, "usage_type": "call"}, {"api_name": "os.path", "line_number": 171, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 172, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 176, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 177, "usage_type": "call"}, {"api_name": "os.path", "line_number": 177, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 180, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 181, "usage_type": "call"}, {"api_name": "os.path", "line_number": 181, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 192, "usage_type": "call"}, {"api_name": "os.path", "line_number": 192, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 192, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 192, "usage_type": "call"}, {"api_name": "warnings.warn", "line_number": 204, "usage_type": "call"}, {"api_name": "shutil.copy", "line_number": 210, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 210, "usage_type": "call"}, {"api_name": "os.path", "line_number": 210, "usage_type": "attribute"}, {"api_name": "shutil.copy", "line_number": 222, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 222, "usage_type": "call"}, {"api_name": "os.path", "line_number": 222, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 229, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 229, "usage_type": "call"}, {"api_name": "os.path", "line_number": 229, "usage_type": "attribute"}, {"api_name": "shutil.copy", "line_number": 236, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 236, "usage_type": "call"}, {"api_name": "os.path", "line_number": 236, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 279, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 279, "usage_type": "call"}, {"api_name": "os.path", "line_number": 279, "usage_type": "attribute"}, {"api_name": "pandas.read_hdf", "line_number": 283, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 283, "usage_type": "call"}, {"api_name": "os.path", "line_number": 283, "usage_type": "attribute"}, {"api_name": "shutil.copy", "line_number": 294, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 294, "usage_type": "call"}, {"api_name": "os.path", "line_number": 294, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 299, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 299, "usage_type": "call"}, {"api_name": "os.path", "line_number": 299, "usage_type": "attribute"}, {"api_name": "gdxpds.to_dataframes", "line_number": 318, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 318, "usage_type": "call"}, {"api_name": "os.path", "line_number": 318, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 403, "usage_type": "call"}, {"api_name": "os.path", "line_number": 403, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 413, "usage_type": "call"}, {"api_name": "os.path", "line_number": 413, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 428, "usage_type": "call"}, {"api_name": "os.path", "line_number": 428, "usage_type": "attribute"}, {"api_name": "gdxpds.to_gdx", "line_number": 436, "usage_type": "call"}, {"api_name": "ticker.toc", "line_number": 443, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 444, "usage_type": "call"}, {"api_name": "os.path", "line_number": 444, "usage_type": "attribute"}]} +{"seq_id": "23145271624", "text": "from logger_utils.CustomFormatter import CustomFormatter\r\nimport datetime\r\n\r\nimport logging\r\n\r\n\r\ndef init_logger(logger: logging.Logger):\r\n logger.setLevel(logging.DEBUG)\r\n\r\n # Define format for logs\r\n fmt = '%(asctime)s | %(levelname)2s | %(message)s'\r\n\r\n # Create stdout handler for logging to the console (logs all five levels)\r\n stdout_handler = logging.StreamHandler()\r\n stdout_handler.setLevel(logging.DEBUG)\r\n stdout_handler.setFormatter(CustomFormatter(fmt))\r\n\r\n # Create file handler for logging to a file (logs all five levels)\r\n today = datetime.date.today()\r\n file_handler = logging.FileHandler('logs\\\\files_server_{}.log'.format(today.strftime('%Y_%m_%d')))\r\n file_handler.setLevel(logging.DEBUG)\r\n file_handler.setFormatter(logging.Formatter(fmt))\r\n\r\n # Add both handlers to the logger_utils\r\n logger.addHandler(stdout_handler)\r\n logger.addHandler(file_handler)\r\n", "repo_name": "zivdayan/maman_15_server", "sub_path": "logger_utils/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 922, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "logging.Logger", "line_number": 7, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 8, "usage_type": "attribute"}, {"api_name": "logging.StreamHandler", "line_number": 14, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 15, "usage_type": "attribute"}, {"api_name": "logger_utils.CustomFormatter.CustomFormatter", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 19, "usage_type": "attribute"}, {"api_name": "logging.FileHandler", "line_number": 20, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 21, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 22, "usage_type": "call"}]} +{"seq_id": "70383889346", "text": "import numpy as np\nfrom scipy.stats import beta\nimport matplotlib.pyplot as plt\n\n\ndef thompson_sampling_policy(state, visualize = False, plot_title = ''):\n action = None\n max_bound = 0\n\n color_list = ['red', 'blue', 'green', 'black', 'yellow']\n\n for b, trials in state.items():\n w = len([r for r in trials if r == 1])\n l = len([r for r in trials if r == -1])\n\n if w + l == 0:\n avg = 0\n else:\n avg = round(w / (w + l), 2)\n\n random_beta = np.random.beta(w + 1, l + 1)\n if random_beta > max_bound:\n max_bound = random_beta\n action = b\n\n if visualize:\n color = color_list[b % len(color_list)]\n x = np.linspace(beta.ppf(0.01, w, l), beta.ppf(0.99, w, l), 100)\n plt.plot(\n x, beta.pdf(x, w, l),\n label = f'Bandit {b}| avg={avg}, v={round(random_beta,2)}',\n color = color, linewidth = 3)\n plt.axvline(x = random_beta, color = color, linestyle = '--')\n\n if visualize:\n plt.title('Thompson Sampling: Beta Distribution. ' + plot_title)\n plt.legend()\n plt.show()\n\n return action\n", "repo_name": "bpbpublications/Practical-Deep-Reinforcement-Learning-with-Python", "sub_path": "Chapter 04/policy/thompson_sampling.py", "file_name": "thompson_sampling.py", "file_ext": "py", "file_size_in_byte": 1189, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 12, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.random.beta", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 21, "usage_type": "attribute"}, {"api_name": "numpy.linspace", "line_number": 28, "usage_type": "call"}, {"api_name": "scipy.stats.beta.ppf", "line_number": 28, "usage_type": "call"}, {"api_name": "scipy.stats.beta", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "scipy.stats.beta.pdf", "line_number": 30, "usage_type": "call"}, {"api_name": "scipy.stats.beta", "line_number": 30, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axvline", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}]} +{"seq_id": "36994860203", "text": "#!/usr/bin/env python3.7\nfrom buttplug.client import (ButtplugClientWebsocketConnector, ButtplugClient,\n ButtplugClientDevice, ButtplugClientConnectorError)\nfrom buttplug.core import ButtplugLogLevel\nimport asyncio\n\nclass SexToyBackend:\n def __init__(self, websocket=\"ws://127.0.0.1:12345\", name=\"Lightning Plug\"):\n self.ws = websocket\n self.name = name\n asyncio.run(self.vibrate(), debug=True)\n\n async def vibrate(self, intensity=0.5, duration=0.3):\n self.intensity = intensity\n self.duration = duration\n # create client\n client = ButtplugClient(self.name)\n # connect to websocket of the intiface\n connector = ButtplugClientWebsocketConnector(self.ws)\n # add event handler\n client.device_added_handler += self.device_added\n # asyncio\n # connect to device\n try:\n await client.connect(connector)\n except ButtplugClientConnectorError as e:\n print(\"Could not connect to server, exiting: {}\".format(e.message))\n return\n\n # get logs\n await client.request_log(ButtplugLogLevel.debug)\n # search for devices\n await client.start_scanning()\n\n # wait\n task = asyncio.create_task(self.cancel_me())\n try:\n await task\n except asyncio.CancelledError:\n pass\n\n # ctrl-c -> stop\n await client.stop_scanning()\n # Now that we've done that, we just disconnect and we're done!\n await client.disconnect()\n\n # just sleep and wait for ctrl-c\n async def cancel_me(self):\n try:\n await asyncio.sleep(1)\n except asyncio.CancelledError:\n pass\n\n def device_added(self, emitter, dev: ButtplugClientDevice):\n asyncio.create_task(self.vibrate_task(dev))\n\n async def vibrate_task(self, dev: ButtplugClientDevice):\n # print(\"Device Added: {}\".format(dev.name))\n # check we can vibrate\n if \"VibrateCmd\" in dev.allowed_messages.keys():\n # vibrate at 50% speed for 1 second\n await dev.send_vibrate_cmd(self.intensity)\n await asyncio.sleep(self.duration)\n await dev.send_stop_device_cmd()\n # check if it can move\n if \"LinearCmd\" in dev.allowed_messages.keys():\n # move to 90% in 1 second (1000ms).\n await dev.send_linear_cmd((int(self.duration*1e3), self.intensity))\n # wait 1s and move back\n await asyncio.sleep(self.duration)\n await dev.send_linear_cmd((int(self.duration*1e3), 0))\n\n def notify(self, intensity, duration):\n asyncio.run(self.vibrate(intensity, duration), debug=True)\n\n def on_route(self, fee_msat, **kwargs):\n self.notify(0.5, 0.3)\n\n def on_payment(self, amount_msat, **kwargs):\n self.notify(0.5, 1)\n\nif __name__ == '__main__':\n dev = SexToyBackend()\n dev.on_route(100)\n dev.on_payment(1000)\n", "repo_name": "citrusferox/lightningplug", "sub_path": "backends/sextoy.py", "file_name": "sextoy.py", "file_ext": "py", "file_size_in_byte": 2976, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "asyncio.run", "line_number": 11, "usage_type": "call"}, {"api_name": "buttplug.client.ButtplugClient", "line_number": 17, "usage_type": "call"}, {"api_name": "buttplug.client.ButtplugClientWebsocketConnector", "line_number": 19, "usage_type": "call"}, {"api_name": "buttplug.client.ButtplugClientConnectorError", "line_number": 26, "usage_type": "name"}, {"api_name": "buttplug.core.ButtplugLogLevel.debug", "line_number": 31, "usage_type": "attribute"}, {"api_name": "buttplug.core.ButtplugLogLevel", "line_number": 31, "usage_type": "name"}, {"api_name": "asyncio.create_task", "line_number": 36, "usage_type": "call"}, {"api_name": "asyncio.CancelledError", "line_number": 39, "usage_type": "attribute"}, {"api_name": "asyncio.sleep", "line_number": 50, "usage_type": "call"}, {"api_name": "asyncio.CancelledError", "line_number": 51, "usage_type": "attribute"}, {"api_name": "buttplug.client.ButtplugClientDevice", "line_number": 54, "usage_type": "name"}, {"api_name": "asyncio.create_task", "line_number": 55, "usage_type": "call"}, {"api_name": "buttplug.client.ButtplugClientDevice", "line_number": 57, "usage_type": "name"}, {"api_name": "asyncio.sleep", "line_number": 63, "usage_type": "call"}, {"api_name": "asyncio.sleep", "line_number": 70, "usage_type": "call"}, {"api_name": "asyncio.run", "line_number": 74, "usage_type": "call"}]} +{"seq_id": "8370667138", "text": "# -*- coding: utf-8 -*-\nfrom configs import get_configs\nfrom data_preprocessing import DataPreprocess\nfrom utils.log import logger\nfrom xgboost_model import XgboostGridSearchModel\nfrom da_rnn_model import DaRnnModel\nfrom tcn_model import TcnModel\n\nSEPARATOR = \"\\n\" + \"*\" * 75 + \"Sperator\" + \"*\" * 75\n\n\ndef main():\n logger.info(SEPARATOR)\n configs = get_configs()\n\n # Run data preprocess\n if configs.data_preprocess_active:\n logger.info(configs)\n preprocess = DataPreprocess(configs)\n preprocess.data_preprocess()\n logger.info(\"Data preprocess finished!\")\n # Run train model\n if configs.da_rnn_model_active:\n logger.info(configs)\n da_rnn_model = DaRnnModel(configs)\n da_rnn_model.run()\n logger.info(\"Da_rnnModel finished!\")\n if configs.xgboost_gridsearch_model_active:\n xgboost_model = XgboostGridSearchModel(configs)\n xgboost_model.run()\n logger.info(\"XGboost finished!\")\n if configs.tcn_big_file_model_active:\n tcn_model = TcnModel(configs)\n tcn_model.run()\n logger.info(\"TcnModel finished!\")\n\n\nif __name__ == '__main__':\n main()\n", "repo_name": "MrGuo2/MyProject", "sub_path": "sequence_predict/src/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1156, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "utils.log.logger.info", "line_number": 13, "usage_type": "call"}, {"api_name": "utils.log.logger", "line_number": 13, "usage_type": "name"}, {"api_name": "configs.get_configs", "line_number": 14, "usage_type": "call"}, {"api_name": "configs.data_preprocess_active", "line_number": 17, "usage_type": "attribute"}, {"api_name": "utils.log.logger.info", "line_number": 18, "usage_type": "call"}, {"api_name": "utils.log.logger", "line_number": 18, "usage_type": "name"}, {"api_name": "data_preprocessing.DataPreprocess", "line_number": 19, "usage_type": "call"}, {"api_name": "utils.log.logger.info", "line_number": 21, "usage_type": "call"}, {"api_name": "utils.log.logger", "line_number": 21, "usage_type": "name"}, {"api_name": "configs.da_rnn_model_active", "line_number": 23, "usage_type": "attribute"}, {"api_name": "utils.log.logger.info", "line_number": 24, "usage_type": "call"}, {"api_name": "utils.log.logger", "line_number": 24, "usage_type": "name"}, {"api_name": "da_rnn_model.DaRnnModel", "line_number": 25, "usage_type": "call"}, {"api_name": "da_rnn_model.run", "line_number": 26, "usage_type": "call"}, {"api_name": "utils.log.logger.info", "line_number": 27, "usage_type": "call"}, {"api_name": "utils.log.logger", "line_number": 27, "usage_type": "name"}, {"api_name": "configs.xgboost_gridsearch_model_active", "line_number": 28, "usage_type": "attribute"}, {"api_name": "xgboost_model.XgboostGridSearchModel", "line_number": 29, "usage_type": "call"}, {"api_name": "xgboost_model.run", "line_number": 30, "usage_type": "call"}, {"api_name": "utils.log.logger.info", "line_number": 31, "usage_type": "call"}, {"api_name": "utils.log.logger", "line_number": 31, "usage_type": "name"}, {"api_name": "configs.tcn_big_file_model_active", "line_number": 32, "usage_type": "attribute"}, {"api_name": "tcn_model.TcnModel", "line_number": 33, "usage_type": "call"}, {"api_name": "tcn_model.run", "line_number": 34, "usage_type": "call"}, {"api_name": "utils.log.logger.info", "line_number": 35, "usage_type": "call"}, {"api_name": "utils.log.logger", "line_number": 35, "usage_type": "name"}]} +{"seq_id": "6992418646", "text": "from django.contrib import admin\nfrom import_export.admin import ImportExportModelAdmin\n\nfrom apps.adresa.models import Uliza\n\n\n@admin.register(Uliza)\nclass UlizaAdmin(ImportExportModelAdmin):\n list_display = [\n 'id',\n 'rayon',\n 'name',\n ]\n autocomplete_fields = ['rayon']\n list_display_links = [\n 'id',\n 'rayon',\n 'name',\n ]\n search_fields = [\n 'id',\n 'rayon__name',\n ]\n list_filter = ['rayon']", "repo_name": "anko011/rs_final", "sub_path": "backend/apps/adresa/admin/UlizaAdmin.py", "file_name": "UlizaAdmin.py", "file_ext": "py", "file_size_in_byte": 476, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "import_export.admin.ImportExportModelAdmin", "line_number": 8, "usage_type": "name"}, {"api_name": "django.contrib.admin.register", "line_number": 7, "usage_type": "call"}, {"api_name": "apps.adresa.models.Uliza", "line_number": 7, "usage_type": "argument"}, {"api_name": "django.contrib.admin", "line_number": 7, "usage_type": "name"}]} +{"seq_id": "30003262468", "text": "\"\"\"day23.py\n\"\"\"\nimport pathlib\nfrom string import ascii_lowercase\n\nALPHA = {x for x in ascii_lowercase}\n\ncwd = pathlib.Path(__file__).parent.absolute()\ndpath = pathlib.PurePath(cwd, 'data')\n\ntest = '''\ncpy 2 a\ntgl a\ntgl a\ntgl a\ncpy 1 a\ndec a\ndec a\n'''.strip().splitlines()\n\nclass Computer:\n def __init__(self, instructions, registers=None, i=None):\n self.instructions = list(instructions)\n self.registers = registers if registers is not None else {}\n self.i = i if i is not None else 0\n self.cmd = {\n 'cpy': self.cpy,\n 'inc': self.inc,\n 'dec': self.dec,\n 'jnz': self.jnz,\n 'tgl': self.tgl,\n }\n\n def run(self):\n instr = self.get_instruction()\n # print(self.i)\n # print(instr)\n # print(self.registers)\n # print()\n # input()\n self.cmd[instr.split()[0]]()\n\n def run_all(self):\n while self.i >= 0 and self.i < len(self.instructions):\n self.run()\n\n def get_instruction(self):\n return self.instructions[self.i]\n\n def cpy(self):\n _, x, y = self.get_instruction().split()\n if x in ALPHA:\n x = self.registers.get(x, 0)\n x = int(x)\n self.registers[y] = x\n self.i += 1\n\n def inc(self):\n _, x = self.get_instruction().split()\n self.registers[x] = self.registers.get(x, 0) + 1\n self.i += 1\n\n def dec(self):\n _, x = self.get_instruction().split()\n self.registers[x] = self.registers.get(x, 0) - 1\n self.i += 1\n\n def jnz(self):\n _, x, y = self.get_instruction().split()\n if x in ALPHA:\n x = self.registers.get(x, 0)\n if y in ALPHA:\n y = self.registers.get(y, 0)\n x = int(x)\n y = int(y)\n if x != 0:\n self.i += y\n else:\n self.i += 1\n\n def tgl(self):\n _, x = self.get_instruction().split()\n if x in ALPHA:\n x = self.registers.get(x, 0)\n x = int(x)\n index = self.i + x\n if index >= 0 and index < len(self.instructions):\n instr = self.instructions[index]\n command, *args = instr.split()\n if len(args) == 1:\n if command == 'inc':\n command = 'dec'\n else:\n command = 'inc'\n self.instructions[index] = ' '.join([command] + args)\n elif len(args) == 2:\n if command == 'jnz':\n command = 'cpy'\n else:\n command = 'jnz'\n self.instructions[index] = ' '.join([command] + args)\n self.i += 1\n\n\nwith open(dpath, 'r') as f:\n data = f.read().splitlines()\n\n# comp = Computer(data, registers={'a': 7})\n# comp.run_all()\n# print(comp.registers)\n\ncomp = Computer(data, registers={'a': 12})\ncomp.run_all()\nprint(comp.registers)\n\n", "repo_name": "brianjp93/aoc2016", "sub_path": "day23/day23.py", "file_name": "day23.py", "file_ext": "py", "file_size_in_byte": 2923, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "string.ascii_lowercase", "line_number": 6, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 8, "usage_type": "call"}, {"api_name": "pathlib.PurePath", "line_number": 9, "usage_type": "call"}]} +{"seq_id": "29852528195", "text": "# -*- coding: utf-8 -*-\n# pylint: disable=duplicate-code\n\"\"\"Module for testing Sentence model\"\"\"\nfrom datetime import timedelta\nfrom pathlib import Path\n\nfrom analyst_report_summarizer.settings import DATETIME_TEST_LEEWAY, TEST_RESOURCES_ROOT\nfrom api.grobid_tfidf_code.main import split_into_sentences\nfrom api.models.report import Report\nfrom api.models.sentence import Sentence\nfrom django.test import TestCase\nfrom django.utils import timezone\n\n\nclass SentenceTestCase(TestCase):\n \"\"\"Tests for the Sentence model\n Tests are decoupled from the Report and GROBID\n server by using create_without_file() to create report instances\"\"\"\n\n with open(\n TEST_RESOURCES_ROOT.joinpath(Path(\"test.plaintext\")), \"r\", encoding=\"utf-8\"\n ) as file:\n plaintext = file.read()\n\n with open(\n TEST_RESOURCES_ROOT.joinpath(Path(\"test.tei.xml\")), \"r\", encoding=\"utf-8\"\n ) as file:\n tei_xml = file.read()\n\n plaintext_sentences = split_into_sentences(plaintext)\n\n @staticmethod\n def _load_test_report() -> Report:\n \"\"\"\n Method to create a report model instance from the preloaded\n plaintext and tei_xml members\n\n This uses create_without_file() meaning extraction is never\n done by the server\n\n Returns:\n A report with the default plaintext and tei_xml\n \"\"\"\n return Report.objects._create_without_file( # pylint: disable=protected-access\n tei_xml=SentenceTestCase.tei_xml, plaintext=SentenceTestCase.plaintext\n )\n\n def test_sentence_creation(self):\n \"\"\"Test to see if a Sentence can be created\n with a given report object\"\"\"\n sample_sentence_text = \"Sample Sentence Text\"\n sample_tfidf_weight = 1.0\n\n report = self._load_test_report()\n sentence = Sentence.objects.create(\n report, sample_sentence_text, sample_tfidf_weight\n )\n\n report_sentences = report.sentences.all()\n self.assertIn(sentence, report_sentences)\n self.assertEqual(1, len(report_sentences))\n\n self.assertEqual(sentence.text, sample_sentence_text)\n self.assertEqual(sentence.tf_idf_weight, sample_tfidf_weight)\n\n def test_sentence_extraction_from_report(self):\n \"\"\"Test to see that the correct sentences are extracted\n from the report plaintext as specified in the function split_into_sentences()\"\"\"\n report = self._load_test_report()\n sentences = Sentence.objects.extract_sentences(report)\n self.assertEqual(\n len(sentences),\n len(self.plaintext_sentences),\n msg=\"number of sentence objects aren't the same as the expected number\",\n )\n\n for sentence in sentences:\n self.assertIn(sentence.text, self.plaintext_sentences)\n report.delete()\n\n def test_deletion_with_report(self):\n \"\"\"Test to see if a Sentence is deleted with it's associated report\"\"\"\n report = self._load_test_report()\n sentences = Sentence.objects.extract_sentences(report)\n num_sentences = len(sentences)\n\n sentence_count = Sentence.objects.all().count()\n\n deleted, _ = report.delete()\n self.assertGreater(deleted, 1)\n self.assertEqual(\n sentence_count - num_sentences,\n Sentence.objects.filter(parent_report=report).count(),\n )\n\n def test_tfidf_weight(self):\n \"\"\"Test to see if the tfidf weight calculated for a sentence is correct\"\"\"\n # Currently not implemented as too time-consuming\n\n def test_sentence_extraction_time(self):\n \"\"\"Test to see if the sentence extraction time is correctly set in a parent report\"\"\"\n now = timezone.now()\n report = self._load_test_report()\n Sentence.objects.extract_sentences(report)\n\n self.assertIsNotNone(report.sentence_datetime)\n self.assertGreater(\n report.sentence_datetime, now - timedelta(seconds=DATETIME_TEST_LEEWAY)\n )\n self.assertLess(\n report.sentence_datetime, now + timedelta(seconds=DATETIME_TEST_LEEWAY)\n )\n", "repo_name": "WillHolbrook/FYPCodeRepo", "sub_path": "backend/api/tests/models/test_sentence.py", "file_name": "test_sentence.py", "file_ext": "py", "file_size_in_byte": 4106, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "24", "api": [{"api_name": "django.test.TestCase", "line_number": 15, "usage_type": "name"}, {"api_name": "analyst_report_summarizer.settings.TEST_RESOURCES_ROOT.joinpath", "line_number": 21, "usage_type": "call"}, {"api_name": "analyst_report_summarizer.settings.TEST_RESOURCES_ROOT", "line_number": 21, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 21, "usage_type": "call"}, {"api_name": "analyst_report_summarizer.settings.TEST_RESOURCES_ROOT.joinpath", "line_number": 26, "usage_type": "call"}, {"api_name": "analyst_report_summarizer.settings.TEST_RESOURCES_ROOT", "line_number": 26, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 26, "usage_type": "call"}, {"api_name": "api.grobid_tfidf_code.main.split_into_sentences", "line_number": 30, "usage_type": "call"}, {"api_name": "api.models.report.Report.objects._create_without_file", "line_number": 44, "usage_type": "call"}, {"api_name": "api.models.report.Report.objects", "line_number": 44, "usage_type": "attribute"}, {"api_name": "api.models.report.Report", "line_number": 44, "usage_type": "name"}, {"api_name": "api.models.report.Report", "line_number": 33, "usage_type": "name"}, {"api_name": "api.models.sentence.Sentence.objects.create", "line_number": 55, "usage_type": "call"}, {"api_name": "api.models.sentence.Sentence.objects", "line_number": 55, "usage_type": "attribute"}, {"api_name": "api.models.sentence.Sentence", "line_number": 55, "usage_type": "name"}, {"api_name": "api.models.sentence.Sentence.objects.extract_sentences", "line_number": 70, "usage_type": "call"}, {"api_name": "api.models.sentence.Sentence.objects", "line_number": 70, "usage_type": "attribute"}, {"api_name": "api.models.sentence.Sentence", "line_number": 70, "usage_type": "name"}, {"api_name": "api.models.sentence.Sentence.objects.extract_sentences", "line_number": 84, "usage_type": "call"}, {"api_name": "api.models.sentence.Sentence.objects", "line_number": 84, "usage_type": "attribute"}, {"api_name": "api.models.sentence.Sentence", "line_number": 84, "usage_type": "name"}, {"api_name": "api.models.sentence.Sentence.objects.all", "line_number": 87, "usage_type": "call"}, {"api_name": "api.models.sentence.Sentence.objects", "line_number": 87, "usage_type": "attribute"}, {"api_name": "api.models.sentence.Sentence", "line_number": 87, "usage_type": "name"}, {"api_name": "api.models.sentence.Sentence.objects.filter", "line_number": 93, "usage_type": "call"}, {"api_name": "api.models.sentence.Sentence.objects", "line_number": 93, "usage_type": "attribute"}, {"api_name": "api.models.sentence.Sentence", "line_number": 93, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 102, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 102, "usage_type": "name"}, {"api_name": "api.models.sentence.Sentence.objects.extract_sentences", "line_number": 104, "usage_type": "call"}, {"api_name": "api.models.sentence.Sentence.objects", "line_number": 104, "usage_type": "attribute"}, {"api_name": "api.models.sentence.Sentence", "line_number": 104, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 108, "usage_type": "call"}, {"api_name": "analyst_report_summarizer.settings.DATETIME_TEST_LEEWAY", "line_number": 108, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 111, "usage_type": "call"}, {"api_name": "analyst_report_summarizer.settings.DATETIME_TEST_LEEWAY", "line_number": 111, "usage_type": "name"}]} +{"seq_id": "30557383642", "text": "import django_filters\r\n\r\nfrom account.models import (\r\n User, \r\n Customer,\r\n Region,\r\n EmployeeStatus,\r\n EmployeeActivity\r\n)\r\nfrom django.contrib.auth.models import Permission, Group\r\nfrom django.db.models import Q\r\n\r\n\r\nclass PermissionFilter(django_filters.FilterSet):\r\n class Meta:\r\n model = Permission\r\n fields = {\r\n 'id': ['exact'],\r\n 'name': ['exact', 'icontains'],\r\n 'content_type': ['exact'],\r\n 'codename': ['exact', 'icontains']\r\n }\r\n\r\nclass GroupFilter(django_filters.FilterSet):\r\n class Meta:\r\n model = Group\r\n fields = {\r\n 'id': ['exact'],\r\n 'name': ['exact', 'icontains'],\r\n 'permissions': ['exact', 'icontains']\r\n }\r\n\r\nclass UserFilter(django_filters.FilterSet):\r\n contract_date = django_filters.DateFilter(field_name='contract_date', input_formats=[\"%d-%m-%Y\"])\r\n contract_date__gte = django_filters.DateFilter(field_name='contract_date', lookup_expr='gte', input_formats=[\"%d-%m-%Y\"])\r\n contract_date__lte = django_filters.DateFilter(field_name='contract_date', lookup_expr='lte', input_formats=[\"%d-%m-%Y\"])\r\n\r\n class Meta:\r\n model = User\r\n fields = {\r\n 'fullname': ['exact', 'icontains'],\r\n 'position__name': ['exact', 'icontains', 'in'],\r\n 'position': ['exact'],\r\n 'is_superuser': ['exact'],\r\n 'salary_style': ['exact'],\r\n\r\n 'register_type': ['exact'],\r\n 'company': ['exact'],\r\n 'company__name': ['exact', 'icontains'],\r\n 'office': ['exact'],\r\n 'office__name': ['exact', 'icontains'],\r\n 'department': ['exact'],\r\n 'department__name': ['exact', 'icontains'],\r\n 'is_active': ['exact'],\r\n 'employee_status': ['exact'],\r\n 'employee_status__status_name': ['exact', 'icontains'],\r\n 'fin_code': ['exact'],\r\n }\r\n\r\nclass EmployeeStatusFilter(django_filters.FilterSet):\r\n class Meta:\r\n model = EmployeeStatus\r\n fields = {\r\n 'status_name': ['exact', 'icontains'],\r\n }\r\n\r\nclass EmployeeActivityFilter(django_filters.FilterSet):\r\n class Meta:\r\n model = EmployeeActivity\r\n fields = {\r\n 'employee': ['exact'],\r\n }\r\n\r\nclass RegionFilter(django_filters.FilterSet):\r\n class Meta:\r\n model = Region\r\n fields = {\r\n 'region_name': ['exact', 'icontains'],\r\n }\r\n\r\nclass CustomerFilter(django_filters.FilterSet):\r\n phone_number = django_filters.CharFilter(method=\"phone_number_filter\", label=\"phone_number\")\r\n def phone_number_filter(self, queryset, name, value):\r\n qs = None\r\n for term in value.split():\r\n qs = queryset.filter(\r\n Q(phone_number_1__icontains=term) | Q(phone_number_2__icontains=term) | Q(phone_number_3__icontains=term) | Q(phone_number_4__icontains=term))\r\n return qs\r\n class Meta:\r\n model = Customer\r\n fields = {\r\n 'fullname': ['exact', 'icontains'],\r\n 'is_active': ['exact'],\r\n 'address': ['exact', 'icontains'],\r\n 'region__region_name': ['exact', 'icontains'],\r\n 'fin_code': ['exact'],\r\n }\r\n", "repo_name": "abbasguliyev/drf_erp", "sub_path": "src/account/api/filters.py", "file_name": "filters.py", "file_ext": "py", "file_size_in_byte": 3291, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django_filters.FilterSet", "line_number": 14, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.Permission", "line_number": 16, "usage_type": "name"}, {"api_name": "django_filters.FilterSet", "line_number": 24, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.Group", "line_number": 26, "usage_type": "name"}, {"api_name": "django_filters.FilterSet", "line_number": 33, "usage_type": "attribute"}, {"api_name": "django_filters.DateFilter", "line_number": 34, "usage_type": "call"}, {"api_name": "django_filters.DateFilter", "line_number": 35, "usage_type": "call"}, {"api_name": "django_filters.DateFilter", "line_number": 36, "usage_type": "call"}, {"api_name": "account.models.User", "line_number": 39, "usage_type": "name"}, {"api_name": "django_filters.FilterSet", "line_number": 60, "usage_type": "attribute"}, {"api_name": "account.models.EmployeeStatus", "line_number": 62, "usage_type": "name"}, {"api_name": "django_filters.FilterSet", "line_number": 67, "usage_type": "attribute"}, {"api_name": "account.models.EmployeeActivity", "line_number": 69, "usage_type": "name"}, {"api_name": "django_filters.FilterSet", "line_number": 74, "usage_type": "attribute"}, {"api_name": "account.models.Region", "line_number": 76, "usage_type": "name"}, {"api_name": "django_filters.FilterSet", "line_number": 81, "usage_type": "attribute"}, {"api_name": "django_filters.CharFilter", "line_number": 82, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 87, "usage_type": "call"}, {"api_name": "account.models.Customer", "line_number": 90, "usage_type": "name"}]} +{"seq_id": "24217190892", "text": "#两数和#\n#给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。\n#暴力求解 通过遍历整数数组来得到与目标值相等的两个整数\n#时间复杂度o(n^2)\nfrom typing import List\nclass Solution(object):\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n n=len(nums)\n i=1\n for x in nums:\n j=0\n for y in nums[i:]:\n if x+y==target:\n return [i-1,i+j]\n j=j+1\n i=i+1\n if i>=n:\n break\n\n\n\n", "repo_name": "Catpoison2019/leetcode", "sub_path": "code/leetcode_1/leetcode_1/leetcode_1.py", "file_name": "leetcode_1.py", "file_ext": "py", "file_size_in_byte": 643, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.List", "line_number": 7, "usage_type": "name"}]} +{"seq_id": "33362257236", "text": "import asyncio\nimport datetime\nimport functools\nimport signal\nimport socket\n\n\n_SYS_EXIT = \"_SYS_EXIT\"\n\n\nclass AsyncioEventLooper:\n def __init__(self):\n # self._loop = asyncio.get_event_loop()\n self._loop = asyncio.new_event_loop()\n asyncio.set_event_loop(self._loop)\n self._q = asyncio.Queue()\n self._init_handler = None\n self._event_handler = None\n self._exit_handler = None\n self._context = None\n\n self._add_default_signal_handler()\n\n def _default_signal_handler(self, signame):\n print('\\n{} received. Exiting...'.format(signame))\n self._q.put_nowait((_SYS_EXIT, signame))\n\n def _add_default_signal_handler(self):\n for signame in ('SIGINT', 'SIGTERM'):\n self._loop.add_signal_handler(getattr(signal, signame), functools.partial(self._default_signal_handler, signame))\n\n async def _task_generate_event(self, event, param, initial_sleep_time, time_delta):\n if initial_sleep_time > 0.0:\n await asyncio.sleep(initial_sleep_time)\n await self._q.put((event, param))\n\n if time_delta is not None:\n next_put_time = datetime.datetime.now() + time_delta\n while True:\n sleep_time = (next_put_time - datetime.datetime.now()).total_seconds()\n if sleep_time > 0:\n await asyncio.sleep(sleep_time)\n await self._q.put((event, param))\n next_put_time += time_delta\n\n async def _run_loop(self):\n keep_running = True\n\n if self._init_handler:\n keep_running = await self._init_handler(self)\n\n while keep_running is not False:\n event, param = await self._q.get()\n\n if event == _SYS_EXIT:\n if self._exit_handler:\n await self._exit_handler(self)\n for task in asyncio.Task.all_tasks():\n if task is not asyncio.tasks.Task.current_task():\n task.cancel()\n await asyncio.sleep(1.0)\n break\n\n keep_running = await self._event_handler(self, event, param)\n\n def generate_event_nowait(self, event, param):\n self._q.put_nowait((event, param))\n\n async def generate_event(self, event, param):\n return self._loop.create_task(self._task_generate_event(event, param, 0.0, None))\n\n async def generate_event_after(self, event, param, seconds):\n return self._loop.create_task(self._task_generate_event(event, param, seconds, None))\n\n async def generate_event_after_periodically(self, event, param, seconds, period):\n return self._loop.create_task(self._task_generate_event(event, param, seconds, datetime.timedelta(seconds=period)))\n\n async def generate_event_at(self, event, param, date_time):\n initial_sleep_time = (date_time - datetime.datetime.now()).total_seconds()\n return self._loop.create_task(self._task_generate_event(event, param, initial_sleep_time, None))\n\n async def generate_event_at_perodically(self, event, param, date_time, time_delta):\n initial_sleep_time = (date_time - datetime.datetime.now()).total_seconds()\n return self._loop.create_task(self._task_generate_event(event, param, initial_sleep_time, time_delta))\n\n async def _stream_server_task_func(self,\n event_conn,\n event_data,\n event_disconn,\n event_eof,\n event_error,\n listening_port):\n class _StreamProtocol(asyncio.Protocol):\n def __init__(self,\n q_,\n event_conn_,\n event_data_,\n event_disconn_,\n event_eof_,\n event_error_):\n self._q = q_\n self._event_conn = event_conn_\n self._event_data = event_data_\n self._event_disconn = event_disconn_\n self._event_eof = event_eof_\n self._event_error = event_error_\n\n def connection_made(self, transport):\n self._q.put_nowait((self._event_conn, transport))\n\n def data_received(self, data):\n self._q.put_nowait((self._event_data, data.decode('utf-8')))\n\n def connection_lost(self, exc):\n self._q.put_nowait((self._event_disconn, None))\n\n def eof_received(self):\n self._q.put_nowait((self._event_eof, None))\n\n def error_received(self, exc):\n self._q.put_nowait((self._event_error, exc))\n\n server = await self._loop.create_server(lambda: _StreamProtocol(self._q,\n event_conn,\n event_data,\n event_disconn,\n event_eof,\n event_error),\n host=socket.gethostname(),\n port=listening_port)\n\n async with server:\n await server.serve_forever()\n\n async def register_stream_server(self, event_conn, event_data, event_disconn, event_eof, event_error, listening_port):\n return self._loop.create_task(self._stream_server_task_func(event_conn, event_data, event_disconn, event_eof, event_error, listening_port))\n\n async def _datagram_server_task_func(self,\n event_conn,\n event_data,\n event_disconn,\n event_eof,\n event_error,\n listening_port):\n class _DatagramProtocol(asyncio.DatagramProtocol):\n def __init__(self,\n q_,\n event_conn_,\n event_data_,\n event_disconn_,\n event_eof_,\n event_error_):\n self._q = q_\n self._event_conn = event_conn_\n self._event_data = event_data_\n self._event_disconn = event_disconn_\n self._event_eof = event_eof_\n self._event_error = event_error_\n\n def connection_made(self, transport):\n self._q.put_nowait((self._event_conn, transport))\n\n def datagram_received(self, data, address):\n self._q.put_nowait((self._event_data, (address, data.decode('utf-8'))))\n\n def connection_lost(self, exc):\n self._q.put_nowait((self._event_disconn, None))\n\n def eof_received(self):\n self._q.put_nowait((self._event_eof, None))\n\n def error_received(self, exc):\n self._q.put_nowait((self._event_error, exc))\n\n transport, protocol = await self._loop.create_datagram_endpoint(lambda: _DatagramProtocol(self._q,\n event_conn,\n event_data,\n event_disconn,\n event_eof,\n event_error),\n local_addr=(socket.gethostbyname(socket.gethostname()), listening_port))\n\n async def register_datagram_server(self, event_conn, event_data, event_disconn, event_eof, event_error, listening_port):\n return self._loop.create_task(self._datagram_server_task_func(event_conn, event_data, event_disconn, event_eof, event_error, listening_port))\n\n async def register_async_func(self, async_func):\n return self._loop.create_task(async_func)\n\n def register_async_func_nowait(self, async_func):\n return self._loop.create_task(async_func)\n\n def stop(self):\n self._q.put_nowait((_SYS_EXIT, None))\n\n def add_signal_handler(self, signal_names, signal_handler):\n for signame in signal_names:\n self._loop.add_signal_handler(getattr(signal, signame), functools.partial(signal_handler, self, signame))\n\n def set_context(self, context):\n self._context = context\n\n def get_context(self):\n return self._context\n\n def run(self, init_handler, event_handler, exit_handler):\n self._init_handler = init_handler\n self._event_handler = event_handler\n self._exit_handler = exit_handler\n self._loop.run_until_complete(self._run_loop())\n asyncio.gather(*asyncio.Task.all_tasks(), return_exceptions=True)\n self._loop.stop()\n self._loop.close()\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n# Test\n\nclass ClientContext:\n def __init__(self):\n self.count = 0\n\n\nasync def _init_handler(looper):\n await looper.generate_event_after_periodically('event_update3', None, 7, 3)\n await looper.generate_event_after_periodically('event_update5', None, 0, 5)\n looper.set_context(ClientContext())\n return True\n\n\nasync def _exit_handler(looper):\n print('Exiting...')\n\n\nasync def _event_handler(looper, event, param):\n context = looper.get_context()\n print(\"{:3} {} {}\".format(context.count, datetime.datetime.now().strftime('%H:%M:%S.%f')[:-4], event))\n context.count += 1\n\n if context.count > 10:\n looper.stop()\n return True\n\n\nif __name__ == \"__main__\":\n _looper = AsyncioEventLooper()\n\n _looper.run(_init_handler, _event_handler, _exit_handler)\n", "repo_name": "jmkangkr/asyncio_util", "sub_path": "asyncio_event_looper.py", "file_name": "asyncio_event_looper.py", "file_ext": "py", "file_size_in_byte": 10293, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "asyncio.new_event_loop", "line_number": 14, "usage_type": "call"}, {"api_name": "asyncio.set_event_loop", "line_number": 15, "usage_type": "call"}, {"api_name": "asyncio.Queue", "line_number": 16, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 30, "usage_type": "call"}, {"api_name": "asyncio.sleep", "line_number": 34, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 38, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 38, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 40, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 40, "usage_type": "attribute"}, {"api_name": "asyncio.sleep", "line_number": 42, "usage_type": "call"}, {"api_name": "asyncio.Task.all_tasks", "line_number": 58, "usage_type": "call"}, {"api_name": "asyncio.Task", "line_number": 58, "usage_type": "attribute"}, {"api_name": "asyncio.tasks.Task.current_task", "line_number": 59, "usage_type": "call"}, {"api_name": "asyncio.tasks", "line_number": 59, "usage_type": "attribute"}, {"api_name": "asyncio.sleep", "line_number": 61, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 76, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 79, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 79, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 83, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 83, "usage_type": "attribute"}, {"api_name": "asyncio.Protocol", "line_number": 93, "usage_type": "attribute"}, {"api_name": "socket.gethostname", "line_number": 129, "usage_type": "call"}, {"api_name": "asyncio.DatagramProtocol", "line_number": 145, "usage_type": "attribute"}, {"api_name": "socket.gethostbyname", "line_number": 181, "usage_type": "call"}, {"api_name": "socket.gethostname", "line_number": 181, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 197, "usage_type": "call"}, {"api_name": "asyncio.gather", "line_number": 210, "usage_type": "call"}, {"api_name": "asyncio.Task.all_tasks", "line_number": 210, "usage_type": "call"}, {"api_name": "asyncio.Task", "line_number": 210, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 236, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 236, "usage_type": "attribute"}]} +{"seq_id": "16729548925", "text": "#!/usr/bin/env\n# -*- coding: utf-8 -*-\n\"\"\"\nTools to create/apply pseudo 3d data, including relighting.\n\"\"\"\nimport math\ntry:\n # first try to use bohrium, since it could help us accelerate\n # https://bohrium.readthedocs.io/users/python/\n import bohrium as np\nexcept ImportError:\n # if not, plain old numpy is good enough\n import numpy as np\nimport scipy.ndimage\nfrom .helper_routines import *\nfrom .imageRepr import *\nfrom .colors import *\nfrom .resizing import *\nfrom .colorSpaces import *\n\n\ndef normalMapFromImage(img,zPower=0.33):\n \"\"\"\n Attempt to get a normal map from an image using edge detection.\n\n :param img: the image to create a normal map for\n :param zPower: percent of z estimation to allow (keep it low because this\n is always a total guess)\n\n NOTE: This is a common approach, but it is only an approximation, not actual\n height data. It will only give you something that may or may not look 3d.\n The real way to do this is to directly measure the height data directly\n using something like a kinect or 3d digitizer. An acceptable alternative\n is a multi-angle photo stitcher such as 123D Catch. In fact, if all you\n have is a 2d image, something like AwesomeBump would be more versitile.\n https://github.com/kmkolasinski/AwesomeBump\n\n See also:\n https://github.com/RobertBeckebans/gimp-plugin-insanebump\n \"\"\"\n img=normalize(grayscale(img))\n x=scipy.ndimage.sobel(img,1)\n y=scipy.ndimage.sobel(img,0)\n mag=np.hypot(x,y)\n z=normalize(scipy.ndimage.distance_transform_edt(mag))*zPower+(0.5-zPower/2)\n return np.dstack((x,y,z))\n\n\ndef directionToNormalColor(azimuth,elevation):\n \"\"\"\n given a direction, convert it into an RGB normal color\n\n :param azimuth: compass direction\n :param elevation: up/down direction\n \"\"\"\n azimuth=math.radians(float(azimuth))\n elevation=math.radians(float(elevation))\n return (np.array([math.sin(azimuth),math.cos(azimuth),math.cos(elevation)])+1)/2\n\n\ndef applyDirectionalLight(img,normalmap=None,lightAzimuth=45,lightElevation=45,lightColor=None):\n \"\"\"\n Add a directional light to the image.\n\n :param img: the image to light\n :param normalmap: a normal map to define its shape (if None, use normalMapFromImage(img))\n :param lightAzimuth: compass direction of the light source\n :param lightElevation: up/down direction of the light source\n :param lightColor: color of the light source (if None, use white)\n\n TODO: doesn't work the greatest\n \"\"\"\n img=numpyArray(img)\n if lightColor is None:\n lightColor=[1.0,1.0,1.0]\n if normalmap is None:\n normalmap=normalMapFromImage(img)\n else:\n normalmap=numpyArray(normalmap)\n normalmap=crop(normalmap,img)\n lightColor=strToColor(lightColor)\n dLight=directionToNormalColor(lightAzimuth,lightElevation)\n normalmap=normalmap[:,:]*dLight\n lightMap=np.average(normalmap,axis=-1)\n lightMap=lightMap[:,:,np.newaxis]*lightColor\n return img+lightMap\n\n\ndef heightMapFromNormalMap(normalmap):\n \"\"\"\n Create a height map (sometimes called a bumpmap) from a normalmap\n\n :param normalmap: normal map to convert\n\n NOTE: Essentially, this is just the blue channel pointing towards us.\n \"\"\"\n normalmap=numpyArray(normalmap)\n return normalize(normalmap[:,:,2])\n\n\ndef normalMapFromHeightMap(heightmap):\n \"\"\"\n Create a normal map from a height map (sometimes called a bumpmap)\n\n :param heightmap: height map to convert\n\n Comes from:\n http://www.juhanalankinen.com/calculating-normalmaps-with-python-and-numpy/\n \"\"\"\n heightmap=numpyArray(heightmap)\n heightmap=normalize(heightmap)\n matI = np.identity(heightmap.shape[0]+1)\n matNeg = -1 * matI[0:-1, 1:]\n matNeg[0, -1] = -1\n matI = matI[1:, 0:-1]\n matI[-1,0] = 1\n matI += matNeg\n matGradX = (matI.dot(heightmap.T)).T\n matGradY = matI.dot(heightmap)\n matNormal = np.zeros([heightmap.shape[0], heightmap.shape[1], 3])\n matNormal[:,:,0] = -matGradX\n matNormal[:,:,1] = matGradY\n matNormal[:,:,2] = 1.0\n fNormMax = np.max(np.abs(matNormal))\n matNormal = ((matNormal / fNormMax) + 1.0) / 2.0\n return matNormal\n\n\ndef cmdline(args):\n \"\"\"\n Run the command line\n\n :param args: command line arguments (WITHOUT the filename)\n \"\"\"\n printhelp=False\n if not args:\n printhelp=True\n else:\n img=None\n norm=None\n bump=None\n for arg in args:\n if arg.startswith('-'):\n arg=[a.strip() for a in arg.split('=',1)]\n if arg[0] in ['-h','--help']:\n printhelp=True\n elif arg[0]=='--img':\n img=arg[1]\n elif arg[0]=='--norm':\n bump=None\n norm=arg[1]\n elif arg[0]=='--bump':\n norm=None\n bump=arg[1]\n elif arg[0]=='--addDirectional':\n if len(arg)<2:\n params=[]\n else:\n params=arg[1].split(',',3)\n if norm is None:\n if bump is not None:\n norm=normalMapFromHeightMap(bump)\n img=applyDirectionalLight(img,norm,*params)\n elif arg[0]=='--show':\n preview(img)\n elif arg[0]=='--showNorm':\n if norm is None:\n if bump is None:\n norm=normalMapFromImage(img)\n else:\n norm=normalMapFromHeightMap(bump)\n preview(norm)\n elif arg[0]=='--showBump':\n if bump is None:\n if norm is None:\n norm=normalMapFromImage(img)\n bump=heightMapFromNormalMap(norm)\n preview(bump)\n elif arg[0]=='--save':\n pilImage(clampImage(img)).save(arg[1])\n elif arg[0]=='--saveNorm':\n if norm is None:\n if bump is None:\n norm=normalMapFromImage(img)\n else:\n norm=normalMapFromHeightMap(bump)\n pilImage(clampImage(norm)).save(arg[1])\n elif arg[0]=='--saveBump':\n if bump is None:\n if norm is None:\n norm=normalMapFromImage(img)\n bump=heightMapFromNormalMap(norm)\n pilImage(clampImage(bump)).save(arg[1])\n else:\n print('ERR: unknown argument \"'+arg[0]+'\"')\n else:\n print('ERR: unknown argument \"'+arg+'\"')\n if printhelp:\n print('Usage:')\n print(' pseudo3d.py [options]')\n print('Options:')\n print(' --img=[filename] ....... set the image')\n print(' --norm=[filename] ...... set the normal map')\n print(' --bump=[filename] ...... set the bump map')\n print(' --addDirectional=azimuth,elevation,color')\n print(' --show ................. show the image')\n print(' --showNorm ............. show the normal map')\n print(' --showBump ............. show the bump map')\n print(' --save=[filename] ...... save out the result')\n print(' --saveNorm=[filename] .. save out the normal map')\n print(' --saveBump=[filename] .. save out the bump map')\n\n\nif __name__=='__main__':\n import sys\n cmdline(sys.argv[1:])\n", "repo_name": "TheHeadlessSourceMan/imageTools", "sub_path": "pseudo3d.py", "file_name": "pseudo3d.py", "file_ext": "py", "file_size_in_byte": 7703, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "scipy.ndimage.ndimage.sobel", "line_number": 42, "usage_type": "call"}, {"api_name": "scipy.ndimage.ndimage", "line_number": 42, "usage_type": "attribute"}, {"api_name": "scipy.ndimage", "line_number": 42, "usage_type": "name"}, {"api_name": "scipy.ndimage.ndimage.sobel", "line_number": 43, "usage_type": "call"}, {"api_name": "scipy.ndimage.ndimage", "line_number": 43, "usage_type": "attribute"}, {"api_name": "scipy.ndimage", "line_number": 43, "usage_type": "name"}, {"api_name": "numpy.hypot", "line_number": 44, "usage_type": "call"}, {"api_name": "scipy.ndimage.ndimage.distance_transform_edt", "line_number": 45, "usage_type": "call"}, {"api_name": "scipy.ndimage.ndimage", "line_number": 45, "usage_type": "attribute"}, {"api_name": "scipy.ndimage", "line_number": 45, "usage_type": "name"}, {"api_name": "numpy.dstack", "line_number": 46, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 56, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 58, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 58, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.average", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 85, "usage_type": "attribute"}, {"api_name": "numpy.identity", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 124, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 216, "usage_type": "attribute"}]} +{"seq_id": "6974955329", "text": "from typing import List\nfrom pprint import pprint\n\n\ndef n_queens(size: int) -> List[List[int]]:\n solutions = []\n solve(size, 0, [], solutions)\n return solutions\n\n\ndef solve(size: int, row: int, row_placement: List[int], solutions: List[List[int]]) -> None:\n # row_placement is a list of row indices where queens are located, where each entry of\n # row_placement is associated with a column\n if row == size:\n # We've exhausted one \"decision path\" - we've went through all rows and did not backtrack,\n # thus we have found one of the solutions\n return solutions.append(row_placement.copy()) # copy, do not add references as they are volatile\n else:\n for row_index in range(size):\n row_placement.append(row_index) # next \"solution candidate\"\n if is_valid(row_placement): # validate a \"solution candidate\"\n solve(size, row + 1, row_placement, solutions) # travel further through the decision space\n row_placement.pop() # Backtrack\n\n\ndef is_valid(row_placement: List[int]) -> bool:\n last_column = len(row_placement) - 1\n for column_index in range(last_column):\n diff = abs(row_placement[last_column] - row_placement[column_index])\n if diff == 0 or diff == last_column - column_index:\n # Queens cannot be in the same row or column - diff == 0\n # And also there cannot be two queens on the same diagonal - diff == current_column - column_index\n return False\n return True\n\n\ndef print_solution(solution: List[int]):\n # Create an empty chess board\n def make_row(length):\n return [\" \"] * length\n\n size = len(solution)\n board = [make_row(size) for _ in range(size)]\n\n for column, row in enumerate(solution):\n board[column][row] = \"$\" # mark queen's position\n pprint(board)\n\n\nif __name__ == \"__main__\":\n solutions = n_queens(4)\n print(f\"Found {len(solutions)} solutions\")\n for index, solution in enumerate(solutions):\n print(f\"Solution no. {index + 1}:\")\n print(solution)\n print_solution(solution)\n", "repo_name": "pniewiejski/algorithms-playground", "sub_path": "backtracking/n_queens_problem.py", "file_name": "n_queens_problem.py", "file_ext": "py", "file_size_in_byte": 2106, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.List", "line_number": 5, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 11, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 26, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 37, "usage_type": "name"}, {"api_name": "pprint.pprint", "line_number": 47, "usage_type": "call"}]} +{"seq_id": "31765642777", "text": "import os\nimport telebot\nimport requests\nimport json\nimport csv, io\n#here we had imported the required modules to run the cinebot sucessfully, io is added for handling input and output values\n\n\nyourkey = \"afcc42dd\"\nbot_id = \"5583870663:AAH9WeUrxXYDGhMZsk67ffvdFzVSYuBDy60\"\n#api key and bot id are stored in this variables respectively\n\nbot = telebot.TeleBot(bot_id)\n\ns = io.StringIO()\nbuf = io.BytesIO()\n#these s and io are used for handling string and binary data, respectively\n\n\n@bot.message_handler(commands=['start','hello'])\ndef greet(message):\n global botRunning\n botRunning = True\n bot.reply_to(message, 'Hello there! I am a bot that will show movie information for you and export it in a csv file.\\n\\n' )\n#This handler will kick start when the user sends '/start' or '/hello' command to the tele bot\n@bot.message_handler(commands=['stop','bye'])\ndef goodbye(message):\n global botRunning\n botRunning = False\n bot.reply_to(message,'Bye!\\nHave a good time')\n #this handler ensures the chat is dead when the user sends '/stop' or '/bye'\n \n@bot.message_handler(func=lambda message: botRunning, commands=['help'])\ndef helpProvider(message):\n bot.reply_to(message,'1.0 You can use \\\"/movie MOVIE_NAME\\\" command to get the details of a particular movie. For eg: \\\"/movie The Shawshank Redemption\\\"\\n\\n2.0. You can use \\\"/export\\\" command to export all the movie data in CSV format.\\n\\n3.0. You can use \\\"/stop\\\" or the command \\\"/bye\\\" to stop the bot.')\n#this handler helps or give suitable instructions when the message command '/help' is sent\n@bot.message_handler(func=lambda message: botRunning, commands=['movie'])\ndef getMovie(message):\n movieName = message.text.replace('/movie ', \"\")\n bot.reply_to(message,'Getting movie info...')\n api_url = f\"https://www.omdbapi.com/?i=tt3896198&apikey=afcc42dd\"\n #http://www.omdbapi.com/?apikey={yourkey}&t={movieName}\n movieDetails = requests.get(api_url).json()\n moviePoster = movieDetails['Poster']\n movieTitle = movieDetails['Title']\n movieYear = movieDetails['Year']\n movieRating = movieDetails['Rated']\n\n bot.reply_to(message,'/movie')\n\n csv.writer(s).writerow([movieTitle,movieYear,movieRating])\n s.seek(0)\n\n buf.write(s.getvalue().encode())\n buf.seek(0)\n\n buf.name = f'datas.csv'\n \n bot.send_photo(message.chat.id, moviePoster , f'Title: {movieTitle} \\nReleased_Year: {movieYear}\\nRating: {movieRating}')\n#this set of code is used to send the movie details from the OMDB app to the csv file(s) when the command '/movie' is sent\n\n@bot.message_handler(func=lambda message: botRunning, commands=['export'])\ndef getList(message):\n bot.reply_to(message,'Generating the data file')\n bot.send_document(message.chat.id,buf) \n #when '/export' command is sent the csv file which contains details of the movie is sent in the tele chat.\n\n@bot.message_handler(func=lambda message: botRunning)\ndef default(message):\n bot.reply_to(message, 'I did not understand '+'\\N{confused face}')\n#this function is just used to say that the bot didn't understand the user input.\nbot.infinity_polling()\n#this ensures the bot is running always untill the user sends '/stop' or '/bye' command\n", "repo_name": "pranavakula/amfoss-tasks", "sub_path": "task4/bot.py", "file_name": "bot.py", "file_ext": "py", "file_size_in_byte": 3202, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "telebot.TeleBot", "line_number": 13, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 15, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 16, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 43, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 51, "usage_type": "call"}]} +{"seq_id": "19758860053", "text": "from afisha import get_afisha\nfrom analytic import write_like, calculate_recomendation\nfrom result import Result\nimport json\n\n\ndef get_feed():\n r = get_afisha()\n return r\n\n\ndef send_like(data):\n userId = data[\"userId\"]\n afishaId = data[\"afishaId\"]\n\n result = write_like(userId, afishaId, 1)\n return result\n\n\ndef send_likes(data):\n userId = data[\"userId\"]\n stats = data[\"stats\"]\n for stat in stats:\n afishaId = stat[\"id\"]\n like = stat[\"value\"]\n write_like(userId, afishaId, like)\n return Result.void_success()\n\n\ndef get_recomendation_feed(userId):\n afishas = json.loads(get_feed().resut)\n values = []\n for afisha in afishas:\n value = calculate_recomendation(userId, afisha[\"id\"])\n values.append((value, afisha))\n\n values.sort(key=lambda x: x[0], reverse=True)\n resulted_feed = list(map(lambda x: x[1], values))\n print(resulted_feed)\n\n return Result(result=json.dumps(resulted_feed))\n\n", "repo_name": "reability/MCHProject2021Mosru", "sub_path": "MSKHackMAG/api.py", "file_name": "api.py", "file_ext": "py", "file_size_in_byte": 969, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "afisha.get_afisha", "line_number": 8, "usage_type": "call"}, {"api_name": "analytic.write_like", "line_number": 16, "usage_type": "call"}, {"api_name": "analytic.write_like", "line_number": 26, "usage_type": "call"}, {"api_name": "result.Result.void_success", "line_number": 27, "usage_type": "call"}, {"api_name": "result.Result", "line_number": 27, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 31, "usage_type": "call"}, {"api_name": "analytic.calculate_recomendation", "line_number": 34, "usage_type": "call"}, {"api_name": "result.Result", "line_number": 41, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 41, "usage_type": "call"}]} +{"seq_id": "9699675087", "text": "# usage: python detect_and_save_to_file.py \n\n# %% argument parse\n\nimport sys\nif len(sys.argv) != 2:\n print('Pass folder path as first parameter, for example: python detect_and_save_to_file.py data/images/GP028291')\n exit(1)\n_, folder_path = sys.argv\n\n# %% imports\n\nimport cv2\nfrom PIL import Image\nfrom glob import glob\nimport os\nimport warnings\nfrom progress.bar import Bar\nwith warnings.catch_warnings():\n warnings.simplefilter('ignore')\n from yolo_box_detector import BoxDetector\n box_detector = BoxDetector()\n\n# %% action\n\nfile_list = glob(os.path.join(folder_path, '*.png'))\nbar = Bar('Processing Images', max=len(file_list))\nfor path in file_list:\n bar.next()\n img = cv2.imread(path)\n pil = Image.fromarray(img)\n boxes, scores = box_detector.detect_boxes(pil)\n left, top, right, bottom = boxes[0]\n folder, filename = os.path.split(path)\n filename, _ = os.path.splitext(filename)\n out_path = os.path.join(folder, f'{filename}.txt')\n with open(out_path, 'w') as out:\n out.write(f'{left} {top} {right} {bottom}')\nbar.finish()", "repo_name": "jschiefner/horse-tracker-cvlab", "sub_path": "detect_and_save_to_file.py", "file_name": "detect_and_save_to_file.py", "file_ext": "py", "file_size_in_byte": 1090, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sys.argv", "line_number": 6, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 9, "usage_type": "attribute"}, {"api_name": "warnings.catch_warnings", "line_number": 19, "usage_type": "call"}, {"api_name": "warnings.simplefilter", "line_number": 20, "usage_type": "call"}, {"api_name": "yolo_box_detector.BoxDetector", "line_number": 22, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "progress.bar.Bar", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 30, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 31, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 31, "usage_type": "name"}, {"api_name": "os.path.split", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path", "line_number": 36, "usage_type": "attribute"}]} +{"seq_id": "41605318457", "text": "from flask import Flask, request\nfrom flask_cors import CORS, cross_origin\nimport route\n\napp = Flask(__name__)\nCORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\nstate = route.GameState()\n\n@app.route('/initBoard', methods=['POST'])\n@cross_origin()\ndef initBoard():\n FEN = request.json['FEN']\n return state.initBoard(FEN)\n\n@app.route('/getMoves', methods=['GET'])\n@cross_origin()\ndef getMoves():\n return state.getMoves()\n\n@app.route('/alphabeta', methods=['POST'])\n@cross_origin()\ndef alphabeta():\n DEPTH = int(request.json['depth'])\n STOPTIME = int(request.json['stopTime'])\n return state.alphaBetaMove(DEPTH, STOPTIME)\n\n@app.route('/mcts', methods=['POST'])\n@cross_origin()\ndef mcts():\n STOPTIME = int(request.json['stopTime'])\n if 'moves' in request.json:\n return state.mctsMove(STOPTIME, request.json['moves']) \n else:\n return state.mctsMove(STOPTIME)\n\n@app.route('/doMove', methods=['POST'])\n@cross_origin()\ndef doMove():\n print(\"executing move\")\n MOVE = request.json['move']\n return state.doMove(MOVE)\n\n@app.route('/undoLastMove', methods=['GET'])\n@cross_origin()\ndef undoLastMove():\n print(\"Undoing last move\")\n return state.undoLastMove()\n", "repo_name": "samchamani/chess-engine-backend", "sub_path": "server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 1205, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "flask.Flask", "line_number": 5, "usage_type": "call"}, {"api_name": "flask_cors.CORS", "line_number": 6, "usage_type": "call"}, {"api_name": "route.GameState", "line_number": 8, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 13, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 13, "usage_type": "name"}, {"api_name": "flask_cors.cross_origin", "line_number": 11, "usage_type": "call"}, {"api_name": "flask_cors.cross_origin", "line_number": 17, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 24, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 25, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 25, "usage_type": "name"}, {"api_name": "flask_cors.cross_origin", "line_number": 22, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 31, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 31, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 32, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 32, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 33, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 33, "usage_type": "name"}, {"api_name": "flask_cors.cross_origin", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 41, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 41, "usage_type": "name"}, {"api_name": "flask_cors.cross_origin", "line_number": 38, "usage_type": "call"}, {"api_name": "flask_cors.cross_origin", "line_number": 45, "usage_type": "call"}]} +{"seq_id": "1829803083", "text": "# coding = utf-8\nimport copy\n\nfrom IPython.core.display import HTML\n\nfrom .nxpd import draw\nfrom matplotlib.figure import Figure\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom .template_visjs import vis_js_template\n\ndef draw_graph_matplotlib(G, nodesize=400, node_color=\"blue\",node_shape=\"s\", font_color=\"white\", figsize=(8, 5), filename=None,ax=None,\n **fig_kwargs):\n \"\"\"\n Draw the pattern graph using matplotlib.\n Parameters\n ----------\n G : nx.Digraph\n pattern graph\n nodesize : int\n node size on the plot\n node_color: str\n node color\n font_color : str\n color of the node label\n figsize : List[float]\n size of the figure\n filename: str or None\n if not None, indicate the output filename\n fig_kwargs: dict\n matplotlib Figure args\n\n Returns\n -------\n Figure\n figure instance\n \"\"\"\n if not ax :\n fig = Figure(figsize=figsize)\n ax = fig.add_subplot(1, 1, 1)\n else:\n fig = plt.gcf()\n\n pos = nx.spring_layout(G, k=0.30,iterations=20)\n nx.draw(G, pos, with_labels=True, node_shape=node_shape,\n node_size=[len(G.nodes[v][\"label\"]) * nodesize for v in G.nodes()],\n font_color=font_color, labels=nx.get_node_attributes(G, \"label\"), ax=ax, node_color=node_color,\n arrowsize=20)\n nx.draw_networkx_edge_labels(G, pos, edge_labels=nx.get_edge_attributes(G, \"label\"), ax=ax)\n ax.set_axis_off()\n if filename:\n fig.savefig(filename)\n return fig\n\n\ndef draw_graph_graphviz(G, filename=None, show=True):\n \"\"\"\n Draw the pattern graph using Graphviz\n Parameters\n ----------\n G: nx.Digraph\n pattern graph\n filename : str or None\n output filename if the figure is to be saved(default is None)\n show:bool or str\n display modality (True:system, \"ipynb\" : notebook).\n\n \"\"\"\n if filename:\n draw(G, filename=filename)\n return draw(G, show=show)\n\n\ndef draw_graph_notebook(G,height=600,node_distance=200):\n nodes_str = \"\"\n edges_str = \"\"\n for node in G.nodes(data=True):\n nodes_str = nodes_str + \"{\" + \"id: \\\"{0}\\\",label: \\\"{1}\\\"\".format(node[0], node[1][\"label\"].replace(\"\\n\",\n \"\\\\n\")) + \"},\\n\"\n for edge in G.edges(data=True):\n edges_str = edges_str + \"{\" + \"from: \\\"{0}\\\", to: \\\"{1}\\\", label: \\\"{2}\\\"\".format(edge[0], edge[1],\n edge[2][\"label\"].replace(\"\\n\",\n \"\\\\n\")) + \"},\\n\"\n html_ = copy.copy(vis_js_template)\n html_ = html_.replace(\"%%nodes\", nodes_str.strip(\",\\n\"))\n html_ = html_.replace(\"%%edges\", edges_str.strip(\",\\n\"))\n html_ = html_.replace(\"%%node_distance\", str(node_distance))\n html_ = html_.replace(\"%%height\", str(height))\n return HTML(html_)\n\n", "repo_name": "Jacobe2169/spacy-depmatcher-pattern-visualiser", "sub_path": "sdpv/draw.py", "file_name": "draw.py", "file_ext": "py", "file_size_in_byte": 3068, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "matplotlib.figure.Figure", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "networkx.spring_layout", "line_number": 44, "usage_type": "call"}, {"api_name": "networkx.draw", "line_number": 45, "usage_type": "call"}, {"api_name": "networkx.get_node_attributes", "line_number": 47, "usage_type": "call"}, {"api_name": "networkx.draw_networkx_edge_labels", "line_number": 49, "usage_type": "call"}, {"api_name": "networkx.get_edge_attributes", "line_number": 49, "usage_type": "call"}, {"api_name": "nxpd.draw", "line_number": 70, "usage_type": "call"}, {"api_name": "nxpd.draw", "line_number": 71, "usage_type": "call"}, {"api_name": "copy.copy", "line_number": 84, "usage_type": "call"}, {"api_name": "template_visjs.vis_js_template", "line_number": 84, "usage_type": "argument"}, {"api_name": "IPython.core.display.HTML", "line_number": 89, "usage_type": "call"}]} +{"seq_id": "41403947749", "text": "import scipy as sp\r\nimport imageio as iio\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport time\r\nimport sys\r\n\r\n\r\n# def progressbar(current, total):\r\n# progress = int(current / total * 50)\r\n# barstatus = \"│\" + (\"█\" * progress) + (\"░\" * (49 - progress)) + \"│ \" + str(int((progress / 50 * 100) + 2)) + \"%\"\r\n# print(f'\\r{barstatus}', end='')\r\n\r\n\r\ndef rgb_to_bw(im):\r\n im_bw = 0.299 * im[:, :, 0] + 0.587 * im[:, :, 1] + 0.114 * im[:, :, 2]\r\n im_bw -= np.amin(im_bw)\r\n im_bw *= 255 / np.amax(im_bw)\r\n # return im_bw\r\n return np.rint(im_bw).astype(int)\r\n\r\n\r\ndef conv_2d(x, h):\r\n h = np.fliplr(h)\r\n h = np.flipud(h)\r\n\r\n x_height, x_width = x.shape\r\n\r\n return_array = np.zeros((x_height, x_width))\r\n\r\n padding_to_add = int(h.shape[0] / 2) * 2\r\n start = int(padding_to_add / 2)\r\n padded_array = np.zeros((x_height + padding_to_add, x_width + padding_to_add))\r\n\r\n padded_array[start:-start, start:-start] = x\r\n\r\n left = 0\r\n top = 0\r\n right = int(left + h.shape[1])\r\n bottom = int(top + h.shape[0])\r\n\r\n for col in range(x_height):\r\n for row in range(x_width):\r\n return_array[col, row] = np.sum(np.multiply(padded_array[top:bottom, left:right], h))\r\n # print(left, x_width)\r\n if left < x_width - 1:\r\n left += 1\r\n else:\r\n top += 1\r\n left = 0\r\n right = int(left + h.shape[1])\r\n bottom = int(top + h.shape[0])\r\n return return_array\r\n\r\n\r\n#\r\ndef normalize(im, im_min=0, im_max=255):\r\n im = np.clip(im, im_min, im_max)\r\n return im\r\n\r\n\r\ndef blur(im):\r\n gaussian_blur_kernel = np.array([[1, 4, 7, 4, 1],\r\n [4, 16, 26, 16, 4],\r\n [7, 26, 41, 26, 7],\r\n [4, 16, 26, 16, 4],\r\n [1, 4, 7, 4, 1]])\r\n gaussian_blur_kernel = (1 / 273) * gaussian_blur_kernel\r\n temp = conv_2d(im, gaussian_blur_kernel)\r\n temp = normalize(temp)\r\n # diff = 0\r\n # for ii in range(im.shape[0]):\r\n # for jj in range(im.shape[1]):\r\n # diff += np.absolute(im[ii, jj] - temp[ii, jj])\r\n # # if np.absolute(im[ii,jj] - temp[ii,jj]) < 0.0001:\r\n # # diff += 1\r\n # print(diff / im.size)\r\n return temp\r\n\r\n\r\ndef sharpen(im, strength):\r\n laplacian_kernel = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])\r\n temp_gaussian = blur(im)\r\n temp_gaussian_edge_detect = conv_2d(temp_gaussian, laplacian_kernel)\r\n return normalize(temp_gaussian_edge_detect + im)\r\n\r\n\r\ndef main():\r\n try:\r\n if len(sys.argv) < 5:\r\n strength = 1\r\n else:\r\n strength = sys.argv[4]\r\n\r\n proc_type = sys.argv[1]\r\n img = sys.argv[2]\r\n output_name = sys.argv[3]\r\n\r\n valid_proc = ['blur', 'sharpen', 'bw'] # Check Proc\r\n assert (proc_type in valid_proc)\r\n\r\n img = iio.imread(img).astype(float)\r\n\r\n grayscale = 0\r\n\r\n if proc_type == 'blur': # Run correct method\r\n processed_img = blur(img)\r\n if proc_type == 'sharpen':\r\n processed_img = sharpen(img, strength)\r\n if proc_type == 'bw':\r\n processed_img = rgb_to_bw(img)\r\n\r\n iio.imwrite(processed_img)\r\n\r\n # plt.imshow(grayscale, cmap='gray')\r\n # plt.show()\r\n except AssertionError:\r\n err_string_proc = \"processing type must be blur, sharpen, or bw\"\r\n print(err_string_proc)\r\n except IndexError:\r\n err_string_usage = (\"Usage:\\n\"\r\n \" $ python imageprocessing.py \"\r\n \" \"\r\n \"[strength (default=1)]\")\r\n print(err_string_usage)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n", "repo_name": "jackj770/ECE1400", "sub_path": "hw6-assignment/imageprocessing.py", "file_name": "imageprocessing.py", "file_ext": "py", "file_size_in_byte": 3872, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.amin", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.amax", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.rint", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.fliplr", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.multiply", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 82, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 90, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 93, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 95, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 96, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 97, "usage_type": "attribute"}, {"api_name": "imageio.imread", "line_number": 102, "usage_type": "call"}, {"api_name": "imageio.imwrite", "line_number": 113, "usage_type": "call"}]} +{"seq_id": "13765607397", "text": "# run with python3\n\n# General data manipulation packages\nimport numpy as np\nimport pandas as pd\nimport sqlite3 as sql\n\n# Useful function to split data sets\nfrom sklearn.model_selection import train_test_split\n\n# Random Forest class:\nfrom sklearn.ensemble import RandomForestClassifier\n\n# For pickling results\nimport pickle\n\n# Function to calculate the prediction accuracy from the classifier\nfrom sklearn.metrics import accuracy_score\n\n# Function to calculate a confusion matrix\nfrom sklearn.metrics import confusion_matrix\n\n# Packages used for plotting\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Function to read in the features in a pandas dataframe\nfrom train_random_forest_sql import reformat_as_dataframe\n\nclass RFPredictions(object):\n \"\"\"Keep track of a random forest's predictions on a test data set\n for analysis and visualization\"\"\"\n def __init__(self, rf, data_test):\n self.rf = rf\n self.data = data_test\n try:\n self.labels = data_test['labels']\n except Exception:\n self.labels = None\n other_columns = [c for c in data_test.columns if c != 'labels']\n self.data = data_test[other_columns]\n def predict(self):\n self.predictions = self.rf.predict(self.data)\n self.probabilities = self.rf.predict_proba(self.data)\n if self.labels is not None:\n self.accuracy = accuracy_score(self.labels, self.predictions)\n def print_score(self):\n print('Out-of-bag score estimate: %.3f' % self.rf.oob_score_)\n if self.labels is not None:\n print('Mean accuracy score: %.3f' % self.accuracy)\n def plot_confusion_matrix(self, title='confusion matrix', figname='cm.pdf', show=False):\n if self.labels is None:\n print('Cannot plot confusion matrix without data labels (true positives).')\n return\n cm_labels = ['unmodified', 'modified']\n cm = pd.DataFrame(confusion_matrix(self.labels, self.predictions))\n print(cm[::-1])\n\n plt.figure(figsize = (10,8))\n sns.set(font_scale=1.4)#for label size\n ax = plt.subplot()\n sns.heatmap(cm, annot=True, annot_kws={\"size\": 12}, ax=ax, fmt='g')# font size, axes, number format\n\n # labels, title and ticks\n ax.set_xlabel('Predicted')\n ax.set_ylabel('True')\n ax.set_title(title);\n ax.xaxis.set_ticklabels(['unmodified', 'modified'])\n ax.yaxis.set_ticklabels(['unmodified', 'modified'])\n ax.set(ylim=(0,2))\n plt.savefig(figname, dpi=300)\n print('Confusion matrix figure saved to %s' % figname)\n if show:\n plt.show()\n\ndef filter_all_tested_to_match_preds(predictions, all_tested_filename, new_filename):\n with open(all_tested_filename, \"r\") as old_file:\n all_tested = old_file.readlines()\n with open(new_filename, \"w\") as new_file:\n filter_print = lambda line: new_file.write(\" \".join(line.split()[:17]) + \"\\n\")\n for i in range(len(predictions)):\n if predictions[i]:\n filter_print(all_tested[i])\n print(\"wrote %s\" % new_filename)\n\n\ndef plot_predictions(rf_filename, db_filename, title=None, show=False):\n with open(rf_filename, \"rb\") as rf_file:\n rf = pickle.load(rf_file)\n features_df = reformat_as_dataframe(db_filename, labels=True)\n predictions = RFPredictions(rf, features_df)\n predictions.predict()\n filter_all_tested_to_match_preds(predictions.predictions, \"all_tested_ptms.out\", \"preds_by_rf.out\")\n predictions.print_score()\n predictions.plot_confusion_matrix(title=title, show=show)\n\nif __name__ == \"__main__\":\n import sys\n rf_filename, db_filename, plot_title = sys.argv[1:4]\n plot_predictions(rf_filename, db_filename, title=plot_title)\n", "repo_name": "fraser-lab/qptm", "sub_path": "train_rf/test_random_forest_sql.py", "file_name": "test_random_forest_sql.py", "file_ext": "py", "file_size_in_byte": 3543, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sklearn.metrics.accuracy_score", "line_number": 46, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 56, "usage_type": "call"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "seaborn.set", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 61, "usage_type": "name"}, {"api_name": "seaborn.heatmap", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 89, "usage_type": "call"}, {"api_name": "train_random_forest_sql.reformat_as_dataframe", "line_number": 90, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 99, "usage_type": "attribute"}]} +{"seq_id": "36197517305", "text": "# !usr/bin/python\n# -*- coding: utf-8 -*-\nfrom flask import jsonify, abort, request\nfrom flask_swagger import swagger\nimport jiebahelper\nfrom flask_swagger_ui import get_swaggerui_blueprint\nfrom collections import Counter\nimport jieba\nfrom flask import Flask\nfrom flask_cors import CORS\nfrom json_flask import JsonFlask\nfrom json_response import JsonResponse\n# app = Flask(__name__)\napp = JsonFlask(__name__)\nSWAGGER_URL = '/api/docs' # URL for exposing Swagger UI (without trailing '/')\nAPI_URL = '/swagger'\n# Call factory function to create our blueprint\nswaggerui_blueprint = get_swaggerui_blueprint(\n # Swagger UI static files will be mapped to '{SWAGGER_URL}/dist/'\n SWAGGER_URL,\n API_URL,\n config={ # Swagger UI config overrides\n 'app_name': \"Jiebao Application\"\n }\n)\n\n\n# Register blueprint at URL\n# (URL must match the one given to factory function above)\napp.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)\nCORS(app, supports_credentials=True)\n\n\n@app.route(\"/swagger\")\ndef spec():\n swag = swagger(app)\n swag['info']['version'] = \"1.0\"\n swag['info']['title'] = \"Segment API\"\n return jsonify(swag)\n\n\n@app.route('/')\ndef index():\n return 'Jiebao Segment API by Python.'\n\n\nfrom flask import make_response\n\n\n@app.errorhandler(404)\ndef not_found(error):\n return make_response(jsonify({'error': 'Not found'}), 404)\n\n\n@app.errorhandler(400)\ndef para_error(error):\n # 数据错误\n return make_response(jsonify({'error': 'Parameter Error'}), 400)\n\n\n@app.route('/segment', methods=['POST'])\ndef segment():\n '''\n 切词。不带词性,去停词\n ---\n tags:\n - segment\n parameters:\n - in: body\n name: body\n description: 内容\n required: true\n schema:\n type: string\n '''\n a = request.data.strip()\n if a == '':\n abort(400)\n ret = jiebahelper.dosegment(a)\n return JsonResponse.success(ret, 200, \"success\")\n\n\n@app.route('/segmentpos', methods=['POST'])\ndef segmentpos():\n '''\n 切词。带词性,去停词\n ---\n tags:\n - segment\n parameters:\n - in: body\n name: body\n description: 内容\n required: true\n schema:\n type: string\n '''\n a = request.data.strip()\n if a == '':\n abort(400)\n ret = jiebahelper.dosegment_with_pos(a)\n return JsonResponse.success(ret, 200, \"success\")\n\n\n@app.route('/segmentall', methods=['POST'])\ndef segmentall():\n '''\n 切词。带词性,不去停词\n ---\n tags:\n - segment\n parameters:\n - in: body\n name: body\n description: 内容\n required: true\n schema:\n type: string\n '''\n a = request.data.strip()\n if not a:\n abort(400)\n ret = jiebahelper.dosegment_all(a)\n return JsonResponse.success(ret, 200, \"success\")\n\n\n# 词频率统计\n@app.route('/wordcount', methods=['POST'])\ndef wordcount():\n '''\n 切词。带词性,去停词\n ---\n tags:\n - segment\n parameters:\n - in: body\n name: body\n description: 内容\n required: true\n schema:\n type: string\n '''\n a = request.data.strip()\n if a == '':\n abort(400)\n ret = jieba.cut(a.strip())\n wordcount = Counter()\n for word in ret:\n if len(word) > 1 and word not in jiebahelper.stopwords:\n wordcount[word] += 1\n print(wordcount.most_common(10))\n return JsonResponse.success(wordcount.most_common(10), 200, \"success\")\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5001)\n", "repo_name": "startshineye/python-tools", "sub_path": "segment_word/app/SegmentAPI.py", "file_name": "SegmentAPI.py", "file_ext": "py", "file_size_in_byte": 3765, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "json_flask.JsonFlask", "line_number": 14, "usage_type": "call"}, {"api_name": "flask_swagger_ui.get_swaggerui_blueprint", "line_number": 18, "usage_type": "call"}, {"api_name": "flask_cors.CORS", "line_number": 31, "usage_type": "call"}, {"api_name": "flask_swagger.swagger", "line_number": 36, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 39, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 58, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 58, "usage_type": "call"}, {"api_name": "flask.request.data.strip", "line_number": 76, "usage_type": "call"}, {"api_name": "flask.request.data", "line_number": 76, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 76, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 78, "usage_type": "call"}, {"api_name": "jiebahelper.dosegment", "line_number": 79, "usage_type": "call"}, {"api_name": "json_response.JsonResponse.success", "line_number": 80, "usage_type": "call"}, {"api_name": "json_response.JsonResponse", "line_number": 80, "usage_type": "name"}, {"api_name": "flask.request.data.strip", "line_number": 98, "usage_type": "call"}, {"api_name": "flask.request.data", "line_number": 98, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 98, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 100, "usage_type": "call"}, {"api_name": "jiebahelper.dosegment_with_pos", "line_number": 101, "usage_type": "call"}, {"api_name": "json_response.JsonResponse.success", "line_number": 102, "usage_type": "call"}, {"api_name": "json_response.JsonResponse", "line_number": 102, "usage_type": "name"}, {"api_name": "flask.request.data.strip", "line_number": 120, "usage_type": "call"}, {"api_name": "flask.request.data", "line_number": 120, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 120, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 122, "usage_type": "call"}, {"api_name": "jiebahelper.dosegment_all", "line_number": 123, "usage_type": "call"}, {"api_name": "json_response.JsonResponse.success", "line_number": 124, "usage_type": "call"}, {"api_name": "json_response.JsonResponse", "line_number": 124, "usage_type": "name"}, {"api_name": "flask.request.data.strip", "line_number": 143, "usage_type": "call"}, {"api_name": "flask.request.data", "line_number": 143, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 143, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 145, "usage_type": "call"}, {"api_name": "jieba.cut", "line_number": 146, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 147, "usage_type": "call"}, {"api_name": "jiebahelper.stopwords", "line_number": 149, "usage_type": "attribute"}, {"api_name": "json_response.JsonResponse.success", "line_number": 152, "usage_type": "call"}, {"api_name": "json_response.JsonResponse", "line_number": 152, "usage_type": "name"}]} +{"seq_id": "37306015288", "text": "from ete3 import Tree, TreeStyle, TreeNode, TextFace, NodeStyle\nimport random\nrandom.seed(4)\nfrom pathlib import Path\nfrom shutil import copy, move\nimport seaborn as sns\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom subprocess import call\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom Bio.Alphabet import IUPAC\nimport json\nimport tarfile\nimport networkx as nx\nimport argparse\n\n#UTILITY FUNCTIONS\n#used to sort tuples based on the third field \"leaves distance\"\ndef getKey(item):\n\treturn item[2]\n\n#method to recursively remove a folder\ndef delete_folder(pth) :\n for sub in pth.iterdir() :\n if sub.is_dir() :\n delete_folder(sub)\n else :\n sub.unlink()\n pth.rmdir()\n\n\n#METHODS\n#backtranslate protein genes of the genomes into DNA\ndef backtranslate(path):\n\taa_codon_table = { #from translation table 11 NCBI\n\t\t'F':'TTT' ,\n\t\t'Y':'TAT' ,\n\t\t'C':'TGT' ,\n\t\t'W':'TGG' ,\n\t\t'H':'CAT' ,\n\t\t'L':'CTC' ,\n\t\t'P':'CCG' ,\n\t\t'Q':'CAG' ,\n\t\t'I':'ATC' ,\n\t\t'T':'ACC' ,\n\t\t'N':'AAC' ,\n\t\t'S':'AGC' , \n\t\t'M':'ATG' , \n\t\t'K':'AAG' ,\n\t\t'R':'AGG' ,\n\t\t'D':'GAC' ,\n\t\t'V':'GTG' , \n\t\t'A':'GCG' ,\n\t\t'E':'GAG' , \n\t\t'G':'GGG' ,\n\t\t'*':'TAG' \n\t}\n\n\t\n\t#path = Path(path,'genome','genome','DB')\n\tPath(path,'dna').mkdir(parents=True, exist_ok=True)\n\tPath(path,'protein').mkdir(parents=True, exist_ok=True)\n\n\tfor filepath in sorted(path.glob('*_aa.fa')):\n\t\t\t\n\t\tto_fasta = list()\n\t\tfor sequence in SeqIO.parse(filepath,'fasta'):\n\t\t\t\t\t\n\t\t\taa_seq = list()\n\t\t\tfor char in sequence.seq:\n\t\t\t\taa_seq.append(aa_codon_table[char])\n\t\t\t\n\t\t\tsequence.seq = Seq(''.join(aa_seq), IUPAC.ambiguous_dna )\n\t\t\tto_fasta.append(sequence)\n\t\n\t\toutfile = filepath.stem.replace('_aa','_dna')+'.fasta'\n\t\tSeqIO.write(to_fasta,Path(path,'dna',outfile),'fasta')\n\n\t\tnew_path = Path(path,'protein',filepath.name.replace('.fa','.fasta'))\n\t\t#move(filepath, new_path) #per ora copio per poter rilanciare il programma\n\t\tcopy(filepath, new_path)\n\t\t#print(outfile)\n\n#CVTree (composition vector tree)\nfrom subprocess import PIPE\ndef runCVTree(in_path, out_path):\n\t#cmd = ['./parallel.out', str(in_path)+'/']\n\tcmd = ['./cvtree.sh', str(in_path)+'/']\n\tif Path('results-parallel.csv').exists():\n\t\tPath('results-parallel.csv').unlink()\n\tprint(\"calling cvtree repeatedly...\")\n\twhile not Path('results-parallel.csv').exists():\n\t\tcall(cmd)\n\t\t\n\t#call(cmd)\n\tif Path(out_path,'results-parallel.csv').exists():\n\t\tPath(out_path,'results-parallel.csv').unlink()\n\tmove('results-parallel.csv', out_path)\n\t\t\n\n#CVTree to matrix\ndef csv2matrix(in_path):\n\n\tdata = pd.read_csv(in_path)\n\tm_size = max(max(data['indexA']),max(data['indexB']))+1\n\tmatrix = np.zeros(shape=(m_size,m_size))\n\n\tlabels = list()\n\t\n\tfor index, row in data.iterrows():\n\t\t\n\t\tidxA = int(row['indexA'])\n\t\tidxB = int(row['indexB'])\n\t\tcorrelation = row['correlation']\n\t\t\n\t\t#distance = 1-correlation\n\t\tmatrix[idxA,idxB] = 1.0 - correlation\n\t\tmatrix[idxB,idxA] = 1.0 - correlation\n\t\t\n\t\tbactA = Path(row['bacteriaA']).stem\n\t\tif bactA not in labels:\n\t\t\tlabels.append(bactA)\n\t\t\n\tlabels.append(Path(data['bacteriaB'].iloc[-1]).stem)\n\n\tdf = pd.DataFrame(matrix, index=labels, columns=labels)\n\t\n\t#i'm removing the '_dna' from indexes and columns in because they are kept\n\tdf.index = [i.replace('_dna','') for i in df.index]\n\tdf.columns = [c.replace('_dna','') for c in df.columns]\n\tdf.to_csv(Path(in_path.parent,'CVTree_matrix.csv'))\n\t\n\treturn df\n\n\n\n#input path of the tar file, output directory where you save the family clus\ndef alf2families(in_path, out_dir): \n\n\t#extract VP.tgz ( it contains data about homologues, orthologues, paralogues and xenologues )\n\ttar = tarfile.open(Path(in_path,'VP.tgz'), \"r:gz\")\n\ttar.extractall(path=in_path)\n\ttar.close()\n\n\tprint('\\nGenerating graph...')\n\tG = nx.Graph() #inizializzo il grafo\n\torthologues_filepath = Path(in_path,'VP','OP.drw')\n\t\n\t#ortologhi\n\torth = open(orthologues_filepath) #non prendo il file HP con tutti gli omologhi perchè è composto ortologhi, paraloghi e xenologhi(LGT). Usare file separati permette di fare statistiche su 3 tipi di omologhi in modo piu chiaro senza impattare sui tempi di analisi del codice\n\ta = orth.readlines()\n\tb = a[1].lstrip('OP := ').rstrip(':\\n')\n\n\tarray = json.loads(b) #dati del file di omologhi ( ortologhi, paraloghi, non dovrebbero essere inclusi gli xenologhi perchè è genoma i vs genoma j e le LGT sono tra 1 genoma e molti genomi paralleli )\n\n\tfor i in range(len(array)): #indice genoma di riferimento --> \"genoma i\" vs\n\t\t\n\t\tid_i = '{0}'.format(str(i+1).zfill(3)) # i+1 perchè i genomi partono da SE001 mentre gli indici partono da 0\n\t\tgenome_i = 'SE'+id_i\n\n\t\tfor j in range(len(array[i])):#indice genoma a cui punta il genoma i --> genoma i vs \"genoma j\"\n\t\t\t\n\t\t\tid_j = '{0}'.format(str(j+1).zfill(3))\n\t\t\tgenome_j = 'SE'+id_j\n\t\t\t#print(genome_i,'vs',genome_j)\n\n\t\t\tfor p in range(len(array[i][j])): #vado a vedere il contenuto delle posizioni\n\t\t\t\t\n\t\t\t\tif array[i][j][p]: #se non è una posizione vuota\n\t\t\t\t\tgene_i = 'G'+str(p+1)\n\t\t\t\t\tgene_j = 'G'+str(array[i][j][p][0])\n\n\t\t\t\t\tnode_i = (genome_i,gene_i)\n\t\t\t\t\tnode_j = (genome_j,gene_j)\n\t\t\t\t\t#print( node_i, node_j )\n\t\t\t\t\t\n\t\t\t\t\tif node_i not in G:\n\t\t\t\t\t\tG.add_node(node_i)\n\t\t\t\t\tif node_j not in G:\n\t\t\t\t\t\tG.add_node(node_j)\n\t\t\t\t\t\n\t\t\t\t\tG.add_edge(node_i,node_j)\n\n\torth.flush()\n\torth.close()\n\n\n\t#paraloghi ( da aggiungere al grafo ) [i paraloghi sono segnati sul file correttamente]\n\tparalogues_filepath = Path(in_path,'VP','PP.drw')\n\tpara = open(paralogues_filepath) #non prendo il file HP con tutti gli omologhi perchè è composto ortologhi, paraloghi e xenologhi(LGT). Usare file separati permette di fare statistiche su 3 tipi di omologhi in modo piu chiaro senza impattare sui tempi di analisi del codice\n\ta = para.readlines()\n\tb = a[1].lstrip('PP := ').rstrip(':\\n')\n\n\tarray = json.loads(b)\n\n\tfor d in range(len(array)):\n\t\tid_i = '{0}'.format(str(d+1).zfill(3)) # prendo solo le diagonali quindi i == j, uso d come indice\n\t\tgenome_i = 'SE'+id_i\n\n\t\tid_j = '{0}'.format(str(d+1).zfill(3))\n\t\tgenome_j = 'SE'+id_j\n\n\t\tfor p in range(len(array[d][d])): #vado a vedere il contenuto delle posizioni\n\t\t\tgene_i = 'G'+str(p+1)\n\t\t\tnode_i = (genome_i,gene_i)\n\t\t\tif node_i not in G:\n\t\t\t\tG.add_node(node_i)\n\n\t\t\tif array[d][d][p]: #se non è una posizione vuota\n\t\t\t\tgene_i = 'G'+str(p+1)\n\t\t\t\tgene_j = 'G'+str(array[d][d][p][0])\n\n\t\t\t\tnode_i = (genome_i,gene_i)\n\t\t\t\tnode_j = (genome_j,gene_j)\n\t\t\t\t#print( node_i, node_j )\n\t\t\t\t\n\t\t\t\tif node_i not in G:\n\t\t\t\t\tG.add_node(node_i)\n\t\t\t\tif node_j not in G:\n\t\t\t\t\tG.add_node(node_j)\n\t\t\t\t\n\t\t\t\tG.add_edge(node_i,node_j)\n\tpara.flush()\n\tpara.close()\n\t\n\t#print('Gene Families found',len(list(nx.connected_components(G))),'\\n')\n\t\n\t#file.clus\n\tcluspath = Path(out_dir,'alf_families.clus')\n\tprint('Saving families.clus in :',cluspath)\n\twith open(cluspath,'w') as handle:\n\t\tfor f in list(nx.connected_components(G)):\n\t\t\t#print(type(f), sorted(f)) #f è un set\n\t\t\taux = list()\n\t\t\tfor s in sorted(f):\n\t\t\t\taux.append(s[1]+'_'+s[0])\n\n\t\t\t#print(repr('\\t'.join(aux)+'\\n'))\t\t\t\n\t\t\thandle.write(' '.join(aux)+'\\n')\n\n\ndef getGenomeDistribution(path_clus):\n\t#qui calcolo l'istogramma della \"genomes per class distribution\"\n\n\thistogram = dict() #numero di famiglie che toccano X genomi\n\tfor line in open(path_clus,'r'):\n\t\tgenes = line.strip().split(' ')\n\t\t\n\t\taux = set() #set perchè non ha ripetizioni, paraloghi appartengono allo stesso genoma\n\t\tfor g in genes:\n\t\t\tgenome = g.split('_')[1]\n\t\t\taux.add(genome)\n\n\t\thistogram[int(len(aux))] = histogram.get(len(aux),0)+1\n\n\treturn histogram\n \n\ndef get_datasetFASTA(tree, pth_mintree_dataset, pth_alf_dataset):\n\tfasta_path = Path(pth_alf_dataset,'DB','dna')\n\t\n\tdataset_path = Path(pth_mintree_dataset,'dna')\n\tdataset_path.mkdir(parents=True, exist_ok=True)\n\n\tleaves = [leaf.name for leaf in tree]\n\tfor f in [leaf+'_dna.fasta' for leaf in leaves]:\n\t\tcopy(Path(fasta_path,f),Path(dataset_path,f))\n\t\n\tfasta_path = Path(pth_alf_dataset,'DB','protein')\n\tdataset_path = Path(pth_mintree_dataset,'protein')\n\tdataset_path.mkdir(parents=True, exist_ok=True)\n\n\tfor f in [leaf+'_aa.fasta' for leaf in leaves]:\n\t\tcopy(Path(fasta_path,f),Path(dataset_path,f))\n\t\n\treturn dataset_path.parent\n\n\n#create the gene family file from the complete family .clus file of ALF\ndef get_familiesSelection(tree,dataset_name,out_path, pth_alf_dataset):\n\twith open(Path(out_path,dataset_name+'.clus'),'w') as out:\n\t\tleaves = [leaf.name for leaf in tree]\n\t\tfor line in open(Path(pth_alf_dataset,'alf_families.clus'),'r'):\n\t\t\tbuffer = list()\n\t\t\tfamily = line.strip().split(' ')\n\t\t\t#rimuovo i geni che non appartengono ai genomi delle foglie\n\t\t\tfor gene in family:\n\t\t\t\tgenome = gene.split('_')[1]\n\t\t\t\tif genome in leaves:\n\t\t\t\t\tbuffer.append(gene)\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\t\t#print(buffer)\n\t\t\t#print(len(buffer))\n\t\t\tif buffer: #se il buffer non è vuoto aggiunge la famiglia sul file\n\t\t\t\tout.write(' '.join(buffer)+'\\n')\n\n\n#shows the selected genomes on the complete phylogenetic tree\ndef highlight_selection(tree, selection, out_name, seed=True):\n\n\thighlight_tree = tree.copy() \n\t# Draws nodes as small red spheres of diameter equal to 10 pixels\n\tnstyle = NodeStyle()\n\tnstyle[\"shape\"] = \"sphere\"\n\tnstyle[\"size\"] = 10\n\tnstyle[\"fgcolor\"] = \"darkred\"\n\n\t#evidenzio diversamente il genoma seed\n\tnstyle_seed = NodeStyle()\n\tnstyle_seed[\"shape\"] = \"square\"\n\tnstyle_seed[\"size\"] = 10\n\tnstyle_seed[\"fgcolor\"] = \"yellow\"\n\n\t# Applies the same static style to all nodes in the tree. Note that,\n\t# if \"nstyle\" is modified, changes will affect to all nodes\n\tfor genome in selection:\n\t\tnode = highlight_tree.get_leaves_by_name(genome)[0]\n\t\tnode.set_style(nstyle)\n\n\t#nodo centrale\n\tif seed:\n\t\tseed = highlight_tree.get_leaves_by_name(selection[0])[0]\n\t\tseed.set_style(nstyle_seed)\n\t\n\thighlight_tree.render(out_name,tree_style=ts)\n\ndef histogramDistribution(in_path, hist_name):\n\thistogram = getGenomeDistribution(in_path)\n\tnof_genomes = max(histogram)\n\t\n\thist = [0]*nof_genomes\n\tfor k in histogram:\n\t\thist[k-1] = histogram[k] \n\t\t\n\tx = range(1,len(hist)+1)\n\n\tplt.bar(x,hist,color='blue')\n\t#plt.xticks([],[]) #no x-axis ticks\n\tplt.xlabel('Genomes')\n\tplt.ylabel('Gene Families')\n\tplt.title('Genomes per family distribution')\n\t\n\tplt.savefig(Path(in_path.parent,hist_name))\n\tplt.clf()\n\t\ndef createALFinput(nof_species, seed, loss_rate=0, indel_rate=0.003, dupl_level=0):\n\tinput_file = [\"SetRand(\"+str(seed)+\"): # use this with any number, if you want reproducable results\",\n\t\"webRequest := false;\",\n\t\"uuid := 's0-uuid';\",\n\t\"# name of simulation - you may want to change this\",\n\t\"mname := dataset;\",\n\t\"# directories for file storage - you may want to change these\",\n\t\"wdir := 'alf_results/datasets/'.mname.'/';\",\n\t\"dbdir := 'DB/';\",\n\t\"#dbAncdir := 'DBancestral/';\",\n\t\"# time scale for simulation (PAM is default)\",\n\t\"unitIsPam := false:\",\n\t\"# parameters concerning the root genome\",\n\t\"realorganism := './input/mycoplasma.g-1.db';\",\n\t\"# parameters concerning the species tree\",\n\t\"treeType := 'BDTree';\",\n\t\"birthRate := 0.2;\",\n\t\"deathRate := 0.15;\",\n\t\"mutRate := 5000;\",\n\t\"NSpecies := \"+str(nof_species)+\";\",\n\t\"ultrametric := false;\",\n\t\"#scaleTree := false;# parameters concerning the substitution models\",\n\t\"substModels := [SubstitutionModel('WAG')];\",\n\t\"#indelModels := [IndelModel(0.002,GEOM,[0.333],50)]; #qui ho una maxLen di indels messa a 50, quindi posso anche avere delle indels lunghe fino a 50\",\n\t\"indelModels := [IndelModel(\"+str(indel_rate)+\", ZIPF, [1.821])];\",\n\t\"rateVarModels := [RateVarModel()];\",\n\t\"# parameters concerning gene duplication\",\n\t\"geneDuplRate := \"+str(dupl_level)+\";\",\n\t\"numberDupl := 10;\",\n\t\"fissionDupl := 0.0;\",\n\t\"fusionDupl := 0.0;\",\n\t\"# parameters concerning gene loss\",\n\t\"geneLossRate := \"+str(loss_rate)+\";\",\n\t\"numberLoss := 10;\",\n\t\"# parameters concerning LGT\",\n\t\"lgtRate := 0;\",\n\t\"#orthRep := 0;\",\n\t\"#lgtGRate := 0;\",\n\t\"#lgtGSize := 10;\",\n\t\"# parameters concerning rate heterogeneity among genes\",\n\t\"#amongGeneDistr := 'Gamma';\",\n\t\"#aGAlpha := 1;\",\n\t\"amongGeneDistr := 'None';\",\n\t\"# select the output you want (apart from the species tree and genomes)\",\n\t\"simOutput := { 'GeneTrees' , 'VP', 'Fasta', NULL }:\"]\n\n\twith open('input_alf.drw','w') as f:\n\t\tf.write('\\n'.join(input_file))\n\n#MAIN\n\n\nparser = argparse.ArgumentParser(description='Input parameters')\nparser.add_argument('-n', nargs=1 , type=int, dest=\"subset_dimension\",required=True, \nhelp=\"dimension of the minimum and random datasets\")\nparser.add_argument('-s', nargs=1 , type=int, dest=\"nof_species\",required=True, \nhelp=\"number of species\")\nparser.add_argument('-r', nargs=1 , type=int, dest=\"repetitions\",required=False, default=[1], \nhelp=\"generate multiple dataset\")\nparser.add_argument('-loss', nargs=1 , type=float, dest=\"loss_rate\",required=False, default=[0],\nhelp=\"loss rate for ALF\")\nparser.add_argument('-indel', nargs=1 , type=float, dest=\"indel_rate\",required=False, default=[0.003],\nhelp=\"indel rate for ALF\")\nparser.add_argument('-dupl', nargs=1 , type=float, dest=\"dupl_level\",required=False, default=[0.0],\nhelp=\"duplication level for ALF\")\nparser.add_argument('--analysis_only', action='store_false', dest='analysis_only', \nhelp=\"use this flag to run only the analysis of the dataset obtained with alf\")\n\nargs = parser.parse_args()\n\ngenome_group_dimension = args.subset_dimension[0]\nnof_species = args.nof_species[0]\nrepetitions = args.repetitions[0]\nloss_rate = args.loss_rate[0]\nindel_rate = args.indel_rate[0]\ndupl_level = args.dupl_level[0]\n\nprint('nof_species:', nof_species)\nprint('repetitions dataset:', repetitions)\nprint('subset dimension:',genome_group_dimension)\nprint('loss rate:', loss_rate)\nprint('indel rate:', indel_rate)\nprint('duplication level', dupl_level)\n#print('analysis only:', 'no' if args.analysis_only else 'yes', end='\\n\\n')\n\ninput_datasets = Path('input_datasets')\n\n#tree style\nts = TreeStyle()\nts.show_leaf_name = True\nts.mode = \"c\" #circular tree\nts.show_branch_length = True\n#ts.scale = 20 #per scalare(ridurre o aumentare) la dimensione dell'albero\nts.arc_start = 0 # 0 degrees = 3 o'clock\nts.arc_span = 360\n\n\n\n#ALF dataset#\n\n#convert mycoplasma genome into darwin format for ALF\n\ncall(['alf/bin/fasta2darwin','input/mycoplasma.g-1.fasta'])\nif Path('alf_results').exists():\n\t\tdelete_folder(Path('alf_results'))\n\nif Path('input_datasets').exists():\n\tdelete_folder(Path('input_datasets'))\n\n\nstartseed = 123\nstartseed = abs(int(repetitions * startseed) + startseed)\nendseed = startseed + repetitions\n\n\nfor seed in range(startseed, endseed):\n\tcreateALFinput(nof_species, seed, loss_rate=loss_rate, indel_rate=indel_rate, dupl_level=dupl_level)\n\t##run alf\n\tcall(['./alf/bin/alfsim','input_alf.drw'])\n\nfor dataset in Path('alf_results','datasets','dataset').glob('*'):\n\n\t#backtranlslate protein files into dna because alf has a bug\n\tbacktranslate(Path(dataset,'DB'))\n\n\t#retrieve genomes families (alf_families.clus)\n\tprint('Writing gene families file : alf_families.clus')\n\talf2families(dataset,dataset)\n\t\n\t\"\"\"\n\t#CVTree on dna fasta files\n\tprint('Running CVTree on :',dataset)\n\trunCVTree(Path(dataset,'DB','dna'),dataset)\n\n\tdf = csv2matrix(Path(dataset,'results-parallel.csv'))\n\n\t#heatmap with cluster\n\tsns.clustermap(df, cmap='RdBu')\n\tplt.savefig(Path(dataset,'heatmap_alfFull.png'))\n\tplt.clf() #clear figure\n\t\"\"\"\n\n\t#computing genomes per family distribution\n\thistogramDistribution(Path(dataset,'alf_families.clus'),'histogram_alfFull.png')\n\n\t#RETRIEVE PHYLOGENETIC TREES FOR ALF DATASETS\n\tnwk = Path(dataset,'RealTree.nwk')\n\tt = Tree(str(nwk))\n\tt.render(str(dataset)+'/TreeFull.png',tree_style=ts)\n\t#t.show(tree_style=ts)\n\t\n\n\t###CREATE CLOSE GENOMES SUBSETS : Tree -> selection -> retrieval from alf data###\n\t#dataset folder mintree (the number corresponds to the relative alf dataset)\n\tif len(dataset.stem.split('_'))>1:\n\t\tdataset_mintree = Path(input_datasets,'dataset_mintree','mintree_'+dataset.stem.split('_')[1])\n\telse:\n\t\tdataset_mintree = Path(input_datasets,'dataset_mintree','mintree')\n\t\n\tdataset_mintree.mkdir(parents=True, exist_ok=True)\t\n\n\tmindist_list = ([],float('inf'))\n\tleaves = [leaf.name for leaf in t]\n\t\n\tfor i in leaves:\n\t\t\n\t\tbuffer = list()\n\t\tfor j in leaves:\t\t\n\t\t\tif i != j:\n\t\t\t\tbuffer.append((i,j, t.get_distance(i,j)))\n\n\t\t# meno 1 perchè calcola i 49 genomi piu vicini +1 che è il genoma iniziale a fare un gruppo da 50\t\t\n\t\tselection = sorted(buffer,key=getKey)[0:genome_group_dimension-1]\n\n\t\tdistance_sum = 0\n\t\tfor q in selection:\n\t\t\tdistance_sum += q[2]\n\t\t\n\t\tif distance_sum < mindist_list[1]:\n\t\t\tmindist_list = (selection,distance_sum)\n\n\n\t#minimum distance list\n\tmin_list = [mindist_list[0][0][0]] #il genoma confrontato con tutti gli altri (seed da acui è calcolata la distanza dagli altri nodi)\n\t#print(min_list)\n\tfor g in mindist_list[0]: #per ogni tupla\n\t\tmin_list.append(g[1])\n\t\n\t#pruning tree with min\n\tmin_tree = t.copy()\n\tmin_tree.prune(min_list)\n\tmin_tree.render(str(dataset_mintree)+'/mintree.png',tree_style=ts)\n\n\t#Retrieve fasta files for the genomes selected for the mintree dataset\n\t#Parameter passed are the phylogenetic tree, the path to the mintree dataset, the relative path to alf dataset\n\tget_datasetFASTA(min_tree, dataset_mintree, dataset)\n\tget_familiesSelection(min_tree, dataset_mintree.stem, dataset_mintree, dataset)\n\thighlight_selection(t,min_list,str(dataset_mintree)+'/highlight_mintree.png')\n\t\t\n\t#histogram genomes per family distribution\n\tprint('computing histogram distribution of close distance genomes...')\n\thistogramDistribution(Path(dataset_mintree,dataset_mintree.stem+'.clus'),'histogram_mintree.png')\n\tprint('...done!')\n\t\n\t####\n\t\"\"\"\n\t#CVTree on randomtree dataset\n\tprint('Running CVTree on random genomes...')\n\trunCVTree(Path(dataset_mintree,'dna'), dataset_mintree)\n\tdf = csv2matrix(Path(dataset_mintree,'results-parallel.csv'))\n\tprint('...done!')\n\n\t#heatmap with cluster\n\tprint('computing heatmap of random genomes...')\n\tsns.clustermap(df, cmap='RdBu')\n\tplt.savefig(Path(dataset_mintree,'heatmap_mintree.png'))\n\tplt.clf()\n\tprint('...done!') \n\t\"\"\"\n\t\n\n\t##CREATE RANDOM SELECTION GENOMES SUBSETS##\n\t#dataset folder randomtree (the number corresponds to the relative alf dataset)\n\tif len(dataset.stem.split('_'))>1:\n\t\tdataset_randomtree = Path(input_datasets,'dataset_randomtree','randomtree_'+dataset.stem.split('_')[1])\n\telse:\n\t\tdataset_randomtree = Path(input_datasets,'dataset_randomtree','randomtree')\n\t\n\tdataset_randomtree.mkdir(parents=True, exist_ok=True)\n\t\n\t#leaves = [leaf.name for leaf in t]\n\n\n\trandom_list = random.sample(leaves, k=genome_group_dimension)\n\n\trandom_tree = t.copy()\n\n\trandom_tree.prune(random_list)\n\t#for l in random_tree:\n\t#\tif l.name not in random_list:\n\t#\t\tl.delete()\n\n\t\n\trandom_tree.render(str(dataset_randomtree)+'/randomtree.png',tree_style=ts)\n\n\tget_datasetFASTA(random_tree,dataset_randomtree, dataset)\n\tget_familiesSelection(random_tree, dataset_randomtree.stem, dataset_randomtree,dataset)\n\thighlight_selection(t,random_list,str(dataset_randomtree)+'/highlight_randomtree.png',seed=False)\n\t\n\t\"\"\"\n\t#CVTree on randomtree dataset\n\tprint('Running CVTree on random genomes...')\n\trunCVTree(Path(dataset_randomtree,'dna'), dataset_randomtree)\n\tdf = csv2matrix(Path(dataset_randomtree,'results-parallel.csv'))\n\tprint('...done!')\n\n\t#heatmap with cluster\n\tprint('computing heatmap of random genomes...')\n\tsns.clustermap(df, cmap='RdBu')\n\tplt.savefig(Path(dataset_randomtree,'heatmap_randomtree.png'))\n\tplt.clf()\n\tprint('...done!')\n\t\"\"\"\n\n\t#histogram genomes per family distribution\n\tprint('computing histogram distribution of random genomes...')\n\thistogramDistribution(Path(dataset_randomtree,dataset_randomtree.stem+'.clus'),'histogram_randomtree.png')\n\tprint('...done!')\n\t\n", "repo_name": "InfOmics/pangenes-review", "sub_path": "singleton-less/generate_datasets/create_dataset.py", "file_name": "create_dataset.py", "file_ext": "py", "file_size_in_byte": 19481, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "random.seed", "line_number": 3, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 63, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 64, "usage_type": "call"}, {"api_name": "Bio.SeqIO.parse", "line_number": 69, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 69, "usage_type": "name"}, {"api_name": "Bio.Seq.Seq", "line_number": 75, "usage_type": "call"}, {"api_name": "Bio.Alphabet.IUPAC.ambiguous_dna", "line_number": 75, "usage_type": "attribute"}, {"api_name": "Bio.Alphabet.IUPAC", "line_number": 75, "usage_type": "name"}, {"api_name": "Bio.SeqIO.write", "line_number": 79, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 79, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 79, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 81, "usage_type": "call"}, {"api_name": "shutil.copy", "line_number": 83, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 91, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 92, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 94, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 95, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 98, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 99, "usage_type": "call"}, {"api_name": "shutil.move", "line_number": 100, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 108, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 122, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 126, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 128, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 133, "usage_type": "call"}, {"api_name": "tarfile.open", "line_number": 143, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 143, "usage_type": "call"}, {"api_name": "networkx.Graph", "line_number": 148, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 149, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 156, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 191, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 196, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 231, "usage_type": "call"}, {"api_name": "networkx.connected_components", "line_number": 234, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 262, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 264, "usage_type": "call"}, {"api_name": "shutil.copy", "line_number": 269, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 269, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 271, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 272, "usage_type": "call"}, {"api_name": "shutil.copy", "line_number": 276, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 276, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 283, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 285, "usage_type": "call"}, {"api_name": "ete3.NodeStyle", "line_number": 306, "usage_type": "call"}, {"api_name": "ete3.NodeStyle", "line_number": 312, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 340, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 340, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 342, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 342, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 343, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 343, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 344, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 344, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 346, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 346, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 346, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 347, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 347, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 401, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 434, "usage_type": "call"}, {"api_name": "ete3.TreeStyle", "line_number": 437, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 451, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 452, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 453, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 455, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 456, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 467, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 469, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 472, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 492, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 495, "usage_type": "call"}, {"api_name": "ete3.Tree", "line_number": 496, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 504, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 506, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 550, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 573, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 575, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 582, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 615, "usage_type": "call"}]} +{"seq_id": "18644212843", "text": "\"\"\"empty message\n\nRevision ID: f7d921398532\nRevises: 3d2a173bf8b7\nCreate Date: 2021-01-12 11:30:56.198382\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'f7d921398532'\ndown_revision = '3d2a173bf8b7'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('comment',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('comment_content', sa.String(length=300), nullable=True),\n sa.Column('comment_image', sa.String(), nullable=True),\n sa.Column('time_posted', sa.DateTime(), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('post_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['post_id'], ['post.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_comment_time_posted'), 'comment', ['time_posted'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_comment_time_posted'), table_name='comment')\n op.drop_table('comment')\n # ### end Alembic commands ###\n", "repo_name": "romon267/flask-network", "sub_path": "migrations/versions/f7d921398532_.py", "file_name": "f7d921398532_.py", "file_ext": "py", "file_size_in_byte": 1268, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "alembic.op.create_table", "line_number": 21, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 21, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 24, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 24, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 25, "usage_type": "call"}, {"api_name": "sqlalchemy.DateTime", "line_number": 25, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 26, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 26, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 27, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 27, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 28, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 29, "usage_type": "call"}, {"api_name": "sqlalchemy.PrimaryKeyConstraint", "line_number": 30, "usage_type": "call"}, {"api_name": "alembic.op.create_index", "line_number": 32, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 32, "usage_type": "name"}, {"api_name": "alembic.op.f", "line_number": 32, "usage_type": "call"}, {"api_name": "alembic.op.drop_index", "line_number": 38, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 38, "usage_type": "name"}, {"api_name": "alembic.op.f", "line_number": 38, "usage_type": "call"}, {"api_name": "alembic.op.drop_table", "line_number": 39, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 39, "usage_type": "name"}]} +{"seq_id": "29832479763", "text": "import starepandas\nimport warnings\nimport shapely\n\nsids = [4611686018427387903, 4611686018427387903]\nsdf = starepandas.STAREDataFrame(sids=[sids])\ntrixels = sdf.make_trixels()\n\n\ndef test_settrixels():\n with warnings.catch_warnings(record=True) as w:\n s = sdf.set_trixels(trixels)\n if len(w) > 0:\n print(w[0])\n raise shapely.errors.ShapelyDeprecationWarning\n\n\n\n", "repo_name": "SpatioTemporal/STAREPandas", "sub_path": "tests/test_shapely20.py", "file_name": "test_shapely20.py", "file_ext": "py", "file_size_in_byte": 399, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "20", "api": [{"api_name": "starepandas.STAREDataFrame", "line_number": 6, "usage_type": "call"}, {"api_name": "warnings.catch_warnings", "line_number": 11, "usage_type": "call"}, {"api_name": "shapely.errors", "line_number": 15, "usage_type": "attribute"}]} +{"seq_id": "11221873299", "text": "\"\"\"\r\nThis program logs data received from a virtual sensor via digital data\r\nacquisition and turns on a green warning light for voltages above \r\n4.27 V and a red warning light for voltages below 2.56 V.\r\nThe signals are displayed using a blinkstick.It was written\r\nby Lalit Mistry in November 2021.\r\nThis code was formatted according to the PEP 8 style guide\r\navailable at https://www.python.org/dev/peps/pep-0008/\r\n\"\"\"\r\n\r\nimport sys\r\nfrom scada import DAQ\r\nimport datetime\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation as animation\r\nfrom matplotlib import style\r\nimport numpy as np\r\nfrom blinkstick import blinkstick\r\n\r\n# find the first available blinkstick\r\nbstick = blinkstick.find_first()\r\n\r\n# Let's ensure that the device is off (and use this in the future to reset it) \r\ndef lights_off():\r\n #turn off all the LEDs \r\n for led in range(0, 8):\r\n bstick.set_color(index = led, name = \"black\") \r\n\r\n# notify/stop if no blinkstick is found \r\nif bstick is None:\r\n print (\"Blinkstick not found...\")\r\n exit() \r\nelse: \r\n print (\"BlinkStick \" + bstick.get_serial() + \" found. Current color: \" + bstick.get_color(color_format = \"hex\"))\r\n #reset \r\n lights_off()\r\n\r\n# create new DAQ and connect to it in coursework mode\r\nmy_daq = DAQ()\r\nmy_daq.connect(\"coursework\")\r\nmy_daq.trigger()\r\n\r\n\r\n# initialise all variables\r\n# array containing times at which voltages are recorded\r\ntimes = []\r\n# array containing voltages\r\nvoltages = []\r\n# initialise counter variable for index of the current reading\r\nreadingNumber = 0\r\n# array containing at most the last 3 measured voltages\r\nlast3Voltages = []\r\n# the standard deviation in voltage\r\nstdeviation = 0.08\r\n\r\n# a function that converts the bit output from scada.py to a voltage\r\ndef b2v(bits):\r\n bitsInVoltage = (bits - 512) / 102.4\r\n return bitsInVoltage\r\n\r\n# a function that returns a tuple containing the time of the next reading and the average of the last 3 recorded voltages including the new voltage\r\ndef returnNextReading(readingNumber):\r\n # voltage in bits received from scada.py\r\n bitvoltage = my_daq.next_reading()[1]\r\n # time the current reading is taken at, assuming we're taking a reading every DELTA_T seconds\r\n time = readingNumber*my_daq.DELTA_T\r\n # array combining time and bitvoltage into an array \"newestReading\"\r\n newestReading = [time, b2v(bitvoltage)]\r\n # check if \"last3Voltages\" contains already 3 or more elements, if so remove the first one to make space for the new one\r\n if len(last3Voltages) >= 3:\r\n last3Voltages.pop(0)\r\n # add the new voltage (second element of array \"newestReading\") to the last 3 voltages\r\n last3Voltages.append(newestReading[1])\r\n # to produce a smoother curve less prone to signal noise we use the mean of the last 3 voltages as current voltage\r\n avgReading = time, np.mean(last3Voltages)\r\n return avgReading\r\n\r\n# a function to produce a matplotlib live plot of voltage against time\r\ndef animate(i, times, voltages):\r\n # declare readingNumber as global to access it within this function\r\n global readingNumber\r\n # read in the next data point\r\n time, voltage = returnNextReading(readingNumber)\r\n # switch blinkstick warning lights according to voltage taking sensor error into account\r\n if voltage <= -2.56 + 3 * stdeviation:\r\n bstick.set_color(index = 0, name = \"red\")\r\n elif voltage >= 4.27 - 3 * stdeviation:\r\n bstick.set_color(index = 0, name = \"green\")\r\n else:\r\n bstick.set_color(index = 0, name = \"black\")\r\n # append new time and voltage to the lists of times and voltages\r\n times.append(time)\r\n voltages.append(voltage)\r\n # record data in file for later usage\r\n datafile = open(\"sensor_data.txt\", \"a\")\r\n datafile.write(str(time) + str(voltage))\r\n # increment readingNumber counter variable to progress to next reading at next function call\r\n readingNumber += 1\r\n # setup plot\r\n ax1.clear()\r\n ax1.set_xlim([0,120])\r\n ax1.set_ylim([-6,6])\r\n ax1.set_xlabel(\"time since start of measurement, [s]\")\r\n ax1.set_ylabel(\"voltage, [V]\")\r\n ax1.set_title(\"sensor voltage over time\", pad = 10)\r\n # add horizontal lines indicating critical voltage thresholds\r\n upper = plt.axhline(y = -2.56, xmin = 0, xmax = 65, color = \"red\", lw = 2)\r\n lower = plt.axhline(y = 4.27, xmin = 0, xmax = 65, color = \"green\", lw = 2)\r\n plt.axhspan(4.27 - 3 * stdeviation, 4.27 + 3 * stdeviation, color = \"green\", alpha = 0.25)\r\n plt.axhspan(-2.56 - 3 * stdeviation, -2.56 + 3 * stdeviation, color = \"red\", alpha = 0.25)\r\n ax1.legend([lower, upper], [\"upper warning (4.27 V)\", \"lower warning (-2.56 V)\"])\r\n ax1.plot(times, voltages, lw = 2)\r\n\r\n# main program\r\n# get current time to determine when data recording started \r\nstartTime = datetime.datetime.now()\r\nprint(\"Data recording started at \" + startTime.strftime(\"%X\"))\r\n# setup plot\r\nstyle.use(\"fivethirtyeight\")\r\nfig = plt.figure()\r\nax1 = fig.add_subplot(1,1,1)\r\n\r\n# start live plot while listening for keyboard interrupt\r\ntry:\r\n ani = animation.FuncAnimation(fig, animate, fargs = (times, voltages), interval = my_daq.DELTA_T * 1000)\r\n plt.show()\r\n\r\nexcept KeyboardInterrupt:\r\n # This exception occurs if the user hits Ctrl+C while the\r\n # simulation is running, rather than crashing out of python\r\n # and leaving all the LEDs that are currently lit on, we can\r\n # turn them all off and exit gracefully.\r\n endTime = datetime.datetime.now()\r\n for led in range(0, 8):\r\n bstick.set_color(index = led,name = \"black\")\r\n print(\"Measurement stopped at \" + endTime.strftime(\"%X\"))\r\n sys.exit()\r\n\r\n\r\n\r\n\r\n \r\n", "repo_name": "schwarzer-geiger/Programming-Skills-for-Engineers", "sub_path": "annunciator.py", "file_name": "annunciator.py", "file_ext": "py", "file_size_in_byte": 5701, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "blinkstick.blinkstick.find_first", "line_number": 21, "usage_type": "call"}, {"api_name": "blinkstick.blinkstick", "line_number": 21, "usage_type": "name"}, {"api_name": "scada.DAQ", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.axhline", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 107, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axhline", "line_number": 108, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 108, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axhspan", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 109, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axhspan", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 116, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 116, "usage_type": "attribute"}, {"api_name": "matplotlib.style.use", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.style", "line_number": 119, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "matplotlib.animation.FuncAnimation", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.animation", "line_number": 125, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 126, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 133, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 133, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 137, "usage_type": "call"}]} +{"seq_id": "11753670224", "text": "from sumy.summarizers.lex_rank import LexRankSummarizer\nfrom sumy.nlp.tokenizers import Tokenizer\nfrom sumy.parsers.plaintext import PlaintextParser\nfrom janome.analyzer import Analyzer\nfrom janome.charfilter import UnicodeNormalizeCharFilter, RegexReplaceCharFilter\nfrom janome.tokenizer import Tokenizer as JanomeTokenizer # sumyのTokenizerと名前が被るため\nfrom janome.tokenfilter import POSKeepFilter, ExtractAttributeFilter\n\ntext = \"\"\"転職 Advent Calendar 2016 - Qiitaの14日目となります。 少しポエムも含みます。\n今年11月にSIerからWebサービスの会社へ転職しました。\n早くから退職することを報告していたこともあって、幸いにも有給消化として1ヶ月のお休みをいただくことができました(これでも10日ほど余らせてしまいました)。\n# ・・・ (省略) ・・・\nだからこそ、有給消化期間はなんとしてでももぎ取るようにしましょう。\"\"\"\n\n# 1行1文となっているため、改行コードで分離\nsentences = [t for t in text.split('\\n')]\nfor i in range(2):\n print(sentences[i])\n# 転職 Advent Calendar 2016 - Qiitaの14日目となります。 少しポエムも含みます。\n# 今年11月にSIerからWebサービスの会社へ転職しました。\n\n# 形態素解析器を作る\nanalyzer = Analyzer(\n [UnicodeNormalizeCharFilter(), RegexReplaceCharFilter(\n r'[(\\)「」、。]', ' ')], # ()「」、。は全てスペースに置き換える\n JanomeTokenizer(),\n [POSKeepFilter(['名詞', '形容詞', '副詞', '動詞']), ExtractAttributeFilter(\n 'base_form')] # 名詞・形容詞・副詞・動詞の原型のみ\n)\n\n# 抽出された単語をスペースで連結\n# 末尾の'。'は、この後使うtinysegmenterで文として分離させるため。\ncorpus = [' '.join(analyzer.analyze(s)) + '。' for s in sentences]\nfor i in range(2):\n print(corpus[i])\n# 転職 Advent Calendar 2016 - Qiita 14 日 目 なる 少し ポエム 含む。\n# 今年 11 月 SIer Web サービス 会社 転職 する。\n\n\n# 連結したcorpusを再度tinysegmenterでトークナイズさせる\nparser = PlaintextParser.from_string(''.join(corpus), Tokenizer('japanese'))\n\n# LexRankで要約を2文抽出\nsummarizer = LexRankSummarizer()\nsummarizer.stop_words = [' '] # スペースも1単語として認識されるため、ストップワードにすることで除外する\n\nsummary = summarizer(document=parser.document, sentences_count=2)\n\nprint('要約しました')\n# 元の文を表示\nfor sentence in summary:\n print(sentences[corpus.index(sentence.__str__())])\n", "repo_name": "t-kabaya/narouSummary", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2650, "program_lang": "python", "lang": "ja", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "janome.analyzer.Analyzer", "line_number": 23, "usage_type": "call"}, {"api_name": "janome.charfilter.UnicodeNormalizeCharFilter", "line_number": 24, "usage_type": "call"}, {"api_name": "janome.charfilter.RegexReplaceCharFilter", "line_number": 24, "usage_type": "call"}, {"api_name": "janome.tokenizer.Tokenizer", "line_number": 26, "usage_type": "call"}, {"api_name": "janome.tokenfilter.POSKeepFilter", "line_number": 27, "usage_type": "call"}, {"api_name": "janome.tokenfilter.ExtractAttributeFilter", "line_number": 27, "usage_type": "call"}, {"api_name": "sumy.parsers.plaintext.PlaintextParser.from_string", "line_number": 41, "usage_type": "call"}, {"api_name": "sumy.parsers.plaintext.PlaintextParser", "line_number": 41, "usage_type": "name"}, {"api_name": "sumy.nlp.tokenizers.Tokenizer", "line_number": 41, "usage_type": "call"}, {"api_name": "sumy.summarizers.lex_rank.LexRankSummarizer", "line_number": 44, "usage_type": "call"}]} +{"seq_id": "70671870145", "text": "# -*- coding: utf-8 -*-\n# 采集保监局行政处罚信息\nimport re\nimport sys\nimport scrapy\nimport time\n\nfrom scrapy_migrate_project.items import Crawler016Item\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Tag\nreload(sys)\nsys.setdefaultencoding('utf8')\n\n\nclass BjjXingzhengSpider(scrapy.Spider):\n name = 'crawler016_2'\n allowed_domains = ['circ.gov.cn']\n start_urls = ['http://www.circ.gov.cn/web/site0/tab5241/module14458/page1.htm']\n\n # 列表页\n def parse(self, response):\n li_list = response.xpath('//td[@class=\"hui14\"]')\n for li in li_list:\n item = Crawler016Item()\n title = li.xpath('./span/a/text()').extract_first()\n # 根据title提取处罚书文号,文号必须包括‘保监罚’字眼\n if (title.find('处罚决定书') != -1 and title.find('保监罚') != -1):\n case_no = title[title.find('处罚决定书'):len(title)].replace('处罚决定书', '').replace('—', '').strip()\n else:\n case_no = title\n if (case_no != None and len(case_no) > 200):\n case_no = case_no[0:200]\n item['case_no'] = case_no\n item['title'] = title\n href = li.xpath('./span/a/@href').extract_first()\n href = 'http://www.circ.gov.cn'+ href\n pub_date =li.xpath('./following-sibling::*[1]/text()').extract_first()\n pub_date ='20' + pub_date.replace(')', '').replace('(', '')\n item['pub_date'] = pub_date\n yield scrapy.Request(href,\n callback=self.parse_detail,\n meta={'item':item})\n\n # 翻页\n ret = response.xpath('//td[@class=\"Normal\"]/text()').extract()\n cur_page = response.xpath('//td[@class=\"Normal\"]/font/text()').extract_first()\n total_pages = ret[-1].split('/')[-1]\n if int(cur_page) < int(total_pages):\n next_page = int(cur_page)+1\n next_url = 'http://www.circ.gov.cn/web/site0/tab5241/module14458/page'+str(next_page)+'.htm'\n yield scrapy.Request(next_url,\n callback=self.parse)\n #详情页\n def parse_detail(self,response):\n item = response.meta['item']\n title= item['title']\n data = response.text\n url = response.url\n item['source_url'] = url\n item['spider_name'] = self.name\n item['source_page'] = data\n soup = BeautifulSoup(data, \"lxml\")\n\n # 提取数据\n item['create_date'] = time.strftime('%Y-%m-%d', time.localtime())\n\n # 提取处罚内容\n node = soup.find(name='span', class_='xilanwb')\n item['content'] = node.text.encode('utf-8').strip()\n\n # 提取公司名称\n subnodes = node.children\n\n ent_name = ''\n\n for subnode in (subnodes):\n if isinstance(subnode, Tag): # 提取每行信息\n node_text = subnode.text.encode('utf-8').replace(' ', '').strip()\n if (node_text.startswith('当事人:') or node_text.startswith('当事人名称:') or node_text.startswith(\n '受处罚机构:') or node_text.startswith('受处罚机构名称:') or node_text.startswith(\n '受处罚单位:') or node_text.startswith('受处罚单位名称:') or node_text.startswith(\n '受处罚人:') or node_text.startswith('受罚人:') or node_text.startswith(\n '受处罚人名称:') or node_text.startswith('名称:') or node_text.startswith(\n '机构名称:') or node_text.startswith('被处罚机构名称:')):\n\n if (node_text.find('以下简称') != -1 and node_text.find('公司') != -1): # 先确定是否是企业信息\n ent_name = self.get_ent_content(node_text[node_text.find(':'):len(node_text)].replace(':', ''))\n # 去掉(简称)字眼\n regex = re.compile(r\"((.*))\")\n results = regex.findall(ent_name)\n if (results != None and len(results) > 0):\n result = '(' + results[0] + ')'\n ent_name = ent_name.replace(result, '')\n elif node_text.find('公司') != -1: # 先确定是否是企业信息\n ent_name = self.get_ent_content(node_text[node_text.find(':'):len(node_text)].replace(':', ''))\n else:\n pass\n ent_name = ent_name.strip()\n item['ent_name'] = ent_name\n item['org_level'] = '2'\n yield item\n\n def get_ent_content(self,content): # 截取字符串,如果发现,。需要进行截取\n result = None\n if (content != None):\n if content.find('。') != -1:\n result = content[0:content.find('。')]\n elif content.find(',') != -1:\n result = content[0:content.find(',')]\n else:\n result = content\n return result\n\n\n", "repo_name": "tdihsuh/dt-1.4-bj", "sub_path": "scrapy_migrate_project/spiders/tag_ci/crawler016_2.py", "file_name": "crawler016_2.py", "file_ext": "py", "file_size_in_byte": 5160, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sys.setdefaultencoding", "line_number": 12, "usage_type": "call"}, {"api_name": "scrapy.Spider", "line_number": 15, "usage_type": "attribute"}, {"api_name": "scrapy_migrate_project.items.Crawler016Item", "line_number": 24, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 40, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 51, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 62, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 65, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 65, "usage_type": "call"}, {"api_name": "bs4.element.Tag", "line_number": 77, "usage_type": "argument"}, {"api_name": "re.compile", "line_number": 89, "usage_type": "call"}]} +{"seq_id": "40234338525", "text": "import seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport json\nimport os\nimport os.path as osp\nimport numpy as np\nimport pandas as pd\nfrom matplotlib.ticker import FormatStrFormatter\n\nimport pickle\nfrom gibson2.utils.utils import parse_config\n\ndef load_data(data_base_path, trials, column_name):\n\tcurves = []\n\tif isinstance(trials, list):\n\t\tfor i in range(len(trials)):\n\t\t\tcurves.append(load_seed_data(os.path.join(data_base_path[i], trials[i]), column_name=column_name))\n\telse:\n\t\tcurves.append(load_seed_data(os.path.join(data_base_path, trials), column_name=column_name))\n\t# n*3\n\tresults = pd.concat(curves, axis=1)\n\t#index = 4000 * results.shape[0]\n\n\t# change index from iteration to timesteps\n\t#old_index = results.index\n\t#new_index = old_index * 4000\n\t#print(new_index)\n\t#results = results.reindex(new_index)\n\t#print(results)\n\n\treturn results\n\ndef load_seed_data(data_path, column_name):\n\tdf = pd.read_csv(os.path.join(data_path, \"progress.csv\"), usecols=[column_name])\n\t#df = sns.load_dataset(os.path.join(data_path, \"progress.csv\"))\n\t#df = np.array(df)\n\n\t#print(type(df))\n\n\treturn df\n\t\n\ndef plot_data(plot_save_path, data_base_path, curve_groups, column_name, end_iteration, plot_name):\n\t# set seaborn\n\tsns.set(style=\"darkgrid\")\n\tfig = plt.figure()\n\n\t# Load the data\n\tcolors = ['r', 'b', 'm', 'g']\n\t#sns.set_palette(\"tab10\")\n\tfor i in range(len(curve_groups)):\n\t\tresults = load_data(data_base_path, curve_groups[i], column_name) \n\t\t# Plot each line\n\t\t# (may want to automate this part e.g. with a loop).\n\t\tsns_plot = sns.lineplot(data=results, legend=False, palette=[colors[i]], ci=\"sd\")\n\n\n\n\t# change index from iteration to timesteps\n\tstart_iteration = 0\n\t#end = len(results) + 1\n\tx_ticks = list(np.arange(start_iteration, end_iteration+1, 25))\n\t#print(x_ticks)\n\ttimesteps_per_iteration = 4000\n\tmax_timestep = end_iteration * timesteps_per_iteration\n\n\t#plt.ticklabel_format(style='sci', axis='x')\n\t\n\tsns_plot.xaxis.set_ticks(x_ticks)\n\t#sns_plot.xaxis.set_ticklabels([str(tick*timesteps_per_iteration) for tick in x_ticks])\n\t#plt.ticklabel_format(axis='x', style='sci')\n\t#sns_plot.xaxis.set_major_formatter(FormatStrFormatter('%.2E'))\n\t#sns_plot.xaxis.set_ticklabels([\"%.2e\"%(tick*timesteps_per_iteration) for tick in x_ticks])\n\tsns_plot.xaxis.set_ticklabels([tick*timesteps_per_iteration/1000000.0 for tick in x_ticks])\n\n\n\t# set x range\n\tplt.xlim((0,end_iteration))\n\t#plt.xtickformat('%.1f')\n\t\n\t# Our y−axis is ”success rate” here.\n\tif '/' not in column_name:\n\t\ty_axis_name = column_name\n\telse:\n\t\tstart_index = column_name.find('/')+1\n\t\ty_axis_name = column_name[start_index:]\t\n\n\ty_axis_name = y_axis_name.replace('_', \" \")\n\ty_axis_name = y_axis_name.replace('mean', \"\")\n\n\tplt.ylabel(y_axis_name, fontsize=10)\n\t# Our x−axis is iteration number.\n\tplt.xlabel(\"million steps\", fontsize=10)\n\t\n\t#plt.xlabel(\"Iterations\", fontsize=10)\n\t# Our task is called ”Awesome Robot Performance”\n\t#plt.title(\"Push One Box\", fontsize=12)\n\t# Legend\n\t#plt.legend(loc='lower right')\n\t# Show the plot on the screen\n\tplt.show()\n\n\t# save figure\n\tfig = sns_plot.get_figure()\n\tfig.savefig(os.path.join(plot_save_path, plot_name))\n\n# def plot_2box(ray_path, plot_save_path, average_seeds=True):\n# \ttwo_box_data_base_path = [os.path.join(ray_path, \"PPO_two_box_one_circle_success1\"), os.path.join(ray_path, \"PPO_two_box_one_circle_success2\"), ]\n# \tno_swap_no_energy_trials=['PPO_OpenRoomEnvironmentRLLIB_6a57c_00000_0_2021-05-10_12-10-42', 'PPO_OpenRoomEnvironmentRLLIB_25a19_00000_0_2021-05-11_09-58-45']\n# \tswap_no_energy_trials=['PPO_OpenRoomEnvironmentRLLIB_9b13f_00000_0_2021-05-10_14-13-45', 'PPO_OpenRoomEnvironmentRLLIB_58e11_00000_0_2021-05-11_10-07-20']\n# \tno_swap_with_energy_trials=['PPO_OpenRoomEnvironmentRLLIB_ee9ba_00000_0_2021-05-10_14-01-47', 'PPO_OpenRoomEnvironmentRLLIB_47df1_00000_0_2021-05-11_11-04-08']\n# \tswap_with_energy_trials=['PPO_OpenRoomEnvironmentRLLIB_12a58_00000_0_2021-05-10_17-23-13', 'PPO_OpenRoomEnvironmentRLLIB_d0a78_00000_0_2021-05-11_11-29-26']\n\n# \tif not os.path.exists(plot_save_path):\n# \t\tos.makedirs(plot_save_path)\n\t\n# \tif average_seeds:\n# \t\tdata = []\n# \t\tdata.append(no_swap_no_energy_trials)\n# \t\tdata.append(swap_no_energy_trials)\n# \t\tdata.append(no_swap_with_energy_trials)\n# \t\tdata.append(swap_with_energy_trials)\n\t\t\n# \t\t#plot_data(plot_save_path, two_box_data_base_path, curve_groups=data, column_name='custom_metrics/episode_pushing_energy_mean', end_iteration=100, plot_name=\"train_curve_2box_pushing_energy.png\")\n# \t\tplot_data(plot_save_path, two_box_data_base_path, curve_groups=data, column_name='custom_metrics/succeed_episode_pushing_energy_mean', end_iteration=100, plot_name=\"train_curve_2box_pushing_energy.png\")\n# \t\tplot_data(plot_save_path, two_box_data_base_path, curve_groups=data, column_name='custom_metrics/success_rate_mean', end_iteration=100, plot_name=\"train_curve_2box_success_rate.png\")\n# \telse:\n# \t\tseed_num = len(no_swap_no_energy_trials)\n# \t\tfor i in range(seed_num):\n# \t\t\tdata = []\n# \t\t\tdata.append(no_swap_no_energy_trials[i])\n# \t\t\tdata.append(swap_no_energy_trials[i])\n# \t\t\tdata.append(no_swap_with_energy_trials[i])\n# \t\t\tdata.append(swap_with_energy_trials[i])\n\t\t\t\n# \t\t\tplot_data(plot_save_path, two_box_data_base_path[i], curve_groups=data, column_name='custom_metrics/succeed_episode_pushing_energy_mean', end_iteration=100, plot_name=\"train_curve_2box_pushing_energy_%d.png\"%(i+1))\n# \t\t\tplot_data(plot_save_path, two_box_data_base_path[i], curve_groups=data, column_name='custom_metrics/success_rate_mean', end_iteration=100, plot_name=\"train_curve_2box_success_rate_%d.png\"%(i+1))\n\ndef plot_2band(two_band_data_base_path, plot_save_path, average_seeds=True):\n\t#two_band_data_base_path = [os.path.join(ray_path, \"PPO\"), os.path.join(ray_path, \"PPO\"), os.path.join(ray_path, \"PPO\")]\n\ttwo_band_data_base_path = [two_band_data_base_path, two_band_data_base_path, two_band_data_base_path]\n\ttwo_band_no_energy_trials=[\"PPO_OpenRoomEnvironmentRLLIB_95cd0_00000_0_2021-05-26_18-05-10\", \"PPO_OpenRoomEnvironmentRLLIB_3fbfc_00000_0_2021-05-27_10-16-18\", \"PPO_OpenRoomEnvironmentRLLIB_f155f_00000_0_2021-05-27_17-59-23\"]\n\ttwo_band_with_energy_trials=[\"PPO_OpenRoomEnvironmentRLLIB_b2d9d_00000_0_2021-05-26_18-05-59\", \"PPO_OpenRoomEnvironmentRLLIB_5f748_00000_0_2021-05-27_10-17-11\", \"PPO_OpenRoomEnvironmentRLLIB_12158_00000_0_2021-05-27_20-02-00\"]\n\n\tif not os.path.exists(plot_save_path):\n\t\tos.makedirs(plot_save_path)\n\t\t\n\tif average_seeds:\n\t\tdata = []\n\t\tdata.append(two_band_no_energy_trials)\n\t\tdata.append(two_band_with_energy_trials)\n\t\t\n\t\tplot_data(plot_save_path, two_band_data_base_path, curve_groups=data, column_name='custom_metrics/succeed_episode_pushing_energy_mean', end_iteration=300, plot_name=\"train_curve_2band_pushing_energy.png\")\n\t\tplot_data(plot_save_path, two_band_data_base_path, curve_groups=data, column_name='custom_metrics/success_rate_mean', end_iteration=250, plot_name=\"train_curve_2band_success_rate.png\")\n\telse:\n\t\tseed_num = len(two_band_no_energy_trials)\n\t\tfor i in range(seed_num):\n\t\t\tdata = []\n\t\t\tdata.append(two_band_no_energy_trials[i])\n\t\t\tdata.append(two_band_with_energy_trials[i])\n\t\t\t\n\t\t\tplot_data(plot_save_path, two_band_data_base_path[i], curve_groups=data, column_name='custom_metrics/succeed_episode_pushing_energy_mean', end_iteration=300, plot_name=\"train_curve_2band_pushing_energy_%d.png\"%(i+1))\n\t\t\tplot_data(plot_save_path, two_band_data_base_path[i], curve_groups=data, column_name='custom_metrics/success_rate_mean', end_iteration=250, plot_name=\"train_curve_2band_success_rate_%d.png\"%(i+1))\n\ndef sort_trials(base_path):\n\ttrials = [None for i in range(4)]\n\tconfig_num = None\n\n\tfor fname in os.listdir(base_path):\n\t\tfpath = os.path.join(base_path, fname)\n\t\t# folder\n\t\tif os.path.isdir(fpath):\n\t\t\t# get config file name\n\t\t\tparam_file = os.path.join(fpath, 'params.pkl')\n\t\t\twith open(param_file, 'rb') as f:\n\t\t\t\tparams = pickle.load(f)\n\t\t\t\tconfig_filename = params['env_config']['config_file']\n\t\t\tconfig_file = os.path.join(fpath, config_filename)\n\t\t\t# get config file\n\t\t\tconfig = parse_config(config_file)\n\t\t\t# check config_num\n\t\t\tif config_num == None:\n\t\t\t\tconfig_num == config['config_index']\n\t\t\telse:\n\t\t\t\tassert config_num == config['config_index'], f\"[sort_trials]Error: config_index of '{fname}' doesn't match: {config['config_index']} v.s. {config_num}!\"\n\t\t\t# sort\n\t\t\tidx = 0\n\t\t\tif config['swap']: idx += 1\n\t\t\tif config['use_energy_cost']: idx += 2\n\t\t\ttrials[idx] = fname\n\n\t# check\n\tassert not (None in trials), f\"[sort_trials]Error: incomplete set of trials, trials got: {trials}!\"\n\n\treturn trials\n\ndef plot_2box(ray_path, plot_save_path, average_seeds=True):\n\ttwo_box_data_base_path = [os.path.join(ray_path, \"config0\"), os.path.join(ray_path, \"config2\") , os.path.join(ray_path, \"config3\"), os.path.join(ray_path, \"config4\"), os.path.join(ray_path, \"config7\")]\n\n\t#print(two_box_data_base_path)\n\t# exit()\n\t# no_swap_no_energy_trials = ['PPO_OpenRoomEnvironmentRLLIB_d2b62_00000_0_2021-05-25_05-43-36', 'PPO_OpenRoomEnvironmentRLLIB_291d0_00000_0_2021-05-16_20-58-38', 'PPO_OpenRoomEnvironmentRLLIB_ae0e5_00000_0_2021-05-17_00-29-57', 'PPO_OpenRoomEnvironmentRLLIB_1d57e_00000_0_2021-05-25_11-14-58', 'PPO_OpenRoomEnvironmentRLLIB_23fc6_00000_0_2021-05-16_21-34-17']\n\t# swap_no_energy_trials = ['PPO_OpenRoomEnvironmentRLLIB_051a6_00000_0_2021-05-25_05-45-01', 'PPO_OpenRoomEnvironmentRLLIB_93aa1_00000_0_2021-05-16_21-01-37', 'PPO_OpenRoomEnvironmentRLLIB_487a3_00000_0_2021-05-17_00-41-25', 'PPO_OpenRoomEnvironmentRLLIB_caf90_00000_0_2021-05-25_11-12-40', 'PPO_OpenRoomEnvironmentRLLIB_eb3f6_00000_0_2021-05-16_22-01-20']\n\t# no_swap_with_energy_trials = ['PPO_OpenRoomEnvironmentRLLIB_7fbae_00000_0_2021-05-25_05-05-29', 'PPO_OpenRoomEnvironmentRLLIB_79c20_00000_0_2021-05-25_02-27-50', 'PPO_OpenRoomEnvironmentRLLIB_2d7e7_00000_0_2021-05-25_04-05-55', 'PPO_OpenRoomEnvironmentRLLIB_a4fff_00000_0_2021-05-25_14-10-34', 'PPO_OpenRoomEnvironmentRLLIB_041bf_00000_0_2021-05-25_03-14-40']\n\t# swap_with_energy_trials = ['PPO_OpenRoomEnvironmentRLLIB_9b768_00000_0_2021-05-25_05-06-16', 'PPO_OpenRoomEnvironmentRLLIB_6aa9b_00000_0_2021-05-25_01-58-47', 'PPO_OpenRoomEnvironmentRLLIB_4a0c3_00000_0_2021-05-25_04-06-43', 'PPO_OpenRoomEnvironmentRLLIB_d8443_00000_0_2021-05-25_14-12-00', 'PPO_OpenRoomEnvironmentRLLIB_e3f23_00000_0_2021-05-25_02-59-27']\n\n\t# sort trials\n\tno_swap_no_energy_trials, swap_no_energy_trials, no_swap_with_energy_trials, swap_with_energy_trials = list(), list(), list(), list()\n\tfor base_path in two_box_data_base_path:\n\t\ttrials = sort_trials(base_path)\n\t\tno_swap_no_energy_trials.append( trials[0])\n\t\tswap_no_energy_trials.append( trials[1])\n\t\tno_swap_with_energy_trials.append( trials[2])\n\t\tswap_with_energy_trials.append( trials[3])\n\t\n\tif not os.path.exists(plot_save_path):\n\t\tos.makedirs(plot_save_path)\n\n\ttwo_box_data_base_path += two_box_data_base_path\n\tno_energy_trials = no_swap_no_energy_trials+swap_no_energy_trials\n\twith_energy_trials = no_swap_with_energy_trials+swap_with_energy_trials\n\n\t#print(no_energy_trials)\n\t#print(with_energy_trials)\n\n\tif average_seeds:\n\t\tdata = []\n\t\t# data.append(no_swap_no_energy_trials)\n\t\t# data.append(swap_no_energy_trials)\n\t\t# data.append(no_swap_with_energy_trials)\n\t\t# data.append(swap_with_energy_trials)\n\t\tdata.append(no_energy_trials)\n\t\tdata.append(with_energy_trials)\n\t\t\n\t\t#plot_data(plot_save_path, two_box_data_base_path, curve_groups=data, column_name='custom_metrics/episode_pushing_energy_mean', end_iteration=100, plot_name=\"train_curve_2box_pushing_energy.png\")\n\t\tplot_data(plot_save_path, two_box_data_base_path, curve_groups=data, column_name='custom_metrics/succeed_episode_pushing_energy_mean', end_iteration=100, plot_name=\"train_curve_2box_pushing_energy.png\")\n\t\tplot_data(plot_save_path, two_box_data_base_path, curve_groups=data, column_name='custom_metrics/success_rate_mean', end_iteration=100, plot_name=\"train_curve_2box_success_rate.png\")\n\telse:\n\t\t# seed_num = len(no_swap_no_energy_trials)\n\t\tseed_num = len(no_energy_trials)\n\t\tfor i in range(seed_num):\n\t\t\tdata = []\n\t\t\t# data.append(no_swap_no_energy_trials[i])\n\t\t\t# data.append(swap_no_energy_trials[i])\n\t\t\t# data.append(no_swap_with_energy_trials[i])\n\t\t\t# data.append(swap_with_energy_trials[i])\n\t\t\tdata.append(no_energy_trials[i])\n\t\t\tdata.append(with_energy_trials[i])\n\t\t\t\n\t\t\tplot_data(plot_save_path, two_box_data_base_path[i], curve_groups=data, column_name='custom_metrics/succeed_episode_pushing_energy_mean', end_iteration=100, plot_name=\"train_curve_2box_pushing_energy_%d.png\"%(i+1))\n\t\t\tplot_data(plot_save_path, two_box_data_base_path[i], curve_groups=data, column_name='custom_metrics/success_rate_mean', end_iteration=100, plot_name=\"train_curve_2box_success_rate_%d.png\"%(i+1))\n\nif __name__ == \"__main__\":\n\tray_path = \"/home/meng/ray_results\"\n\tplot_save_path = os.path.join(ray_path, \"plots\")\n\n\t# plot 2 band results\n\tplot_2band(two_band_data_base_path=os.path.join(ray_path, \"two-band-paper\"), plot_save_path=os.path.join(plot_save_path, \"2band\"), average_seeds=False)\n\tprint(\"2 band separate plot Done.\")\n\tplot_2band(two_band_data_base_path=os.path.join(ray_path, \"two-band-paper\"), plot_save_path=os.path.join(plot_save_path, \"2band\"), average_seeds=True)\n\tprint(\"2 band overall plot Done.\")\n\n\t# plot 2 box results\n\tplot_2box(ray_path=os.path.join(ray_path, \"two-box-paper\"), plot_save_path=os.path.join(plot_save_path, \"2box\"), average_seeds=False)\n\tprint(\"2 box separate plot Done.\")\n\tplot_2box(ray_path=os.path.join(ray_path, \"two-box-paper\"), plot_save_path=os.path.join(plot_save_path, \"2box\"), average_seeds=True)\n\tprint(\"2 box overall plot Done.\")\n", "repo_name": "mengsong16/openvrooms", "sub_path": "rllib_learning/plot_2band_2box.py", "file_name": "plot_2band_2box.py", "file_ext": "py", "file_size_in_byte": 13580, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.path.join", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path", "line_number": 18, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "pandas.concat", "line_number": 22, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "seaborn.set", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "seaborn.lineplot", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 92, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 92, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 94, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 94, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 102, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 102, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path", "line_number": 106, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 146, "usage_type": "call"}, {"api_name": "os.path", "line_number": 146, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 147, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 170, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 171, "usage_type": "call"}, {"api_name": "os.path", "line_number": 171, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 173, "usage_type": "call"}, {"api_name": "os.path", "line_number": 173, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 175, "usage_type": "call"}, {"api_name": "os.path", "line_number": 175, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 177, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 179, "usage_type": "call"}, {"api_name": "os.path", "line_number": 179, "usage_type": "attribute"}, {"api_name": "gibson2.utils.utils.parse_config", "line_number": 181, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 199, "usage_type": "call"}, {"api_name": "os.path", "line_number": 199, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 217, "usage_type": "call"}, {"api_name": "os.path", "line_number": 217, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 218, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 256, "usage_type": "call"}, {"api_name": "os.path", "line_number": 256, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 259, "usage_type": "call"}, {"api_name": "os.path", "line_number": 259, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 261, "usage_type": "call"}, {"api_name": "os.path", "line_number": 261, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 265, "usage_type": "call"}, {"api_name": "os.path", "line_number": 265, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 267, "usage_type": "call"}, {"api_name": "os.path", "line_number": 267, "usage_type": "attribute"}]} +{"seq_id": "4145274323", "text": "from http import client\nimport xlwings as xw\nimport pandas as pd\nimport os\n\n\ndef save_mapping_dictionary(dict_file, mapping_dictionary, out_path, header=False):\n wbapp = xw.App(visible=False)\n wb = wbapp.books.open(dict_file)\n ws = wb.sheets[\"Sheet1\"]\n ws[\"A1\"].options(\n pd.DataFrame, header=header, index=False, expand=\"table\"\n ).value = mapping_dictionary\n wb.save(out_path)\n wb.close()\n wbapp.quit()\n\n\ndef save_based_on_template(template_path, df, out_path, header=False):\n wbapp = xw.App(visible=False)\n wb = wbapp.books.open(template_path)\n ws = wb.sheets[\"Sheet1\"]\n ws[\"A1\"].options(\n pd.DataFrame, header=header, index=False, expand=\"table\"\n ).value = df\n wb.save(out_path)\n wb.close()\n wbapp.quit()\n\n\ndef save_new_summary(template_path, summaries, out_path, sheet_names):\n out = os.path.join(out_path, \"New summary.xlsx\")\n wbapp = xw.App(visible=False)\n wb = wbapp.books.open(template_path)\n\n ws = wb.sheets[\"Sheet1\"]\n for _ in range(len(summaries) - 1):\n ws.api.Copy(Before=ws.api)\n\n for ws, summary, sheet_name in zip(wb.sheets, summaries, sheet_names):\n ws.name = sheet_name[-31:]\n ws[\"A1\"].options(\n pd.DataFrame, header=False, index=False, expand=\"table\"\n ).value = summary\n\n # client_data_upper_left_corner_row, 120 is the length of the footer\n ul_row = len(summary) - 120\n\n col_name_dict = {\n \"AA\": \"Amortization\",\n \"AB\": \"Depreciation\",\n \"AC\": \"Accrual to Cash\",\n \"AD\": \"Nondeductible\",\n \"AE\": \"Book Income (Loss)\",\n \"K\": \"Ownership Percentages\",\n \"L\": \"Beginning Tax Capital\",\n \"M\": \"Contribution\",\n \"N\": \"Distribution\",\n \"O\": \"Tax Capital Subtotal\",\n \"P\": \"Taxable Income (Loss)\",\n \"Q\": \"Tier 1\",\n \"R\": \"Tier 2\",\n \"S\": \"Special Allocated Taxable Income (Loss)\",\n \"T\": \"Ending Tax Basis\",\n \"U\": \"Qualified Nonrecourse Debt\",\n \"V\": \"Recourse Debt\",\n \"W\": \"CY Allocation Percentages\",\n \"X\": \"Ordinary Income (Loss)\",\n \"Y\": \"Interest Income\",\n \"Z\": \"Charitable Contributions\",\n }\n\n for k, v in col_name_dict.items():\n ws[k + str(ul_row)].value = v\n\n sum_upper_cells_let = [\"K\", \"L\", \"M\", \"N\", \"O\", \"Q\", \"S\", \"T\", \"V\", \"W\"]\n sum_upper_cells = {\n let + str(ul_row + 3): f\"=SUM({let}{ul_row+1}:{let}{ul_row+2})\"\n for let in sum_upper_cells_let\n }\n for k, v in sum_upper_cells.items():\n ws[k].value = v\n\n ws[\"R\" + str(ul_row + 3)].value = f\"=P{ul_row+3}-Q{ul_row+3}\"\n ws[\"X\" + str(ul_row + 3)].value = f\"=P{ul_row+3}-Y{ul_row+3}-Z{ul_row+3}\"\n\n ws[\"O\" + str(ul_row + 1)].value = f\"=L{ul_row+1}+M{ul_row+1}+N{ul_row+1}\"\n ws[\"O\" + str(ul_row + 2)].value = f\"=L{ul_row+2}+M{ul_row+2}+N{ul_row+2}\"\n\n ws[\"P\" + str(ul_row + 1)].value = f\"=$P${ul_row+3}*K{ul_row+1}\"\n ws[\"P\" + str(ul_row + 2)].value = f\"=$P${ul_row+3}*K{ul_row+2}\"\n\n ws[\"Q\" + str(ul_row + 1)].value = f\"=P{ul_row+1}\"\n ws[\"Q\" + str(ul_row + 2)].value = f\"=P{ul_row+2}\"\n\n ws[\"T\" + str(ul_row + 1)].value = f\"=O{ul_row+1}+S{ul_row+1}+AD{ul_row+1}\"\n ws[\"T\" + str(ul_row + 2)].value = f\"=O{ul_row+2}+S{ul_row+2}+AD{ul_row+2}\"\n\n ws[\"U\" + str(ul_row + 1)].value = f\"=P{ul_row+1}+T{ul_row+1}+AE{ul_row+1}\"\n ws[\"U\" + str(ul_row + 2)].value = f\"=P{ul_row+2}+T{ul_row+2}+AE{ul_row+2}\"\n\n ws[\"W\" + str(ul_row + 1)].value = f\"=S{ul_row+1}/$S${ul_row+3}\"\n ws[\"W\" + str(ul_row + 2)].value = f\"=S{ul_row+2}/$S${ul_row+3}\"\n\n mul_list = [\"X\", \"Y\", \"Z\", \"AA\", \"AB\", \"AC\", \"AD\", \"AE\"]\n for char in mul_list:\n ws[char + str(ul_row + 1)].value = f\"=${char}${ul_row+3}*W{ul_row+1}\"\n ws[char + str(ul_row + 2)].value = f\"=${char}${ul_row+3}*W{ul_row+2}\"\n\n wb.save(out)\n wb.close()\n wbapp.quit()\n\n\n\"\"\"\n\n\ndef save_reviewers_aid(reviewers_aid, out_path):\n sf = StyleFrame(\n reviewers_aid,\n Styler(\n border_type=None,\n fill_pattern_type=None,\n font=utils.fonts.calibri,\n font_size=11,\n ),\n )\n sf.set_column_width_dict({0: 28, 1: 31, 2: 11, 3: 19, 4: 50, 5: 15})\n ew = StyleFrame.ExcelWriter(out_path)\n sf.to_excel(ew, header=False)\n ew.save()\n ew.close()\n\n\ndef save_summary(summary, out_path):\n sf = StyleFrame(\n summary,\n Styler(\n border_type=None,\n fill_pattern_type=None,\n font=utils.fonts.calibri,\n font_size=11,\n ),\n )\n cols = summary.columns\n sf.set_column_width_dict({cols[0]: 30, cols[1]: 30})\n ew = StyleFrame.ExcelWriter(out_path)\n sf.to_excel(ew)\n ew.save()\n ew.close()\n\ndef save_new_summary(summaries, out_path, sheet_names):\n ew = StyleFrame.ExcelWriter(os.path.join(out_path, \"New summary.xlsx\"))\n for summary, sheet_name in zip(summaries, sheet_names):\n sf = StyleFrame(\n summary,\n Styler(\n border_type=None,\n fill_pattern_type=None,\n font=utils.fonts.calibri,\n font_size=11,\n horizontal_alignment=\"left\",\n vertical_alignment=\"center\",\n ),\n )\n cols = summary.columns\n sf.set_column_width_dict(\n {\n cols[0]: 30,\n cols[1]: 50,\n cols[2]: 30,\n cols[3]: 30,\n cols[4]: 5,\n cols[5]: 30,\n cols[6]: 5,\n cols[7]: 30,\n cols[8]: 5,\n cols[9]: 45,\n }\n )\n sf.to_excel(ew, header=None, sheet_name=sheet_name[-31:])\n ew.save()\n ew.close()\n\"\"\"\n\n", "repo_name": "dldowning/Accounting-Installer", "sub_path": "src/savers.py", "file_name": "savers.py", "file_ext": "py", "file_size_in_byte": 5907, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "25", "api": [{"api_name": "xlwings.App", "line_number": 8, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 12, "usage_type": "attribute"}, {"api_name": "xlwings.App", "line_number": 20, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path", "line_number": 32, "usage_type": "attribute"}, {"api_name": "xlwings.App", "line_number": 33, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 43, "usage_type": "attribute"}]} +{"seq_id": "74340950769", "text": "# how amazon does it\ndef toMp4(incoming, outgoing): \n import boto3\n client = boto3.client('elastictranscoder') \n response = client.create_job(\n PipelineId='1453398326915-jvsbts',\n Input={\n 'Key': incoming\n },\n Output={\n 'Key': 'video/' + outgoing + '.mp4',\n 'ThumbnailPattern': 'thumb/' + outgoing + '-{count}',\n 'PresetId': '1351620000001-100070'\n }\n )\n return response", "repo_name": "kmcintyre/morningoogle.com", "sub_path": "etc/python/transcoder.py", "file_name": "transcoder.py", "file_ext": "py", "file_size_in_byte": 472, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "boto3.client", "line_number": 4, "usage_type": "call"}]} +{"seq_id": "15701799299", "text": "import emoji\n\n\ndef identify_special_texts(text):\n if text[:2] == '[[':\n type_of_text = text[2:]\n type_of_text = type_of_text.split(']]')[0]\n type_of_text = type_of_text.split(' ')[0]\n type_of_text = type_of_text.strip(',')\n\n return '[[' + type_of_text + ']]'\n else:\n return False\n\n\ndef identify_links(text):\n if text[:4] == 'http':\n return True\n else:\n return False\n\n\ndef identify_forwards(text):\n if text[:5] == '{{FWD':\n return True\n else:\n return False\n\n\ndef char_is_emoji(char):\n return char in emoji.UNICODE_EMOJI\n\n\ndef text_has_emoji(text):\n for character in text:\n if character in emoji.UNICODE_EMOJI:\n return True\n return False\n\n\ndef separate_emojis_at_the_end_of_tokens(text):\n final_text = ''\n\n if text_has_emoji(text):\n for char in text:\n if char_is_emoji(char):\n if len(final_text):\n if final_text[-1] != ' ':\n final_text += ' '\n final_text += char\n final_text += ' '\n else:\n final_text += char\n else:\n final_text = text\n\n return final_text\n\n\ndef separate_special_characters_at_the_end_of_tokens(text):\n special_characters = [',', '.']\n\n for special_character in special_characters:\n text = text.replace(special_character, '')\n\n text = ' '.join(text.split())\n\n return text\n\n\ndef convert_smileys_to_emojis(text):\n smileys = [':)', ':p', ':(']\n emojis = ['😀', '😟','😋']\n\n for smiley, emoji in zip(smileys, emojis):\n text = text.replace(smiley, emoji)\n\n return text\n", "repo_name": "gsravank/chat-messages", "sub_path": "chat_messages/text_utils.py", "file_name": "text_utils.py", "file_ext": "py", "file_size_in_byte": 1686, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "emoji.UNICODE_EMOJI", "line_number": 31, "usage_type": "attribute"}, {"api_name": "emoji.UNICODE_EMOJI", "line_number": 36, "usage_type": "attribute"}]} +{"seq_id": "33310399417", "text": "import argparse, os\nfrom PIL import Image\n\n# Convert all images to jpeg and try to fix error: Corrupt JPEG data bad Huffman code\n\nif __name__ == '__main__':\n\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-f\", \"--folder\", required=True, help=\"path to directory of images\")\n args, unknown = ap.parse_known_args()\n\n folder = args.folder\n if os.path.isabs(folder): directory = folder\n else: directory = os.path.sep.join([\"data\", args.folder])\n\n images = [\".jpg\", \".jpeg\", \".png\", \".bmp\", \".gif\", \".webp\", \".tiff\", \".jfif\"]\n\n converted = 0\n rewrite = 0\n\n for this in os.listdir(directory):\n\n extension = os.path.splitext(this)[1].lower()\n filePath = os.path.join(directory, this)\n noExtension = os.path.splitext(filePath)[0]\n\n if os.path.isfile(filePath) and extension in images:\n\n jpegPath = noExtension + \".jpg\"\n\n with Image.open(filePath) as im:\n im.convert('RGB').save(jpegPath)\n\n if extension == \".jpg\":\n rewrite += 1\n else:\n os.remove(filePath)\n converted += 1\n\n print(f\"Converted {converted} | Rewrite {rewrite}\")\n", "repo_name": "tiagordc/bing-image-scrapper", "sub_path": "fix.py", "file_name": "fix.py", "file_ext": "py", "file_size_in_byte": 1185, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path.isabs", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "os.path.sep.join", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path", "line_number": 27, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 31, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 31, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 37, "usage_type": "call"}]} +{"seq_id": "28131716419", "text": "import numpy as np\nfrom utils.utils import read_points\nfrom utils.camera_calibration import Image\n\nlpath = 'inputs/left.jpg'\nrpath = 'inputs/right.jpg'\n\nlpoints = read_points('outputs/all_points_left.txt')\nrpoints = read_points('outputs/all_points_right.txt')\nobj_points = read_points('inputs/calibration_points3.txt')\n\n# Return two image objects with calculated camera parameters and corresponding points\nlimage = Image(lpath, lpoints, obj_points)\nrimage = Image(rpath, rpoints, obj_points)\n\nm1l = limage.M_calc[0]\nm2l = limage.M_calc[1]\nm3l = limage.M_calc[2]\n\nm1r = rimage.M_calc[0]\nm2r = rimage.M_calc[1]\nm3r = rimage.M_calc[2]\n\n# Calculate 3D homogeneous coordinates (1x4)\nX_h = []\nfor (lpoints, rpoints) in zip(limage.corresp_points, rimage.corresp_points):\n xl = lpoints[0]\n yl = lpoints[1]\n xr = rpoints[0]\n yr = rpoints[1]\n\n P = np.zeros((4, 4))\n P[0, :] = xl*m3l - m1l\n P[1, :] = yl*m3l - m2l\n P[2, :] = xr*m3r - m1r\n P[3, :] = yr*m3r - m2r\n\n _, _, vh = np.linalg.svd(P)\n solution = vh[-1, :]\n X_h.append(solution)\n\nX_h = np.asarray(X_h)\nestimated_points = X_h[:, :3]/np.expand_dims(X_h[:, 3], axis=1)\n\n# Mean squared error for 12 given points\nmse = ((obj_points - estimated_points[:12, :])**2).mean()\nprint('MSE:', round(mse, 3))\n\n\nif 0 < mse < 1:\n with open('outputs/estimated_points3D.txt', 'w') as f:\n for i in range(estimated_points.shape[0]):\n line = list(map(int, estimated_points[i, :]))\n f.write(str(line).replace(',', ' ').strip('[]')+'\\n')\nelse:\n print('MSE is bigger than 1. Solution is incorrect!')\n\n\n", "repo_name": "kSahatova/ComputerVision_VUB", "sub_path": "stereo-vision/stereo-vision/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1599, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "utils.utils.read_points", "line_number": 8, "usage_type": "call"}, {"api_name": "utils.utils.read_points", "line_number": 9, "usage_type": "call"}, {"api_name": "utils.utils.read_points", "line_number": 10, "usage_type": "call"}, {"api_name": "utils.camera_calibration.Image", "line_number": 13, "usage_type": "call"}, {"api_name": "utils.camera_calibration.Image", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.linalg.svd", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 38, "usage_type": "attribute"}, {"api_name": "numpy.asarray", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 43, "usage_type": "call"}]} +{"seq_id": "32346155533", "text": "\"\"\"\r\n\r\n main.m\r\n\r\n Description:\r\n This program is used to optimize the disk in aero engine.\r\n\r\n\r\n All the codes had been written by Zhizhen Dong in 2022\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport math\r\nimport pandas as pd\r\nfrom functools import reduce\r\nfrom numpy import exp, abs, angle\r\nfrom scipy import interpolate\r\nimport pylab as pl\r\n\r\nmn = 4 # 网格的中间节点数(输入!!!)\r\nbn = 1 # 叶片网格层数\r\nSize = 50 # 粒子组数\r\nG = 600 # 最大迭代次数\r\n\r\n# 导入数据\r\n# couplednodes = pd.read_table(r\"couplednodes.txt\", sep=\",\", header=None) # 按行读文本\r\ncouplednodes = np.loadtxt(\"couplednodes.txt\", dtype=int, delimiter=' ')\r\nleft_1 = np.array([[2956, 2947, 2948]])\r\nleft_2 = np.array([couplednodes[:, 0]])\r\nleft_3 = np.array([[2611, 2612, 2623, 2624]])\r\nleft = np.vstack((left_1.T, left_2.T, left_3.T))\r\n\r\nright_1 = np.array([[2730, 2734, 2739]])\r\nright_2 = np.array([couplednodes[:, mn + 1]])\r\nright_3 = np.array([[2669, 2672, 2681, 2684]])\r\nright = np.vstack((right_1.T, right_2.T, right_3.T))\r\n\r\n\r\n# 计算chebyshev点\r\ndef chebyshev(a_t, b_t, n_t): # k坐标变换,多项式阶数\r\n k1 = (a_t + b_t) / 2\r\n k2 = (-a_t + b_t) / 2\r\n c = np.zeros(n_t)\r\n\r\n for i in range(n_t):\r\n c_temp = (k1 + k2 * math.cos((2 * i + 1) * math.pi / (2 * (n_t + 1))))\r\n c[i] = float('%.2f' % c_temp)\r\n\r\n return c\r\n\r\n\r\na = 32.5 # 范围\r\nb1 = 95\r\nb2 = 98.8\r\nn = 8 # 阶数-1\r\n\r\nleft_cheby_r = chebyshev(a, b1, n)\r\nright_cheby_r = chebyshev(a, b2, n)\r\n\r\n''' 导入全部节点信息(编号、坐标)极坐标换算 '''\r\nnodeini = pd.read_excel(r\"nodedata.xlsx\", sheet_name='datapaper', header=None)\r\nnodeinitial = np.array(nodeini)\r\nnn = np.array([nodeinitial[:, 0]]).astype(int)\r\nxini = np.array([nodeinitial[:, 1]])\r\nyini = np.array([nodeinitial[:, 2]])\r\nzini = np.array([nodeinitial[:, 3]])\r\n\r\n\r\ndef cart2pol(x_t, y_t, z_t=None):\r\n rho_t = np.sqrt(x_t ** 2 + y_t ** 2)\r\n phi_t = np.arctan2(y_t, x_t)\r\n if z_t is None:\r\n return (phi_t, rho_t)\r\n else:\r\n return (phi_t, rho_t, z_t)\r\n\r\n\r\ndef pol2cart(rho_t, phi_t, z_t=None):\r\n x_t = rho_t * np.cos(phi_t)\r\n y_t = rho_t * np.sin(phi_t)\r\n if z_t is None:\r\n return (x_t, y_t)\r\n else:\r\n return (x_t, y_t, z_t)\r\n\r\n\r\nth, r, z = cart2pol(xini, zini, yini)\r\nnodetrans = np.hstack((r.T, z.T, nn.T, th.T)) # 节点、单元全部信息整合\r\n\r\n# left、right网格索引同节点编号\r\n\r\n\r\n''' 周向各层角坐标提取 '''\r\nfacenodes = np.array(pd.read_excel(r\"nodedata.xlsx\", sheet_name='dataface', header=None)) # 导入左边界节点、坐标\r\nth_t = np.around(th, 4)\r\n\r\n\r\ndef del_repeatnum(s):\r\n s1 = []\r\n for i in s:\r\n if i not in s1:\r\n s1.append(i)\r\n return s1\r\n\r\n\r\nth_unique = np.array(del_repeatnum(th_t.T)).T # 周向各层角坐标提取\r\nzn = th_unique.shape[1] - 1 # 周向层数\r\ndelta_th = (np.max(th_unique) - np.min(th_unique)) / zn # 周向夹角\r\n\r\nsita_2 = np.sort(th_unique, axis=1) # 正序,非际序\r\nsita_3 = abs(np.sort(-th_unique, axis=1)) # 倒序,实际序\r\n\r\n# 极坐标按角坐标分类,按实际序\r\nsita_part = np.zeros((int((nodetrans.shape[0] - facenodes.shape[0] * sita_2.shape[1]) / (bn + 1) + facenodes.shape[0]),\r\n facenodes.shape[1], sita_2.shape[1])) # 注意叶片网格层数\r\nfor i in range(sita_2.shape[1]):\r\n tt = 0\r\n for j in range(nodetrans.shape[0]):\r\n if (nodetrans[j, 3] <= sita_3[0, i] + 0.001).all() and (nodetrans[j, 3] >= sita_3[0, i] - 0.001).all():\r\n for k in range(facenodes.shape[1]):\r\n sita_part[tt, k, i] = nodetrans[j, k]\r\n tt += 1\r\n\r\n''' 2D端面内节点关联 '''\r\n# 2D端面内节点期望坐标计算\r\ncopnds1 = np.array(pd.read_excel(r\"nodedata.xlsx\", sheet_name='core', header=None))[:, :2]\r\ncopnds2 = np.array(pd.read_excel(r\"nodedata.xlsx\", sheet_name='expanded', header=None))[:, :2]\r\ncopnds = np.vstack((copnds1, copnds2))\r\n\r\ndeltadis_r = np.zeros((copnds.shape[0], 1))\r\ndeltadis_z = np.zeros((copnds.shape[0], 1))\r\n\r\nfor i in range(copnds.shape[0]):\r\n discopnds_r = nodetrans[copnds[i, 1] - 1, 0] - nodetrans[copnds[i, 0] - 1, 0]\r\n discopnds_z = nodetrans[copnds[i, 1] - 1, 1] - nodetrans[copnds[i, 0] - 1, 1]\r\n deltadis_r[i] = discopnds_r / (mn + 1)\r\n deltadis_z[i] = discopnds_z / (mn + 1)\r\n\r\ncoupled_2D_temp = np.zeros((copnds.shape[0], mn + 2)) # 初始化全部端面耦合节点在APDL网格中的索引\r\ncoupled_2D_ndr = np.zeros((copnds.shape[0], mn + 2)) # 初始化全部端面耦合节点在APDL网格中的r坐标\r\ncoupled_2D_ndz = np.zeros((copnds.shape[0], mn + 2)) # 初始化全部端面耦合节点在APDL网格中的z坐标\r\n\r\nfor i in range(copnds.shape[0]):\r\n coupled_2D_ndr[i, 0] = nodetrans[copnds[i, 0] - 1, 0]\r\n coupled_2D_ndr[i, mn + 1] = nodetrans[copnds[i, 1] - 1, 0]\r\n coupled_2D_ndz[i, 0] = nodetrans[copnds[i, 0] - 1, 1]\r\n coupled_2D_ndz[i, mn + 1] = nodetrans[copnds[i, 1] - 1, 1]\r\n for j in range(1, mn + 1):\r\n coupled_2D_ndr[i, j] = nodetrans[copnds[i, 0] - 1, 0] + deltadis_r[i] * j\r\n coupled_2D_ndz[i, j] = nodetrans[copnds[i, 0] - 1, 1] + deltadis_z[i] * j\r\n\r\n# 2D端面内节点索引匹配\r\ndeltadis_t = np.sqrt(deltadis_r ** 2 + deltadis_z ** 2)\r\ntrshd = np.min(deltadis_t) / 2 # 比较关键\r\n\r\ntemp_rz_face = np.zeros((facenodes.shape[0], 3)) # 端面nrz坐标索引\r\nfor i in range(facenodes.shape[0]):\r\n temp_rz_face[i, 0] = facenodes[i, 0]\r\n temp_rz_face[i, 1] = nodetrans[int(facenodes[i, 0] - 1), 0]\r\n temp_rz_face[i, 2] = nodetrans[int(facenodes[i, 0] - 1), 1]\r\n\r\nfor i in range(copnds.shape[0]):\r\n for j in range(mn + 2):\r\n temp_r_index = temp_rz_face[reduce(np.intersect1d, [np.where(temp_rz_face[:, 1] < coupled_2D_ndr[i, j] + trshd),\r\n np.where(temp_rz_face[:, 1] > coupled_2D_ndr[\r\n i, j] - trshd)]), 0] # 多数组求交\r\n temp_z_index = temp_rz_face[np.intersect1d(np.where(temp_rz_face[:, 2] < coupled_2D_ndz[i, j] + trshd),\r\n np.where(temp_rz_face[:, 2] > coupled_2D_ndz[i, j] - trshd)), 0]\r\n\r\n for k in temp_r_index: # 提高通用性\r\n if np.intersect1d(k, temp_z_index) is not None:\r\n coupled_2D_temp[i, j] = nodetrans[int(k), 2]\r\n\r\ntt = 0\r\ncoupled_2D_index = np.zeros((copnds.shape[0] * (mn + 2), 1))\r\nfor j in range(mn + 2): # 数据整理\r\n for i in range(copnds.shape[0]):\r\n coupled_2D_index[tt, 0] = coupled_2D_temp[i, j]\r\n tt += 1\r\n\r\ncoupled_2D_ntr = np.zeros((coupled_2D_index.shape[0], 1)) # 后续使用\r\ncoupled_2D_ntz = np.zeros((coupled_2D_index.shape[0], Size)) # 后续使用\r\nfor i in range(coupled_2D_index.shape[0]):\r\n coupled_2D_ntr[i, 0] = nodetrans[int(coupled_2D_index[i, 0]) - 1, 0]\r\n\r\n# 3D待优化区内节点索引匹配\r\ntrshd = 0.2 # 比较关键\r\ncoupled_3D_index = np.zeros((coupled_2D_index.shape[0], mn + 2))\r\ncoupled_3D_index[:, 5] = coupled_2D_index[:, 0]\r\nfor i in range(coupled_2D_index.shape[0]):\r\n for j in range(zn):\r\n sita_temp = sita_part[:, :, j]\r\n temp2_r_index = sita_temp[\r\n np.intersect1d(np.where(sita_temp[:, 0] < nodetrans[int(coupled_2D_index[i]), 0] + trshd),\r\n np.where(nodetrans[int(coupled_2D_index[i]), 0] - trshd < sita_temp[:, 0])), 0]\r\n temp2_z_index = sita_temp[\r\n np.intersect1d(np.where(sita_temp[:, 1] < nodetrans[int(coupled_2D_index[i]), 1] + trshd * 2),\r\n np.where(nodetrans[int(coupled_2D_index[i]), 1] - trshd * 2 < sita_temp[:, 1])), 1]\r\n\r\n for k in temp2_r_index: # 提高通用性\r\n if np.intersect1d(k, temp2_z_index) is not None:\r\n coupled_3D_index[i, j] = sita_temp[int(k), 2]\r\n\r\n# 3D补充节(过渡区)节点索引匹配\r\ntrshd = 0.001 # 比较关键\r\nsuply = np.array(pd.read_excel(r\"nodedata.xlsx\", sheet_name='suply', header=None))[:32,\r\n :] # 从mapping文件的suply_det变量获取,输入excel\r\ncoupled_2D_index = np.vstack([coupled_2D_index, suply]) # 2D补充\r\n\r\nsuply_r = np.zeros((suply.shape[0], 1))\r\nsuply_z = np.zeros((suply.shape[0], 1))\r\nfor i in range(suply.shape[0]):\r\n suply_r[i] = nodetrans[int(suply[i]) - 1, 0]\r\n suply_z[i] = nodetrans[int(suply[i]) - 1, 1]\r\n\r\ncoupled_3D_temp = np.zeros((1, mn + 2))\r\nfor i in range(suply.shape[0]):\r\n tt = 0\r\n temp3_r_index = np.intersect1d(np.where(nodetrans[:, 0] < suply_r[i] + trshd),\r\n np.where(suply_r[i] - trshd < nodetrans[:, 0]))\r\n temp3_z_index = np.intersect1d(np.where(nodetrans[:, 1] < suply_z[i] + trshd),\r\n np.where(suply_z[i] - trshd < nodetrans[:, 1]))\r\n\r\n for j in temp3_r_index: # 通用性提高\r\n if np.intersect1d(j, temp3_z_index) is not None: # & & find(temp_rz_index(j) == temp_z_index(:))\r\n coupled_3D_temp[0, tt] = j\r\n tt += 1\r\n\r\n coupled_3D_index = np.concatenate((coupled_3D_index, coupled_3D_temp), axis=0) # 拼接行\r\n\r\n''' 筛选除待更新节点外的固定节点 '''\r\ndelete_3D_index = coupled_3D_index.reshape(1, coupled_3D_index.shape[0] * coupled_3D_index.shape[1]).astype(int)\r\nnodefixed = np.delete(nodeinitial, delete_3D_index - 1, 0) # 删除待更新节点坐标信息\r\n\r\n''' cubic插值(��解chebyshev点对应的Z坐标值) '''\r\nleft_R = np.zeros(left.shape[0])\r\nleft_Z = np.zeros(left.shape[0])\r\nright_R = np.zeros(right.shape[0])\r\nright_Z = np.zeros(right.shape[0])\r\nfor i in range(left.shape[0]):\r\n left_R[i] = nodetrans[left[i, 0] - 1, 0] # left(:,3)\r\n left_Z[i] = nodetrans[left[i, 0] - 1, 1] # left(:,2)\r\n\r\n# for kind in [\"cubic\"]: # 插值方式[\"nearest\", \"zero\", \"slinear\", \"quadratic\", \"cubic\"] , \"nearest\",\"zero\"为阶梯插值, slinear 线性插值, \"quadratic\",\"cubic\" 为2阶、3阶B样条曲线插值\r\nf = interpolate.interp1d(left_R, left_Z, kind=\"cubic\")\r\nleft_cheby_z = f(left_cheby_r) # R的值不能重复 作为PSO初始边界\r\n\r\nfor i in range(right.shape[0]):\r\n right_R[i] = nodetrans[right[i, 0] - 1, 0]\r\n right_Z[i] = nodetrans[right[i, 0] - 1, 1]\r\n\r\nf = interpolate.interp1d(right_R, right_Z, kind=\"cubic\")\r\nright_cheby_z = f(right_cheby_r) # R的值不能重复 作为PSO初始边界\r\npl.plot(left_cheby_z, left_cheby_r, \"ro\", right_cheby_z, right_cheby_r, \"bo\")\r\n\r\n''' PSOA初始化 '''\r\nleft_min_z = left_cheby_z - [0.5, 0.6, 0.7, 0.8, 0.8, 0.7, 0.6, 0.5] # 参数搜索范围\r\nleft_max_z = left_cheby_z + [2, 3, 4.5, 5, 4.5, 4, 3, 2]\r\nright_min_z = right_cheby_z - [2, 3, 4.5, 5, 5, 4.5, 3, 2] # 参数搜索范围\r\nright_max_z = right_cheby_z + [0.5, 0.6, 0.7, 0.8, 0.8, 0.7, 0.6, 0.5]\r\n\r\nMinX = np.hstack((left_min_z, right_min_z))\r\nMaxX = np.hstack((left_max_z, right_max_z))\r\n\r\nVmax = 1\r\nVmin = -1 # 限定速度的范围\r\n\r\nCodeL = len(left_min_z) + len(right_min_z) # 参数个数\r\n\r\nc1=1.9;c2=2.0;c3=0.1;c4=0.15 # 学习因子\r\nwmax=0.9;wmin=0.4 # 惯性权重范围\r\n\r\nw = np.zeros(G)\r\nfor i in range(G):\r\n w[i-1] = wmax - ((wmax - wmin) / (G - 1)) * i\r\n\r\nX = np.zeros((Size, CodeL))\r\nv = np.zeros((Size, CodeL))\r\nfor i in range(Size):\r\n for j in range(int(CodeL / 2)): # 参数个数\r\n X[i, j] = left_cheby_z[j] + (left_max_z[j] - left_min_z[j]) * np.random.random(1)\r\n X[i, int(CodeL / 2 + j)] = right_cheby_z[j] + (right_max_z[j] - right_min_z[j]) * np.random.random(1)\r\n v[i, j] = Vmin + (Vmax - Vmin) * np.random.random(1)\r\n v[i, int(CodeL / 2 + j)] = Vmin + (Vmax - Vmin) * np.random.random(1)\r\n\r\n#\r\n# for i=1:1:Size\r\n# \tssaleft=ssa([nodetrans(2956,2),nodetrans(2947,2),X(i,1:CodeL/2),nodetrans(2623,2),nodetrans(2624,2)]);\r\n# \tX(i,1:CodeL/2)=ssaleft(3:length(ssaleft)-2);\r\n# \tssaright=ssa([nodetrans(2730,2),nodetrans(2734,2),X(i,CodeL/2+1:CodeL),nodetrans(2681,2),nodetrans(2684,2)]);\r\n# \tX(i,CodeL/2+1:CodeL)=ssaright(3:length(ssaright)-2);\r\n# end\r\n\r\n''' 切比雪夫转换为节点坐标 '''\r\n# transformation\r\n\r\n''' 过渡段网格调整 '''\r\njoin = np.array(pd.read_excel(r\"nodedata.xlsx\", sheet_name='join', header=None))[:20, :3]\r\njoin_lu_index = join[1:4, :]\r\njoin_ru_index = join[5:8, :]\r\njoin_ld_index = join[9:14, :]\r\njoin_rd_index = join[15:20, :]\r\n\r\n# 过渡段矩阵初始化(左上,右上,左下,右下)\r\njoin_lu_z = np.zeros([join_lu_index.shape[0], join_lu_index.shape[1], Size], dtype=int) # int? 待确认\r\njoin_ru_z = np.zeros([join_ru_index.shape[0], join_ru_index.shape[1], Size], dtype=int)\r\njoin_ld_z = np.zeros([join_ld_index.shape[0], join_ld_index.shape[1], Size], dtype=int)\r\njoin_rd_z = np.zeros([join_rd_index.shape[0], join_rd_index.shape[1], Size], dtype=int)\r\n\r\njoin_lu_r = np.zeros([join_lu_index.shape[0], join_lu_index.shape[1], Size], dtype=int)\r\njoin_ru_r = np.zeros([join_ru_index.shape[0], join_ru_index.shape[1], Size], dtype=int)\r\njoin_ld_r = np.zeros([join_ld_index.shape[0], join_ld_index.shape[1], Size], dtype=int)\r\njoin_rd_r = np.zeros([join_rd_index.shape[0], join_rd_index.shape[1], Size], dtype=int)\r\n\r\n# 初始赋值,根据相对节点,给予原始Z值\r\nfor i in range(join.shape[1]): # 按列排列\r\n join_lu_z[:, i, 1] = nodetrans[(join_lu_index[:, i] - 1).astype(int), 1]\r\n join_ru_z[:, i, 1] = nodetrans[(join_ru_index[:, i] - 1).astype(int), 1]\r\n\r\n\r\nfor i in range(join.shape[1]): # 按列排列\r\n join_ld_z[:, i, 1] = nodetrans[(join_ld_index[:, i] - 1).astype(int), 1]\r\n join_rd_z[:, i, 1] = nodetrans[(join_rd_index[:, i] - 1).astype(int), 1]\r\n\r\n\r\n# 补齐固定节点(调试过程可注释掉)\r\nfor i in range(Size):\r\n join_lu_z[1, :, i] = join_lu_z[1, :, 1]\r\n join_ru_z[1, :, i] = join_ru_z[1, :, 1]\r\n\r\n", "repo_name": "DongZhizhen/Disk-opt-master-fr-AE", "sub_path": "DiskOptMasterV1.0/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 13798, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.loadtxt", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 44, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 47, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 47, "usage_type": "attribute"}, {"api_name": "pandas.read_excel", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.arctan2", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 95, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.around", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 127, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 128, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 131, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 140, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 157, "usage_type": "call"}, {"api_name": "functools.reduce", "line_number": 165, "usage_type": "call"}, {"api_name": "numpy.intersect1d", "line_number": 165, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 165, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.intersect1d", "line_number": 168, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 168, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 169, "usage_type": "call"}, {"api_name": "numpy.intersect1d", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 182, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 183, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 189, "usage_type": "call"}, {"api_name": "numpy.intersect1d", "line_number": 195, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 195, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.intersect1d", "line_number": 198, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 198, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 199, "usage_type": "call"}, {"api_name": "numpy.intersect1d", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 207, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 207, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 209, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 212, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 217, "usage_type": "call"}, {"api_name": "numpy.intersect1d", "line_number": 220, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 220, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 221, "usage_type": "call"}, {"api_name": "numpy.intersect1d", "line_number": 222, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 222, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 223, "usage_type": "call"}, {"api_name": "numpy.intersect1d", "line_number": 226, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 230, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 234, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 237, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 238, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 239, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 240, "usage_type": "call"}, {"api_name": "scipy.interpolate.interp1d", "line_number": 246, "usage_type": "call"}, {"api_name": "scipy.interpolate", "line_number": 246, "usage_type": "name"}, {"api_name": "scipy.interpolate.interp1d", "line_number": 253, "usage_type": "call"}, {"api_name": "scipy.interpolate", "line_number": 253, "usage_type": "name"}, {"api_name": "pylab.plot", "line_number": 255, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 263, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 264, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 274, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 278, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 279, "usage_type": "call"}, {"api_name": "numpy.random.random", "line_number": 282, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 282, "usage_type": "attribute"}, {"api_name": "numpy.random.random", "line_number": 283, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 283, "usage_type": "attribute"}, {"api_name": "numpy.random.random", "line_number": 284, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 284, "usage_type": "attribute"}, {"api_name": "numpy.random.random", "line_number": 285, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 285, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 299, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 299, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 306, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 307, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 308, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 309, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 311, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 312, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 313, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 314, "usage_type": "call"}]} +{"seq_id": "38800062827", "text": "from api.views import GamesViewSet, PlayersPreformViewSet, PlayersViewSet, ActionsViewSet\nfrom django.urls import include, path, re_path, reverse_lazy\nfrom rest_framework.routers import DefaultRouter\nfrom django.views.generic.base import RedirectView\nfrom rest_framework import permissions\nfrom drf_yasg.views import get_schema_view\nfrom drf_yasg import openapi\n\napp_name = 'api'\n\n########################################################################################\n# doc\n########################################################################################\n\nschema_view = get_schema_view(\n openapi.Info(\n title=\"Bizarre Poker API\",\n default_version='v1',\n description=\"Internal REST API to link fronted and backend parts of app.\",\n terms_of_service=\"https://github.com/MishaVyb/bizarre-poker\",\n contact=openapi.Contact(email=\"vbrn.mv@gmail.com\"),\n license=openapi.License(name=\"BSD License\"),\n ),\n public=True,\n permission_classes=[permissions.AllowAny],\n)\n\nurlpatterns = [\n re_path(\n r'^swagger(?P\\.json|\\.yaml)$',\n schema_view.without_ui(cache_timeout=0),\n name='schema-json',\n ),\n re_path(\n r'^swagger/$',\n schema_view.with_ui('swagger', cache_timeout=0),\n name='schema-swagger-ui',\n ),\n re_path(\n r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'\n ),\n]\n\n########################################################################################\n# auth\n########################################################################################\n\nurlpatterns += [\n path('v1/auth/', include('djoser.urls')),\n path('v1/auth/', include('djoser.urls.authtoken')),\n]\n\n########################################################################################\n# games\n########################################################################################\n\nrouter = DefaultRouter()\nrouter.register('games', GamesViewSet)\nrouter.register(r'games/(?P\\d+)/actions', ActionsViewSet, basename='actions')\nrouter.register(r'games/(?P\\d+)/players', PlayersViewSet, basename='players')\nrouter.register(r'games/(?P\\d+)/playersPreforms', PlayersPreformViewSet, basename='players_preforms')\n\nurlpatterns += [\n path('v1/', include(router.urls)),\n]\n\n########################################################################################\n# main api root\n########################################################################################\n\nurlpatterns += [\n path('', RedirectView.as_view(url=reverse_lazy('api:schema-swagger-ui'))),\n]\n", "repo_name": "MishaVyb/bizarre-poker", "sub_path": "backend/apps/api/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 2607, "program_lang": "python", "lang": "de", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "20", "api": [{"api_name": "drf_yasg.views.get_schema_view", "line_number": 15, "usage_type": "call"}, {"api_name": "drf_yasg.openapi.Info", "line_number": 16, "usage_type": "call"}, {"api_name": "drf_yasg.openapi", "line_number": 16, "usage_type": "name"}, {"api_name": "drf_yasg.openapi.Contact", "line_number": 21, "usage_type": "call"}, {"api_name": "drf_yasg.openapi", "line_number": 21, "usage_type": "name"}, {"api_name": "drf_yasg.openapi.License", "line_number": 22, "usage_type": "call"}, {"api_name": "drf_yasg.openapi", "line_number": 22, "usage_type": "name"}, {"api_name": "rest_framework.permissions.AllowAny", "line_number": 25, "usage_type": "attribute"}, {"api_name": "rest_framework.permissions", "line_number": 25, "usage_type": "name"}, {"api_name": "django.urls.re_path", "line_number": 29, "usage_type": "call"}, {"api_name": "django.urls.re_path", "line_number": 34, "usage_type": "call"}, {"api_name": "django.urls.re_path", "line_number": 39, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 49, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 49, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 50, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 50, "usage_type": "call"}, {"api_name": "rest_framework.routers.DefaultRouter", "line_number": 57, "usage_type": "call"}, {"api_name": "api.views.GamesViewSet", "line_number": 58, "usage_type": "argument"}, {"api_name": "api.views.ActionsViewSet", "line_number": 59, "usage_type": "argument"}, {"api_name": "api.views.PlayersViewSet", "line_number": 60, "usage_type": "argument"}, {"api_name": "api.views.PlayersPreformViewSet", "line_number": 61, "usage_type": "argument"}, {"api_name": "django.urls.path", "line_number": 64, "usage_type": "call"}, {"api_name": "django.urls.include", "line_number": 64, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 72, "usage_type": "call"}, {"api_name": "django.views.generic.base.RedirectView.as_view", "line_number": 72, "usage_type": "call"}, {"api_name": "django.views.generic.base.RedirectView", "line_number": 72, "usage_type": "name"}, {"api_name": "django.urls.reverse_lazy", "line_number": 72, "usage_type": "call"}]} +{"seq_id": "38275671363", "text": "from boost_histogram import Histogram\n\n\nclass BaseHist(Histogram):\n\n def _compute_commonindex(self, index):\n \"\"\"\n Method overriden to preprocess dict containing callable values (i.e loc(...))\n before passing it to its superclass function\n \"\"\"\n\n # preprocessing for dict\n if hasattr(index, \"items\"):\n for i, val in index.items():\n\n # check if callable (eg. bh.loc(...))\n if callable(val):\n index[i] = val(self.axes[i])\n\n return super()._compute_commonindex(index)\n", "repo_name": "aribalam/MyHist", "sub_path": "src/hist/core.py", "file_name": "core.py", "file_ext": "py", "file_size_in_byte": 575, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "boost_histogram.Histogram", "line_number": 4, "usage_type": "name"}]} +{"seq_id": "44443752585", "text": "from pathlib import Path\nfrom datetime import datetime\nimport importlib\nimport importlib.metadata\nimport sys\nimport os\nimport shutil\nimport json\nimport pickle\n\nloaded_results = []\noutput_directories = []\n\ntry:\n results_root = Path(os.environ[\"RESULTSROOT\"]).resolve()\nexcept KeyError:\n results_root = Path(\"results\")\n\nclass ResultsDirectory(type(Path())):\n\n def json(self, path, data=None):\n if data is not None:\n with open(self / path, \"w\") as file:\n json.dump(data, file)\n else:\n with open(self / path, \"r\") as file:\n return json.load(file)\n\n def pickle(self, path, data=None):\n if data is not None:\n with open(self / path, \"wb\") as file:\n pickle.dump(data, file)\n else:\n with open(self / path, \"rb\") as file:\n return pickle.load(file)\n\n def numpy(self, path, data=None):\n import numpy\n if data is not None:\n numpy.save(self / path, data)\n else:\n return numpy.load(self / path)\n\n def binary(self, path, data=None):\n if data is not None:\n with open(self / path, \"wb\") as file:\n file.write(data)\n else:\n with open(self / path, \"rb\") as file:\n return file.read()\n\n def text(self, path, data=None):\n if data is not None:\n with open(self / path, \"w\") as file:\n file.write(data)\n else:\n with open(self / path, \"r\") as file:\n return file.read()\n \n\ndef find_source_code(code_root):\n modules = set()\n for name in sys.modules:\n module = sys.modules[name]\n try:\n module_file = Path(module.__file__)\n is_descendant = code_root in module_file.resolve().parents\n if is_descendant:\n modules.add(module_file.resolve())\n except (AttributeError, TypeError):\n pass\n return modules\n\n\ndef recursive_write_protect(root):\n file_read_only = 0o444\n directory_read_only = 0o555\n all_files = []\n all_dirs = []\n for root, dirs, files in os.walk(root):\n for name in files:\n path = os.path.join(root, name)\n all_files.append(path)\n\n for name in dirs:\n path = os.path.join(root, name)\n all_dirs.append(path)\n\n for path in all_files:\n os.chmod(path, file_read_only)\n\n for path in all_dirs:\n os.chmod(path, directory_read_only)\n\n os.chmod(root, directory_read_only)\n\n\ndef create_results_directory(tag=None):\n try:\n code_root = Path(os.environ[\"CODEROOT\"]).resolve()\n except KeyError:\n raise KeyError(\"Set CODEROOT environment variable to top directory containing your code. Any code used in this run under that directory will be copied into the results directory.\")\n\n now = datetime.now().strftime(\"%d-%m-%y@%H:%M:%S\")\n if tag is not None:\n output_directory_name = f\"{tag}-{now}\"\n else:\n output_directory_name = now\n \n output_directory = results_root / output_directory_name\n assert not output_directory.exists(), f\"Output directory {output_directory} already exists.\"\n\n output_directory.mkdir(parents=True, exist_ok=True)\n \n details_directory = Path(output_directory) / \"details\"\n details_directory.mkdir(exist_ok=True, parents=True)\n\n code_directory = details_directory / \"code\"\n modules = find_source_code(code_root)\n for module_path in modules:\n target_path = code_directory / module_path.relative_to(code_root)\n target_path.parent.mkdir(exist_ok=True, parents=True)\n with open(target_path, \"w\") as file, open(module_path, \"r\") as source_file:\n file.write(source_file.read())\n\n with open(details_directory / \"run.sh\", \"w\") as file:\n print(\"python\", *sys.argv, file=file)\n\n with open(details_directory / \"requirements.txt\", \"w\") as file:\n packages = importlib.metadata.distributions()\n for package in packages:\n name = package.metadata[\"Name\"]\n version = package.metadata[\"Version\"]\n print(f\"{name}=={version}\", file=file)\n\n if len(loaded_results) > 0:\n results_directory = details_directory / \"results\"\n results_directory.mkdir(exist_ok=True, parents=True)\n for result in loaded_results:\n shutil.copytree(result / \"details\", results_directory / result.name)\n\n recursive_write_protect(details_directory)\n \n directory = ResultsDirectory(output_directory)\n output_directories.append(directory)\n return directory\n\n\ndef load_results_directory(path):\n directory = ResultsDirectory(results_root / path)\n loaded_results.append(directory)\n\n read_only = 0o555\n full_access = 0o777\n for output_directory in output_directories:\n details_directory = output_directory / \"details\"\n os.chmod(details_directory, full_access)\n\n results_directory = details_directory / \"results\"\n results_directory.mkdir(exist_ok=True, parents=True)\n for result in loaded_results:\n shutil.copytree(result / \"details\", results_directory / result.name)\n\n recursive_write_protect(results_directory)\n os.chmod(details_directory, read_only)\n\n return directory", "repo_name": "geajack/results", "sub_path": "results.py", "file_name": "results.py", "file_ext": "py", "file_size_in_byte": 5308, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pathlib.Path", "line_number": 15, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 15, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 17, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 19, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 24, "usage_type": "call"}, {"api_name": "json.load", "line_number": 27, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 32, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 42, "usage_type": "call"}, {"api_name": "sys.modules", "line_number": 63, "usage_type": "attribute"}, {"api_name": "sys.modules", "line_number": 64, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 66, "usage_type": "call"}, {"api_name": "os.walk", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 82, "usage_type": "call"}, {"api_name": "os.path", "line_number": 82, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 86, "usage_type": "call"}, {"api_name": "os.path", "line_number": 86, "usage_type": "attribute"}, {"api_name": "os.chmod", "line_number": 90, "usage_type": "call"}, {"api_name": "os.chmod", "line_number": 93, "usage_type": "call"}, {"api_name": "os.chmod", "line_number": 95, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 100, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 100, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 104, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 104, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 115, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 127, "usage_type": "attribute"}, {"api_name": "importlib.metadata.distributions", "line_number": 130, "usage_type": "call"}, {"api_name": "importlib.metadata", "line_number": 130, "usage_type": "attribute"}, {"api_name": "shutil.copytree", "line_number": 140, "usage_type": "call"}, {"api_name": "os.chmod", "line_number": 157, "usage_type": "call"}, {"api_name": "shutil.copytree", "line_number": 162, "usage_type": "call"}, {"api_name": "os.chmod", "line_number": 165, "usage_type": "call"}]} +{"seq_id": "6388368321", "text": "from django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom users import views\n\nurlpatterns = [\n url(r'^groups$', views.UserGroupList.as_view()),\n url(r'^login$', views.LogIn),\n url(r'^logout$',views.LogOut),\n url(r'^register$',views.UserRegister.as_view()),\n url(r'^creategroup$',views.CreateGroup.as_view()),\n url(r'^joingroup$', views.JoinGroup.as_view()),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)", "repo_name": "wenjuzhou/ustcoj", "sub_path": "users/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 470, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "django.conf.urls.url", "line_number": 6, "usage_type": "call"}, {"api_name": "users.views.UserGroupList.as_view", "line_number": 6, "usage_type": "call"}, {"api_name": "users.views.UserGroupList", "line_number": 6, "usage_type": "attribute"}, {"api_name": "users.views", "line_number": 6, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 7, "usage_type": "call"}, {"api_name": "users.views.LogIn", "line_number": 7, "usage_type": "attribute"}, {"api_name": "users.views", "line_number": 7, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 8, "usage_type": "call"}, {"api_name": "users.views.LogOut", "line_number": 8, "usage_type": "attribute"}, {"api_name": "users.views", "line_number": 8, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 9, "usage_type": "call"}, {"api_name": "users.views.UserRegister.as_view", "line_number": 9, "usage_type": "call"}, {"api_name": "users.views.UserRegister", "line_number": 9, "usage_type": "attribute"}, {"api_name": "users.views", "line_number": 9, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 10, "usage_type": "call"}, {"api_name": "users.views.CreateGroup.as_view", "line_number": 10, "usage_type": "call"}, {"api_name": "users.views.CreateGroup", "line_number": 10, "usage_type": "attribute"}, {"api_name": "users.views", "line_number": 10, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 11, "usage_type": "call"}, {"api_name": "users.views.JoinGroup.as_view", "line_number": 11, "usage_type": "call"}, {"api_name": "users.views.JoinGroup", "line_number": 11, "usage_type": "attribute"}, {"api_name": "users.views", "line_number": 11, "usage_type": "name"}, {"api_name": "rest_framework.urlpatterns.format_suffix_patterns", "line_number": 14, "usage_type": "call"}]} +{"seq_id": "72571621809", "text": "import logging\nfrom config import Config\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom bot import updater, browser, restricted\nfrom telegram.ext import run_async\nfrom telegram import ChatAction\nimport os\nimport pickle\nimport time\nfrom os import execl\nfrom sys import executable\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.keys import Keys\nuserId = Config.USERID\ndef joinMeet(context, url_meet):\n\n def students(context):\n try:\n number = WebDriverWait(browser, 2400).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"ow3\"]/div[1]/div/div[8]/div[3]/div[6]/div[3]/div/div[2]/div[1]/span/span/div/div/span[2]'))).text\n except:\n return\n print(number)\n if(int(number) <10):\n context.bot.send_message(chat_id=userId, text=\"Your Class has ended!\")\n browser.quit()\n execl(executable, executable, \"chromium.py\")\n\n try:\n browser.get(url_meet)\n browser.save_screenshot(\"ss.png\")\n context.bot.send_chat_action(chat_id=userId, action=ChatAction.UPLOAD_PHOTO)\n mid = context.bot.send_photo(chat_id=userId, photo=open('ss.png', 'rb'), timeout = 120).message_id\n os.remove('ss.png')\n\n if(browser.find_elements_by_xpath('//*[@id=\"yDmH0d\"]/div[3]/div/div[2]/div[3]/div')):\n browser.find_element_by_xpath('//*[@id=\"yDmH0d\"]/div[3]/div/div[2]/div[3]/div').click()\n time.sleep(3)\n\n context.bot.delete_message(chat_id=userId ,message_id = mid)\n\n browser.save_screenshot(\"ss.png\")\n context.bot.send_chat_action(chat_id=userId, action=ChatAction.UPLOAD_PHOTO)\n mid = context.bot.send_photo(chat_id=userId, photo=open('ss.png', 'rb'), timeout = 120).message_id\n os.remove('ss.png')\n try:\n WebDriverWait(browser, 30).until(EC.visibility_of_element_located((By.XPATH, \"//span[@class='NPEfkd RveJvd snByac' and contains(text(), 'Ask to join')]\"))).click()\n except:\n WebDriverWait(browser, 30).until(EC.visibility_of_element_located((By.XPATH, \"//span[@class='NPEfkd RveJvd snByac' and contains(text(), 'Join now')]\"))).click()\n context.bot.delete_message(chat_id=userId ,message_id = mid)\n\n browser.save_screenshot(\"ss.png\")\n context.bot.send_chat_action(chat_id=userId, action=ChatAction.UPLOAD_PHOTO)\n mid = context.bot.send_photo(chat_id=userId, photo=open('ss.png', 'rb'), timeout = 120).message_id\n os.remove('ss.png')\n a = ActionChains(browser)\n time.sleep(5)\n a.key_down(Keys.CONTROL).send_keys('d' + 'e').key_up(Keys.CONTROL).perform()\n context.bot.delete_message(chat_id=userId ,message_id = mid)\n time.sleep(7)\n browser.save_screenshot(\"ss.png\")\n context.bot.send_chat_action(chat_id=userId, action=ChatAction.UPLOAD_PHOTO)\n mid = context.bot.send_photo(chat_id=userId, photo=open('ss.png', 'rb'), timeout = 120).message_id\n os.remove('ss.png')\n\n context.bot.send_chat_action(chat_id=userId, action=ChatAction.TYPING)\n context.bot.send_message(chat_id=userId, text=\"Attending your lecture. You can chill :v\")\n logging.info(\"STAAAAPH!!\")\n except Exception as e:\n context.bot.send_message(chat_id=userId, text=\"Error occurred! Fix error and retry!\")\n context.bot.send_message(chat_id=userId, text=str(e))\n\n j = updater.job_queue\n j.run_repeating(students, 20, 1000)\n\n\n@restricted\n@run_async\ndef meet(update,context):\n logging.info(\"DOING\")\n\n context.bot.send_chat_action(chat_id=userId, action=ChatAction.TYPING)\n url_meet = update.message.text.split()[-1]\n joinMeet(context, url_meet)\n\n\n", "repo_name": "1337w0rm/YeetMeet", "sub_path": "bot/meet.py", "file_name": "meet.py", "file_ext": "py", "file_size_in_byte": 3849, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 161, "dataset": "github-code", "pt": "20", "api": [{"api_name": "config.Config.USERID", "line_number": 16, "usage_type": "attribute"}, {"api_name": "config.Config", "line_number": 16, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.ui.WebDriverWait", "line_number": 21, "usage_type": "call"}, {"api_name": "bot.browser", "line_number": 21, "usage_type": "argument"}, {"api_name": "selenium.webdriver.support.expected_conditions.presence_of_element_located", "line_number": 21, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 21, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 21, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 21, "usage_type": "name"}, {"api_name": "bot.browser.quit", "line_number": 27, "usage_type": "call"}, {"api_name": "bot.browser", "line_number": 27, "usage_type": "name"}, {"api_name": "os.execl", "line_number": 28, "usage_type": "call"}, {"api_name": "sys.executable", "line_number": 28, "usage_type": "argument"}, {"api_name": "bot.browser.get", "line_number": 31, "usage_type": "call"}, {"api_name": "bot.browser", "line_number": 31, "usage_type": "name"}, {"api_name": "bot.browser.save_screenshot", "line_number": 32, "usage_type": "call"}, {"api_name": "bot.browser", "line_number": 32, "usage_type": "name"}, {"api_name": "telegram.ChatAction.UPLOAD_PHOTO", "line_number": 33, "usage_type": "attribute"}, {"api_name": "telegram.ChatAction", "line_number": 33, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 35, "usage_type": "call"}, {"api_name": "bot.browser.find_elements_by_xpath", "line_number": 37, "usage_type": "call"}, {"api_name": "bot.browser", "line_number": 37, "usage_type": "name"}, {"api_name": "bot.browser.find_element_by_xpath", "line_number": 38, "usage_type": "call"}, {"api_name": "bot.browser", "line_number": 38, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 39, "usage_type": "call"}, {"api_name": "bot.browser.save_screenshot", "line_number": 43, "usage_type": "call"}, {"api_name": "bot.browser", "line_number": 43, "usage_type": "name"}, {"api_name": "telegram.ChatAction.UPLOAD_PHOTO", "line_number": 44, "usage_type": "attribute"}, {"api_name": "telegram.ChatAction", "line_number": 44, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 46, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.ui.WebDriverWait", "line_number": 48, "usage_type": "call"}, {"api_name": "bot.browser", "line_number": 48, "usage_type": "argument"}, {"api_name": "selenium.webdriver.support.expected_conditions.visibility_of_element_located", "line_number": 48, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 48, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 48, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 48, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.ui.WebDriverWait", "line_number": 50, "usage_type": "call"}, {"api_name": "bot.browser", "line_number": 50, "usage_type": "argument"}, {"api_name": "selenium.webdriver.support.expected_conditions.visibility_of_element_located", "line_number": 50, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 50, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 50, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 50, "usage_type": "name"}, {"api_name": "bot.browser.save_screenshot", "line_number": 53, "usage_type": "call"}, {"api_name": "bot.browser", "line_number": 53, "usage_type": "name"}, {"api_name": "telegram.ChatAction.UPLOAD_PHOTO", "line_number": 54, "usage_type": "attribute"}, {"api_name": "telegram.ChatAction", "line_number": 54, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 56, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.action_chains.ActionChains", "line_number": 57, "usage_type": "call"}, {"api_name": "bot.browser", "line_number": 57, "usage_type": "argument"}, {"api_name": "time.sleep", "line_number": 58, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.CONTROL", "line_number": 59, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 59, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 61, "usage_type": "call"}, {"api_name": "bot.browser.save_screenshot", "line_number": 62, "usage_type": "call"}, {"api_name": "bot.browser", "line_number": 62, "usage_type": "name"}, {"api_name": "telegram.ChatAction.UPLOAD_PHOTO", "line_number": 63, "usage_type": "attribute"}, {"api_name": "telegram.ChatAction", "line_number": 63, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 65, "usage_type": "call"}, {"api_name": "telegram.ChatAction.TYPING", "line_number": 67, "usage_type": "attribute"}, {"api_name": "telegram.ChatAction", "line_number": 67, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 69, "usage_type": "call"}, {"api_name": "bot.updater.job_queue", "line_number": 74, "usage_type": "attribute"}, {"api_name": "bot.updater", "line_number": 74, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 81, "usage_type": "call"}, {"api_name": "telegram.ChatAction.TYPING", "line_number": 83, "usage_type": "attribute"}, {"api_name": "telegram.ChatAction", "line_number": 83, "usage_type": "name"}, {"api_name": "bot.restricted", "line_number": 78, "usage_type": "name"}, {"api_name": "telegram.ext.run_async", "line_number": 79, "usage_type": "name"}]} +{"seq_id": "71449153026", "text": "# blueprint of application -> has views and routes\nfrom flask import Blueprint, render_template, request, flash, jsonify\nfrom flask_login import login_required, current_user\nfrom .models import Articles\nfrom . import db\nimport json\n\nviews = Blueprint('views', __name__)\n\n@views.route('/admin', methods=['Get', 'POST'])\n@login_required\ndef admin():\n # ---------------------------------------- for posting (updating the db using site) ------------------------\n if(current_user.email != \"admin@cti.ro\"): \n articles = Articles.query.all()\n return render_template(\"home.html\", user=current_user, articles=articles) \n\n else:\n if request.method == 'POST': \n article_content = request.form.get('article_content')#Gets the article from the HTML \n article_title = request.form.get('article_title')\n if len(article_content) < 1:\n flash('Article too short!', category='error') \n if len(article_title) < 1:\n flash('Title too short!', category='error') \n else:\n from .test import predict_category\n categ = predict_category(article_content)\n new_article = Articles(title=article_title, content=article_content, sentiment=\"not sure\", category = categ) #providing the schema for the article \n db.session.add(new_article) #adding the article to the database \n db.session.commit()\n flash('Article added!', category='success')\n \n articles = Articles.query.all()\n return render_template(\"admin.html\", user=current_user, articles=articles)\n\n@views.route('/', methods=['GET', 'POST'])\n@login_required\ndef home():\n\n # from .test import test_df\n\n # for i in range(0, len(test_df)):\n # article = test_df.iloc[i]\n # new_article = Articles(title=article[\"content\"], content=article[\"content\"], sentiment=article[\"trust_prediction\"], category=article[\"category_predictions\"]) #providing the schema for the article \n # db.session.add(new_article) #adding the article to the database \n # db.session.commit()\n # # flash('Article added!', category='success')\n\n articles = Articles.query.all()\n\n # with this check if an user is logged in\n return render_template(\"home.html\", user=current_user, articles=articles) \n\n\n@views.route('/delete-article', methods=['POST'])\ndef delete_article(): \n article = json.loads(request.data)# this function expects a JSON from the INDEX.js file \n articleId = article['articleId']\n article = Articles.query.get(articleId)\n if article:\n if current_user.email == \"admin@cti.ro\":\n db.session.delete(article)\n db.session.commit()\n return jsonify({})\n\n\n # -------------------------------------------hardcoded article adding ------------------------ \n\n #------------------------------------------------------ add article script---------------------------\n \n # new_article = Articles( title=\"This is a test \", \n # content=\"This Test has proven to be testy\", \n # sentiment=\"kinda testy ngl\")\n # db.session.add(new_article)\n # db.session.commit()\n\n #------------------------------------------------------ delete article script---------------------------\n \n # articleId = 1\n # article = Articles.query.get(articleId)\n # if article:\n # db.session.delete(article)\n # db.session.commit()", "repo_name": "ioananghel/speech-sense_NLP", "sub_path": "website/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 3496, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "flask.Blueprint", "line_number": 8, "usage_type": "call"}, {"api_name": "flask_login.current_user.email", "line_number": 14, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 14, "usage_type": "name"}, {"api_name": "models.Articles.query.all", "line_number": 15, "usage_type": "call"}, {"api_name": "models.Articles.query", "line_number": 15, "usage_type": "attribute"}, {"api_name": "models.Articles", "line_number": 15, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 16, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 16, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 19, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 19, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 20, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 20, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 20, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 21, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 21, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 21, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 23, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 25, "usage_type": "call"}, {"api_name": "test.predict_category", "line_number": 28, "usage_type": "call"}, {"api_name": "models.Articles", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 32, "usage_type": "call"}, {"api_name": "models.Articles.query.all", "line_number": 34, "usage_type": "call"}, {"api_name": "models.Articles.query", "line_number": 34, "usage_type": "attribute"}, {"api_name": "models.Articles", "line_number": 34, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 35, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 35, "usage_type": "name"}, {"api_name": "flask_login.login_required", "line_number": 11, "usage_type": "name"}, {"api_name": "models.Articles.query.all", "line_number": 50, "usage_type": "call"}, {"api_name": "models.Articles.query", "line_number": 50, "usage_type": "attribute"}, {"api_name": "models.Articles", "line_number": 50, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 53, "usage_type": "call"}, {"api_name": "flask_login.current_user", "line_number": 53, "usage_type": "name"}, {"api_name": "flask_login.login_required", "line_number": 38, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 58, "usage_type": "call"}, {"api_name": "flask.request.data", "line_number": 58, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 58, "usage_type": "name"}, {"api_name": "models.Articles.query.get", "line_number": 60, "usage_type": "call"}, {"api_name": "models.Articles.query", "line_number": 60, "usage_type": "attribute"}, {"api_name": "models.Articles", "line_number": 60, "usage_type": "name"}, {"api_name": "flask_login.current_user.email", "line_number": 62, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 62, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 65, "usage_type": "call"}]} +{"seq_id": "28814309211", "text": "# -*- coding: utf-8 -*-\n# @Author: 何睿\n# @Create Date: 2019-08-30 19:55:46\n# @Last Modified by: 何睿\n# @Last Modified time: 2019-08-30 20:17:06\n\nimport heapq\nimport random\n\nfrom typing import List\n\n\nclass Solution:\n\n def __init__(self, nums: List[int]):\n self.arrays = nums\n\n def pick(self, target: int) -> int:\n hep = []\n for i, v in enumerate(self.arrays):\n if v == target:\n heapq.heappush(hep, (random.random(), i))\n _, index = heapq.heappop(hep)\n return index\n\n def pick2(self, target: int) -> int:\n\n n, res = 0, 0\n for x in filter(lambda x: x[1] == target, enumerate(self.arrays)):\n n += 1\n if random.randint(1, n) == n:\n res = x[0]\n\n return res\n", "repo_name": "ruicore/algorithm", "sub_path": "LeetCode/2019-08-30-398-Random-Pick-Index.py", "file_name": "2019-08-30-398-Random-Pick-Index.py", "file_ext": "py", "file_size_in_byte": 805, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "20", "api": [{"api_name": "typing.List", "line_number": 15, "usage_type": "name"}, {"api_name": "heapq.heappush", "line_number": 22, "usage_type": "call"}, {"api_name": "random.random", "line_number": 22, "usage_type": "call"}, {"api_name": "heapq.heappop", "line_number": 23, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "710372986", "text": "\"\"\"Adding itemauditscores table\n\nRevision ID: 67ea2aac5ea0\nRevises: 55725cc4bf25\nCreate Date: 2016-01-26 21:43:10.398048\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '67ea2aac5ea0'\ndown_revision = '55725cc4bf25'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('itemauditscores',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('technology', sa.String(length=128), nullable=False),\n sa.Column('method', sa.String(length=256), nullable=False),\n sa.Column('score', sa.Integer(), nullable=False),\n sa.Column('disabled', sa.Boolean(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n\n op.create_unique_constraint('tech_method_uc', 'itemauditscores', ['technology', 'method'])\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('itemauditscores')\n ### end Alembic commands ###\n", "repo_name": "Netflix/security_monkey", "sub_path": "migrations/versions/67ea2aac5ea0_.py", "file_name": "67ea2aac5ea0_.py", "file_ext": "py", "file_size_in_byte": 1008, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4344, "dataset": "github-code", "pt": "20", "api": [{"api_name": "alembic.op.create_table", "line_number": 19, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 19, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 20, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 20, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 21, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 21, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 23, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 24, "usage_type": "call"}, {"api_name": "sqlalchemy.Boolean", "line_number": 24, "usage_type": "call"}, {"api_name": "sqlalchemy.PrimaryKeyConstraint", "line_number": 25, "usage_type": "call"}, {"api_name": "alembic.op.create_unique_constraint", "line_number": 28, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 28, "usage_type": "name"}, {"api_name": "alembic.op.drop_table", "line_number": 34, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 34, "usage_type": "name"}]} +{"seq_id": "23417693150", "text": "from nltk.corpus import brown\r\n\r\ntagged_words = brown.tagged_words()\r\n\r\nadjs = [x for (x,y) in tagged_words if y=='JJ']\r\nnouns = [x for (x,y) in tagged_words if y=='NN']\r\npnouns = [x for (x,y) in tagged_words if y=='NNS']\r\npropers = [x for (x,y) in tagged_words if y=='NP']\r\nadvbs = [x for (x,y) in tagged_words if y=='RB']\r\nvbgs = [x for (x,y) in tagged_words if y=='VBG']\r\nvbzs = [x for (x,y) in tagged_words if y=='VBZ']\r\npreps = [x for (x,y) in tagged_words if y=='IN']\r\nfws = [x for (x,y) in tagged_words if y.startswith('FW')]\r\n\r\nwith open(\"adjs.txt\",'w') as f:\r\n\tfor x in adjs:\r\n\t\tf.write(x + '\\n')\r\n\r\nwith open(\"nouns.txt\",'w') as f:\r\n\tfor x in nouns:\r\n\t\tf.write(x + '\\n')\r\n\r\nwith open(\"pnouns.txt\",'w') as f:\r\n\tfor x in pnouns:\r\n\t\tf.write(x + '\\n')\r\n\r\nwith open(\"propers.txt\",'w') as f:\r\n\tfor x in propers:\r\n\t\tf.write(x + '\\n')\r\n\r\nwith open(\"advbs.txt\",'w') as f:\r\n\tfor x in advbs:\r\n\t\tf.write(x + '\\n')\r\n\r\nwith open(\"vbgs.txt\",'w') as f:\r\n\tfor x in vbgs:\r\n\t\tf.write(x + '\\n')\r\n\r\nwith open(\"vbzs.txt\",'w') as f:\r\n\tfor x in vbzs:\r\n\t\tf.write(x + '\\n')\r\n\r\nwith open(\"preps.txt\",'w') as f:\r\n\tfor x in preps:\r\n\t\tf.write(x + '\\n')\r\n\r\nwith open(\"fws.txt\",'w') as f:\r\n\tfor x in fws:\r\n\t\tf.write(x + '\\n')\r\n", "repo_name": "gillian-smith/random-phrases", "sub_path": "extractwords.py", "file_name": "extractwords.py", "file_ext": "py", "file_size_in_byte": 1205, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "nltk.corpus.brown.tagged_words", "line_number": 3, "usage_type": "call"}, {"api_name": "nltk.corpus.brown", "line_number": 3, "usage_type": "name"}]} +{"seq_id": "41863507276", "text": "#Libraries \nimport pandas as pd\n#Models\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n\n\n#Entry Point\nif __name__ == \"__main__\":\n dataset = pd.read_csv('./Data/heart.csv')\n #print(dataset.info())\n\n #Features and target\n X = dataset.drop(['target'], axis=1)\n y = dataset['target']\n #print(y.head(5))\n\n #Train and Test division\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.30, random_state=42)\n\n #Implementation\n kn_class = KNeighborsClassifier().fit(X_train, y_train)\n kn_predict = kn_class.predict(X_test)\n print(\"=\"*32)\n print(accuracy_score(kn_predict, y_test))\n\n bag_class = BaggingClassifier(base_estimator=KNeighborsClassifier(), n_estimators=50).fit(X_train, y_train)\n bag_predict = bag_class.predict(X_test)\n print(\"=\"*32)\n print(accuracy_score(bag_predict, y_test))\n\n #Challenge: Try another classifier (not KN)", "repo_name": "fermavec/machine_learning_01", "sub_path": "bagging.py", "file_name": "bagging.py", "file_ext": "py", "file_size_in_byte": 1045, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pandas.read_csv", "line_number": 12, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 21, "usage_type": "call"}, {"api_name": "sklearn.neighbors.KNeighborsClassifier", "line_number": 24, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 27, "usage_type": "call"}, {"api_name": "sklearn.ensemble.BaggingClassifier", "line_number": 29, "usage_type": "call"}, {"api_name": "sklearn.neighbors.KNeighborsClassifier", "line_number": 29, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 32, "usage_type": "call"}]} +{"seq_id": "18579125695", "text": "'''\n建立代理ip池--开放代理\n'''\n\nimport requests\nfrom fake_useragent import UserAgent\nclass ProxyPool:\n def __init__(self):\n self.api_url=''\n self.test_url='http://httpbin.org/get'\n self.headers={'User-Agent':UserAgent().random}\n\n\n def get_proxy(self):\n '''获取代理ip'''\n html=requests.get(url=self.api_url,headers=self.headers).text\n proxy_list=html.split('\\r\\n')\n for proxy in proxy_list:\n # 测试函数\n self.test_proxy(proxy)\n\n def test_proxy(self,proxy):\n '''测试一个代理IP是否可用'''\n proxies={\n 'http':'http://{}'.format(proxy),\n 'https': 'https://{}'.format(proxy),\n }\n try:\n resp=requests.get(url=self.test_url,proxies=proxies,headers=self.headers,timeout=3)\n print(proxy,'可用')\n except Exception as e:\n print(proxy,'不可用')\n\n\nif __name__ == '__main__':\n spider=ProxyPool()\n spider.get_proxy()", "repo_name": "Amiao-miao/month04", "sub_path": "day03/06_proxyPool.py", "file_name": "06_proxyPool.py", "file_ext": "py", "file_size_in_byte": 1008, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "fake_useragent.UserAgent", "line_number": 11, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 16, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 29, "usage_type": "call"}]} +{"seq_id": "42561339238", "text": "import sys\nimport select\nimport socket\nimport os\nimport os.path\nimport urllib.request, urllib.parse, urllib.error\nimport mimetypes\nimport threading\nimport time\nimport re\nimport random\n\nimport gzip\nimport io\nimport json\nimport cgi\nimport hashlib\nimport base64\n\n# Verbose error messages from CGI module\nimport cgitb\ncgitb.enable()\n\nimport http.server\nimport socketserver\n\nDB_TYPE=\"mysql\" \n\nimport MySQLdb\n\nfrom Common import API,PrettyPrint\nfrom Common.Utils import *\n#from Common.PictureSupplier import PictureSupplier\nfrom Tools import TailLog, HUD\nfrom Common.InternalDB import mysql as sqldb\n\nglobal channel_ids \nglobal param_ids\nglobal disablePic\nchannel_ids = {}\nparam_ids = {}\ndisablePic = False\nWebSocketMagic = \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\"\n\nDEBUG = False\n\ndef toUnicode(string):\n \"\"\"\n Function to change a string (unicode or not) into a unicode string\n Will try utf-8 first, then latin-1.\n TODO: Is there a better way? There HAS to be!!!\n \"\"\"\n\n if string.__class__ != str:\n return string\n try:\n return str(string, \"utf-8\")\n except:\n pass\n return str(string, \"latin-1\")\n\n\ndef microsec_to_string(microsec):\n \"\"\"\n Convert from million seconds to a decent string\n \"\"\"\n\n str = \"\"\n\n sec = int(microsec)/1000000000\n # Now make this into \"hours\" \"minutes\" \"seconds\"\n hours = sec/3600\n if hours:\n sec -= hours*3600\n str = \"%d h \"%hours\n \n minutes = sec/60\n if minutes:\n sec -= minutes*60\n str += \"%d min \"%minutes\n\n str += \"%d sec\"%sec\n\n return str\n\n\n\n \nclass LogDB(TailLog.TailLog):\n \n def __init__(self):\n TailLog.TailLog.__init__(self)\n\n def get_changes_by_time(self, args, \n start_time,\n stop_time): \n # TODO: Also do sessions, times and stuff here\n if args:\n sql = \"AND \" + args\n else:\n sql = \"\"\n\n rows = 0\n cursor = self._execute(\"SELECT * FROM log WHERE timestamp>? AND timestamp? \";\n params = [_last_id]\n if len(args) > 0:\n SQL += \"AND %s \"%args[0]\n params += args[1]\n SQL += \"ORDER BY id DESC \"\n if limit:\n SQL += \"LIMIT %s\"\n params.append(int(limit))\n cursor = self._execute(SQL, params)\n return cursor\n\n def get_modules(self):\n \"\"\"\n Return a list of modules that have been logging\n \"\"\"\n cursor = self._execute(\"SELECT DISTINCT(module) FROM log\")\n return cursor\n\n def get_log_levels(self):\n \"\"\"\n Return a list of textual log levels that are available\n \"\"\"\n return list(API.log_level_str.keys())\n\nclass DBWrapper:\n def __init__(self, status_db=\"System.Status.MySQL\"):\n self.status_db = status_db\n self._dbs = {}\n \n def get_db(self, db_name):\n if not db_name in list(self._dbs.keys()):\n self._dbs[db_name] = StatusDB(db_name = db_name, status_db = self.status_db)\n \n return self._dbs[db_name]\n\nclass StatusDB(sqldb):\n\n def __init__(self, name = \"WebGui.StatusDB\", db_name = None, status_db = \"System.Status.MySQL\"):\n\n self._cached_params = {}\n self.name = name\n self.log = API.get_log(self.name)\n cfg = API.get_config(status_db)\n print(db.__class__)\n ssl = None\n if cfg[\"ssl\"]:\n ssl = {\n \"key\": \"/opt/LSG/keys/client-key.pem\",\n \"cert\": \"/opt/LSG/keys/client-cert.pem\",\n \"ca\": \"/opt/LSG/keys/server-ca.pem\"\n }\n\n sqldb.__init__(self, name, cfg, db_name = db_name, ssl=ssl)\n\n def fesk_get_param_info(self, aid, paramid):\n \"\"\"\n Get the channel and name of a parameter\n \"\"\"\n if not paramid in self._cached_params:\n SQL = \"SELECT status_channel.name,status_parameter.name FROM gstatus_channel,gstatus_parameter \"\\\n \"WHERE gstatus_parameter.chanid=gstatus_channel.chanid AND paramid=%s AND aid=%s\"\n cursor = self._execute(SQL, [paramid, aid])\n row = cursor.fetchone()\n if not row:\n raise Exception(\"No parameter '%s'\"%paramid)\n self._cached_params[paramid] = {\"channel\":row[0],\n \"name\":row[1]}\n return self._cached_params[paramid]\n \n \n ########### Available interface ############\n\n def fesk_get_timestamps(self):\n \"\"\"\n Return the smallest and largest timestamp (for relative clocks)\n \"\"\"\n cursor = self._execute(\"SELECT MIN(timestamp), MAX(timestamp) FROM status\")\n try:\n row = cursor.fetchone()\n return {\"min\":row[0], \"max\":row[1]}\n except:\n return {}\n\n def get_aids(self):\n cursor = self._execute(\"SELECT aid, aname FROM anlegg\")\n aids = []\n for aid, aname in cursor.fetchall():\n aids.append((aid, aname))\n return aids\n\n def get_channels(self, aid):\n cursor = self._execute(\"SELECT chanid, name FROM gstatus_channel WHERE aid=%s ORDER BY name\", [aid])\n global channel_ids\n if aid not in channel_ids:\n channel_ids[aid] = {}\n channels = []\n for row in cursor.fetchall():\n if row[1] not in channel_ids:\n channel_ids[aid][row[1]] = row[0]\n channels.append(row[1])\n return channels\n\n def get_params(self, aid, channel):\n if not channel in channel_ids[aid]:\n self.get_channels()\n\n cursor = self._execute(\"SELECT paramid, name FROM gstatus_parameter WHERE chanid=%s AND aid=%s ORDER BY name\",[channel_ids[aid][channel]], aid)\n params = []\n global param_ids\n if aid not in param_ids:\n param_ids[aid] = {}\n for row in cursor.fetchall():\n fullname = channel + \".\" + row[1]\n if not fullname in param_ids:\n param_ids[aid][fullname] = row[0]\n params.append(row[1])\n return params\n\n def get_params_with_ids(self, aid, channel):\n if not channel in channel_ids:\n self.get_channels(aid)\n\n cursor = self._execute(\"SELECT paramid, name FROM gstatus_parameter WHERE aid=%s AND chanid=%s ORDER BY name\", [aid, channel_ids[aid][channel]])\n params = []\n global param_ids\n for row in cursor.fetchall():\n fullname = channel + \".\" + row[1]\n if not fullname in param_ids:\n param_ids[fullname] = row[0]\n params.append((row[0], row[1]))\n return params\n\n def get_config(self, aid):\n cursor = self._execute(\"SELECT config FROM config WHERE aid=%s\", [aid])\n row = cursor.fetchone()\n if not row:\n raise Exception(\"Missing AID %s\" % aid)\n return row[0]\n\n def get_data(self, aid, params, start_time, end_time, since=0, aggregate=None):\n if len(params) == 0:\n raise Exception(\"No parameters given\")\n\n p = [aid, start_time, end_time, since]\n SQL = \"SELECT id, paramid, timestamp, value FROM gstatus WHERE aid=%s AND timestamp>%s AND timestamp<%s AND id> %s AND (\"\n for param in params:\n SQL += \"paramid=%s OR \"\n p.append(param)\n if aggregate is not None:\n SQL = SQL[:-4] + \") GROUP BY paramid, timestamp DIV %d\" % aggregate\n else:\n SQL = SQL[:-4] + \") ORDER BY paramid, timestamp\"\n\n print(SQL, str(p))\n cursor = self._execute(SQL, p)\n dataset = {}\n max_id = since\n for i, p, ts, v in cursor.fetchall():\n max_id = max(max_id, i)\n if p not in dataset:\n dataset[p] = []\n\n try:\n v = float(v)\n except:\n pass\n\n dataset[p].append((ts, v))\n return max_id, dataset\n\n\nclass MyWebServer(http.server.HTTPServer):\n \"\"\"\n Non-blocking, multi-threaded IPv6 enabled web server\n \"\"\"\n # DS: Temporarily disable ipv6\n #if socket.has_ipv6:\n # address_family = socket.AF_INET6\n \n # Override that blasted blocking thing!\n def get_request(self):\n \"\"\"Get the request and client address from the socket.\n Override to allow non-blocking requests.\n\n WARNING: This will make \"serve_forever\" and \"handle_request\"\n throw exceptions and stuff! Serve_forever thus does not work!\n \"\"\"\n\n # Use select for non-blocking IO\n if select.select([self.socket], [], [], 1)[0]:\n return self.socket.accept()\n else:\n return None\n\n# TODO: Implement class ThreadPoolMixIn defining\n#def process_request(self, request, client_address):\n# Which queues requests on a queu and executes the handler\n# with requests, client_address as parameter\n# \"\"\"Start a new thread to process the request.\"\"\"\n# t = threading.Thread(target = self.process_request_thread,\n# args = (request, client_address))\n# if self.daemon_threads:\n# t.setDaemon (1)\n# t.start()\n# where process_request_thread(self): is \n# try:\n# self.finish_request(request, client_address)\n# self.close_request(request)\n# except:\n# self.handle_error(request, client_address)\n# self.close_request(request)\n\n\n\nclass MyWebHandler(http.server.BaseHTTPRequestHandler):\n \"\"\"\n Handle requests\n \"\"\"\n\n server_version = \"UAV Onboard/0.1\"\n\n def log_message(self, format, *args):\n \"\"\"\n Override message logging - don't want reverse DNS lookups\n or output to stderr\n\n The first argument, FORMAT, is a format string for the\n message to be logged. If the format string contains\n any % escapes requiring parameters, they should be\n specified as subsequent arguments (it's just like\n printf!).\n\n The client host and current date/time are prefixed to\n every message.\n\n \"\"\"\n\n if self.server.cfg[\"log_requests\"]:\n self.get_log().debug(format%args)\n\n def getPath(self, strip_args=False):\n \"\"\"\n Get the unicode, unquoted path of the request\n \"\"\"\n path = urllib.parse.unquote(self.path)\n path = str(path, \"utf-8\", \"replace\")\n\n if strip_args and path.find(\"?\") > -1:\n path = path[:path.find(\"?\")]\n return path\n\n def failed(self, code, message = None):\n \"\"\"\n Request failed, return error\n \"\"\"\n \n try:\n if message:\n self.send_error(code, str(message))\n else:\n self.send_error(code)\n except Exception as e:\n print(\"Could not send error:\",e)\n return False\n\n def get_log(self):\n return API.get_log(\"WebGUI.Handler\")\n \n def prepare_send(self, type, size=None, response=200, encoding=None, content_range=None):\n\n try:\n# self.server.log.debug(\"Sending %s\"%response)\n self.send_response(response)\n except Exception as e:\n self.get_log().warning(\"Error sending response: %s\"%e)\n return\n\n #self.send_header(\"date\", makeRFC1123time(time.time()))\n self.send_header(\"server\", self.server_version)\n \n # Send type\n if type:\n# self.server.log.debug(\"Content-Type: %s \"%type)\n self.send_header(\"Content-Type\", type)\n\n if content_range:\n# self.server.log.debug(\"Content-Range: bytes %d-%d/%d\"%content_range)\n self.send_header(\"Content-Range\", \"bytes %d-%d/%d\"%content_range)\n\n self.send_header(\"Accept-Ranges\", \"bytes\")\n\n if size:\n# self.server.log.debug(\"Content-Length: %s\"%size)\n self.send_header(\"Content-Length\",size)\n \n if encoding:\n# self.server.log.debug(\"Content-Encoding: %s\"%encoding)\n self.send_header(\"Content-Encoding\", encoding)\n \n self.end_headers()\n\n def _to_file(self, path):\n \"\"\"\n Return a valid file, send error and return None if not allowed\n \"\"\"\n if not file:\n return self.failed(404, \"No file specified\")\n \n if not self.server.cfg[\"web_root\"]:\n self.server.log.error(\"Internal error: 'web_root' config parameter does not exist\")\n return self.failed(400)\n\n file_path = os.path.join(self.server.cfg[\"web_root\"], path[1:])\n\n if not os.path.abspath(file_path).startswith(os.path.abspath(self.server.cfg[\"web_root\"])):\n self.failed(403)\n return None\n \n if not os.path.exists(file_path):\n self.failed(404, \"No such file '%s'\"%file_path)\n return None\n return file_path\n \n \n \n def _send_image(self, path, fullpath=False):\n if not path:\n return self.failed(404, \"No file specified\")\n if fullpath:\n p = path\n else:\n p = self._to_file(path)\n if not p:\n self.server.log.info(\"Got request for '%s' which turned into None\"%path)\n return self.failed(404, \"Nothing know about '%s'\"%path)\n \n if os.path.exists(p):\n data = open(p,\"r\").read()\n self.prepare_send(\"image/jpeg\", len(data))\n self.wfile.write(data)\n self.wfile.close()\n return\n self.failed(404, \"Missing file '%s'\"%path)\n\n def add_url(self, _url, reset=False):\n \"\"\"\n \"\"\"\n import re\n m = re.match(\"/.*url=(.*)\", _url)\n if not m:\n return\n\n url = m.groups()[0]\n if reset:\n self.server.player.clear()\n\n self.server.player.add_url(url)\n \n def do_POST(self):\n\n path = self.getPath()\n\n if path != \"/set_config\":\n return self.failed(404)\n \n ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))\n if ctype == 'multipart/form-data':\n form = cgi.parse_multipart(self.rfile, pdict)\n elif ctype == 'application/x-www-form-urlencoded':\n length = int(self.headers.getheader('content-length'))\n form = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)\n else:\n form = {}\n #data = self.rfile.read(length)\n #self.server.log.debug(\"Got data:\" + data)\n #form = cgi.FieldStorage(fp=self.rfile)\n self.server.log.debug(\"set config: \" + str(list(form.keys())))\n\n if \"version\" not in form:\n return self.send_error(400, \"Missing version\")\n if \"json\" not in form:\n return self.send_error(400, \"Missing config\")\n \n if \"root\" in form:\n root = form[\"root\"].value\n else:\n root = None\n\n version = form[\"version\"][0]\n serialized = form[\"json\"][0]\n\n if path.startswith(\"/set_config\"):\n try:\n self.server.log.info(\"Should save config\" + \" root:\" + str(root) + \", version:\" + str(version))\n\n self.server.log.info(\"Saving config '%s'\"%version)\n\n cfg = API.get_config()\n \n # First we add the version if it doesn't already exist\n try:\n cfg.add_version(version)\n except:\n pass # Ignore any errors at this point\n cfg.deserialize(serialized, \n root=root, \n version=version,\n overwrite=True)\n self.server.log.debug(\"Saved OK\")\n return self.send_response(200)\n except Exception as e:\n self.server.log.exception(\"Setting config '%s'\"%path)\n return self.failed(404, \"Failed to save:\" + str(e))\n\n\n return self.failed(300, \"Should never get here\")\n\n def _get_arg(self, args, name, default):\n if name in args:\n return args[name]\n return default\n \n def get_db(self):\n return self.server.db.get_db(self._get_params()[\"db\"])\n\n def _do_GET_pic(self, path, args):\n \"\"\"\n Divided into two different variants - if a timestamp is given,\n the image id to the correct image is given. If img has a\n value, that image is returned with the correct quality\n\n Try to get a picture based on a timestamp, according to the\n given quality parameters\n - quality (typical values 0.4-0.9), default 0.9, 0 is thumbnail\n - scale (up to 1.0), default 1.0\n - crop (left,top,right,bottom), default whole image\n \"\"\"\n global disablePic\n if disablePic:\n return self.failed(403, \"Pictures disabled on basestation\")\n \n if not \"t\" in args:\n if not \"img\" in args:\n return self.failed(400, \"Need timestamp or picture id\")\n\n if \"t\" in args:\n timestamp = float(args[\"t\"])\n instrumentid = self._get_arg(args, \"i\", None)\n try:\n info = self.server.picture_supplier.get_image(timestamp, \n instrumentid)\n except:\n return self.failed(404, \"No image for given time\")\n\n data = json.dumps({\"img\":info[\"id\"], \"i\":[info[\"timestamp\"], info[\"instrument\"], \n info[\"lat\"], info[\"lon\"], info[\"alt\"],\n info[\"q0\"], info[\"q1\"], info[\"q2\"], info[\"q3\"], \n info[\"roll\"], info[\"pitch\"], info[\"yaw\"], info[\"alt\"]]})\n return self._send_html(data);\n \n img_id = args[\"img\"]\n if (self._get_arg(args, \"o\", False)):\n # Request for the unmodified original \n try:\n info = self.server.picture_supplier.get_image_by_id(img_id)\n self._send_image(info[\"path\"], fullpath=True)\n except:\n self.failed(404)\n return\n\n quality = float(self._get_arg(args, \"q\", 0.9))\n scale = float(self._get_arg(args, \"s\", 1.0))\n crop = self._get_arg(args, \"crop\", None)\n histogram = self._get_arg(args, \"h\", None)\n headers_only = self._get_arg(args, \"p\", False)\n cached = self._get_cached(img_id, quality, scale, crop, histogram)\n if cached:\n return self._send_img_result(cached, headers_only)\n\n rotation = self.server.picture_supplier.get_rotation(img_id)\n\n crop_box = None\n if crop:\n c = crop.split(\",\")\n crop_box = (int(c[0]), int(c[1]), int(c[2]), int(c[3]))\n\n try:\n info = self.server.picture_supplier.get_image_by_id(img_id)\n except Exception as e:\n #self.server.log.exception(\"Getting picture\")\n return self.failed(404, e)\n\n header = [info[\"timestamp\"], info[\"instrument\"], \n info[\"lat\"], info[\"lon\"], info[\"alt\"],\n info[\"q0\"], info[\"q1\"], info[\"q2\"], info[\"q3\"]]\n if histogram:\n data = self.server.picture_supplier.get_histogram(info[\"path\"])\n print(len(data))\n content_type = \"application/binary\"\n else:\n #content_type = \"image/jpeg\"\n content_type = \"image/png\"\n # Got file info, prepare header and get data\n\n try:\n if quality == 0:\n inf, data = self.server.picture_supplier.get_thumbnail(info[\"path\"], rotation)\n if len(data) == 0:\n inf, data = self.server.picture_supplier.resample(info[\"path\"], scale=0.2, rotation=rotation, filetype=\"png\")\n else:\n inf, data = self.server.picture_supplier.resample(info[\"path\"], scale=scale,\n quality=quality, crop_box=crop_box, rotation=rotation, filetype=\"png\")\n except Exception as e:\n self.server.log.exception(\"Getting picture\")\n return self.failed(404, e)\n\n self.server.log.debug(\"Sending picture %s (%d bytes)\"%(info[\"path\"], len(data)))\n \n # We also send the physical size of the image as well as the\n # lat,lon of the boundingbox for it. These are crude\n # estimations atm\n additional_info = {}\n for key in [\"bb_size\", \"bb_sw\", \"bb_ne\"]:\n if key in inf:\n additional_info[key] = inf[key]\n\n # Send data\n result = {\"content-type\":content_type,\n \"content-length\":len(data),\n \"i\":json.dumps(header),\n \"a\": json.dumps(additional_info),\n \"data\":data}\n self._cache_result(img_id, quality, scale, crop, histogram, result)\n self._send_img_result(result, headers_only)\n \n def _send_img_result(self, result, headers_only = False):\n self.send_response(200)\n for header in [\"content-type\", \"content-length\", \"i\", \"a\"]:\n if header in result:\n if headers_only and header == \"content-length\":\n continue\n self.send_header(header, result[header])\n self.end_headers()\n if not headers_only:\n self.wfile.write(result[\"data\"])\n self.wfile.close()\n return\n\n def _cache_result(self, img_id, quality, scale, crop, histogram, result):\n # Quick and dirty\n if not os.path.exists(\"/tmp/cache\"):\n os.mkdir(\"/tmp/cache\")\n\n cache_file = \"/tmp/cache/%s_%s_%s_%s_%s\"%(img_id, quality, scale, crop, histogram)\n f = open(cache_file, \"w\")\n f.write(result[\"data\"])\n f.close()\n res = {}\n for k in list(result.keys()):\n if k == \"data\":\n continue\n res[k] = result[k]\n f = open(cache_file + \".nfo\", \"w\")\n f.write(json.dumps(res))\n f.close()\n \n def _get_cached(self, img_id, quality, scale, crop, histogram):\n cache_file = \"/tmp/cache/%s_%s_%s_%s_%s\"%(img_id, quality, scale, crop, histogram)\n \n if os.path.exists(cache_file):\n f = open(cache_file + \".nfo\", \"r\")\n result = json.loads(f.read())\n f.close()\n f = open(cache_file, \"r\")\n result[\"data\"] = f.read()\n f.close()\n return result\n \n return None\n \n def _get_additional_info(self, rotation, inf):\n \"\"\"\n Physical size of bounding box + lat_lon of bounding box\n \"\"\"\n additional = {}\n \n # We expect square pixels\n additional[\"px_size\"] = rotation[\"image_width\"]/inf[\"new_size\"][0]\n\n #bounding-box size\n additional[\"bb_size\"] = (inf[\"bb_size\"][0]*additional[\"px_size\"],\n inf[\"bb_size\"][1]*additional[\"px_size\"])\n \n # Lat-lon top left and bottom right corners\n # Latitude: 1 deg = 110.54 km\n # Longitude: 1 deg = 111.320*cos(latitude) km\n additional[\"bb_sw\"] = (rotation[\"lat\"] - (additional[\"bb_size\"][0]/(2*110540.0)),\n rotation[\"lon\"] - (additional[\"bb_size\"][1]/(2*112320.0*math.cos(math.radians(rotation[\"lat\"])))))\n additional[\"bb_ne\"] = (rotation[\"lat\"] + (additional[\"bb_size\"][0]/(2*110540.0)),\n rotation[\"lon\"] + (additional[\"bb_size\"][1]/(2*112320.0*math.cos(math.radians(rotation[\"lat\"])))))\n\n print(additional)\n return additional\n \n \n def processItemRequest(self, path, args):\n data = None\n if path == \"/item/list\":\n l = self.get_db().list_items();\n data = json.dumps({\"keys\":l})\n elif path == \"/item/add\":\n self.get_db().add_item(args[\"key\"], args[\"item\"]);\n data = \"\";\n elif path == \"/item/get\":\n data = self.get_db().get_item(args[\"key\"])\n if data == None:\n return self.failed(404, \"Missing data\")\n self._send_html(data)\n \n def processConfigRequest(self, path, args):\n #cfg = API.get_config()\n cfg = self.server.root_cfg\n print(\"Config request: '%s'(%s)\"%(path, args))\n res = None\n try:\n if path == \"/cfg/get\":\n res = cfg[args[\"param\"]]\n #res = self.server.cfg.get(args[\"param\"], absolute_path=True).get_value()\n elif path == \"/cfg/set\":\n if args[\"value\"].isdigit():\n val = int(args[\"value\"])\n elif args[\"value\"].replace(\".\",\"\").isdigit():\n val = float(args[\"value\"])\n else:\n val = args[\"value\"]\n cfg[args[\"param\"]] = val\n #try:\n # self.server.cfg.set(args[\"param\"], args[\"value\"], absolute_path=True)\n #except NoSuchParameterException:\n # self.server.cfg.add(args[\"param\"], args[\"value\"])\n res = []\n except:\n self.server.log.exception(\"Config request failed: %s=%s\"%(path, args))\n return self.failed(400, \"Bad request\")\n if res == None:\n return self.failed(404, \"No such elmement %s\"%path)\n self._send_html(json.dumps(res))\n\n def do_GET(self):\n try:\n self._do_GET()\n except:\n self.server.log.exception(\"In GET\")\n\n def _get_params(self):\n import urllib.parse\n path = self.getPath()\n if path.find(\"?\") > -1:\n args = cgi.parse_qs(path[path.find(\"?\")+1:])\n for key in args:\n args[key] = args[key][0]\n path = path[:path.find(\"?\")]\n else:\n args = {}\n\n if not \"ts\" in args:\n args[\"ts\"] = None\n\n if not \"db\" in args:\n args[\"db\"] = None\n return args\n \n\n def _do_ws_request(self):\n \"\"\"\n Process a web socket request\n \"\"\"\n headers = self.headers\n self.server.log.debug(\"Processing web socket request\")\n valid = True\n if \"upgrade\" in list(headers.keys()):\n if headers[\"upgrade\"] == \"websocket\":\n self.send_response(101)\n # Handshake\n if \"cookie\" in list(headers.keys()):\n self.send_header(\"Cookie\", headers[\"cookie\"])\n self.send_header(\"Connection\", \"Upgrade\")\n self.send_header(\"Upgrade\", \"websocket\")\n self.send_header(\"Sec-WebSocket-Version\", 13)\n the_string = headers[\"sec-websocket-key\"] + WebSocketMagic;\n m = hashlib.sha1()\n m.update(the_string)\n self.send_header(\"Sec-WebSocket-Accept\", base64.b64encode(m.digest()))\n else:\n return self.error(400, \"Unsupported request\")\n\n path = self.getPath(strip_args=True)\n if path == \"/hud\":\n # Head up display \n class fakeit:\n def __init__(self, rfile, wfile):\n self.rfile = rfile\n self.wfile = wfile\n def send(self, data):\n return self.wfile.write(data)\n def recv(self, maxlen):\n return self.rfile.read(maxlen)\n\n f = fakeit(self.rfile, self.wfile)\n hud = HUD.HUDProvider(f)\n hud.start()\n return\n \n\n def _do_GET(self):\n\n if \"upgrade\" in list(self.headers.keys()):\n return self._do_ws_request()\n\n \n self._compress = False\n if \"Accept-Encoding\" in self.headers:\n if \"gzip\" in self.headers[\"Accept-Encoding\"]:\n self._compress = True\n\n path = self.getPath(strip_args=True)\n args = self._get_params()\n\n # Picture request?\n try:\n if path.startswith(\"/pic\"):\n return self._do_GET_pic(path, args)\n except:\n self.server.log.exception(\"Getting picture\")\n return self.failed(500, \"unknown error\")\n\n if path.startswith(\"/img/\"):\n return self._send_image(path)\n\n if path.startswith(\"/list_aids\"):\n return self._send_html(json.dumps(self._list_aids()))\n\n if path.startswith(\"/list_channels_and_params_full\"):\n if \"aid\" not in args:\n return self.failed(500, \"Missing aid\")\n return self._list_channels_and_params_full(args[\"aid\"])\n\n if path.startswith(\"/get_config\"):\n if \"aid\" not in args:\n return self.failed(500, \"Missing aid\")\n try:\n self._send_html(self._get_config(args[\"aid\"]))\n return\n except Exception as e:\n print(e)\n return self.failed(404)\n\n if path.startswith(\"/get\"):\n if \"aid\" not in args:\n return self.failed(500, \"Missing aid\")\n\n # List of parameters to get, and a time window is required\n if \"params\" not in args:\n return self.failed(500, \"Missing parameter list\")\n\n if \"start\" not in args:\n return self.failed(500, \"Missing start\")\n\n if \"end\" not in args:\n return self.failed(500, \"Missing end\")\n\n try:\n params = json.loads(args[\"params\"])\n if len(params) == 0:\n return self.failed(500, \"Missing parameters\")\n except:\n return self.failed(500, \"Bad parameter list\")\n\n if \"since\" in args:\n since = int(args[\"since\"])\n else:\n since = 0\n if \"aggregate\" in args:\n try:\n aggregate = int(args[\"aggregate\"])\n except:\n aggregate = None\n else:\n aggregate = None\n # Now get the data!\n ret = self._get_data(args[\"aid\"], params, args[\"start\"], args[\"end\"], since, aggregate)\n if ret:\n ret[\"ts\"] = time.time()\n self._send_html(json.dumps(ret))\n else:\n self.failed(404)\n return\n\n if path == \"/\":\n file_path = self._to_file(\"/index.html\")\n else:\n file_path = self._to_file(path)\n \n if file_path:\n response = 200;\n content_range = None\n ftype = mimetypes.guess_type(file_path)[0]\n print(\"Request for\",file_path,\"of type\",ftype)\n if \"Range\" in self.headers:\n response = 206;\n r = self.headers[\"Range\"]\n if not r.startswith(\"bytes=\"):\n self.failed(400, \"Bad request range\")\n start, end = r[6:].split(\"-\")\n f = open(file_path, \"r\")\n f.seek(int(start))\n fsize = os.path.getsize(file_path)\n if not end:\n content = f.read()\n content_range = (int(start), len(content)+int(start)-1, fsize)\n else:\n content = f.read(int(end)-int(start))\n content_range = (int(start), int(end), fsize)\n else: \n content = open(file_path, \"r\").read()\n if ftype ==\"text/html\" or ftype == \"application/javascript\":\n content = self._replace_base_path(content)\n\n self._send_html(content, ftype, response=response, content_range=content_range)\n\n def _replace_base_path(self, content):\n \"\"\"\n Allow config of base-path, allowing us to move some library stuff\n to another machine if we want to\n \"\"\"\n \n if self.server.cfg[\"base_path\"]:\n return content.replace(\"_BASE_PATH_\", self.server.cfg[\"base_path\"])\n return content.replace(\"_BASE_PATH_\", \"\")\n\n def _list_aids(self):\n \"\"\"\n Return all AIDs and their associated names\n \"\"\"\n anlegg = [];\n for aid, aname in self.get_db().get_aids():\n anlegg.append((aid, aname))\n return anlegg\n\n def _list_channels_and_params(self, aid):\n \"\"\"\n Return all channels and their parameters as one giant json dump.\n \"\"\"\n channelsAndParams = {}\n for channel in self.get_db().get_channels(aid):\n params = self.get_db().get_params(channel, aid)\n channelsAndParams[channel] = params\n data = json.dumps({\"channels\":channelsAndParams})\n self._send_html(data)\n\n def _list_channels_and_params_full(self, aid):\n \"\"\"\n Return all channels and their parameters as one giant json dump.\n \"\"\"\n channelsAndParams = {}\n for channel in self.get_db().get_channels(aid):\n params = self.get_db().get_params_with_ids(aid, channel)\n channelsAndParams[channel] = params\n data = json.dumps({\"channels\":channelsAndParams})\n self._send_html(data)\n \n def _get_config(self, aid):\n \"\"\"\n Return the config of the given aid\n \"\"\"\n cfg = self.get_db().get_config(aid)\n return cfg\n\n def _get_data(self, aid, params, start_time, end_time, since=0, aggregate=None):\n \"\"\"\n Return the dataset of the given parameters\n \"\"\"\n max_id, dataset = self.get_db().get_data(aid, params, start_time, end_time, since, aggregate)\n return {\"max_id\": max_id, \"data\": dataset}\n\n def _get_changes(self, since, start_time=None, stop_time=None):\n \"\"\"\n Return changes since time X as a map in JSON {LineNum:\n (ID,timestamp,channel,name,value), ...} where num is from 0\n and up\n \n \"\"\"\n #return json.dumps(self.get_db().get_changes(since))\n\n res = {}\n \n i=0\n print(\"Time interval:\",start_time, stop_time)\n rows = self.get_db().get_changes(since, session=self.session, start_time=start_time, stop_time=stop_time)\n if rows:\n for (id, timestamp, paramid, value) in rows:\n try:\n value = float(value)\n except:\n pass # TODO: Do this nicer!\n\n res[i] = (id, timestamp, paramid, value)\n i += 1\n\n return json.dumps(res)\n\n def _send_html(self, html, mimetype=\"text/html\", response=200, content_range=None):\n \n # Only compress text if > 100 bytes\n if mimetype and mimetype.startswith(\"text\") and self._compress and len(html) > 100: \n encoding = \"gzip\"\n compressed = io.StringIO()\n zipped = gzip.GzipFile(mode=\"w\", fileobj=compressed, \n compresslevel=9)\n zipped.write(html)\n zipped.close()\n html = compressed.getvalue()\n else:\n encoding = None\n\n self.prepare_send(mimetype, len(html), encoding=encoding, \n response=response, content_range=content_range)\n self.wfile.write(html)\n self.wfile.close()\n \n\n \nclass WebServer(threading.Thread):\n\n def __init__(self, port, db, stop_event):\n threading.Thread.__init__(self)\n print(\"Starting WebServer on port %s\"%port)\n\n self.stop_event = stop_event\n \n self.log = API.get_log(\"WebGUI\")\n self.cfg = API.get_config(\"System.WebServer\")\n self.cfg.require([\"web_root\"])\n \n self.log.debug(\"Initializing WebServer\")\n self.server = MyWebServer(('0.0.0.0', int(port)), MyWebHandler)\n self.server.cfg = self.cfg\n \n self.server.root_cfg = API.get_config()\n \n self.server.db = db\n self.server.picture_supplier = None #PictureSupplier()\n\n try:\n from Instruments.TriOS.TriOS import DBDump\n #self.server.trios = DBDump(\"UAV/trios.sqlite\") # Replace with Postgres\n self.server.trios = DBDump(\"TriOS\") \n except:\n self.server.trios = None\n\n self.server._log_db = LogDB()\n self.server.log = self.log\n\n self.log.debug(\"WebServer initialized OK\")\n\n def run(self):\n while not self.stop_event.is_set():\n try:\n self.server.handle_request()\n except Exception as e:\n # Ignore these, Just means that there was no request\n # waiting for us\n pass\n\n self.log.info(\"Stopped\")\n\n def stop(self):\n print(\"Stopping\")\n self.running = False\n\n self.server.socket.close()\n\n\nif __name__ == \"__main__\":\n\n socket.setdefaulttimeout(5.0)\n \n\t\n #if len(sys.argv) == 2:\n # db = StatusDB(sys.argv[1])\n #else:\n # db = StatusDB()\n\n stop_event = threading.Event()\n if len(sys.argv) > 1:\n db = DBWrapper(status_db = sys.argv[1])\n else:\n db = DBWrapper()\n ws = WebServer(4321, db, stop_event)\n if \"--disable-pic\" in sys.argv:\n disablePic = True\n else:\n disablePic = False\n ws.start()\n \n print(\"WebServer running on port 4321\")\n try:\n input(\"Press ENTER to stop\")\n# while True:\n# time.sleep(10)\n except Exception as e:\n pass\n\n print(\"Stopping server\")\n stop_event.set()\n\n API.shutdown()\n \n", "repo_name": "Snarkdoof/cryocore", "sub_path": "CryoCore/GUI/Web/WebServer2.py", "file_name": "WebServer2.py", "file_ext": "py", "file_size_in_byte": 38089, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "cgitb.enable", "line_number": 22, "usage_type": "call"}, {"api_name": "Tools.TailLog.TailLog", "line_number": 89, "usage_type": "attribute"}, {"api_name": "Tools.TailLog", "line_number": 89, "usage_type": "name"}, {"api_name": "Tools.TailLog.TailLog.__init__", "line_number": 92, "usage_type": "call"}, {"api_name": "Tools.TailLog.TailLog", "line_number": 92, "usage_type": "attribute"}, {"api_name": "Tools.TailLog", "line_number": 92, "usage_type": "name"}, {"api_name": "Common.API.log_level_str.keys", "line_number": 144, "usage_type": "call"}, {"api_name": "Common.API.log_level_str", "line_number": 144, "usage_type": "attribute"}, {"api_name": "Common.API", "line_number": 144, "usage_type": "name"}, {"api_name": "Common.InternalDB.mysql", "line_number": 157, "usage_type": "name"}, {"api_name": "Common.API.get_log", "line_number": 163, "usage_type": "call"}, {"api_name": "Common.API", "line_number": 163, "usage_type": "name"}, {"api_name": "Common.API.get_config", "line_number": 164, "usage_type": "call"}, {"api_name": "Common.API", "line_number": 164, "usage_type": "name"}, {"api_name": "Common.InternalDB.mysql.__init__", "line_number": 174, "usage_type": "call"}, {"api_name": "Common.InternalDB.mysql", "line_number": 174, "usage_type": "name"}, {"api_name": "http.server.server", "line_number": 293, "usage_type": "attribute"}, {"api_name": "http.server", "line_number": 293, "usage_type": "name"}, {"api_name": "select.select", "line_number": 311, "usage_type": "call"}, {"api_name": "http.server.server", "line_number": 336, "usage_type": "attribute"}, {"api_name": "http.server", "line_number": 336, "usage_type": "name"}, {"api_name": "urllib.request.parse.unquote", "line_number": 366, "usage_type": "call"}, {"api_name": "urllib.request.parse", "line_number": 366, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 366, "usage_type": "name"}, {"api_name": "Common.API.get_log", "line_number": 388, "usage_type": "call"}, {"api_name": "Common.API", "line_number": 388, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 434, "usage_type": "call"}, {"api_name": "os.path", "line_number": 434, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 436, "usage_type": "call"}, {"api_name": "os.path", "line_number": 436, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 440, "usage_type": "call"}, {"api_name": "os.path", "line_number": 440, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 458, "usage_type": "call"}, {"api_name": "os.path", "line_number": 458, "usage_type": "attribute"}, {"api_name": "re.match", "line_number": 470, "usage_type": "call"}, {"api_name": "cgi.parse_header", "line_number": 487, "usage_type": "call"}, {"api_name": "cgi.parse_multipart", "line_number": 489, "usage_type": "call"}, {"api_name": "cgi.parse_qs", "line_number": 492, "usage_type": "call"}, {"api_name": "Common.API.get_config", "line_number": 519, "usage_type": "call"}, {"api_name": "Common.API", "line_number": 519, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 576, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 651, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 652, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 672, "usage_type": "call"}, {"api_name": "os.path", "line_number": 672, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 673, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 685, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 691, "usage_type": "call"}, {"api_name": "os.path", "line_number": 691, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 693, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 731, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 768, "usage_type": "call"}, {"api_name": "cgi.parse_qs", "line_number": 780, "usage_type": "call"}, {"api_name": "hashlib.sha1", "line_number": 812, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 814, "usage_type": "call"}, {"api_name": "Tools.HUD.HUDProvider", "line_number": 831, "usage_type": "call"}, {"api_name": "Tools.HUD", "line_number": 831, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 862, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 894, "usage_type": "call"}, {"api_name": "time.time", "line_number": 914, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 915, "usage_type": "call"}, {"api_name": "mimetypes.guess_type", "line_number": 928, "usage_type": "call"}, {"api_name": "os.path.getsize", "line_number": 938, "usage_type": "call"}, {"api_name": "os.path", "line_number": 938, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 979, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 990, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 1031, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 1038, "usage_type": "call"}, {"api_name": "gzip.GzipFile", "line_number": 1039, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 1054, "usage_type": "attribute"}, {"api_name": "threading.Thread.__init__", "line_number": 1057, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 1057, "usage_type": "attribute"}, {"api_name": "Common.API.get_log", "line_number": 1062, "usage_type": "call"}, {"api_name": "Common.API", "line_number": 1062, "usage_type": "name"}, {"api_name": "Common.API.get_config", "line_number": 1063, "usage_type": "call"}, {"api_name": "Common.API", "line_number": 1063, "usage_type": "name"}, {"api_name": "Common.API.get_config", "line_number": 1070, "usage_type": "call"}, {"api_name": "Common.API", "line_number": 1070, "usage_type": "name"}, {"api_name": "Instruments.TriOS.TriOS.DBDump", "line_number": 1078, "usage_type": "call"}, {"api_name": "socket.setdefaulttimeout", "line_number": 1107, "usage_type": "call"}, {"api_name": "threading.Event", "line_number": 1115, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 1116, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 1117, "usage_type": "attribute"}, {"api_name": "{'DBDump': 'Instruments.TriOS.TriOS.DBDump'}", "line_number": 1120, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 1121, "usage_type": "attribute"}, {"api_name": "Common.API.shutdown", "line_number": 1138, "usage_type": "call"}, {"api_name": "Common.API", "line_number": 1138, "usage_type": "name"}]} +{"seq_id": "39578693972", "text": "\r\n# ------------- Script for IHA assessment ------------ #\r\n# --Instituto de Pesquisas Hidraulicas - Hidrologia em Grande Escala (HGE)\r\n# --Author: Larissa de Castro Ribeiro (larissa.ribeirocr@gmail.com)\r\n# --Advisor: Dr. Rodrigo Cauduro Dias de Paiva\r\n# --Date: 19/11/2019\r\n# --Updated in: 04/03/2021\r\n\r\n# CONSIDERATIONS\r\n# IHA indices generated by this script were developed according to the\r\n# \"Indicator of Hydrologic Alteration Version 7.1 User's Manual\" by The Nature\r\n# Conservancy (2009) with the following modifications:\r\n\r\n# i) the discharges data are divided in hydrological years of maximum and minimum\r\n# for each river segment to calculate the indices;\r\n# ii) date information is transformed to angle in degrees to perform circular\r\n# statistics and obtain maximum and minimum hydrological year dates.\r\n# The alteration of maximum and minimum Julian days is calculated considering\r\n# 182,5 days as a 100% alteration, with standard deviation given in days and the\r\n# coefficient of variation being a ration of standard deviation by 182,5 days;\r\n# c) minimum discharge related indices were calculated considering the hydrological\r\n# year of minimums and maximum discharge related indices considered the\r\n#hydrological year of maximums\r\n\r\n\r\n# This script calculates the following IHA:\r\n#1 - Mean monthly discharge: M_jan, M_fev, ...\r\n#2 - Mean monthly discharge standard deviation: M_D_jan, M_D_fev,...\r\n#3 - Mean monthly discharge coefficient of variation: M_CV_jan, M_CV_fev, ...\r\n\r\n#4 - 1 day, 3 days, 30 days and 90 days minimum discharge: E_1_min1, E_1_min3, ...\r\n#5 - Standard deviation of 1 day minimum discharge: E_1_min1_D, E_1_min3_D\r\n#6 - Coefficient of variation of 1 day minimum discharge: E_1_min1_CV, E_1_min3_CV\r\n\r\n#7 - 1 day, 3 days, 30 days and 90 days maximum discharge: E_2_max1, E_2_max3 ...\r\n#8 - Standard deviation of 1 day maximum discharge: E_2_max1_D, E_2_max3_D\r\n#9 - Coefficient of variation of 1 day maximum discharge: E_2_max1_CV, E_2_max3_CV\r\n\r\n#10 - Date of minimum discharge: T_1\r\n#11 - Standard deviation of Date of minimum discharge (days): T_1_D\r\n#12 - Coefficient of variation of Date of minimum discharge (days): T_1_CV\r\n\r\n#13 - Date of maximum discharge: T_2\r\n#14 - Standard deviation of Date of maximum discharge (days): T_2_D\r\n#15 - Coefficient of variation of Date of maximum discharge (days): T_2_CV\r\n\r\n#16 - Ascension rate: G_1\r\n#17 - Standard deviation of ascension rate: G_1_D\r\n#18 - Coefficient of variation of ascension rate: G_1_CV\r\n\r\n#19 - Recession rate: G_2\r\n#20 - Standard deviation of recession rate: G_2_D\r\n#21 - Coefficient of variation of recession rate: G_2_CV\r\n\r\n#22 - Number of reversions: G_3\r\n#23 - Standard deviation of number of reversions: G_3_D\r\n#24 - Coefficient of variation of number of reversions: G_3_CV\r\n\r\n\r\n########################### Importing libraries ###########################\r\n\r\nimport pandas as pd\r\nimport datetime\r\nfrom scipy.stats import variation \r\nfrom scipy import stats\r\nfrom scipy.stats import circstd\r\nfrom scipy.stats import circvar\r\nimport numpy as np\r\nimport winsound\r\nfrom scipy.io import loadmat\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n######################################################\r\n### SECTION 1 - IMPORT DISCHARGE DATA ###\r\n######################################################\r\n# Input data are series of discharges in dataframe format;\r\n# rows are time intervals and columns are different river segments\r\n\r\n### CONVERTING INPUT FILE FROM .mat TO DataFrame ###\r\n##\r\n\r\nmat = loadmat(\"folder/discharge_data.mat\")\r\nmdata = mat['...']\r\n\r\ndf = 0\r\ndf = pd.DataFrame(mdata[:,:])\r\n\r\ndel mat\r\ndel mdata\r\n\r\n### CONVERTING INPUT FILE FROM .xls TO DataFrame ###\r\n##\r\n\r\n#df = pd.read_excel(r'../discharge_data.xlsx', engine='openpyxl')\r\n\r\n######################################################### \r\n### SECTION 2 - CREATING DATE INFORMATION ###\r\n#########################################################\r\n### Creating DataFrame in date format and number of days of discharge entries time step ###\r\n\r\n# start = INPUT THE DATE OF THE FIRST DISCHARGE ENTRY\r\nstart = datetime.datetime.strptime(\"01/01/1980\", \"%d/%m/%Y\").date()\r\n\r\nnumdays = len(df)\r\ndatelist = []\r\nfor x in range(0, numdays):\r\n datelist.append(start + datetime.timedelta(days=x))\r\n\r\n# Creating a DataFrame with days, date, discharges and a river segment\r\n##\r\n# Creating days list (time step)\r\nz = np.arange(len(df))\r\nz = z + 1\r\n\r\ndf.insert(0, 'IT', z)\r\n\r\ndias_contagem = list(df['IT'])\r\n\r\n############################################################\r\n### SECTION 3 - CREATING EMPTY MATRIX FOR INDICES ###\r\n############################################################\r\n\r\n########################### IHA MATRIX ###########################\r\n\r\nz = list(df)\r\ndel z[0]\r\n\r\niha = pd.DataFrame(columns=['M_jan','M_fev','M_mar','M_abr',\r\n 'M_mai','M_jun','M_jul','M_ago',\r\n 'M_set','M_out','M_nov','M_dez',\r\n 'M_D_jan','M_D_fev','M_D_mar','M_D_abr',\r\n 'M_D_mai','M_D_jun','M_D_jul','M_D_ago',\r\n 'M_D_set','M_D_out','M_D_nov','M_D_dez',\r\n 'M_CV_jan','M_CV_fev','M_CV_mar',\r\n 'M_CV_abr','M_CV_mai','M_CV_jun',\r\n 'M_CV_jul','M_CV_ago','M_CV_set',\r\n 'M_CV_out','M_CV_nov','M_CV_dez',\r\n 'E_1_min1','E_1_min3','E_1_min7',\r\n 'E_1_min30','E_1_min90',\r\n 'E_1_min1_D','E_1_min3_D','E_1_min7_D',\r\n 'E_1_min30_D','E_1_min90_D',\r\n 'E_1_min1_CV','E_1_min3_CV','E_1_min7_CV',\r\n 'E_1_min30_CV','E_1_min90_CV',\r\n 'E_2_max1','E_2_max3','E_2_max7',\r\n 'E_2_max30','E_2_max90',\r\n 'E_2_max1_D','E_2_max3_D','E_2_max7_D',\r\n 'E_2_max30_D','E_2_max90_D',\r\n 'E_2_max1_CV','E_2_max3_CV','E_2_max7_CV',\r\n 'E_2_max30_CV','E_2_max90_CV',\r\n 'T_1','T_1_D','T_1_CV',\r\n 'T_2','T_2_D','T_2_CV','G_1', \r\n 'G_2','G_3','G_1_D','G_2_D',\r\n 'G_3_D','G_1_CV','G_2_CV','G_3_CV','AnoH_Min','AnoH_Max'],index=z)\r\n\r\ndel x\r\ndel numdays\r\ndel start\r\n\r\n\r\n###################################################### \r\n### SECTION 4 - CALCULATION OF INDICES ###\r\n######################################################\r\n \r\n########################### LOOP FOR RIVER SEGMENTS ###########################\r\n#Calculates indices for each river segment of the input data\r\n#Converting segment discharge from column to list\r\n\r\nbefore = datetime.datetime.now().isoformat(timespec='minutes')\r\nbefore = pd.to_datetime(before) \r\n \r\nk=0\r\nfor k in range (54,len(z)):\r\n \r\n vazoes_trecho = list(df.iloc[:,k+1])\r\n \r\n matriz = 0\r\n matriz = pd.DataFrame({\"dia\": dias_contagem,\"data\": datelist,\"vazao\":vazoes_trecho})\r\n matriz['data'] = pd.to_datetime(matriz['data'])\r\n \r\n print(\"Calculando trecho \" + str(k+1) + \" de \" + str(len(df.columns)))\r\n\r\n\r\n ################## Determining the beginning of the hydrological year ##################\r\n # For minimum\r\n ##\r\n q = pd.DataFrame()\r\n q['data'] = matriz['data']\r\n q['data'] = q['data'].dt.year\r\n q= q.groupby('data').size()\r\n \r\n yearlist = 0\r\n \r\n # Here you must input the series of discharge starting date\r\n\r\n yearlist = [datetime.datetime.strptime(\"1980\", \"%Y\").year + index for index \r\n in range(len(q))] ##TODO colocar o ano inicial\r\n yearlist_df = pd.DataFrame({\"ano\": yearlist})\r\n yearlist_df['ano'] = pd.to_datetime(yearlist_df['ano'])\r\n \r\n anos_min = 0\r\n anos_min = pd.DataFrame(index=list(yearlist),\r\n columns = ['Data da vazao minima','Mes da vazao minima'])\r\n anos_min['Data da vazao minima'] = pd.to_datetime(anos_min['Data da vazao minima'])\r\n \r\n i = 0\r\n for i in range (0,len(yearlist)):\r\n ano1 = matriz.copy()\r\n ano1 = ano1.loc[(ano1['data'].dt.year==yearlist[i])]\r\n mini = ano1.copy()\r\n mini = mini.loc[(mini['vazao']==mini['vazao'].min())]\r\n \r\n if mini.size > 0:\r\n \r\n mini2 = mini.iloc[0] \r\n anos_min.at[yearlist[i],'Data da vazao minima'] = mini2['data']\r\n anos_min['Mes da vazao minima'] = anos_min['Data da vazao minima'].dt.month\r\n else:\r\n pass\r\n \r\n anos_min = anos_min.groupby('Mes da vazao minima').size().sort_values(ascending=False)\r\n mes_ano_min = anos_min.index[0] - 5\r\n \r\n if mes_ano_min <= 0:\r\n mes_ano_min = mes_ano_min+12\r\n mes_anterior = mes_ano_min - 1\r\n if mes_anterior == 0:\r\n mes_anterior = 12\r\n \r\n iha.iloc[k,81] = mes_ano_min\r\n \r\n # Deleting data outside of the hydrological year range\r\n \r\n matriz_min = 0\r\n matriz_min = matriz.copy()\r\n \r\n i = 0\r\n for i in range (0,365):\r\n while matriz_min['data'][matriz_min.index[i]].month!=mes_ano_min:\r\n matriz_min = matriz_min.drop(index=[matriz_min.index[i]],axis=1)\r\n break\r\n \r\n i=0 \r\n matriz_min2 = matriz_min.iloc[::-1] \r\n for i in range (0,365):\r\n while matriz_min2['data'][matriz_min2.index[i]].month!=mes_anterior:\r\n matriz_min2 = matriz_min2.drop(index=[matriz_min2.index[i]],axis=1)\r\n break\r\n \r\n # DataFrame with hydrological years of minimums\r\n matriz_min = matriz_min2.iloc[::-1]\r\n del(matriz_min2)\r\n \r\n # Hydrological year of maximums\r\n ## \r\n \r\n anos_max = 0\r\n anos_max = pd.DataFrame(index=list(yearlist),\r\n columns = ['Data da vazao maxima','Mes da vazao maxima'])\r\n anos_max['Data da vazao maxima'] = pd.to_datetime(anos_max['Data da vazao maxima'])\r\n \r\n i = 0\r\n for i in range (0,len(yearlist)):\r\n ano1 = matriz.copy()\r\n ano1 = ano1.loc[(ano1['data'].dt.year==yearlist[i])]\r\n maxi = ano1.copy()\r\n maxi = maxi.loc[(maxi['vazao']==maxi['vazao'].max())]\r\n \r\n if maxi.size > 0:\r\n \r\n maxi2 = maxi.iloc[0] \r\n anos_max.at[yearlist[i],'Data da vazao maxima'] = maxi2['data']\r\n anos_max['Mes da vazao maxima'] = anos_max['Data da vazao maxima'].dt.month\r\n else:\r\n pass \r\n \r\n anos_max = anos_max.groupby('Mes da vazao maxima').size().sort_values(ascending=False)\r\n mes_ano_max = anos_max.index[0]-5\r\n \r\n if mes_ano_max <= 0:\r\n mes_ano_max = mes_ano_max+12\r\n mes_anterior = mes_ano_max - 1\r\n if mes_anterior == 0:\r\n mes_anterior = 12\r\n \r\n iha.iloc[k,82] = mes_ano_max\r\n \r\n # Deleting data outside of the hydrological year range\r\n \r\n matriz_max = 0\r\n matriz_max = matriz.copy()\r\n \r\n i = 0\r\n for i in range (0,365):\r\n while matriz_max['data'][matriz_max.index[i]].month!=mes_ano_max:\r\n matriz_max = matriz_max.drop(index=[matriz_max.index[i]],axis=1)\r\n break\r\n \r\n matriz_max2 = matriz_max.iloc[::-1] \r\n i = 0 \r\n for i in range (0,365):\r\n while matriz_max2['data'][matriz_max2.index[i]].month!=mes_anterior:\r\n matriz_max2 = matriz_max2.drop(index=[matriz_max2.index[i]],axis=1)\r\n break\r\n \r\n # DataFrama with hydrological years of maximums\r\n matriz_max = matriz_max2.iloc[::-1]\r\n del(matriz_max2)\r\n \r\n ################## G1 - MEAN MAGNITUDE METRICS ##################\r\n ##\r\n # mean monthly discharge for each year\r\n \r\n mag_medias_AH = 0\r\n mag_medias_AH = pd.DataFrame(index = np.arange(len(yearlist)),\r\n columns=['jan','fev','mar','abr',\r\n 'mai','jun','jul','ago',\r\n 'set','out','nov','dez'])\r\n \r\n meses = 12\r\n i = 0\r\n j = 0\r\n for i in range (0,len(yearlist)):\r\n mes = matriz.loc[\r\n matriz['data'].dt.year == matriz.iloc[0,1].year+i\r\n ]\r\n for j in range (0,meses):\r\n mes_i = mes.loc[(mes['data'].dt.month==j+1)]\r\n mag_medias_AH.iloc[i,j] = mes_i['vazao'].mean()\r\n \r\n meses2 = 12\r\n j = 0\r\n for j in range (0,meses2):\r\n iha.iloc[k,j] = mag_medias_AH.iloc[:,j].mean()\r\n iha.iloc[k,j+12] = mag_medias_AH.iloc[:,j].std(skipna=True)\r\n iha.iloc[k,j+24] = mag_medias_AH.iloc[:,j].std(skipna=True\r\n )/mag_medias_AH.iloc[:,j].mean()\r\n \r\n ################## G2 - EXTREME MAGNITUDE METRICS ##################\r\n ##\r\n # for hydrological year of minimum\r\n \r\n yearlist2 = 0\r\n yearlist2 = matriz_min['data'].dt.year\r\n yearlist2 = pd.DataFrame(yearlist2)\r\n yearlist2 = yearlist2.groupby('data').size()\r\n \r\n mag_medias_AH_min = 0\r\n mag_medias_AH_min = pd.DataFrame(index = np.arange(len(yearlist2)-1),\r\n columns=['jan','fev','mar','abr',\r\n 'mai','jun','jul','ago',\r\n 'set','out','nov','dez'])\r\n \r\n # Calculating metrics for consecutive minimum discharges for a hydrological year of minimums\r\n\r\n mag_ext_AH_min = 0\r\n mag_ext_AH_min = pd.DataFrame(index = np.arange(len(yearlist2)-1),\r\n columns=['vazao minima de 1 dia',\r\n 'vazao minima de 3 dias',\r\n 'vazao minima de 7 dias',\r\n 'vazao minima de 30 dias',\r\n 'vazao minima de 90 dias'])\r\n \r\n ## Calculating timing for extreme minimum discharges\r\n ex_min = 0\r\n ex_min = pd.DataFrame(index = np.arange(len(yearlist2)-1),\r\n columns=['data', 'vazao', 'graus', 'dias no ano'])\r\n \r\n dias = 0\r\n dias = np.arange(0, len(ex_min))\r\n \r\n \r\n meses = 12\r\n \r\n try:\r\n i = 0\r\n j = 0\r\n for i in range (0,len(yearlist2)):\r\n mes = matriz_min.loc[\r\n matriz_min['data'].dt.year == matriz_min.iloc[0,1].year+i\r\n ]\r\n mes = mes.loc[mes['data'].dt.month >= mes_ano_min]\r\n mes2 = matriz_min.loc[\r\n matriz_min['data'].dt.year == matriz_min.iloc[0,1].year+i+1\r\n ]\r\n mes2 = mes2.loc[mes2['data'].dt.month < mes_ano_min]\r\n mes = mes.append(mes2)\r\n \r\n mag_ext_AH_min.iloc[i,0] = mes['vazao'].min()\r\n med3_mov_min = mes.copy()\r\n med3_mov_min['vazao'] = mes.vazao.rolling(window=3).mean()\r\n mag_ext_AH_min.iloc[i,1] = med3_mov_min['vazao'].min()\r\n med7_mov_min = mes.copy()\r\n med7_mov_min['vazao'] = mes.vazao.rolling(window=7).mean()\r\n mag_ext_AH_min.iloc[i,2] = med7_mov_min['vazao'].min()\r\n med30_mov_min = mes.copy()\r\n med30_mov_min['vazao'] = mes.vazao.rolling(window=30).mean()\r\n mag_ext_AH_min.iloc[i,3] = med30_mov_min['vazao'].min()\r\n med90_mov_min = mes.copy()\r\n med90_mov_min['vazao'] = mes.vazao.rolling(window=90).mean()\r\n mag_ext_AH_min.iloc[i,4] = med90_mov_min['vazao'].min()\r\n \r\n dias[i] = len(mes)\r\n \r\n for j in range (0,meses):\r\n if mes['vazao'].isna().sum().sum() < 364:\r\n mes_i = mes.loc[(mes['data'].dt.month==j+1)]\r\n mag_medias_AH_min.iloc[i, j] = mes_i['vazao'].mean()\r\n mini2 = mes.loc[(mes['vazao']==mes['vazao'].min())]\r\n mini2 = mini2.iloc[0]\r\n ex_min['data'][i] = mini2['data']\r\n ex_min['vazao'][i] = mini2['vazao']\r\n else:\r\n ex_min['data'][i] = np.nan\r\n ex_min['vazao'][i] = np.nan\r\n \r\n \r\n except IndexError:\r\n pass\r\n \r\n ex_min['dias no ano'] = 0\r\n ex_min['dias no ano'] = pd.DataFrame(dias)\r\n extrem = 5\r\n \r\n mag_ext_AH_min = mag_ext_AH_min.dropna()\r\n \r\n j=0\r\n for j in range (0,extrem):\r\n iha.iloc[k,j+36] = mag_ext_AH_min.iloc[:,j].mean()\r\n iha.iloc[k,j+41] = stats.tstd(mag_ext_AH_min.iloc[:,j])\r\n if (mag_ext_AH_min.iloc[:,j]).sum() != 0:\r\n iha.iloc[k,j+46] = variation(mag_ext_AH_min.iloc[:,j], axis = 0)\r\n else:\r\n iha.iloc[k,j+46] = np.nan\r\n \r\n # For hydrological year of maximums\r\n \r\n yearlist3 = 0\r\n yearlist3 = matriz_max['data'].dt.year\r\n yearlist3 = pd.DataFrame(yearlist3)\r\n yearlist3 = yearlist3.groupby('data').size()\r\n \r\n mag_medias_AH_max = 0\r\n mag_medias_AH_max = pd.DataFrame(index = np.arange(len(yearlist3)-1),\r\n columns=['jan','fev','mar','abr',\r\n 'mai','jun','jul','ago',\r\n 'set','out','nov','dez'])\r\n \r\n # Calculating metrics of consecutive maximum discharges for hydrological year of maximums\r\n mag_ext_AH_max = 0\r\n mag_ext_AH_max = pd.DataFrame(index = np.arange(len(yearlist3)-1),\r\n columns=['vazao maxima de 1 dia',\r\n 'vazao maxima de 3 dias',\r\n 'vazao maxima de 7 dias',\r\n 'vazao maxima de 30 dias',\r\n 'vazao maxima de 90 dias'])\r\n \r\n # Calculating timing of extreme for maximum discharge\r\n \r\n ex_max = 0\r\n ex_max = pd.DataFrame(index = np.arange(len(yearlist)-1),\r\n columns=['data', 'vazao', 'graus', 'dias no ano'])\r\n dias = 0\r\n dias = np.arange(0, len(ex_max))\r\n \r\n meses = 12\r\n \r\n try:\r\n j = 0\r\n i = 0\r\n for i in range (0,len(yearlist3)):\r\n mes = matriz_max.loc[\r\n matriz_max['data'].dt.year == matriz_max.iloc[0,1].year+i\r\n ]\r\n mes = mes.loc[mes['data'].dt.month >= mes_ano_max]\r\n mes2 = matriz_max.loc[\r\n matriz_max['data'].dt.year == matriz_max.iloc[0,1].year+i+1\r\n ]\r\n mes2 = mes2.loc[mes2['data'].dt.month < mes_ano_max]\r\n mes = mes.append(mes2)\r\n \r\n mag_ext_AH_max.iloc[i,0] = mes['vazao'].max()\r\n med3_mov_max = mes.copy()\r\n med3_mov_max['vazao'] = mes.vazao.rolling(window=3).mean()\r\n mag_ext_AH_max.iloc[i,1] = med3_mov_max['vazao'].max()\r\n med7_mov_max = mes.copy()\r\n med7_mov_max['vazao'] = mes.vazao.rolling(window=7).mean()\r\n mag_ext_AH_max.iloc[i,2] = med7_mov_max['vazao'].max()\r\n med30_mov_max = mes.copy()\r\n med30_mov_max['vazao'] = mes.vazao.rolling(window=30).mean()\r\n mag_ext_AH_max.iloc[i,3] = med30_mov_max['vazao'].max()\r\n med90_mov_max = mes.copy()\r\n med90_mov_max['vazao'] = mes.vazao.rolling(window=90).mean()\r\n mag_ext_AH_max.iloc[i,4] = med90_mov_max['vazao'].max()\r\n dias[i] = len(mes)\r\n \r\n for j in range (0,meses): \r\n if mes['vazao'].isna().sum().sum() < 364:\r\n mes_i = mes.loc[(mes['data'].dt.month==j+1)]\r\n mag_medias_AH_max.iloc[i, j] = mes_i['vazao'].mean()\r\n maxi2 = mes.loc[(mes['vazao']==mes['vazao'].min())]\r\n maxi2 = maxi2.iloc[0]\r\n ex_max['data'][i] = maxi2['data']\r\n ex_max['vazao'][i] = maxi2['vazao']\r\n else:\r\n ex_max['data'][i] = np.nan\r\n ex_max['vazao'][i] = np.nan\r\n \r\n \r\n except IndexError:\r\n pass\r\n \r\n ex_max['dias no ano'] = 0\r\n ex_max['dias no ano'] = pd.DataFrame(dias)\r\n extrem = 5\r\n \r\n mag_ext_AH_max = mag_ext_AH_max.dropna()\r\n \r\n j=0\r\n for j in range (0,extrem):\r\n iha.iloc[k,j+51] = mag_ext_AH_max.iloc[:,j].mean()\r\n iha.iloc[k,j+56] = stats.tstd(mag_ext_AH_max.iloc[:,j])\r\n iha.iloc[k,j+61] = variation(mag_ext_AH_max.iloc[:,j], axis = 0)\r\n \r\n \r\n ######################### G3 - TIMING OF EXTREMES #########################\r\n ##Calculating timing of extremes for minimum discharge\r\n \r\n #dates to degrees\r\n graus = 0\r\n graus = np.arange(0, len(ex_min)).astype(float)\r\n \r\n \r\n try:\r\n i = 0\r\n for i in range(0, len(ex_min)):\r\n if np.isnan(ex_min['vazao'][i]) == False:\r\n if ex_min['dias no ano'][i] == 365:\r\n if ex_min['data'][i].month == 1:\r\n graus[i] = (360/365)*ex_min['data'][i].day\r\n elif ex_min['data'][i].month == 2:\r\n graus[i] = (360/365)*(ex_min['data'][i].day+31)\r\n elif ex_min['data'][i].month == 3:\r\n graus[i] = (360/365)*(ex_min['data'][i].day+59)\r\n elif ex_min['data'][i].month == 4:\r\n graus[i] = (360/365)*(ex_min['data'][i].day+90)\r\n elif ex_min['data'][i].month == 5:\r\n graus[i] = (360/365)*(ex_min['data'][i].day+120)\r\n elif ex_min['data'][i].month == 6:\r\n graus[i] = (360/365)*(ex_min['data'][i].day+151)\r\n elif ex_min['data'][i].month == 7:\r\n graus[i] = (360/365)*(ex_min['data'][i].day+181)\r\n elif ex_min['data'][i].month == 8:\r\n graus[i] = (360/365)*(ex_min['data'][i].day+212)\r\n elif ex_min['data'][i].month == 9:\r\n graus[i] = (360/365)*(ex_min['data'][i].day+243)\r\n elif ex_min['data'][i].month == 10:\r\n graus[i] = (360/365)*(ex_min['data'][i].day+273)\r\n elif ex_min['data'][i].month == 11:\r\n graus[i] = (360/365)*(ex_min['data'][i].day+304)\r\n elif ex_min['data'][i].month == 12:\r\n graus[i] = (360/365)*(ex_min['data'][i].day+334)\r\n \r\n elif ex_min['dias no ano'][i] == 366:\r\n if ex_min['data'][i].month == 1:\r\n graus[i] = (360/366)*ex_min['data'][i].day\r\n elif ex_min['data'][i].month == 2:\r\n graus[i] = (360/366)*(ex_min['data'][i].day+31)\r\n elif ex_min['data'][i].month == 3:\r\n graus[i] = (360/366)*(ex_min['data'][i].day+60)\r\n elif ex_min['data'][i].month == 4:\r\n graus[i] = (360/366)*(ex_min['data'][i].day+91)\r\n elif ex_min['data'][i].month == 5:\r\n graus[i] = (360/366)*(ex_min['data'][i].day+121)\r\n elif ex_min['data'][i].month == 6:\r\n graus[i] = (360/366)*(ex_min['data'][i].day+152)\r\n elif ex_min['data'][i].month == 7:\r\n graus[i] = (360/366)*(ex_min['data'][i].day+182)\r\n elif ex_min['data'][i].month == 8:\r\n graus[i] = (360/366)*(ex_min['data'][i].day+213)\r\n elif ex_min['data'][i].month == 9:\r\n graus[i] = (360/366)*(ex_min['data'][i].day+244)\r\n elif ex_min['data'][i].month == 10:\r\n graus[i] = (360/366)*(ex_min['data'][i].day+274)\r\n elif ex_min['data'][i].month == 11:\r\n graus[i] = (360/366)*(ex_min['data'][i].day+305)\r\n elif ex_min['data'][i].month == 12:\r\n graus[i] = (360/366)*(ex_min['data'][i].day+335)\r\n \r\n else:\r\n print(\"One of the years has less than 365 days, check input data\")\r\n \r\n else:\r\n graus[i] = np.nan\r\n \r\n except IndexError:\r\n pass\r\n\r\n ex_min['graus'] = 0\r\n ex_min['graus'] = pd.DataFrame(graus)\r\n \r\n sin_mean = 0\r\n sin_mean = np.sum(np.sin(np.radians(ex_min['graus'])))/len(ex_min)\r\n cos_mean = 0\r\n cos_mean = np.sum(np.cos(np.radians(ex_min['graus'])))/len(ex_min)\r\n \r\n timing_min = 0\r\n timing_min = np.degrees(np.arctan2(sin_mean, cos_mean))\r\n if timing_min < 0:\r\n timing_min = timing_min + 360\r\n if timing_min == 0:\r\n timing_min = 360\r\n timing_min = int(np.round(timing_min*365/360))\r\n graus = graus[np.logical_not(np.isnan(graus))]\r\n timing_min_std = int(round(np.degrees(circstd(graus*np.pi/180))*365/360))\r\n timing_min_var = circvar(graus*np.pi/180)\r\n \r\n # transforming degrees to month-day\r\n if timing_min > 0 and timing_min < 32:\r\n timing_min = \"01-\"+str(timing_min)\r\n elif timing_min >= 32 and timing_min< 60:\r\n timing_min = \"02-\"+str(timing_min-31)\r\n elif timing_min >= 60 and timing_min< 91:\r\n timing_min = \"03-\"+str(timing_min-59)\r\n elif timing_min >= 91 and timing_min< 121:\r\n timing_min = \"04-\"+str(timing_min-90)\r\n elif timing_min >= 121 and timing_min< 152:\r\n timing_min = \"05-\"+str(timing_min-120)\r\n elif timing_min >= 152 and timing_min< 182:\r\n timing_min = \"06-\"+str(timing_min-151)\r\n elif timing_min >= 182 and timing_min< 213:\r\n timing_min = \"07-\"+str(timing_min-181)\r\n elif timing_min >= 213 and timing_min< 244:\r\n timing_min = \"08-\"+str(timing_min-212)\r\n elif timing_min >= 244 and timing_min< 274:\r\n timing_min = \"09-\"+str(timing_min-243)\r\n elif timing_min >= 274 and timing_min< 305:\r\n timing_min = \"10-\"+str(timing_min-273)\r\n elif timing_min >= 305 and timing_min< 335:\r\n timing_min = \"11-\"+str(timing_min-304)\r\n elif timing_min >= 335 and timing_min<= 365:\r\n timing_min = \"12-\"+str(timing_min-334)\r\n \r\n \r\n \r\n iha.iloc[k,66] = timing_min\r\n iha.iloc[k,67] = timing_min_std\r\n iha.iloc[k,68] = timing_min_var\r\n \r\n # Calculating timing of extreme for maximum discharge\r\n \r\n # dates to degrees\r\n graus = 0\r\n graus = np.arange(0, len(ex_max)).astype(float)\r\n \r\n \r\n try:\r\n i = 0\r\n for i in range(0, len(ex_max)):\r\n if np.isnan(ex_max['vazao'][i]) == False:\r\n if ex_max['dias no ano'][i] == 365:\r\n if ex_max['data'][i].month == 1:\r\n graus[i] = (360/365)*ex_max['data'][i].day\r\n elif ex_max['data'][i].month == 2:\r\n graus[i] = (360/365)*(ex_max['data'][i].day+31)\r\n elif ex_max['data'][i].month == 3:\r\n graus[i] = (360/365)*(ex_max['data'][i].day+59)\r\n elif ex_max['data'][i].month == 4:\r\n graus[i] = (360/365)*(ex_max['data'][i].day+90)\r\n elif ex_max['data'][i].month == 5:\r\n graus[i] = (360/365)*(ex_max['data'][i].day+120)\r\n elif ex_max['data'][i].month == 6:\r\n graus[i] = (360/365)*(ex_max['data'][i].day+151)\r\n elif ex_max['data'][i].month == 7:\r\n graus[i] = (360/365)*(ex_max['data'][i].day+181)\r\n elif ex_max['data'][i].month == 8:\r\n graus[i] = (360/365)*(ex_max['data'][i].day+212)\r\n elif ex_max['data'][i].month == 9:\r\n graus[i] = (360/365)*(ex_max['data'][i].day+243)\r\n elif ex_max['data'][i].month == 10:\r\n graus[i] = (360/365)*(ex_max['data'][i].day+273)\r\n elif ex_max['data'][i].month == 11:\r\n graus[i] = (360/365)*(ex_max['data'][i].day+304)\r\n elif ex_max['data'][i].month == 12:\r\n graus[i] = (360/365)*(ex_max['data'][i].day+334)\r\n \r\n elif ex_max['dias no ano'][i] == 366:\r\n if ex_max['data'][i].month == 1:\r\n graus[i] = (360/366)*ex_max['data'][i].day\r\n elif ex_max['data'][i].month == 2:\r\n graus[i] = (360/366)*(ex_max['data'][i].day+31)\r\n elif ex_max['data'][i].month == 3:\r\n graus[i] = (360/366)*(ex_max['data'][i].day+60)\r\n elif ex_max['data'][i].month == 4:\r\n graus[i] = (360/366)*(ex_max['data'][i].day+91)\r\n elif ex_max['data'][i].month == 5:\r\n graus[i] = (360/366)*(ex_max['data'][i].day+121)\r\n elif ex_max['data'][i].month == 6:\r\n graus[i] = (360/366)*(ex_max['data'][i].day+152)\r\n elif ex_max['data'][i].month == 7:\r\n graus[i] = (360/366)*(ex_max['data'][i].day+182)\r\n elif ex_max['data'][i].month == 8:\r\n graus[i] = (360/366)*(ex_max['data'][i].day+213)\r\n elif ex_max['data'][i].month == 9:\r\n graus[i] = (360/366)*(ex_max['data'][i].day+244)\r\n elif ex_max['data'][i].month == 10:\r\n graus[i] = (360/366)*(ex_max['data'][i].day+274)\r\n elif ex_max['data'][i].month == 11:\r\n graus[i] = (360/366)*(ex_max['data'][i].day+305)\r\n elif ex_max['data'][i].month == 12:\r\n graus[i] = (360/366)*(ex_max['data'][i].day+335)\r\n \r\n else:\r\n print(\"One of the years has less than 365 days, check input data\")\r\n \r\n else:\r\n graus[i] = np.nan\r\n \r\n except IndexError:\r\n pass\r\n \r\n \r\n ex_max['graus'] = 0\r\n ex_max['graus'] = pd.DataFrame(graus)\r\n \r\n sin_mean = 0\r\n sin_mean = np.sum(np.sin(np.radians(ex_max['graus'])))/len(ex_max)\r\n cos_mean = 0\r\n cos_mean = np.sum(np.cos(np.radians(ex_max['graus'])))/len(ex_max)\r\n \r\n timing_max = 0\r\n timing_max = np.degrees(np.arctan2(sin_mean, cos_mean))\r\n if timing_max < 0:\r\n timing_max = timing_max + 360\r\n if timing_max == 0:\r\n timing_max = 360\r\n timing_max = int(np.round(timing_max*365/360))\r\n graus = graus[np.logical_not(np.isnan(graus))]\r\n timing_max_std = int(round(np.degrees(circstd(graus*np.pi/180))*365/360))\r\n timing_max_var = circvar(graus*np.pi/180)\r\n \r\n # transforming degrees to month-day\r\n if timing_max > 0 and timing_max < 32:\r\n timing_max = \"01-\"+str(timing_max)\r\n elif timing_max >= 32 and timing_max< 60:\r\n timing_max = \"02-\"+str(timing_max-31)\r\n elif timing_max >= 60 and timing_max< 91:\r\n timing_max = \"03-\"+str(timing_max-59)\r\n elif timing_max >= 91 and timing_max< 121:\r\n timing_max = \"04-\"+str(timing_max-90)\r\n elif timing_max >= 121 and timing_max< 152:\r\n timing_max = \"05-\"+str(timing_max-120)\r\n elif timing_max >= 152 and timing_max< 182:\r\n timing_max = \"06-\"+str(timing_max-151)\r\n elif timing_max >= 182 and timing_max< 213:\r\n timing_max = \"07-\"+str(timing_max-181)\r\n elif timing_max >= 213 and timing_max< 244:\r\n timing_max = \"08-\"+str(timing_max-212)\r\n elif timing_max >= 244 and timing_max< 274:\r\n timing_max = \"09-\"+str(timing_max-243)\r\n elif timing_max >= 274 and timing_max< 305:\r\n timing_max = \"10-\"+str(timing_max-273)\r\n elif timing_max >= 305 and timing_max< 335:\r\n timing_max = \"11-\"+str(timing_max-304)\r\n elif timing_max >= 335 and timing_max<= 365:\r\n timing_max = \"12-\"+str(timing_max-334)\r\n \r\n \r\n iha.iloc[k,69] = timing_max\r\n iha.iloc[k,70] = timing_max_std\r\n iha.iloc[k,71] = timing_max_var\r\n \r\n ################## G5 - GRADIENT OF VARIABLES IN TIME ##################\r\n # Calculating ascension rate (GA), descent rate (GD) and reversion rate (RV)\r\n \r\n mag_G = 0\r\n mag_G = pd.DataFrame(index = np.arange(len(yearlist)), columns=['GA','GD','RV'])\r\n \r\n try:\r\n i = 0\r\n \r\n for i in range (0,len(mag_G)):\r\n j = 0\r\n \r\n ano_g = matriz.loc[\r\n matriz['data'].dt.year == matriz.iloc[0,1].year+i]\r\n ano_g['GA'] = 0\r\n ano_g['GD'] = 0\r\n ano_g['GAD'] = 0\r\n ano_g['rev'] = 0\r\n \r\n \r\n ano_g['GAD'] = ano_g['vazao']-ano_g['vazao'].shift(1)\r\n ano_g['GD'] = np.where(ano_g['GAD']<0,ano_g['GAD'],0)\r\n ano_g['GA'] = np.where(ano_g['GAD']>0,ano_g['GAD'],0)\r\n ano_g['rev'] = np.where(\r\n (ano_g['GAD']*ano_g['GAD'].shift(-1)) < 0,1,0\r\n )\r\n \r\n ano_g.iloc[0,3] = 0\r\n ano_g.iloc[0,4] = 0\r\n mag_G.iloc[i,0] = sum(ano_g['GA'])/(len(ano_g) -\r\n ano_g['GA'].isin([0]).sum())\r\n mag_G.iloc[i,1] = sum(-ano_g['GD'])/(len(ano_g) -\r\n ano_g['GD'].isin([0]).sum())\r\n mag_G.iloc[i,2] = sum(ano_g['rev'])\r\n \r\n except IndexError:\r\n pass\r\n \r\n # Filling the IHA matrix with rates values\r\n mag_G = mag_G.dropna()\r\n \r\n iha.iloc[k,72] = mag_G['GA'].mean()\r\n iha.iloc[k,73] = mag_G['GD'].mean()\r\n iha.iloc[k,74] = mag_G['RV'].mean()\r\n \r\n iha.iloc[k,75] = stats.tstd(mag_G['GA'])\r\n iha.iloc[k,76] = stats.tstd(mag_G['GD'])\r\n iha.iloc[k,77] = stats.tstd(mag_G['RV'])\r\n \r\n iha.iloc[k,78] = variation(mag_G['GA'])\r\n iha.iloc[k,79] = variation(mag_G['GD'])\r\n iha.iloc[k,80] = variation(mag_G['RV'])\r\n \r\n \r\n##############################################################################\r\n \r\nafter = datetime.datetime.now().isoformat(timespec='minutes')\r\nafter = pd.to_datetime(after) \r\ntempo_execucao = after-before\r\nprint(tempo_execucao)\r\n\r\nduration = 1000 # milliseconds\r\nfreq = 440 # Hz\r\nwinsound.Beep(freq, duration)\r\n\r\n\r\n########################## END ###########################\r\n \r\n", "repo_name": "Larissacr/hydrological_signatures", "sub_path": "python_IHA.py", "file_name": "python_IHA.py", "file_ext": "py", "file_size_in_byte": 34765, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "25", "api": [{"api_name": "warnings.filterwarnings", "line_number": 72, "usage_type": "call"}, {"api_name": "scipy.io.loadmat", "line_number": 83, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 87, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 103, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 103, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 113, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 129, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 169, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 169, "usage_type": "attribute"}, {"api_name": "pandas.to_datetime", "line_number": 170, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 178, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 179, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 187, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 196, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 196, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 198, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 199, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 202, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 204, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 258, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 260, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 315, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 315, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 345, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 349, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 349, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 357, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 357, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 366, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 366, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 370, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 414, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 415, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 422, "usage_type": "call"}, {"api_name": "scipy.stats.tstd", "line_number": 430, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 430, "usage_type": "name"}, {"api_name": "scipy.stats.variation", "line_number": 432, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 434, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 440, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 444, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 444, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 451, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 451, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 461, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 461, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 464, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 506, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 507, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 514, "usage_type": "call"}, {"api_name": "scipy.stats.tstd", "line_number": 522, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 522, "usage_type": "name"}, {"api_name": "scipy.stats.variation", "line_number": 523, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 531, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 537, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 594, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 600, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 603, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 603, "usage_type": "call"}, {"api_name": "numpy.radians", "line_number": 603, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 605, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 605, "usage_type": "call"}, {"api_name": "numpy.radians", "line_number": 605, "usage_type": "call"}, {"api_name": "numpy.degrees", "line_number": 608, "usage_type": "call"}, {"api_name": "numpy.arctan2", "line_number": 608, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 613, "usage_type": "call"}, {"api_name": "numpy.logical_not", "line_number": 614, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 614, "usage_type": "call"}, {"api_name": "numpy.degrees", "line_number": 615, "usage_type": "call"}, {"api_name": "scipy.stats.circstd", "line_number": 615, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 615, "usage_type": "attribute"}, {"api_name": "scipy.stats.circvar", "line_number": 616, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 616, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 654, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 660, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 717, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 724, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 727, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 727, "usage_type": "call"}, {"api_name": "numpy.radians", "line_number": 727, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 729, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 729, "usage_type": "call"}, {"api_name": "numpy.radians", "line_number": 729, "usage_type": "call"}, {"api_name": "numpy.degrees", "line_number": 732, "usage_type": "call"}, {"api_name": "numpy.arctan2", "line_number": 732, "usage_type": "call"}, {"api_name": "numpy.round", "line_number": 737, "usage_type": "call"}, {"api_name": "numpy.logical_not", "line_number": 738, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 738, "usage_type": "call"}, {"api_name": "numpy.degrees", "line_number": 739, "usage_type": "call"}, {"api_name": "scipy.stats.circstd", "line_number": 739, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 739, "usage_type": "attribute"}, {"api_name": "scipy.stats.circvar", "line_number": 740, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 740, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 777, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 777, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 794, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 795, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 796, "usage_type": "call"}, {"api_name": "scipy.stats.tstd", "line_number": 818, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 818, "usage_type": "name"}, {"api_name": "scipy.stats.tstd", "line_number": 819, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 819, "usage_type": "name"}, {"api_name": "scipy.stats.tstd", "line_number": 820, "usage_type": "call"}, {"api_name": "scipy.stats", "line_number": 820, "usage_type": "name"}, {"api_name": "scipy.stats.variation", "line_number": 822, "usage_type": "call"}, {"api_name": "scipy.stats.variation", "line_number": 823, "usage_type": "call"}, {"api_name": "scipy.stats.variation", "line_number": 824, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 829, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 829, "usage_type": "attribute"}, {"api_name": "pandas.to_datetime", "line_number": 830, "usage_type": "call"}, {"api_name": "winsound.Beep", "line_number": 836, "usage_type": "call"}]} +{"seq_id": "72374898931", "text": "from behave import given, when, use_step_matcher\nfrom behave.runner import Context\n\nfrom features.steps.selenium_steps import click\n\nuse_step_matcher(\"parse\")\n\n\n@given(\"I click the menu item {menu_item}\")\n@when(\"I click the menu item {menu_item}\")\ndef click_menu_item(context: Context, menu_item: str):\n if context.selenium.is_mobile:\n hamburger_menu_xpath = \"//span[contains(@class, 'navbar-toggler-icon')]\"\n click(context, hamburger_menu_xpath)\n\n xpath = f\"//a[contains(@class, 'nav-link') and contains(text(), '{menu_item}')]\"\n click(context, xpath)\n", "repo_name": "Zettafi/brain-conductor", "sub_path": "features/steps/nav.py", "file_name": "nav.py", "file_ext": "py", "file_size_in_byte": 576, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "behave.use_step_matcher", "line_number": 6, "usage_type": "call"}, {"api_name": "behave.runner.Context", "line_number": 11, "usage_type": "name"}, {"api_name": "features.steps.selenium_steps.click", "line_number": 14, "usage_type": "call"}, {"api_name": "features.steps.selenium_steps.click", "line_number": 17, "usage_type": "call"}, {"api_name": "behave.given", "line_number": 9, "usage_type": "call"}, {"api_name": "behave.when", "line_number": 10, "usage_type": "call"}]} +{"seq_id": "17743130009", "text": "#LeakyFaucet Server SMS Caller v1.3.0\n#Written: Twilio Support with a few modifications by Mr.Waterhouse\n#May 10, 2023\n#\n#This is script 3 of 4 required on the server side of LeakyFaucet.\n#\n#This script is called by the Filemon script and fed the phone number for messaging.\n#This script is directly from Twilio support and I've just modified a few things.\n#\n#This script will check an authorized number list before making the SMS API call.\n#If a number is presented that is not authorized, no SMS call occurs and the number is logged.\n#\n# Download the helper library from https://www.twilio.com/docs/python/install\n\n#Import required modules\nimport os\nfrom twilio.rest import Client\nimport sys\nimport time\nimport subprocess\nfrom datetime import datetime\n\n# Find your Account SID and Auth Token at twilio.com/console\naccount_sid = os.environ['TWILIO_ACCOUNT_SID'] #Get your SID from Twilio account and use /etc/profile.d/*.sh file to export as variable\nauth_token = os.environ['TWILIO_AUTH_TOKEN'] #Get your TOKEN from Twilio account and use /etc/profile.d/*.sh file to export as variable\ntwilio_num = os.environ['TWILIO_PHONE_SENDER'] #Get your NUMBER from Twilio account and use /etc/profile.d/*.sh file to export as variable\nclient = Client(account_sid, auth_token)\n\n#Assign command-line arguments to variables. These are passed by the filemon script\nphone_num = sys.argv[1]\nsession = sys.argv[2]\nverify_mode = sys.argv[3]\nprint(phone_num)\nprint(session)\nprint(verify_mode)\n\n#Assign message body variables\ncontact_msg = \"Leaky Faucet contacted! I'll let you know how you did in 3 minutes. SessionID: \"\nverify_msg = \" additional line(s) of data received after 3 minutes.\"\n\n#Assign SMS call log files\nwhitelist_file = \"/home/ubuntu/lfauth/lf_phone.auth\" #If phone_num is not in this file, it will not send SMS\nunauthorized_file = \"/home/ubuntu/lflog/lf_unauthAttempts.log\" #All unauthorized attempts will be logged here.\nsmsSent_file = \"/home/ubuntu/lflog/lf_smsSent.log\" #All authorized attempts will be logged here.\ntimeStamp = datetime.now()\nsession_dir = \"/home/ubuntu/lfdata/lf_exfil/\"\n\n#Read an external list of 'authorized' phone numbers and assign the contents to a variable\nwith open(whitelist_file) as f:\n phonewhitelist = [line.strip() for line in f]\n\n#Check if the phone_num is in the whitelist\nif phone_num in phonewhitelist and verify_mode == \"0\":\n # send message if phone_num is whitelisted\n message = client.messages \\\n .create(\n body=str(contact_msg) + str(session), #\"Call a plumber because you've got a leak!\",\n from_=twilio_num,\n to='+' + phone_num\n )\n print(message.sid)\n\n # write to the sms message sent log file if phone_num is whitelisted\n with open(smsSent_file, 'a') as f:\n f.write(str(timeStamp) + ' ' + str(phone_num) + ' was sent a message.\\n')\n\nelse:\n # write to the unauthAttempts.log file if phone_num is not whitelisted\n with open(unauthorized_file, 'a') as f:\n f.write(str(timeStamp) + ' ' + str(phone_num) + ' attempted to receive messages.\\n')\n\n#Check if the script is in verify mode, if so run the following\nif verify_mode == \"1\":\n #What 3 minutes before validating data received\n time.sleep(180)\n session_val = str(session_dir) + str(session) + \".txt\"\n #Read how many lines are in the session file\n with open(session_val, 'r') as file:\n session_data = sum(1 for line in file)\n session_data = session_data - 1 #This is so we don't count the phone number as data.\n \n # send message with verification results\n message = client.messages \\\n .create(\n body=\"SessionID: \" + str(session) + \" had \" + str(session_data) + str(verify_msg), #\"Call a plumber because you've got a leak!\",\n from_=twilio_num,\n to='+' + phone_num\n )\n print(message.sid)\n\n # write to the sms message sent log file that verification was invoked\n with open(smsSent_file, 'a') as f:\n f.write(str(timeStamp) + ' ' + str(phone_num) + ' verification process invoked.\\n')", "repo_name": "MrWaterhouse/leakyfaucet", "sub_path": "Server/lf_sms.py", "file_name": "lf_sms.py", "file_ext": "py", "file_size_in_byte": 4158, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "os.environ", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 26, "usage_type": "attribute"}, {"api_name": "twilio.rest.Client", "line_number": 27, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 30, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 31, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 32, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 45, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 45, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 75, "usage_type": "call"}]} +{"seq_id": "3322284802", "text": "from simso.core import Model\nfrom tools.fitness import Fitness\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\n\nclass Results():\n\n def __init__(self):\n self.dictOfIterationToGenerationList = {}\n self.graphDataList = []\n\n def insertNewGeneration(self, iteration, chromosomeGenerationList):\n self.dictOfIterationToGenerationList[iteration] = chromosomeGenerationList\n\n def setOptimalChromosome(self, optimalChromosome):\n self.optimalChromosome = optimalChromosome\n\n # Called by default runs.\n @staticmethod\n def outputDefResults(args,model):\n \n ### Grab Metadata\n outputPath = args.resultsFilePath\n configuration = args.configFileNames[args.currentConfigIdx]\n scheduler = args.schedNames[args.currentSchedIdx]\n\n if(os.path.exists(outputPath)):\n outputFile = open(outputPath, 'a')\n if(not os.path.exists(outputPath)):\n headerString = ('Configuration,'\n 'Scheduler,'\n 'Deadlines Exceeded,'\n 'Pre-emptions,'\n 'Migrations,'\n 'NormalizeLaxity,'\n 'FitnessScore,'\n 'Scheduler Overhead,' \n 'Activate Overhead\\n')\n outputFile = open(outputPath, 'w+')\n outputFile.write(headerString)\n\n de = model.results.total_exceeded_count\n pre = model.results.total_preemptions\n mig = model.results.total_migrations\n nl = Fitness.getAverageNormalizedLaxity(model)\n fs = Fitness.getFitnessScoreStatic(de,pre,mig)\n so = model.results.scheduler.schedule_overhead\n ao = model.results.scheduler.activate_overhead\n\n resultString = (f'{configuration},{scheduler},'\n f'{de},{pre},{mig},{nl},{fs},{so},{ao}\\n')\n outputFile.write(resultString)\n\n\n #Used for deubgging/testing\n def print_results(self,fitness):\n print(\"Total Migrations: \" + str(model.results.total_migrations))\n print(\"Total Pre-emptions: \" + str(model.results.total_preemptions))\n print(\"Total Exceeded Count: \" + str(model.results.total_exceeded_count))\n\n # Called by GA runs\n @staticmethod\n def outputStatsForRun(organism,args):\n with open(args.pklFilePath,'wb') as f:\n pickle.dump(organism, f)\n\n # grab metadata\n outputPath = organism.metadataDict['ResultsFilePath']\n configuration = organism.metadataDict['ConfigFile']\n scheduler = organism.metadataDict['SchedulerName']\n\n # setup output file\n outputFile = None\n if(os.path.exists(outputPath)): # if file exists, append\n outputFile = open(outputPath, 'a')\n else:\n outputFile = open(outputPath, 'w+') # if doesn't exist make new one\n headerString = \"Generation,Deadlines Missed,Preemptions,Migrations,Fitness Score\\n\"\n outputFile.write(headerString)\n \n # write metadata to line in output file\n outputFile.write(f'{configuration},{scheduler},'\n f'TotalChrom{organism.numberOfChromosomes},MR{organism.mutationRate},'\n f'{args.selection},{args.crossover},{args.cke}\\n')\n \n fsData = []\n for idx,bestChromList in enumerate(organism.optimalChromList):\n bestChrom = bestChromList[0]\n gen = idx+1\n dm = bestChrom.fitness.metricToVal['Total Exceeded Count'][idx]\n pr = bestChrom.fitness.metricToVal['Total Preemptions'][idx]\n mi = bestChrom.fitness.metricToVal['Total Migrations'][idx]\n fs = bestChrom.fitness.metricToVal['Fitness Score'][idx]\n printStr = f\"{gen},{dm},{pr},{mi},{fs}\\n\"\n outputFile.write(printStr)\n fsData.append(fs)\n #self.graphDataList.append(fsData)\n \n @staticmethod\n def showGraph():\n legendLabels = ['100 Chromosomes, 0.5 MR',\n '100 Chromosomes, 1.0 MR',\n '100 Chromosomes, 1.5 MR']\n\n data05 = []\n data10 = []\n data15 = []\n x_gens = np.arange(20)\n\n plt.plot(x_gens, data05)\n plt.plot(x_gens, data10)\n plt.plot(x_gens, data15)\n\n plt.legend(['0.5 MR', '1.0 MR', '1.5 MR'], loc='upper left');\n plt.xlabel('Generations');\n plt.ylabel('Fitness Score');\n plt.show(block=False);\n input('press to continue');\n", "repo_name": "nicholas-botzer/FrogScheduling", "sub_path": "tools/results.py", "file_name": "results.py", "file_ext": "py", "file_size_in_byte": 4539, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "os.path.exists", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "tools.fitness.Fitness.getAverageNormalizedLaxity", "line_number": 47, "usage_type": "call"}, {"api_name": "tools.fitness.Fitness", "line_number": 47, "usage_type": "name"}, {"api_name": "tools.fitness.Fitness.getFitnessScoreStatic", "line_number": 48, "usage_type": "call"}, {"api_name": "tools.fitness.Fitness", "line_number": 48, "usage_type": "name"}, {"api_name": "pickle.dump", "line_number": 67, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path", "line_number": 76, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 112, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 112, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 113, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 117, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 117, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 118, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}]} +{"seq_id": "24214788659", "text": "import torch\nimport pytorch_lightning\nfrom pytorch_lightning import LightningDataModule, LightningModule, Trainer\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom NAFNet import NAFNet\nfrom STN import SpatialTransformer,gradient_loss\nfrom timm.scheduler.cosine_lr import CosineLRScheduler\nfrom losses import L1_Charbonnier_loss,LCC\nfrom torch.utils.data import DataLoader \nfrom datasets import Build_dataset\nimport wandb\nfrom pytorch_lightning.loggers import WandbLogger\nimport argparse\nfrom torchmetrics.functional import structural_similarity_index_measure as SSIM\nfrom torchmetrics.functional import peak_signal_noise_ratio as PSNR\n# from torchmetrics.functional import dice as DICE\nfrom Metric import DistributedMetricSum\n\nclass LightningModel(LightningModule):\n def __init__(self,args):\n super().__init__()\n self.args = args\n self.DenoiseModel = NAFNet(img_channel=1, width=32, middle_blk_num=12,\n enc_blk_nums=[2, 2, 4, 8], dec_blk_nums=[2, 2, 2, 2])\n self.RegistrationModel = SpatialTransformer(channels=1)\n self.lr = self.args.lr\n self.gradient_loss = gradient_loss\n self.similarity = LCC()\n self.selfloss = L1_Charbonnier_loss()#torch.nn.MSELoss()#\n self.crossloss = L1_Charbonnier_loss()\n # Important: This property activates manual optimization.\n self.automatic_optimization = False\n self.train_dataset,self.val_dataset = Build_dataset(root_path=args.path_root) ## M4raw old version need to change\n self.Metrics_ssim = DistributedMetricSum() \n self.Metrics_psnr = DistributedMetricSum()\n self.Metrics_lcc = DistributedMetricSum()\n # self.show_tag = True\n def forward(self, x,ref):\n x = self.DenoiseModel(x)\n grid,offset = self.RegistrationModel(x,ref)\n x = self.RegistrationModel.warp(x,grid)\n return x\n\n def training_step(self, batch, batch_idx):\n D_opt, R_opt = self.optimizers()\n x_noise, x_clean,y_noise,y_clean = batch\n \n x_out = self.DenoiseModel(x_noise)\n y_out = self.DenoiseModel(y_noise)\n selfloss = self.selfloss(x_out,x_clean) + self.selfloss(y_out,y_clean)\n\n\n grid_y, offset_y = self.RegistrationModel(y_clean,x_clean)\n y_reg = self.RegistrationModel.warp(y_clean,grid_y)\n\n\n grid_x, offset_x = self.RegistrationModel(x_clean, y_clean)\n x_reg = self.RegistrationModel.warp(x_clean, grid_x)\n \n crossloss = self.crossloss(x_out,y_reg.detach()) + self.crossloss(y_out,x_reg.detach())\n ##########################\n # Optimize DenoiseModel #\n ########################## \n D_loss = 2 * selfloss + crossloss\n D_opt.zero_grad()\n self.manual_backward(D_loss,retain_graph=True) \n\n similarity_loss = self.similarity(y_reg,x_clean) + self.similarity(x_reg,y_clean)\n smooth_loss = self.gradient_loss(offset_y) + self.gradient_loss(offset_x)\n \n ######################\n # Optimize RegistrationModel #\n ######################\n R_loss = similarity_loss + 1000 * smooth_loss\n R_opt.zero_grad()\n self.manual_backward(R_loss,retain_graph=True)\n D_opt.step() \n R_opt.step() ##这个BUG难了我两个钟,特此记录一下\n \n \n if self.global_step%1000==0:\n x_n = torch.einsum('chw->hwc', x_noise[0].detach().cpu()).numpy()\n x_b = torch.einsum('chw->hwc', x_clean[0].detach().cpu()).numpy()\n x_o = torch.einsum('chw->hwc', x_out[0].detach().cpu()).numpy()\n\n y_b = torch.einsum('chw->hwc', y_noise[0].detach().cpu()).numpy()\n y_o = torch.einsum('chw->hwc', y_out[0].detach().cpu()).numpy()\n y_r = torch.einsum('chw->hwc', y_reg[0].detach().cpu()).numpy()\n\n self.logger.experiment.log({\"x_noise\":wandb.Image(x_n, caption=\"x_noise\"),\n \"x_target\":wandb.Image(x_b, caption=\"x_target\"),\n \"x_out\":wandb.Image(x_o, caption=\"x_out\"),\n \"y_base\":wandb.Image(y_b, caption=\"y_base\"),\n \"y_out\":wandb.Image(y_o, caption=\"y_out\"),\n \"y_reg\":wandb.Image(y_r, caption=\"y_reg\")\n })\n \n self.log_dict({\"D_loss\": D_loss, \"R_loss\": R_loss}, prog_bar=True)\n \n def validation_step(self, batch, batch_idx):\n x_noise, x_clean,y_clean = batch\n\n grid_y, offset_y = self.RegistrationModel(y_clean,x_clean)\n y_reg = self.RegistrationModel.warp(y_clean,grid_y)\n lcc = 1-self.similarity(y_reg,x_clean)\n \n targets = (y_reg + x_clean)/2\n \n output = self.DenoiseModel(x_noise)\n \n ssim = SSIM(output,targets,data_range = 1.0)*lcc\n psnr = PSNR(output,targets,data_range = 1.0)*lcc\n self.Metrics_ssim(ssim)\n self.Metrics_psnr(psnr)\n self.Metrics_lcc(lcc)\n \n# if self.show_tag:\n# x_n = torch.einsum('chw->hwc', x_noise[0].detach()).cpu().numpy()\n# x_b = torch.einsum('chw->hwc', x_clean[0].detach()).cpu().numpy()\n# x_o = torch.einsum('chw->hwc', output[0].detach()).cpu().numpy()\n\n# y_b = torch.einsum('chw->hwc', targets[0].detach()).cpu().numpy()\n# y_r = torch.einsum('chw->hwc', y_reg[0].detach()).cpu().numpy()\n# y_i = torch.einsum('chw->hwc', y_noise[0].detach()).cpu().numpy()\n# self.logger.experiment.log({\"x_noise\":wandb.Image(x_n, caption=\"x_noise\"),\n# \"x_base\":wandb.Image(x_b, caption=\"x_base\"),\n# \"x_out\":wandb.Image(x_o, caption=\"x_out\"),\n# \"target\":wandb.Image(y_b, caption=\"target\"),\n# \"y_base\":wandb.Image(y_i, caption=\"y_base\"),\n# \"y_reg\":wandb.Image(y_r, caption=\"y_reg\")\n# })\n# self.show_tag = False\n \n\n \n def validation_epoch_end(self, outputs):\n ssim = self.Metrics_ssim.compute()\n psnr = self.Metrics_psnr.compute()\n lcc = self.Metrics_lcc.compute()\n self.log_dict({\"SSIM\": ssim,'PSNR':psnr,'LCC':lcc},prog_bar=True,sync_dist=True)\n \n self.Metrics_ssim.reset()\n self.Metrics_psnr.reset()\n self.Metrics_lcc.reset()\n # self.show_tag = True\n\n def configure_optimizers(self):\n D_opt = torch.optim.AdamW(self.DenoiseModel.parameters(), self.lr,weight_decay=0.,betas=(0.9, 0.9))\n R_opt = torch.optim.AdamW(self.RegistrationModel.parameters(), self.lr,weight_decay=0.,betas=(0.9, 0.9))\n D_lr_scheduler = CosineLRScheduler(\n D_opt,\n t_initial=self.args.num_epochs,\n cycle_mul=1.,\n lr_min=1e-7,\n warmup_lr_init=5e-7,\n warmup_t=self.args.warmup_epoch,\n cycle_limit=1,\n t_in_epochs=True,\n )\n R_lr_scheduler = CosineLRScheduler(\n R_opt,\n t_initial=self.args.num_epochs,\n cycle_mul=1.,\n lr_min=1e-7,\n warmup_lr_init=5e-7,\n warmup_t=self.args.warmup_epoch,\n cycle_limit=1,\n t_in_epochs=True,\n )\n \n return [D_opt, R_opt], [D_lr_scheduler,R_lr_scheduler]\n \n def lr_scheduler_step(self, scheduler, optimizer_idx, metric):\n pass\n \n def training_epoch_end(self, outputs):\n D_lr_scheduler,R_lr_scheduler = self.lr_schedulers()\n D_lr_scheduler.step(self.current_epoch)\n R_lr_scheduler.step(self.current_epoch)\n \n \n def train_dataloader(self):\n train_loader = DataLoader(self.train_dataset, batch_size=self.args.train_batchsize, shuffle=True, num_workers=self.args.num_workers,drop_last=True,pin_memory=self.args.pin_memory)\n return train_loader\n \n def val_dataloader(self):\n val_loader = DataLoader(self.val_dataset, batch_size=self.args.val_batchsize, shuffle=False, num_workers=self.args.num_workers,drop_last=False,pin_memory=self.args.pin_memory)\n return val_loader\n \n \nif __name__ == '__main__':\n parser = argparse.ArgumentParser('Train denoise with pytorch-lightning')\n\n parser.add_argument('--model_name',default='Denoise',type=str)\n parser.add_argument('--path_root',default='/data0/M4RawV1.5',type=str)\n parser.add_argument('--seed', default=42, type=int)\n parser.add_argument('--gpu_num', default=2, type=int)\n parser.add_argument('--use_pretrain', default=False, type=bool)\n parser.add_argument('--batch_dice', default=False, type=bool)\n parser.add_argument('--pin_memory', default=True, type=bool) \n parser.add_argument(\"--lr\", default=0.001, type=float)\n parser.add_argument('--num_epochs', default=50, type=int, help='Number of epochs of training.')\n parser.add_argument('--warmup_epoch', default=2, type=int)\n parser.add_argument('--train_batchsize', default=1, type=int)\n parser.add_argument('--val_batchsize', default=4, type=int)\n parser.add_argument('--sw_batchsize', default=4, type=int)\n parser.add_argument('--num_workers', default=2, type=int, help='Number of data loading workers per GPU.')\n parser.add_argument('--val_interval', default=50, type=int, help=\"Epoch frequency for validation.\")\n parser.add_argument('--checkpoint_path',default='',type=str)\n parser.add_argument('--resume',default=None,type=str)\n parser.add_argument('--wandbID',default=None,type=str)\n parser.add_argument('--find_unused_parameters', default=False, type=bool)\n parser.add_argument('opts',\n help=\"Modify config options using the command-line\",\n default=None,\n nargs=argparse.REMAINDER) \n\n args = parser.parse_args()\n if args.resume is not None:\n wandb_logger = WandbLogger(project=\"Denoise\",resume='allow',id=args.wandbID,)\n else:\n wandb_logger = WandbLogger(project=\"Denoise\",name =args.model_name,)\n \n pytorch_lightning.utilities.seed.seed_everything(seed=args.seed, workers=True)\n best_checkpoint_callback = ModelCheckpoint(\n save_top_k=1,\n monitor=\"PSNR\",\n mode=\"max\",\n dirpath=\"./checkpoint/\",\n filename=f\"{args.model_name}-best_metric_model\",\n )\n current_checkpoint_callback = ModelCheckpoint(dirpath=\"./checkpoint/\",\n filename='{epoch}',every_n_epochs=5,\n save_on_train_epoch_end =True)\n from pytorch_lightning.callbacks import ModelSummary\n model = LightningModel(args)\n if args.gpu_num >1:\n from pytorch_lightning.strategies import DDPStrategy\n# from pytorch_lightning.profilers import PyTorchProfiler\n\n# profiler = PyTorchProfiler(filename=\"perf-logs\")\n trainer = Trainer(max_epochs=args.num_epochs,\n devices=args.gpu_num,\n # gpus=args.gpu_num,\n accelerator=\"gpu\",\n strategy=DDPStrategy(find_unused_parameters=args.find_unused_parameters),\n #strategy=DDPStrategy(gradient_as_bucket_view=True),#'ddp_find_unused_parameters_false',#\n callbacks=[current_checkpoint_callback,best_checkpoint_callback,ModelSummary(max_depth=3)],\n logger=wandb_logger,\n check_val_every_n_epoch=args.val_interval,\n precision=32,\n log_every_n_steps=10,\n sync_batchnorm=True,\n num_sanity_val_steps=0,\n detect_anomaly=False,\n # limit_train_batches=1,\n # limit_val_batches=1,\n #profiler=profiler\n )\n else:\n trainer = Trainer(max_epochs=args.num_epochs,\n devices=args.gpu_num,\n # gpus=args.gpu_num,\n accelerator=\"gpu\",\n callbacks=[current_checkpoint_callback,best_checkpoint_callback,ModelSummary(max_depth=3)],\n logger=wandb_logger,\n check_val_every_n_epoch=args.val_interval,\n log_every_n_steps=20,\n num_sanity_val_steps=0,\n # auto_lr_find='lr',\n precision=32,\n detect_anomaly=False,\n # profiler=\"simple\",\n # limit_train_batches=5,\n # limit_val_batches=1,\n )\n\n # trainer.tune(model)\n\n trainer.fit(model,ckpt_path=args.resume)\n", "repo_name": "Breeze-Zero/MRI_Tools", "sub_path": "Denoise/Reg_N2N_M4Raw/train.py", "file_name": "train.py", "file_ext": "py", "file_size_in_byte": 12988, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pytorch_lightning.LightningModule", "line_number": 19, "usage_type": "name"}, {"api_name": "NAFNet.NAFNet", "line_number": 23, "usage_type": "call"}, {"api_name": "STN.SpatialTransformer", "line_number": 25, "usage_type": "call"}, {"api_name": "STN.gradient_loss", "line_number": 27, "usage_type": "name"}, {"api_name": "losses.LCC", "line_number": 28, "usage_type": "call"}, {"api_name": "losses.L1_Charbonnier_loss", "line_number": 29, "usage_type": "call"}, {"api_name": "losses.L1_Charbonnier_loss", "line_number": 30, "usage_type": "call"}, {"api_name": "datasets.Build_dataset", "line_number": 33, "usage_type": "call"}, {"api_name": "Metric.DistributedMetricSum", "line_number": 34, "usage_type": "call"}, {"api_name": "Metric.DistributedMetricSum", "line_number": 35, "usage_type": "call"}, {"api_name": "Metric.DistributedMetricSum", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.einsum", "line_number": 82, "usage_type": "call"}, {"api_name": "torch.einsum", "line_number": 83, "usage_type": "call"}, {"api_name": "torch.einsum", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.einsum", "line_number": 86, "usage_type": "call"}, {"api_name": "torch.einsum", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.einsum", "line_number": 88, "usage_type": "call"}, {"api_name": "wandb.Image", "line_number": 90, "usage_type": "call"}, {"api_name": "wandb.Image", "line_number": 91, "usage_type": "call"}, {"api_name": "wandb.Image", "line_number": 92, "usage_type": "call"}, {"api_name": "wandb.Image", "line_number": 93, "usage_type": "call"}, {"api_name": "wandb.Image", "line_number": 94, "usage_type": "call"}, {"api_name": "wandb.Image", "line_number": 95, "usage_type": "call"}, {"api_name": "torchmetrics.functional.structural_similarity_index_measure", "line_number": 111, "usage_type": "call"}, {"api_name": "torchmetrics.functional.peak_signal_noise_ratio", "line_number": 112, "usage_type": "call"}, {"api_name": "torch.optim.AdamW", "line_number": 148, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 148, "usage_type": "attribute"}, {"api_name": "torch.optim.AdamW", "line_number": 149, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 149, "usage_type": "attribute"}, {"api_name": "timm.scheduler.cosine_lr.CosineLRScheduler", "line_number": 150, "usage_type": "call"}, {"api_name": "timm.scheduler.cosine_lr.CosineLRScheduler", "line_number": 160, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 183, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 187, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 192, "usage_type": "call"}, {"api_name": "argparse.REMAINDER", "line_number": 216, "usage_type": "attribute"}, {"api_name": "pytorch_lightning.loggers.WandbLogger", "line_number": 220, "usage_type": "call"}, {"api_name": "pytorch_lightning.loggers.WandbLogger", "line_number": 222, "usage_type": "call"}, {"api_name": "pytorch_lightning.utilities.seed.seed_everything", "line_number": 224, "usage_type": "call"}, {"api_name": "pytorch_lightning.utilities", "line_number": 224, "usage_type": "attribute"}, {"api_name": "pytorch_lightning.callbacks.ModelCheckpoint", "line_number": 225, "usage_type": "call"}, {"api_name": "pytorch_lightning.callbacks.ModelCheckpoint", "line_number": 232, "usage_type": "call"}, {"api_name": "pytorch_lightning.Trainer", "line_number": 242, "usage_type": "call"}, {"api_name": "pytorch_lightning.strategies.DDPStrategy", "line_number": 246, "usage_type": "call"}, {"api_name": "pytorch_lightning.callbacks.ModelSummary", "line_number": 248, "usage_type": "call"}, {"api_name": "pytorch_lightning.Trainer", "line_number": 261, "usage_type": "call"}, {"api_name": "pytorch_lightning.callbacks.ModelSummary", "line_number": 265, "usage_type": "call"}]} +{"seq_id": "27266620487", "text": "import numpy as np\nimport scipy.sparse as sp\n\ndef tanh_grading(start_value, end_value, num_points):\n \n# % a tanh function appears to be smoother at the edges of the grid\n\n center = np.min(start_value, end_value)+np.abs(end_value-start_value)/2;\n xspace = np.linspace(start_value, end_value, num_points);\n grading = np.tanh(xspace-center);\n return grading\n \n\ndef logarithmic_grading(h0, hf,N):\n # alpha: grading factor\n # N, number of steps to grade down to\n grading = np.logspace(np.log10(h0), np.log10(hf), N);\n return grading\n\n\ndef non_uniform_scaling_operator(dx_scale, dy_scale, dz_scale):\n \n# %operators which perform the row-wise scaling\n# %xs: 1D array containing dx scalings (only for forward differences\n#. these operators have to be applied to the individual dxf, dyf, operators...no global operators allowed\n \n # create grid of x and y points\n [Xs, Ys, Zs] = np.meshgrid(dx_scale, dy_scale, dz_scale, indexing = 'ij');\n M = np.prod(Xs.shape);\n \n Fsxi = sp.spdiags(1/Xs.flatten(order = 'F'), 0, M,M)\n Fsyi = sp.spdiags(1/Ys.flatten(order = 'F'), 0, M,M)\n Fszi = sp.spdiags(1/Zs.flatten(order = 'F'), 0, M,M) \n \n # might as well construct the conjugate grid.\n xc = (dx_scale + np.roll(dx_scale, -1))/2; #note differencesroll vs matlab's circshift\n yc = (dy_scale + np.roll(dy_scale, -1))/2;\n zc = (dz_scale + np.roll(dz_scale, -1))/2;\n [Xc, Yc, Zc] = np.meshgrid(xc, yc, zc, indexing='ij')\n\n Fsyi_conj = sp.spdiags(1/Yc.flatten(order = 'F'),0,M,M)\n Fsxi_conj = sp.spdiags(1/Xc.flatten(order = 'F'),0,M,M)\n Fszi_conj = sp.spdiags(1/Zc.flatten(order = 'F'),0,M,M)\n \n # return like this...\n return Fsxi, Fsyi, Fszi, Fsxi_conj, Fsyi_conj, Fszi_conj\n \n\n\n# this function must be flexible enough to accept a nonuniform grid in subsets of cartesian axes\ndef generate_nonuniform_scaling(\n Nft: np.array, \n drt: np.array, \n) -> list:\n \n #Nft: 1st column is x, 2nd column is y\n #drt: list of discretizations...normalized by some reference\n # we can express drt as proportions of the largest discretization\n # available on the grid...but seems inefficient\n # advantage is we don't have to rewrite the pml sfactor\n _, dimension = Nft.shape; #dimension is the number of coordinates we're dealing with\n dr_scalings = []\n num_regions = len(Nft)\n\n for i in range(dimension):\n Ni = np.sum(Nft[:,i])\n di_scale = np.ones(Ni)\n i0 = 0;\n for j in range(0, num_regions, 2):\n di_scale[i0:i0+Nft[j,i]] = drt[j,i];\n if(j== num_regions-1):\n i0 = i0+Nft[j,i];\n else:\n i0 = i0+Nft[j,i]+Nft[j+1,i];\n i0 = Nft[0,0] \n for j in range(1, num_regions, 2): # these are the transition regions\n di1 = drt[j-1,i]; di2 = drt[j+1,i];\n nit = Nft[j,i] \n grading_i = np.logspace(np.log10(di1), np.log10(di2), nit+1);\n di_scale[i0:i0+nit+1] = grading_i;\n i0 = i0+Nft[j,i]+Nft[j+1,i]; \n dr_scalings.append(di_scale);\n return dr_scalings #list\n \n# Nx = np.sum(Nft[:,0])\n# Ny = np.sum(Nft[:,1])\n# Nz = np.sum(Nft[:,2]) \n# dx_scale = np.ones(Nx)\n# dy_scale = np.ones(Ny)\n# dz_scale = np.ones(Nx)\n# num_regions = len(Nft)\n# x0 = y0 = z0 = 0\n \n# # % Here, we can assume that all odd indices are fixed regions\n# # % even indices are transition regions\n \n# for i in range(0, num_regions, 2): #coarse regions\n# dx_scale[x0:x0+Nft[i,0]] = drt[i,0]\n# dy_scale[y0:y0+Nft[i,1]] = drt[i,1]\n# dz_scale[z0:z0+Nft[i,2]] = drt[i,2]\n\n# if(i==num_regions-1): #o transition after last region\n# x0 = x0+Nft[i,0];\n# y0 = y0+Nft[i,1];\n# z0 = z0+Nft[i,2]\n# else:\n# x0 = x0+Nft[i,1]+Nft[i+1,0];\n# y0 = y0+Nft[i,1]+Nft[i+1,1];\n# z0 = z0+Nft[i,2]+Nft[i+1,2]\n\n \n# # do some sort of grading from region i to region i+1\n# x0 = Nft[0,0] #x0 represents end point\n# y0 = Nft[0,1]\n# z0 = Nft[0,2] \n \n# for i in range(1, num_regions, 2): # these are the transition regions\n# dx1 = drt[i-1,0]; dx2 = drt[i+1,0];\n# dy1 = drt[i-1,1]; dy2 = drt[i+1,1];\n# dz1 = drt[i-1,2]; dz2 = drt[i+1,2];\n \n# nxt = Nft[i,0] \n# nyt = Nft[i,1]\n# nzt = Nft[i,2] \n# print(nxt, nyt, nzt, dx1, dx2, dy1, dy2)\n\n# grading_x = np.logspace(np.log10(dx1), np.log10(dx2), nxt+1);\n# grading_y = np.logspace(np.log10(dy1), np.log10(dy2), nyt+1);\n# grading_z = np.logspace(np.log10(dz1), np.log10(dz2), nzt+1);\n \n# dx_scale[x0:x0+nxt+1] = grading_x;\n# dy_scale[y0:y0+nyt+1] = grading_y;\n# dz_scale[z0:z0+nzt+1] = grading_z;\n \n# x0 = x0+Nft[i,0]+Nft[i+1,0]; \n# y0 = y0+Nft[i,1]+Nft[i+1,1];\n# z0 = z0+Nft[i,2]+Nft[i+1,2] \n\n# return dx_scale, dy_scale, dz_scale", "repo_name": "zhaonat/py-maxwell-fd3d", "sub_path": "pyfd3d/nonuniform_grid.py", "file_name": "nonuniform_grid.py", "file_ext": "py", "file_size_in_byte": 5160, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 14, "dataset": "github-code", "pt": "20", "api": [{"api_name": "numpy.min", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.tanh", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.logspace", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.prod", "line_number": 29, "usage_type": "call"}, {"api_name": "scipy.sparse.spdiags", "line_number": 31, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 31, "usage_type": "name"}, {"api_name": "scipy.sparse.spdiags", "line_number": 32, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 32, "usage_type": "name"}, {"api_name": "scipy.sparse.spdiags", "line_number": 33, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 33, "usage_type": "name"}, {"api_name": "numpy.roll", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.roll", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.roll", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 39, "usage_type": "call"}, {"api_name": "scipy.sparse.spdiags", "line_number": 41, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 41, "usage_type": "name"}, {"api_name": "scipy.sparse.spdiags", "line_number": 42, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 42, "usage_type": "name"}, {"api_name": "scipy.sparse.spdiags", "line_number": 43, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 43, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 52, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 53, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.logspace", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 79, "usage_type": "call"}]} +{"seq_id": "660925231", "text": "# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport time\nimport logging\nfrom selenium.webdriver.common.action_chains import ActionChains\nsys.path.append(os.getcwd())\nfrom chineseocr_lite import ocr\nimport importlib\nimportlib.reload(sys)\n\nlogging.basicConfig(level=logging.INFO,\n # filename='selenium.log',\n filemode='a')\n\n# 破解携程滑块验证码\ndef crack_slide_verification(browser,url):\n driver = browser\n slider_btn = driver.find_element_by_xpath('//*[@id=\"J_slider_verification_qwewq\"]/div[1]/div[2]')\n if slider_btn:\n logging.info(url + u' drag slider button')\n actions = ActionChains(driver)\n actions.click_and_hold(slider_btn).perform()\n actions.move_by_offset(280,0).release(slider_btn).perform()\n # driver.save_screenshot('screenshot-verify.png')\n\n return driver,url\n\n# 破解携程中文验证码\ndef crack_ocr_verification(browser,url):\n driver = browser\n dest_img_url = driver.find_element_by_xpath('//*[@id=\"J_slider_verification_qwewq-choose\"]/div[2]/div[1]/img').get_attribute('src')\n dest_img_res = ocr.resultBase64(dest_img_url)\n for dest_img_character in dest_img_res:\n # dest_img_characters = unicode(dest_img_character['word'], 'utf-8')\n dest_img_characters = dest_img_character['word']\n logging.info(url + u' dest characters: ' + dest_img_characters)\n characters = list(dest_img_characters)\n\n sele_img_url = driver.find_element_by_xpath('//*[@id=\"J_slider_verification_qwewq-choose\"]/div[2]/div[3]/img').get_attribute('src')\n sele_img_res = ocr.resultBase64(sele_img_url)\n sele_characters = []\n sele_characters_pos = []\n for sele_img_character in sele_img_res:\n sele_characters.append(sele_img_character['word'])\n sele_characters_pos.append(sele_img_character['pos'])\n logging.info(url + u' candidate characters: ' + ' '.join(sele_characters))\n\n characters_pos = []\n for c in characters:\n for i in range(0,len(sele_characters)):\n if sele_characters[i] == c:\n characters_pos.append(sele_characters_pos[i])\n\n return driver,url,characters,characters_pos\n\n# 刷新携程中文验证码\ndef fresh_verification(browser,url,characters,characters_pos):\n driver = browser\n if len(characters_pos) == len(characters):\n return driver,url,characters,characters_pos\n\n while (len(characters_pos) != len(characters)):\n cpt_choose_refresh = driver.find_element_by_xpath('//*[@id=\"J_slider_verification_qwewq-choose\"]/div[2]/div[4]/div/a')\n cpt_choose_refresh.click()\n driver,url,characters,characters_pos = crack_ocr_verification(driver,url)\n\n if len(characters_pos) == len(characters):\n # driver.save_screenshot('screenshot-verify.png')\n return driver,url,characters,characters_pos\n\n# 点选携程中文验证码\ndef click_verification(browser,url,characters,characters_pos):\n driver = browser\n\n actions = ActionChains(driver)\n while (len(characters_pos) == len(characters)):\n cpt_big_img = driver.find_element_by_class_name(\"cpt-big-img\")\n for i in range(0,len(characters)):\n logging.info(url + u' click ' + characters[i] + u' located (' + str(characters_pos[i]['x']) + ',' + str(characters_pos[i]['y']) + ')')\n actions.move_to_element_with_offset(cpt_big_img,0,0).perform()\n actions.move_by_offset(characters_pos[i]['x'],characters_pos[i]['y']).click().perform()\n time.sleep(2)\n # driver.save_screenshot('screenshot-click.png')\n\n # 提交点选验证码\n cpt_choose_submit = driver.find_element_by_xpath('//*[@id=\"J_slider_verification_qwewq-choose\"]/div[2]/div[4]/a')\n cpt_choose_submit.click()\n # driver.save_screenshot('screenshot-submit.png')\n\n return driver\n\n# 检查是否点选成功\ndef check_verification(browser,url):\n driver = browser\n cpt_success_click = driver.find_element_by_xpath('//*[@id=\"J_slider_verification_qwewq\"]/div[1]/div[3]/div/span')\n while (u'校验成功' not in cpt_success_click.text):\n driver,url,characters,characters_pos = crack_ocr_verification(driver,url)\n driver,url,characters,characters_pos = fresh_verification(driver, url, characters, characters_pos)\n driver = click_verification(driver, url, characters, characters_pos)\n logging.info(url + ' ' + cpt_success_click.text)\n\n # 点击重新搜索\n research_btn = driver.find_element_by_xpath('//*[@id=\"app\"]/div/div[2]/div/div[2]/div/div[2]/div/button')\n research_btn.click()\n # driver.save_screenshot('screenshot-search.png')\n time.sleep(2)\n return driver", "repo_name": "ag-niemin/ctrip", "sub_path": "crack.py", "file_name": "crack.py", "file_ext": "py", "file_size_in_byte": 4680, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 5, "dataset": "github-code", "pt": "20", "api": [{"api_name": "sys.path.append", "line_number": 7, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 7, "usage_type": "call"}, {"api_name": "importlib.reload", "line_number": 10, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 12, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 12, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 21, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.action_chains.ActionChains", "line_number": 22, "usage_type": "call"}, {"api_name": "chineseocr_lite.ocr.resultBase64", "line_number": 33, "usage_type": "call"}, {"api_name": "chineseocr_lite.ocr", "line_number": 33, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 37, "usage_type": "call"}, {"api_name": "chineseocr_lite.ocr.resultBase64", "line_number": 41, "usage_type": "call"}, {"api_name": "chineseocr_lite.ocr", "line_number": 41, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 47, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.action_chains.ActionChains", "line_number": 76, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 80, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 83, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 101, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 107, "usage_type": "call"}]} +{"seq_id": "25274175234", "text": "import asyncio\nimport contextlib\n\nfrom middlewared.schema import accepts, Bool, Dict\nfrom middlewared.service import CallError, private, Service\nfrom middlewared.utils.asyncio_ import asyncio_map\n\nfrom .utils import ACTIVE_STATES\nfrom .vm_supervisor import VMSupervisorMixin\n\n\nSHUTDOWN_LOCK = asyncio.Lock()\n\n\nclass VMService(Service, VMSupervisorMixin):\n\n @private\n async def wait_for_libvirtd(self, timeout):\n async def libvirtd_started(middleware):\n await middleware.call('service.start', 'libvirtd')\n while not await middleware.call('service.started', 'libvirtd'):\n await asyncio.sleep(2)\n\n try:\n self._system_supports_virtualization()\n if not await self.middleware.call('service.started', 'libvirtd'):\n await asyncio.wait_for(self.middleware.create_task(libvirtd_started(self.middleware)), timeout=timeout)\n # We want to do this before initializing libvirt connection\n await self.middleware.run_in_thread(self._open)\n await self.middleware.run_in_thread(self._check_connection_alive)\n await self.middleware.call('vm.setup_libvirt_events')\n except (asyncio.TimeoutError, CallError):\n self.middleware.logger.error('Failed to setup libvirt', exc_info=True)\n\n @private\n def setup_libvirt_connection(self, timeout=30):\n self.middleware.call_sync('vm.wait_for_libvirtd', timeout)\n\n @private\n async def check_setup_libvirt(self):\n if not await self.middleware.call('service.started', 'libvirtd'):\n await self.middleware.call('vm.setup_libvirt_connection')\n\n @private\n def initialize_vms(self, timeout=30):\n vms = self.middleware.call_sync('vm.query')\n if vms and self._is_kvm_supported():\n self.setup_libvirt_connection(timeout)\n else:\n return\n\n if self._is_connection_alive():\n for vm_data in vms:\n try:\n self._add_with_vm_data(vm_data)\n except Exception as e:\n # Whatever happens, we don't want middlewared not booting\n self.middleware.logger.error(\n 'Unable to setup %r VM object: %s', vm_data['name'], str(e), exc_info=True\n )\n self.middleware.call_sync('service.reload', 'http')\n else:\n self.middleware.logger.error('Failed to establish libvirt connection')\n\n @private\n async def start_on_boot(self):\n for vm in await self.middleware.call('vm.query', [('autostart', '=', True)], {'force_sql_filters': True}):\n try:\n await self.middleware.call('vm.start', vm['id'])\n except Exception as e:\n self.middleware.logger.error(f'Failed to start VM {vm[\"name\"]}: {e}')\n\n @private\n @accepts(\n Dict(\n 'deinitialize_vms_options',\n Bool('stop_libvirt', default=True),\n )\n )\n async def deinitialize_vms(self, options):\n await self.middleware.call('vm.close_libvirt_connection')\n await self.middleware.call('service.reload', 'http')\n if options['stop_libvirt']:\n await self.middleware.call('service.stop', 'libvirtd')\n\n @private\n def close_libvirt_connection(self):\n if self.LIBVIRT_CONNECTION:\n with contextlib.suppress(CallError):\n self._close()\n\n @private\n def setup_details(self):\n return {\n 'connected': self._is_connection_alive(),\n 'connection_initialised': bool(self.LIBVIRT_CONNECTION),\n 'domains': list(self.vms.keys()),\n 'libvirt_domains': self._list_domains() if self.LIBVIRT_CONNECTION else None,\n }\n\n @private\n async def terminate(self):\n async with SHUTDOWN_LOCK:\n await self.middleware.call('vm.deinitialize_vms', {'stop_libvirt': False})\n\n @private\n async def terminate_timeout(self):\n return max(map(lambda v: v['shutdown_timeout'], await self.middleware.call('vm.query')), default=10)\n\n\nasync def __event_system_ready(middleware, event_type, args):\n \"\"\"\n Method called when system is ready, supposed to start VMs\n flagged that way.\n \"\"\"\n await middleware.call('vm.initialize_vms')\n\n # we ignore the 'ready' event on an HA system since the failover event plugin\n # is responsible for starting this service, however, the VMs still need to be\n # initialized (which is what the above callers are doing)\n if await middleware.call('failover.licensed'):\n return\n\n middleware.create_task(middleware.call('vm.start_on_boot'))\n\n\nasync def __event_system_shutdown(middleware, event_type, args):\n async def poweroff_stop_vm(vm):\n if vm['status']['state'] == 'RUNNING':\n stop_job = await middleware.call('vm.stop', vm['id'], {'force_after_timeout': True})\n await stop_job.wait()\n if stop_job.error:\n middleware.logger.error('Stopping %r VM failed: %r', vm['name'], stop_job.error)\n else:\n try:\n await middleware.call('vm.poweroff', vm['id'])\n except Exception:\n middleware.logger.error('Powering off %r VM failed', vm['name'], exc_info=True)\n\n async with SHUTDOWN_LOCK:\n await asyncio_map(\n poweroff_stop_vm,\n (await middleware.call('vm.query', [('status.state', 'in', ACTIVE_STATES)])), 16\n )\n middleware.logger.debug('VM(s) stopped successfully')\n # We do this in vm.terminate as well, reasoning for repeating this here is that we don't want to\n # stop libvirt on middlewared restarts, we only want that to happen if a shutdown has been initiated\n # and we have cleanly exited\n await middleware.call('vm.deinitialize_vms')\n\n\nasync def setup(middleware):\n # it's _very_ important that we run this before we do\n # any type of VM initialization. We have to capture the\n # zfs c_max value before we start manipulating these\n # sysctls during vm start/stop\n await middleware.call('sysctl.store_default_arc_max')\n\n if await middleware.call('system.ready'):\n middleware.create_task(middleware.call('vm.initialize_vms', 5)) # We use a short timeout here deliberately\n middleware.event_subscribe('system.ready', __event_system_ready)\n middleware.event_subscribe('system.shutdown', __event_system_shutdown)\n", "repo_name": "truenas/middleware", "sub_path": "src/middlewared/middlewared/plugins/vm/lifecycle.py", "file_name": "lifecycle.py", "file_ext": "py", "file_size_in_byte": 6456, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2144, "dataset": "github-code", "pt": "20", "api": [{"api_name": "asyncio.Lock", "line_number": 12, "usage_type": "call"}, {"api_name": "middlewared.service.Service", "line_number": 15, "usage_type": "name"}, {"api_name": "vm_supervisor.VMSupervisorMixin", "line_number": 15, "usage_type": "name"}, {"api_name": "asyncio.sleep", "line_number": 22, "usage_type": "call"}, {"api_name": "asyncio.wait_for", "line_number": 27, "usage_type": "call"}, {"api_name": "asyncio.TimeoutError", "line_number": 32, "usage_type": "attribute"}, {"api_name": "middlewared.service.CallError", "line_number": 32, "usage_type": "name"}, {"api_name": "middlewared.service.private", "line_number": 17, "usage_type": "name"}, {"api_name": "middlewared.service.private", "line_number": 35, "usage_type": "name"}, {"api_name": "middlewared.service.private", "line_number": 39, "usage_type": "name"}, {"api_name": "middlewared.service.private", "line_number": 44, "usage_type": "name"}, {"api_name": "middlewared.service.private", "line_number": 65, "usage_type": "name"}, {"api_name": "middlewared.service.private", "line_number": 73, "usage_type": "name"}, {"api_name": "middlewared.schema.accepts", "line_number": 74, "usage_type": "call"}, {"api_name": "middlewared.schema.Dict", "line_number": 75, "usage_type": "call"}, {"api_name": "middlewared.schema.Bool", "line_number": 77, "usage_type": "call"}, {"api_name": "contextlib.suppress", "line_number": 89, "usage_type": "call"}, {"api_name": "middlewared.service.CallError", "line_number": 89, "usage_type": "argument"}, {"api_name": "middlewared.service.private", "line_number": 86, "usage_type": "name"}, {"api_name": "middlewared.service.private", "line_number": 92, "usage_type": "name"}, {"api_name": "middlewared.service.private", "line_number": 101, "usage_type": "name"}, {"api_name": "middlewared.service.private", "line_number": 106, "usage_type": "name"}, {"api_name": "middlewared.utils.asyncio_.asyncio_map", "line_number": 141, "usage_type": "call"}, {"api_name": "utils.ACTIVE_STATES", "line_number": 143, "usage_type": "name"}]} +{"seq_id": "21968652012", "text": "import numpy as np\r\nimport streamlit as st\r\nimport pickle\r\n\r\n#loading the saved model\r\nloaded_model=pickle.load(open(\"D:/Courses/iNeuron/ML_webapp/trained_model.sav\",\"rb\"))\r\n\r\n#creating a function for prediction\r\ndef phishing(input_data):\r\n\r\n # change the input_data to numpy array\r\n input_data_numpy = np.asarray(input_data)\r\n\r\n # reshape the array\r\n input_data_reshaped = input_data_numpy.reshape(1, -1)\r\n\r\n prediction = loaded_model.predict(input_data_reshaped)\r\n print(prediction)\r\n\r\n if (prediction[0] == 0):\r\n return \"Not Phishing Website\"\r\n else:\r\n return \"Phishing Website\"\r\n\r\ndef main():\r\n\r\n #giving a title\r\n st.title(\"Phishing Domain Detection\")\r\n\r\n #getting the input data from user\r\n\r\n ttl_hostname=st.text_input(\"ttl_hostname\")\r\n qty_nameservers=st.text_input(\"qty_nameservers\")\r\n time_domain_activation=st.text_input(\"time_domain_activation\")\r\n qty_hyphen_file=st.text_input(\"qty_hyphen_file\")\r\n directory_length=st.text_input(\"directory_length\")\r\n qty_dot_domain=st.text_input(\"qty_dot_domain\")\r\n length_url=st.text_input(\"length_url\")\r\n qty_slash_url=st.text_input(\"qty_slash_url\")\r\n\r\n #code for prediction\r\n result=\"\"\r\n\r\n #create a button for prediction\r\n if st.button(\"Test\"):\r\n result=phishing([ttl_hostname,qty_nameservers,time_domain_activation,qty_hyphen_file,directory_length,qty_dot_domain,length_url,qty_slash_url])\r\n\r\n st.success(result)\r\n\r\nif __name__=='__main__':\r\n main()", "repo_name": "Sri-HariHaran-R/Phishing-Domain-Detection", "sub_path": "predict_page.py", "file_name": "predict_page.py", "file_ext": "py", "file_size_in_byte": 1497, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pickle.load", "line_number": 6, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 12, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 28, "usage_type": "call"}, {"api_name": "streamlit.text_input", "line_number": 32, "usage_type": "call"}, {"api_name": "streamlit.text_input", "line_number": 33, "usage_type": "call"}, {"api_name": "streamlit.text_input", "line_number": 34, "usage_type": "call"}, {"api_name": "streamlit.text_input", "line_number": 35, "usage_type": "call"}, {"api_name": "streamlit.text_input", "line_number": 36, "usage_type": "call"}, {"api_name": "streamlit.text_input", "line_number": 37, "usage_type": "call"}, {"api_name": "streamlit.text_input", "line_number": 38, "usage_type": "call"}, {"api_name": "streamlit.text_input", "line_number": 39, "usage_type": "call"}, {"api_name": "streamlit.button", "line_number": 45, "usage_type": "call"}, {"api_name": "streamlit.success", "line_number": 48, "usage_type": "call"}]} +{"seq_id": "1044567812", "text": "import sqlite3\n\ndef crear_bd():\n conexion = sqlite3.connect(\"restaurante.db\")\n cursor = conexion.cursor()\n\n try:\n cursor.execute('''CREATE TABLE categoria(\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n nombre VARCHAR(100) UNIQUE NOT NULL)''')\n except sqlite3.OperationalError:\n print(\"La tabla de Categorías ya existe.\")\n else:\n print(\"La tabla de Categorías se ha creado correctamente.\")\n\n try:\n cursor.execute('''CREATE TABLE plato(\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n nombre VARCHAR(100) UNIQUE NOT NULL, \n categoria_id INTEGER NOT NULL,\n FOREIGN KEY(categoria_id) REFERENCES categoria(id))''')\n except sqlite3.OperationalError:\n print(\"La tabla de Platos ya existe.\")\n else:\n print(\"La tabla de Platos se ha creado correctamente.\")\n\n\n conexion.close()\n\n\ndef agregar_categoria():\n categoria = input(\"¿Nombre de la nueva categoría?\\n> \")\n\n conexion = sqlite3.connect(\"restaurante.db\")\n cursor = conexion.cursor()\n\n try:\n cursor.execute(\"INSERT INTO categoria VALUES (null, '{}')\".format(categoria) )\n except sqlite3.IntegrityError:\n print(\"La categoría '{}' ya existe.\".format(categoria))\n else:\n print(\"Categoría '{}' creada correctamente.\".format(categoria))\n\n conexion.commit()\n conexion.close()\n\n# Crear la base de datos\ncrear_bd()\n\n# Menú de opciones del programa\nwhile True:\n print(\"\\nBienvenido al gestor del restaurante!\")\n opcion = input(\n \"\\nIntroduce una opción:\" \\\n \"\\n[1] Agregar una categoría\" \\\n \"\\n[4] Salir del programa\\n\\n> \")\n\n if opcion == \"1\":\n agregar_categoria()\n\n elif opcion == \"4\":\n print(\"Nos vemos!\")\n break\n\n else:\n print(\"Opción incorrecta\")", "repo_name": "HecFranco/course_python", "sub_path": "04_DataBase/Examples/64_restaurant_02.py", "file_name": "64_restaurant_02.py", "file_ext": "py", "file_size_in_byte": 1849, "program_lang": "python", "lang": "es", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sqlite3.connect", "line_number": 4, "usage_type": "call"}, {"api_name": "sqlite3.OperationalError", "line_number": 11, "usage_type": "attribute"}, {"api_name": "sqlite3.OperationalError", "line_number": 22, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 34, "usage_type": "call"}, {"api_name": "sqlite3.IntegrityError", "line_number": 39, "usage_type": "attribute"}]} +{"seq_id": "26154657789", "text": "from flask import Flask, request, jsonify\nfrom pprint import pprint\n# from handle_messages import handle_add_user, handle_add_song, send_text\nfrom spotify import spotify_queuer\nimport spotipy\nimport requests as r\nimport nexmo\nimport re\nfrom flask_cors import CORS, cross_origin\nfrom app import get_track_id\n\n\n# from state import state, phones\nMAX_GUESTS = 20\nstate = {\"next_room_id\": 999, \"rooms\":{}}\n\nphones = {} #key = phone num, val = phone num\n\napp = Flask(__name__)\nrooms = state[\"rooms\"]\ncors = CORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\n\n\n\n@app.route('/create-room', methods=['POST','OPTIONS'])\n@cross_origin()\ndef create_room():\n print(\"recieved a request\")\n if request.is_json:\n req_json = request.get_json() #accept spotify access token\n print(req_json)\n userid = r.get(\"https://api.spotify.com/v1/me\", headers={\"Authorization\": \"Bearer \" + req_json[\"access_token\"]}).json()[\"id\"]\n state[\"next_room_id\"] += 1\n state[\"rooms\"][str(state[\"next_room_id\"] )] = {\"skip_song\": [],\"phone_numbers\": [], \"access_token\": req_json[\"access_token\"],\"userid\": userid, \"playlist_id\": req_json[\"playlist_id\"], \"spotify_queue\": spotify_queuer(userid,req_json[\"access_token\"],req_json[\"playlist_id\"])} #create a new room with empty phone numbers\n print(state)\n return jsonify({'code': str(state[\"next_room_id\"])})\n\n\n\n@app.route('/webhooks/nexmo', methods=['GET','POST'])\n@cross_origin()\ndef delivery_receipt():\n text_message = request.get_json()['text'].lower()\n sender = request.get_json()['msisdn'] #sender phone number\n print(text_message)\n if \"join\" in text_message:\n print(\"I crash here\")\n room_number = str(re.search(r\"join (\\d+)\",text_message).group(1)) #extract room number to join from text message\n if room_number is None:\n send_text(\"room does not exist\", sender)\n else:\n handle_add_user(sender, room_number)\n elif text_message[:3] == \"add\":\n song_query = re.search(r\"^add (.+)$\" , text_message).group(1) #extract song to add to playlsist from text message\n handle_add_song(song_query, sender)\n elif text_message == \"skip\":\n handle_skip_song(sender)\n\n return str(200)\n\n#\n# @app.route('/room-guests', methods=['GET'])\n# @cross_origin()\n# def request_guests():\n# print(\"recieved a request\")\n# if request.get_json() == None:\n# return str(200)\n# room_id = request.get_json()[\"code\"]\n#\n# return jsonify({'guests': len(state[\"rooms\"][room_id][\"phone_numbers\"])})\n\n@app.route('/room-guests/', methods=['GET'])\n@cross_origin()\ndef request_guests(code):\n print(\"recieved a request\")\n print(code)\n if not (code in state[\"rooms\"]):\n return jsonify({'guests': '0'})\n return jsonify({'guests': len(state[\"rooms\"][code][\"phone_numbers\"])})\n\n#\n# @app.route('/next-song/', methods=['GET'])\n# @cross_origin()\n# def update_next_song(code):\n# print(\"next song\")\n# state['rooms'][code][\"spotify_queue\"].next_song()\n# return str(200)\n\ndef handle_add_user(sender, room_number):\n rooms = state['rooms']\n if room_number not in rooms:\n send_text(sender, \"that room does not exist\")\n elif len(rooms[room_number]['phone_numbers']) >= MAX_GUESTS:\n send_text(sender, \"max guests reached\")\n else:\n room = rooms[room_number]\n room['phone_numbers'].append(sender) #adds phone number to that room\n phones[sender] = room_number\n send_text(sender, \"added to room \" + room_number)\n\n\ndef handle_add_song(song_name,sender):\n if not (sender in phones):\n return\n room = phones[sender]\n print(room)\n token = state[\"rooms\"][room][\"access_token\"]\n queue = state[\"rooms\"][room][\"spotify_queue\"]\n song_id = get_track_id(song_name,token)\n if song_id is None:\n send_text(sender, \"sorry I cannot find that song\")\n else:\n queue.add_song_to_playlist(song_id)\n\ndef send_text(sender, text):\n client = nexmo.Client('355a63c2', 'vZQnmEP5A8lZhtYE')\n client.send_message({'from': 'Spotify Player', 'to': sender, 'text': text})\n\n\n\ndef handle_skip_song(sender):\n if not(sender in phones):\n return\n room = phones[sender]\n phones_in_room = state['rooms'][room][\"phone_numbers\"]\n token = state['rooms'][room][\"access_token\"]\n queue = state['rooms'][room][\"spotify_queue\"]\n skippers = state['rooms'][room][\"skip_song\"]\n if not(sender in skippers):\n skippers.append(sender)\n if(len(sender) / len(phones_in_room)) > 0.4:\n queue.skip_track()\n\n\n\n\ndef handle_leave_room(sender):\n if sender in phones:\n guests = state[\"rooms\"][phones[sender]][\"phone_numbers\"]\n del guests[sender]\n del phones[sender]\n else:\n send_text(\"you are not in a room\")\n\n\napp.run(port=3000, host=\"127.0.0.1\")\n\n", "repo_name": "sub-standard/spotiparty", "sub_path": "server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 4826, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "flask.Flask", "line_number": 19, "usage_type": "call"}, {"api_name": "flask_cors.CORS", "line_number": 21, "usage_type": "call"}, {"api_name": "app.config", "line_number": 22, "usage_type": "attribute"}, {"api_name": "flask.request.is_json", "line_number": 30, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 30, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 31, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 31, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 33, "usage_type": "call"}, {"api_name": "spotify.spotify_queuer", "line_number": 35, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 37, "usage_type": "call"}, {"api_name": "app.route", "line_number": 26, "usage_type": "call"}, {"api_name": "flask_cors.cross_origin", "line_number": 27, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 44, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 44, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 45, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 45, "usage_type": "name"}, {"api_name": "re.search", "line_number": 49, "usage_type": "call"}, {"api_name": "re.search", "line_number": 55, "usage_type": "call"}, {"api_name": "app.route", "line_number": 41, "usage_type": "call"}, {"api_name": "flask_cors.cross_origin", "line_number": 42, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 79, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 80, "usage_type": "call"}, {"api_name": "app.route", "line_number": 73, "usage_type": "call"}, {"api_name": "flask_cors.cross_origin", "line_number": 74, "usage_type": "call"}, {"api_name": "app.get_track_id", "line_number": 110, "usage_type": "call"}, {"api_name": "nexmo.Client", "line_number": 117, "usage_type": "call"}, {"api_name": "app.run", "line_number": 147, "usage_type": "call"}]} +{"seq_id": "19448132795", "text": "\"\"\"Topic tests\"\"\"\n\nimport pytest\nimport datetime as dt\nimport sqlalchemy as sqla\n\nfrom bemserver_core.database import db\nfrom bemserver_core.model import Timeseries\nfrom bemserver_service_acquisition_mqtt.model import (\n Topic, TopicLink, TopicByBroker, TopicBySubscriber)\n\n\nclass TestTopicModel:\n\n def test_topic_crud(\n self, database, decoder_mosquitto_uptime, broker, subscriber):\n\n decoder_mosquitto_uptime_cls, decoder = decoder_mosquitto_uptime\n\n assert Topic.get_by_id(None) is None\n assert Topic.get_by_id(1) is None\n\n topic = Topic(\n name=\"$SYS/broker/uptime\", payload_decoder_id=decoder.id)\n assert topic.id is None\n topic.save()\n assert topic.id is not None\n assert topic.qos == 1\n assert topic.is_enabled\n assert topic.payload_decoder == decoder\n assert topic.payload_decoder_cls == decoder_mosquitto_uptime_cls\n assert isinstance(\n topic.payload_decoder_instance, decoder_mosquitto_uptime_cls)\n assert topic.links == []\n assert topic.brokers == []\n assert topic.subscribers == []\n\n assert Topic.get_by_id(topic.id) == topic\n\n # Add links to topic.\n assert len(decoder.fields) > 0\n for payload_field in decoder.fields:\n ts = Timeseries(name=f\"Timeseries {payload_field.name}\")\n db.session.add(ts)\n db.session.commit()\n topic_link = topic.add_link(payload_field.id, ts.id)\n assert topic_link.topic == topic\n assert topic_link.payload_field == payload_field\n assert topic_link.timeseries == ts\n\n assert len(topic.links) == len(decoder.fields)\n assert [x.payload_field.name for x in topic.links] == [\n x.name for x in decoder.fields]\n\n # Remove links from topic.\n topic.remove_link(666, ts.id)\n assert len(topic.links) == len(decoder.fields)\n topic.remove_link(decoder.fields[0].id, 666)\n assert len(topic.links) == len(decoder.fields)\n topic.remove_link(decoder.fields[0].id, ts.id)\n assert len(topic.links) == len(decoder.fields) - 1\n topic.add_link(decoder.fields[0].id, ts.id)\n assert len(topic.links) == len(decoder.fields)\n\n # Add relation between topic and broker.\n topic_by_broker = topic.add_broker(broker.id)\n assert topic_by_broker.topic_id == topic.id\n assert topic_by_broker.broker_id == broker.id\n assert topic.brokers == [broker]\n with pytest.raises(sqla.exc.IntegrityError):\n topic.add_broker(666)\n\n # Remove relation between topic and broker.\n topic.remove_broker(broker.id)\n assert topic.brokers == []\n # No problem if we remove a relation to an inexistant broker.\n topic.remove_broker(666)\n\n # Add relation between topic and subscriber.\n topic_by_subscriber = topic.add_subscriber(subscriber.id)\n assert topic_by_subscriber.topic_id == topic.id\n assert topic_by_subscriber.subscriber_id == subscriber.id\n assert topic.subscribers == [subscriber]\n with pytest.raises(sqla.exc.IntegrityError):\n topic.add_subscriber(666)\n\n ts_now = dt.datetime.now(dt.timezone.utc)\n topic.update_subscription(subscriber.id, True)\n assert topic_by_subscriber.is_subscribed\n assert topic_by_subscriber.timestamp_last_subscription is not None\n assert topic_by_subscriber.timestamp_last_subscription > ts_now\n ts_last_sub = topic_by_subscriber.timestamp_last_subscription\n\n topic.update_subscription(subscriber.id, False)\n assert not topic_by_subscriber.is_subscribed\n assert topic_by_subscriber.timestamp_last_subscription == ts_last_sub\n\n # Remove relation between topic and subscriber.\n topic.remove_subscriber(subscriber.id)\n assert topic.subscribers == []\n # No problem if we remove a relation to an inexistant subscriber.\n topic.remove_subscriber(666)\n\n # Save errors.\n topic.qos = 666\n with pytest.raises(ValueError) as exc:\n topic._verify_consistency()\n assert str(exc) == \"Invalid QoS level!\"\n\n topic.qos = 2\n topic.payload_decoder_id = 666\n with pytest.raises(sqla.exc.IntegrityError):\n topic.save()\n\n topic.delete()\n assert Topic.get_by_id(topic.id) is None\n\n topic.delete() # try to delete again\n assert Topic.get_by_id(topic.id) is None\n\n topic.save()\n assert Topic.get_by_id(topic.id) is not None\n assert len(topic.links) == 0\n\n def test_topic_delete_cascade(\n self, database, mosquitto_topic, broker, subscriber):\n\n topic_id = mosquitto_topic.id\n assert len(mosquitto_topic.links) > 0\n mosquitto_topic.add_broker(broker.id)\n assert len(mosquitto_topic.brokers) > 0\n mosquitto_topic.add_subscriber(subscriber.id)\n assert len(mosquitto_topic.subscribers) > 0\n\n mosquitto_topic.delete()\n assert Topic.get_by_id(topic_id) is None\n\n # Deleting a topic also deletes in cascade links...\n stmt = sqla.select(TopicLink).filter(TopicLink.topic_id == topic_id)\n rows = db.session.execute(stmt).all()\n assert len(rows) == 0\n\n # ...relations to broker...\n stmt = sqla.select(TopicByBroker)\n stmt = stmt.filter(TopicByBroker.topic_id == topic_id)\n rows = db.session.execute(stmt).all()\n assert len(rows) == 0\n\n # ...and relations to subscriber.\n stmt = sqla.select(TopicBySubscriber)\n stmt = stmt.filter(TopicBySubscriber.topic_id == topic_id)\n rows = db.session.execute(stmt).all()\n assert len(rows) == 0\n\n\nclass TestTopicLinkModel:\n\n def test_topic_link_crud(\n self, database, subscriber, mosquitto_topic_name,\n decoder_mosquitto_uptime):\n\n _, decoder = decoder_mosquitto_uptime\n\n topic = Topic(\n name=mosquitto_topic_name, payload_decoder_id=decoder.id)\n topic.save()\n\n assert topic.links == []\n\n for payload_field in decoder.fields:\n ts = Timeseries(name=f\"Timeseries {payload_field.name}\")\n db.session.add(ts)\n db.session.commit()\n topic_link = TopicLink(\n topic_id=topic.id, payload_field_id=payload_field.id,\n timeseries_id=ts.id)\n topic_link.save()\n assert topic_link.topic == topic\n assert topic_link.payload_field == payload_field\n assert topic_link.timeseries == ts\n\n assert len(topic.links) == len(decoder.fields)\n assert [x.payload_field.name for x in topic.links] == [\n x.name for x in decoder.fields]\n\n # Verify unique constraints between:\n # - topic and payload field\n # - topic and timeseries\n topic_link = TopicLink(\n topic_id=topic.id,\n payload_field_id=topic.links[0].payload_field_id,\n timeseries_id=topic.links[0].timeseries_id)\n with pytest.raises(sqla.exc.IntegrityError):\n topic_link.save()\n\n payload_field_test = decoder.add_field(\"test\")\n topic_link.payload_field_id = payload_field_test.id\n with pytest.raises(sqla.exc.IntegrityError):\n topic_link.save()\n\n ts_test = Timeseries(name=\"Timeseries test\")\n db.session.add(ts_test)\n db.session.commit()\n topic_link.payload_field_id = topic.links[0].payload_field_id\n topic_link.timeseries_id = ts_test.id\n with pytest.raises(sqla.exc.IntegrityError):\n topic_link.save()\n\n topic_link.payload_field_id = payload_field_test.id\n topic_link.save()\n assert len(topic.links) == 2\n\n topic_link.delete()\n assert len(topic.links) == 1\n\n\nclass TestTopicByBrokerModel:\n\n def test_topic_by_broker(\n self, database, decoder_mosquitto_uptime, broker):\n\n _, decoder = decoder_mosquitto_uptime\n\n assert len(broker.topics) == 0\n\n topic = Topic(name=\"test\", payload_decoder_id=decoder.id)\n topic.save()\n assert len(topic.brokers) == 0\n\n topic.add_broker(broker.id)\n assert topic.brokers == [broker]\n assert broker.topics == [topic]\n\n topic_by_broker = TopicByBroker.get_by_id((topic.id, broker.id,))\n assert topic_by_broker.is_enabled\n\n topic.remove_broker(broker.id)\n assert len(topic.brokers) == 0\n assert len(broker.topics) == 0\n\n topic_by_broker = TopicByBroker.get_by_id((topic.id, broker.id,))\n assert topic_by_broker is None\n\n\nclass TestTopicBySubscriberModel:\n\n def test_topic_by_subscriber(\n self, database, decoder_mosquitto_uptime, subscriber):\n\n _, decoder = decoder_mosquitto_uptime\n\n assert len(subscriber.topics) == 0\n\n topic = Topic(name=\"test\", payload_decoder_id=decoder.id)\n topic.save()\n assert len(topic.subscribers) == 0\n\n topic.add_subscriber(subscriber.id)\n assert len(topic.subscribers) == 1\n assert len(subscriber.topics) == 1\n\n topic_by_subscriber = TopicBySubscriber.get_by_id(\n (topic.id, subscriber.id,))\n assert topic_by_subscriber.is_enabled\n assert not topic_by_subscriber.is_subscribed\n assert topic_by_subscriber.timestamp_last_subscription is None\n\n ts_now = dt.datetime.now(dt.timezone.utc)\n topic.update_subscription(subscriber.id, True)\n assert topic_by_subscriber.is_subscribed\n assert topic_by_subscriber.timestamp_last_subscription is not None\n assert topic_by_subscriber.timestamp_last_subscription > ts_now\n ts_last_sub = topic_by_subscriber.timestamp_last_subscription\n\n topic_by_subscriber.update_subscription(False)\n assert not topic_by_subscriber.is_subscribed\n assert topic_by_subscriber.timestamp_last_subscription == ts_last_sub\n\n topic.remove_subscriber(subscriber.id)\n assert len(topic.subscribers) == 0\n assert len(subscriber.topics) == 0\n", "repo_name": "BEMServer/bemserver-service-acquisition-mqtt", "sub_path": "tests/model/test_topic.py", "file_name": "test_topic.py", "file_ext": "py", "file_size_in_byte": 10151, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "bemserver_service_acquisition_mqtt.model.Topic.get_by_id", "line_number": 20, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic", "line_number": 20, "usage_type": "name"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic.get_by_id", "line_number": 21, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic", "line_number": 21, "usage_type": "name"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic", "line_number": 23, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic.get_by_id", "line_number": 38, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic", "line_number": 38, "usage_type": "name"}, {"api_name": "bemserver_core.model.Timeseries", "line_number": 43, "usage_type": "call"}, {"api_name": "bemserver_core.database.db.session.add", "line_number": 44, "usage_type": "call"}, {"api_name": "bemserver_core.database.db.session", "line_number": 44, "usage_type": "attribute"}, {"api_name": "bemserver_core.database.db", "line_number": 44, "usage_type": "name"}, {"api_name": "bemserver_core.database.db.session.commit", "line_number": 45, "usage_type": "call"}, {"api_name": "bemserver_core.database.db.session", "line_number": 45, "usage_type": "attribute"}, {"api_name": "bemserver_core.database.db", "line_number": 45, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 70, "usage_type": "call"}, {"api_name": "sqlalchemy.exc", "line_number": 70, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 84, "usage_type": "call"}, {"api_name": "sqlalchemy.exc", "line_number": 84, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 87, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 87, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 87, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 106, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 112, "usage_type": "call"}, {"api_name": "sqlalchemy.exc", "line_number": 112, "usage_type": "attribute"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic.get_by_id", "line_number": 116, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic", "line_number": 116, "usage_type": "name"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic.get_by_id", "line_number": 119, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic", "line_number": 119, "usage_type": "name"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic.get_by_id", "line_number": 122, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic", "line_number": 122, "usage_type": "name"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic.get_by_id", "line_number": 136, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic", "line_number": 136, "usage_type": "name"}, {"api_name": "sqlalchemy.select", "line_number": 139, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicLink", "line_number": 139, "usage_type": "argument"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicLink.topic_id", "line_number": 139, "usage_type": "attribute"}, {"api_name": "bemserver_core.database.db.session.execute", "line_number": 140, "usage_type": "call"}, {"api_name": "bemserver_core.database.db.session", "line_number": 140, "usage_type": "attribute"}, {"api_name": "bemserver_core.database.db", "line_number": 140, "usage_type": "name"}, {"api_name": "sqlalchemy.select", "line_number": 144, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicByBroker", "line_number": 144, "usage_type": "argument"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicByBroker.topic_id", "line_number": 145, "usage_type": "attribute"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicByBroker", "line_number": 145, "usage_type": "name"}, {"api_name": "bemserver_core.database.db.session.execute", "line_number": 146, "usage_type": "call"}, {"api_name": "bemserver_core.database.db.session", "line_number": 146, "usage_type": "attribute"}, {"api_name": "bemserver_core.database.db", "line_number": 146, "usage_type": "name"}, {"api_name": "sqlalchemy.select", "line_number": 150, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicBySubscriber", "line_number": 150, "usage_type": "argument"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicBySubscriber.topic_id", "line_number": 151, "usage_type": "attribute"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicBySubscriber", "line_number": 151, "usage_type": "name"}, {"api_name": "bemserver_core.database.db.session.execute", "line_number": 152, "usage_type": "call"}, {"api_name": "bemserver_core.database.db.session", "line_number": 152, "usage_type": "attribute"}, {"api_name": "bemserver_core.database.db", "line_number": 152, "usage_type": "name"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic", "line_number": 164, "usage_type": "call"}, {"api_name": "bemserver_core.model.Timeseries", "line_number": 171, "usage_type": "call"}, {"api_name": "bemserver_core.database.db.session.add", "line_number": 172, "usage_type": "call"}, {"api_name": "bemserver_core.database.db.session", "line_number": 172, "usage_type": "attribute"}, {"api_name": "bemserver_core.database.db", "line_number": 172, "usage_type": "name"}, {"api_name": "bemserver_core.database.db.session.commit", "line_number": 173, "usage_type": "call"}, {"api_name": "bemserver_core.database.db.session", "line_number": 173, "usage_type": "attribute"}, {"api_name": "bemserver_core.database.db", "line_number": 173, "usage_type": "name"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicLink", "line_number": 174, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicLink", "line_number": 189, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 193, "usage_type": "call"}, {"api_name": "sqlalchemy.exc", "line_number": 193, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 198, "usage_type": "call"}, {"api_name": "sqlalchemy.exc", "line_number": 198, "usage_type": "attribute"}, {"api_name": "bemserver_core.model.Timeseries", "line_number": 201, "usage_type": "call"}, {"api_name": "bemserver_core.database.db.session.add", "line_number": 202, "usage_type": "call"}, {"api_name": "bemserver_core.database.db.session", "line_number": 202, "usage_type": "attribute"}, {"api_name": "bemserver_core.database.db", "line_number": 202, "usage_type": "name"}, {"api_name": "bemserver_core.database.db.session.commit", "line_number": 203, "usage_type": "call"}, {"api_name": "bemserver_core.database.db.session", "line_number": 203, "usage_type": "attribute"}, {"api_name": "bemserver_core.database.db", "line_number": 203, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 206, "usage_type": "call"}, {"api_name": "sqlalchemy.exc", "line_number": 206, "usage_type": "attribute"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic", "line_number": 226, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicByBroker.get_by_id", "line_number": 234, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicByBroker", "line_number": 234, "usage_type": "name"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicByBroker.get_by_id", "line_number": 241, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicByBroker", "line_number": 241, "usage_type": "name"}, {"api_name": "bemserver_service_acquisition_mqtt.model.Topic", "line_number": 254, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicBySubscriber.get_by_id", "line_number": 262, "usage_type": "call"}, {"api_name": "bemserver_service_acquisition_mqtt.model.TopicBySubscriber", "line_number": 262, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 268, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 268, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 268, "usage_type": "attribute"}]} +{"seq_id": "7827574809", "text": "import json\n\nfrom ScriptResult import EXECUTION_STATE_FAILED, EXECUTION_STATE_COMPLETED\nfrom SiemplifyAction import SiemplifyAction\nfrom SiemplifyUtils import output_handler\nfrom TIPCommon import extract_configuration_param, extract_action_param\nfrom ZohoDeskExceptions import ZohoDeskNotFound\nfrom ZohoDeskManager import ZohoDeskManager\nfrom constants import (\n UPDATE_TICKET_SCRIPT_NAME,\n INTEGRATION_NAME,\n ASSIGNEE_TYPE_MAPPING,\n AGENT_TYPE_ASSIGNEE,\n TEAM_TYPE_ASSIGNEE, MARK_STATE_MAPPING, READ, UNREAD\n)\n\n\n@output_handler\ndef main():\n siemplify = SiemplifyAction()\n siemplify.script_name = UPDATE_TICKET_SCRIPT_NAME\n siemplify.LOGGER.info(\"----------------- Main - Param Init -----------------\")\n\n # INTEGRATION Configuration\n api_root = extract_configuration_param(siemplify, provider_name=INTEGRATION_NAME, param_name=\"API Root\",\n is_mandatory=True, print_value=True)\n client_id = extract_configuration_param(siemplify, provider_name=INTEGRATION_NAME, param_name=\"Client ID\",\n is_mandatory=True, print_value=True)\n client_secret = extract_configuration_param(siemplify, provider_name=INTEGRATION_NAME, param_name=\"Client Secret\",\n is_mandatory=True, remove_whitespaces=False)\n refresh_token = extract_configuration_param(siemplify, provider_name=INTEGRATION_NAME, param_name=\"Refresh Token\",\n is_mandatory=False, remove_whitespaces=False)\n verify_ssl = extract_configuration_param(siemplify, provider_name=INTEGRATION_NAME, param_name=\"Verify SSL\",\n is_mandatory=True, input_type=bool, print_value=True)\n\n # Action configuration\n ticket_id = extract_action_param(siemplify, param_name=\"Ticket ID\", is_mandatory=True, print_value=True)\n title = extract_action_param(siemplify, param_name=\"Title\", is_mandatory=False, print_value=True)\n description = extract_action_param(siemplify, param_name=\"Description\", is_mandatory=False, print_value=True)\n department_name = extract_action_param(siemplify, param_name=\"Department Name\", is_mandatory=False,\n print_value=True)\n contact_email = extract_action_param(siemplify, param_name=\"Contact\", is_mandatory=False, print_value=True)\n assignee_type = extract_action_param(siemplify, param_name=\"Assignee Type\", is_mandatory=False, print_value=True)\n assignee_name = extract_action_param(siemplify, param_name=\"Assignee Name\", is_mandatory=False, print_value=True)\n resolution = extract_action_param(siemplify, param_name=\"Resolution\", is_mandatory=False, print_value=True)\n priority = extract_action_param(siemplify, param_name=\"Priority\", is_mandatory=False, print_value=True)\n ticket_status = extract_action_param(siemplify, param_name=\"Status\", is_mandatory=False, print_value=True)\n mark_state = extract_action_param(siemplify, param_name=\"Mark State\", is_mandatory=False, print_value=True)\n classification = extract_action_param(siemplify, param_name=\"Classification\", is_mandatory=False, print_value=True)\n channel = extract_action_param(siemplify, param_name=\"Channel\", is_mandatory=False, print_value=True)\n category = extract_action_param(siemplify, param_name=\"Category\", is_mandatory=False, print_value=True)\n sub_category = extract_action_param(siemplify, param_name=\"Sub Category\", is_mandatory=False, print_value=True)\n due_date = extract_action_param(siemplify, param_name=\"Due Date\", is_mandatory=False, print_value=True)\n custom_fields = extract_action_param(siemplify, param_name=\"Custom Fields\", is_mandatory=False, print_value=True)\n\n siemplify.LOGGER.info(\"----------------- Main - Started -----------------\")\n result_value = True\n status = EXECUTION_STATE_COMPLETED\n\n try:\n assignee_type = ASSIGNEE_TYPE_MAPPING.get(assignee_type)\n if assignee_type and not assignee_name:\n raise Exception(f\"\\\"Assignee Name\\\" needs to be provided.\")\n mark_state = MARK_STATE_MAPPING.get(mark_state)\n\n if custom_fields:\n try:\n custom_fields = json.loads(custom_fields)\n except Exception:\n raise Exception(\"Unable to parse \\\"Custom Fields\\\" parameter as JSON.\")\n\n manager = ZohoDeskManager(api_root=api_root, client_id=client_id, client_secret=client_secret,\n refresh_token=refresh_token, verify_ssl=verify_ssl, siemplify_logger=siemplify.LOGGER)\n department = None\n if department_name:\n department = manager.find_department(department_name)\n if not department:\n raise ZohoDeskNotFound(\n f\"Error executing action “Update Ticket”. Reason: department {department_name} \"\n f\"wasn’t found in Zoho Desk. Please check the spelling.\"\n )\n department = department[0]\n\n contact = None\n if contact_email:\n contacts = manager.find_contact()\n contact = next((item for item in contacts if item.email == contact_email), None)\n if not contact:\n raise ZohoDeskNotFound(\n f\"Error executing action “Update Ticket”. Reason: contact {contact_email} \"\n f\"wasn’t found in Zoho Desk. Please check the spelling.\"\n )\n\n agent, team = None, None\n\n if assignee_type == AGENT_TYPE_ASSIGNEE:\n agents = manager.find_agent(assignee_name)\n if not agents:\n raise ZohoDeskNotFound(\n f\"Error executing action “Update Ticket”. Reason: agent {assignee_name} \"\n f\"wasn’t found in Zoho Desk. Please check the spelling.\"\n )\n agent = agents[0]\n\n elif assignee_type == TEAM_TYPE_ASSIGNEE:\n teams = manager.find_team()\n team = next((item for item in teams if item.name == assignee_name), None)\n if not team:\n raise ZohoDeskNotFound(\n f\"Error executing action “Update Ticket”. Reason: team {assignee_name} \"\n \"wasn’t found in Zoho Desk. Please check the spelling.\"\n )\n\n if mark_state == READ:\n manager.mark_ticket_as_read(ticket_id)\n elif mark_state == UNREAD:\n manager.mark_ticket_as_unread(ticket_id)\n\n ticket = manager.update_ticket(\n ticket_id,\n title=title,\n description=description,\n department=department,\n contact=contact,\n agent=agent,\n team=team,\n resolution=resolution,\n priority=priority,\n status=ticket_status,\n classification=classification,\n channel=channel,\n category=category,\n sub_category=sub_category,\n due_date=due_date,\n custom_fields=custom_fields\n )\n siemplify.result.add_result_json(ticket.to_json())\n output_message = f\"Successfully updated ticket with ID {ticket_id} in Zoho Desk.\"\n except Exception as error:\n output_message = f\"Error executing action “{UPDATE_TICKET_SCRIPT_NAME}”. Reason: {error}\"\n siemplify.LOGGER.error(output_message)\n siemplify.LOGGER.exception(error)\n status = EXECUTION_STATE_FAILED\n result_value = False\n\n siemplify.LOGGER.info('----------------- Main - Finished -----------------')\n siemplify.LOGGER.info(f\"Status: {status}\")\n siemplify.LOGGER.info(f\"Result Value: {result_value}\")\n siemplify.LOGGER.info(f\"Output Message: {output_message}\")\n siemplify.end(output_message, result_value, status)\n\n\nif __name__ == '__main__':\n main()\n", "repo_name": "chronicle/tip-marketplace", "sub_path": "Integrations/ZohoDesk/ActionsScripts/UpdateTicket.py", "file_name": "UpdateTicket.py", "file_ext": "py", "file_size_in_byte": 7874, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "20", "api": [{"api_name": "SiemplifyAction.SiemplifyAction", "line_number": 20, "usage_type": "call"}, {"api_name": "constants.UPDATE_TICKET_SCRIPT_NAME", "line_number": 21, "usage_type": "name"}, {"api_name": "TIPCommon.extract_configuration_param", "line_number": 25, "usage_type": "call"}, {"api_name": "constants.INTEGRATION_NAME", "line_number": 25, "usage_type": "name"}, {"api_name": "TIPCommon.extract_configuration_param", "line_number": 27, "usage_type": "call"}, {"api_name": "constants.INTEGRATION_NAME", "line_number": 27, "usage_type": "name"}, {"api_name": "TIPCommon.extract_configuration_param", "line_number": 29, "usage_type": "call"}, {"api_name": "constants.INTEGRATION_NAME", "line_number": 29, "usage_type": "name"}, {"api_name": "TIPCommon.extract_configuration_param", "line_number": 31, "usage_type": "call"}, {"api_name": "constants.INTEGRATION_NAME", "line_number": 31, "usage_type": "name"}, {"api_name": "TIPCommon.extract_configuration_param", "line_number": 33, "usage_type": "call"}, {"api_name": "constants.INTEGRATION_NAME", "line_number": 33, "usage_type": "name"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 37, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 38, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 39, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 40, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 42, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 43, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 44, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 45, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 46, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 47, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 48, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 49, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 50, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 51, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 52, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 53, "usage_type": "call"}, {"api_name": "TIPCommon.extract_action_param", "line_number": 54, "usage_type": "call"}, {"api_name": "ScriptResult.EXECUTION_STATE_COMPLETED", "line_number": 58, "usage_type": "name"}, {"api_name": "constants.ASSIGNEE_TYPE_MAPPING.get", "line_number": 61, "usage_type": "call"}, {"api_name": "constants.ASSIGNEE_TYPE_MAPPING", "line_number": 61, "usage_type": "name"}, {"api_name": "constants.MARK_STATE_MAPPING.get", "line_number": 64, "usage_type": "call"}, {"api_name": "constants.MARK_STATE_MAPPING", "line_number": 64, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 68, "usage_type": "call"}, {"api_name": "ZohoDeskManager.ZohoDeskManager", "line_number": 72, "usage_type": "call"}, {"api_name": "ZohoDeskExceptions.ZohoDeskNotFound", "line_number": 78, "usage_type": "call"}, {"api_name": "ZohoDeskExceptions.ZohoDeskNotFound", "line_number": 89, "usage_type": "call"}, {"api_name": "constants.AGENT_TYPE_ASSIGNEE", "line_number": 96, "usage_type": "name"}, {"api_name": "ZohoDeskExceptions.ZohoDeskNotFound", "line_number": 99, "usage_type": "call"}, {"api_name": "constants.TEAM_TYPE_ASSIGNEE", "line_number": 105, "usage_type": "name"}, {"api_name": "ZohoDeskExceptions.ZohoDeskNotFound", "line_number": 109, "usage_type": "call"}, {"api_name": "constants.READ", "line_number": 114, "usage_type": "name"}, {"api_name": "constants.UNREAD", "line_number": 116, "usage_type": "name"}, {"api_name": "constants.UPDATE_TICKET_SCRIPT_NAME", "line_number": 140, "usage_type": "name"}, {"api_name": "ScriptResult.EXECUTION_STATE_FAILED", "line_number": 143, "usage_type": "name"}, {"api_name": "SiemplifyUtils.output_handler", "line_number": 18, "usage_type": "name"}]} +{"seq_id": "12907492035", "text": "from datasets.arrow_dataset import Dataset\nfrom datasets.dataset_dict import DatasetDict\nfrom transformers.training_args import TrainingArguments\nfrom .args import *\nimport shlex\nimport re\n\n@dataclass\nclass TrainSplit(object):\n dataset: Dataset\n\n@dataclass\nclass EvalSplit(object):\n dataset: Dataset\n examples: Dataset\n\n@dataclass\nclass DatasetSplits(object):\n train_split: Optional[TrainSplit]\n eval_split: Optional[EvalSplit]\n test_splits: Optional[Dict[str, EvalSplit]]\n\n\ndef _prepare_train_split(\n dataset: Dataset,\n data_training_args: DataTrainingArguments,\n data_args: DataArguments,\n parse_query_function: Callable[[dict, Optional[str]], dict],\n add_serialized_schema: Callable[[dict, Optional[str], Optional[dict]], dict],\n pre_process_function: Callable[[dict, Optional[int], Optional[int]], dict],\n) -> TrainSplit:\n\n dataset = dataset.map(\n lambda ex: parse_query_function(\n ex=ex,\n mode='train'\n ),\n batched=False,\n num_proc=data_training_args.preprocessing_num_workers,\n load_from_cache_file=True,\n )\n\n dataset = dataset.map(\n lambda ex: add_serialized_schema(\n ex=ex,\n mode='train'\n ),\n batched=False,\n num_proc=data_training_args.preprocessing_num_workers,\n load_from_cache_file=True,\n )\n\n if data_training_args.train_samples_ratio != 1.0:\n dataset = dataset.select(range(int(dataset.num_rows*data_training_args.train_samples_ratio)))\n\n column_names = dataset.column_names\n\n dataset = dataset.map(\n lambda batch: pre_process_function(\n batch=batch,\n mode='train',\n ),\n batched=True,\n num_proc=data_training_args.preprocessing_num_workers,\n remove_columns=column_names,\n load_from_cache_file=False,\n )\n return TrainSplit(dataset=dataset)\n\n\ndef _prepare_eval_split(\n dataset: Dataset,\n data_training_args: DataTrainingArguments,\n data_args: DataArguments,\n parse_query_function: Callable[[dict], dict],\n add_serialized_schema: Callable[[dict, Optional[str], Optional[dict]], dict],\n pre_process_function: Callable[[dict, Optional[int], Optional[int]], dict],\n) -> EvalSplit:\n\n dataset = dataset.map(\n lambda ex: parse_query_function(\n ex=ex,\n mode='eval'\n ),\n batched=False,\n num_proc=data_training_args.preprocessing_num_workers,\n load_from_cache_file=False,\n )\n\n eval_examples = dataset\n\n eval_dataset = eval_examples.map(\n lambda ex: add_serialized_schema(\n ex=ex,\n mode='eval'\n ),\n batched=False,\n num_proc=data_training_args.preprocessing_num_workers,\n load_from_cache_file=True,\n )\n if data_training_args.max_val_samples is not None:\n eval_dataset = eval_dataset.select(range(data_training_args.max_val_samples))\n column_names = eval_dataset.column_names\n eval_dataset = eval_dataset.map(\n lambda batch: pre_process_function(\n batch=batch,\n mode='eval',\n ),\n batched=True,\n num_proc=data_training_args.preprocessing_num_workers,\n remove_columns=column_names,\n load_from_cache_file=False,\n )\n return EvalSplit(dataset=eval_dataset, examples=eval_examples)\n\n\ndef _prepare_test_split(\n dataset: Dataset,\n data_training_args: DataTrainingArguments,\n data_args: DataArguments,\n parse_query_function: Callable[[dict], dict],\n add_serialized_schema: Callable[[dict, Optional[str], Optional[dict]], dict],\n pre_process_function: Callable[[dict, Optional[int], Optional[int]], dict],\n) -> EvalSplit:\n\n test_examples = dataset\n\n test_dataset = test_examples.map(\n lambda ex: add_serialized_schema(\n ex=ex,\n mode='test'\n ),\n batched=False,\n num_proc=data_training_args.preprocessing_num_workers,\n load_from_cache_file=True,\n )\n column_names = test_dataset.column_names\n test_dataset = test_dataset.map(\n lambda batch: pre_process_function(\n batch=batch,\n mode='test',\n ),\n batched=True,\n num_proc=data_training_args.preprocessing_num_workers,\n remove_columns=column_names,\n load_from_cache_file=False,\n )\n return EvalSplit(dataset=test_dataset, examples=test_examples)\n\n\ndef _prepare_dblp_qald_final_test_split(\n dataset: Dataset,\n data_training_args: DataTrainingArguments,\n data_args: DataArguments,\n add_serialized_schema: Callable[[dict, Optional[str], Optional[dict]], dict],\n pre_process_function: Callable[[dict, Optional[int], Optional[int]], dict],\n) -> EvalSplit:\n\n test_examples = dataset\n\n test_dataset = test_examples.map(\n lambda ex: add_serialized_schema(\n ex=ex,\n mode='test_final'\n ),\n batched=False,\n num_proc=data_training_args.preprocessing_num_workers,\n load_from_cache_file=True,\n )\n column_names = test_dataset.column_names\n test_dataset = test_dataset.map(\n lambda batch: pre_process_function(\n batch=batch,\n mode='test_final'\n ),\n batched=True,\n num_proc=data_training_args.preprocessing_num_workers,\n remove_columns=column_names,\n load_from_cache_file=False,\n )\n return EvalSplit(dataset=test_dataset, examples=test_examples)\n\n\ndef _prepare_orkg_sciqa_final_test_split(\n dataset: Dataset,\n data_training_args: DataTrainingArguments,\n data_args: DataArguments,\n add_serialized_schema: Callable[[dict, Optional[str], Optional[dict]], dict],\n pre_process_function: Callable[[dict, Optional[int], Optional[int]], dict],\n) -> EvalSplit:\n\n test_examples = dataset\n\n test_dataset = test_examples.map(\n lambda ex: add_serialized_schema(\n ex=ex,\n mode='test_final'\n ),\n batched=False,\n num_proc=data_training_args.preprocessing_num_workers,\n load_from_cache_file=True,\n )\n column_names = test_dataset.column_names\n test_dataset = test_dataset.map(\n lambda batch: pre_process_function(\n batch=batch,\n mode='test_final'\n ),\n batched=True,\n num_proc=data_training_args.preprocessing_num_workers,\n remove_columns=column_names,\n load_from_cache_file=False,\n )\n return EvalSplit(dataset=test_dataset, examples=test_examples)\n\ndef prepare_splits(\n dataset_dict: DatasetDict,\n data_args: DataArguments,\n training_args: TrainingArguments,\n data_training_args: DataTrainingArguments,\n parse_query_function: Callable[[dict], dict],\n add_serialized_schema: Callable[[dict, Optional[dict]], dict],\n pre_process_function: Callable[[dict, Optional[int], Optional[int]], dict],\n) -> DatasetSplits:\n\n train_split, eval_split, test_split = None, None, None\n if training_args.do_train:\n train_split = _prepare_train_split(\n dataset_dict[\"train\"],\n data_training_args=data_training_args,\n data_args=data_args,\n parse_query_function=parse_query_function,\n add_serialized_schema=add_serialized_schema,\n pre_process_function=pre_process_function,\n )\n if training_args.do_eval:\n eval_split = _prepare_eval_split(\n dataset_dict[\"validation\"],\n data_args=data_args,\n data_training_args=data_training_args,\n parse_query_function=parse_query_function,\n add_serialized_schema=add_serialized_schema,\n pre_process_function=pre_process_function,\n )\n if training_args.do_predict:\n if data_args.dataset == \"dblp_qald_final\":\n test_split = _prepare_dblp_qald_final_test_split(\n dataset_dict[\"test\"],\n data_args=data_args,\n data_training_args=data_training_args,\n add_serialized_schema=add_serialized_schema,\n pre_process_function=pre_process_function,\n )\n elif data_args.dataset == \"orkg_sciqa_final\":\n test_split = _prepare_orkg_sciqa_final_test_split(\n dataset_dict[\"test\"],\n data_args=data_args,\n data_training_args=data_training_args,\n add_serialized_schema=add_serialized_schema,\n pre_process_function=pre_process_function,\n )\n\n else:\n test_split = _prepare_eval_split(\n dataset_dict[\"test\"],\n data_args=data_args,\n data_training_args=data_training_args,\n parse_query_function=parse_query_function,\n add_serialized_schema=add_serialized_schema,\n pre_process_function=pre_process_function,\n )\n\n return DatasetSplits(\n train_split=train_split,\n eval_split=eval_split,\n test_splits={\"test\": test_split}\n )\n\n\ndef serialize_schema(\n db_id: str,\n db_properties: List[str],\n db_entities: List[str],\n db_property_labels: List[str],\n db_entity_labels: List[str],\n schema_serialization_type: str = \"peteshaw\",\n schema_serialization_with_db_id: bool = True,\n schema_serialization_with_db_content: bool = False,\n schema_serialization_with_db_relation_content: bool = False,\n schema_serialization_with_db_entity_content: bool = False\n) -> str:\n if schema_serialization_type == \"verbose\":\n kg_id_str = \"database: {kg_id}. \"\n properties_str = \"properties: {properties}. \"\n property_sep = \", \"\n property_str_with_values = \"{property_id} ({property_label})\"\n property_str_without_values = \"{property_id}\"\n entities_str = \"entities: {entities}. \"\n entity_sep = \", \"\n entity_str_with_values = \"{entity_id} ({entity_label})\"\n entity_str_without_values = \"{entity_id}\"\n elif schema_serialization_type == \"peteshaw\":\n kg_id_str = \" {kg_id}\"\n properties_str = \" | properties: {properties} \"\n property_sep = \", \"\n property_str_with_values = \"{property_id} ({property_label})\"\n property_str_without_values = \"{property_id}\"\n entities_str = \" | entities: {entities} \"\n entity_sep = \", \"\n entity_str_with_values = \"{entity_id} ({entity_label})\"\n entity_str_without_values = \"{entity_id}\"\n else:\n raise NotImplementedError\n\n if schema_serialization_with_db_content and schema_serialization_with_db_relation_content:\n property_str_list = [\n property_str_with_values.format(\n property_id=property_id,\n property_label=property_label\n )\n for property_id, property_label in zip(db_properties, db_property_labels)\n ]\n else:\n property_str_list = [\n property_str_without_values.format(\n property_id=property_id\n )\n for property_id in db_properties\n ]\n\n if schema_serialization_with_db_content and schema_serialization_with_db_entity_content:\n entity_str_list = [\n entity_str_with_values.format(\n entity_id=entity_id,\n entity_label=entity_label\n )\n for entity_id, entity_label in zip(db_entities, db_entity_labels)\n ]\n else:\n entity_str_list = [\n entity_str_without_values.format(\n entity_id=entity_id\n )\n for entity_id in db_entities\n ]\n\n if schema_serialization_with_db_id:\n serialized_schema = kg_id_str.format(kg_id=db_id)\n serialized_schema += properties_str.format(properties=property_sep.join(property_str_list))\n serialized_schema += entities_str.format(entities=entity_sep.join(entity_str_list))\n else:\n serialized_schema = \"database: \"\n serialized_schema += properties_str.format(properties=property_sep.join(property_str_list))\n serialized_schema += entities_str.format(entities=entity_sep.join(entity_str_list))\n\n return serialized_schema\n\n\nSPARQL_KEYWORDS = {\n 'SELECT', 'CONSTRUCT', 'ASK', 'DESCRIBE', 'BIND', 'WHERE', 'LIMIT',\n 'VALUES', 'DISTINCT', 'AS', 'FILTER', 'ORDER', 'BY', 'HAVING', 'IN', 'SERVICE', 'OFFSET',\n 'NOT', 'EXISTS', 'OPTIONAL', 'UNION', 'FROM', 'GRAPH', 'NAMED', 'DESC',\n 'ASC', 'REDUCED', 'STR', 'LANG', 'LANGMATCHES', 'REGEX', 'BOUND', 'DATATYPE',\n 'ISBLANK', 'ISLITERAL', 'ISIRI', 'ISURI', 'GROUP_CONCAT', 'GROUP', 'DELETE', 'CLEAR',\n 'CREATE', 'COPY', 'DROP', 'INSERT', 'LOAD', 'DATA', 'INTO', 'WITH', 'ALL', 'SILENT',\n 'DEFAULT', 'USING', 'MD5', 'SHA1', 'SHA256', 'SHA384', 'SHA512', 'STRSTARTS',\n 'STRENDS', 'SAMETERM', 'ISNUMERIC', 'UCASE', 'SUBSTR', 'STRLEN', 'STRBEFORE', 'STRAFTER',\n 'REPLACE', 'LEVENSHTEIN_DIST', 'LCASE', 'ENCODE_FOR_URI', 'CONTAINS', 'CONCAT',\n 'COALESCE', 'CHOOSE_BY_MAX', 'CHOOSE_BY_MIN', 'YEAR', 'DAY', 'TZ', 'TIMEZONE', 'HOURS',\n 'MINUTES', 'MONTH', 'NOW', 'DUR_TO_USECS', 'SECONDS_DBL', 'USECS_TO_DUR', 'IF', 'MINUS',\n 'AVG', 'COUNT', 'MAX', 'MIN', 'SAMPLE', 'SUM', 'ABS', 'ADD', 'BASE', 'CEIL', 'COS', 'FLOOR',\n 'HAMMING_DIST', 'HAVERSINE_DIST', 'LN', 'LOG2', 'MOD', 'POWER', 'RADIANS', 'RAND',\n 'ROUND', 'ROUNDDOWN', 'ROUNDUP', 'TAN', 'VAR', 'VARP'\n}\n\nREPLACEMENTS = [\n [' * ', ' asterisk '],\n [' <= ', ' math_leq '],\n [' >= ', ' math_geq '],\n [' != ', ' math_neq '],\n [' = ', ' math_eql '],\n [' < ', ' math_lt '],\n [' > ', ' math_gt '],\n [' ; ', ' separator_semi '],\n #['\"', \" quote_str \"],\n [' , ', ' separator_com '],\n #['^^', ' str_type '],\n ['||', ' or_logical '],\n ['&&', ' and_logical '],\n [' ! ', ' bool_not '],\n #['@', ' lang_at '],\n [' ( ', ' par_open '],\n [' ) ', ' par_close '],\n [' )', ' par_close '],\n ['{', ' brace_open '],\n ['}', ' brace_close '],\n [' . ', ' separator_dot ']\n]\n\nREVERSE_REPLACEMENTS = [\n [' asterisk ', ' * '],\n [' math_leq ', ' <= '],\n [' math_geq ', ' >= '],\n [' math_neq ', ' != '],\n [' math_eql ', ' = '],\n [' math_lt ', ' < '],\n [' math_gt ', ' > '],\n [' separator_semi ', ' ; '],\n #[' quote_str ', '\"'],\n [' separator_com ', ' , '],\n #[' str_type ', '^^'],\n ['or_logical', ' || '],\n ['and_logical', ' && '],\n [' bool_not ', ' ! '],\n #[' lang_at ', '@'],\n [' par_open ', ' ( '],\n [' par_close ', ' ) '],\n [' par_close', ' ) '],\n [' brace_open ', ' { '],\n [' brace_close ', ' } '],\n [' separator_dot ', ' . ']\n]\n\n# Function to check parentheses\ndef checkParentheses(myStr, open_list, close_list):\n stack = []\n for i in myStr:\n if i in open_list: stack.append(i)\n elif i in close_list:\n pos = close_list.index(i)\n if ((len(stack) > 0) and (open_list[pos] == stack[len(stack) - 1])):\n stack.pop()\n else:\n return True\n return True if len(stack) == 0 else False\n\ndef decompose(sparql: str, ent_pattern, rel_pattern, var_pattern):\n\n open_list = [\"par_open\"]\n close_list = [\"par_close\"]\n\n query_tok_list = sparql.split()\n\n content = \"\"\n structure = \"\"\n is_limit = False\n is_offset = False\n is_filter = False\n is_having = False\n constraint_start_idx = 0\n parentheses = \"\"\n\n for idx, query_tok in enumerate(query_tok_list):\n\n if query_tok == \"limit\":\n is_limit = True\n structure += query_tok + \" \"\n continue\n\n if query_tok == \"offset\":\n is_offset = True\n structure += query_tok + \" \"\n continue\n\n if is_limit:\n content += \"[val] \" + query_tok + \" \"\n structure += \"[val] \"\n is_limit = False\n continue\n\n if is_offset:\n content += \"[val] \" + query_tok + \" \"\n structure += \"[val] \"\n is_offset = False\n continue\n\n if query_tok == \"filter\" and is_filter == False:\n is_filter = True\n constraint_start_idx = idx\n structure += query_tok + \" \"\n elif query_tok == \"having\":\n is_having = True\n constraint_start_idx = idx\n structure += query_tok + \" \"\n else:\n if is_filter or is_having:\n if query_tok == \"par_open\" or query_tok == \"par_close\":\n parentheses += query_tok + \" \"\n\n if checkParentheses(parentheses.split(), open_list, close_list) and len(parentheses) != 0:\n is_filter = False\n is_having = False\n parentheses = \"\"\n content += \"[con] \" + \" \".join(\n query_tok_list[constraint_start_idx+1:idx+1]) + \" \"\n structure += \"[con] \"\n else:\n continue\n\n else:\n\n if var_pattern.findall(query_tok):\n # if query_tok == \"var_0\":\n # content += \"[var] \" + \"*\" + \" \"\n # else:\n # content += \"[var] \" + query_tok + \" \"\n content += \"[var] \" + query_tok + \" \"\n structure += \"[var] \"\n elif ent_pattern.findall(query_tok):\n content += \"[ent] \" + query_tok + \" \"\n structure += \"[ent] \"\n elif rel_pattern.findall(query_tok):\n content += \"[rel] \" + query_tok + \" \"\n structure += \"[rel] \"\n else:\n structure += query_tok + \" \"\n\n structure = structure.strip()\n content = content.strip()\n\n ## future process the structure, because there might be some literals as values\n structure_tok_list = structure.split()\n structure_value_indices = []\n structure_start_idx = 0\n placeholder_counter = 0\n for idx, token in enumerate(structure_tok_list):\n if token in [\"[var]\", \"[ent]\", \"[rel]\", \"[con]\", \"[val]\"]:\n placeholder_counter += 1\n else:\n if token in [\"single_quote_begin\", \"quote_begin\"]:\n structure_start_idx = idx\n elif token in [\"single_quote_end\", \"quote_end\"]:\n structure_value_indices.append([placeholder_counter, structure_start_idx, idx+1])\n\n content_tok_list = content.split()\n content_value_indices = []\n for value_idx in structure_value_indices:\n content_start_idx = 0\n content_placeholder_counter = 0\n for idx, content_token in enumerate(content_tok_list):\n if content_token in [\"[var]\", \"[ent]\", \"[rel]\", \"[con]\", \"[val]\"]:\n content_placeholder_counter += 1\n if content_placeholder_counter == value_idx[0]:\n content_start_idx = idx\n break\n\n content_end_idx = content_start_idx + 1\n while content_end_idx < len(content_tok_list) and content_tok_list[content_end_idx] not in [\"[var]\", \"[ent]\", \"[rel]\", \"[con]\", \"[val]\"]:\n content_end_idx += 1\n\n content_value_indices.append([content_start_idx, content_end_idx])\n\n new_structure_tok_list = []\n new_content_tok_list = []\n s_previous_end_idx = 0\n c_previous_end_idx = 0\n\n for s_value_idx, c_value_idx in zip(structure_value_indices, content_value_indices):\n new_structure_tok_list += structure_tok_list[s_previous_end_idx:s_value_idx[1]]\n new_structure_tok_list += [\"[val]\"]\n s_previous_end_idx = s_value_idx[2]\n\n new_content_tok_list += content_tok_list[c_previous_end_idx:c_value_idx[1]]\n new_content_tok_list += [\"[val]\"] + structure_tok_list[s_value_idx[1]:s_value_idx[2]]\n c_previous_end_idx = c_value_idx[1]\n\n new_structure_tok_list += structure_tok_list[s_previous_end_idx:]\n new_content_tok_list += content_tok_list[c_previous_end_idx:]\n\n structure = \" \".join(new_structure_tok_list)\n content = \" \".join(new_content_tok_list)\n\n return structure, content\n\n\ndef combine_SC(content: str, structure: str) -> str:\n\n var_num = structure.count('[var]')\n val_num = structure.count('[val]')\n ent_num = structure.count('[ent]')\n rel_num = structure.count('[rel]')\n con_num = structure.count('[con]')\n\n if (content.count('[var]') != var_num) or (content.count('[val]') != val_num) or (content.count('[ent]') != ent_num) or (content.count('[rel]') != rel_num) or (content.count('[con]') != con_num):\n return structure\n\n content_dict = {\"[var]\": [], \"[ent]\": [], \"[val]\": [], \"[rel]\": [], \"[con]\": []}\n tok = None\n temp_str = ''\n i = 0\n while i < len(content):\n if content[i] == '[' and i + 4 < len(content) and content[i + 4] == ']' and (\n content[i:i + 5] in ['[var]', '[ent]', '[val]', '[rel]', '[con]']):\n if tok != None:\n content_dict[tok].append(temp_str.strip())\n tok = content[i:i + 5]\n temp_str = ''\n i += 6\n continue\n temp_str += content[i]\n i += 1\n if tok != None:\n content_dict[tok].append(temp_str.strip())\n\n pred_sql = structure\n\n # replace [var]\n end_index = 0\n for i in range(var_num):\n begin_index = pred_sql[end_index:].index('[var]') + end_index\n pred_sql = pred_sql[:begin_index] + content_dict['[var]'][i] + pred_sql[begin_index + 5:]\n end_index = begin_index + len(content_dict['[var]'][i]) + 1\n\n # replace [ent]\n end_index = 0\n for i in range(ent_num):\n begin_index = pred_sql[end_index:].index('[ent]') + end_index\n pred_sql = pred_sql[:begin_index] + content_dict['[ent]'][i] + pred_sql[begin_index + 5:]\n end_index = begin_index + len(content_dict['[ent]'][i]) + 1\n\n # replace [val]\n end_index = 0\n for i in range(val_num):\n begin_index = pred_sql[end_index:].index('[val]') + end_index\n pred_sql = pred_sql[:begin_index] + content_dict['[val]'][i] + pred_sql[begin_index + 5:]\n end_index = begin_index + len(content_dict['[val]'][i]) + 1\n\n # replace [rel]\n end_index = 0\n for i in range(rel_num):\n begin_index = pred_sql[end_index:].index('[rel]') + end_index\n pred_sql = pred_sql[:begin_index] + content_dict['[rel]'][i] + pred_sql[begin_index + 5:]\n end_index = begin_index + len(content_dict['[rel]'][i]) + 1\n\n # replace [con]\n end_index = 0\n for i in range(con_num):\n begin_index = pred_sql[end_index:].index('[con]') + end_index\n pred_sql = pred_sql[:begin_index] + content_dict['[con]'][i] + pred_sql[begin_index + 5:]\n end_index = begin_index + len(content_dict['[con]'][i]) + 1\n\n if pred_sql[0] == ' ':\n pred_sql = pred_sql[1:]\n\n pred_sql = [p for p in pred_sql.split() if p != \"\"]\n pred_sql = \" \".join(pred_sql)\n return pred_sql\n\n\ndef store_schema_items(query: str, ent_pattern, rel_pattern):\n schemafactory = SchemaItemFactory()\n entity_matches = ent_pattern.findall(query)\n for entity_match in set(entity_matches):\n match_entity_name = schemafactory[entity_match]\n query = re.sub(entity_match+\"( )+\", match_entity_name+\" \", query)\n\n relation_matches = rel_pattern.findall(query)\n for relation_match in set(relation_matches):\n match_relation_name = schemafactory[relation_match]\n query = re.sub(relation_match+\"( )+\", match_relation_name+\" \", query)\n\n return schemafactory, query\n\n\ndef store_strings(query):\n quoted_string_pattern_str = r'((? str:\n\n normalized_sparql = ' '.join(normalized_sparql.split())\n\n stringfactory, normalized_sparql = store_strings(normalized_sparql)\n\n encoded_sparql = do_replacements(normalized_sparql)\n\n for key, value in stringfactory.v2c.items():\n if value[-1] not in [\"'\", '\"']:\n if \"'@\" in value or '\"@' in value:\n tag = \" lang_at \"\n index = value.index(\"'@\")+1 if \"'@\" in value else value.index('\"@')+1\n left_part = value[:index]\n right_part = value[index + 1:]\n if \"'^^\" in value or '\"^^' in value:\n tag = \" string_type \"\n index = value.index(\"'^^\")+1 if \"'^^\" in value else value.index('\"^^')+1\n left_part = value[:index]\n right_part = value[index + 2:]\n\n if left_part[-1] == \"'\":\n left_part = \"single_quote_begin \"+left_part[1:-1]+\" single_quote_end\"\n elif left_part[-1] == '\"':\n left_part = \"quote_begin \" + left_part[1:-1] + \" quote_end\"\n encoded_sparql = encoded_sparql.replace(key, left_part + tag + right_part)\n else:\n if value == \"''\":\n encoded_sparql = encoded_sparql.replace(key, \"single_quote_begin single_quote_end\")\n elif value == '\"\"':\n encoded_sparql = encoded_sparql.replace(key, \"quote_begin quote_end\")\n else:\n if value[-1] == \"'\":\n part = \"single_quote_begin \"+value[1:-1]+\" single_quote_end\"\n elif value[-1] == '\"':\n part = \"quote_begin \" + value[1:-1] + \" quote_end\"\n encoded_sparql = encoded_sparql.replace(key, part)\n\n encoded_sparql = ' '.join(encoded_sparql.split())\n\n return encoded_sparql\n\n\ndef decode(encoded_sparql: str) -> str:\n\n sparql = reverse_replacements(encoded_sparql)\n\n sparql = sparql.replace(\"single_quote_begin single_quote_end\", \"''\")\n sparql = sparql.replace(\"quote_begin quote_end\", '\"\"')\n sparql = sparql.replace(\"single_quote_begin \", \"'\").replace(\" single_quote_end\", \"'\")\n sparql = sparql.replace(\"quote_begin \", '\"').replace(\" quote_end\", '\"')\n sparql = sparql.replace(\" lang_at \", '@')\n sparql = sparql.replace(\" string_type \", '^^')\n\n return ' '.join(sparql.split())\n\n\ndef reverse_replacements(sparql: str) -> str:\n for r in REVERSE_REPLACEMENTS:\n encoding = r[0]\n original = r[-1]\n sparql = sparql.replace(encoding, original)\n stripped_encoding = str.strip(encoding)\n sparql = sparql.replace(stripped_encoding, original)\n sparql = sparql.replace('{', ' { ').replace('}', ' } ')\n return sparql\n\ndef do_replacements(sparql: str) -> str:\n for r in REPLACEMENTS:\n encoding = r[-1]\n for original in r[:-1]:\n sparql = sparql.replace(original, encoding)\n return sparql\n\n\nclass VarNameFactory():\n def __init__(self, prefix=\"var_\"):\n self.prefix = prefix\n self.idx = 1\n self.v2c = {} # var(0,1,...) to custom names\n self.c2v = {} # custom names to var(0,1,...)\n\n def __getitem__(self, name):\n if name not in self.c2v:\n if name == \"*\":\n self.v2c[self.prefix+str(0)] = name\n self.c2v[name] = self.prefix+str(0)\n else:\n self.v2c[self.prefix+str(self.idx)] = name\n self.c2v[name] = self.prefix+str(self.idx)\n self.idx += 1\n return self.c2v[name]\n\n def __len__(self):\n return len(self.v2c)\n\n def __contains__(self, name):\n return name in self.c2v\n\n\nclass StringFactory():\n def __init__(self, prefix=\"string_\"):\n self.prefix = prefix\n self.idx = 0\n self.v2c = {} # string to custom names\n self.c2v = {} # custom names to string\n\n def __getitem__(self, string):\n if string not in self.c2v:\n self.v2c[self.prefix+str(self.idx)] = string\n self.c2v[string] = self.prefix+str(self.idx)\n self.idx += 1\n return self.c2v[string]\n\n def __len__(self):\n return len(self.v2c)\n\n def __contains__(self, name):\n return name in self.c2v\n\n\nclass SchemaItemFactory():\n def __init__(self, prefix=\"schema_\"):\n self.prefix = prefix\n self.idx = 0\n self.v2c = {} # string to custom names\n self.c2v = {} # custom names to string\n\n def __getitem__(self, string):\n if string not in self.c2v:\n self.v2c[self.prefix+str(self.idx)] = string\n self.c2v[string] = self.prefix+str(self.idx)\n self.idx += 1\n return self.c2v[string]\n\n def __len__(self):\n return len(self.v2c)\n\n def __contains__(self, name):\n return name in self.c2v\n\n\ndef lower_(word: str) -> str:\n if word.upper() in SPARQL_KEYWORDS:\n return word.lower()\n else:\n return word", "repo_name": "semantic-systems/ScholarlyQuAD-QA-Solution", "sub_path": "src/utils/dataset.py", "file_name": "dataset.py", "file_ext": "py", "file_size_in_byte": 30475, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "datasets.arrow_dataset.Dataset", "line_number": 10, "usage_type": "name"}, {"api_name": "datasets.arrow_dataset.Dataset", "line_number": 14, "usage_type": "name"}, {"api_name": "datasets.arrow_dataset.Dataset", "line_number": 15, "usage_type": "name"}, {"api_name": "datasets.arrow_dataset.Dataset", "line_number": 25, "usage_type": "name"}, {"api_name": "datasets.arrow_dataset.Dataset", "line_number": 72, "usage_type": "name"}, {"api_name": "datasets.arrow_dataset.Dataset", "line_number": 118, "usage_type": "name"}, {"api_name": "datasets.arrow_dataset.Dataset", "line_number": 152, "usage_type": "name"}, {"api_name": "datasets.arrow_dataset.Dataset", "line_number": 185, "usage_type": "name"}, {"api_name": "datasets.dataset_dict.DatasetDict", "line_number": 217, "usage_type": "name"}, {"api_name": "transformers.training_args.TrainingArguments", "line_number": 219, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 655, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 660, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 667, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 670, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 673, "usage_type": "call"}]} +{"seq_id": "70273680706", "text": "import yfinance as yf\nimport pandas as pd\nimport numpy as np\n\ndef get_data(ticker, start_date, end_date, close=True):\n if close:\n data = pd.DataFrame(yf.download(ticker, start_date, end_date)['Adj Close'])\n\n # convert to log returns, dropna\n data = data.apply(lambda x: np.log(x / x.shift(1))).dropna()\n\n # change the data shape to (n // 5, 5)\n if len(data) // 5 != 0:\n data = data.iloc[:len(data) // 5 * 5]\n data = data.values.reshape(len(data) // 5, 5)\n else:\n data = data.values.reshape(1, 5)\n\n return data\n\n else:\n data = yf.download(ticker, start_date, end_date)\n close = data['Adj Close']\n close = close.apply(lambda x: np.log(x / x.shift(1)))\n data['Adj Close'] = close\n\n data = data.dropna(inplace=True)\n\n return data\n", "repo_name": "rshea33/stocksGAN", "sub_path": "get_data.py", "file_name": "get_data.py", "file_ext": "py", "file_size_in_byte": 857, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pandas.DataFrame", "line_number": 7, "usage_type": "call"}, {"api_name": "yfinance.download", "line_number": 7, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 10, "usage_type": "call"}, {"api_name": "yfinance.download", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 24, "usage_type": "call"}]} +{"seq_id": "12709494479", "text": "import pygame\nimport math\nfrom pygame.sprite import Sprite\n\nclass Bullet(Sprite):\n \"\"\"A class to manage bullets fired from towers.\"\"\"\n\n def __init__(self, td_game, tower, enemy):\n \"\"\"Create a bullet object at the tower's current position.\"\"\"\n super().__init__()\n self.screen = td_game.screen\n self.settings = td_game.settings\n\n # load the bullet image and get it's rect\n self.image = pygame.image.load('images/bullet.bmp')\n self.rect = self.image.get_rect()\n\n # locate bullet at tower when created\n self.rect.center = tower.rect.center\n\n # Store bullet's position as decimal value\n self.x = float(self.rect.center[0])\n self.y = float(self.rect.center[1])\n\n # bullet attributes\n self.speed = 2\n self.damage = 50\n\n self._point_bullet(tower, enemy)\n\n def _point_bullet(self, tower, enemy):\n \"\"\"Point the bullet from the tower to the enemy.\"\"\"\n dx = enemy.rect.center[0] - tower.rect.center[0]\n dy = enemy.rect.center[1] - tower.rect.center[1]\n self.theta = math.atan2(-dy, dx) # dy is neg because y is down in pygame\n degs = math.degrees(self.theta)\n self.image = pygame.transform.rotate(self.image, degs)\n\n\n def update(self):\n \"\"\"Update the bullets position based on speed and target direction.\"\"\"\n self.y = self.y - (self.speed * math.sin(self.theta))\n self.x = self.x + (self.speed * math.cos(self.theta))\n\n self.rect.y = self.y\n self.rect.x = self.x\n\n\n\n", "repo_name": "mrashorn/tower_defense", "sub_path": "bullet.py", "file_name": "bullet.py", "file_ext": "py", "file_size_in_byte": 1555, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pygame.sprite.Sprite", "line_number": 5, "usage_type": "name"}, {"api_name": "pygame.image.load", "line_number": 15, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 15, "usage_type": "attribute"}, {"api_name": "math.atan2", "line_number": 35, "usage_type": "call"}, {"api_name": "math.degrees", "line_number": 36, "usage_type": "call"}, {"api_name": "pygame.transform.rotate", "line_number": 37, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 37, "usage_type": "attribute"}, {"api_name": "math.sin", "line_number": 42, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 43, "usage_type": "call"}]} +{"seq_id": "38646921172", "text": "# Django settings for audioFeatures project.\nimport os\nimport sys\nimport django.conf.global_settings as DEFAULT_SETTINGS\n\nPROJECT_DIR = os.path.dirname(__file__)\nTEMPLATE_DIRS = os.path.join(PROJECT_DIR, 'templates')\nsys.path.insert(0, os.path.join(PROJECT_DIR, 'apps'))\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n ('admin', 'alex@againstyou.net'),\n)\n\nMANAGERS = ADMINS\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': os.path.join(PROJECT_DIR, 'data.db'), # Or path to database file if using sqlite3.\n # The following settings are not used with sqlite3:\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.\n 'PORT': '', # Set to empty string for default.\n }\n}\n\n# Hosts/domain names that are valid for this site; required if DEBUG is False\n# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts\nALLOWED_HOSTS = []\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\nTIME_ZONE = 'America/Chicago'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale.\nUSE_L10N = True\n\n# If you set this to False, Django will not use timezone-aware datetimes.\nUSE_TZ = True\n\n# media deliver\nMEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')\nMEDIA_URL = '/media/'\n\n# static files (application js/img etc)\nSTATIC_ROOT = os.path.join(PROJECT_DIR, 'static')\nSTATIC_URL = '/static/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n os.path.join(PROJECT_DIR, 'site-static'),\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = '=v&991ik4m2&h2(9jt8f0obb_ahmbp)4up0a0&+qj*w38nn&7o'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n # Uncomment the next line for simple clickjacking protection:\n # 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'audioFeatures.urls'\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = 'audioFeatures.wsgi.application'\n\nimport os\nTEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\\\','/'),)\n\nTEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (\n #...#\n 'django.core.context_processors.request',\n #...#\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n # Uncomment the next line to enable the admin:\n 'django.contrib.admin',\n # Uncomment the next line to enable admin documentation:\n # 'django.contrib.admindocs',\n 'django_extensions',\n 'audioFeatures',\n 'af_documentation',\n 'audio',\n 'audio_processor',\n 'mptt',\n 'inplaceeditform',\n)\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\nINPLACEEDIT_EDIT_EMPTY_VALUE = 'Double click to edit'\nINPLACEEDIT_AUTO_SAVE = True\nINPLACEEDIT_EVENT = \"dblclick\"\nINPLACEEDIT_DISABLE_CLICK = True # For inplace edit text into a link tag\nINPLACEEDIT_EDIT_MESSAGE_TRANSLATION = 'Write a translation' # transmeta option\nINPLACEEDIT_SUCCESS_TEXT = 'Successfully saved'\nINPLACEEDIT_UNSAVED_TEXT = 'You have unsaved changes'\nINPLACE_ENABLE_CLASS = 'enable'\n#DEFAULT_INPLACE_EDIT_OPTIONS = {} # dictionnary of the optionals parameters that the templatetag can receive to change its behavior (see the Advanced usage section)\n#DEFAULT_INPLACE_EDIT_OPTIONS_ONE_BY_ONE = True # modify the behavior of the DEFAULT_INPLACE_EDIT_OPTIONS usage, if True then it use the default values not specified in your template, if False it uses these options only when the dictionnary is empty (when you do put any options in your template)\n#ADAPTOR_INPLACEEDIT_EDIT = 'app_name.perms.MyAdaptorEditInline' # Explain in Permission Adaptor API\n#ADAPTOR_INPLACEEDIT = {'myadaptor': 'app_name.fields.MyAdaptor'} # Explain in Adaptor API\nINPLACE_GET_FIELD_URL = None # to change the url where django-inplaceedit use to get a field\nINPLACE_SAVE_URL = None # to change the url where django-inplaceedit use to save a field\n", "repo_name": "alexgustafson/audioFeatures", "sub_path": "audioFeatures/settings.py", "file_name": "settings.py", "file_ext": "py", "file_size_in_byte": 6587, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "os.path.dirname", "line_number": 6, "usage_type": "call"}, {"api_name": "os.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "sys.path.insert", "line_number": 8, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path", "line_number": 59, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path", "line_number": 63, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 71, "usage_type": "call"}, {"api_name": "os.path", "line_number": 71, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 108, "usage_type": "call"}, {"api_name": "os.path", "line_number": 108, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 108, "usage_type": "call"}, {"api_name": "django.conf.global_settings.TEMPLATE_CONTEXT_PROCESSORS", "line_number": 110, "usage_type": "attribute"}, {"api_name": "django.conf.global_settings", "line_number": 110, "usage_type": "name"}]} +{"seq_id": "39926387172", "text": "from os import name\nimport discord\nfrom discord import player\nfrom discord.colour import Color\nfrom discord.ext import commands\nimport time\nimport asyncio\nfrom discord.ext import tasks\nfrom discord import Embed, Member\nfrom datetime import datetime\nimport random\nimport string\nfrom discord.ext.commands.core import command\nfrom discord.message import Message\nimport requests\nimport urllib.request\nfrom requests.api import request\nimport youtube_dl\nfrom colorama import Fore\nimport re\nfrom googlesearch import search\nimport aiohttp\nfrom keep_alive import keep_alive\n# set the apikey and limit\napikey = \"LIVDSRZULELA\" # test value\nlmt = 8\n\n# our test search\nsearch_term = \"excited\"\n\n\nclient = commands.Bot(command_prefix= \"p.\")\nclient.remove_command(\"help\")\nactiveservers = client.guilds\n@client.event\nasync def on_ready():\n\n print(f'''\nDeveloper : DySecurity\n мяєχρℓσιт & ᴛᴇꜱꜱ\n\n ''' )\n\n#-----------------------------------------------------------------------------\n# error system & random\n\n\n@client.event\nasync def on_command_error(ctx,error):\n embed = discord.Embed(\n title=\"PentCode Bot System Error\",\n color=0x9B59B6)\n if isinstance(error, commands.CommandNotFound):\n pass\n if isinstance(error, commands.MissingPermissions):\n embed.add_field(name=f'Error:', value=f'You dont have permissions.')\n await ctx.send(embed=embed)\n else:\n embed.add_field(name = f'Error:', value = f\"```{error}```\")\n await ctx.send(embed = embed)\n\ndef RandomColor():\n randcolor = discord.Color(random.randint(0x000000, 0xFFFFFF))\n\n\n\n#-----------------------------------------------------------------------------\n# ADmin System\n@client.command()\n@commands.has_permissions(manage_messages=True)\nasync def clear(ctx, amount=20):\n await ctx.channel.purge(limit=amount)\n embed=discord.Embed(title=\"Cleared Chat\", description='`' + str(amount) + \" massege has been cleared`\", color=discord.Color.blue())\n await ctx.send(embed=embed)\n\n@client.command(description=\"Mutes the specified user.\")\n@commands.has_permissions(manage_messages=True)\nasync def mute(ctx, member: discord.Member, *, reason=None):\n guild = ctx.guild\n mutedRole = discord.utils.get(guild.roles, name=\"muted\")\n\n if not mutedRole:\n mutedRole = await guild.create_role(name=\"muted\")\n\n for channel in guild.channels:\n await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)\n\n await member.add_roles(mutedRole, reason=reason)\n embed=discord.Embed(title=\"muted\", description=f\"muted {member.mention} for reason {reason}.\", color=discord.Color.blue())\n await ctx.send(embed=embed)\n\n@client.command(description=\"Unmutes a specified user.\")\n@commands.has_permissions(manage_messages=True)\nasync def unmute(ctx, member: discord.Member):\n mutedRole = discord.utils.get(ctx.guild.roles, name=\"muted\")\n\n await member.remove_roles(mutedRole)\n embed=discord.Embed(title=\"Unmuted\", description=f\"Unmuted {member.mention}\", color=discord.Color.blue())\n await ctx.send(embed=embed)\n\n@client.command()\n@commands.has_permissions(ban_members=True)\nasync def ban(ctx, member: discord.Member, *, reason=None):\n await member.ban(reason=reason)\n embed=discord.Embed(title=\"Banned\", description=f\"{member} was Banned From Server !\", color=discord.Color.blue())\n await ctx.send(embed=embed)\n\n@client.command()\n@commands.has_permissions(kick_members=True)\nasync def kick(ctx, member: discord.Member, *, reason=None):\n await member.kick(reason=reason)\n embed=discord.Embed(title=\"kicked\", description=f\"{member} was kicked From Server !\", color=discord.Color.blue())\n await ctx.send(embed=embed)\n\n\n@client.command(name='dc', help='To make the bot leave the voice channel')\nasync def dc(ctx):\n voice_client = ctx.message.guild.voice_client\n if voice_client.is_connected():\n await voice_client.disconnect()\n else:\n await ctx.send(\"The bot is not connected to a voice channel.\")\n\n\ndef Ali(ctx):\n return ctx.author.id == 815161361793417287\n\ndef Tess(ctx):\n return ctx.author.id == 828537840131637260\n\n@client.command()\n@commands.check(Tess)\nasync def Tess_playing(ctx, *, message):\n await ctx.message.delete()\n game = discord.Game(\n name=message\n )\n await client.change_presence(activity=game)\n\n@client.command()\n@commands.check(Ali)\nasync def Ali_playing(ctx, *, message):\n await ctx.message.delete()\n game = discord.Game(\n name=message\n )\n await client.change_presence(activity=game)\n\n\n#-----------------------------------------------------------------------------\n# System Public\n@client.command()\nasync def avatar(ctx, *, user: discord.Member = None):\n if user is None:\n user = ctx.author\n em = discord.Embed(description=\"Avatar System\")\n em.set_author(name=str(user), icon_url=user.avatar_url)\n em.set_thumbnail(url=user.avatar_url)\n em.add_field(name=\"Avatar Of\", value=user.mention)\n await ctx.send(embed=em)\n@client.command()\nasync def id(ctx):\n embed=discord.Embed(title=\"DySecurity\", description=f\"Your Developer ID : {ctx.author.id}\", color=discord.Color.blue())\n await ctx.send(embed=embed)\n\n@client.command()\nasync def info(ctx, *, user: discord.Member = None):\n if user is None:\n user = ctx.author\n if isinstance(ctx.message.channel, discord.Guild):\n date_format = \"%a, %d %b %Y %I:%M %p\"\n em = discord.Embed(description=user.mention)\n em.set_author(name=str(user), icon_url=user.avatar_url)\n em.set_thumbnail(url=user.avatar_url)\n em.add_field(name=\"Registered\", value=user.created_at.strftime(date_format))\n em.add_field(name=\"Joined\", value=user.joined_at.strftime(date_format))\n members = sorted(ctx.guild.members, key=lambda m: m.joined_at)\n em.add_field(name=\"Join position\", value=str(members.index(user) + 1))\n if len(user.roles) > 1:\n role_string = ' '.join([r.mention for r in user.roles][1:])\n em.add_field(name=\"Roles [{}]\".format(len(user.roles) - 1), value=role_string, inline=False)\n perm_string = ', '.join([str(p[0]).replace(\"_\", \" \").title() for p in user.guild_permissions if p[1]])\n em.add_field(name=\"Permissions\", value=perm_string, inline=False)\n em.set_footer(text='ID: ' + str(user.id))\n return await ctx.send(embed=em)\n else:\n date_format = \"%a, %d %b %Y %I:%M %p\"\n em = discord.Embed(description=user.mention)\n em.set_author(name=str(user), icon_url=user.avatar_url)\n em.set_thumbnail(url=user.avatar_url)\n em.add_field(name=\"Created\", value=user.created_at.strftime(date_format))\n em.set_footer(text='ID: ' + str(user.id))\n return await ctx.send(embed=em)\n\n# #@client.command(description=\"Gets info about the user\")\n# async def myinfo(ctx):\n# user = ctx.author\n\n# embed=discord.Embed(title=\"USER INFO\", description=f\"Here is the info we retrieved about {user}\", colour=RandomColor())\n# embed.set_thumbnail(url=user.avatar_url)\n# embed.add_field(name=\"Name\", value=user.name, inline=True)\n# embed.add_field(name=\"Nickname\", value=user.nick, inline=True)\n# embed.add_field(name=\"ID\", value=user.id, inline=True)\n# embed.add_field(name=\"Top role\", value=user.top_role.name, inline=True)\n# await ctx.send(embed=embed)\n\n\n@client.command()\nasync def invites(ctx, member:discord.Member=None):\n if member == None:\n member = ctx.message.author\n totalInvites = 0\n for i in await ctx.guild.invites():\n if i.inviter == member:\n totalInvites += i.uses\n embed=discord.Embed(title=\"Your Invites\", description=\"**\" + member.mention + \" has invited `\" + str(totalInvites) + \" User` to `\" + str(ctx.guild.name) + \"`**\", color=RandomColor())\n await ctx.send(embed=embed)\n\n@client.command()\nasync def stream(ctx):\n if not ctx.message.author.voice:\n await ctx.send(\"{} Please Connect To a Voice Channel :D & Using This Command\".format(ctx.message.author.name))\n return\n else:\n channel = ctx.message.author.voice.channel\n await channel.connect()\n\n\n\n@client.command()\nasync def slap(ctx, user: discord.Member):\n await ctx.message.delete()\n r = requests.get(\"https://nekos.life/api/v2/img/slap\")\n res = r.json()\n try:\n async with aiohttp.ClientSession() as session:\n async with session.get(res['url']) as resp:\n image = await resp.read()\n with io.BytesIO(image) as file:\n await ctx.send(user.mention, file=discord.File(file, f\"client_slap.gif\"))\n except:\n em = discord.Embed(description=user.mention)\n em.set_image(url=res['url'])\n await ctx.send(embed=em)\n\n@client.command()\nasync def hug(ctx, user: discord.Member):\n await ctx.message.delete()\n r = requests.get(\"https://nekos.life/api/v2/img/hug\")\n res = r.json()\n try:\n async with aiohttp.ClientSession() as session:\n async with session.get(res['url']) as resp:\n image = await resp.read()\n with io.BytesIO(image) as file:\n await ctx.send(user.mention, file=discord.File(file, f\"PentCode-2.gif\"))\n except:\n em = discord.Embed(description=user.mention)\n em.set_image(url=res['url'])\n await ctx.send(embed=em)\n\n@client.command()\nasync def kiss(ctx, user: discord.Member):\n await ctx.message.delete()\n r = requests.get(\"https://nekos.life/api/v2/img/kiss\")\n res = r.json()\n try:\n async with aiohttp.ClientSession() as session:\n async with session.get(res['url']) as resp:\n image = await resp.read()\n with io.BytesIO(image) as file:\n await ctx.send(user.mention, file=discord.File(file, f\"PentCode-1.gif\"))\n except:\n em = discord.Embed(description=user.mention)\n em.set_image(url=res['url'])\n await ctx.send(embed=em)\n\n@client.command()\nasync def wallpaper(ctx):\n await ctx.message.delete()\n r = requests.get(\"https://nekos.life/api/v2/img/wallpaper\")\n res = r.json()\n try:\n async with aiohttp.ClientSession() as session:\n async with session.get(res['url']) as resp:\n image = await resp.read()\n with io.BytesIO(image) as file:\n await ctx.send(file=discord.File(file, f\"PentCode-2.gif\"))\n except:\n em = discord.Embed(description=\"PentCode Bot Wallpaper\")\n em.set_image(url=res['url'])\n await ctx.send(embed=em)#6S24K27YK4TP\n@client.command()\nasync def blowjob(ctx):\n await ctx.message.delete()\n r = requests.get(\"https://nekos.life/api/v2/img/blowjob\")\n res = r.json()\n try:\n async with aiohttp.ClientSession() as session:\n async with session.get(res['url']) as resp:\n image = await resp.read()\n with io.BytesIO(image) as file:\n await ctx.send(file=discord.File(file, f\"PentCode-2.gif\"))\n except:\n em = discord.Embed(description=\"PentCode Bot Wallpaper\")\n em.set_image(url=res['url'])\n await ctx.send(embed=em)\n\n\n@client.command()\nasync def inviteme(ctx, *, user: discord.Member = None):\n if user is None:\n await ctx.send(f\"**DySecurity Official Server** : https://discord.gg/dWSkje5Jwt\")\n\n\n\n@client.command()\nasync def addbot(ctx, *, user: discord.Member = None):\n if user is None:\n await ctx.send(f\"**PentCode addBot Link :** https://discord.com/oauth2/authorize?client_id=838436903887306772&permissions=42949672878&scope=bot\")\n\n\n\n#---------------------------------------Music Bot -----------------------------------------\nyoutube_dl.utils.bug_reports_message = lambda: ''\n\nytdl_format_options = {\n 'format': 'bestaudio/best',\n 'restrictfilenames': True,\n 'noplaylist': True,\n 'nocheckcertificate': True,\n 'ignoreerrors': False,\n 'logtostderr': False,\n 'quiet': True,\n 'no_warnings': True,\n 'default_search': 'auto',\n 'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues sometimes\n}\n\nffmpeg_options = {\n 'options': '-vn'\n}\n\nytdl = youtube_dl.YoutubeDL(ytdl_format_options)\n\nclass YTDLSource(discord.PCMVolumeTransformer):\n def __init__(self, source, *, data, volume=0.5):\n super().__init__(source, volume)\n self.data = data\n self.title = data.get('title')\n self.url = \"\"\n\n @classmethod\n async def from_url(cls, url, *, loop=None, stream=False):\n loop = loop or asyncio.get_event_loop()\n data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))\n if 'entries' in data:\n # take first item from a playlist\n data = data['entries'][0]\n filename = data['title'] if stream else ytdl.prepare_filename(data)\n return filename\n\n#-----------------------------------------------------------------------------------\n\n@client.command()\nasync def announce(self, ctx, message):\n # Find a channel from the guilds `text channels` (Rather then voice channels)\n # with the name announcements\n channel = discord.utils.get(ctx.guild.text_channels, name=\"announcements\")\n if channel: # If a channel exists with the name\n\n embed = discord.Embed(color=discord.Color.dark_gold(), timestamp=ctx.message.created_at)\n embed.set_author(name=\"Announcement\", icon_url=self.client.user.avatar_url)\n embed.add_field(name=f\"Sent by {ctx.message.author}\", value=str(message), inline=False)\n embed.set_thumbnail(url=self.client.user.avatar_url)\n embed.set_footer(text=self.client.user.name, icon_url=self.client.user.avatar_url)\n await ctx.message.add_reaction(emoji=\"✅\")\n await channel.send(embed=embed)\n\n#--------------------------------------------------------------------------------------\n\n@client.command()\nasync def developer(ctx):\n await ctx.send(\"***Developers :*** `MrExploit & Tess`\")\n\n@client.command()\n@commands.has_permissions(administrator=True)\nasync def nitro(ctx):\n code = ''.join(random.choices(string.ascii_letters + string.digits, k=16))\n await ctx.send(f'https://discord.gift/{code}')\n\n@client.command()\n@commands.has_permissions(administrator=True)\nasync def slowmode(ctx, seconds: int):\n await ctx.channel.edit(slowmode_delay=seconds)\n await ctx.send(f\"Set the slowmode delay in this channel to {seconds} seconds!\")\n\n@client.command()\nasync def play(ctx,url):\n if not ctx.message.author.voice:\n await ctx.send(\"{} Please Connect To a Voice Channel :D & Using This Command\".format(ctx.message.author.name))\n return\n else:\n channel = ctx.message.author.voice.channel\n await channel.connect()\n try :\n url.strip()\n url = url.replace(' ','+')\n urlmusic = \"https://youtube.com/results?search_query=\"+url\n html = urllib.request.urlopen(urlmusic)\n video_url = re.findall(r\"watch\\?v=(\\S{11})\", html.read().decode())\n url = \"https://youtube.com/watch?v=\" + video_url[1]\n server = ctx.message.guild\n voice_channel = server.voice_client\n\n async with ctx.typing():\n filename = await YTDLSource.from_url(url, loop=client.loop)\n voice_channel.play(discord.FFmpegPCMAudio(executable=\"ffmpeg.exe\", source=filename))\n await ctx.send('**Now playing:** {}'.format(filename))\n except:\n await ctx.send(\"Error ! - VPS is Or Bot is Not Connected To a Voice Channel.\")\n\n\n\n#--------------------------------------------\n\n@client.command(helpinfo='Info about servers PentCode Bot is in', aliases=['server', 'num', 'count'])\n@commands.check(Ali)\nasync def servers(ctx):\n '''\n Info about servers PentCode Bot is in\n '''\n servers = client.guilds\n servers.sort(key=lambda x: x.member_count, reverse=True)\n await ctx.send('***Top servers with PentCode Bot:***')\n for x in servers[:5]:\n await ctx.send('**{}**, **{}** Members, {} region, Owned by <@{}>, Created at {}\\n{}'.format(x.name, x.member_count, x.region, x.owner_id, x.created_at, x.icon_url_as(format='png',size=32)))\n y = 0\n for x in client.guilds:\n y += x.member_count\n await ctx.send('**Total number of PentCode Bot users:** ***{}***!\\n**Number of servers:** ***{}***!'.format(y, len(client.guilds)))\n\n\n\n@client.command()\nasync def website(ctx):\n '''\n PentCode Bot WebSite :D\n '''\n await ctx.send('***DySecurity WebSite : `DySecurity.net`')\n\n#-------------------------------------------\n\n\n\n@client.command()\nasync def wikipedia(ctx, *, query: str):\n '''\n Uses Wikipedia APIs to summarise search\n '''\n sea = requests.get(\n ('https://en.wikipedia.org//w/api.php?action=query'\n '&format=json&list=search&utf8=1&srsearch={}&srlimit=5&srprop='\n ).format(query)).json()['query']\n\n if sea['searchinfo']['totalhits'] == 0:\n await ctx.send('Sorry, your search could not be found.')\n else:\n for x in range(len(sea['search'])):\n article = sea['search'][x]['title']\n req = requests.get('https://en.wikipedia.org//w/api.php?action=query'\n '&utf8=1&redirects&format=json&prop=info|images'\n '&inprop=url&titles={}'.format(article)).json()['query']['pages']\n if str(list(req)[0]) != \"-1\":\n break\n else:\n await ctx.send('Sorry, your search could not be found.')\n return\n article = req[list(req)[0]]['title']\n arturl = req[list(req)[0]]['fullurl']\n artdesc = requests.get('https://en.wikipedia.org/api/rest_v1/page/summary/'+article).json()['extract']\n lastedited = datetime.datetime.strptime(req[list(req)[0]]['touched'], \"%Y-%m-%dT%H:%M:%SZ\")\n embed = discord.Embed(title='**'+article+'**', url=arturl, description=artdesc, color=0x3FCAFF)\n embed.set_footer(text='Wiki entry last modified',\n icon_url='https://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png')\n embed.set_author(name='Wikipedia', url='https://en.wikipedia.org/',\n icon_url='https://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png')\n embed.timestamp = lastedited\n await ctx.send('**Search result for:** ***\"{}\"***:'.format(query), embed=embed)\n\n@client.command()\nasync def wikifarsi(ctx, *, query: str):\n '''\n Uses Wikipedia APIs to summarise search\n '''\n sea = requests.get(\n ('https://fa.wikipedia.org//w/api.php?action=query'\n '&format=json&list=search&utf8=1&srsearch={}&srlimit=5&srprop='\n ).format(query)).json()['query']\n\n if sea['searchinfo']['totalhits'] == 0:\n await ctx.send('Sorry, your search could not be found.')\n else:\n for x in range(len(sea['search'])):\n article = sea['search'][x]['title']\n req = requests.get('https://fa.wikipedia.org//w/api.php?action=query'\n '&utf8=1&redirects&format=json&prop=info|images'\n '&inprop=url&titles={}'.format(article)).json()['query']['pages']\n if str(list(req)[0]) != \"-1\":\n break\n else:\n await ctx.send('Sorry, your search could not be found.')\n return\n article = req[list(req)[0]]['title']\n arturl = req[list(req)[0]]['fullurl']\n artdesc = requests.get('https://fa.wikipedia.org/api/rest_v1/page/summary/'+article).json()['extract']\n lastedited = datetime.datetime.strptime(req[list(req)[0]]['touched'], \"%Y-%m-%dT%H:%M:%SZ\")\n embed = discord.Embed(title='**'+article+'**', url=arturl, description=artdesc, color=0x3FCAFF)\n embed.set_footer(text='Wiki entry last modified',\n icon_url='https://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png')\n embed.set_author(name='Wikipedia', url='https://fa.wikipedia.org/',\n icon_url='https://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png')\n embed.timestamp = lastedited\n await ctx.send('**Search result for:** ***\"{}\"***:'.format(query), embed=embed)\n\n\n@client.command()\n@commands.has_permissions(manage_messages=True)\nasync def say(ctx, *, message):\n await ctx.message.delete()\n await ctx.send(message)\n@client.command(name='pause', help='This command pauses the song')\nasync def pause(ctx):\n voice_client = ctx.message.guild.voice_client\n if voice_client.is_playing():\n await voice_client.pause()\n else:\n await ctx.send(\"The bot is not playing anything at the moment.\")\n\n@client.command(name='resume', help='Resumes the song')\nasync def resume(ctx):\n voice_client = ctx.message.guild.voice_client\n if voice_client.is_paused():\n await voice_client.resume()\n else:\n await ctx.send(\"The bot was not playing anything before this. Use play_song command\")\n\n@client.command(name='stop', help='Stops the song')\nasync def stop(ctx):\n voice_client = ctx.message.guild.voice_client\n if voice_client.is_playing():\n await voice_client.stop()\n else:\n await ctx.send(\"The bot is not playing anything at the moment.\")\n#---------------------------------------------------------------------------------------------\n# system help\n# 19 Gh 182:25\n\n@client.command()\nasync def help(ctx, category=None):\n await ctx.message.delete()\n if category is None:\n embed = discord.Embed(colour=discord.Color.blue())\n embed.set_author(name=f\"PentCode Bot Commands\")\n embed.add_field(name=\"[Admins Commands]\", value=\"-------------------------\", inline=False)\n embed.add_field(name=\"p.clear [Amount]\", value=\"Clear Messages💬\", inline=False)\n embed.add_field(name=\"p.slowmode [time]\" , value=\"Set the slowmode delay in a channel\")\n embed.add_field(name=\"p.mute [user] [reason]\", value=\"mute user -> the user can't Send massege and see channels🔇\", inline=False)\n embed.add_field(name=\"p.unmute [user] [reason]\", value=\"Unmute The Muted Users🔊\", inline=False)\n embed.add_field(name=\"p.kick [user] [reason]\", value=\"For Kicking a User🛑\", inline=False)\n embed.add_field(name=\"p.ban [user] [reason]\", value=\"For Banned a User🛑\", inline=False)\n embed.add_field(name=\"[Public commands]\", value=\"-------------------------\", inline=False)\n embed.add_field(name=\"p.id\", value=\"Get Your Developer ID✔️\", inline=False)\n embed.add_field(name=\"p.addbot\", value=\"Add Bot in Your Servers\",inline=False)\n embed.add_field(name=\"p.info [user]\", value=\"Get The User Info✔️\", inline=False)\n embed.add_field(name=\"p.myinfo\", value=\"Get Your Inf✔️o\", inline=False)\n embed.add_field(name=\"p.invites\", value=\"Your Invites✔️\", inline=False)\n embed.add_field(name=\"p.inviteme\", value=\"Official DySecurity Discord Server💕\", inline=False)\n embed.add_field(name=\"[ Fun commands ]\", value=\"-------------------------\", inline=False)\n embed.add_field(name=\"p.slap [user]\", value=\"For Slaping any User💔\", inline=False)\n embed.add_field(name=\"p.kiss [user]\", value=\"For Kissing any User👄\", inline=False)\n embed.add_field(name=\"p.hug [user]\", value=\"For Hug any User🙌\", inline=False)\n embed.add_field(name=\"p.avatar\" , value=\"Send Your Avatar 🙂\" , inline=False)\n embed.add_field(name=\"p.mooz\" , value=\"Send a Banana Picture And Say Mooz is Here :D🙂\" , inline=False)\n embed.add_field(name=\"p.joon\" , value=\"Send a Mr.Joon Picture And Say Mr.Joon is Here :D🙂\" , inline=False)\n embed.add_field(name=\"[ Music ]\", value=\"-------------------------\", inline=False)\n embed.add_field(name=\"p.dc\", value=\"For Disconnecting Bot From Voice Channel🔴\", inline=False)\n embed.add_field(name=\"p.play [MusicName]\" , value=\"For Play a Music From Youtube 🙂\" , inline=False)\n embed.add_field(name=\"p.pause\" , value=\"For Pause Music🙂\" , inline=False)\n embed.add_field(name=\"p.resume\" , value=\"For Resume Music🙂\" , inline=False)\n embed2 = discord.Embed(colour=discord.Color.blue())\n embed.set_author(name=f\"PentCode Bot Commands\")\n embed.add_field(name=\"[ +18 Commands ]\" , value=\"---------------------------\" , inline=False)\n embed.add_field(name=\"p.blowjob\" , value=\"BlowJob Gif :) \" , inline=False)\n await ctx.send(embed=embed)\n await ctx.send(embed=embed2)\n# https://discord.com/oauth2/authorize?client_id=838436903887306772&permissions=42949672878&scope=bot\nkeep_alive()\nclient.run(\"ODc5MzAxMTg2MTI0MTQ4ODE3.YSNvCw.ejUADWZkEQygam5ZyvFNxk_MB54\")\n", "repo_name": "neu-ma-tic/test9475", "sub_path": "44cda272-9f4d-49ce-b2e1-253bac8befdc/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 24796, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "discord.ext.commands.Bot", "line_number": 32, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 32, "usage_type": "name"}, {"api_name": "discord.Embed", "line_number": 50, "usage_type": "call"}, {"api_name": "discord.ext.commands.CommandNotFound", "line_number": 53, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 53, "usage_type": "name"}, {"api_name": "discord.ext.commands.MissingPermissions", "line_number": 55, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 55, "usage_type": "name"}, {"api_name": "discord.Color", "line_number": 63, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 63, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 73, "usage_type": "call"}, {"api_name": "discord.Color.blue", "line_number": 73, "usage_type": "call"}, {"api_name": "discord.Color", "line_number": 73, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.has_permissions", "line_number": 70, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 70, "usage_type": "name"}, {"api_name": "discord.Member", "line_number": 78, "usage_type": "attribute"}, {"api_name": "discord.utils.get", "line_number": 80, "usage_type": "call"}, {"api_name": "discord.utils", "line_number": 80, "usage_type": "attribute"}, {"api_name": "discord.Embed", "line_number": 89, "usage_type": "call"}, {"api_name": "discord.Color.blue", "line_number": 89, "usage_type": "call"}, {"api_name": "discord.Color", "line_number": 89, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.has_permissions", "line_number": 77, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 77, "usage_type": "name"}, {"api_name": "discord.Member", "line_number": 94, "usage_type": "attribute"}, {"api_name": "discord.utils.get", "line_number": 95, "usage_type": "call"}, {"api_name": "discord.utils", "line_number": 95, "usage_type": "attribute"}, {"api_name": "discord.Embed", "line_number": 98, "usage_type": "call"}, {"api_name": "discord.Color.blue", "line_number": 98, "usage_type": "call"}, {"api_name": "discord.Color", "line_number": 98, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.has_permissions", "line_number": 93, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 93, "usage_type": "name"}, {"api_name": "discord.Member", "line_number": 103, "usage_type": "attribute"}, {"api_name": "discord.Embed", "line_number": 105, "usage_type": "call"}, {"api_name": "discord.Color.blue", "line_number": 105, "usage_type": "call"}, {"api_name": "discord.Color", "line_number": 105, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.has_permissions", "line_number": 102, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 102, "usage_type": "name"}, {"api_name": "discord.Member", "line_number": 110, "usage_type": "attribute"}, {"api_name": "discord.Embed", "line_number": 112, "usage_type": "call"}, {"api_name": "discord.Color.blue", "line_number": 112, "usage_type": "call"}, {"api_name": "discord.Color", "line_number": 112, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.has_permissions", "line_number": 109, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 109, "usage_type": "name"}, {"api_name": "discord.Game", "line_number": 135, "usage_type": "call"}, {"api_name": "discord.ext.commands.check", "line_number": 132, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 132, "usage_type": "name"}, {"api_name": "discord.Game", "line_number": 144, "usage_type": "call"}, {"api_name": "discord.ext.commands.check", "line_number": 141, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 141, "usage_type": "name"}, {"api_name": "discord.Member", "line_number": 153, "usage_type": "attribute"}, {"api_name": "discord.Embed", "line_number": 156, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 163, "usage_type": "call"}, {"api_name": "discord.Color.blue", "line_number": 163, "usage_type": "call"}, {"api_name": "discord.Color", "line_number": 163, "usage_type": "attribute"}, {"api_name": "discord.Member", "line_number": 167, "usage_type": "attribute"}, {"api_name": "discord.Guild", "line_number": 170, "usage_type": "attribute"}, {"api_name": "discord.Embed", "line_number": 172, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 188, "usage_type": "call"}, {"api_name": "discord.Member", "line_number": 209, "usage_type": "attribute"}, {"api_name": "discord.Embed", "line_number": 216, "usage_type": "call"}, {"api_name": "discord.Member", "line_number": 231, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 233, "usage_type": "call"}, {"api_name": "aiohttp.ClientSession", "line_number": 236, "usage_type": "call"}, {"api_name": "discord.File", "line_number": 240, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 242, "usage_type": "call"}, {"api_name": "discord.Member", "line_number": 247, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 249, "usage_type": "call"}, {"api_name": "aiohttp.ClientSession", "line_number": 252, "usage_type": "call"}, {"api_name": "discord.File", "line_number": 256, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 258, "usage_type": "call"}, {"api_name": "discord.Member", "line_number": 263, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 265, "usage_type": "call"}, {"api_name": "aiohttp.ClientSession", "line_number": 268, "usage_type": "call"}, {"api_name": "discord.File", "line_number": 272, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 274, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 281, "usage_type": "call"}, {"api_name": "aiohttp.ClientSession", "line_number": 284, "usage_type": "call"}, {"api_name": "discord.File", "line_number": 288, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 290, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 296, "usage_type": "call"}, {"api_name": "aiohttp.ClientSession", "line_number": 299, "usage_type": "call"}, {"api_name": "discord.File", "line_number": 303, "usage_type": "call"}, {"api_name": "discord.Embed", "line_number": 305, "usage_type": "call"}, {"api_name": "discord.Member", "line_number": 311, "usage_type": "attribute"}, {"api_name": "discord.Member", "line_number": 318, "usage_type": "attribute"}, {"api_name": "youtube_dl.utils", "line_number": 325, "usage_type": "attribute"}, {"api_name": "youtube_dl.YoutubeDL", "line_number": 344, "usage_type": "call"}, {"api_name": "discord.PCMVolumeTransformer", "line_number": 346, "usage_type": "attribute"}, {"api_name": "asyncio.get_event_loop", "line_number": 355, "usage_type": "call"}, {"api_name": "discord.utils.get", "line_number": 369, "usage_type": "call"}, {"api_name": "discord.utils", "line_number": 369, "usage_type": "attribute"}, {"api_name": "discord.Embed", "line_number": 372, "usage_type": "call"}, {"api_name": "discord.Color.dark_gold", "line_number": 372, "usage_type": "call"}, {"api_name": "discord.Color", "line_number": 372, "usage_type": "attribute"}, {"api_name": "random.choices", "line_number": 389, "usage_type": "call"}, {"api_name": "string.ascii_letters", "line_number": 389, "usage_type": "attribute"}, {"api_name": "string.digits", "line_number": 389, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.has_permissions", "line_number": 387, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 387, "usage_type": "name"}, {"api_name": "discord.ext.commands.has_permissions", "line_number": 393, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 393, "usage_type": "name"}, {"api_name": "urllib.request.request.urlopen", "line_number": 410, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 410, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 410, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 411, "usage_type": "call"}, {"api_name": "discord.FFmpegPCMAudio", "line_number": 418, "usage_type": "call"}, {"api_name": "discord.ext.commands.check", "line_number": 428, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 428, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 461, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 471, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 481, "usage_type": "call"}, {"api_name": "datetime.datetime.datetime.strptime", "line_number": 482, "usage_type": "call"}, {"api_name": "datetime.datetime.datetime", "line_number": 482, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 482, "usage_type": "name"}, {"api_name": "discord.Embed", "line_number": 483, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 496, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 506, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 516, "usage_type": "call"}, {"api_name": "datetime.datetime.datetime.strptime", "line_number": 517, "usage_type": "call"}, {"api_name": "datetime.datetime.datetime", "line_number": 517, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 517, "usage_type": "name"}, {"api_name": "discord.Embed", "line_number": 518, "usage_type": "call"}, {"api_name": "discord.ext.commands.has_permissions", "line_number": 528, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 528, "usage_type": "name"}, {"api_name": "discord.Embed", "line_number": 563, "usage_type": "call"}, {"api_name": "discord.Color.blue", "line_number": 563, "usage_type": "call"}, {"api_name": "discord.Color", "line_number": 563, "usage_type": "attribute"}, {"api_name": "discord.Embed", "line_number": 591, "usage_type": "call"}, {"api_name": "discord.Color.blue", "line_number": 591, "usage_type": "call"}, {"api_name": "discord.Color", "line_number": 591, "usage_type": "attribute"}, {"api_name": "keep_alive.keep_alive", "line_number": 598, "usage_type": "call"}]} +{"seq_id": "7343450197", "text": "import requests\nimport json\nfrom random import choice\n\n\nclass Proxies:\n def __init__(self, type='http'):\n self.proxies = []\n self.type = type\n self.update()\n\n def update(self):\n url = 'http://lab.crossincode.com/proxy/get/'\n params = {\n 'num': 5000,\n 'head': self.type\n }\n ret = requests.get(url, params=params)\n\n if ret.status_code != 200:\n print(\"请求错误:\", ret.text)\n return\n\n jsonret = json.loads(ret.text)\n\n if 'error' in jsonret:\n print('获取ip池失败')\n\n proxies = jsonret['proxies']\n for proxy in proxies:\n self.proxies.append(proxy[self.type])\n\n def get_proxies(self):\n return self.proxies\n\n def get_random(self):\n return choice(self.proxies)\n\n\nif __name__ == '__main__':\n http = Proxies()\n\n print(http.get_random())\n\n url = 'http://hjwblog.com'\n proxies = {'http' : '114.99.17.184:808'}\n response = requests.get(url, proxies=proxies)\n print(requests)\n", "repo_name": "philhuan/EnterpriseInformation", "sub_path": "proxies/proxies.py", "file_name": "proxies.py", "file_ext": "py", "file_size_in_byte": 1067, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "requests.get", "line_number": 18, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 24, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 37, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 47, "usage_type": "call"}]} +{"seq_id": "38869935403", "text": "import json\nimport os\nimport time\nimport zipfile\n\nfrom termcolor import cprint as print\n\nfrom ...enums import EnvironmentType, HookTypes\nfrom ...tools.hooksmanager import hooksManager\nfrom ...tools.configuration import ConfigurationTool, ConfigKey\nfrom ...tools.template import TemplateTool\nfrom ...tools.boto import BotoTool\nfrom .ideploymentaction import IDeploymentAction\n\n\nclass CloudFormationDeployment(IDeploymentAction):\n\t\"\"\" Deployment through AWS CloudFormation\n\t\"\"\"\n\n\t@classmethod\n\tdef shouldExecute(cls):\n\t\t\"\"\" Check if the Action should be deployed\n\t\t\"\"\"\n\t\t# Check if there is an template\n\t\treturn os.path.exists(\"template.yaml\")\n\n\tdef start(self, environType, **kwargs):\n\t\t\"\"\" Start the deployment\n\t\t\"\"\"\n\t\t# Get the configs\n\t\tConfigurationTool.readConfig()\n\n\t\t# Check if there is an template\n\t\tif os.path.exists(\"template.yaml\") is False:\n\t\t\traise Exception(\"Cant find CloudFormation template: 'template.yaml'\")\n\n\t\t# Save the environment type\n\t\tself.environment = environType\n\n\t\t# Execute the PRE_COMPILE hooks\n\t\thooksManager.executeHooks(environType, HookTypes.PRE_COMPILE)\n\n\t\t# Create a temporary directory\n\t\tprint(\"Creating environment\")\n\t\tself._createTempDir()\n\n\t\t# Create a new temporary template\n\t\tprint(\"Creating template\")\n\t\ttry:\n\t\t\tparameters = self._createTemporaryTemplate()\n\t\texcept Exception as e:\n\t\t\tprint(e, \"red\")\n\t\t\treturn False\n\n\t\t# Check if there are other parameters\n\t\tparameters = self._checkParameters(parameters)\n\n\t\t# Execute the POST_COMPILE hooks\n\t\thooksManager.executeHooks(environType, HookTypes.POST_COMPILE)\n\n\t\t# Execute the PRE_INSTALL hooks\n\t\thooksManager.executeHooks(environType, HookTypes.PRE_INSTALL)\n\n\t\t# Check the dependencies\n\t\tprint(\"Installing dependencies\")\n\t\tself._checkDependencies()\n\n\t\t# Execute the POST_INSTALL hooks\n\t\thooksManager.executeHooks(environType, HookTypes.POST_INSTALL)\n\n\t\t# Execute the PRE_UPLOAD hooks\n\t\thooksManager.executeHooks(environType, HookTypes.PRE_UPLOAD)\n\n\t\t# Zip it all\n\t\tprint(\"Zipping content\")\n\t\tzipName = self._zipContent()\n\n\t\t# Upload the zip\n\t\tprint(\"Uploading to S3\")\n\t\ts3Location = self._uploadToS3(zipName)\n\n\t\t# Execute the POST_UPLOAD hooks\n\t\thooksManager.executeHooks(environType, HookTypes.POST_UPLOAD)\n\n\t\t# Execute the PRE_DEPLOYMENT hooks\n\t\thooksManager.executeHooks(environType, HookTypes.PRE_DEPLOYMENT)\n\n\t\t# Send it to CloudFormation\n\t\tprint(\"CloudFormation deploying\")\n\t\t# Execute CloudFormation\n\t\tstatus = self._cloudformationDeploy(parameters, s3Location)\n\n\t\t# Execute the PRE_DEPLOYMENT hooks\n\t\thooksManager.executeHooks(environType, HookTypes.POST_DEPLOYMENT)\n\n\t\t# Check if all is well\n\t\tif status is False:\n\t\t\treturn False\n\t\treturn True\n\n\tdef _createTemporaryTemplate(self):\n\t\t\"\"\" Create a temporary template\n\n\t\t\tReturns a dict with the parameters\n\t\t\"\"\"\n\t\t# Get the template\n\t\tf = open(\"template.yaml\", \"r\")\n\t\ttemplate = f.read()\n\t\tf.close()\n\t\ttemplate = TemplateTool.parseTemplate(template)\n\n\t\t# Check the environment\n\t\tif self.environment == EnvironmentType.DEVELOPMENT:\n\t\t\tif ConfigurationTool.getConfig(ConfigKey.DEV_SUFFIX) is True:\n\t\t\t\t# Add the dev suffix to the items\n\t\t\t\ttemplate = TemplateTool.addSuffixToItems(template)\n\n\t\t# Check the parameters\n\t\ttemplate, parameters = TemplateTool.checkVariables(template)\n\n\t\t# Save the template\n\t\tf = open(os.path.join(self.location, \".deployment.template.json\"), \"w\")\n\t\tf.write(json.dumps(template))\n\t\tf.close()\n\n\t\t# Add the basic parameters\n\t\tparameters['environment'] = self.environment\n\t\tparameters['stackName'] = ConfigurationTool.getConfig(ConfigKey.STACK_NAME) + (\"_development\" if ConfigurationTool.getConfig(ConfigKey.DEV_SUFFIX) is True and self.environment == EnvironmentType.DEVELOPMENT else \"\")\n\t\tparameters['projectName'] = ConfigurationTool.getConfig(ConfigKey.STACK_NAME)\n\n\t\treturn parameters\n\n\tdef _zipContent(self):\n\t\t\"\"\" Zip the current directory\n\n\t\t\tReturns the zip filename\n\t\t\"\"\"\n\t\t# Create a list of ignored folders\n\t\tignoredFolders = [\".git\", \".svn\", \".pete\", \".vscode\", \"seeders\", \".cache\"]\n\n\t\t# Create a filename\n\t\tzipFileName = \"pete_%s.zip\" % int(time.time())\n\n\t\t# Create the zip file\n\t\twith zipfile.ZipFile(os.path.join(self.location, zipFileName), \"w\", zipfile.ZIP_DEFLATED) as zipFile:\n\t\t\t# Walk through all the files\n\t\t\tfor root, dirs, files in os.walk(self.location):\n\t\t\t\t# Check the ignored folders\n\t\t\t\tgoToNext = False\n\t\t\t\tfor ignoredFolderName in ignoredFolders:\n\t\t\t\t\tif ignoredFolderName in root:\n\t\t\t\t\t\tgoToNext = True\n\t\t\t\t\t\tbreak\n\n\t\t\t\t# Check if we found a ignored folder\n\t\t\t\tif goToNext is True:\n\t\t\t\t\tcontinue\n\n\t\t\t\t# Walk throught the files of the directory\n\t\t\t\tfor fileName in files:\n\t\t\t\t\t# Check if this is an zip\n\t\t\t\t\tif \".zip\" in fileName:\n\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t# Add them to the zip file\n\t\t\t\t\tarcname = os.path.join(root, fileName)[len(self.location):]\n\t\t\t\t\tzipFile.write(os.path.join(root, fileName), arcname=arcname)\n\n\t\treturn zipFileName\n\n\tdef _uploadToS3(self, zipName):\n\t\t\"\"\" Upload the zip file to S3\n\t\t\"\"\"\n\t\t# Create a full filename\n\t\tfullFileName = \"%s/%s\" % ((ConfigurationTool.getConfig(ConfigKey.STACK_NAME).lower()), zipName)\n\n\t\t# Get the bucket name and profile\n\t\tbucketName = self._getDeploymentBucketName()\n\t\tprofileName = self._getDeploymentProfile()\n\t\tregion = self._getDeploymentRegion()\n\n\t\t# Upload the file\n\t\tBotoTool.uploadToS3(\n\t\t\tfromPath=os.path.join(self.location, zipName),\n\t\t\ttoBucket=bucketName,\n\t\t\ttoKey=fullFileName,\n\t\t\tregion=region,\n\t\t\tprofile=profileName\n\t\t)\n\n\t\treturn fullFileName\n\n\tdef _getDeploymentBucketName(self):\n\t\t\"\"\" Get the deployment Bucket name from the config\n\n\t\t\tReturns name of the bucket\n\t\t\"\"\"\n\t\t# Check if we use the development environment\n\t\tif self.environment == EnvironmentType.DEVELOPMENT:\n\t\t\t# Check if the DEV_BUCKET is in the projectConfig\n\t\t\tbucketName = ConfigurationTool.getConfig(ConfigKey.DEV_BUCKET)\n\n\t\t# This is the production environment\n\t\telse:\n\t\t\t# Check if the PROD_BUCKET is in the projectConfig\n\t\t\tbucketName = ConfigurationTool.getConfig(ConfigKey.PROD_BUCKET)\n\n\t\treturn bucketName.strip()\n\n\tdef _getDeploymentProfile(self):\n\t\t\"\"\" Get the deployment AWS Profile\n\n\t\t\tReturns name of profile\n\t\t\"\"\"\n\t\t# Check if we use the development environment\n\t\tif self.environment == EnvironmentType.DEVELOPMENT:\n\t\t\t# Check if the DEV_PROFILE is in the projectConfig\n\t\t\tprofileName = ConfigurationTool.getConfig(ConfigKey.DEV_PROFILE)\n\n\t\t# This is the production environment\n\t\telse:\n\t\t\t# Check if the PROD_PROFILE is in the projectConfig\n\t\t\tprofileName = ConfigurationTool.getConfig(ConfigKey.PROD_PROFILE)\n\n\t\treturn profileName.strip()\n\n\tdef _getDeploymentRegion(self):\n\t\t\"\"\" Get the deployment AWS Region\n\n\t\t\tReturns name of region\n\t\t\"\"\"\n\t\t# Default option for region\n\t\tregion = None\n\n\t\t# Check if we use the development environment\n\t\tif self.environment == EnvironmentType.DEVELOPMENT:\n\t\t\t# Check if the DEV_REGION is in the projectConfig\n\t\t\tregion = ConfigurationTool.getConfig(ConfigKey.DEV_REGION)\n\n\t\t# This is the production environment\n\t\telse:\n\t\t\t# Check if the PROD_REGION is in the projectConfig\n\t\t\tregion = ConfigurationTool.getConfig(ConfigKey.PROD_REGION)\n\n\t\treturn region\n\n\tdef _cloudformationDeploy(self, parameters, s3Location):\n\t\t\"\"\" Deploy to CloudFormation\n\t\t\"\"\"\n\t\t# Get the information\n\t\tdeploymentBucket = self._getDeploymentBucketName()\n\t\tprofileName = self._getDeploymentProfile()\n\t\tregion = self._getDeploymentRegion()\n\t\tstackName = ConfigurationTool.getConfig(ConfigKey.STACK_NAME)\n\n\t\t# Get the boto client\n\t\tclient = BotoTool._getClient(\"cloudformation\", region=region, profile=profileName)\n\n\t\t# Check if the stack exists\n\t\tstackExists = False\n\t\ttry:\n\t\t\tclient.describe_stacks(StackName=stackName)\n\t\texcept Exception:\n\t\t\t# There are currently no stacks in CloudFormation\n\t\t\tpass\n\t\telse:\n\t\t\t# The stack exists\n\t\t\tstackExists = True\n\n\t\t# Upload the file to S3\n\t\ttemplatePath = os.path.join(self.location, \".deployment.template.json\")\n\t\ttemplateName = \"%s/template-%s.json\" % (stackName.lower(), str(int(time.time())))\n\t\ttemplateUrl = BotoTool.uploadToS3(\n\t\t\tfromPath=templatePath,\n\t\t\ttoBucket=deploymentBucket,\n\t\t\ttoKey=templateName,\n\t\t\tregion=region,\n\t\t\tprofile=profileName\n\t\t)\n\n\t\t# Create a change set name\n\t\tchangeStackName = \"%s%s\" % (stackName, str(int(time.time())))\n\n\t\t# Create the change set parameters\n\t\tchangeStackParameters = [\n\t\t\t{\"ParameterKey\": \"deploymentBucket\", \"ParameterValue\": deploymentBucket},\n\t\t\t{\"ParameterKey\": \"s3FileName\", \"ParameterValue\": s3Location}\n\t\t]\n\n\t\t# Add extra parameters\n\t\tfor key, value in parameters.items():\n\t\t\tchangeStackParameters.append({\"ParameterKey\": key, \"ParameterValue\": str(value)})\n\n\t\t# Check if the stack exists\n\t\tif stackExists is False:\n\t\t\t# Create the stack\n\t\t\tclient.create_stack(\n\t\t\t\tStackName=stackName,\n\t\t\t\tTemplateURL=templateUrl,\n\t\t\t\tParameters=changeStackParameters,\n\t\t\t\tCapabilities=[\"CAPABILITY_IAM\", \"CAPABILITY_NAMED_IAM\"],\n\t\t\t\tTags=[\n\t\t\t\t\t{\"Key\": \"Stack\", \"Value\": stackName},\n\t\t\t\t]\n\t\t\t)\n\n\t\telse:\n\t\t\t# Create a change set\n\t\t\tclient.create_change_set(\n\t\t\t\tStackName=stackName,\n\t\t\t\tChangeSetName=changeStackName,\n\t\t\t\tTemplateURL=templateUrl,\n\t\t\t\tParameters=changeStackParameters,\n\t\t\t\tCapabilities=[\"CAPABILITY_IAM\", \"CAPABILITY_NAMED_IAM\"],\n\t\t\t\tTags=[\n\t\t\t\t\t{\"Key\": \"Stack\", \"Value\": stackName},\n\t\t\t\t]\n\t\t\t)\n\n\t\t\t# Wait for the results\n\t\t\twhile True:\n\t\t\t\t# Get the change set\n\t\t\t\tchangeSet = client.describe_change_set(StackName=stackName, ChangeSetName=changeStackName)\n\n\t\t\t\t# Try to get the status\n\t\t\t\ttry:\n\t\t\t\t\tstackStatus = changeSet[\"Status\"]\n\t\t\t\t\tif \"StatusReason\" in changeSet:\n\t\t\t\t\t\tstatusText = changeSet[\"StatusReason\"]\n\t\t\t\t\telse:\n\t\t\t\t\t\tstatusText = \"\"\n\t\t\t\texcept Exception:\n\t\t\t\t\tstackStatus = \"CREATE_IN_PROGRESS\"\n\n\t\t\t\t# Check the status\n\t\t\t\tif stackStatus[-7:] == \"_FAILED\" or stackStatus == \"FAILED\":\n\t\t\t\t\tprint(statusText, \"red\")\n\t\t\t\t\treturn False\n\t\t\t\telif stackStatus[-9:] == \"_COMPLETE\":\n\t\t\t\t\tbreak\n\n\t\t\t\t# Wait a little\n\t\t\t\ttime.sleep(15)\n\n\t\t\t# Apply the change set\n\t\t\tclient.execute_change_set(\n\t\t\t\tChangeSetName=changeStackName,\n\t\t\t\tStackName=stackName\n\t\t\t)\n\n\t\t# Wait for the results\n\t\twhile True:\n\t\t\t# Get the stack\n\t\t\tstack = client.describe_stacks(StackName=stackName)\n\n\t\t\t# Try to get the status\n\t\t\ttry:\n\t\t\t\tstackStatus = stack[\"Stacks\"][0][\"StackStatus\"]\n\t\t\texcept Exception:\n\t\t\t\tstackStatus = \"CREATE_IN_PROGRESS\"\n\n\t\t\t# Check the status\n\t\t\tif \"IN_PROGRESS\" in stackStatus:\n\t\t\t\tpass\n\t\t\telif stackStatus[-7:] == \"_FAILED\" or \"ROLLBACK\" in stackStatus:\n\t\t\t\treturn False\n\t\t\telif stackStatus[-9:] == \"_COMPLETE\":\n\t\t\t\treturn True\n\n\t\t\t# Wait a little\n\t\t\ttime.sleep(15)\n\n\tdef _checkParameters(self, parameters):\n\t\t\"\"\" Check if there are other parameters we need information about\n\t\t\"\"\"\n\t\t# Walk through the parameters\n\t\tfor parameterName in parameters:\n\t\t\t# Check if there is an value\n\t\t\tif parameters[parameterName] in [\"String\", \"Number\", \"List\", \"CommaDelimitedList\"]:\n\t\t\t\t# Check if we have the parameter in de project config\n\t\t\t\tparametersConfig = ConfigurationTool.getConfig(ConfigKey.PARAMETERS)\n\t\t\t\tif parametersConfig is None:\n\t\t\t\t\tparametersConfig = {}\n\n\t\t\t\t# Check if the environment exists in the config\n\t\t\t\tif str(self.environment) in parametersConfig:\n\t\t\t\t\tif parameterName in parametersConfig[str(self.environment)]:\n\t\t\t\t\t\tparameters[parameterName] = parametersConfig[str(self.environment)][parameterName]\n\t\t\t\t\t\tcontinue\n\n\t\t\t\t# We dont have a value\n\t\t\t\traise Exception(\"Has no value for parameter '%s'\" % parameterName)\n\n\t\treturn parameters\n", "repo_name": "totalpunch/TPD-Pete", "sub_path": "tpd_pete/actions/deployment/cloudformationdeployment.py", "file_name": "cloudformationdeployment.py", "file_ext": "py", "file_size_in_byte": 11314, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "ideploymentaction.IDeploymentAction", "line_number": 16, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "tools.configuration.ConfigurationTool.readConfig", "line_number": 31, "usage_type": "call"}, {"api_name": "tools.configuration.ConfigurationTool", "line_number": 31, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "tools.hooksmanager.hooksManager.executeHooks", "line_number": 41, "usage_type": "call"}, {"api_name": "tools.hooksmanager.hooksManager", "line_number": 41, "usage_type": "name"}, {"api_name": "enums.HookTypes.PRE_COMPILE", "line_number": 41, "usage_type": "attribute"}, {"api_name": "enums.HookTypes", "line_number": 41, "usage_type": "name"}, {"api_name": "termcolor.cprint", "line_number": 44, "usage_type": "call"}, {"api_name": "termcolor.cprint", "line_number": 48, "usage_type": "call"}, {"api_name": "termcolor.cprint", "line_number": 52, "usage_type": "call"}, {"api_name": "tools.hooksmanager.hooksManager.executeHooks", "line_number": 59, "usage_type": "call"}, {"api_name": "tools.hooksmanager.hooksManager", "line_number": 59, "usage_type": "name"}, {"api_name": "enums.HookTypes.POST_COMPILE", "line_number": 59, "usage_type": "attribute"}, {"api_name": "enums.HookTypes", "line_number": 59, "usage_type": "name"}, {"api_name": "tools.hooksmanager.hooksManager.executeHooks", "line_number": 62, "usage_type": "call"}, {"api_name": "tools.hooksmanager.hooksManager", "line_number": 62, "usage_type": "name"}, {"api_name": "enums.HookTypes.PRE_INSTALL", "line_number": 62, "usage_type": "attribute"}, {"api_name": "enums.HookTypes", "line_number": 62, "usage_type": "name"}, {"api_name": "termcolor.cprint", "line_number": 65, "usage_type": "call"}, {"api_name": "tools.hooksmanager.hooksManager.executeHooks", "line_number": 69, "usage_type": "call"}, {"api_name": "tools.hooksmanager.hooksManager", "line_number": 69, "usage_type": "name"}, {"api_name": "enums.HookTypes.POST_INSTALL", "line_number": 69, "usage_type": "attribute"}, {"api_name": "enums.HookTypes", "line_number": 69, "usage_type": "name"}, {"api_name": "tools.hooksmanager.hooksManager.executeHooks", "line_number": 72, "usage_type": "call"}, {"api_name": "tools.hooksmanager.hooksManager", "line_number": 72, "usage_type": "name"}, {"api_name": "enums.HookTypes.PRE_UPLOAD", "line_number": 72, "usage_type": "attribute"}, {"api_name": "enums.HookTypes", "line_number": 72, "usage_type": "name"}, {"api_name": "termcolor.cprint", "line_number": 75, "usage_type": "call"}, {"api_name": "termcolor.cprint", "line_number": 79, "usage_type": "call"}, {"api_name": "tools.hooksmanager.hooksManager.executeHooks", "line_number": 83, "usage_type": "call"}, {"api_name": "tools.hooksmanager.hooksManager", "line_number": 83, "usage_type": "name"}, {"api_name": "enums.HookTypes.POST_UPLOAD", "line_number": 83, "usage_type": "attribute"}, {"api_name": "enums.HookTypes", "line_number": 83, "usage_type": "name"}, {"api_name": "tools.hooksmanager.hooksManager.executeHooks", "line_number": 86, "usage_type": "call"}, {"api_name": "tools.hooksmanager.hooksManager", "line_number": 86, "usage_type": "name"}, {"api_name": "enums.HookTypes.PRE_DEPLOYMENT", "line_number": 86, "usage_type": "attribute"}, {"api_name": "enums.HookTypes", "line_number": 86, "usage_type": "name"}, {"api_name": "termcolor.cprint", "line_number": 89, "usage_type": "call"}, {"api_name": "tools.hooksmanager.hooksManager.executeHooks", "line_number": 94, "usage_type": "call"}, {"api_name": "tools.hooksmanager.hooksManager", "line_number": 94, "usage_type": "name"}, {"api_name": "enums.HookTypes.POST_DEPLOYMENT", "line_number": 94, "usage_type": "attribute"}, {"api_name": "enums.HookTypes", "line_number": 94, "usage_type": "name"}, {"api_name": "tools.template.TemplateTool.parseTemplate", "line_number": 110, "usage_type": "call"}, {"api_name": "tools.template.TemplateTool", "line_number": 110, "usage_type": "name"}, {"api_name": "enums.EnvironmentType.DEVELOPMENT", "line_number": 113, "usage_type": "attribute"}, {"api_name": "enums.EnvironmentType", "line_number": 113, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigurationTool.getConfig", "line_number": 114, "usage_type": "call"}, {"api_name": "tools.configuration.ConfigurationTool", "line_number": 114, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigKey.DEV_SUFFIX", "line_number": 114, "usage_type": "attribute"}, {"api_name": "tools.configuration.ConfigKey", "line_number": 114, "usage_type": "name"}, {"api_name": "tools.template.TemplateTool.addSuffixToItems", "line_number": 116, "usage_type": "call"}, {"api_name": "tools.template.TemplateTool", "line_number": 116, "usage_type": "name"}, {"api_name": "tools.template.TemplateTool.checkVariables", "line_number": 119, "usage_type": "call"}, {"api_name": "tools.template.TemplateTool", "line_number": 119, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 122, "usage_type": "call"}, {"api_name": "os.path", "line_number": 122, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 123, "usage_type": "call"}, {"api_name": "tools.configuration.ConfigurationTool.getConfig", "line_number": 128, "usage_type": "call"}, {"api_name": "tools.configuration.ConfigurationTool", "line_number": 128, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigKey.STACK_NAME", "line_number": 128, "usage_type": "attribute"}, {"api_name": "tools.configuration.ConfigKey", "line_number": 128, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigKey.DEV_SUFFIX", "line_number": 128, "usage_type": "attribute"}, {"api_name": "enums.EnvironmentType.DEVELOPMENT", "line_number": 128, "usage_type": "attribute"}, {"api_name": "enums.EnvironmentType", "line_number": 128, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigurationTool.getConfig", "line_number": 129, "usage_type": "call"}, {"api_name": "tools.configuration.ConfigurationTool", "line_number": 129, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigKey.STACK_NAME", "line_number": 129, "usage_type": "attribute"}, {"api_name": "tools.configuration.ConfigKey", "line_number": 129, "usage_type": "name"}, {"api_name": "time.time", "line_number": 142, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 145, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 145, "usage_type": "call"}, {"api_name": "os.path", "line_number": 145, "usage_type": "attribute"}, {"api_name": "zipfile.ZIP_DEFLATED", "line_number": 145, "usage_type": "attribute"}, {"api_name": "os.walk", "line_number": 147, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 166, "usage_type": "call"}, {"api_name": "os.path", "line_number": 166, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 167, "usage_type": "call"}, {"api_name": "os.path", "line_number": 167, "usage_type": "attribute"}, {"api_name": "tools.configuration.ConfigurationTool.getConfig", "line_number": 175, "usage_type": "call"}, {"api_name": "tools.configuration.ConfigurationTool", "line_number": 175, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigKey.STACK_NAME", "line_number": 175, "usage_type": "attribute"}, {"api_name": "tools.configuration.ConfigKey", "line_number": 175, "usage_type": "name"}, {"api_name": "tools.boto.BotoTool.uploadToS3", "line_number": 183, "usage_type": "call"}, {"api_name": "tools.boto.BotoTool", "line_number": 183, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 184, "usage_type": "call"}, {"api_name": "os.path", "line_number": 184, "usage_type": "attribute"}, {"api_name": "enums.EnvironmentType.DEVELOPMENT", "line_number": 199, "usage_type": "attribute"}, {"api_name": "enums.EnvironmentType", "line_number": 199, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigurationTool.getConfig", "line_number": 201, "usage_type": "call"}, {"api_name": "tools.configuration.ConfigurationTool", "line_number": 201, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigKey.DEV_BUCKET", "line_number": 201, "usage_type": "attribute"}, {"api_name": "tools.configuration.ConfigKey", "line_number": 201, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigurationTool.getConfig", "line_number": 206, "usage_type": "call"}, {"api_name": "tools.configuration.ConfigurationTool", "line_number": 206, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigKey.PROD_BUCKET", "line_number": 206, "usage_type": "attribute"}, {"api_name": "tools.configuration.ConfigKey", "line_number": 206, "usage_type": "name"}, {"api_name": "enums.EnvironmentType.DEVELOPMENT", "line_number": 216, "usage_type": "attribute"}, {"api_name": "enums.EnvironmentType", "line_number": 216, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigurationTool.getConfig", "line_number": 218, "usage_type": "call"}, {"api_name": "tools.configuration.ConfigurationTool", "line_number": 218, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigKey.DEV_PROFILE", "line_number": 218, "usage_type": "attribute"}, {"api_name": "tools.configuration.ConfigKey", "line_number": 218, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigurationTool.getConfig", "line_number": 223, "usage_type": "call"}, {"api_name": "tools.configuration.ConfigurationTool", "line_number": 223, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigKey.PROD_PROFILE", "line_number": 223, "usage_type": "attribute"}, {"api_name": "tools.configuration.ConfigKey", "line_number": 223, "usage_type": "name"}, {"api_name": "enums.EnvironmentType.DEVELOPMENT", "line_number": 236, "usage_type": "attribute"}, {"api_name": "enums.EnvironmentType", "line_number": 236, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigurationTool.getConfig", "line_number": 238, "usage_type": "call"}, {"api_name": "tools.configuration.ConfigurationTool", "line_number": 238, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigKey.DEV_REGION", "line_number": 238, "usage_type": "attribute"}, {"api_name": "tools.configuration.ConfigKey", "line_number": 238, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigurationTool.getConfig", "line_number": 243, "usage_type": "call"}, {"api_name": "tools.configuration.ConfigurationTool", "line_number": 243, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigKey.PROD_REGION", "line_number": 243, "usage_type": "attribute"}, {"api_name": "tools.configuration.ConfigKey", "line_number": 243, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigurationTool.getConfig", "line_number": 254, "usage_type": "call"}, {"api_name": "tools.configuration.ConfigurationTool", "line_number": 254, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigKey.STACK_NAME", "line_number": 254, "usage_type": "attribute"}, {"api_name": "tools.configuration.ConfigKey", "line_number": 254, "usage_type": "name"}, {"api_name": "tools.boto.BotoTool._getClient", "line_number": 257, "usage_type": "call"}, {"api_name": "tools.boto.BotoTool", "line_number": 257, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 271, "usage_type": "call"}, {"api_name": "os.path", "line_number": 271, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 272, "usage_type": "call"}, {"api_name": "tools.boto.BotoTool.uploadToS3", "line_number": 273, "usage_type": "call"}, {"api_name": "tools.boto.BotoTool", "line_number": 273, "usage_type": "name"}, {"api_name": "time.time", "line_number": 282, "usage_type": "call"}, {"api_name": "termcolor.cprint", "line_number": 337, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 343, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 371, "usage_type": "call"}, {"api_name": "tools.configuration.ConfigurationTool.getConfig", "line_number": 381, "usage_type": "call"}, {"api_name": "tools.configuration.ConfigurationTool", "line_number": 381, "usage_type": "name"}, {"api_name": "tools.configuration.ConfigKey.PARAMETERS", "line_number": 381, "usage_type": "attribute"}, {"api_name": "tools.configuration.ConfigKey", "line_number": 381, "usage_type": "name"}]} +{"seq_id": "4994267972", "text": "from datetime import datetime\nfrom typing import Dict, Type\nfrom uuid import uuid4\n\nfrom sanic import Sanic\nfrom sanic.log import logger\nfrom sanic.request import Request\nfrom sanic.response import json\n\nfrom doxa_competition.evaluation import EvaluationDriver\nfrom doxa_competition.events import EvaluationEvent\nfrom doxa_competition.proto.umpire.scheduling import (\n DeregisterDriverRequest,\n RegisterDriverRequest,\n UmpireSchedulingServiceStub,\n)\nfrom doxa_competition.utils import make_pulsar_client, make_umpire_channel\n\n\ndef make_evaluation_event(request: Request) -> EvaluationEvent:\n \"\"\"Validates and creates an evaluation event from the evaluation request.\n\n Args:\n request (Request): The incoming HTTP request.\n\n Returns:\n EvaluationEvent: The resulting event.\n \"\"\"\n\n # {\n # \"id\": ...,\n # \"competition_tag\": ...,\n # \"batch_id\": ...,\n # \"queued_at\": ...,\n # \"participants\": [{\n # \"participant_index\": ...,\n # \"agent_id\": ...,\n # \"agent_metadata\": {...},\n # \"enrolment_id\": ...,\n # \"endpoint\": ...,\n # \"auth_token\": ...,\n # }, ...],\n # }\n\n assert \"id\" in request.json\n assert \"competition_tag\" in request.json\n assert \"batch_id\" in request.json\n assert \"queued_at\" in request.json\n assert \"participants\" in request.json\n assert isinstance(request.json[\"participants\"], list)\n assert len(request.json[\"participants\"]) > 0\n\n for participant in request.json[\"participants\"]:\n assert isinstance(participant, dict)\n assert \"participant_index\" in participant\n assert \"agent_id\" in participant\n assert \"agent_metadata\" in participant\n assert isinstance(participant[\"agent_metadata\"], dict)\n assert \"enrolment_id\" in participant\n assert \"endpoint\" in participant\n assert \"storage_endpoint\" in participant\n assert \"upload_id\" in participant\n assert \"auth_token\" in participant\n\n return EvaluationEvent(body=request.json)\n\n\nasync def process_evaluation(\n driver: EvaluationDriver, event: EvaluationEvent, umpire_channel_connection: dict\n):\n try:\n await driver.startup(make_umpire_channel(**umpire_channel_connection))\n await driver._handle(event)\n except Exception as e:\n driver._handle_error(e, \"INTERNAL\")\n finally:\n await driver.teardown()\n\n\ndef make_server(\n drivers: Dict[str, Type[EvaluationDriver]],\n driver_endpoint: str,\n workers: int,\n pulsar_path: str,\n umpire_host: str,\n umpire_port: int,\n):\n driver_uuid = uuid4()\n start_time = datetime.now()\n\n app = Sanic(\"doxa-competition-worker\")\n app.ctx.pulsar_client = make_pulsar_client(pulsar_path=pulsar_path)\n app.ctx.umpire_channel_connection = {\"host\": umpire_host, \"port\": umpire_port}\n\n logger.info(f\"Driver {str(driver_uuid)} is starting with {workers} workers.\")\n\n @app.main_process_start\n async def startup_handler(app, loop):\n app.ctx.umpire_channel = make_umpire_channel(host=umpire_host, port=umpire_port)\n app.ctx.umpire_scheduling = UmpireSchedulingServiceStub(app.ctx.umpire_channel)\n await app.ctx.umpire_scheduling.register_driver(\n RegisterDriverRequest(\n runtime_id=str(driver_uuid),\n competition_tags=list(drivers.keys()),\n endpoint=driver_endpoint,\n workers=workers,\n )\n )\n logger.info(\"Registered with Umpire.\")\n\n @app.main_process_stop\n async def shutdown_handler(app, loop):\n try:\n await app.ctx.umpire_scheduling.deregister_driver(\n DeregisterDriverRequest(\n runtime_id=str(driver_uuid),\n )\n )\n logger.info(\"Successfully deregistered from Umpire.\")\n except:\n logger.error(\"Failed to deregister from Umpire.\")\n\n app.ctx.umpire_channel.close()\n\n @app.get(\"/status\")\n async def status_handler(request: Request):\n return json(\n {\n \"uuid\": str(driver_uuid),\n \"competitions\": list(drivers.keys()),\n \"started_at\": start_time.isoformat(),\n \"workers\": workers,\n }\n )\n\n @app.post(\"/evaluation\")\n async def evaluation_handler(request: Request):\n try:\n event = make_evaluation_event(request)\n\n if event.competition_tag not in drivers:\n logger.warn(\n f\"Failed to process evaluation for competition {event.competition_tag}\"\n )\n raise ValueError\n except:\n return json({\"success\": False}, status=400)\n\n logger.info(f\"Handling evaluation {event.evaluation_id}\")\n request.app.add_task(\n process_evaluation(\n driver=drivers[event.competition_tag](\n event.competition_tag,\n request.app.ctx.pulsar_client,\n ),\n event=event,\n umpire_channel_connection=app.ctx.umpire_channel_connection,\n )\n )\n\n return json({\"success\": True})\n\n return app\n", "repo_name": "DoxaAI/competition-framework", "sub_path": "src/doxa_competition/evaluation/server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 5231, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "25", "api": [{"api_name": "sanic.request.Request", "line_number": 20, "usage_type": "name"}, {"api_name": "doxa_competition.events.EvaluationEvent", "line_number": 65, "usage_type": "call"}, {"api_name": "doxa_competition.events.EvaluationEvent", "line_number": 20, "usage_type": "name"}, {"api_name": "doxa_competition.evaluation.EvaluationDriver", "line_number": 69, "usage_type": "name"}, {"api_name": "doxa_competition.events.EvaluationEvent", "line_number": 69, "usage_type": "name"}, {"api_name": "doxa_competition.utils.make_umpire_channel", "line_number": 72, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 81, "usage_type": "name"}, {"api_name": "typing.Type", "line_number": 81, "usage_type": "name"}, {"api_name": "doxa_competition.evaluation.EvaluationDriver", "line_number": 81, "usage_type": "name"}, {"api_name": "uuid.uuid4", "line_number": 88, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 89, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 89, "usage_type": "name"}, {"api_name": "sanic.Sanic", "line_number": 91, "usage_type": "call"}, {"api_name": "doxa_competition.utils.make_pulsar_client", "line_number": 92, "usage_type": "call"}, {"api_name": "sanic.log.logger.info", "line_number": 95, "usage_type": "call"}, {"api_name": "sanic.log.logger", "line_number": 95, "usage_type": "name"}, {"api_name": "doxa_competition.utils.make_umpire_channel", "line_number": 99, "usage_type": "call"}, {"api_name": "doxa_competition.proto.umpire.scheduling.UmpireSchedulingServiceStub", "line_number": 100, "usage_type": "call"}, {"api_name": "doxa_competition.proto.umpire.scheduling.RegisterDriverRequest", "line_number": 102, "usage_type": "call"}, {"api_name": "sanic.log.logger.info", "line_number": 109, "usage_type": "call"}, {"api_name": "sanic.log.logger", "line_number": 109, "usage_type": "name"}, {"api_name": "doxa_competition.proto.umpire.scheduling.DeregisterDriverRequest", "line_number": 115, "usage_type": "call"}, {"api_name": "sanic.log.logger.info", "line_number": 119, "usage_type": "call"}, {"api_name": "sanic.log.logger", "line_number": 119, "usage_type": "name"}, {"api_name": "sanic.log.logger.error", "line_number": 121, "usage_type": "call"}, {"api_name": "sanic.log.logger", "line_number": 121, "usage_type": "name"}, {"api_name": "sanic.request.Request", "line_number": 126, "usage_type": "name"}, {"api_name": "sanic.response.json", "line_number": 127, "usage_type": "call"}, {"api_name": "sanic.request.Request", "line_number": 137, "usage_type": "name"}, {"api_name": "sanic.log.logger.warn", "line_number": 142, "usage_type": "call"}, {"api_name": "sanic.log.logger", "line_number": 142, "usage_type": "name"}, {"api_name": "sanic.response.json", "line_number": 147, "usage_type": "call"}, {"api_name": "sanic.log.logger.info", "line_number": 149, "usage_type": "call"}, {"api_name": "sanic.log.logger", "line_number": 149, "usage_type": "name"}, {"api_name": "sanic.response.json", "line_number": 161, "usage_type": "call"}]} +{"seq_id": "2807747140", "text": "import json\nimport time\nfrom confluent_kafka import Producer\nimport socket\n\nfrom google_play_scraper import Sort, reviews_all\n\nconf = {'bootstrap.servers': \"pkc-l7pr2.ap-south-1.aws.confluent.cloud:9092\",\n 'client.id': socket.gethostname(),\n 'security.protocol':'SASL_SSL', \n 'sasl.mechanism':'PLAIN', \n 'sasl.username':'FL5OOZQ4OQPATRJZ', \n 'sasl.password':'v2Wbjn3yGNDlGyPwIO+2CRoswrIQC3Ej7d16HXwsrbFt02+9gieNsAt+CwUeImUD'}\n\nproducer = Producer(conf)\n\nresult = reviews_all(\n 'com.havells.havellsone',\n sleep_milliseconds=0, # defaults to 0\n lang='en', # defaults to 'en'\n country='us', # defaults to 'us'\n sort=Sort.MOST_RELEVANT, # defaults to Sort.MOST_RELEVANT\n filter_score_with=5 # defaults to None(means all score)\n)\n\nobj = {\n 'reviewId': '',\n 'userName': '',\n 'userImage': '',\n 'content': '',\n 'score': 0,\n 'thumbsUpCount': 0,\n 'reviewCreatedVersion': '',\n 'replyContent': '',\n 'repliedAt': ''\n}\n\ndef main(event=None, context=None):\n for i in range(len(result)):\n registered_user = result[i]\n print(registered_user)\n obj['reviewId'] = registered_user['reviewId']\n obj['userName'] = registered_user['userName']\n obj['userImage'] = registered_user['userImage']\n obj['content'] = registered_user['content']\n obj['score'] = registered_user['score']\n obj['thumbsUpCount'] = registered_user['thumbsUpCount']\n obj['reviewCreatedVersion'] = registered_user['reviewCreatedVersion']\n obj['replyContent'] = registered_user['replyContent']\n obj['repliedAt'] = registered_user['repliedAt']\n producer.produce(\"test\", key=\"key\", value=json.dumps(obj))\n time.sleep(4)\n\n# if __name__ == \"__main__\":\n# main()\n", "repo_name": "Teja-Ram-Murthy-K/ConsumerProducerConfluent", "sub_path": "producer.py", "file_name": "producer.py", "file_ext": "py", "file_size_in_byte": 1760, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "socket.gethostname", "line_number": 9, "usage_type": "call"}, {"api_name": "confluent_kafka.Producer", "line_number": 15, "usage_type": "call"}, {"api_name": "google_play_scraper.reviews_all", "line_number": 17, "usage_type": "call"}, {"api_name": "google_play_scraper.Sort.MOST_RELEVANT", "line_number": 22, "usage_type": "attribute"}, {"api_name": "google_play_scraper.Sort", "line_number": 22, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 51, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 52, "usage_type": "call"}]} +{"seq_id": "72748395584", "text": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n# generate default secret name\nimport os\nimport kfp\nfrom kfp import components\nfrom kfp import dsl\n\nsecret_name = 'kfp-creds'\nconfiguration_op = components.load_component_from_url('https://raw.githubusercontent.com/kubeflow/pipelines/master/components/ibm-components/commons/config/component.yaml')\ntrain_op = components.load_component_from_url('https://raw.githubusercontent.com/kubeflow/pipelines/master/components/ibm-components/watson/train/component.yaml')\nstore_op = components.load_component_from_url('https://raw.githubusercontent.com/kubeflow/pipelines/master/components/ibm-components/watson/store/component.yaml')\ndeploy_op = components.load_component_from_url('https://raw.githubusercontent.com/kubeflow/pipelines/master/components/ibm-components/watson/deploy/component.yaml')\n\n# Helper function for secret mount and image pull policy\ndef use_ai_pipeline_params(secret_name, secret_volume_mount_path='/app/secrets', image_pull_policy='IfNotPresent'):\n def _use_ai_pipeline_params(task):\n from kubernetes import client as k8s_client\n task = task.add_volume(k8s_client.V1Volume(name=secret_name, # secret_name as volume name\n secret=k8s_client.V1SecretVolumeSource(secret_name=secret_name)))\n task.container.add_volume_mount(k8s_client.V1VolumeMount(mount_path=secret_volume_mount_path, \n name=secret_name))\n task.container.set_image_pull_policy(image_pull_policy)\n return task\n return _use_ai_pipeline_params\n\n\n# create pipelines\n\n@dsl.pipeline(\n name='KFP on WML training',\n description='Kubeflow pipelines running on WML performing tensorflow image recognition.'\n)\ndef kfp_wml_pipeline(\n GITHUB_TOKEN='',\n CONFIG_FILE_URL='https://raw.githubusercontent.com/user/repository/branch/creds.ini',\n train_code='tf-model.zip',\n execution_command='\\'python3 convolutional_network.py --trainImagesFile ${DATA_DIR}/train-images-idx3-ubyte.gz --trainLabelsFile ${DATA_DIR}/train-labels-idx1-ubyte.gz --testImagesFile ${DATA_DIR}/t10k-images-idx3-ubyte.gz --testLabelsFile ${DATA_DIR}/t10k-labels-idx1-ubyte.gz --learningRate 0.001 --trainingIters 20000\\'',\n framework='tensorflow',\n framework_version='1.15',\n runtime = 'python',\n runtime_version='3.6',\n run_definition = 'wml-tensorflow-definition',\n run_name = 'wml-tensorflow-run',\n model_name='wml-tensorflow-mnist',\n scoring_payload='tf-mnist-test-payload.json',\n compute_name='k80',\n compute_nodes='1'\n):\n # op1 - this operation will create the credentials as secrets to be used by other operations\n get_configuration = configuration_op(\n token=GITHUB_TOKEN,\n url=CONFIG_FILE_URL,\n name=secret_name\n )\n\n # op2 - this operation trains the model with the model codes and data saved in the cloud object store\n wml_train = train_op(\n config=get_configuration.output,\n train_code=train_code,\n execution_command=execution_command,\n framework=framework,\n framework_version=framework_version,\n runtime=runtime,\n runtime_version=runtime_version,\n run_definition=run_definition,\n run_name=run_name,\n compute_name=compute_name,\n compute_nodes=compute_nodes\n ).apply(use_ai_pipeline_params(secret_name, image_pull_policy='Always'))\n\n # op3 - this operation stores the model trained above\n wml_store = store_op(\n wml_train.outputs['run_uid'],\n model_name,\n framework=framework,\n framework_version=framework_version,\n runtime_version=runtime_version\n ).apply(use_ai_pipeline_params(secret_name, image_pull_policy='Always'))\n\n # op4 - this operation deploys the model to a web service and run scoring with the payload in the cloud object store\n wml_deploy = deploy_op(\n wml_store.output,\n model_name,\n scoring_payload\n ).apply(use_ai_pipeline_params(secret_name, image_pull_policy='Always'))\n\nif __name__ == '__main__':\n # compile the pipeline\n import kfp.compiler as compiler\n pipeline_filename = kfp_wml_pipeline.__name__ + '.zip'\n compiler.Compiler().compile(kfp_wml_pipeline, pipeline_filename)\n", "repo_name": "GoogleCloudPlatform/training-data-analyst", "sub_path": "courses/machine_learning/deepdive2/production_ml/labs/samples/contrib/ibm-samples/watson/watson_train_serve_pipeline.py", "file_name": "watson_train_serve_pipeline.py", "file_ext": "py", "file_size_in_byte": 5074, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7179, "dataset": "github-code", "pt": "25", "api": [{"api_name": "kfp.components.load_component_from_url", "line_number": 21, "usage_type": "call"}, {"api_name": "kfp.components", "line_number": 21, "usage_type": "name"}, {"api_name": "kfp.components.load_component_from_url", "line_number": 22, "usage_type": "call"}, {"api_name": "kfp.components", "line_number": 22, "usage_type": "name"}, {"api_name": "kfp.components.load_component_from_url", "line_number": 23, "usage_type": "call"}, {"api_name": "kfp.components", "line_number": 23, "usage_type": "name"}, {"api_name": "kfp.components.load_component_from_url", "line_number": 24, "usage_type": "call"}, {"api_name": "kfp.components", "line_number": 24, "usage_type": "name"}, {"api_name": "kubernetes.client.V1Volume", "line_number": 30, "usage_type": "call"}, {"api_name": "kubernetes.client", "line_number": 30, "usage_type": "name"}, {"api_name": "kubernetes.client.V1SecretVolumeSource", "line_number": 31, "usage_type": "call"}, {"api_name": "kubernetes.client", "line_number": 31, "usage_type": "name"}, {"api_name": "kubernetes.client.V1VolumeMount", "line_number": 32, "usage_type": "call"}, {"api_name": "kubernetes.client", "line_number": 32, "usage_type": "name"}, {"api_name": "kfp.dsl.pipeline", "line_number": 41, "usage_type": "call"}, {"api_name": "kfp.dsl", "line_number": 41, "usage_type": "name"}, {"api_name": "kfp.compiler.Compiler", "line_number": 103, "usage_type": "call"}, {"api_name": "kfp.compiler", "line_number": 103, "usage_type": "name"}]} +{"seq_id": "30849759802", "text": "import pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import f1_score, accuracy_score\nfrom mlxtend.evaluate import bias_variance_decomp as bvd\nfrom concurrent.futures import ProcessPoolExecutor\nimport operator\nimport time\nimport os\nimport warnings\nwarnings.filterwarnings('ignore')\n\ndef loadDatset(filname, cVal=False):\n dset=pd.read_csv(filname)\n if cVal:\n y=dset['class']\n x=dset['spectrometric_redshift']\n x = x.to_numpy()\n else:\n if len(dset.columns)==38:\n dset=dset.drop(dset.columns[31:],axis=1)\n y=dset['class']\n dset=dset.drop(dset.columns[13:16],axis=1)\n x=dset.drop(dset.columns[0:7],axis=1)\n else:\n dset=dset.drop(dset.columns[30:],axis=1)\n y=dset['class']\n dset=dset.drop(dset.columns[13:15],axis=1)\n x=dset.drop(dset.columns[0:7],axis=1)\n sc = MinMaxScaler(feature_range=(0, 1))\n x = sc.fit_transform(x)\n\n y = y.to_numpy()\n return x,y\n\nclass mykNearstNeighs:\n def __init__(self, k):\n self.k=k\n\n def fit(self, traingSetx, traingSety):\n self.traingSetx=traingSetx\n self.traingSety=traingSety\n return self\n\n def predict(self, tstSetx):\n prdicns=[]\n for x in range(len(tstSetx)):\n neighbrs = self.getNeighs(self.traingSetx, self.traingSety, tstSetx[x], self.k)\n resp = self.getMajrtyVote(neighbrs)\n prdicns.append(resp)\n return prdicns\n\n def getNeighs(self, traingSetx, traingSety, tstInst, k):\n distncs = []\n for x in range(len(traingSetx)):\n distncs.append( ( traingSety[x] , self.manhatDistnc(tstInst,traingSetx[x]) ) )\n\n distncs.sort(key=operator.itemgetter(1))\n kneighs=[x[0] for x in distncs[:k]]\n\n return kneighs\n \n def manhatDistnc(self, instnc1, instnc2):\n\t return np.sum(np.absolute(instnc1-instnc2))\n \n def getMajrtyVote(self, kneighs):\n clsVotes = [0,0]\n for x in range(len(kneighs)):\n resp = kneighs[x]\n clsVotes[resp] += 1\n return int(clsVotes[1]>clsVotes[0])\n\ndef kNearstNeighs(Setx, Sety, traingSetx, traingSety, k):\n mykNN=mykNearstNeighs(k)\n mykNN.fit(traingSetx,traingSety)\n prdicns=mykNN.predict(Setx)\n\n return f1_score(Sety.tolist(),prdicns,average='weighted')*100.0 , prdicns\n\ndef kNNwrap(filname):\n totSetx,totSety=loadDatset(filname)\n traingSetx,tstSetx,traingSety,tstSety=train_test_split(totSetx,totSety, test_size = 0.25, random_state = 69)\n '''print(filname,repr(len(tstSetx)))\n accurcy, prdictdMod = kNearstNeighs(tstSetx, tstSety, traingSetx, traingSety, 5)\n\n totSetx,totSety=loadDatset(filname,True)\n traingSetx,tstSetx,traingSety,tstSety=train_test_split(totSetx,totSety, test_size = 0.25, random_state = 69)\n prdictdRedShift=[]\n for i in tstSetx:\n prdictdRedShift.append((1 if i>=0.004 else 0))\n\n crossvalfscore=f1_score(prdictdMod,prdictdRedShift,average='weighted')*100.0'''\n print(filname+'\\nAverage Expected Loss=%d; Average Bias=%d; Average Variance=%d\\n' % bvd(mykNearstNeighs(1), traingSetx, traingSety, tstSetx, tstSety, num_rounds=75, random_seed=69), flush=True)\n print(filname+'\\nAverage Expected Loss=%d; Average Bias=%d; Average Variance=%d\\n' % bvd(mykNearstNeighs(5), traingSetx, traingSety, tstSetx, tstSety, num_rounds=75, random_seed=69), flush=True)\n print(filname+'\\nAverage Expected Loss=%d; Average Bias=%d; Average Variance=%d\\n' % bvd(mykNearstNeighs(15), traingSetx, traingSety, tstSetx, tstSety, num_rounds=75, random_seed=69), flush=True)\n\ndef main():\n dirctry=os.fsencode('.')\n initime=time.time()\n filnames=[]\n for F in os.listdir(dirctry): #each file in directory\n filname=os.fsdecode(F) #get filename\n if filname.endswith('.csv'):\n #kNNwrap(filname)\n filnames.append(filname)\n with ProcessPoolExecutor(8) as executr:\n executr.map(kNNwrap,filnames)\n\n print('Total time elapsed:', time.time()-initime)\n\nmain()\n\n'''\nk=5,cat3\nb=0.036\nv=0.011\n'''\n", "repo_name": "raunaks42/StarQuasarClassifier", "sub_path": "knn-biasvardec.py", "file_name": "knn-biasvardec.py", "file_ext": "py", "file_size_in_byte": 4269, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "warnings.filterwarnings", "line_number": 12, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 15, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.MinMaxScaler", "line_number": 31, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.absolute", "line_number": 65, "usage_type": "call"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 79, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 83, "usage_type": "call"}, {"api_name": "mlxtend.evaluate.bias_variance_decomp", "line_number": 94, "usage_type": "call"}, {"api_name": "mlxtend.evaluate.bias_variance_decomp", "line_number": 95, "usage_type": "call"}, {"api_name": "mlxtend.evaluate.bias_variance_decomp", "line_number": 96, "usage_type": "call"}, {"api_name": "os.fsencode", "line_number": 99, "usage_type": "call"}, {"api_name": "time.time", "line_number": 100, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 102, "usage_type": "call"}, {"api_name": "os.fsdecode", "line_number": 103, "usage_type": "call"}, {"api_name": "concurrent.futures.ProcessPoolExecutor", "line_number": 107, "usage_type": "call"}, {"api_name": "time.time", "line_number": 110, "usage_type": "call"}]} +{"seq_id": "26801931037", "text": "import time\nimport pandas as pd\nimport logging\nfrom typing import List, Optional\nfrom datetime import datetime\nimport sys\n\nlogging.basicConfig(\n format=\"%(asctime)s %(levelname)s %(message)s\",\n level=logging.DEBUG,\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n)\nlogger = logging.getLogger()\n\nDECISION_LIST = [\"buy_or_sell\", \"currency\", \"amount\"]\nSLEEP_TIME = 0.5\n\nmockup_raw_hamsterwheel_df = pd.DataFrame(\n {\n \"id\": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n \"time\": [\n \"2023-08-03 12:00:00\",\n \"2023-08-03 12:00:01\",\n \"2023-08-03 12:00:02\",\n \"2023-08-03 12:00:03\",\n \"2023-08-03 12:00:04\",\n \"2023-08-03 12:00:05\",\n \"2023-08-03 12:00:06\",\n \"2023-08-03 12:00:07\",\n \"2023-08-03 12:00:08\",\n \"2023-08-03 12:00:09\",\n ],\n \"magnet\": [1, 0, 1, 0, 1, 0, 1, 0, 1, 1],\n }\n)\n\nmockup_latest_hamsterwheel_df = pd.DataFrame(\n {\n \"id\": [1, 2, 3, 4, 5],\n \"time\": [\n \"2023-08-03 12:00:00\",\n \"2023-08-03 12:00:01\",\n \"2023-08-03 12:00:02\",\n \"2023-08-03 12:00:03\",\n \"2023-08-03 12:00:04\",\n ],\n \"magnet\": [1, 1, 1, 1, 1],\n }\n)\n\nmockup_decision_df = pd.DataFrame(\n {\n \"id\": [1],\n \"start_time\": [\"2023-08-03 12:00:00\"],\n \"end_time\": [None],\n \"type\": [\"buy_or_sell\"],\n \"number_hamsterwheel_turns\": [None],\n \"status\": [\"open\"],\n \"result\": [None],\n }\n)\n\nmockup_wallet_df = pd.DataFrame(\n {\n \"id\": [1, 2, 3, 4],\n \"currency\": [\"BTC\", \"ETH\", \"DOGE\", \"USD\"],\n \"amount\": [10, 4, 5, 10000],\n }\n)\n\nmockup_price_df = pd.DataFrame(\n {\n \"id\": [1, 2, 3, 4, 5, 6],\n \"currency\": [\"BTC\", \"ETH\", \"DOGE\", \"ADA\", \"AVAX\", \"XRP\"],\n \"price\": [25_000, 1_595, 0.064, 0.25, 12.48, 0.5],\n }\n)\n\n# TODO Write function that executes orders\n# TODO Write function to read price from binance and save to database\n\n\ndef get_latest_decision(df_decision: pd.DataFrame) -> Optional[pd.DataFrame]:\n \"\"\"Function to get the latest decision\"\"\"\n if df_decision is not None:\n # order by start_time desc\n df_decision = df_decision.sort_values(by=\"start_time\", ascending=False)\n df_decision_latest = df_decision.iloc[[0]]\n return df_decision_latest\n return None\n\n\ndef is_hamsterwheel_running(df: pd.DataFrame) -> bool:\n \"\"\"Function to determine if the hamsterwheel is running, i.e., there has been a magnet 0 in the last 5 seconds\"\"\"\n if 0 in df[\"magnet\"].values:\n return True\n return False\n\n\ndef is_decision_open(df_decision_latest: pd.DataFrame) -> bool:\n \"\"\"Function to determine if there is currently a decision open\"\"\"\n # During init, the length of df is 0\n if df_decision_latest is not None:\n if \"open\" in df_decision_latest[\"status\"].values:\n return True\n return False\n\n\ndef get_next_decision(\n df_decision_latest: pd.DataFrame, decisions: List[str] = DECISION_LIST\n) -> str:\n \"\"\"Function to get the next decision\"\"\"\n if df_decision_latest is not None:\n current_decision = df_decision_latest[\"type\"].values[0]\n current_decision_index = decisions.index(current_decision)\n next_decision_index = current_decision_index + 1\n if next_decision_index >= len(decisions):\n next_decision_index = 0\n return decisions[next_decision_index]\n\n # If there is no decision yet, return the first decision\n return decisions[0]\n\n\ndef save_new_decision(next_decision: str) -> None:\n \"\"\"Function to save a new decision to the database\"\"\"\n save_log(message=f\"Saving new decision: {next_decision}\")\n now = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n new_decision = pd.DataFrame(\n {\n \"start_time\": [now],\n \"end_time\": [None],\n \"number_hamsterwheel_turns\": [None],\n \"type\": [next_decision],\n \"status\": [\"open\"],\n \"result\": [None],\n }\n )\n # TODO: Save the new decision to the database\n logger.debug(f\"New decision: {new_decision}\")\n\n\ndef update_decision(df_decision_latest: pd.DataFrame) -> None:\n \"\"\"Function to update a decision in the database\"\"\"\n # TODO: Update the decision in the database\n save_log(message=f\"Updating decision: {df_decision_latest}\")\n\n\ndef get_decision_cycle(df_decision: pd.DataFrame) -> Optional[pd.DataFrame]:\n \"\"\"Function to get the decision cycle, i.e., all\n decisions after the last buy_or_sell decision\"\"\"\n # Get the last buy_or_sell decision\n if df_decision is not None:\n buy_or_sell_filter = df_decision[\"type\"] == \"buy_or_sell\"\n df_buy_or_sell = df_decision[buy_or_sell_filter]\n # Order by start_time desc\n df_buy_or_sell = df_buy_or_sell.sort_values(by=\"start_time\", ascending=False)\n last_buy_or_sell = df_buy_or_sell.iloc[[0]]\n last_buy_or_sell_index = last_buy_or_sell.index[0]\n # Get all the decisions after the last buy_or_sell decision\n df_decision_cycle = df_decision.iloc[last_buy_or_sell_index:]\n return df_decision_cycle\n return None\n\n\ndef has_money(df_wallet: pd.DataFrame) -> bool:\n \"\"\"Function to check if the hamster has money.\n If the hamster has less than 5 USD, then it is broke\"\"\"\n if df_wallet is not None:\n if \"USD\" in df_wallet[\"currency\"].values:\n usd_filter = df_wallet[\"currency\"] == \"USD\"\n df_usd = df_wallet[usd_filter]\n if df_usd[\"amount\"].values[0] > 5:\n return True\n else:\n return False\n return False\n\n\ndef has_crypto(df_wallet: pd.DataFrame) -> bool:\n \"\"\"Function to determine if the hamster has crypto (True).\"\"\"\n if df_wallet is not None:\n # Check if there is any non USD currency\n currencies = df_wallet[\"currency\"].values\n if len(currencies) > 1:\n return True\n return False\n\n\ndef get_buy_or_sell_decision(df_decision_cycle: pd.DataFrame) -> str:\n \"\"\"Function to get the buy_or_sell decision\"\"\"\n # Return the result of the last buy_or_sell decision\n buy_or_sell_filter = df_decision_cycle[\"type\"] == \"buy_or_sell\"\n df_buy_or_sell = df_decision_cycle[buy_or_sell_filter]\n return df_buy_or_sell[\"result\"].values[0]\n\n\ndef get_currency_decision(df_decision_cycle: pd.DataFrame) -> str:\n \"\"\"Function to get the currency decision\"\"\"\n # Return the result of the last currency decision\n currency_filter = df_decision_cycle[\"type\"] == \"currency\"\n df_currency = df_decision_cycle[currency_filter]\n return df_currency[\"result\"].values[0]\n\n\ndef get_currencies_to_sell(df_wallet: pd.DataFrame) -> List[str]:\n \"\"\"Function to get the currencies to sell\"\"\"\n currencies_to_sell = []\n if df_wallet is not None:\n # Get all the currencies\n currencies = df_wallet[\"currency\"].values\n # Remove USD from the currencies\n currencies = [currency for currency in currencies if currency != \"USD\"]\n # If there are currencies left, return them\n if len(currencies) > 0:\n return currencies\n return currencies_to_sell\n\n\ndef close_decision(\n df_decision_latest: pd.DataFrame,\n df_decision_cycle: pd.DataFrame,\n number_hamsterwheel_turns: int,\n end_time: datetime,\n df_wallet: pd.DataFrame,\n) -> pd.DataFrame:\n \"\"\"Function to close a decision and return the result\"\"\"\n save_log(message=f\"Closing decision: {df_decision_latest}\")\n\n df_decision_latest[\"end_time\"] = end_time\n df_decision_latest[\"status\"] = \"closed\"\n df_decision_latest[\"number_hamsterwheel_turns\"] = number_hamsterwheel_turns\n current_decision = df_decision_latest[\"type\"].values[0]\n if current_decision == \"buy_or_sell\":\n result = get_result_buy_or_sell(number_hamsterwheel_turns)\n # If the hamster has money but no crypto, then the result will be buy\n if has_money(df_wallet) and not has_crypto(df_wallet):\n result = \"buy\"\n\n # If the hamster has no money but crypto, then the result will be sell\n if not has_money(df_wallet) and has_crypto(df_wallet):\n result = \"sell\"\n\n elif current_decision == \"currency\":\n # TODO Add logic if the buy_or_sell decision was sell, then the currency_list is the list of currencies the hamster has\n if get_buy_or_sell_decision(df_decision_cycle) == \"sell\":\n currency_list = get_currencies_to_sell(df_wallet=df_wallet)\n if get_buy_or_sell_decision(df_decision_cycle) == \"buy\":\n currency_list = [\"USD\"]\n\n result = get_result_currency(\n number_hamsterwheel_turns=number_hamsterwheel_turns,\n currency_list=currency_list,\n )\n elif current_decision == \"amount\":\n result = get_result_amount(number_hamsterwheel_turns)\n df_decision_latest[\"result\"] = result\n\n update_decision(df_decision_latest)\n\n return df_decision_latest\n\n\ndef get_number_hamsterwheel_turns(\n df_raw_hamsterwheel: pd.DataFrame, start_time: datetime, end_time: datetime\n) -> int:\n \"\"\"Function to get the number of hamsterwheel turns\"\"\"\n time_filter = (df_raw_hamsterwheel[\"time\"] >= start_time) & (\n df_raw_hamsterwheel[\"time\"] <= end_time\n )\n df_hamsterwheel_turns = df_raw_hamsterwheel[time_filter]\n magnet_filter = df_hamsterwheel_turns[\"magnet\"] == 0\n df_hamsterwheel_turns = df_hamsterwheel_turns[magnet_filter]\n number_hamsterwheel_turns = len(df_hamsterwheel_turns)\n logger.debug(\n f\"Between {start_time} and {end_time} there were {number_hamsterwheel_turns} hamsterwheel turns\"\n )\n return number_hamsterwheel_turns\n\n\ndef get_result_buy_or_sell(number_hamsterwheel_turns: int) -> str:\n \"\"\"Function to get the result of the buy or sell decision\"\"\"\n # If the number of hamsterwheel turns is even, then buy\n if number_hamsterwheel_turns % 2 == 0:\n return \"buy\"\n # If the number of hamsterwheel turns is odd, then sell\n return \"sell\"\n\n\ndef get_result_currency(\n number_hamsterwheel_turns: int, currency_list: List[str]\n) -> str:\n \"\"\"Function to get the result of the currency decision\"\"\"\n # Repeat the list of currencies until it is longer than the number of hamsterwheel turns\n currency_list = currency_list * (\n number_hamsterwheel_turns // len(currency_list) + 1\n )\n # Get the currency at the index of the number of hamsterwheel turns\n return currency_list[number_hamsterwheel_turns]\n\n\ndef get_result_amount(number_hamsterwheel_turns: int) -> float:\n \"\"\"Function to get the result of the amount decision\"\"\"\n amount_options = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n # Repeat the list of amount options until it is longer than the number of hamsterwheel turns\n amount_options = amount_options * (\n number_hamsterwheel_turns // len(amount_options) + 1\n )\n # Get the amount at the index of the number of hamsterwheel turns\n return amount_options[number_hamsterwheel_turns]\n\n\ndef get_wallet_id(currency: str, df_wallet: pd.DataFrame) -> int:\n \"\"\"Function to get the wallet id\"\"\"\n currency_filter = df_wallet[\"currency\"] == currency\n df_currency = df_wallet[currency_filter]\n return df_currency[\"id\"].values[0]\n\n\ndef get_price(currency: str, df_price: pd.DataFrame) -> float:\n \"\"\"Function to get the price\"\"\"\n currency_filter = df_price[\"currency\"] == currency\n df_currency = df_price[currency_filter]\n return df_currency[\"price\"].values[0]\n\n\ndef prepare_order(\n df_decision_closed: pd.DataFrame,\n df_decision_cycle: pd.DataFrame,\n df_wallet: pd.DataFrame,\n) -> pd.DataFrame:\n \"\"\"Function to prepare the order\"\"\"\n # Get the buy_or_sell decision\n buy_or_sell_decision = get_buy_or_sell_decision(df_decision_cycle=df_decision_cycle)\n # Get the currency decision\n currency_decision = get_currency_decision(df_decision_cycle=df_decision_cycle)\n # Get the amount decision\n amount_decision = df_decision_closed[\"result\"].values[0]\n\n wallet_id = get_wallet_id(currency=currency_decision, df_wallet=df_wallet)\n price = get_price(currency=currency_decision, df_price=df_price)\n order = pd.DataFrame(\n {\n \"wallet_id\": [wallet_id],\n \"type\": [buy_or_sell_decision],\n \"currency\": [currency_decision],\n \"amount\": [amount_decision],\n \"price\": [price],\n \"state\": [\"pending\"],\n }\n )\n return order\n\n\ndef save_log(message: str) -> None:\n \"\"\"Function to save a log message to the database\"\"\"\n logger.info(message)\n # TODO: Save the log message to the database\n # logger.info(\"Saved log message to database\")\n\n\nif __name__ == \"__main__\":\n while True:\n # TODO Check if there is an open order\n # TODO: Read the latest 5 seconds of hamsterwheel data from the mysql database and store in a pandas dataframe\n df_latest_hamsterwheel = mockup_latest_hamsterwheel_df\n\n # TODO: Read the latest decision in the decision table from the database\n df_decision = mockup_decision_df\n\n # TODO: Read the wallet of the hamster from the database\n df_wallet = mockup_wallet_df\n\n # TODO: Read the price of the currencies from the database\n df_price = mockup_price_df\n\n df_decision_latest = get_latest_decision(df_decision=df_decision)\n\n logger.debug(f\"Latest decision: {df_decision_latest}\")\n\n # Determine if the hamsterwheel is running, i.e., there has been a magnet 0 in the last 5 seconds\n is_running = is_hamsterwheel_running(df_latest_hamsterwheel)\n save_log(message=f\"Hamsterwheel is running? {is_running}\")\n\n # Check if there is currently a decision open\n decision_open = is_decision_open(df_decision_latest)\n save_log(message=f\"Decision open? {decision_open}\")\n\n # If the hamster has no money and no crypto, then it is broke\n if not has_money(df_wallet) and not has_crypto(df_wallet):\n save_log(message=\"Hamster is broke\")\n sys.exit()\n # If the hamsterwheel is running and there is no decision open, then open a new decision\n if is_running and not decision_open:\n save_log(message=\"Opening a new decision\")\n next_decision = get_next_decision(df_decision_latest)\n save_log(message=f\"Next decision: {next_decision}\")\n\n save_new_decision(next_decision)\n time.sleep(SLEEP_TIME)\n continue\n\n # If the hamsterwheel is not running and there is no decision open, then do nothing\n if not is_running and not decision_open:\n save_log(message=\"No decision open and hamsterwheel not running\")\n time.sleep(SLEEP_TIME)\n continue\n\n # If the hamsterwheel is running and there is a decision open, then do nothing\n if is_running and decision_open:\n save_log(message=\"Hamsterwheel running and decision open\")\n time.sleep(SLEEP_TIME)\n continue\n\n # If the hamsterwheel is not running and there is a decision open, then close the decision\n if not is_running and decision_open:\n save_log(message=\"Closing the decision\")\n now = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n # Check how many hamsterwheel turns there were\n number_hamsterwheel_turns = get_number_hamsterwheel_turns(\n df_raw_hamsterwheel=mockup_raw_hamsterwheel_df,\n start_time=df_decision_latest[\"start_time\"].values[0],\n end_time=now,\n )\n logging.debug(f\"Number of hamsterwheel turns: {number_hamsterwheel_turns}\")\n # Get all the decisions for this cycle of decisions\n df_decision_cycle = get_decision_cycle(df_decision=df_decision)\n df_decision_closed = close_decision(\n df_decision_latest=df_decision_latest,\n df_decision_cycle=df_decision_cycle,\n number_hamsterwheel_turns=number_hamsterwheel_turns,\n end_time=now,\n df_wallet=df_wallet,\n )\n save_log(message=f\"Decision closed: {df_decision_closed}\")\n\n # If the decision was amount and is closed, place the order\n if df_decision_closed[\"type\"].values[0] == \"amount\":\n save_log(message=\"Preparing order\")\n order = prepare_order(\n df_decision_closed=df_decision_closed,\n df_decision_cycle=df_decision_cycle,\n df_wallet=df_wallet,\n )\n logging.debug(f\"Order: {order}\")\n", "repo_name": "kromerh/cryptohamster", "sub_path": "src/python/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 16636, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "logging.basicConfig", "line_number": 8, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 10, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 13, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 18, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 37, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 51, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 63, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 71, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 83, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 83, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 93, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 100, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 110, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 110, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 128, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 128, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 129, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 143, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 149, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 149, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 166, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 180, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 190, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 198, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 206, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 206, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 221, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 222, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 224, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 225, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 226, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 265, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 265, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 291, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 313, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 320, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 328, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 329, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 330, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 342, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 331, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 392, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 400, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 406, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 412, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 418, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 418, "usage_type": "name"}, {"api_name": "logging.debug", "line_number": 425, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 445, "usage_type": "call"}]} +{"seq_id": "33079535552", "text": "from flask import Flask, render_template,url_for,redirect,session,request,flash,send_file\nfrom authlib.integrations.flask_client import OAuth\nfrom passlib.hash import sha256_crypt\nfrom flask_pymongo import PyMongo\nfrom bson.json_util import dumps\nimport json\nimport zipfile\nimport os\nimport pickle\napp = Flask(__name__)\napp.config['MONGO_URI']='mongodb+srv://zaidAhmed:pakistan1999$@mb.pvwut.mongodb.net/MB?retryWrites=true&w=majority'\nmongo = PyMongo(app)\noauth = OAuth(app)\napp.secret_key=(\"123\")\n\ngoogle = oauth.register(\n name = 'google',\n client_id='1061641137723-hhefi45ih1n7a7ej4ois859o3h3r1u73.apps.googleusercontent.com',\n client_secret='chs57MRobQyNf4dbh-WAd43n',\n access_token_url='https://accounts.google.com/o/oauth2/token',\n access_token_params=None,\n authorize_url='https://accounts.google.com/o/oauth2/auth',\n authorize_params=None,\n api_base_url='https://www.googleapis.com/oauth2/v1/',\n client_kwargs={'scope':'openid profile email'},\n)\n@app.route('/')\ndef main():\n if \"profile\" in session :\n return redirect(url_for('dashboard'))\n else: \n return render_template('login.html')\n\n#Sign in with google button\n\n@app.route('/login')\ndef login():\n google = oauth.create_client('google')\n redirect_uri = url_for('authorize', _external=True)\n return google.authorize_redirect(redirect_uri)\n\n\n@app.route('/authorize')\ndef authorize():\n google = oauth.create_client('google')\n token = google.authorize_access_token()\n resp = google.get('userinfo')\n user_info = resp.json()\n # do something with the token and profile\n session['profile'] = user_info['email']\n # make the session permanant so it keeps existing after broweser gets closed\n session.permanent = True \n cursor = mongo.db.userRegistration\n email = dict(session)['profile']\n if cursor.find_one({\"email\":email}):\n flash(\"You're now logged in\" , \"info\")\n return redirect('/dashboard')\n else:\n cursor.insert({\"email\":email,\"name\":\"N/A\",\"gender\":\"N/A\",\"location\":\"N/A\",\"profile\":'N/A'})\n name = session[\"profile\"] \n myquery = {\"email\":name}\n user_info = cursor.find(myquery)\n flash(\"You're now logged in\" , \"info\")\n return redirect('/dashboard')\n\n#dashboard\n\n@app.route('/dashboard',methods=[\"GET\",\"POST\"])\ndef dashboard():\n if \"profile\" in session :\n cursor = mongo.db.modelsInputs\n name = session[\"profile\"] \n myquery = {\"User\":name}\n user_info = cursor.find(myquery)\n return render_template('dashboard.html' ,user_info=user_info)\n else:\n return redirect(url_for(\"main\"))\n\n#signup form\n\n@app.route('/RegisterUser',methods=[\"GET\",\"POST\"])\ndef sigup_form():\n data = request.form\n name = data[\"name\"]\n email = data[\"email\"]\n password = sha256_crypt.encrypt(str(data[\"password\"]))\n cursor = mongo.db.userRegistration\n user_info = cursor.find_one({\"email\":email})\n if user_info==None:\n cursor.insert_one({\"name\":name,\"email\":email,\"password\":password,\"gender\":\"N/A\",\"location\":\"N/A\",'profile':'N/A'})\n user_info = cursor.find_one({\"email\":email})\n session['profile'] = user_info[\"email\"]\n session.permanent = True # make the session permanant so it keeps existing after broweser gets closed\n flash(\"You're now logged in\" , \"info\")\n return redirect(url_for('dashboard'))\n \n else:\n flash(\"You're now logged in\" , \"info\")\n return render_template('dashboard.html' ,user_info=user_info)\n\n \n#signin form\n\n@app.route(\"/signinUser\", methods = [\"GET\",\"POST\"])\ndef signin():\n data = request.form\n name = data[\"email\"]\n password_candid = data[\"password\"]\n cursor = mongo.db.userRegistration\n user_info = cursor.find_one({\"email\":name})\n if user_info :\n password = user_info['password']\n if sha256_crypt.verify(password_candid , password):\n session['profile'] = user_info['email']\n session.permanent = True\n return redirect('/dashboard')\n else :\n flash(\"Incorrect Password...!\",\"danger\")\n return redirect(url_for('main'))\n else:\n flash(\"Username not found...!\" , \"danger\")\n return redirect(url_for('main'))\n\n#ML Inputs\n\n@app.route('/MlForm')\ndef MlForm():\n if \"profile\" in session :\n return render_template('Minputs.html')\n else:\n return(redirect('/'))\n\n\n@app.route('/MlInputs' , methods = [\"GET\" , \"POST\"])\ndef MlInputs():\n if \"profile\" in session :\n try:\n data = request.form\n TrainingDataSet = request.files['TrainingDataSet']\n ValidationDataSet = request.files['ValidationDataSet']\n CnnNumberOfLayers = data['NumberOfCNNLayer']\n CnnLayerOutputs = data['CNNLayersOutput']\n DenseNumberOfLayers =data['NumberOfDenseLayer']\n DenseLayerOutputs = data['DenseLayersOutput']\n BeginingLayersOutputFunction = data['BeginingActivation']\n EndLayerOutputFunction = data['EndActivation']\n InputShape = data['InputShape']\n LossFunction = data['LossFunction']\n LearingRate = data['LearningRate']\n TargetSize = data['TargetSize']\n ClassMode = data['ClassMode'] \n BatchSize = data['BatchSize']\n Epochs = data['Epochs']\n StepsPerEpoch = data['StepPerEpochs']\n ValidationSteps =data['ValidationSteps']\n #inserting data into database\n cursor = mongo.db.modelsInputs\n cursor.insert_one({\"User\":session['profile'],\"Model\":\"Machine Learning\",\"CnnNumberOfLayers\":CnnNumberOfLayers,\"CnnLayerOutputs\":CnnLayerOutputs,\n \"DenseNumberOfLayers\":DenseNumberOfLayers,\"DenseLayerOutputs\":DenseLayerOutputs,\n \"BeginingLayersOutputFunction\":BeginingLayersOutputFunction,\"EndLayerOutputFunction\":EndLayerOutputFunction,\n \"InputShape\":InputShape,\"LossFunction\":LossFunction,\"LearingRate\":LearingRate,\"TargetSize\":TargetSize,\n \"ClassMode\":ClassMode,\"BatchSize\":BatchSize,\"Epochs\":Epochs,\"StepsPerEpoch\":StepsPerEpoch,\n \"ValidationSteps\":ValidationSteps,\"accuracy\":0})\n result = cursor.find({\"User\":session['profile']}).sort([(\"_id\",-1)])\n #DataSet Handling\n target1 = TrainingDataSet\n target2 = ValidationDataSet\n handle1 = zipfile.ZipFile(target1)\n handle2 = zipfile.ZipFile(target2)\n handle1.extractall(f'Uploads/MachineLearning/{result[0][\"_id\"]}/training')\n handle2.extractall(f'Uploads/MachineLearning/{result[0][\"_id\"]}/validation')\n #creating a file\n a = str(result[0][\"_id\"])\n b = CnnLayerOutputs.split(\",\")\n c = DenseLayerOutputs.split(\",\")\n f = open(f'Uploads/{a}.py',\"w\")\n f.write(\"from keras import layers \\nfrom keras import models \\nmodel = models.Sequential()\")\n f.write(f'\\ntrain_dir =\"Uploads/MachineLearning/{result[0][\"_id\"]}/training\" ')\n f.write(f'\\nvalidation_dir = \"Uploads/MachineLearning/{result[0][\"_id\"]}/validation\"')\n for i in range(0,int(CnnNumberOfLayers)):\n if i == 0:\n f.write(f'\\nmodel.add(layers.Conv2D({b[i]}, (3, 3), activation=\"{BeginingLayersOutputFunction}\", input_shape=({InputShape})))')\n f.write(f'\\nmodel.add(layers.MaxPooling2D((2, 2))) ')\n else:\n f.write(f'\\nmodel.add(layers.Conv2D({b[i]}, (3, 3), activation=\"{BeginingLayersOutputFunction}\"))')\n f.write(f'\\nmodel.add(layers.MaxPooling2D((2, 2))) ')\n\n f.write(\"\\nmodel.add(layers.Flatten())\")\n\n for i in range(0,int(DenseNumberOfLayers)):\n if i == int(DenseNumberOfLayers)-1:\n f.write(f'\\nmodel.add(layers.Dense({c[i]}, activation=\"{EndLayerOutputFunction}\"))')\n else:\n f.write(f'\\nmodel.add(layers.Dense({c[i]}, activation=\"{BeginingLayersOutputFunction}\"))')\n\n f.write(\"\\nfrom keras import optimizers \\nfrom keras import backend as k\")\n f.write(f'\\nmodel.compile(loss=\"{LossFunction}\", optimizer=optimizers.RMSprop(lr=1e{LearingRate}),metrics=[\"acc\"])')\n f.write(f'\\nfrom keras.preprocessing.image import ImageDataGenerator \\ntrain_datagen = ImageDataGenerator(rescale=1./255) \\ntest_datagen = ImageDataGenerator(rescale=1./255)')\n f.write(f'\\ntrain_generator = train_datagen.flow_from_directory(train_dir, target_size=({TargetSize}),batch_size={BatchSize} , class_mode=\"{ClassMode}\") \\nvalidation_generator = test_datagen.flow_from_directory( validation_dir,target_size=({TargetSize}) , batch_size={BatchSize} , class_mode=\"{ClassMode}\")')\n f.write(f'\\nhistory = model.fit_generator(train_generator,steps_per_epoch={StepsPerEpoch},epochs={Epochs},validation_data=validation_generator,validation_steps={ValidationSteps})')\n f.write(f'\\npickle.dump(history,open(\"Uploads/{a}.p\",\"wb\"))')\n f.write(f'\\nmodel.save(\"Uploads/h5/{a}.h5\")')\n f.write(f'\\nk.clear_session()')\n f.close()\n exec(compile(open(f'Uploads/{a}.py', \"rb\").read(), f'{a}.py', 'exec'))\n z = pickle.load(open(f'Uploads/{a}.p',\"rb\"))\n z = z.history['acc'][int(Epochs)-1]\n cursor.find_one_and_update({\"_id\":result[0][\"_id\"]},{\"$set\":{\"accuracy\":f'{str(z*100)}'}})\n return redirect(url_for(dashboard)) \n \n except :\n flash(\"Make sure everything is as per requirment\", \"danger\")\n return redirect(url_for('MlForm'))\n \n else:\n return redirect(url_for('main'))\n\n#DL Inputs\n\n@app.route('/DlForm')\ndef dlForm():\n if \"profile\" in session:\n return render_template('Dinputs.html')\n else:\n return redirect('/')\n \n@app.route('/DlInputs' , methods = ['GET' , 'POST'])\ndef DlInputs():\n try:\n data = request.form\n trainingFile = request.files['training']\n fileName = trainingFile.filename\n Name = data['name']\n Description = data['description']\n NumberOfFeatures = data['NumberOfFeatues']\n DenseNumberOfLayers =data['NumberOfDenseLayer']\n DenseLayerOutputs = data['DenseLayersOutput']\n BeginingLayersOutputFunction = data['BeginingActivation']\n EndLayerOutputFunction = data['EndActivation']\n InputShape = data['InputShape']\n LossFunction = data['LossFunction']\n BatchSize = data['BatchSize']\n Epochs = data['Epochs']\n cursor = mongo.db.modelsInputs\n cursor.insert_one({\"User\":session['profile'],\"Model\":\"Deep Learning\",\"Name\":Name,\"Description\":Description,\n \"DenseNumberOfLayers\":DenseNumberOfLayers,\"DenseLayerOutputs\":DenseLayerOutputs,\n \"BeginingLayersOutputFunction\":BeginingLayersOutputFunction,\"EndLayerOutputFunction\":EndLayerOutputFunction,\n \"InputShape\":InputShape,\"LossFunction\":LossFunction,\"BatchSize\":BatchSize,\"Epochs\":Epochs,\"accuracy\":0})\n result = cursor.find({\"User\":session['profile']}).sort([(\"_id\",-1)])\n #handling dataset\n validation_dir = os.path.join(\"Uploads/DeepLearning\",f'{result[0][\"_id\"]}')\n os.mkdir(validation_dir) \n trainingFile.save(os.path.join(validation_dir , trainingFile.filename)) \n #creating file\n a = str(result[0][\"_id\"])\n c = DenseLayerOutputs.split(\",\")\n f = open(f'Uploads/{a}.py',\"w\")\n f.write(\"from keras.models import Sequential\\nimport pickle \\nfrom keras.layers import Dense\\nimport pandas \\nimport numpy \\nfrom keras.wrappers.scikit_learn import KerasClassifier \\nfrom sklearn.model_selection import cross_val_score \\nfrom sklearn.preprocessing import LabelEncoder \\nfrom sklearn.model_selection import StratifiedKFold \\nfrom sklearn.preprocessing import StandardScaler \\nfrom sklearn.pipeline import Pipeline \\nfrom keras import models \\nfrom keras import layers \")\n f.write(\"\\nseed = 7 \\nnumpy.random.seed(seed)\")\n f.write(f'\\ndataframe = pandas.read_csv(\"Uploads/DeepLearning/{a}/{fileName}\", header=None)\\ndataset = dataframe.values')\n f.write(f'\\nx = dataset[:,0:{int(NumberOfFeatures)}]')\n f.write(f'\\ny = dataset[:,{int(NumberOfFeatures)}]')\n f.write(\"\\ndef create_baseline():\\n from keras import layers\\n from keras import models \\n network = models.Sequential() \")\n for i in range(0,int(DenseNumberOfLayers)):\n if i == int(DenseNumberOfLayers)-1:\n f.write(f'\\n network.add(layers.Dense({c[i]}, activation=\"{EndLayerOutputFunction}\"))')\n elif i == 0:\n f.write(f'\\n network.add(layers.Dense({c[i]}, activation=\"{BeginingLayersOutputFunction}\",input_shape=({InputShape},)))')\n else:\n f.write(f'\\n network.add(layers.Dense({c[i]}, activation=\"{BeginingLayersOutputFunction}\"))')\n \n f.write(f'\\n network.compile(optimizer=\"Adam\",loss=\"{LossFunction}\",metrics=[\"accuracy\"]) \\n return network')\n f.write(f'\\nestimator = KerasClassifier(build_fn=create_baseline, epochs={int(Epochs)}, batch_size={int(BatchSize)}, verbose=0)')\n f.write(\"\\nkfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)\")\n f.write(\"\\nresults = cross_val_score(estimator, x, y, cv=kfold)\")\n f.write(f'\\npickle.dump(results[{int(Epochs)-1}],open(\"Uploads/{a}.p\",\"wb\"))')\n f.write(\"\\nmodel = create_baseline()\")\n f.write(f'\\nmodel.save(\"Uploads/h5/{a}.h5\")')\n f.write('\\nfrom keras import backend as k \\nk.clear_session()')\n f.close()\n exec(open(f'Uploads/{a}.py', \"rb\").read())\n z = pickle.load(open(f'Uploads/{a}.p',\"rb\"))\n r=cursor.find_one_and_update({\"_id\":result[0][\"_id\"]},{\"$set\":{\"accuracy\":f'{str(z*100)}'}})\n return str(z) \n except :\n flash(\"Make sure everything is as per requirment\" , \"danger\")\n return redirect(url_for('dlForm'))\n \n@app.route('/Signout')\ndef signout():\n if \"profile\" in session:\n flash(\"You're sucessfully logged out...!\" , \"info\")\n session.clear()\n return redirect(url_for('main'))\n else:\n return redirect('/')\n\n@app.route('/download/',methods = ['GET' , 'POST'])\ndef download(file):\n if \"profile\" in session:\n return send_file(f\"E:/buildin/Uploads/h5/{file}.h5\")\n\n\n@app.route('/profile')\ndef profile():\n if \"profile\" in session:\n cursor = mongo.db.userRegistration\n data = cursor.find_one({\"email\":session[\"profile\"]})\n cursor = mongo.db.modelsInputs\n DL = cursor.find({\"User\":session[\"profile\"] , \"Model\":\"Deep Learning\"}).count()\n if DL > 0:\n data[\"Dl\"] = DL +1\n else:\n data['Dl'] = 0\n ML = cursor.find({\"User\":session[\"profile\"] , \"Model\":\"Machine Learning\"}).count()\n if ML > 0:\n data[\"Ml\"] = ML +1\n else:\n data['Ml'] = 0\n if DL + ML >0:\n data[\"Total\"] = DL + ML + 2\n else :\n data['Total'] = 0\n return render_template('profile.html' , data=data)\n\n@app.route('/updateProfile' , methods = ['GET' , 'POST'])\ndef updateProfile():\n if \"profile\" in session:\n form = request.form\n if 'image' in request.files:\n image = request.files['image']\n mongo.save_file(session['profile'] , image)\n cursor = mongo.db.userRegistration\n data = cursor.find_one({\"email\":session[\"profile\"]})\n if form['name']:\n name = form['name']\n else:\n name = data['name']\n try:\n gander = form['gender'] \n except :\n gander = data['gender']\n try:\n location = form['location'] \n except :\n location = data['location']\n cursor = mongo.db.userRegistration\n cursor.find_one_and_update({\"email\":session[\"profile\"]},{\"$set\":{\"name\":f'{str(name)}',\"gender\":f'{str(gander)}',\"location\":f'{str(location)}'}})\n return redirect(url_for('profile'))\n else:\n redirect(url_for('profile'))\n \n@app.route(\"/file/\")\ndef file(filename):\n return mongo.send_file(filename)\n\n@app.route(\"/search\" , methods = ['GET' , 'POST'])\ndef search():\n if \"profile\" in session:\n data = request.form\n name = data['search']\n cursor = mongo.db.modelsInputs\n user_info = cursor.find({\"Name\":f'{name}'}) \n if len(list(user_info))>0:\n user_info = cursor.find({\"Name\":f'{name}'})\n return render_template('search.html' ,user_info=user_info)\n else:\n flash('no data found' , \"info\")\n return redirect(url_for('dashboard'))\n \n", "repo_name": "SZaidAhmed/Buildin-v1", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 16837, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "flask.Flask", "line_number": 10, "usage_type": "call"}, {"api_name": "flask_pymongo.PyMongo", "line_number": 12, "usage_type": "call"}, {"api_name": "authlib.integrations.flask_client.OAuth", "line_number": 13, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 29, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 30, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 30, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 32, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 39, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 50, "usage_type": "name"}, {"api_name": "flask.session.permanent", "line_number": 52, "usage_type": "attribute"}, {"api_name": "flask.session", "line_number": 52, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 54, "usage_type": "argument"}, {"api_name": "flask.flash", "line_number": 56, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 57, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 60, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 63, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 64, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 70, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 72, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 75, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 77, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 77, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 83, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 83, "usage_type": "name"}, {"api_name": "passlib.hash.sha256_crypt.encrypt", "line_number": 86, "usage_type": "call"}, {"api_name": "passlib.hash.sha256_crypt", "line_number": 86, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 92, "usage_type": "name"}, {"api_name": "flask.session.permanent", "line_number": 93, "usage_type": "attribute"}, {"api_name": "flask.session", "line_number": 93, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 94, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 95, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 95, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 98, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 99, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 106, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 106, "usage_type": "name"}, {"api_name": "passlib.hash.sha256_crypt.verify", "line_number": 113, "usage_type": "call"}, {"api_name": "passlib.hash.sha256_crypt", "line_number": 113, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 114, "usage_type": "name"}, {"api_name": "flask.session.permanent", "line_number": 115, "usage_type": "attribute"}, {"api_name": "flask.session", "line_number": 115, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 116, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 118, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 119, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 119, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 121, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 122, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 122, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 128, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 129, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 131, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 136, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 138, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 138, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 139, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 139, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 140, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 140, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 158, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 164, "usage_type": "name"}, {"api_name": "zipfile.ZipFile", "line_number": 168, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 169, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 206, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 209, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 209, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 212, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 213, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 213, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 216, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 216, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 222, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 223, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 225, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 230, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 230, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 231, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 231, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 245, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 249, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 251, "usage_type": "call"}, {"api_name": "os.path", "line_number": 251, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 252, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 253, "usage_type": "call"}, {"api_name": "os.path", "line_number": 253, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 282, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 286, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 287, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 287, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 291, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 292, "usage_type": "call"}, {"api_name": "flask.session.clear", "line_number": 293, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 293, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 294, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 294, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 296, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 300, "usage_type": "name"}, {"api_name": "flask.send_file", "line_number": 301, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 306, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 308, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 310, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 315, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 324, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 328, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 329, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 329, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 330, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 330, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 331, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 331, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 332, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 334, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 348, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 349, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 349, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 351, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 351, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 359, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 360, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 360, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 366, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 368, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 369, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 369, "usage_type": "call"}]} +{"seq_id": "12154348420", "text": "import torch\n\nimport torch_geometric\nfrom torch_geometric.data import Data\nfrom torch_geometric.data.datapipes import functional_transform\nfrom torch_geometric.transforms import BaseTransform\n\n\n@functional_transform('point_pair_features')\nclass PointPairFeatures(BaseTransform):\n r\"\"\"Computes the rotation-invariant Point Pair Features\n (functional name: :obj:`point_pair_features`).\n\n .. math::\n \\left( \\| \\mathbf{d_{j,i}} \\|, \\angle(\\mathbf{n}_i, \\mathbf{d_{j,i}}),\n \\angle(\\mathbf{n}_j, \\mathbf{d_{j,i}}), \\angle(\\mathbf{n}_i,\n \\mathbf{n}_j) \\right)\n\n of linked nodes in its edge attributes, where :math:`\\mathbf{d}_{j,i}`\n denotes the difference vector between, and :math:`\\mathbf{n}_i` and\n :math:`\\mathbf{n}_j` denote the surface normals of node :math:`i` and\n :math:`j` respectively.\n\n Args:\n cat (bool, optional): If set to :obj:`False`, all existing edge\n attributes will be replaced. (default: :obj:`True`)\n \"\"\"\n def __init__(self, cat: bool = True):\n self.cat = cat\n\n def forward(self, data: Data) -> Data:\n ppf_func = torch_geometric.nn.conv.ppf_conv.point_pair_features\n\n assert data.edge_index is not None\n assert data.pos is not None and data.norm is not None\n assert data.pos.size(-1) == 3\n assert data.pos.size() == data.norm.size()\n\n row, col = data.edge_index\n pos, norm, pseudo = data.pos, data.norm, data.edge_attr\n\n ppf = ppf_func(pos[row], pos[col], norm[row], norm[col])\n\n if pseudo is not None and self.cat:\n pseudo = pseudo.view(-1, 1) if pseudo.dim() == 1 else pseudo\n data.edge_attr = torch.cat([pseudo, ppf.type_as(pseudo)], dim=-1)\n else:\n data.edge_attr = ppf\n\n return data\n", "repo_name": "pyg-team/pytorch_geometric", "sub_path": "torch_geometric/transforms/point_pair_features.py", "file_name": "point_pair_features.py", "file_ext": "py", "file_size_in_byte": 1794, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 18979, "dataset": "github-code", "pt": "25", "api": [{"api_name": "torch_geometric.transforms.BaseTransform", "line_number": 10, "usage_type": "name"}, {"api_name": "torch_geometric.data.Data", "line_number": 31, "usage_type": "name"}, {"api_name": "torch_geometric.nn", "line_number": 32, "usage_type": "attribute"}, {"api_name": "torch.cat", "line_number": 46, "usage_type": "call"}, {"api_name": "torch_geometric.data.datapipes.functional_transform", "line_number": 9, "usage_type": "call"}]} +{"seq_id": "9008953099", "text": "import pandas as pd\nfrom requests_html import AsyncHTMLSession \nfrom bs4 import BeautifulSoup as bs # importing BeautifulSoup\nimport nest_asyncio\nimport json\nimport re\nimport time\nnest_asyncio.apply() #jupyter notebook일 경우\nimport pymysql\nfrom tqdm import tqdm\n\ndf_cid['channel_id'] #Youtube 채널 아이디 목록 17000여개\n\nurl = \"https://www.youtube.com/channel/\"\n\nsession = AsyncHTMLSession()\nmail_pattern = r\"([\\w\\.-]+)@([\\w\\.-]+)(\\.[\\w\\.]+)\" #이메일 패턴 정규식\n\nresults = {}\n\ncnt = 0 \n\nfor cid in tqdm(df_cid['channel_id']):\n result = {}\n video_url = url+cid\n response = await session.get(video_url)\n soup = bs(response.html.html, \"html.parser\")\n if(soup.find(\"meta\", itemprop=\"description\") != None):\n description = soup.find(\"meta\", itemprop=\"description\")['content']\n else:\n description = ''\n match = re.search(mail_pattern,description)\n result['channel_id'] = cid\n if(match != None):\n result['email'] = match.group()\n else:\n result['email'] = 'None'\n results[cid] = result\n cnt += 1\n if (cnt % 99 == 0):\n time.sleep(15) #얼마나 걸어줘야 429 에러에서 벗어나는 지 몰라서 테스트 중 (100개 크롤하고 15초 휴식)\n\npd.DataFrame(results).T.to_csv('./channel_id_emails_1500.csv',encoding='utf-8-sig',index=False) #파일저장\n", "repo_name": "clastro/Crawling", "sub_path": "youtube/emailFromMeta.py", "file_name": "emailFromMeta.py", "file_ext": "py", "file_size_in_byte": 1349, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "nest_asyncio.apply", "line_number": 8, "usage_type": "call"}, {"api_name": "requests_html.AsyncHTMLSession", "line_number": 16, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 23, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 27, "usage_type": "call"}, {"api_name": "re.search", "line_number": 32, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 41, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 43, "usage_type": "call"}]} +{"seq_id": "98139637", "text": "import pandas as pd\nimport pdb\nfrom sklearn.preprocessing import LabelEncoder\n\ntrain_path = '/home/xiaodong/Desktop/tencent_ad/ad_xiaodong/data/train_preliminary/'\n\nad_name = 'ad.csv'\nuser_name = 'user.csv'\nclick_name = 'click_log.csv'\n\ndef process_error_value(x):\n try:\n x = int(x)\n return x\n except:\n return -1\n\ndef get_full_sample_data():\n df_ad = pd.read_csv(train_path + ad_name, sep=',')\n print(df_ad.columns)\n\n df_click = pd.read_csv(train_path + click_name, sep=',')\n print(df_click.columns)\n\n df_user = pd.read_csv(train_path + user_name, sep=',')\n print(df_user.columns)\n\n df = pd.merge(df_click, df_ad, on='creative_id')\n print(df.columns)\n print(df.tail(10))\n print(df.shape)\n\n df = pd.merge(df, df_user, on='user_id')\n print(df.columns)\n print(df.tail(10))\n print(df.shape)\n columns = df.columns\n df.time = df.time.apply(lambda x: int(x) % 7)\n pdb.set_trace()\n for col in columns:\n df[col] = df[col].apply(lambda x: process_error_value(x))\n if col not in ['click_times']:\n le = LabelEncoder()\n df[col] = le.fit_transform(df[col])\n\n pdb.set_trace()\n time_num = str(1)\n click_times_num = str(1)\n creative_id_num = str(len(set(df['creative_id'].astype('str').tolist())))\n ad_id_num = str(len(set(df['ad_id'].astype('str').tolist())))\n product_id_num = str(len(set(df['product_id'].astype('str').tolist())))\n product_category_num = str(len(set(df['product_category'].astype('str').tolist())))\n advertiser_id_num = str(len(set(df['advertiser_id'].astype('str').tolist())))\n industry_num = str(len(set(df['industry'].astype('str').tolist())))\n with open('/home/xiaodong/Desktop/tencent_ad/ad_xiaodong/data/sample_data/feature_sizes.txt', 'w+') as f:\n f.write(','.join([time_num, click_times_num, creative_id_num, ad_id_num, product_id_num, product_category_num, advertiser_id_num, industry_num]) + '\\n')\n df = df.drop(['user_id'], axis=1)\n df.to_csv('/home/xiaodong/Desktop/tencent_ad/ad_xiaodong/data/sample_data/train.txt', sep=',', index=None,\n columns=['time', 'click_times', 'creative_id', 'ad_id', 'product_id', 'product_category', 'advertiser_id', 'industry', 'gender'])\n df.to_csv('/home/xiaodong/Desktop/tencent_ad/ad_xiaodong/data/sample_data/train1.txt', sep=',', index=None,\n columns=['time', 'click_times', 'creative_id', 'ad_id', 'product_id', 'product_category', 'advertiser_id', 'industry', 'age'])\n\nif __name__ == '__main__':\n get_full_sample_data()", "repo_name": "golfayi/ad_xiaodong", "sub_path": "DeepFM/process_data.py", "file_name": "process_data.py", "file_ext": "py", "file_size_in_byte": 2565, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pandas.read_csv", "line_number": 19, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 22, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 25, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 28, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 33, "usage_type": "call"}, {"api_name": "pdb.set_trace", "line_number": 39, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.LabelEncoder", "line_number": 43, "usage_type": "call"}, {"api_name": "pdb.set_trace", "line_number": 46, "usage_type": "call"}]} +{"seq_id": "5060307406", "text": "import os, logging\nimport numpy, numexpr\nfrom osgeo import gdal\nfrom ULA3.dataset import SceneDataset\nfrom ULA3.common.pqa_result import PQAResult\nfrom ULA3.image_processor import ProcessorConfig\nfrom ULA3.image_processor import constants\nfrom ULA3 import DataManager\nfrom ULA3.utils import dump_array\n\nlogger = logging.getLogger('root.' + __name__)\n\ndef process(subprocess_list=[], resume=False):\n logger.info('%s.process(%s, %s) called', __name__, subprocess_list, resume)\n\n CONFIG = ProcessorConfig()\n DATA = DataManager()\n\n # Change string argument to list if necessary\n if type(subprocess_list) == str:\n subprocess_list = subprocess_list.split(',')\n\n # Create sub-sublogger to allow interleaved multithreaded logs to be sorted out afterwards\n if len(subprocess_list) == 1:\n if type(subprocess_list[0]) == str:\n sublogger_name = logger.name + '.' + subprocess_list[0]\n elif type(subprocess_list[0]) == list:\n sublogger_name = logger.name + '.' + '.'.join(subprocess_list[0])\n else:\n sublogger_name = logger.name\n logger.debug('sublogger_name = %s', sublogger_name)\n sublogger = logging.getLogger(sublogger_name)\n sublogger.debug('%s.process(%s, %s) called', __name__, subprocess_list, resume)\n else:\n sublogger = logger\n\n l1t_input_dataset = DATA.get_item(CONFIG.input['l1t']['path'], SceneDataset)\n assert l1t_input_dataset, 'Unable to retrieve SceneDataset object for L1T input scene dataset'\n sublogger.debug( 'SceneDataset object for %s retrieved', l1t_input_dataset.pathname)\n\n l1t_stack = DATA.get_item('l1t_stack', numpy.ndarray)\n assert l1t_stack is not None, 'Unable to retrieve ndarray object for l1t_stack'\n sublogger.debug( 'ndarray object for l1t_stack retrieved')\n\n result = DATA.get_item('result.tif', PQAResult)\n assert result, 'Unable to retrieve PQAResult object for result'\n sublogger.debug( 'PQAResult object for result retrieved')\n\n # *** Change this function to allow input under and over saturation values. Default 1 & 255 ?? *** DONE\n # *** Also the query is wrong. It currently is including 0 as a saturated value *** DONE\n def SaturationMask(band_array, under_sat=1, over_sat=255, use_numexpr=True):\n \"\"\"\n Creates a saturation mask for a single band.\n\n Under and over saturated pixels are masked.\n\n :param band_array:\n A 2D numpy array containing a single Landsat band.\n\n :param under_sat:\n Value used to detect under saturation. Default is 1.\n\n :param over_sat:\n Value used to detect over saturation. Default is 255.\n\n :param use_numexpr:\n If True (default) numexpression will be used to evalute the mask.\n Otherwise standard NumPy will be used to evaluate the mask.\n\n :return:\n A 2D Numpy Boolean array with True == Unsaturated.\n \"\"\"\n\n if len(band_array) == 0: return None\n assert type(band_array) == numpy.ndarray, 'Input is not valid'\n\n # Work-around for non-thread-safe numexpr expression\n if use_numexpr:\n sublogger.debug('numexpr used: numexpr.evaluate(\"(band_array != %i) & (band_array != %i)\")'%(under_sat,over_sat))\n mask = numexpr.evaluate(\"(band_array != under_sat) & (band_array != over_sat)\")\n else:\n sublogger.debug('numpy used: (band_array != %i) & (band_array != %i)'%(under_sat,over_sat))\n mask = (band_array != under_sat) & (band_array != over_sat)\n\n return mask\n\n # *** Potentially will need the full band list to be able to index the correct band *** DONE\n # List of all band numbers\n #full_band_list = sorted(set(l1t_input_dataset.bands('REFLECTIVE')) |\n # set(l1t_input_dataset.bands('THERMAL')))\n #assert len(full_band_list) == l1t_stack.shape[0], 'Mismatch between array depth and band count'\n #sublogger.debug('full_band_list = %s', full_band_list)\n\n # *** Replace with a call to PQ_constants *** DONE\n # Default to processing all reflective & thermal bands\n #band_list = [int(subprocess) for subprocess in subprocess_list] or full_band_list\n pq_const = constants.pqaContants(l1t_input_dataset.sensor)\n band_list = pq_const.saturation_bands\n full_band_list = pq_const.available_bands\n band_index_list = pq_const.getArrayBandLookup(band_list)\n \n\n # *** Replace with a call to PQ_constants *** DONE\n # Determine bit indices of all available bands from file numbers\n #bit_index_list = [CONFIG.pqa_test_index['SATURATION'][band_file_no] for band_file_no in sorted(\n # set(l1t_input_dataset.satellite.BAND_TYPES['REFLECTIVE']) |\n # set(l1t_input_dataset.satellite.BAND_TYPES['THERMAL'])\n # )]\n #assert len(bit_index_list) == l1t_stack.shape[0], 'Unable to determine bit indices for all bands'\n bit_index_list = pq_const.saturation_bits\n sublogger.debug('bit_index_list = %s', bit_index_list)\n\n # *** Change how the loop is constructed so it can retrieve the correct bit index and the correct l1t_stack band index *** DONE\n for band in band_list:\n if band not in full_band_list:\n sublogger.warning('Ignoring invalid band number: %d', band)\n continue\n\n band_index = full_band_list.index(band)\n bit_index = bit_index_list[band_list.index(band)]\n sublogger.debug('Processing saturation for band = %d, band_index = %d, bit_index = %d', band, band_index, bit_index)\n\n band_array = l1t_stack[band_index]\n\n # Use numpy for single bands run in parallel - numexpr is not thread safe\n mask = SaturationMask(band_array, (len(band_list) > 1 or CONFIG.sequential))\n\n result.set_mask(mask, bit_index)\n if CONFIG.debug:\n dump_array(mask,\n os.path.join(CONFIG.work_path, 'mask_%02d.tif' % bit_index),\n l1t_input_dataset)\n\n # *** This will need to change. Tests not run will not be set. ***\n # Copy results for first thermal band to second one if there is only one available\n if bit_index == 5 and 6 not in bit_index_list: # If this is thermal band 1 and there is no thermal band 2 in this dataset\n bit_index = 6\n sublogger.debug('Copying thermal band mask to bit %d', bit_index)\n result.set_mask(mask, bit_index)\n\n\n", "repo_name": "jeremyh/gaip", "sub_path": "image_processor/pqa/calc_pqa_masks/saturation_masking.py", "file_name": "saturation_masking.py", "file_ext": "py", "file_size_in_byte": 6411, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "logging.getLogger", "line_number": 11, "usage_type": "call"}, {"api_name": "ULA3.image_processor.ProcessorConfig", "line_number": 16, "usage_type": "call"}, {"api_name": "ULA3.DataManager", "line_number": 17, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 32, "usage_type": "call"}, {"api_name": "ULA3.dataset.SceneDataset", "line_number": 37, "usage_type": "argument"}, {"api_name": "numpy.ndarray", "line_number": 41, "usage_type": "attribute"}, {"api_name": "ULA3.common.pqa_result.PQAResult", "line_number": 45, "usage_type": "argument"}, {"api_name": "numpy.ndarray", "line_number": 75, "usage_type": "attribute"}, {"api_name": "numexpr.evaluate", "line_number": 80, "usage_type": "call"}, {"api_name": "ULA3.image_processor.constants.pqaContants", "line_number": 97, "usage_type": "call"}, {"api_name": "ULA3.image_processor.constants", "line_number": 97, "usage_type": "name"}, {"api_name": "ULA3.utils.dump_array", "line_number": 130, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 131, "usage_type": "call"}, {"api_name": "os.path", "line_number": 131, "usage_type": "attribute"}]} +{"seq_id": "8353225248", "text": "import zmq\r\nimport hashlib\r\nimport os\r\n\r\nclass FileManagementModule:\r\n def __init__(self, path):\r\n self.path = path\r\n context = zmq.Context()\r\n self.zmq_socket = context.socket(zmq.REP)\r\n self.zmq_socket.bind(\"tcp://*:5565\")\r\n\r\n def start(self):\r\n while True:\r\n #request_type|username\r\n request = self.zmq_socket.recv()\r\n request = str(request, 'utf-8')\r\n print(request)\r\n request = request.split(\"|\")\r\n if request[0] == \"store_file\":\r\n self.zmq_socket.send(bytes(\"ok\", 'utf-8'))\r\n self.__store_file(request[1])\r\n elif request[0] == \"delete_file\":\r\n self.__delete_file(request[1], request[2])\r\n elif request[0] == \"list_files\":\r\n self.__list_user_file(request[1])\r\n elif request[0] == \"register_user\":\r\n self.zmq_socket.send(bytes(\"ok\", 'utf-8'))\r\n self.__create_user_storage(request[1])\r\n elif request[0] == \"retrieve_file\":\r\n self.__retrieve_file(request[1], request[2])\r\n elif request[0] == \"check_if_file_exists\":\r\n self.__check_if_file_exists(request[1], request[2])\r\n else:\r\n self.zmq_socket.send(b\"invalid_request\")\r\n\r\n def __check_if_file_exists(self, username, file):\r\n file_to_retrieve_path = self.__generate_path_to_file(username, file)\r\n # check if file exists or not\r\n if not os.path.isfile(file_to_retrieve_path):\r\n self.zmq_socket.send(b\"file-1\")\r\n else:\r\n self.zmq_socket.send(b\"file1\")\r\n\r\n def __store_file(self, username):\r\n #receive file metadata\r\n file_name, file_size = self.__receive_file_metadata()\r\n user_directory_path = self.path + \"\\\\\" + username + \"\\\\\" + file_name\r\n\r\n #send okay to split the buffer\r\n self.zmq_socket.send(bytes(\"ok\", 'utf-8'))\r\n\r\n #receive the file contents\r\n file_content = self.zmq_socket.recv()\r\n self.zmq_socket.send(bytes(\"ok\", 'utf-8'))\r\n\r\n #receie the hash result\r\n hash_result = self.zmq_socket.recv()\r\n #self.zmq_socket.send(bytes(\"ok\", 'utf-8'))\r\n\r\n if self.__check_hash(file_name, file_size, file_content, hash_result) == 1:\r\n self.zmq_socket.send(bytes(\"Hash1\", 'utf-8'))\r\n with open(user_directory_path, 'wb+') as file_descriptor:\r\n file_descriptor.write(file_content)\r\n file_descriptor.close()\r\n else:\r\n self.zmq_socket.send(\"Hash-1\")\r\n\r\n def __receive_file_metadata(self):\r\n #file_name|file_size\r\n raw_data = self.zmq_socket.recv()\r\n raw_data = str(raw_data, 'utf-8')\r\n\r\n split_raw_data = raw_data.split(\"|\")\r\n file_name = split_raw_data[0]\r\n file_size = split_raw_data[1]\r\n\r\n return file_name, file_size\r\n\r\n def __build_hash(self, file_name, file_size, file_content):\r\n hash_result = hashlib.sha3_512()\r\n hash_result.update(bytes(file_name, 'utf-8'))\r\n hash_result.update(bytes(str(file_size), 'utf-8'))\r\n hash_result.update(file_content)\r\n\r\n return hash_result.digest()\r\n\r\n def __check_hash(self, file_name, file_size, file_content, received_hash):\r\n built_hash = self.__build_hash(file_name, file_size, file_content)\r\n if received_hash == built_hash:\r\n return 1\r\n else:\r\n return 0\r\n\r\n def __generate_path_to_file(self, username, file_name):\r\n path_to_file = self.path + \"\\\\\"+username + \"\\\\\" + file_name\r\n return path_to_file\r\n\r\n def __retrieve_file(self, username, file_name):\r\n file_to_retrieve_path = self.__generate_path_to_file(username, file_name)\r\n #check if file exists or not\r\n if not os.path.isfile(file_to_retrieve_path):\r\n self.zmq_socket.send(b\"file-1\")\r\n return -1\r\n # generate file name and size\r\n file_name = file_to_retrieve_path.split(\"\\\\\")[-1]\r\n file_size = os.path.getsize(file_to_retrieve_path)\r\n # read the files contents\r\n file_descriptor = open(file_to_retrieve_path, \"rb\")\r\n file_content = file_descriptor.read()\r\n\r\n hash_result = self.__build_hash(file_name, file_size, file_content)\r\n\r\n #send metada\r\n file_metadata = file_name + \"|\" + str(file_size)\r\n self.zmq_socket.send(bytes(file_metadata, \"utf-8\"))\r\n #wait for ok\r\n self.zmq_socket.recv()\r\n #send content\r\n self.zmq_socket.send(file_content)\r\n #wait for ok\r\n self.zmq_socket.recv()\r\n #send hash\r\n self.zmq_socket.send(hash_result)\r\n\r\n def __retrieve_key(self, key_name):\r\n pass\r\n\r\n def __create_user_storage(self, username):\r\n user_directory_path = self.path + \"\\\\\" + username\r\n os.mkdir(user_directory_path)\r\n\r\n def __list_user_file(self, username):\r\n user_directory_path = self.path + \"\\\\\" + username\r\n result = os.listdir(user_directory_path)\r\n files_stored = \"\"\r\n if len(result) > 0:\r\n for i in range(0, len(result)):\r\n files_stored += result[i] + \"|\"\r\n files_stored = files_stored[:-1]\r\n self.zmq_socket.send(bytes(files_stored, 'utf-8'))\r\n\r\n def __delete_file(self, username, file_name):\r\n file_to_delete_path = self.path + \"\\\\\"+username + \"\\\\\" + file_name\r\n if os.path.isfile(file_to_delete_path):\r\n if os.remove(file_to_delete_path):\r\n self.zmq_socket.send(bytes(\"delete-1\", \"utf-8\"))\r\n else:\r\n self.zmq_socket.send(bytes(\"delete1\", \"utf-8\"))\r\n else:\r\n self.zmq_socket.send(bytes(\"delete-1\", \"utf-8\"))\r\n\r\n\r\nobj = FileManagementModule(\"C:\\\\Users\\\\lazar\\\\Desktop\\Scheme\\\\Storage\")\r\nobj.start()\r\n\r\n\r\n\r\n#file names will be encrypted with a user key(or not?)(creates problems)\r\n#every user will have a folder\r\n#keys will be stored in a filed named hash(file_name,username)\r\n#list user files command\r\n#list other user files as admin\r\n#password\r\n#make admin acc", "repo_name": "lazaroidarius/Cloud-Storage-Scheme-POC", "sub_path": "Server/FileManagementModule.py", "file_name": "FileManagementModule.py", "file_ext": "py", "file_size_in_byte": 6132, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "zmq.Context", "line_number": 8, "usage_type": "call"}, {"api_name": "zmq.REP", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path", "line_number": 39, "usage_type": "attribute"}, {"api_name": "hashlib.sha3_512", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 101, "usage_type": "call"}, {"api_name": "os.path", "line_number": 101, "usage_type": "attribute"}, {"api_name": "os.path.getsize", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path", "line_number": 106, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 130, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 134, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 144, "usage_type": "call"}, {"api_name": "os.path", "line_number": 144, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 145, "usage_type": "call"}]} +{"seq_id": "3645090249", "text": "from bs4 import BeautifulSoup\nimport urllib.request as req\nimport requests\nimport os\nfrom concurrent.futures import ThreadPoolExecutor\nimport glob\n\nparentDirectory = \"D:\\\\Python-ds\\\\Python-ds\\\\Tkinter\\\\Check\" #Parent directory\nmainUrl = \"https://e4ftl01.cr.usgs.gov/MOTA/MCD43A4.006/\" # main url from which we get the data\nprint(\"Please enter the date\")\n\ndate = input()\ndate = date.replace(\"-\", \".\")\ndate = date + \"/\"\ndic = {}\nr = requests.get(mainUrl)\ncontent0 = r.content\nsoup = BeautifulSoup(content0, features = \"lxml\")\nimages = soup.find_all('a')\nurls =[]\nfor image in images:\n href = str(image).split(\">\")\n urladd = href[1].split(\"<\")\n urls.append(urladd[0])\nstart = urls.index(date)\nurls = urls[start:]\n\n\ndef download(urlstart):\n updatestr = mainUrl + urlstart #updating the url to get into the date\n year, month, day = urlstart.split(\".\")\n\n yearpath = os.path.join(parentDirectory,year)\n if( not os.path.exists(yearpath)):\n os.mkdir(yearpath)\n monthpath = os.path.join(yearpath, month)\n if( not os.path.exists(monthpath)):\n os.mkdir(monthpath)\n datepath = os.path.join(monthpath, day)\n if (not os.path.exists(datepath)):\n os.mkdir(datepath)\n abi = requests.get(updatestr)\n content1 = abi.content\n soup1 = BeautifulSoup(content1, features = \"lxml\")\n href = soup1.find_all('a')\n j = 0\n for h in href:\n i = str(h).split(\"\\\"\") #getting the image name\n imagelink = updatestr + i[1] # getting the image\n ext = \".jpg\"\n if ext in imagelink:\n os.chdir(datepath)\n req.urlretrieve(imagelink, i[1])\n countofimages = str(datepath)\n countImages = countofimages.replace(\"\\\\\", \"/\")\n countImages = countImages + \"/*\"\n count = os.path.normpath(countImages)\n ImagesCount = glob.glob(count)\n print(len(ImagesCount))\n print(str(updatestr))\n if urlstart not in dic:\n dic[urlstart] = []\n dic[urlstart].append(urlstart)\n dic[urlstart].append(str(updatestr))\n dic[urlstart].append(len(ImagesCount))\n else:\n dic[urlstart].append(len(ImagesCount))\n\n\n\nif __name__ == '__main__':\n with ThreadPoolExecutor(max_workers = 12) as executor: # starts the Threadpool executor with 6 threads\n results = executor.map(download, urls) # Maping the process to the threadpool\n print(dic)\n\n", "repo_name": "Abijithhebbar/Python-ds", "sub_path": "Tkinter/app3.py", "file_name": "app3.py", "file_ext": "py", "file_size_in_byte": 2351, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "requests.get", "line_number": 16, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path", "line_number": 36, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path", "line_number": 39, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 41, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 42, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 44, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 52, "usage_type": "call"}, {"api_name": "urllib.request.urlretrieve", "line_number": 53, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 53, "usage_type": "name"}, {"api_name": "os.path.normpath", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path", "line_number": 57, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 58, "usage_type": "call"}, {"api_name": "concurrent.futures.ThreadPoolExecutor", "line_number": 72, "usage_type": "call"}]} +{"seq_id": "9699664327", "text": "# %% imports\nimport sys\nimport os\nfrom glob import glob\nimport matplotlib.pyplot as plt\nimport cv2\nfrom math import sqrt\nframe_width = 3840\nframe_height = 2160\nratio = frame_width / frame_height\nplot_width = 14\nout_res = 227\nsqrt2 = sqrt(2)\n\ndef jpg(name):\n return str(name) + '.jpg'\n \ndef txt(name):\n return str(name) + '.txt'\n \ndef show(frame):\n plt.figure(figsize=(plot_width, plot_width * ratio))\n plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n\n# %% argparse\n\nif len(sys.argv) < 3:\n print('pass out_path and at least one folder')\n exit(1)\n\nout_path = sys.argv[1]\nprint(f'out: {out_path}')\nout_file = open(out_path, mode='a')\nfolder_paths = sys.argv[2:]\nfor folder_path in folder_paths:\n print(folder_path)\n target_folder_path = folder_path + '_target'\n searching_folder_path = folder_path + '_searching'\n\n file_list = glob(os.path.join(folder_path, '*.jpg'))\n file_list.sort()\n if not os.path.isdir(target_folder_path): os.mkdir(target_folder_path)\n if not os.path.isdir(searching_folder_path): os.mkdir(searching_folder_path)\n\n for index, target_path in enumerate(file_list):\n if index == len(file_list)-1: break\n _, target_file = os.path.split(target_path)\n target_name, _ = os.path.splitext(target_file)\n target_txt_path = os.path.join(folder_path, txt(target_name))\n target = cv2.imread(target_path)\n try:\n with open(target_txt_path, mode='r') as file:\n _, x, y, _, height = file.readline().split(' ')\n x, y, height = round(float(x)*frame_width), round(float(y)*frame_height), round(float(height)*frame_height)\n x,y,height\n except Exception as e:\n print(e)\n continue\n offset = round(sqrt2*height/2)\n left, top, right, bottom = x-offset, y-offset, x+offset, y+offset\n cropped_height = bottom-top\n scale = out_res / cropped_height\n try:\n resized_target = cv2.resize(target[top:bottom, left:right], (out_res, out_res))\n except Exception as e:\n print(e)\n continue\n target_out_path = os.path.join(target_folder_path, jpg(target_name))\n cv2.imwrite(target_out_path, resized_target)\n \n for i in range(index+1,index+6,2):\n print(index, i)\n try:\n searching_path = file_list[i]\n except IndexError as e:\n break\n _, searching_file = os.path.split(searching_path)\n searching_name, _ = os.path.splitext(searching_file)\n searching = cv2.imread(searching_path)\n searching_txt_path = os.path.join(folder_path, txt(searching_name))\n resized_searching = cv2.resize(searching[top:bottom, left:right], (out_res, out_res))\n try:\n with open(searching_txt_path, mode='r') as file:\n _, x, y, width, height = file.readline().split(' ')\n x, y, offset_x, offset_y = float(x)*frame_width, float(y)*frame_height, float(width)*frame_width/2, float(height)*frame_height/2\n except Exception as e:\n print(e)\n continue\n sleft, stop, sright, sbottom = round(x-offset_x), round(y-offset_y), round(x+offset_x), round(y+offset_y)\n sleft, stop, sright, sbottom = sleft-left, stop-top, sright-left, sbottom-top\n sleft, stop, sright, sbottom = sleft*scale, stop*scale, sright*scale, sbottom*scale\n sleft, stop, sright, sbottom = sleft/out_res, stop/out_res, sright/out_res, sbottom/out_res\n \n searching_out_path = os.path.join(searching_folder_path, jpg(f'{target_name}_{i}'))\n cv2.imwrite(searching_out_path, resized_searching)\n out_file.write(f'{target_out_path},{searching_out_path},{sleft},{stop},{sright},{sbottom}\\n')\n \nout_file.close()\n", "repo_name": "jschiefner/horse-tracker-cvlab", "sub_path": "convert_images_to_goturn.py", "file_name": "convert_images_to_goturn.py", "file_ext": "py", "file_size_in_byte": 3910, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "math.sqrt", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "cv2.cvtColor", "line_number": 23, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 23, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 27, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 31, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 34, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path", "line_number": 42, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path", "line_number": 43, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path.split", "line_number": 47, "usage_type": "call"}, {"api_name": "os.path", "line_number": 47, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path", "line_number": 48, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path", "line_number": 49, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 50, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path", "line_number": 68, "usage_type": "attribute"}, {"api_name": "cv2.imwrite", "line_number": 69, "usage_type": "call"}, {"api_name": "os.path.split", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path", "line_number": 77, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path", "line_number": 78, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 79, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path", "line_number": 80, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 81, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 94, "usage_type": "call"}, {"api_name": "os.path", "line_number": 94, "usage_type": "attribute"}, {"api_name": "cv2.imwrite", "line_number": 95, "usage_type": "call"}]} +{"seq_id": "73364954608", "text": "import base64\nimport json\nimport logging\nimport os\nimport secrets\nimport socket\nimport string\nimport subprocess\nfrom typing import List\n\nimport ops_sunbeam.charm as sunbeam_charm\nimport ops_sunbeam.guard as sunbeam_guard\nimport ops_sunbeam.ovn.relation_handlers as ovn_relation_handlers\nimport ops_sunbeam.relation_handlers as sunbeam_rhandlers\nfrom netifaces import AF_INET, gateways, ifaddresses\nimport ops.framework\nfrom ops.main import main\n\nlogger = logging.getLogger(__name__)\n\n\ndef _get_local_ip_by_default_route() -> str:\n \"\"\"Get IP address of host associated with default gateway.\"\"\"\n interface = \"lo\"\n ip = \"127.0.0.1\"\n\n # TOCHK: Gathering only IPv4\n if \"default\" in gateways():\n interface = gateways()[\"default\"][AF_INET][1]\n\n ip_list = ifaddresses(interface)[AF_INET]\n if len(ip_list) > 0 and \"addr\" in ip_list[0]:\n ip = ip_list[0][\"addr\"]\n\n return ip\n\n\nclass HypervisorOperatorCharm(sunbeam_charm.OSBaseOperatorCharm):\n \"\"\"Charm the service.\"\"\"\n\n _state = ops.framework.StoredState()\n service_name = \"hypervisor\"\n METADATA_SECRET_KEY = \"ovn-metadata-proxy-shared-secret\"\n DEFAULT_SECRET_LENGTH = 32\n\n def __init__(self, framework: ops.framework.Framework) -> None:\n \"\"\"Run constructor.\"\"\"\n super().__init__(framework)\n self._state.set_default(metadata_secret='')\n\n def get_relation_handlers(\n self, handlers: List[sunbeam_rhandlers.RelationHandler] = None\n ) -> List[sunbeam_rhandlers.RelationHandler]:\n \"\"\"Relation handlers for the service.\"\"\"\n handlers = handlers or []\n if self.can_add_handler(\"ovsdb-cms\", handlers):\n self.ovsdb_cms = ovn_relation_handlers.OVSDBCMSRequiresHandler(\n self,\n \"ovsdb-cms\",\n self.configure_charm,\n \"ovsdb-cms\" in self.mandatory_relations,\n )\n handlers.append(self.ovsdb_cms)\n handlers = super().get_relation_handlers(handlers)\n return handlers\n\n def ensure_services_running(self):\n \"\"\"Ensure systemd services running.\"\"\"\n # This should taken care of by the snap\n svcs = [\n 'snap.openstack-hypervisor.neutron-ovn-metadata-agent.service',\n 'snap.openstack-hypervisor.nova-api-metadata.service',\n 'snap.openstack-hypervisor.nova-compute.service']\n for svc in svcs:\n if os.system(f'systemctl is-active --quiet {svc}') != 0:\n os.system(f'systemctl start {svc}')\n\n def generate_metadata_secret(self) -> str:\n \"\"\"Generate a secure secret.\n\n :param length: length of generated secret\n :type length: int\n :return: string containing the generated secret\n \"\"\"\n return \"\".join(\n secrets.choice(string.ascii_letters + string.digits)\n for i in range(self.DEFAULT_SECRET_LENGTH)\n )\n\n def metadata_secret(self) -> str:\n \"\"\"Retrieve or set self.METADATA_SECRET_KEY.\"\"\"\n if self._state.metadata_secret:\n logging.debug(\"Found metadata secret in local db\")\n return self._state.metadata_secret\n else:\n logging.debug(\"Generating new metadata secret\")\n secret = self.generate_metadata_secret()\n self._state.metadata_secret = secret\n return secret\n\n def configure_unit(self, event) -> None:\n \"\"\"Run configuration on this unit.\"\"\"\n self.check_leader_ready()\n self.check_relation_handlers_ready()\n config = self.model.config.get\n subprocess.check_call(\n [\n \"snap\",\n \"install\",\n \"openstack-hypervisor\",\n \"--channel\",\n config(\"snap-channel\"),\n ]\n )\n local_ip = _get_local_ip_by_default_route()\n try:\n contexts = self.contexts()\n sb_connection_strs = list(contexts.ovsdb_cms.db_ingress_sb_connection_strs)\n if not sb_connection_strs:\n raise AttributeError(name='ovsdb southbound ingress string')\n snap_data = {\n \"compute.cpu-mode\": \"host-model\",\n \"compute.spice-proxy-address\": config(\"ip-address\") or local_ip,\n \"compute.virt-type\": \"kvm\",\n \"credentials.ovn-metadata-proxy-shared-secret\": self.metadata_secret(),\n \"identity.auth-url\": contexts.identity_credentials.public_endpoint,\n \"identity.password\": contexts.identity_credentials.password,\n \"identity.project-domain-name\": contexts.identity_credentials.project_domain_name,\n \"identity.project-name\": contexts.identity_credentials.project_name,\n \"identity.region-name\": contexts.identity_credentials.region,\n \"identity.user-domain-name\": contexts.identity_credentials.user_domain_name,\n \"identity.username\": contexts.identity_credentials.username,\n \"logging.debug\": json.dumps(config(\"debug\")),\n \"network.dns-domain\": config(\"dns-domain\"),\n \"network.dns-servers\": config(\"dns-servers\"),\n \"network.enable-gateway\": json.dumps(config(\"enable-gateway\")),\n \"network.external-bridge\": config(\"external-bridge\"),\n \"network.external-bridge-address\": config(\"external-bridge-address\") or \"10.20.20.1/24\",\n \"network.ip-address\": config(\"ip-address\") or local_ip,\n \"network.ovn-key\": base64.b64encode(\n contexts.certificates.key.encode()\n ).decode(),\n \"network.ovn-cert\": base64.b64encode(\n contexts.certificates.cert.encode()\n ).decode(),\n \"network.ovn-cacert\": base64.b64encode(\n contexts.certificates.ca_cert.encode()\n ).decode(),\n \"network.ovn-sb-connection\": sb_connection_strs[0],\n \"network.physnet-name\": config(\"physnet-name\"),\n \"node.fqdn\": config(\"fqdn\") or socket.getfqdn(),\n \"node.ip-address\": config(\"ip-address\") or local_ip,\n \"rabbitmq.url\": contexts.amqp.transport_url,\n }\n\n cmd = [\"snap\", \"set\", \"openstack-hypervisor\"] + [\n f\"{k}={v}\" for k, v in snap_data.items()\n ]\n except AttributeError as e:\n raise sunbeam_guard.WaitingExceptionError(\"Data missing: {}\".format(e.name))\n subprocess.check_call(cmd)\n self.ensure_services_running()\n self._state.unit_bootstrapped = True\n\n\nif __name__ == \"__main__\": # pragma: no cover\n main(HypervisorOperatorCharm)\n", "repo_name": "openstack-charmers/charm-openstack-hypervisor", "sub_path": "src/charm.py", "file_name": "charm.py", "file_ext": "py", "file_size_in_byte": 6701, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "logging.getLogger", "line_number": 19, "usage_type": "call"}, {"api_name": "netifaces.gateways", "line_number": 28, "usage_type": "call"}, {"api_name": "netifaces.gateways", "line_number": 29, "usage_type": "call"}, {"api_name": "netifaces.AF_INET", "line_number": 29, "usage_type": "name"}, {"api_name": "netifaces.ifaddresses", "line_number": 31, "usage_type": "call"}, {"api_name": "netifaces.AF_INET", "line_number": 31, "usage_type": "name"}, {"api_name": "ops_sunbeam.charm.OSBaseOperatorCharm", "line_number": 38, "usage_type": "attribute"}, {"api_name": "ops_sunbeam.charm", "line_number": 38, "usage_type": "name"}, {"api_name": "ops.framework.framework.StoredState", "line_number": 41, "usage_type": "call"}, {"api_name": "ops.framework.framework", "line_number": 41, "usage_type": "attribute"}, {"api_name": "ops.framework", "line_number": 41, "usage_type": "name"}, {"api_name": "ops.framework.framework", "line_number": 46, "usage_type": "attribute"}, {"api_name": "ops.framework", "line_number": 46, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 52, "usage_type": "name"}, {"api_name": "ops_sunbeam.relation_handlers.RelationHandler", "line_number": 52, "usage_type": "attribute"}, {"api_name": "ops_sunbeam.relation_handlers", "line_number": 52, "usage_type": "name"}, {"api_name": "ops_sunbeam.ovn.relation_handlers.OVSDBCMSRequiresHandler", "line_number": 57, "usage_type": "call"}, {"api_name": "ops_sunbeam.ovn.relation_handlers", "line_number": 57, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 53, "usage_type": "name"}, {"api_name": "ops_sunbeam.relation_handlers.RelationHandler", "line_number": 53, "usage_type": "attribute"}, {"api_name": "ops_sunbeam.relation_handlers", "line_number": 53, "usage_type": "name"}, {"api_name": "os.system", "line_number": 75, "usage_type": "call"}, {"api_name": "os.system", "line_number": 76, "usage_type": "call"}, {"api_name": "secrets.choice", "line_number": 86, "usage_type": "call"}, {"api_name": "string.ascii_letters", "line_number": 86, "usage_type": "attribute"}, {"api_name": "string.digits", "line_number": 86, "usage_type": "attribute"}, {"api_name": "logging.debug", "line_number": 93, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 96, "usage_type": "call"}, {"api_name": "subprocess.check_call", "line_number": 106, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 133, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 136, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 140, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 143, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 146, "usage_type": "call"}, {"api_name": "socket.getfqdn", "line_number": 151, "usage_type": "call"}, {"api_name": "ops_sunbeam.guard.WaitingExceptionError", "line_number": 160, "usage_type": "call"}, {"api_name": "ops_sunbeam.guard", "line_number": 160, "usage_type": "name"}, {"api_name": "subprocess.check_call", "line_number": 161, "usage_type": "call"}, {"api_name": "ops.main.main", "line_number": 167, "usage_type": "call"}]} +{"seq_id": "12492833803", "text": "import numpy as np\nimport pandas as pd\ntry:\n import cupy as cp\nexcept Exception as e:\n print(e)\n\nfrom .. import Variable\nfrom .. import optimizer\nfrom .. import GradientTape\nfrom .. import layer\nfrom ..models import Model\nfrom .. import functions as f\nfrom ..core import elementary_function as ef\nfrom ..core import shape_function as sf\nfrom . import DataSet\n\nimport tensorflow as tf\nfrom tensorflow.keras import datasets\nfrom sklearn.metrics import accuracy_score, f1_score, confusion_matrix\nimport matplotlib.pyplot as plt\n\nimport time\n\nclass Models(Model):\n def __init__(self, hidden_size, out_size):\n super().__init__()\n self.l1 = layer.Linear(hidden_size, initializer_func='he_uniform')\n self.l2 = layer.Linear(hidden_size, initializer_func='he_uniform')\n self.l3 = layer.Linear(out_size, initializer_func='he_uniform')\n\n def forward(self, x):\n y = self.l1(x)\n y = f.activation.relu(y)\n y = self.l2(y)\n y = f.activation.relu(y)\n y = self.l3(y)\n return y\n\nclass clf_Models(Model):\n def __init__(self, hidden_size, out_size):\n super().__init__()\n self.l1 = layer.Linear(hidden_size, initializer_func='he_uniform')\n self.l2 = layer.Linear(hidden_size, initializer_func='he_uniform')\n self.l3 = layer.Linear(out_size, initializer_func='he_uniform')\n\n def forward(self, x):\n y = self.l1(x)\n y = f.activation.relu(y)\n y = self.l2(y)\n y = f.activation.relu(y)\n y = self.l3(y)\n y = f.activation.softmax(y)\n return y\n\n\nclass SimpleRNN(Model):\n def __init__(self, hidden_size, out_size):\n super().__init__()\n self.l1 = layer.RNN(hidden_size)\n self.l2 = layer.Linear(out_size, initializer_func='he_uniform')\n\n def forward(self, x):\n y = self.l1(x)\n y = y[-2:-1]\n y = self.l2(y)\n return y\n\nclass CNN(Model):\n def __init__(self):\n super().__init__()\n self.l1 = layer.Conv2d(64, (3,3))\n self.l2 = layer.Conv2d(128, (2,2))\n self.l3 = layer.Conv2d(64, (3,3))\n self.predict = layer.Linear(10)\n self.flatten = layer.flatten\n\n def forward(self, x):\n y = self.l1(x)\n y = f.activation.relu(y)\n y = self.l2(x)\n y = f.activation.relu(y)\n y = self.l3(x)\n y = f.activation.relu(y)\n y = self.flatten(y)\n y = self.predict(y)\n\n return y\n\nclass TestFunction():\n def matyas(self, x, y):\n z = 0.26 * (x ** 2 + y ** 2) - 0.48 * x * y\n return z\n\n def goldstein(self, x, y):\n z = (1 + (x + y + 1) ** 2 * (19 - 14 * x + 3 * x ** 2 - 14 * y + 6 * x * y + 3 * y ** 2)) * \\\n (30 + (2 * x - 3 * y) ** 2 * (18 - 32 * x + 12 * x ** 2 + 48 * y - 36 * x * y + 27 * y ** 2))\n return z\n\n\nclass OrderFunction():\n def high_order_function(self, x, y):\n z = x ** 4 + y ** 3 + x ** 2 + y ** (1 / 2)\n return z\n\n def matrix_order_function(self, x):\n y = 2 * x ** 3\n return y\n\n\nclass JacobianFunction():\n def matmul(self, x, y, k):\n with GradientTape() as tape:\n result = ef.matmul(x, sf.transpose(y))\n result_2 = ef.matmul(result, k)\n return tape\n\n def reduce_sum(self, x, y, k):\n with GradientTape() as tape:\n result = ef.matmul(x, sf.transpose(y))\n result_2 = ef.matmul(result, k)\n result_3 = ef.flowsum(result_2)\n return tape\n\n def div(self, x, y, k):\n with GradientTape() as tape:\n result = ef.matmul(x, sf.transpose(y))\n result_2 = ef.matmul(result, k)\n result_3 = result_2 / result\n return tape\n\n def sum(self, x, y, k):\n with GradientTape() as tape:\n result = ef.matmul(x, sf.transpose(y))\n result_2 = ef.matmul(result, k)\n result_3 = result_2 + result\n return tape\n\n def mul(self, x, y, k):\n with GradientTape() as tape:\n result = ef.matmul(x, sf.transpose(y))\n result_2 = ef.matmul(result, k)\n result_3 = result_2 * result\n return tape\n\n\nclass GradientStartFunction():\n def gradient_start_middle(self, x, y, k):\n x = Variable(np.array([[1., 2.], [4., 5.]]))\n v = Variable(np.array([[4., 5.], [6., 7.]]))\n k = Variable(np.array([[1., 3.], [4., 6.]]))\n\n with GradientTape() as tape:\n result = ef.matmul(x, sf.transpose(v))\n result_2 = ef.matmul(result, k)\n result_3 = result_2 / x\n\n tape.CalcGradient(target=result_2)\n return x.grad.data, v.grad.data, k.grad.data\n\n def gradient_stop_test(self, x, y, k):\n x = Variable(np.array([[1., 2.], [4., 5.]]))\n v = Variable(np.array([[4., 5.], [6., 7.]]))\n k = Variable(np.array([[1., 3.], [4., 6.]]))\n\n with GradientTape() as tape_1, GradientTape() as tape_2:\n result = ef.matmul(x, sf.transpose(v))\n result_2 = ef.matmul(ef.stop_gradient(result), k)\n result_2 = result_2 ** 2\n result_3 = result_2 * x\n tape_2.CalcGradient()\n return x.grad.data, k.grad.data\n\nclass LinalgFunction():\n def linalg_concat_test(self):\n x = Variable(np.array([[[3.0, 2.0, 1.0]], [[6., 5., 4.]]]))\n y = Variable(np.array([[[1.0, 2.0, 3.0]], [[4., 5., 6.]]]))\n k = Variable(np.array([[[1.0, 2.0, 5.0]], [[7., 8., 9.]]]))\n\n with GradientTape() as tape:\n d = x * y\n concats = f.linalg.flowconcat([k, d])\n result = concats * concats\n\n tape.CalcGradient()\n\n return concats.grad.data, k.grad.data, d.grad.data, x.grad.data, y.grad.data\n\n def linalg_stack_test(self):\n x = Variable(np.array([[[3.0, 2.0, 1.0]], [[6., 5., 4.]]]))\n y = Variable(np.array([[[1.0, 2.0, 3.0]], [[4., 5., 6.]]]))\n k = Variable(np.array([[[1.0, 2.0, 5.0]], [[7., 8., 9.]]]))\n\n with GradientTape() as tape:\n d = x * y\n concats = f.linalg.flowstack([k, d])\n result = concats * concats\n\n tape.CalcGradient()\n\n return concats.grad.data, k.grad.data, d.grad.data, x.grad.data, y.grad.data\n\nclass TestAnswer():\n\n def matyas(self, x=None, y=None):\n if (x is None) | (y is None):\n return (0.040000000000000036, 0.040000000000000036)\n else:\n return\n\n def goldstein(self, x=None, y=None):\n if (x is None) | (y is None):\n return (-5376.0, 8064.0)\n else:\n return\n\n def high_order_function(self, order, x=None, y=None):\n if order == 0:\n if (x is None) | (y is None):\n return 36., 12.3535\n else:\n return\n\n if order == 1:\n if (x is None) | (y is None):\n return 50, 11.911\n else:\n return\n\n else:\n return\n\n def matrix_order_function(self, order, x=None, y=None):\n if order == 0:\n if (x is None) | (y is None):\n return np.array([[6., 24.], [96., 150.]])\n else:\n return\n\n if order == 1:\n if (x is None) | (y is None):\n return np.array([[12., 24.], [48., 60.]])\n else:\n return\n\n if order == 2:\n if (x is None) | (y is None):\n return np.array([[12., 12.], [12., 12.]])\n else:\n return\n\n def matmul(self, x=None, y=None, k=None):\n answer = []\n if x is None:\n x = tf.Variable(np.array([[1., 2.], [4., 5.]]))\n y = tf.Variable(np.array([[4., 5.], [6., 7.]]))\n k = tf.Variable(np.array([[1., 3.], [4., 6.]]))\n for i in ['x', 'y', 'k']:\n with tf.GradientTape() as tape:\n result = tf.matmul(x, tf.transpose(y))\n result_2 = tf.matmul(result, k)\n\n answer.append(tape.jacobian(result_2, eval(i)).numpy())\n return tuple(answer)\n\n def reduce_sum(self, x=None, y=None, k=None):\n if x is None:\n x = tf.Variable(np.array([[1., 2.], [4., 5.]]))\n y = tf.Variable(np.array([[4., 5.], [6., 7.]]))\n k = tf.Variable(np.array([[1., 3.], [4., 6.]]))\n answer = []\n for i in ['x', 'y', 'k']:\n with tf.GradientTape() as tape:\n result = tf.matmul(x, tf.transpose(y))\n result_2 = tf.matmul(result, k)\n result_3 = tf.math.reduce_sum(result_2)\n\n answer.append(tape.jacobian(result_3, eval(i)).numpy())\n\n return tuple(answer)\n\n def div(self, x=None, y=None, k=None):\n if x is None:\n x = tf.Variable(np.array([[1., 2.], [4., 5.]]))\n y = tf.Variable(np.array([[4., 5.], [6., 7.]]))\n k = tf.Variable(np.array([[1., 3.], [4., 6.]]))\n answer = []\n for i in ['x', 'y', 'k']:\n with tf.GradientTape() as tape:\n result = tf.matmul(x, tf.transpose(y))\n result_2 = tf.matmul(result, k)\n result_3 = result_2 / result\n\n answer.append(tape.jacobian(result_3, eval(i)).numpy())\n\n return tuple(answer)\n\n def sum(self, x=None, y=None, k=None):\n if x is None:\n x = tf.Variable(np.array([[1., 2.], [4., 5.]]))\n y = tf.Variable(np.array([[4., 5.], [6., 7.]]))\n k = tf.Variable(np.array([[1., 3.], [4., 6.]]))\n answer = []\n for i in ['x', 'y', 'k']:\n with tf.GradientTape() as tape:\n result = tf.matmul(x, tf.transpose(y))\n result_2 = tf.matmul(result, k)\n result_3 = result_2 + result\n\n answer.append(tape.jacobian(result_3, eval(i)).numpy())\n\n return tuple(answer)\n\n def mul(self, x=None, y=None, k=None):\n if x is None:\n x = tf.Variable(np.array([[1., 2.], [4., 5.]]))\n y = tf.Variable(np.array([[4., 5.], [6., 7.]]))\n k = tf.Variable(np.array([[1., 3.], [4., 6.]]))\n answer = []\n for i in ['x', 'y', 'k']:\n with tf.GradientTape() as tape:\n result = tf.matmul(x, tf.transpose(y))\n result_2 = tf.matmul(result, k)\n result_3 = result_2 * result\n\n answer.append(tape.jacobian(result_3, eval(i)).numpy())\n\n return tuple(answer)\n\n def start_middle(self, x=None, y=None, k=None):\n x = tf.Variable(np.array([[1., 2.], [4., 5.]]))\n v = tf.Variable(np.array([[4., 5.], [6., 7.]]))\n k = tf.Variable(np.array([[1., 3.], [4., 6.]]))\n\n with tf.GradientTape() as tape:\n result = tf.matmul(x, tf.transpose(v))\n result_2 = tf.matmul(result, k)\n result_3 = result_2 / x\n\n answer = tape.gradient(result_2, [x, v])\n\n return answer\n\n def gradient_start_middle(self, x=None, y=None, k=None):\n x = tf.Variable(np.array([[1., 2.], [4., 5.]]))\n v = tf.Variable(np.array([[4., 5.], [6., 7.]]))\n k = tf.Variable(np.array([[1., 3.], [4., 6.]]))\n\n with tf.GradientTape() as tape:\n result = tf.matmul(x, tf.transpose(v))\n result_2 = tf.matmul(result, k)\n result_3 = result_2 / x\n\n answer = tape.gradient(result_2, [x, v, k])\n answer = [i.numpy() for i in answer]\n\n return answer\n\n def gradient_stop_test(self, x=None, y=None, k=None):\n x = tf.Variable(np.array([[1., 2.], [4., 5.]]))\n v = tf.Variable(np.array([[4., 5.], [6., 7.]]))\n k = tf.Variable(np.array([[1., 3.], [4., 6.]]))\n\n with tf.GradientTape() as tape:\n result = tf.matmul(x, tf.transpose(v))\n result_2 = tf.matmul(tf.stop_gradient(result), k)\n result_2 = result_2 ** 2\n result_3 = result_2 * x\n\n answer = tape.gradient(result_3, [x, k])\n answer = [i.numpy() for i in answer]\n\n return answer\n\n def linalg_concat_test(self):\n a = np.array([[[2., 4., 10.]],\n [[14., 16., 18.]],\n [[6., 8., 6.]],\n [[48., 50., 48.]]])\n\n b = np.array([[[2., 4., 10.]],\n [[14., 16., 18.]]])\n\n c = np.array([[[6., 8., 6.]],\n [[48., 50., 48.]]])\n\n d = np.array([[[6., 16., 18.]],\n [[192., 250., 288.]]])\n\n e = np.array([[[18., 16., 6.]],\n [[288., 250., 192.]]])\n\n return a, b, c, d, e\n\n def linalg_stack_test(self):\n a = np.array([[[[2., 4., 10.]],\n [[14., 16., 18.]]],\n [[[6., 8., 6.]],\n [[48., 50., 48.]]]])\n\n b = np.array([[[2., 4., 10.]],\n [[14., 16., 18.]]])\n\n c = np.array([[[6., 8., 6.]],\n [[48., 50., 48.]]])\n\n d = np.array([[[6., 16., 18.]],\n [[192., 250., 288.]]])\n\n e = np.array([[[18., 16., 6.]],\n [[288., 250., 192.]]])\n\n return a, b, c, d, e\n\n\nclass UnitTest():\n def __init__(self):\n self.dataset_path = tf.keras.utils.get_file(\n \"auto-mpg.data\", \"http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data\")\n self.dataset_clf_path = tf.keras.utils.get_file(\n 'petfinder_mini.zip', 'http://storage.googleapis.com/download.tensorflow.org/data/petfinder-mini.zip',\n extract=True, cache_dir='.')\n self.jacobian_preset = JacobianFunction()\n self.function_preset = TestFunction()\n self.order_preset = OrderFunction()\n self.start_preset = GradientStartFunction()\n self.answer_preset = TestAnswer()\n self.linalg_preset = LinalgFunction()\n\n def data_preprocessing(self):\n def norm(x):\n return (x - train_stats['mean']) / train_stats['std']\n\n column_names = ['MPG', 'Cylinders', 'Displacement', 'Horsepower', 'Weight',\n 'Acceleration', 'Model Year', 'Origin']\n raw_dataset = pd.read_csv(self.dataset_path, names=column_names,\n na_values=\"?\", comment='\\t',\n sep=\" \", skipinitialspace=True)\n\n dataset = raw_dataset.copy()\n dataset = dataset.dropna()\n origin = dataset.pop('Origin')\n\n dataset['USA'] = (origin == 1) * 1.0\n dataset['Europe'] = (origin == 2) * 1.0\n dataset['Japan'] = (origin == 3) * 1.0\n\n train_dataset = dataset.sample(frac=0.8, random_state=0)\n test_dataset = dataset.drop(train_dataset.index)\n\n train_stats = train_dataset.describe()\n train_stats.pop(\"MPG\")\n train_stats = train_stats.transpose()\n\n normed_train_data = norm(train_dataset)\n normed_test_data = norm(test_dataset)\n train_labels = train_dataset.pop('MPG')\n\n X = Variable(np.array(normed_train_data.drop('MPG', axis=1)))\n y = (np.array(train_labels) - np.mean(np.array(train_dataset))) / np.std(np.array(train_dataset))\n y = Variable(np.array(y).reshape([-1, 1]))\n\n return X, y\n def data_preprocessing_clf(self):\n def norm(x):\n return (x - train_stats['mean']) / train_stats['std']\n\n column_names = ['MPG', 'Cylinders', 'Displacement', 'Horsepower', 'Weight',\n 'Acceleration', 'Model Year', 'Origin']\n raw_dataset = pd.read_csv('datasets/petfinder-mini/petfinder-mini.csv')\n # In the original dataset \"4\" indicates the pet was not adopted.\n raw_dataset['target'] = np.where(raw_dataset['AdoptionSpeed'] == 4, 0, 1)\n # Drop un-used columns.\n train = raw_dataset.drop(columns=['AdoptionSpeed', 'Description'])\n train_processing = pd.concat([pd.get_dummies(train.loc[:, train.apply(lambda x: x.dtype == 'object')]),\n train.loc[:, train.apply(lambda x: x.dtype != 'object')].apply(\n lambda x: (x - min(x)) / (max(x) - min(x)))],\n axis=1)\n\n X = train_processing.drop(['target'], axis=1).to_numpy()\n y = np.array(pd.get_dummies(train_processing.loc[:, 'target']))\n\n return X, y\n\n def data_preprocessing_rnn(self):\n num_data = 1000\n dtype = np.float64\n\n x = np.linspace(0, 2 * np.pi, num_data)\n noise_range = (-0.05, 0.05)\n noise = np.random.uniform(noise_range[0], noise_range[1], size=x.shape)\n y = np.sin(x) + noise\n y = y.astype(dtype)\n data = y[:-1][:, np.newaxis]\n label = y[1:][:, np.newaxis]\n\n return data, label\n\n return data, label\n\n def data_preprocessing_cnn(self):\n (train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()\n train_images = train_images.reshape((60000, 28, 28, 1))\n test_images = test_images.reshape((10000, 28, 28, 1))\n # 픽셀 값을 0~1 사이로 정규화합니다.\n train_images, test_images = train_images / 255.0, test_images / 255.0\n\n train_images = train_images.reshape(train_images.shape[0],\n train_images.shape[3],\n train_images.shape[1],\n train_images.shape[2])\n\n test_images = test_images.reshape(test_images.shape[0],\n test_images.shape[3],\n test_images.shape[1],\n test_images.shape[2])\n\n return train_images, train_labels, test_images, test_labels\n\n def answer_correction(self, function, answer, pred, tor):\n answer = [np.abs(i.reshape(j.shape)) for i,j in zip(answer, pred)]\n pred = [np.abs(x) for x in pred]\n loss = [np.abs(i - j) for i,j in zip(answer, pred)]\n loss = np.array([i.sum() for i in loss])\n if np.all(loss < tor):\n print(function, ' : ok')\n else :\n print(function, ' : Failed')\n print('answer :', answer)\n print('pred :', pred)\n print('error :', loss)\n\n def preset_test(self, tor=0.01, function=None, x=None, y=None):\n try:\n if x is None:\n x = Variable(np.array(1.0))\n if y is None:\n y = Variable(np.array(1.0))\n function_list = [i for i in self.function_preset.__dir__() if not i.startswith('_')]\n for function in function_list:\n current_function = self.function_preset.__getattribute__(function)\n with GradientTape() as tape:\n z = current_function(x, y)\n tape.CalcGradient()\n pred = (x.grad.data, y.grad.data)\n answer = self.answer_preset.__getattribute__(function)()\n self.answer_correction(function, answer, pred, tor)\n tape.resetgrads()\n except Exception as e:\n print(f'preset_function_test is failed :', e)\n\n def high_order_test(self, orders=2):\n #try:\n x = Variable(np.array(2.0))\n y = Variable(np.array(2.0))\n order_function = self.order_preset.high_order_function\n tape_dict = dict()\n with GradientTape() as tape:\n f = order_function(x, y)\n tape_dict[0] = tape\n for order in range(orders):\n with GradientTape() as tape_1:\n tape_dict[order].CalcGradient()\n tape_dict[order + 1] = tape_1\n pred = (x.grad.data, y.grad.data)\n tape_dict[order].resetgrads()\n answer = self.answer_preset.high_order_function(order)\n answer = [np.array(i) for i in answer]\n self.answer_correction(f'high_order_test_{order}', answer, pred, 0.01)\n tape.resetgrads()\n #except Exception as e:\n # print(f'high_order_test_{order} is failed :', e)\n\n def matrix_test(self, orders=3):\n try:\n X = Variable(np.array([[1., 2.], [4., 5.]]))\n matrix_function = self.order_preset.matrix_order_function\n tape_dict = dict()\n with GradientTape() as tape:\n result = matrix_function(X)\n tape_dict[0] = tape\n for order in range(orders):\n with GradientTape() as tape_1:\n tape_dict[order].CalcGradient()\n tape_dict[order + 1] = tape_1\n pred = X.grad.data\n tape_dict[order].resetgrads()\n answer = self.answer_preset.matrix_order_function(order)\n self.answer_correction(f'matrix_order_test_{order}',\n answer,\n pred,\n 0.01)\n except Exception as e:\n print(f'matrix_order_test_{order} is failed :', e)\n\n def jacobian_test(self, tor=0.01, x=None, v=None, k=None, target=None):\n try:\n if x is None:\n x = Variable(np.array([[1., 2.], [4., 5.]]))\n if v is None:\n v = Variable(np.array([[4., 5.], [6., 7.]]))\n if k is None:\n k = Variable(np.array([[1., 3.], [4., 6.]]))\n jacobian_function = self.jacobian_preset\n function_list = [i for i in jacobian_function.__dir__() if not i.startswith('_')]\n for function in function_list:\n current_function = jacobian_function.__getattribute__(function)\n tape = current_function(x, v, k)\n if target is not None:\n pred = (tape.jacobian(target=target, var=x, var_return='numpy'),\n tape.jacobian(target=target, var=v, var_return='numpy'),\n tape.jacobian(target=target, var=k, var_return='numpy'))\n else:\n pred = (tape.jacobian(var=x, var_return='numpy'),\n tape.jacobian(var=v, var_return='numpy'),\n tape.jacobian(var=k, var_return='numpy'))\n answer = self.answer_preset.__getattribute__(function)()\n self.answer_correction(f'jacobian_{function}', answer, pred, tor)\n tape.resetgrads()\n except Exception as e:\n print(f'jacobian_test is failed :', e)\n\n def gradient_start_index_test(self, tor=0.01, x=None, v=None, k=None):\n try:\n if x is None:\n x = Variable(np.array([[1., 2.], [4., 5.]]))\n if v is None:\n v = Variable(np.array([[4., 5.], [6., 7.]]))\n if k is None:\n k = Variable(np.array([[1., 3.], [4., 6.]]))\n start_index_function = self.start_preset\n function_list = [i for i in start_index_function.__dir__() if not i.startswith('_')]\n for function in function_list:\n current_function = start_index_function.__getattribute__(function)\n pred = current_function(x, v, k)\n answer = self.answer_preset.__getattribute__(function)()\n self.answer_correction(function, answer, pred, tor)\n except Exception as e:\n print(f'gradient_{function} is failed :', e)\n\n def linalg_test(self, tor=0.01):\n try:\n linalg_function = self.linalg_preset\n function_list = [i for i in linalg_function.__dir__() if not i.startswith('_')]\n for function in function_list:\n current_function = linalg_function.__getattribute__(function)\n preds = current_function()\n answers = self.answer_preset.__getattribute__(function)()\n self.answer_correction(function, answers, preds, tor)\n except Exception as e:\n print(f'linalg_{function} is failed :', e)\n\n def modeling_test(self, tor=1e-7, end_iter=4):\n try:\n X, y = self.data_preprocessing()\n\n lr = 0.1\n loss_flow = []\n loss_iter = 0\n\n start_time = time.time()\n model = Models(100, 1)\n optimizers = optimizer.Adam()\n optimizers.setup(model)\n for i in range(10000):\n with GradientTape() as tape:\n y_pred = model(X)\n\n loss = f.loss.mean_squared_error(y, y_pred)\n\n tape.CalcGradient()\n\n optimizers.update()\n\n if i % 1000 == 0:\n loss_flow.append(loss.data)\n if (loss_iter > end_iter):\n if (abs(loss_flow[loss_iter - 1]) - (\n abs(loss_flow[loss_iter]))) < tor:\n print('loss_value :', [float(i) for i in loss_flow])\n print('model is under local minima, Attempt to retry..')\n self.modeling_test()\n break\n else:\n print('loss_value :', [float(i) for i in loss_flow])\n print('model training test : ok')\n break\n loss_iter += 1\n except Exception as e:\n print(f'model_training test is failed : {e}')\n\n def modeling_test_clf(self, tor=1e-7, end_iter=4):\n try:\n X, y = self.data_preprocessing_clf()\n\n lr = 0.001\n hidden_size = 200\n out_size = 2\n batch_size = 50\n loss_flow = []\n loss_iter = 0\n\n X = Variable(np.array(X))\n y = Variable(y)\n\n\n start_time = time.time()\n model = clf_Models(hidden_size, out_size)\n optimizers = optimizer.Adam(lr)\n optimizers.setup(model)\n for i in range(10000):\n dataset = DataSet(X, y)\n dataset.batch_setup(batch_size)\n for j in range(np.ceil((len(dataset) / batch_size)).astype('int')):\n X_set, y_set = next(dataset)\n\n with GradientTape() as tape:\n y_pred = model(X_set)\n loss = f.loss.categorical_crossentropy(y_set, y_pred)\n tape.CalcGradient()\n optimizers.update()\n\n loss_flow.append(loss.data)\n if (loss_iter > end_iter):\n if (abs(loss_flow[loss_iter - 1]) - (\n abs(loss_flow[loss_iter]))) < tor:\n print('loss_value :', [float(i) for i in loss_flow])\n print('model is under local minima, Attempt to retry..')\n self.modeling_test_clf()\n break\n else:\n print('loss_value :', [float(i) for i in loss_flow])\n print('clf model training test : ok')\n break\n loss_iter += 1\n except Exception as e:\n print(f'clf model_training test is failed : {e}')\n\n def modeling_test_rnn(self, tor=1e-7, end_iter=4):\n try:\n X, y = self.data_preprocessing_rnn()\n\n step = 10\n lr = 0.001\n loss_flow = []\n loss_iter = 0\n\n start_time = time.time()\n model = SimpleRNN(100, 1)\n optimizers = optimizer.SGD()\n optimizers.setup(model)\n for i in range(10000):\n for teps in range(len(X) - step - 1):\n with GradientTape() as tape:\n y_pred = model(X[teps: teps + step])\n loss = f.loss.mean_squared_error(y_pred, y[(teps + 1) + step])\n\n tape.CalcGradient()\n optimizers.update()\n\n loss_flow.append(loss.data)\n if (loss_iter > end_iter):\n if (abs(loss_flow[loss_iter - 1]) - (\n abs(loss_flow[loss_iter]))) < tor:\n print('loss_value :', [float(i) for i in loss_flow])\n print('model is under local minima, Attempt to retry..')\n self.modeling_test_rnn()\n break\n else:\n print('loss_value :', [float(i) for i in loss_flow])\n y_pred = list()\n for teps in range(int(len(X) - step)):\n y_pred.append(model(X[teps: teps + step]).data)\n plt.plot(np.squeeze(np.squeeze(y_pred)))\n plt.plot(np.squeeze(X))\n print('RNN model training test : ok')\n break\n loss_iter += 1\n except Exception as e:\n print(f'RNN model_training test is failed : {e}')\n\n def modeling_test_cnn(self, tor=1e-7, end_iter=2):\n try:\n X_train, y_train, X_test, y_test = self.data_preprocessing_cnn()\n\n lr = 0.001\n loss_flow = []\n loss_iter = 0\n batch_size = 100\n\n start_time = time.time()\n model = CNN()\n optimizers = optimizer.Adam(lr)\n optimizers.setup(model)\n for i in range(10000):\n for j in range(np.ceil((len(X_train) / batch_size)).astype('int')):\n train = X_train[j * batch_size: (j + 1) * batch_size]\n label = y_train[j * batch_size: (j + 1) * batch_size]\n\n with GradientTape() as tape:\n y_pred = model(train)\n loss = f.loss.softmax_cross_entropy(y_pred, label)\n\n tape.CalcGradient()\n optimizers.update()\n print(i)\n loss_flow.append(loss.data)\n if (loss_iter > end_iter):\n if (abs(loss_flow[loss_iter - 1]) - (\n abs(loss_flow[loss_iter]))) < tor:\n print('loss_value :', [float(i) for i in loss_flow])\n print('model is under local minima, Attempt to retry..')\n self.modeling_test_cnn()\n break\n else:\n print('loss_value :', [float(i) for i in loss_flow])\n test_pred = model(X_test)\n print('test셋 정확도 : ', accuracy_score(np.argmax(test_pred.data, axis=-1), y_test))\n print('혼동행렬')\n print(confusion_matrix(np.argmax(test_pred.data, axis=-1), y_test))\n print('CNN model training test : ok')\n break\n loss_iter += 1\n except Exception as e:\n print(f'CNN model_training test is failed : {e}')\n\n def start_testing(self):\n self.high_order_test()\n self.matrix_test()\n self.jacobian_test()\n self.gradient_start_index_test()\n self.linalg_test()\n self.modeling_test()\n self.modeling_test_clf()\n self.modeling_test_rnn()\n self.modeling_test_cnn()", "repo_name": "dlanjrjs/nariflow", "sub_path": "nariflow/utils/unit_test.py", "file_name": "unit_test.py", "file_ext": "py", "file_size_in_byte": 31448, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "models.Model", "line_number": 25, "usage_type": "name"}, {"api_name": "models.Model", "line_number": 40, "usage_type": "name"}, {"api_name": "models.Model", "line_number": 57, "usage_type": "name"}, {"api_name": "models.Model", "line_number": 69, "usage_type": "name"}, {"api_name": "core.elementary_function.matmul", "line_number": 114, "usage_type": "call"}, {"api_name": "core.elementary_function", "line_number": 114, "usage_type": "name"}, {"api_name": "core.shape_function.transpose", "line_number": 114, "usage_type": "call"}, {"api_name": "core.shape_function", "line_number": 114, "usage_type": "name"}, {"api_name": "core.elementary_function.matmul", "line_number": 115, "usage_type": "call"}, {"api_name": "core.elementary_function", "line_number": 115, "usage_type": "name"}, {"api_name": "core.elementary_function.matmul", "line_number": 120, "usage_type": "call"}, {"api_name": "core.elementary_function", "line_number": 120, "usage_type": "name"}, {"api_name": "core.shape_function.transpose", "line_number": 120, "usage_type": "call"}, {"api_name": "core.shape_function", "line_number": 120, "usage_type": "name"}, {"api_name": "core.elementary_function.matmul", "line_number": 121, "usage_type": "call"}, {"api_name": "core.elementary_function", "line_number": 121, "usage_type": "name"}, {"api_name": "core.elementary_function.flowsum", "line_number": 122, "usage_type": "call"}, {"api_name": "core.elementary_function", "line_number": 122, "usage_type": "name"}, {"api_name": "core.elementary_function.matmul", "line_number": 127, "usage_type": "call"}, {"api_name": "core.elementary_function", "line_number": 127, "usage_type": "name"}, {"api_name": "core.shape_function.transpose", "line_number": 127, "usage_type": "call"}, {"api_name": "core.shape_function", "line_number": 127, "usage_type": "name"}, {"api_name": "core.elementary_function.matmul", "line_number": 128, "usage_type": "call"}, {"api_name": "core.elementary_function", "line_number": 128, "usage_type": "name"}, {"api_name": "core.elementary_function.matmul", "line_number": 134, "usage_type": "call"}, {"api_name": "core.elementary_function", "line_number": 134, "usage_type": "name"}, {"api_name": "core.shape_function.transpose", "line_number": 134, "usage_type": "call"}, {"api_name": "core.shape_function", "line_number": 134, "usage_type": "name"}, {"api_name": "core.elementary_function.matmul", "line_number": 135, "usage_type": "call"}, {"api_name": "core.elementary_function", "line_number": 135, "usage_type": "name"}, {"api_name": "core.elementary_function.matmul", "line_number": 141, "usage_type": "call"}, {"api_name": "core.elementary_function", "line_number": 141, "usage_type": "name"}, {"api_name": "core.shape_function.transpose", "line_number": 141, "usage_type": "call"}, {"api_name": "core.shape_function", "line_number": 141, "usage_type": "name"}, {"api_name": "core.elementary_function.matmul", "line_number": 142, "usage_type": "call"}, {"api_name": "core.elementary_function", "line_number": 142, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 151, "usage_type": "call"}, {"api_name": "core.elementary_function.matmul", "line_number": 154, "usage_type": "call"}, {"api_name": "core.elementary_function", "line_number": 154, "usage_type": "name"}, {"api_name": "core.shape_function.transpose", "line_number": 154, "usage_type": "call"}, {"api_name": "core.shape_function", "line_number": 154, "usage_type": "name"}, {"api_name": "core.elementary_function.matmul", "line_number": 155, "usage_type": "call"}, {"api_name": "core.elementary_function", "line_number": 155, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 164, "usage_type": "call"}, {"api_name": "core.elementary_function.matmul", "line_number": 167, "usage_type": "call"}, {"api_name": "core.elementary_function", "line_number": 167, "usage_type": "name"}, {"api_name": "core.shape_function.transpose", "line_number": 167, "usage_type": "call"}, {"api_name": "core.shape_function", "line_number": 167, "usage_type": "name"}, {"api_name": "core.elementary_function.matmul", "line_number": 168, "usage_type": "call"}, {"api_name": "core.elementary_function", "line_number": 168, "usage_type": "name"}, {"api_name": "core.elementary_function.stop_gradient", "line_number": 168, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 178, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 190, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 191, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 192, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 236, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 242, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 248, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 255, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 255, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 256, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 256, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 257, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 257, "usage_type": "call"}, {"api_name": "tensorflow.GradientTape", "line_number": 259, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 260, "usage_type": "call"}, {"api_name": "tensorflow.transpose", "line_number": 260, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 261, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 268, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 268, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 269, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 269, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 270, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 270, "usage_type": "call"}, {"api_name": "tensorflow.GradientTape", "line_number": 273, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 274, "usage_type": "call"}, {"api_name": "tensorflow.transpose", "line_number": 274, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 275, "usage_type": "call"}, {"api_name": "tensorflow.math.reduce_sum", "line_number": 276, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 276, "usage_type": "attribute"}, {"api_name": "tensorflow.Variable", "line_number": 284, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 284, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 285, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 285, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 286, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 286, "usage_type": "call"}, {"api_name": "tensorflow.GradientTape", "line_number": 289, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 290, "usage_type": "call"}, {"api_name": "tensorflow.transpose", "line_number": 290, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 291, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 300, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 300, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 301, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 301, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 302, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 302, "usage_type": "call"}, {"api_name": "tensorflow.GradientTape", "line_number": 305, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 306, "usage_type": "call"}, {"api_name": "tensorflow.transpose", "line_number": 306, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 307, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 316, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 316, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 317, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 317, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 318, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 318, "usage_type": "call"}, {"api_name": "tensorflow.GradientTape", "line_number": 321, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 322, "usage_type": "call"}, {"api_name": "tensorflow.transpose", "line_number": 322, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 323, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 331, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 331, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 332, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 332, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 333, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 333, "usage_type": "call"}, {"api_name": "tensorflow.GradientTape", "line_number": 335, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 336, "usage_type": "call"}, {"api_name": "tensorflow.transpose", "line_number": 336, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 337, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 345, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 345, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 346, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 346, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 347, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 347, "usage_type": "call"}, {"api_name": "tensorflow.GradientTape", "line_number": 349, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 350, "usage_type": "call"}, {"api_name": "tensorflow.transpose", "line_number": 350, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 351, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 360, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 360, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 361, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 361, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 362, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 362, "usage_type": "call"}, {"api_name": "tensorflow.GradientTape", "line_number": 364, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 365, "usage_type": "call"}, {"api_name": "tensorflow.transpose", "line_number": 365, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 366, "usage_type": "call"}, {"api_name": "tensorflow.stop_gradient", "line_number": 366, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 376, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 381, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 384, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 387, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 390, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 396, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 401, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 404, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 407, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 410, "usage_type": "call"}, {"api_name": "tensorflow.keras.utils.get_file", "line_number": 418, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 418, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.utils.get_file", "line_number": 420, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 420, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 436, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 459, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 460, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 460, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 460, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 461, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 470, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 472, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 475, "usage_type": "call"}, {"api_name": "pandas.get_dummies", "line_number": 475, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 481, "usage_type": "call"}, {"api_name": "pandas.get_dummies", "line_number": 481, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 487, "usage_type": "attribute"}, {"api_name": "numpy.linspace", "line_number": 489, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 489, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 491, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 491, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 492, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 494, "usage_type": "attribute"}, {"api_name": "numpy.newaxis", "line_number": 495, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.datasets.mnist.load_data", "line_number": 502, "usage_type": "call"}, {"api_name": "tensorflow.keras.datasets.mnist", "line_number": 502, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.datasets", "line_number": 502, "usage_type": "name"}, {"api_name": "numpy.abs", "line_number": 521, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 522, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 523, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 524, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 525, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 536, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 538, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 554, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 555, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 568, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 576, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 599, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 601, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 603, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 626, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 628, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 630, "usage_type": "call"}, {"api_name": "time.time", "line_number": 661, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 703, "usage_type": "call"}, {"api_name": "time.time", "line_number": 707, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 714, "usage_type": "call"}, {"api_name": "time.time", "line_number": 748, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 774, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 774, "usage_type": "name"}, {"api_name": "numpy.squeeze", "line_number": 774, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 775, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 775, "usage_type": "name"}, {"api_name": "numpy.squeeze", "line_number": 775, "usage_type": "call"}, {"api_name": "time.time", "line_number": 791, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 796, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 818, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 818, "usage_type": "call"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 820, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 820, "usage_type": "call"}]} +{"seq_id": "41332877949", "text": "import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\noptions_1 = Options()\noptions_1.headless = True\n\ndriver_chrome = webdriver.Chrome(options=options_1)\n#url = \"https://www.google.co.in/\"\n#driver_chrome.get(url)\n\nclass Program:\n def __init__(self, url):\n self.url=url\n driver_chrome.get(self.url)\n def get_title(self):\n print(driver_chrome.title)\n def get_url(self):\n print(driver_chrome.current_url)\n\nurl_1 = \"https://www.guvi.in\"\nprog = Program(url_1)\nprog.get_title()\nprog.get_url()\ndriver_chrome.quit()", "repo_name": "Tharique007/python-preactice-Basics", "sub_path": "PracticeI/Selenium_1.py", "file_name": "Selenium_1.py", "file_ext": "py", "file_size_in_byte": 593, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "selenium.webdriver.chrome.options.Options", "line_number": 5, "usage_type": "call"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 8, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 8, "usage_type": "name"}]} +{"seq_id": "30617618025", "text": "import argparse\nimport pathlib\nimport json\n\nparser = argparse.ArgumentParser(description=\"get git branch\")\n\n\nparser.add_argument(dest='branch_name',\n metavar='branch_name',\n help=\"github branch name\")\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n branch_name = args.branch_name\n params_directory = pathlib.Path(__file__).parent.parent / \"cloudformation\" / \"cfn-config\"\n params_json_file = params_directory / \"feature-branch-params.json\"\n parameters = json.loads(params_json_file.read_text())\n parameters_no_branch = [param for param in parameters if param[\"ParameterKey\"] != \"CurrentBranch\"]\n parameters_no_branch.append({\n \"ParameterKey\": \"CurrentBranch\",\n \"ParameterValue\": branch_name\n })\n params_deploy = params_directory / \"feature-branch-params-deploy.json\"\n with open(params_deploy, \"w+\") as fp:\n fp.write(json.dumps(parameters_no_branch))\n", "repo_name": "robertointerface/payment-system", "sub_path": "utils/add_branch_name_to_cloudformation_params.py", "file_name": "add_branch_name_to_cloudformation_params.py", "file_ext": "py", "file_size_in_byte": 947, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 5, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 15, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 17, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "4977786277", "text": "from typing import Optional, Tuple\n\nfrom sqlalchemy import update\nfrom sqlalchemy.engine import Result\nfrom sqlalchemy.orm import Session\n\nfrom api.database.models import DbContact\nfrom api.schemas.contacts_schema import ContactsCreate\n\n\nclass ContactService:\n\n @classmethod\n def insert_contact_by_user_id(\n cls,\n contact: ContactsCreate,\n user_id: int,\n db: Session\n ) -> Tuple[Optional[DbContact], str]:\n\n try:\n\n results = DbContact(**contact.dict())\n\n if not results:\n db.rollback()\n raise ConnectionError('Erro Ao Salvar Contato. Tente Novamente Mais Tarde')\n\n db.add(results)\n\n db.commit()\n\n db.refresh(results)\n\n return results, 'Contato Adicionado Com Sucesso!'\n\n except Exception as e:\n return None, str(e.detail)\n\n @classmethod\n def select_contact_by_user_id(\n cls,\n db: Session,\n user_id: int,\n ) -> Tuple[Optional[DbContact], str]:\n\n try:\n\n results = db.query(DbContact).filter(DbContact.FK_UserID == user_id).first()\n\n if not results:\n db.rollback()\n return None, 'Contato Não Localizado. Tente Novamente Mais Tarde'\n\n return results, 'Contato Localizado Com Sucesso!'\n\n except Exception as e:\n return None, str(e.detail)\n\n @classmethod\n def update_contact_by_user_id(\n cls,\n contact: ContactsCreate,\n user_id: int,\n db: Session\n ) -> Tuple[Optional[Result], str]:\n\n try:\n\n results = db.execute(\n update(DbContact)\n .where(DbContact.FK_UserID == user_id)\n .values(**contact.dict()))\n\n if not results:\n db.rollback()\n return None, 'Erro ao Atualizar. Tente Novamente Mais Tarde!'\n\n return results, 'Atualizado Com Sucesso!'\n\n except Exception as e:\n return None, str(e.detail)\n", "repo_name": "JefersonMelo/Projeto_Integrador_Coffee_Gourmet", "sub_path": "api/services/contacts_service.py", "file_name": "contacts_service.py", "file_ext": "py", "file_size_in_byte": 2079, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "api.schemas.contacts_schema.ContactsCreate", "line_number": 16, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 18, "usage_type": "name"}, {"api_name": "api.database.models.DbContact", "line_number": 23, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 19, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 19, "usage_type": "name"}, {"api_name": "api.database.models.DbContact", "line_number": 19, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 43, "usage_type": "name"}, {"api_name": "api.database.models.DbContact", "line_number": 49, "usage_type": "argument"}, {"api_name": "api.database.models.DbContact.FK_UserID", "line_number": 49, "usage_type": "attribute"}, {"api_name": "typing.Tuple", "line_number": 45, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 45, "usage_type": "name"}, {"api_name": "api.database.models.DbContact", "line_number": 45, "usage_type": "name"}, {"api_name": "api.schemas.contacts_schema.ContactsCreate", "line_number": 63, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 65, "usage_type": "name"}, {"api_name": "sqlalchemy.update", "line_number": 71, "usage_type": "call"}, {"api_name": "api.database.models.DbContact", "line_number": 71, "usage_type": "argument"}, {"api_name": "api.database.models.DbContact.FK_UserID", "line_number": 72, "usage_type": "attribute"}, {"api_name": "api.database.models.DbContact", "line_number": 72, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 66, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 66, "usage_type": "name"}, {"api_name": "sqlalchemy.engine.Result", "line_number": 66, "usage_type": "name"}]} +{"seq_id": "1675224767", "text": "#!/usr/bin/env python3\nfrom troposphere import Template, Ref, GetAtt, Export, Output, Sub\nfrom troposphere import ec2 as t_ec2\nfrom pawslib.ec2 import split_net_across_zones\nfrom pawslib.var import alphanum\n\n\ndef multiaz_subnets(\n name_prefix: str,\n cidr_block: str,\n region: str,\n vpc: object = None,\n vpc_id: str = None,\n no_of_subnets: int = 4,\n network_acl: object = None,\n network_acl_id: str = None,\n route_table: object = None,\n route_table_id: str = None,\n) -> list:\n \"\"\"Split given CIDR block into subnets over multiple AZs\n\n Either `vpc` or both `vpc_id` and `region` are required.\n\n If a network ACL or route table are passed as parameters, they\n will be associated with the subnets.\n\n `vpc`, `network_acl` and `route_table` are expected to be\n Troposphere resource objects which can be passed to Ref and GetAtt\n functions. As an alternative, `vpc_id`, `region`, `network_acl_id`\n `route_table_id` can be passed directly. If both resource and *_id\n are specified, the *_id will take precedence.\n\n Returns a list of Troposphere resources that describes the subnets\n and can be attached to a Template object.\n\n Returned subnet objects have the following keys set in their\n Metadata attribute:\n az: full availability zone name (\"eu-west-1a\")\n az_index: uppercase AZ, without the region part (\"A\")\n suffix: the suffix that was added to the name to form a unique\n resource title. Probably a single digit.\n\n Args:\n name_prefix (str): Prefix each resource with this string. Use to\n assure unique name for the resource in the calling Template\n cidr_block (str): IP range to split into subnets\n region (str): AWS region\n vpc (object, optional): VPC Troposphere resource. One of vpc or\n vpc_id is required. Defaults to None.\n vpc_id (str, optional): VPC ID. One of vpc or vpc_id is\n required. Defaults to None.\n no_of_subnets (int, optional): Create this many subnets. must\n be a power of 2. Defaults to 4.\n network_acl (object, optional): Network ACL Troposphere\n resource. Defaults to None.\n network_acl_id (str, optional): Network ACL ID. Defaults to\n None.\n route_table (object, optional): Route table resource.\n Defaults to None.\n route_table_id (str, optional): Route table ID. Defaults to\n None.\n\n Raises:\n ValueError: If neither vpc nor vpc_id were specified.\n\n Returns:\n list: Troposphere resources to be added to Template.\n\n \"\"\"\n if vpc is None and vpc_id is None:\n raise ValueError(\"One of vpc or vpc_id must be specified\")\n if vpc_id is None:\n vpc_id = Ref(vpc)\n # Resource names only accept alphanumeric\n prefix = alphanum(name_prefix).lower().capitalize()\n net_split = split_net_across_zones(cidr_block, region, no_of_subnets)\n resources = list()\n for index, net_segment in enumerate(net_split):\n # set subnet\n az_index = net_segment[\"az\"][-1:].upper()\n subnet = t_ec2.Subnet(\n title=f\"{prefix}{index+1}\",\n AvailabilityZone=net_segment[\"az\"],\n CidrBlock=net_segment[\"cidr\"],\n VpcId=vpc_id,\n Tags=[{\"Key\": \"Name\", \"Value\": f\"{name_prefix} {az_index}\"}],\n )\n subnet.Metadata = {}\n subnet.Metadata[\"az\"] = net_segment[\"az\"].lower()\n subnet.Metadata[\"az_index\"] = az_index\n subnet.Metadata[\"suffix\"] = index + 1\n resources.append(subnet)\n # associate network ACL with subnet\n if network_acl_id is None and network_acl is not None:\n network_acl_id = Ref(network_acl)\n if network_acl_id is not None:\n resources.append(\n t_ec2.SubnetNetworkAclAssociation(\n title=f\"{subnet.title}NaclAssociation\",\n SubnetId=Ref(subnet),\n NetworkAclId=network_acl_id,\n )\n )\n if route_table_id is None and route_table is not None:\n route_table_id = Ref(route_table)\n if route_table_id is not None:\n resources.append(\n t_ec2.SubnetRouteTableAssociation(\n title=f\"{subnet.title}RouteAssociation\",\n SubnetId=Ref(subnet),\n RouteTableId=route_table_id,\n )\n )\n return resources\n\n\nclass VpcTemplate:\n \"\"\"Generate a CloudFormation Template that creates a VPC\n\n It can create the VPC, connect it to the internet via an internet\n gateway, set up NAT gateways and public and private subnets with the\n corresponding route tables and network ACLs.\n\n Exports:\n - VPC ID: stackname-vpc-id\n \"\"\"\n\n def __init__(\n self,\n region: str,\n cidr_block: str,\n name: str = \"VPC\",\n internet_access_enabled: bool = True,\n internal_networks: list = [],\n ):\n \"\"\"Create VPC, internet gateway, route tables and network ACLs\n\n Args:\n region (str): Region to use when setting up the VPC. The\n maximum number of subnets set up depends on the number\n of availability zones present in the region.\n cidr_block (str): IP range used by the VPC\n name (str, optional): VPC name. Defaults to \"VPC\".\n internet_access_enabled (bool, optional): If False, internet\n gateway will not be set up. Public network ACLs and\n route tables will still be created.\n Defaults to True.\n internal_networks (list, optional): IP ranges for private\n networks that this VPC will be connected to. They will\n be added to network ACLs. Defaults to [].\n \"\"\"\n self.name = name\n self.region = region\n self.cidr_block = cidr_block\n self.internal_networks = internal_networks\n self.internet_access_enabled = internet_access_enabled\n self.public_subnets = []\n # Gateway subnets are public subnets hosting exit points like\n # NAT Gateway and VPC Endpoint interfaces\n self.gateway_subnets = []\n self.public_route_table = None\n self.natted_route_tables = []\n self.nat_gateways = []\n self._t = Template() # Template\n self._r = dict() # Resources\n self._o = dict() # Outputs\n self._r[\"Vpc\"] = t_ec2.VPC(\n title=f\"{self.name}Vpc\",\n CidrBlock=self.cidr_block,\n EnableDnsHostnames=True,\n EnableDnsSupport=True,\n Tags=[{\"Key\": \"Name\", \"Value\": self.name}],\n )\n self.vpc = self._r[\"Vpc\"]\n self._o[\"VpcId\"] = Output(\n title=\"VpcId\",\n Value=Ref(self.vpc),\n Export=Export(Sub(\"${AWS::StackName}-vpc-id\")),\n )\n if internet_access_enabled:\n # Create Internet Gateway\n title = \"Igw\"\n self._r[title] = t_ec2.InternetGateway(\n title=title,\n Tags=[{\"Key\": \"Name\", \"Value\": f\"{self.name}-igw\"}],\n )\n self._r[\"igw_attachment\"] = t_ec2.VPCGatewayAttachment(\n title=\"IgwAttachment\",\n VpcId=Ref(self.vpc),\n InternetGatewayId=Ref(self._r[\"Igw\"]),\n )\n # Public routing table\n self._r[\"PubRouteTable\"] = t_ec2.RouteTable(\n title=\"PubRouteTable\",\n VpcId=Ref(self.vpc),\n Tags=[{\"Key\": \"Name\", \"Value\": \"Public\"}],\n )\n self.public_route_table = self._r[\"PubRouteTable\"]\n if internet_access_enabled:\n self._r[\"pub_rtt_rt_pub\"] = t_ec2.Route(\n title=\"PubRoute\",\n RouteTableId=Ref(self._r[\"PubRouteTable\"]),\n DestinationCidrBlock=\"0.0.0.0/0\",\n GatewayId=Ref(self._r[\"Igw\"]),\n )\n # Network ACL for public subnets\n self._r[\"PubNacl\"] = t_ec2.NetworkAcl(\n title=\"PubNacl\",\n VpcId=Ref(self.vpc),\n Tags=[{\"Key\": \"Name\", \"Value\": \"Public\"}],\n )\n self.public_nacl = self._r[\"PubNacl\"]\n self._r[\"pub_nacl_out_all\"] = t_ec2.NetworkAclEntry(\n title=\"PubNaclOutAll\",\n NetworkAclId=Ref(self.public_nacl),\n Egress=True,\n RuleNumber=500,\n CidrBlock=\"0.0.0.0/0\",\n Protocol=-1,\n RuleAction=\"allow\",\n )\n self._r[\"pub_nacl_in_icmp\"] = t_ec2.NetworkAclEntry(\n title=\"PubNaclInIcmp\",\n NetworkAclId=Ref(self.public_nacl),\n Egress=False,\n RuleNumber=99,\n CidrBlock=\"0.0.0.0/0\",\n Protocol=1,\n Icmp=t_ec2.ICMP(Code=-1, Type=-1),\n RuleAction=\"allow\",\n )\n self._r[\"pub_nacl_in_vpc\"] = t_ec2.NetworkAclEntry(\n title=\"PubNaclInVpc\",\n NetworkAclId=Ref(self.public_nacl),\n Egress=False,\n RuleNumber=100,\n CidrBlock=GetAtt(self.vpc, \"CidrBlock\"),\n Protocol=-1,\n RuleAction=\"allow\",\n )\n for index, cidr_block in enumerate(self.internal_networks):\n self._r[f\"pub_nacl_in_internal_{index}\"] = t_ec2.NetworkAclEntry(\n title=f\"PubNaclInInternal{index}\",\n NetworkAclId=Ref(self.public_nacl),\n Egress=False,\n RuleNumber=101 + index,\n CidrBlock=cidr_block,\n Protocol=-1,\n RuleAction=\"allow\",\n )\n self._r[\"pub_nacl_in_ssh\"] = t_ec2.NetworkAclEntry(\n title=\"PubNaclInSsh\",\n NetworkAclId=Ref(self.public_nacl),\n Egress=False,\n RuleNumber=210,\n CidrBlock=\"0.0.0.0/0\",\n Protocol=6,\n PortRange=t_ec2.PortRange(From=22, To=22),\n RuleAction=\"allow\",\n )\n self._r[\"pub_nacl_in_http\"] = t_ec2.NetworkAclEntry(\n title=\"PubNaclInHttp\",\n NetworkAclId=Ref(self.public_nacl),\n Egress=False,\n RuleNumber=220,\n CidrBlock=\"0.0.0.0/0\",\n Protocol=6,\n PortRange=t_ec2.PortRange(From=80, To=80),\n RuleAction=\"allow\",\n )\n self._r[\"pub_nacl_in_https\"] = t_ec2.NetworkAclEntry(\n title=\"PubNaclInHttps\",\n NetworkAclId=Ref(self.public_nacl),\n Egress=False,\n RuleNumber=221,\n CidrBlock=\"0.0.0.0/0\",\n Protocol=6,\n PortRange=t_ec2.PortRange(From=443, To=443),\n RuleAction=\"allow\",\n )\n self._r[\"pub_nacl_in_nat_tcp\"] = t_ec2.NetworkAclEntry(\n title=\"PubNaclInNatTcp\",\n NetworkAclId=Ref(self.public_nacl),\n Egress=False,\n RuleNumber=500,\n CidrBlock=\"0.0.0.0/0\",\n Protocol=6,\n PortRange=t_ec2.PortRange(From=1024, To=65535),\n RuleAction=\"allow\",\n )\n self._r[\"pub_nacl_in_nat_udp\"] = t_ec2.NetworkAclEntry(\n title=\"PubNaclInNatUdp\",\n NetworkAclId=Ref(self.public_nacl),\n Egress=False,\n RuleNumber=501,\n CidrBlock=\"0.0.0.0/0\",\n Protocol=17,\n PortRange=t_ec2.PortRange(From=1024, To=65535),\n RuleAction=\"allow\",\n )\n # Network ACL for private subnets\n self._r[\"InternalNacl\"] = t_ec2.NetworkAcl(\n title=\"InternalNacl\",\n VpcId=Ref(self.vpc),\n Tags=[{\"Key\": \"Name\", \"Value\": \"Private\"}],\n )\n self.internal_nacl = self._r[\"InternalNacl\"]\n self._r[\"internal_nacl_out_all\"] = t_ec2.NetworkAclEntry(\n title=\"InternalNaclOutAll\",\n NetworkAclId=Ref(self.internal_nacl),\n Egress=True,\n RuleNumber=500,\n CidrBlock=\"0.0.0.0/0\",\n Protocol=-1,\n RuleAction=\"allow\",\n )\n self._r[\"internal_nacl_in_icmp\"] = t_ec2.NetworkAclEntry(\n title=\"InternalNaclInIcmp\",\n NetworkAclId=Ref(self.internal_nacl),\n Egress=False,\n RuleNumber=99,\n CidrBlock=\"0.0.0.0/0\",\n Protocol=1,\n Icmp=t_ec2.ICMP(Code=-1, Type=-1),\n RuleAction=\"allow\",\n )\n self._r[\"internal_nacl_in_vpc\"] = t_ec2.NetworkAclEntry(\n title=\"InternalNaclInVpc\",\n NetworkAclId=Ref(self.internal_nacl),\n Egress=False,\n RuleNumber=100,\n CidrBlock=GetAtt(self.vpc, \"CidrBlock\"),\n Protocol=-1,\n RuleAction=\"allow\",\n )\n for index, cidr_block in enumerate(self.internal_networks):\n self._r[f\"internal_nacl_in_internal_{index}\"] = t_ec2.NetworkAclEntry(\n title=f\"InternalNaclInInternal{index}\",\n NetworkAclId=Ref(self.internal_nacl),\n Egress=False,\n RuleNumber=101 + index,\n CidrBlock=cidr_block,\n Protocol=-1,\n RuleAction=\"allow\",\n )\n self._r[\"internal_nacl_in_nat_tcp\"] = t_ec2.NetworkAclEntry(\n title=\"InternalNaclInNatTcp\",\n NetworkAclId=Ref(self.internal_nacl),\n Egress=False,\n RuleNumber=500,\n CidrBlock=\"0.0.0.0/0\",\n Protocol=6,\n PortRange=t_ec2.PortRange(From=1024, To=65535),\n RuleAction=\"allow\",\n )\n self._r[\"internal_nacl_in_nat_udp\"] = t_ec2.NetworkAclEntry(\n title=\"InternalNaclInNatUdp\",\n NetworkAclId=Ref(self.internal_nacl),\n Egress=False,\n RuleNumber=501,\n CidrBlock=\"0.0.0.0/0\",\n Protocol=17,\n PortRange=t_ec2.PortRange(From=1024, To=65535),\n RuleAction=\"allow\",\n )\n\n def add_public_subnet_group(\n self,\n name_prefix: str,\n cidr_block: str,\n no_of_subnets: int = 4,\n create_nat_gateways: bool = False,\n ):\n \"\"\"Create public subnets and, optionally, NAT Gateways\n\n Args:\n name_prefix (str): Subnet name. AZ will be added at the end.\n cidr_block (str): Range of IP addresses to be split over\n availability zones.\n no_of_subnets (int, optional): How many subnets to set up.\n Defaults to 4.\n create_nat_gateways (bool, optional): If True, it will\n create one NAT gateway in each subnet and a private\n route table for each. Defaults to False.\n \"\"\"\n for res in multiaz_subnets(\n name_prefix=name_prefix,\n cidr_block=cidr_block,\n region=self.region,\n no_of_subnets=no_of_subnets,\n vpc=self.vpc,\n network_acl=self.public_nacl,\n route_table=self.public_route_table,\n ):\n self._r[res.title] = res\n self.public_subnets.append(res)\n if create_nat_gateways and res.resource[\"Type\"] == \"AWS::EC2::Subnet\":\n subnet = res\n az = subnet.Metadata[\"az\"]\n az_index = subnet.Metadata[\"az_index\"]\n suffix = subnet.Metadata[\"suffix\"]\n # Elastic IP for NAT Gateway\n eip = t_ec2.EIP(title=f\"EipNatGw{suffix}\", Domain=\"vpc\")\n self._r[eip.title] = eip\n # NAT Gateway\n nat_gw = t_ec2.NatGateway(\n title=f\"NatGw{suffix}\",\n AllocationId=GetAtt(eip, \"AllocationId\"),\n SubnetId=Ref(subnet),\n Tags=[{\"Key\": \"Name\", \"Value\": f\"Nat Gw {az_index}\"}],\n Metadata={\"az\": az, \"az_index\": az_index, \"suffix\": suffix},\n )\n self._r[nat_gw.title] = nat_gw\n self.nat_gateways.append(nat_gw)\n # Natted route table\n route_table = t_ec2.RouteTable(\n title=f\"PrivRouteTable{suffix}\",\n VpcId=Ref(self.vpc),\n Tags=[{\"Key\": \"Name\", \"Value\": f\"Private {az_index}\"}],\n Metadata={\"az\": az, \"az_index\": az_index, \"suffix\": suffix},\n )\n self.gateway_subnets.append(subnet)\n self.natted_route_tables.append(route_table)\n # NAT route\n self._r[route_table.title] = route_table\n route = t_ec2.Route(\n title=f\"NatRoute{az_index.upper()}\",\n RouteTableId=Ref(route_table),\n DestinationCidrBlock=\"0.0.0.0/0\",\n NatGatewayId=Ref(nat_gw),\n )\n self._r[route.title] = route\n\n def add_natted_subnet_group(\n self, cidr_block: str, name_prefix: str, no_of_subnets: int = 4\n ):\n \"\"\"Create private subnets behind NAT gateways\n\n Creates a group of subnets, attaches the private network ACL and\n the corresponding private route table depending on AZ\n\n Args:\n cidr_block (str): Will be split across AZs\n name_prefix (str): Subnet name. AZ will be added at the end.\n no_of_subnets (int, optional): How many subnets to set up.\n Must be a power of 2. Defaults to 4.\n\n Raises:\n NotImplementedError: [description]\n \"\"\"\n for res in multiaz_subnets(\n name_prefix=name_prefix,\n cidr_block=cidr_block,\n region=self.region,\n no_of_subnets=no_of_subnets,\n vpc=self.vpc,\n network_acl=self.internal_nacl,\n ):\n self._r[res.title] = res\n if res.resource[\"Type\"] == \"AWS::EC2::Subnet\":\n subnet = res\n route_found = False\n for route_table in self.natted_route_tables:\n if route_table.Metadata[\"az\"] == subnet.Metadata[\"az\"]:\n self._r[\n f\"{subnet.title}RouteAssociation\"\n ] = t_ec2.SubnetRouteTableAssociation(\n title=f\"{subnet.title}RouteAssociation\",\n SubnetId=Ref(subnet),\n RouteTableId=Ref(route_table),\n )\n route_found = True\n break\n if not route_found:\n raise NotImplementedError(\n f\"Can't find NAT gateway in {subnet.Metadata['az']}\"\n )\n\n def add_subnet_group(\n self,\n name_prefix: str,\n cidr_block: str,\n vpc: object = None,\n no_of_subnets: int = 4,\n network_acl: object = None,\n route_table: object = None,\n ):\n for res in multiaz_subnets(\n name_prefix=name_prefix,\n cidr_block=cidr_block,\n region=self.region,\n vpc=self.vpc,\n network_acl=network_acl,\n route_table=route_table,\n ):\n self._r[res.title] = res\n\n def peer_with_another_vpc(\n self,\n peer_vpc_id: str,\n peer_vpc_name: str,\n peer_role_arn: str = None,\n peer_owner_id: str = None,\n peer_region: str = None,\n peer_cidrs: list = [],\n add_route_to_private_tables: bool = True,\n add_route_to_public_table: bool = True,\n ):\n \"\"\"Set VPC Peering\n\n Args:\n peer_vpc_id (str): The ID of the VPC with which you are\n creating the VPC peering connection\n peer_vpc_name (str): A name for the peer VPC, used in\n the Name tag for the peering connection\n peer_role_arn (str, optional): VPC peer role for the\n peering connection in another AWS account.\n Required if peering with a different AWS account.\n Defaults to None.\n peer_owner_id (str, optional): Owner of the other AWS\n account, if any.\n Defaults to None.\n peer_region (str, optional): The Region code for the\n accepter VPC. Defaults to the same region as requester\n VPC.\n peer_cidrs: (list, optional): List of CIDR blocks used\n by the peer VPC. If non-empty and any add_route_*\n argument is set to true, a route entry will be added\n to the respective table pointing that CIDR block to\n the peered connection.\n Defaults to an empty list.\n add_route_to_private_tables (bool,optional): If True,\n add the peered VPC to the private routing tables.\n Defaults to True.\n add_route_to_public_tables (bool,optional): If True,\n add the peered VPC to the public routing table.\n Defaults to True.\n\n Notes:\n - For the peered VPC to be added to the routing tables,\n they must already exist when this method is called. That\n means subnets should be created before setting up\n VPC Connection Peering.\n - As of Jan 2022 CloudFormation can't enable DNS resolution\n \"\"\"\n res = t_ec2.VPCPeeringConnection(\n title=alphanum(\n f\"Peer{peer_vpc_name.capitalize()}With{self.name.capitalize()}\"\n ),\n VpcId=Ref(self.vpc),\n PeerVpcId=peer_vpc_id,\n Tags=[{\"Key\": \"Name\", \"Value\": f\"{peer_vpc_name} - {self.name}\"}],\n )\n if peer_region is not None:\n res.PeerRegion = peer_region\n if peer_owner_id is not None:\n res.PeerOwnerId = peer_owner_id\n if peer_role_arn is not None:\n res.PeerRoleArn = peer_role_arn\n self._r[res.title] = res\n if add_route_to_private_tables:\n self.add_vpc_peering_to_private_tables(\n peer_cidrs=peer_cidrs, vpc_peering_id=Ref(res)\n )\n if add_route_to_public_table:\n self.add_vpc_peering_to_public_table(\n peer_cidrs=peer_cidrs, vpc_peering_id=Ref(res)\n )\n\n def add_vpc_peering_to_private_tables(\n self,\n peer_cidrs: list = [],\n vpc_peering_id: str = None,\n ):\n for cidr in peer_cidrs:\n for route_table in self.natted_route_tables:\n route_title = f\"{route_table.title}Peer{alphanum(cidr)}Route\"\n self._r[route_title] = t_ec2.Route(\n title=route_title,\n RouteTableId=Ref(route_table),\n DestinationCidrBlock=cidr,\n VpcPeeringConnectionId=vpc_peering_id,\n )\n\n def add_vpc_peering_to_public_table(\n self,\n peer_cidrs: list = [],\n vpc_peering_id: str = None,\n ):\n for cidr in peer_cidrs:\n route_title = f\"{self.public_route_table.title}Peer{alphanum(cidr)}Route\"\n self._r[route_title] = t_ec2.Route(\n title=route_title,\n RouteTableId=Ref(self.public_route_table),\n DestinationCidrBlock=cidr,\n VpcPeeringConnectionId=vpc_peering_id,\n )\n\n def set_s3_endpoint(self):\n \"\"\"Set an S3 endpoint with full access and add it to private routes\"\"\"\n res = t_ec2.VPCEndpoint(\n title=alphanum(f\"{self.name}S3EndpointGateway\"),\n VpcId=Ref(self.vpc),\n ServiceName=f\"com.amazonaws.{self.region}.s3\",\n RouteTableIds=[\n Ref(route_table) for route_table in self.natted_route_tables\n ],\n )\n if self.public_route_table is not None:\n res.RouteTableIds.append(Ref(self.public_route_table))\n self._r[res.title] = res\n\n def set_prometheus_endpoint(self):\n \"\"\"\n Set a Managed Prometheus endpoint with full access and add it to\n private routes\n \"\"\"\n sg_res = t_ec2.SecurityGroup(\n title=alphanum(f\"{self.name}ApsVpcEndpointSG\"),\n VpcId=Ref(self.vpc),\n GroupDescription=\"Used by Prometheus VPC Endpoint\",\n SecurityGroupIngress=[\n t_ec2.SecurityGroupRule(\n IpProtocol=\"tcp\", FromPort=\"443\", ToPort=\"443\", CidrIp=\"0.0.0.0/0\"\n )\n ],\n )\n self._r[sg_res.title] = sg_res\n res = t_ec2.VPCEndpoint(\n title=alphanum(f\"{self.name}ApsVpcEndpoint\"),\n VpcId=Ref(self.vpc),\n ServiceName=f\"com.amazonaws.{self.region}.aps-workspaces\",\n SubnetIds=[Ref(subnet) for subnet in self.gateway_subnets],\n SecurityGroupIds=[Ref(self._r[sg_res.title])],\n VpcEndpointType=\"Interface\",\n )\n self._r[res.title] = res\n\n def generate(self):\n for key, resource in self._r.items():\n self._t.add_resource(resource)\n for key, output in self._o.items():\n self._t.add_output(output)\n return self._t.to_yaml()\n\n\nif __name__ == \"__main__\":\n pass\n", "repo_name": "bgdnlp/tropolib", "sub_path": "src/ec2.py", "file_name": "ec2.py", "file_ext": "py", "file_size_in_byte": 25133, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "troposphere.Ref", "line_number": 73, "usage_type": "call"}, {"api_name": "pawslib.var.alphanum", "line_number": 75, "usage_type": "call"}, {"api_name": "pawslib.ec2.split_net_across_zones", "line_number": 76, "usage_type": "call"}, {"api_name": "troposphere.ec2.Subnet", "line_number": 81, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 81, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 95, "usage_type": "call"}, {"api_name": "troposphere.ec2.SubnetNetworkAclAssociation", "line_number": 98, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 98, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 100, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 105, "usage_type": "call"}, {"api_name": "troposphere.ec2.SubnetRouteTableAssociation", "line_number": 108, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 108, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 110, "usage_type": "call"}, {"api_name": "troposphere.Template", "line_number": 164, "usage_type": "call"}, {"api_name": "troposphere.ec2.VPC", "line_number": 167, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 167, "usage_type": "name"}, {"api_name": "troposphere.Output", "line_number": 175, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 177, "usage_type": "call"}, {"api_name": "troposphere.Export", "line_number": 178, "usage_type": "call"}, {"api_name": "troposphere.Sub", "line_number": 178, "usage_type": "call"}, {"api_name": "troposphere.ec2.InternetGateway", "line_number": 183, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 183, "usage_type": "name"}, {"api_name": "troposphere.ec2.VPCGatewayAttachment", "line_number": 187, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 187, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 189, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 190, "usage_type": "call"}, {"api_name": "troposphere.ec2.RouteTable", "line_number": 193, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 193, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 195, "usage_type": "call"}, {"api_name": "troposphere.ec2.Route", "line_number": 200, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 200, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 202, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 204, "usage_type": "call"}, {"api_name": "troposphere.ec2.NetworkAcl", "line_number": 207, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 207, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 209, "usage_type": "call"}, {"api_name": "troposphere.ec2.NetworkAclEntry", "line_number": 213, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 213, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 215, "usage_type": "call"}, {"api_name": "troposphere.ec2.NetworkAclEntry", "line_number": 222, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 222, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 224, "usage_type": "call"}, {"api_name": "troposphere.ec2.ICMP", "line_number": 229, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 229, "usage_type": "name"}, {"api_name": "troposphere.ec2.NetworkAclEntry", "line_number": 232, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 232, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 234, "usage_type": "call"}, {"api_name": "troposphere.GetAtt", "line_number": 237, "usage_type": "call"}, {"api_name": "troposphere.ec2.NetworkAclEntry", "line_number": 242, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 242, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 244, "usage_type": "call"}, {"api_name": "troposphere.ec2.NetworkAclEntry", "line_number": 251, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 251, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 253, "usage_type": "call"}, {"api_name": "troposphere.ec2.PortRange", "line_number": 258, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 258, "usage_type": "name"}, {"api_name": "troposphere.ec2.NetworkAclEntry", "line_number": 261, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 261, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 263, "usage_type": "call"}, {"api_name": "troposphere.ec2.PortRange", "line_number": 268, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 268, "usage_type": "name"}, {"api_name": "troposphere.ec2.NetworkAclEntry", "line_number": 271, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 271, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 273, "usage_type": "call"}, {"api_name": "troposphere.ec2.PortRange", "line_number": 278, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 278, "usage_type": "name"}, {"api_name": "troposphere.ec2.NetworkAclEntry", "line_number": 281, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 281, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 283, "usage_type": "call"}, {"api_name": "troposphere.ec2.PortRange", "line_number": 288, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 288, "usage_type": "name"}, {"api_name": "troposphere.ec2.NetworkAclEntry", "line_number": 291, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 291, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 293, "usage_type": "call"}, {"api_name": "troposphere.ec2.PortRange", "line_number": 298, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 298, "usage_type": "name"}, {"api_name": "troposphere.ec2.NetworkAcl", "line_number": 302, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 302, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 304, "usage_type": "call"}, {"api_name": "troposphere.ec2.NetworkAclEntry", "line_number": 308, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 308, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 310, "usage_type": "call"}, {"api_name": "troposphere.ec2.NetworkAclEntry", "line_number": 317, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 317, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 319, "usage_type": "call"}, {"api_name": "troposphere.ec2.ICMP", "line_number": 324, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 324, "usage_type": "name"}, {"api_name": "troposphere.ec2.NetworkAclEntry", "line_number": 327, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 327, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 329, "usage_type": "call"}, {"api_name": "troposphere.GetAtt", "line_number": 332, "usage_type": "call"}, {"api_name": "troposphere.ec2.NetworkAclEntry", "line_number": 337, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 337, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 339, "usage_type": "call"}, {"api_name": "troposphere.ec2.NetworkAclEntry", "line_number": 346, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 346, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 348, "usage_type": "call"}, {"api_name": "troposphere.ec2.PortRange", "line_number": 353, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 353, "usage_type": "name"}, {"api_name": "troposphere.ec2.NetworkAclEntry", "line_number": 356, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 356, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 358, "usage_type": "call"}, {"api_name": "troposphere.ec2.PortRange", "line_number": 363, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 363, "usage_type": "name"}, {"api_name": "troposphere.ec2.EIP", "line_number": 403, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 403, "usage_type": "name"}, {"api_name": "troposphere.ec2.NatGateway", "line_number": 406, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 406, "usage_type": "name"}, {"api_name": "troposphere.GetAtt", "line_number": 408, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 409, "usage_type": "call"}, {"api_name": "troposphere.ec2.RouteTable", "line_number": 416, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 416, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 418, "usage_type": "call"}, {"api_name": "troposphere.ec2.Route", "line_number": 426, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 426, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 428, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 430, "usage_type": "call"}, {"api_name": "troposphere.ec2.SubnetRouteTableAssociation", "line_number": 467, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 467, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 469, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 470, "usage_type": "call"}, {"api_name": "troposphere.ec2.VPCPeeringConnection", "line_number": 546, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 546, "usage_type": "name"}, {"api_name": "pawslib.var.alphanum", "line_number": 547, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 550, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 563, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 567, "usage_type": "call"}, {"api_name": "pawslib.var.alphanum", "line_number": 577, "usage_type": "call"}, {"api_name": "troposphere.ec2.Route", "line_number": 578, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 578, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 580, "usage_type": "call"}, {"api_name": "pawslib.var.alphanum", "line_number": 591, "usage_type": "call"}, {"api_name": "troposphere.ec2.Route", "line_number": 592, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 592, "usage_type": "name"}, {"api_name": "troposphere.Ref", "line_number": 594, "usage_type": "call"}, {"api_name": "troposphere.ec2.VPCEndpoint", "line_number": 601, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 601, "usage_type": "name"}, {"api_name": "pawslib.var.alphanum", "line_number": 602, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 603, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 606, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 610, "usage_type": "call"}, {"api_name": "troposphere.ec2.SecurityGroup", "line_number": 618, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 618, "usage_type": "name"}, {"api_name": "pawslib.var.alphanum", "line_number": 619, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 620, "usage_type": "call"}, {"api_name": "troposphere.ec2.SecurityGroupRule", "line_number": 623, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 623, "usage_type": "name"}, {"api_name": "troposphere.ec2.VPCEndpoint", "line_number": 629, "usage_type": "call"}, {"api_name": "troposphere.ec2", "line_number": 629, "usage_type": "name"}, {"api_name": "pawslib.var.alphanum", "line_number": 630, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 631, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 633, "usage_type": "call"}, {"api_name": "troposphere.Ref", "line_number": 634, "usage_type": "call"}]} +{"seq_id": "15818690622", "text": "# -- coding: utf-8 --\n\n\"\"\"NeRF/Loss.py: Loss implementation for the vanilla (i.e. original) NeRF method.\"\"\"\n\nimport torch\nfrom torch import Tensor\nimport torchmetrics\n\nfrom Cameras.utils import RayPropertySlice\nfrom Losses.Base import BaseLoss\nfrom Losses.utils import LossMetricItem, QualityMetricItem\n\n\nclass NeRFLoss(BaseLoss):\n \"\"\"Defines a class for all sub-losses of the NeRF method.\"\"\"\n\n def __init__(self, lambda_color: float, lambda_alpha: float, activate_logging: bool = False) -> None:\n super().__init__(\n loss_metrics=[\n LossMetricItem(name='rgb', metric_func=torch.nn.functional.mse_loss, weight=lambda_color),\n LossMetricItem(name='alpha', metric_func=torch.nn.functional.mse_loss, weight=lambda_alpha),\n ],\n quality_metrics=[\n QualityMetricItem(name='PSNR', metric_func=torchmetrics.functional.peak_signal_noise_ratio)\n ],\n activate_logging=activate_logging\n )\n\n def forward(self, outputs: dict[str, Tensor | None], rays: Tensor) -> Tensor:\n \"\"\"Defines loss calculation.\"\"\"\n return super().forward({\n 'rgb': {'input': outputs['rgb'], 'target': rays[:, RayPropertySlice.rgb]},\n 'alpha': {'input': outputs['alpha'], 'target': rays[:, RayPropertySlice.alpha]},\n 'PSNR': {'preds': outputs['rgb'], 'target': rays[:, RayPropertySlice.rgb], 'data_range': 1.0},\n })\n", "repo_name": "MoritzKappel/MoNeRF", "sub_path": "src/Methods/NeRF/Loss.py", "file_name": "Loss.py", "file_ext": "py", "file_size_in_byte": 1450, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 13, "dataset": "github-code", "pt": "25", "api": [{"api_name": "Losses.Base.BaseLoss", "line_number": 14, "usage_type": "name"}, {"api_name": "Losses.utils.LossMetricItem", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "attribute"}, {"api_name": "Losses.utils.LossMetricItem", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "attribute"}, {"api_name": "Losses.utils.QualityMetricItem", "line_number": 24, "usage_type": "call"}, {"api_name": "torchmetrics.functional", "line_number": 24, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 29, "usage_type": "name"}, {"api_name": "Cameras.utils.RayPropertySlice.rgb", "line_number": 32, "usage_type": "attribute"}, {"api_name": "Cameras.utils.RayPropertySlice", "line_number": 32, "usage_type": "name"}, {"api_name": "Cameras.utils.RayPropertySlice.alpha", "line_number": 33, "usage_type": "attribute"}, {"api_name": "Cameras.utils.RayPropertySlice", "line_number": 33, "usage_type": "name"}, {"api_name": "Cameras.utils.RayPropertySlice.rgb", "line_number": 34, "usage_type": "attribute"}, {"api_name": "Cameras.utils.RayPropertySlice", "line_number": 34, "usage_type": "name"}]} +{"seq_id": "22765265926", "text": "\nimport copy\nimport numpy as np\nfrom plyfile import PlyData, PlyElement\n\ndef convert_2D_array_2_1D_list(a):\n \"\"\"\n Return a 2D NumPy array into a list of tuples.\n \"\"\"\n\n res = []\n\n for i in range(a.shape[0]):\n t = tuple( a[i,:].tolist() )\n res.append( t )\n \n return res\n\ndef write_PLY(fn, coor, color=None, binary=True):\n \"\"\"\n fn: The output filename.\n coor (NumPy array): (3, N)\n color (NumPy array): The color vector. The vector could be (N,) or (C, N).\n C could be 1 or 3. If color==None, no color properties \n will be in the output PLY file.\n binary: Set True to write a binary format PLY file. Set False for\n a ASCII version.\n \"\"\"\n\n # Need a table-like array.\n coor = coor.astype(np.float32).transpose()\n\n # Handle color.\n if ( color is not None ):\n if ( 1 == color.ndim ):\n color = np.stack([ color, color, color ], axis=0)\n \n # Need a table-like array.\n color = color.transpose()\n \n # Clip and convert to uint8.\n color = np.clip( color, 0, 255 ).astype(np.uint8)\n\n # Concatenate.\n vertex = np.concatenate([coor, color], axis=1)\n\n # Create finial vetex array.\n vertex = convert_2D_array_2_1D_list(vertex)\n vertex = np.array( vertex, dtype=[\\\n ( \"x\", \"f4\" ), \\\n ( \"y\", \"f4\" ), \\\n ( \"z\", \"f4\" ), \\\n ( \"red\", \"u1\" ), \\\n ( \"green\", \"u1\" ), \\\n ( \"blue\", \"u1\" ) \\\n ] )\n else:\n coor = convert_2D_array_2_1D_list(coor)\n vertex = np.array( coor, dtype=[\\\n ( \"x\", \"f4\" ), \\\n ( \"y\", \"f4\" ), \\\n ( \"z\", \"f4\" ) \\\n ] )\n \n # Save the PLY file.\n el = PlyElement.describe(vertex, \"vertex\")\n\n PlyData([el], text= (not binary) ).write(fn)\n ", "repo_name": "Duisterhof/360cam_extrinsics", "sub_path": "image_sampling/dsta_mvs_datacollection/data_collection/mvs_utils/point_cloud_helper.py", "file_name": "point_cloud_helper.py", "file_ext": "py", "file_size_in_byte": 1868, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "numpy.float32", "line_number": 31, "usage_type": "attribute"}, {"api_name": "numpy.stack", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 42, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 59, "usage_type": "call"}, {"api_name": "plyfile.PlyElement.describe", "line_number": 66, "usage_type": "call"}, {"api_name": "plyfile.PlyElement", "line_number": 66, "usage_type": "name"}, {"api_name": "plyfile.PlyData", "line_number": 68, "usage_type": "call"}]} +{"seq_id": "24101738626", "text": "# !/usr/bin/env python\n# -*- coding: utf-8-*-\n# pylint:disable=invalid-name\n\nimport sys\n\nfrom PyPDF2 import PdfFileReader, PdfFileWriter\n\n#将pdf文档全部分割\ndef SplitAll(pfile, wr):\n pdf = PdfFileReader(pfile)\n for idx in range(pdf.getNumPages()):\n wr.addPage(pdf.getPage(idx))\n with open(str(idx + 1) + '_split.pdf', 'wb') as out:\n wr.write(out)\n wr = PdfFileWriter()\n \n#将指定页分割成pdf文档\ndef SplitSpec(pfile, wr, page):\n pdf = PdfFileReader(pfile)\n if int(page) > pdf.getNumPages():\n print('out of pages!!')\n sys.exit()\n wr.addPage(pdf.getPage(int(page) - 1))\n with open(str(page) + '_split.pdf', 'wb') as out:\n wr.write(out)\n\n#将指定范围的页分割成pdf文档\ndef SplitRange(pfile, wr, start, end):\n pdf = PdfFileReader(pfile)\n if int(start) < 0 and int(end) > pdf.getNumPages():\n print('Range is wrong !!!')\n sys.exit()\n\n for idx in range(int(start), int(end) + 1):\n wr.addPage(pdf.getPage(idx - 1))\n\n with open (str(start) + \"-\" + str(end) + '_split.pdf', 'wb') as out:\n wr.write(out)\n\n#将指定范围的页分割成单独的pdf文档\ndef SplitRangeSig(pfile, wr, start, end):\n pdf = PdfFileReader(pfile)\n\n if int(start) < 0 and int(end) > pdf.getNumPages():\n print('Range is wrong !!!')\n sys.exit()\n\n for idx in range(int(start), int(end) + 1):\n wr.addPage(pdf.getPage(idx - 1))\n with open(str(idx) + '_split.pdf', 'wb') as out:\n wr.write(out)\n wr = PdfFileWriter()\n\n#将指定的多个pdf文件合并成一个pdf\ndef MergePdf(wr):\n for idx in range(2, len(sys.argv)):\n pdf = PdfFileReader(sys.argv[idx])\n for idy in range(pdf.getNumPages()):\n wr.addPage(pdf.getPage(idy))\n\n with open('new_merge_file.pdf', 'wb') as out:\n wr.write(out)\n\n#将一个pdf文件中的指定页合并成一个pdf文件\ndef MergeSpecPdf(pfile, wr):\n pdf = PdfFileReader(pfile)\n\n for idx in range(3, len(sys.argv)):\n if (int(sys.argv[idx]) - 1) < 0 or (int(sys.argv[idx]) - 1)> pdf.getNumPages():\n print('Wrong page number!')\n sys.exit()\n wr.addPage(pdf.getPage(int(sys.argv[idx]) - 1))\n\n with open('merge_one.pdf', 'wb') as out:\n wr.write(out)\n \n'''\n 参数说明:\n argv --\n 0:程序名\n 1:文件目录及文件名\n 2:指定操作\n a -- 分割全部\n s -- 分割指定页\n r -- 分割指定范围\n rs-- 分割指定范围为单独pdf\n m -- 合并指定的pdf文档\n ms-- 合并一个pdf文件中的指定页数\n 3:可选参数\n argv[2]==a :不指定\n argv[2]==s : 指定的页数\n argv[2]==r / rs: 指定范围的开始页数\n 4:可选参数\n argv[2]==r / rs: 指定范围的结束页数\n'''\n\nif __name__ == \"__main__\":\n fileName = sys.argv[2]\n writer = PdfFileWriter()\n #deal\n if sys.argv[1] == '-a':\n SplitAll(fileName, writer)\n elif sys.argv[1] == '-s':\n SplitSpec(fileName, writer, sys.argv[3])\n elif sys.argv[1] == '-r':\n SplitRange(fileName, writer, sys.argv[3], sys.argv[4])\n elif sys.argv[1] == '-rs':\n SplitRangeSig(fileName, writer, sys.argv[3], sys.argv[4])\n elif sys.argv[1] == '-m':\n MergePdf(writer)\n elif sys.argv[1] == '-ms':\n MergeSpecPdf(fileName, writer)\n else:\n #error\n print('should not come here!')\n print('Done Successful!')\n", "repo_name": "kiter521/PDFTool", "sub_path": "PDFTool.py", "file_name": "PDFTool.py", "file_ext": "py", "file_size_in_byte": 3541, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "PyPDF2.PdfFileReader", "line_number": 11, "usage_type": "call"}, {"api_name": "PyPDF2.PdfFileWriter", "line_number": 16, "usage_type": "call"}, {"api_name": "PyPDF2.PdfFileReader", "line_number": 20, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 23, "usage_type": "call"}, {"api_name": "PyPDF2.PdfFileReader", "line_number": 30, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 33, "usage_type": "call"}, {"api_name": "PyPDF2.PdfFileReader", "line_number": 43, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 47, "usage_type": "call"}, {"api_name": "PyPDF2.PdfFileWriter", "line_number": 53, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 57, "usage_type": "attribute"}, {"api_name": "PyPDF2.PdfFileReader", "line_number": 58, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 58, "usage_type": "attribute"}, {"api_name": "PyPDF2.PdfFileReader", "line_number": 67, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 69, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 70, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 72, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 73, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 99, "usage_type": "attribute"}, {"api_name": "PyPDF2.PdfFileWriter", "line_number": 100, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 102, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 104, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 105, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 106, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 107, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 108, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 109, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 110, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 112, "usage_type": "attribute"}]} +{"seq_id": "19061127858", "text": "import os\nimport pickle\nimport argparse\nimport pandas as pd\nfrom pathlib import Path\n\n\ndef validate(input_dir_path: Path, model_path: Path, output_dir_path: Path):\n X = pd.read_csv(input_dir_path / \"data.csv\", index_col=0)\n \n print(X.columns)\n \n if \"target\" in X.columns:\n X = X.drop(columns=\"target\").values\n\n print(X.columns)\n\n with open(model_path, \"rb\") as f:\n model = pickle.load(f)\n\n y_pred = model.predict(X)\n\n os.makedirs(output_dir_path, exist_ok=True)\n pred_df = pd.DataFrame({\"prediction\": y_pred})\n pred_df.to_csv(os.path.join(output_dir_path, \"predictions.csv\"))\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--input-dir\", \"-i\", type=str, required=True, help=\"Path to data directory\")\n parser.add_argument(\"--model-path\", \"-m\", type=str, required=True, help=\"Path to model\")\n parser.add_argument(\"--output-dir\", \"-o\", type=str, required=True, help=\"Path to predictions dir\")\n args = parser.parse_args()\n validate(Path(args.input_dir), Path(args.model_path), Path(args.output_dir))\n\n\nif __name__ == \"__main__\":\n main()", "repo_name": "made-ml-in-prod-2022/made_ml_in_prod_vroy", "sub_path": "lab3_airflow_ml_dags/images/airflow-predict/predict.py", "file_name": "predict.py", "file_ext": "py", "file_size_in_byte": 1124, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pathlib.Path", "line_number": 8, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 9, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 19, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 23, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 29, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 34, "usage_type": "call"}]} +{"seq_id": "33137806333", "text": "import numpy as np\r\nimport matplotlib as mp\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation as animation\r\n\r\nN = 100 #punti sulle x\r\nx = np.linspace(0, N, N)\r\ntstep = 5000 #punti sul tempo\r\nT = np.zeros((N,tstep))\r\n\r\n#Profilo di temperatura iniziale\r\nT[0:N,0] = 500*np.exp(-((50-x)/20)**2)\r\n\r\nD = 0.5\r\ndx = 0.01\r\ndt = 1e-4\r\nr = D*dt/dx**2\r\n#r < 1/2 affinche integri bene\r\nprint(r)\r\n\r\nfor time in range(1,tstep):\r\n for i in range(1,N-1):\r\n T[i,time] = T[i,time-1] + r*(T[i-1,time-1]+T[i+1,time-1]-2*T[i,time-1])\r\n\r\n# T[0,time] = T[1,time] #per avere bordi non fissi\r\n# T[N-1,time] = T[N-2,time]\r\n\r\nfig = plt.figure(1)\r\nax = fig.gca(projection='3d')\r\ngridx, gridy = np.meshgrid(range(tstep), range(N))\r\nax.plot_surface(gridx,gridy,T, cmap=mp.cm.coolwarm,vmax=250,linewidth=0,rstride=2, cstride=100)\r\nax.set_title('Diffusione del calore')\r\nax.set_xlabel('Tempo')\r\nax.set_ylabel('Lunghezza')\r\nax.set_zlabel('Temperatura')\r\n\r\nfig = plt.figure(2)\r\nplt.xlim(np.min(x), np.max(x))\r\nplt.ylim(np.min(T), np.max(T))\r\n\r\nline, = plt.plot([], [], 'b')\r\ndef animate(i):\r\n line.set_data(x, T[:,i])\r\n return line,\r\n\r\n\r\nanim = animation.FuncAnimation(fig, animate, frames=tstep, interval=10, blit=True, repeat=True)\r\n\r\nplt.grid()\r\nplt.title('Diffusione del calore')\r\nplt.xlabel('Distanza')\r\nplt.ylabel('Temperatura')\r\n\r\n#anim.save('calore.mp4', fps=30, extra_args=['-vcodec', 'libx264'])\r\n\r\nplt.show()", "repo_name": "Francesco-Zeno-Costanzo/4BLP", "sub_path": "PDE/Calore_FTCS.py", "file_name": "Calore_FTCS.py", "file_ext": "py", "file_size_in_byte": 1418, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "20", "api": [{"api_name": "numpy.linspace", "line_number": 7, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "numpy.meshgrid", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.cm", "line_number": 31, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "numpy.min", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "numpy.min", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.animation.FuncAnimation", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.animation", "line_number": 47, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 56, "usage_type": "name"}]} +{"seq_id": "14150742672", "text": "from subprocess import run\nfrom pathlib import Path\nfrom datetime import datetime\nimport shutil\n\ndef main():\n mount_drives()\n path = copy_to_ssd()\n upload_files(path)\n analize()\n thumbnails()\n mongo_db\n backup\n \ndef upload_files(folder_with_photos):\n run([\"rclone\", \"sync\", str(folder_with_photos), f\"y:Photos/imports/{folder_with_photos.name}\"])\n \ndef mount_drives():\n lsblk = run([\"sudo\",\"lsblk\"], capture_output=True).stdout.decode().split('\\n')\n for line in lsblk:\n if 'part' in line:\n if '118.4G' in line and len(line.split())<7:\n mount = line.split(' ')[0].replace('└─','')\n print((line.split()))\n run([\"sudo\", \"mount\", f\"/dev/{mount}\", \"/home/ubuntu/ssd\"])\n if '29.8G' in line and len(line.split())<7:\n mount = line.split(' ')[0].replace('└─','')\n run([\"sudo\", \"mount\", f\"/dev/{mount}\", \"/home/ubuntu/camera_drive\"])\n \ndef copy_to_ssd():\n camera_folder = Path('/home/ubuntu/camera_drive/DCIM/')\n folder_name = f\"upload_{datetime.now():%Y%m%d}\"\n new_path = Path(f'/home/ubuntu/ssd/ph/{folder_name}')\n new_path.mkdir(exist_ok=True)\n for file in camera_folder.glob('*/*'):\n name = file.name\n shutil.move(file, new_path.joinpath(name))\n return new_path\n \n \nif __name__ == \"__main__\":\n main()\n", "repo_name": "sZXZ/raspberry_projects", "sub_path": "py/utils/import_photos.py", "file_name": "import_photos.py", "file_ext": "py", "file_size_in_byte": 1399, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "subprocess.run", "line_number": 16, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 19, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 25, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 28, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 32, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 32, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 33, "usage_type": "call"}, {"api_name": "shutil.move", "line_number": 37, "usage_type": "call"}]} +{"seq_id": "35949346135", "text": "from src.mlProject.entity.config_entity import DataTransformationConfig\r\nimport os\r\nfrom src.mlProject import logger\r\nfrom sklearn.model_selection import train_test_split\r\nimport pandas as pd\r\nfrom sklearn.compose import ColumnTransformer\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.impute import SimpleImputer\r\nfrom sklearn.preprocessing import StandardScaler,OrdinalEncoder,OneHotEncoder\r\nimport numpy as np\r\nfrom src.mlProject.constants import *\r\nfrom src.mlProject.utils.common import *\r\n\r\n\r\nclass DataTransformation:\r\n def __init__(self, config: DataTransformationConfig):\r\n self.config = config\r\n\r\n\r\n\r\n def get_data_transformer_object(self):\r\n try:\r\n\r\n Numerical_col_1 = ['temperature','unit_price', 'timestamp_day_of_month', 'timestamp_day_of_week','timestamp_hour']\r\n\r\n Numerical_col_2 = ['quantity']\r\n\r\n categorical_col_for_OnehotEncoding = ['category']\r\n\r\n\r\n Numerical_pipeline_one_for_missingvalues = Pipeline(\r\n steps=[\r\n ('scaler',StandardScaler())\r\n ])\r\n\r\n Numerical_pipeline_two_for_missingvalues = Pipeline(\r\n steps=[\r\n ('imputer',SimpleImputer(strategy='constant', fill_value=0)),\r\n ('scaler',StandardScaler())\r\n ])\r\n \r\n categorical_pipeline_for_OnehotEncoding = Pipeline(\r\n steps=[\r\n ('one_hot_encoder', OneHotEncoder(sparse_output=False,handle_unknown = 'ignore')),\r\n ('scaler',StandardScaler())\r\n ]\r\n )\r\n\r\n preprocessor=ColumnTransformer(transformers= \r\n [('Numerical_pipeline_1_for_missingvalues', Numerical_pipeline_one_for_missingvalues,Numerical_col_1),\r\n ('Numerical_pipeline_2_for_missingvalues', Numerical_pipeline_two_for_missingvalues,Numerical_col_2),\r\n ('categorical_pipeline_for_OnehotEncoding', categorical_pipeline_for_OnehotEncoding,categorical_col_for_OnehotEncoding )\r\n ],\r\n remainder='passthrough',sparse_threshold=0) \r\n \r\n return preprocessor\r\n \r\n\r\n except Exception as e:\r\n raise e\r\n \r\n def initiate_data_transformation(self,):\r\n try:\r\n \r\n train_df = pd.read_csv(self.config.train_file_path)\r\n test_df = pd.read_csv(self.config.test_file_path)\r\n preprocessor = self.get_data_transformer_object()\r\n\r\n\r\n #training dataframe\r\n input_feature_train_df = train_df.drop(columns='estimated_stock_pct', axis=1)\r\n target_feature_train_df = train_df['estimated_stock_pct']\r\n\r\n #testing dataframe\r\n input_feature_test_df = test_df.drop(columns='estimated_stock_pct', axis=1)\r\n target_feature_test_df = test_df['estimated_stock_pct']\r\n\r\n preprocessor_object = preprocessor.fit(input_feature_train_df)\r\n input_feature_train_final = preprocessor_object.transform(input_feature_train_df)\r\n input_feature_test_final =preprocessor_object.transform(input_feature_test_df)\r\n\r\n\r\n train_arr = np.c_[input_feature_train_final, np.array(target_feature_train_df)]\r\n test_arr = np.c_[input_feature_test_final, np.array(target_feature_test_df)]\r\n\r\n\r\n #save numpy array data\r\n\r\n save_numpy_array(train_arr, self.config.transformed_train_file_path, 'train_array.npy')\r\n save_numpy_array(test_arr, self.config.transformed_train_file_path, 'test_array.npy')\r\n save_preprocessor(preprocessor_object, self.config.transformed_object_file_path)\r\n\r\n \r\n return (\r\n train_arr,\r\n test_arr,\r\n self.config.transformed_object_file_path, preprocessor_object\r\n )\r\n \r\n except Exception as e:\r\n raise e\r\n \r\n\r\n", "repo_name": "brevankumar/Inventory-Management-and-Predictive-Analytics-with-IOT", "sub_path": "src/mlProject/components/data_transformation.py", "file_name": "data_transformation.py", "file_ext": "py", "file_size_in_byte": 4252, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "src.mlProject.entity.config_entity.DataTransformationConfig", "line_number": 16, "usage_type": "name"}, {"api_name": "sklearn.pipeline.Pipeline", "line_number": 31, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.StandardScaler", "line_number": 33, "usage_type": "call"}, {"api_name": "sklearn.pipeline.Pipeline", "line_number": 36, "usage_type": "call"}, {"api_name": "sklearn.impute.SimpleImputer", "line_number": 38, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.StandardScaler", "line_number": 39, "usage_type": "call"}, {"api_name": "sklearn.pipeline.Pipeline", "line_number": 42, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.OneHotEncoder", "line_number": 44, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.StandardScaler", "line_number": 45, "usage_type": "call"}, {"api_name": "sklearn.compose.ColumnTransformer", "line_number": 49, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 65, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.c_", "line_number": 83, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.c_", "line_number": 84, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 84, "usage_type": "call"}]} +{"seq_id": "31460058868", "text": "from django.shortcuts import render, redirect\n\nfrom books.models import Book\nfrom django.core.paginator import Paginator\n\n\ndef index(request):\n return redirect('books')\n\n\ndef books_view(request):\n template = 'books/books_list.html'\n books = Book.objects.all()\n context = {\n 'books': books\n }\n return render(request, template, context)\n\n\ndef book_view(request, date):\n template = 'books/books_list.html'\n books = Book.objects.filter(pub_date=date).all()\n\n paginator = Paginator(books, 10)\n page_date = request.GET.get('date')\n page = paginator.get_page(page_date)\n\n context = {\n 'books': books,\n 'page': page,\n }\n return render(request, template, context)\n", "repo_name": "Alexander2327/dj_net", "sub_path": "2.1-databases/models_list_displaying/books/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 718, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "django.shortcuts.redirect", "line_number": 8, "usage_type": "call"}, {"api_name": "books.models", "line_number": 13, "usage_type": "name"}, {"api_name": "books.models.Book.objects.all", "line_number": 13, "usage_type": "call"}, {"api_name": "books.models.Book.objects", "line_number": 13, "usage_type": "attribute"}, {"api_name": "books.models.Book", "line_number": 13, "usage_type": "name"}, {"api_name": "books.models", "line_number": 15, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 17, "usage_type": "call"}, {"api_name": "books.models", "line_number": 22, "usage_type": "name"}, {"api_name": "books.models.Book.objects.filter", "line_number": 22, "usage_type": "call"}, {"api_name": "books.models.Book.objects", "line_number": 22, "usage_type": "attribute"}, {"api_name": "books.models.Book", "line_number": 22, "usage_type": "name"}, {"api_name": "django.core.paginator.Paginator", "line_number": 24, "usage_type": "call"}, {"api_name": "books.models", "line_number": 24, "usage_type": "argument"}, {"api_name": "books.models", "line_number": 29, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 32, "usage_type": "call"}]} +{"seq_id": "15784035513", "text": "import os\n\nfrom math import radians, degrees, sin, cos, asin, acos, sqrt, pi\n\nimport pandas as pd\nimport numpy as np\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine\n\nfrom flask import Flask, jsonify, render_template, url_for\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom werkzeug.routing import BaseConverter\n\nclass ListConverter(BaseConverter):\n\n def to_python(self, value):\n return value.split('+')\n\n def to_url(self, values):\n return '+'.join(BaseConverter.to_url(value)\n for value in values)\n\napp = Flask(__name__)\n\napp.url_map.converters['list'] = ListConverter\n\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///static/data/ghcn.db\"\ndb = SQLAlchemy(app)\n\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(db.engine, reflect=True)\n\n# Save references to each table\nInventory = Base.classes.inventory\nStations = Base.classes.stations\n\n@app.route(\"/testing/\")\ndef testing(variable_args):\n print(variable_args)\n for variable in variable_args:\n print(variable)\n return jsonify(variable_args)\n\ndef df_to_geojson(df, properties, lat='latitude', lon='longitude'):\n # print(df)\n geojson = {'type':'FeatureCollection', 'features':[]}\n for _, row in df.iterrows():\n feature = {'type':'Feature',\n 'properties':{},\n 'geometry':{'type':'Point',\n 'coordinates':[]}}\n feature['geometry']['coordinates'] = [row[lon],row[lat]]\n for prop in properties:\n feature['properties'][prop] = row[prop]\n geojson['features'].append(feature)\n\n # print(geojson)\n\n return jsonify(geojson)\n\ndef find_stations_with(session, element, lon_min, lon_max, lat_min, lat_max, first_year=None, last_year=None,):\n \"\"\"\n Args: \n element: one of the elements in the inventory table.\n first_year: the earliest year that must be included. If None, we do not filter on first_year\n last_year: the latest year that must be included. If None, we do not filter on last_year\n \"\"\"\n \n if first_year:\n if last_year: \n t = session.query(\n Inventory.station_id,\n ).filter(Inventory.first_year <= first_year)\\\n .filter(Inventory.last_year >= last_year)\\\n .filter(Inventory.element == element).subquery('t')\n else:\n t = session.query(\n Inventory.station_id,\n ).filter(Inventory.first_year <= first_year)\\\n .filter(Inventory.element == element).subquery('t')\n else:\n if last_year: \n t = session.query(\n Inventory.station_id,\n ).filter(Inventory.last_year >= last_year)\\\n .filter(Inventory.element == element).subquery('t')\n else:\n t = session.query(\n Inventory.station_id,\n ).filter(Inventory.element == element).subquery('t')\n \n\n query = session.query(Stations).filter(Stations.station_id == t.c.station_id)\\\n .filter(Stations.longitude >= lon_min)\\\n .filter(Stations.longitude <= lon_max)\\\n .filter(Stations.latitude >= lat_min)\\\n .filter(Stations.latitude <= lat_max)\n\n return pd.read_sql(query.statement, session.bind)\n\ndef find_stations_near(session, lon, lat, radius, element, miles=False, first_year=None, last_year=None):\n\n def great_circle_distance(lon1, lat1, lon2, lat2, miles=False):\n \"\"\"\n Compute the Great Circle Distance between two points given by longitude and latitude, in degrees,\n on the surface of the Earth. Code is modified from: \n https://medium.com/@petehouston/calculate-distance-of-two-locations-on-earth-using-python-1501b1944d97\n \"\"\"\n # Radius of the Earth\n if miles:\n multiplier = 3958.756\n else:\n multiplier = 6378.137\n \n lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])\n \n return multiplier * (\n acos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon1 - lon2))\n )\n\n def bounding_box(lon, lat, distance, miles=False):\n \"\"\"\n Return bounding coordinates that includes all points within the given distance of the point given by lon, lat.\n Based on the code given by Jan Philip Matuschek at:\n http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates\n \"\"\" \n # Radius of the Earth\n if miles:\n multiplier = 3958.756\n else:\n multiplier = 6378.137\n \n lon, lat = map(radians, [lon, lat])\n \n # angular distance in radians on a great circle\n rad_dist = distance / multiplier\n\n min_lat = lat - rad_dist\n max_lat = lat + rad_dist\n \n if min_lat > radians(-90) and max_lat < radians(90):\n delta_lon = asin(sin(rad_dist) / cos(lat))\n \n min_lon = lon - delta_lon\n if min_lon < radians(-180):\n min_lon += 2 * pi\n \n max_lon = lon + delta_lon\n if max_lon > radians(180):\n max_lon -= 2 * pi\n \n else:\n # a pole is within the distance\n min_lat = max(min_lat, radians(-90))\n max_lat = min(max_lat, radians(90))\n min_lon = radians(-180)\n max_lon = radians(180)\n\n return map(degrees, [min_lon, max_lon, min_lat, max_lat])\n\n # First get the bounding box to limit the search:\n lon_min, lon_max, lat_min, lat_max = bounding_box(lon, lat, radius, miles)\n \n # now query the database for all points within bounding box \n df = find_stations_with(session, element, lon_min, lon_max, lat_min, lat_max, first_year, last_year)\n \n distance = []\n # now compute the great circle distance to each station\n for row in df.itertuples():\n distance.append(great_circle_distance(lon, lat, row.longitude, row.latitude, miles))\n\n df['distance'] = distance\n \n return df[df.distance <= radius]\n\n\"\"\"\nApp routes \n\"\"\"\n@app.route(\"/\")\ndef index():\n \"\"\"Return the homepage.\"\"\"\n return render_template(\"index.html\")\n\n@app.route(\"/find_stations/\")\ndef find_stations(search_args):\n print(\"-\"*50)\n print(search_args)\n element = search_args[0]\n first_year = int(search_args[1])\n last_year = int(search_args[2])\n longitude = float(search_args[3])\n latitude = float(search_args[4])\n radius = float(search_args[5])\n\n df = find_stations_near(db.session, longitude, latitude, radius, element, False, first_year, last_year)\n #if not df.empty:\n # df.set_index('station_id', inplace=True)\n \n data = df.to_json(orient='records')\n # The NaNs were causing the problem in js. df.to_json fixes this\n '''\n data = []\n\n for row in df.itertuples():\n row_dict = {\n 'station': row.station_id,\n 'country': row.country_id,\n 'state': row.state_id,\n 'longitude': row.longitude,\n 'latitude': row.latitude,\n 'elevation': row.elevation,\n 'name': row.name,\n 'gsn': row.gsn,\n 'hcn': row.hcn,\n 'wmo': row.wmo\n }\n data.append(row_dict)\n '''\n\n print(df.head())\n print(df.shape)\n #print(data[:5])\n print(\"-\"*50)\n return data\n\nif __name__ == \"__main__\":\n app.run()\n", "repo_name": "douglasdrake/GHCN-stations", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 7543, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "werkzeug.routing.BaseConverter", "line_number": 18, "usage_type": "name"}, {"api_name": "werkzeug.routing.BaseConverter.to_url", "line_number": 24, "usage_type": "call"}, {"api_name": "werkzeug.routing.BaseConverter", "line_number": 24, "usage_type": "name"}, {"api_name": "flask.Flask", "line_number": 27, "usage_type": "call"}, {"api_name": "flask_sqlalchemy.SQLAlchemy", "line_number": 32, "usage_type": "call"}, {"api_name": "sqlalchemy.ext.automap.automap_base", "line_number": 35, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 48, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 65, "usage_type": "call"}, {"api_name": "pandas.read_sql", "line_number": 105, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 121, "usage_type": "argument"}, {"api_name": "math.acos", "line_number": 124, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 124, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 124, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 139, "usage_type": "argument"}, {"api_name": "math.radians", "line_number": 147, "usage_type": "call"}, {"api_name": "math.asin", "line_number": 148, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 148, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 148, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 151, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 152, "usage_type": "name"}, {"api_name": "math.radians", "line_number": 155, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 156, "usage_type": "name"}, {"api_name": "math.radians", "line_number": 160, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 161, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 162, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 163, "usage_type": "call"}, {"api_name": "math.degrees", "line_number": 165, "usage_type": "argument"}, {"api_name": "flask.render_template", "line_number": 188, "usage_type": "call"}]} +{"seq_id": "1279520546", "text": "from flask import current_app, redirect, request\n\nYEAR_IN_SECS = 31536000\n\nclass SSLify(object):\n \"\"\"Secures your Flask App.\"\"\"\n\n def __init__(self, app=None, age=YEAR_IN_SECS, subdomains=False, permanent=False, skips=None, ssl_debug=False, preload=False):\n self.app = app or current_app\n self.hsts_age = age\n self.ssl_debug = ssl_debug\n self.preload = preload\n\n self.hsts_include_subdomains = subdomains\n self.permanent = permanent\n self.skip_list = skips\n\n if app is not None:\n self.init_app(app)\n\n def init_app(self, app):\n \"\"\"Configures the specified Flask app to enforce SSL.\"\"\"\n app.config.setdefault('SSLIFY_SUBDOMAINS', False)\n app.config.setdefault('SSLIFY_PERMANENT', False)\n app.config.setdefault('SSLIFY_SKIPS', None)\n\n self.hsts_include_subdomains = self.hsts_include_subdomains or app.config['SSLIFY_SUBDOMAINS']\n self.permanent = self.permanent or self.app.config['SSLIFY_PERMANENT']\n self.skip_list = self.skip_list or self.app.config['SSLIFY_SKIPS']\n self.hsts_include_preload = self.preload or self.app.config['SSLIFY_PRELOAD']\n\n app.before_request(self.redirect_to_ssl)\n app.after_request(self.set_hsts_header)\n\n @property\n def hsts_header(self):\n \"\"\"Returns the proper HSTS policy.\"\"\"\n hsts_policy = 'max-age={0}'.format(self.hsts_age)\n\n if self.hsts_include_subdomains:\n hsts_policy += '; includeSubDomains'\n\n if self.hsts_include_preload:\n hsts_policy += '; preload'\n\n return hsts_policy\n\n @property\n def skip(self):\n \"\"\"Checks the skip list.\"\"\"\n # Should we skip?\n if self.skip_list and isinstance(self.skip_list, list):\n for skip in self.skip_list:\n if request.path.startswith('/{0}'.format(skip)):\n return True\n return False\n\n @property\n def debug_criteria(self):\n if self.ssl_debug:\n return False\n else:\n return current_app.debug\n\n def redirect_to_ssl(self):\n \"\"\"Redirect incoming requests to HTTPS.\"\"\"\n # Should we redirect?\n criteria = [\n request.is_secure,\n self.debug_criteria,\n current_app.testing,\n request.headers.get('X-Forwarded-Proto', 'http') == 'https',\n \"X-Appengine-Cron\" in request.headers,\n \"X-Appengine-TaskName\" in request.headers\n ]\n\n if not any(criteria) and not self.skip:\n if request.url.startswith('http://'):\n url = request.url.replace('http://', 'https://', 1)\n code = 302\n if self.permanent:\n code = 301\n r = redirect(url, code=code)\n return r\n\n def set_hsts_header(self, response):\n \"\"\"Adds HSTS header to each response.\"\"\"\n # Should we add STS header?\n if request.is_secure and not self.skip:\n response.headers.setdefault('Strict-Transport-Security', self.hsts_header)\n return response\n", "repo_name": "Morningstar/GoASQ", "sub_path": "src/flask_sslify.py", "file_name": "flask_sslify.py", "file_ext": "py", "file_size_in_byte": 3121, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 29, "dataset": "github-code", "pt": "25", "api": [{"api_name": "flask.current_app", "line_number": 9, "usage_type": "name"}, {"api_name": "flask.request.path.startswith", "line_number": 54, "usage_type": "call"}, {"api_name": "flask.request.path", "line_number": 54, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 54, "usage_type": "name"}, {"api_name": "flask.current_app.debug", "line_number": 63, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 63, "usage_type": "name"}, {"api_name": "flask.request.is_secure", "line_number": 69, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 69, "usage_type": "name"}, {"api_name": "flask.current_app.testing", "line_number": 71, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 71, "usage_type": "name"}, {"api_name": "flask.request.headers.get", "line_number": 72, "usage_type": "call"}, {"api_name": "flask.request.headers", "line_number": 72, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 72, "usage_type": "name"}, {"api_name": "flask.request.headers", "line_number": 73, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 73, "usage_type": "name"}, {"api_name": "flask.request.headers", "line_number": 74, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 74, "usage_type": "name"}, {"api_name": "flask.request.url.startswith", "line_number": 78, "usage_type": "call"}, {"api_name": "flask.request.url", "line_number": 78, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 78, "usage_type": "name"}, {"api_name": "flask.request.url.replace", "line_number": 79, "usage_type": "call"}, {"api_name": "flask.request.url", "line_number": 79, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 79, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 83, "usage_type": "call"}, {"api_name": "flask.request.is_secure", "line_number": 89, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 89, "usage_type": "name"}]} +{"seq_id": "38743379032", "text": "import requests \nimport json\n\nurl = \"https://api.coinstats.app/public/v1/coins\"\nparams = \"?skip=0&limit=5¤cy=EUR\"\n\nurlFinal = url+params\n\nresponse = requests.get(urlFinal)\n\njsonResponse = json.loads(response.content)\n\nprint(jsonResponse)", "repo_name": "JosephRiosHenao/SchoolHelperTools", "sub_path": "CurrencyValue.py", "file_name": "CurrencyValue.py", "file_ext": "py", "file_size_in_byte": 243, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "requests.get", "line_number": 9, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 11, "usage_type": "call"}]} +{"seq_id": "8857756198", "text": "from asyncio.windows_events import NULL\nimport logging\nfrom math import fabs\nfrom time import sleep\nfrom telegram import *\nfrom telegram.ext import * \nfrom requests import *\nimport json\nimport rotations_algo\n\n#User =>\n# user => user chat id - user preferences\ndef load_users():\n try:\n global users\n file = open('Data/users.json')\n users = json.loads(file.read())\n file.close()\n except FileNotFoundError:\n file = open(\"data/users.json\", \"w\")\n _json = json.dumps(users)\n file.write(_json)\n\ndef save_users():\n file = open(\"Data/users.json\", \"w\")\n _json = json.dumps(users)\n file.write(_json)\n\ndef add_user(user):\n users.append(user)\n save_users()\n\ndef set_age(user, age):\n user[\"age\"] = age\n save_users()\n\ndef remove_user(user):\n users.remove(user)\n save_users()\n\ndef set_user_preferences(user, preference):\n if(preference not in user[\"preferences\"]):\n user[\"preferences\"].append(preference)\n else:\n user[\"preferences\"].remove(preference)\n save_users()\n#User End\n\n# Enable logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n# Setup =>\ndef get_setup_preference_emoji(user, pref):\n if(pref in user[\"preferences\"]):\n return \"✔️\"\n return \"❌\"\n\ndef get_setup_buttons(user):\n buttons = [[InlineKeyboardButton(\"Müzeleri 🏛️\" + get_setup_preference_emoji(user, 1), callback_data=\"preference 1\"), InlineKeyboardButton(\"Doğal Ortamları 🌳\" + get_setup_preference_emoji(user, 2), callback_data=\"preference 2\")], \n [InlineKeyboardButton(\"Avmleri 🛒\" + get_setup_preference_emoji(user, 3), callback_data=\"preference 3\"), InlineKeyboardButton(\"Lunaparkları 🎠\" + get_setup_preference_emoji(user, 4), callback_data=\"preference 4\")], \n [InlineKeyboardButton(\"Tamamdır ✔️\", callback_data=\"finish setup\")]]\n return InlineKeyboardMarkup(buttons)\n\ndef set_setup_buttons(user, callback_query):\n buttons = get_setup_buttons(user)\n callback_query.edit_message_reply_markup(buttons)\n\ndef set_preference(user, callback_query):\n set_user_preferences(user, int(callback_query.data[-1]))\n set_setup_buttons(user, callback_query)\n\ndef start_setup(effective_chat, context):\n user = {\"id\" : effective_chat.id, \"preferences\" : []}\n add_user(user)\n text = f'Öncelikle hoş geldin {effective_chat.first_name}\\nŞimdi sana bir profil oluşturmamız lazım.\\nYaşını şu şekilde ayarlayabilirsin => yas 19\\nBana biraz kendinden bahset, mesela nereleri gezmekten hoşlanırsın ?'\n buttons = get_setup_buttons(user)\n context.bot.send_message(chat_id=effective_chat.id, text=text, reply_markup=buttons)\n# Setup End\n\n#Menu\nis_entered = False\ndef get_menu_buttons():\n buttons = [[InlineKeyboardButton(\"Profili sıfırla 🔄\", callback_data=\"reset profile\")], [InlineKeyboardButton(\"Rotasyon oluştur 🗺️\", callback_data=\"create rotation\")]]\n return InlineKeyboardMarkup(buttons)\n\ndef update_location(update: Update, context: CallbackContext):\n user = {}\n for us in users:\n if(us[\"id\"] == update.effective_user.id):\n user = us\n break\n\n user[\"current_pos\"] = [update.message.location.latitude, update.message.location.longitude]\n text = 'Tamamdır, konumunu kaptım.'\n context.bot.send_message(chat_id=user[\"id\"], text=text)\n\ndef get_input(update, context):\n user = {}\n for us in users:\n if(us[\"id\"] == update.effective_user.id):\n user = us\n break\n \n if(update.message.text.startswith(\"yas\")):\n set_age(user,int(update.message.text.split(\" \")[1]))\n text = f'Ooo demek {update.message.text.split(\" \")[1]} yaşındasın.'\n context.bot.send_message(chat_id=user[\"id\"], text=text)\n return\n\n val = update.message.text.split(\" \")\n user[\"hour\"] = int(val[0])\n user[\"budget\"] = \"B\"\n\n text = 'Süreni ve bütçeni kaydettim.'\n context.bot.send_message(chat_id=user[\"id\"], text=text)\n\ndef create_rotations(user, context):\n if(user[\"current_pos\"] == NULL):\n text = 'Sana uygun bir şeyler bulmak için konumuna ihtiyacım var, yollayabilir misin ?'\n context.bot.send_message(chat_id=user[\"id\"], text=text)\n return\n\n context.bot.send_message(chat_id=user[\"id\"], text=\"Sana en uygun rotayı bulmak için düşünüyorum.. Biraz bekleteceğim :)\")\n result = rotations_algo.get_positions(user[\"current_pos\"], user[\"preferences\"], user[\"hour\"] *60, user[\"budget\"])\n user[\"locations\"] = result[0]\n text = f\"https://www.google.com/maps/dir/'{user['current_pos'][0]},{user['current_pos'][1]}'/{result[1][0]},{result[1][1]}/\"\n buttons = [[InlineKeyboardButton(\"Devam ➡\", callback_data=\"go next\")]]\n buttons = InlineKeyboardMarkup(buttons)\n context.bot.send_message(chat_id=user[\"id\"], text=text, reply_markup=buttons)\n \ndef go_next(user, context):\n text = f\"https://www.google.com/maps/dir/'{user['locations']['lat'].iloc[-1]},{user['locations']['long'].iloc[-1]}'/{user['locations']['lat'].iloc[-2]},{user['locations']['long'].iloc[-2]}/\"\n user[\"locations\"] = user[\"locations\"][:-1]\n buttons = [[InlineKeyboardButton(\"Devam ➡\", callback_data=\"go next\")]]\n buttons = InlineKeyboardMarkup(buttons)\n context.bot.send_message(chat_id=user[\"id\"], text=text, reply_markup=buttons)\n\ndef start_menu(user, context):\n text = 'Süreni ve bütçeni şu şekilde girebilirsin => 2 saat 350 tl\\nRotasyon belirlemeden önce bunları girmeli ve konumunu yüklemelisin.'\n context.bot.send_message(chat_id=user[\"id\"], text=text)\n text = 'Ne yapmak istersin ?'\n context.bot.send_message(chat_id=user[\"id\"], text=text, reply_markup=get_menu_buttons())\n#Menu End\n\n#Start Command\ndef start(update: Update, context: CallbackContext):\n for user in users:\n if(user[\"id\"] == update.effective_user.id):\n text = f'Tekrar hoş geldin {update.effective_chat.first_name}.'\n context.bot.send_message(chat_id=update.effective_chat.id, text=text)\n start_menu(update.effective_chat, context)\n return\n\n start_setup(update.effective_chat, context)\n\n#Button Click Events Handler =>\ndef callBackQuery(update: Update, context: CallbackContext):\n user = {}\n for _user in users:\n if(_user[\"id\"] == update.effective_chat.id):\n user = _user\n if(user == {}):\n logger.warning(\"Var olmayan kullancı işlem yapmaya çalışıyor!\")\n return\n \n if(update.callback_query.data.startswith(\"preference\")):\n set_preference(user, update.callback_query)\n elif(update.callback_query.data == \"finish setup\"):\n update.callback_query.delete_message()\n start_menu(user, context)\n elif(update.callback_query.data == \"reset profile\"):\n remove_user(user)\n update.callback_query.delete_message()\n start_setup(update.effective_chat, context)\n elif(update.callback_query.data == \"create rotation\"):\n create_rotations(user, context)\n elif(update.callback_query.data == \"go next\"):\n go_next(user, context)\n\n#Other funcs\ndef echo(update, context):\n update.message.reply_text(\"Ne dedin anlayamadım :'( Lütfen kontrol eder misin ?\")\n\n\ndef error(update, context):\n logger.warning('Update => \"%s\" Error => \"%s\"', update, context.error)\n\n\ndef main():\n load_users()\n\n token = \"Your Telegram Token Here\"\n updater = Updater(token, use_context=True)\n\n dp = updater.dispatcher\n \n dp.add_handler(MessageHandler(Filters.location, update_location))\n dp.add_handler(CommandHandler(\"start\", start))\n dp.add_handler(CallbackQueryHandler(callBackQuery))\n dp.add_handler(MessageHandler(Filters.text, get_input))\n\n dp.add_error_handler(error)\n\n updater.start_polling()\n\n updater.idle()\n\n\nif __name__ == '__main__':\n main()", "repo_name": "farukborann/Konya_Travel_Route_Assistant", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 7911, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "25", "api": [{"api_name": "json.loads", "line_number": 17, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 21, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 26, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 50, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 50, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 51, "usage_type": "call"}, {"api_name": "asyncio.windows_events.NULL", "line_number": 119, "usage_type": "name"}, {"api_name": "rotations_algo.get_positions", "line_number": 125, "usage_type": "call"}]} +{"seq_id": "47724315192", "text": "import rclpy\nfrom std_msgs.msg import Empty\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import Twist\n\nimport numpy as np\nfrom math import degrees, radians\n\nfrom .motor_ctrl import MotorCtrl\nfrom ..utils import cffirmware\n\nclass MotorCtrlFPQR(MotorCtrl):\n\n def init(self, webots_node, properties):\n super().init(webots_node, properties)\n\n print('MotorCrtlFPQR Started!')\n\n # Declare Subscriptions\n msg_type = Twist()\n self.target_cmd_vel = msg_type\n self.cf_driver.create_subscription(msg_type, '/{}/cmd_vel'.format(self.namespace), self.setpoint_callback, 1)\n self.odom_publisher = self.cf_driver.create_publisher(Odometry, '/{}/odom'.format(self.namespace), 10)\n self.stop_subscription = self.cf_driver.create_subscription(Empty, '/stop', self.stop, 10)\n \n # Initialize cf classes\n cffirmware.controllerPidInit()\n \n def setpoint_callback(self, twist):\n self.target_cmd_vel = twist\n\n def step(self):\n\n rclpy.spin_once(self.cf_driver, timeout_sec=0)\n self.time = self.robot.getTime()\n\n self.update_current_pose()\n self.publish_odometry()\n self.update_cf_state()\n self.update_cf_sensors()\n self.check_safety_area()\n\n if self.initialization:\n self.initialization = False\n self.init_setpoint()\n\n self.compute_setpoint()\n\n ## Firmware PID bindings\n tick = 100 #this value makes sure that the position controller and attitude controller are always always initiated\n cffirmware.controllerPid(self.control, self.setpoint, self.sensors, self.state, tick)\n\n ## \n cmd_roll = radians(self.control.roll) # rad/s \n cmd_pitch = radians(self.control.pitch) # rad/s\n cmd_yaw = -radians(self.control.yaw) # rad/s\n cmd_thrust = self.control.thrust # uint (PWM)\n\n if self.emergency_stop:\n cmd_roll = 0.0\n cmd_pitch = 0.0\n cmd_yaw = 0.0\n cmd_thrust = 0.0\n\n string = \"Thrust = {:.0f}\\tRoll = {:.4f}\\tPitch = {:.4f}\\tYaw = {:.4f}\".format(cmd_thrust, cmd_roll, cmd_pitch, cmd_yaw)\n # print(string)\n \n self.send_motor_cmd(cmd_thrust, cmd_roll, cmd_pitch, cmd_yaw)\n\n self.past_time = self.robot.getTime()\n self.past_position = self.current_pose.position\n\n\n def init_setpoint(self):\n\n # Initialize setpoint modes\n self.setpoint.mode.roll = cffirmware.modeVelocity\n self.setpoint.mode.pitch = cffirmware.modeVelocity\n self.setpoint.mode.yaw = cffirmware.modeVelocity\n self.setpoint.mode.z = cffirmware.modeDisable # needed to use thrust as setpoint\n\n def compute_setpoint(self):\n # Conversion constants\n mg_newton = 0.372652 # Thrust in Newton to take_off\n mg_pwm = 38615.0 # Thrust in PWM units to take_off with mass 0.038 (webots), scaling = 800\n newton2pwm = mg_pwm/mg_newton\n\n # Thrust limits\n thrust_min = 10001\n thrust_max = 60000\n\n self.setpoint.attitudeRate.roll = degrees(self.target_cmd_vel.angular.x) # deg/s\n # NOTE: minus @ pitch\n self.setpoint.attitudeRate.pitch = degrees(-self.target_cmd_vel.angular.y) # deg/s\n self.setpoint.attitudeRate.yaw = degrees(self.target_cmd_vel.angular.z) # deg/s\n self.setpoint.thrust = np.clip(thrust_min, self.target_cmd_vel.linear.z*newton2pwm, thrust_max) # PWM units\n", "repo_name": "OPT4SMART/crazychoir", "sub_path": "crazychoir/crazychoir/webots_plugin/motor_ctrl_fpqr.py", "file_name": "motor_ctrl_fpqr.py", "file_ext": "py", "file_size_in_byte": 3535, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 23, "dataset": "github-code", "pt": "20", "api": [{"api_name": "motor_ctrl.MotorCtrl", "line_number": 12, "usage_type": "name"}, {"api_name": "geometry_msgs.msg.Twist", "line_number": 20, "usage_type": "call"}, {"api_name": "nav_msgs.msg.Odometry", "line_number": 23, "usage_type": "argument"}, {"api_name": "std_msgs.msg.Empty", "line_number": 24, "usage_type": "argument"}, {"api_name": "utils.cffirmware.controllerPidInit", "line_number": 27, "usage_type": "call"}, {"api_name": "utils.cffirmware", "line_number": 27, "usage_type": "name"}, {"api_name": "rclpy.spin_once", "line_number": 34, "usage_type": "call"}, {"api_name": "utils.cffirmware.controllerPid", "line_number": 51, "usage_type": "call"}, {"api_name": "utils.cffirmware", "line_number": 51, "usage_type": "name"}, {"api_name": "math.radians", "line_number": 54, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 55, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 56, "usage_type": "call"}, {"api_name": "utils.cffirmware.modeVelocity", "line_number": 77, "usage_type": "attribute"}, {"api_name": "utils.cffirmware", "line_number": 77, "usage_type": "name"}, {"api_name": "utils.cffirmware.modeVelocity", "line_number": 78, "usage_type": "attribute"}, {"api_name": "utils.cffirmware", "line_number": 78, "usage_type": "name"}, {"api_name": "utils.cffirmware.modeVelocity", "line_number": 79, "usage_type": "attribute"}, {"api_name": "utils.cffirmware", "line_number": 79, "usage_type": "name"}, {"api_name": "utils.cffirmware.modeDisable", "line_number": 80, "usage_type": "attribute"}, {"api_name": "utils.cffirmware", "line_number": 80, "usage_type": "name"}, {"api_name": "math.degrees", "line_number": 92, "usage_type": "call"}, {"api_name": "math.degrees", "line_number": 94, "usage_type": "call"}, {"api_name": "math.degrees", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 96, "usage_type": "call"}]} +{"seq_id": "72526742451", "text": "from __future__ import annotations\n\nimport torch\nfrom torch_geometric.data import Batch\n\nfrom src.original.trans_bt.loader import augment\nfrom src.dataset.molecule_dataset import MoleculeDataset\nfrom torch.utils.data import Dataset\n\n\nclass TTTAugDataset(Dataset):\n def __init__(\n self,\n dataset: MoleculeDataset,\n num_augmentations: int,\n aug: str = \"none\",\n aug_ratio: int | float = None,\n ):\n self.dataset = dataset\n self.aug = aug\n self.aug_ratio = aug_ratio\n self.num_augmentations = num_augmentations\n\n def __len__(self):\n return len(self.dataset)\n\n def __getitem__(self, idx):\n data = self.dataset[idx]\n augmented_data = [\n augment(data.clone(), self.aug, self.aug_ratio)\n for _ in range(self.num_augmentations)\n ]\n augmented_data = Batch.from_data_list(augmented_data)\n return data, augmented_data\n\n def shuffle(self):\n self.dataset = self.dataset.shuffle()\n return self\n", "repo_name": "universuen/UDA_GNN", "sub_path": "src/dataset/ttt_aug_dataset.py", "file_name": "ttt_aug_dataset.py", "file_ext": "py", "file_size_in_byte": 1054, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "torch.utils.data.Dataset", "line_number": 11, "usage_type": "name"}, {"api_name": "src.dataset.molecule_dataset.MoleculeDataset", "line_number": 14, "usage_type": "name"}, {"api_name": "src.original.trans_bt.loader.augment", "line_number": 30, "usage_type": "call"}, {"api_name": "torch_geometric.data.Batch.from_data_list", "line_number": 33, "usage_type": "call"}, {"api_name": "torch_geometric.data.Batch", "line_number": 33, "usage_type": "name"}]} +{"seq_id": "37161172302", "text": "import re\nfrom collections import defaultdict\nfrom myutils.file_reader import read_lines\n\n\nclass LuggageProcessing:\n def __init__(self, filename):\n self.rules = read_lines(filename)\n self.process()\n\n def process(self):\n self.contained = defaultdict(set)\n self.contains = dict()\n\n for rule in self.rules:\n parts = re.sub('[.]', '', rule).split('contain')\n cont = defaultdict(int)\n parent = parts[0].strip()\n parent = re.sub('bags|bag', '', parent).strip()\n parts = parts[1].split(',')\n children = []\n for c in parts:\n sub = c.strip().split(' ')\n try:\n count = int(sub[0])\n except ValueError:\n continue\n child = ' '.join(sub[1:])\n child = re.sub('bags|bag', '', child).strip()\n cont[child] += count\n self.contained[child].update((parent,))\n self.contains[parent] = cont\n return\n\n def contained_count(self, name):\n bags = set()\n stack = [name]\n while stack:\n for k in self.contained[stack.pop()]:\n if k not in bags:\n bags.update((k,))\n stack.append(k)\n bags.discard(name)\n return(len(bags))\n\n def contains_count(self, name):\n counter = 1\n contents = self.contains.get(name, dict())\n for bag_name, count in contents.items():\n counter += count * self.contains_count(bag_name)\n return(counter)\n\n def contains_inside_count(self, name):\n return self.contains_count(name) - 1\n\n\nif __name__ == '__main__':\n luggage_test1 = LuggageProcessing('test1.txt')\n assert luggage_test1.contained_count('shiny gold') == 4\n luggage_test2 = LuggageProcessing('test2.txt')\n assert luggage_test2.contains_inside_count('shiny gold') == 126\n\n luggage_proc = LuggageProcessing('input.txt')\n print(luggage_proc.contained_count('shiny gold'),\n luggage_proc.contains_inside_count('shiny gold'))\n", "repo_name": "shahroudy/Advent-of-Code", "sub_path": "python/aoc2020/day07/d07.py", "file_name": "d07.py", "file_ext": "py", "file_size_in_byte": 2124, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "myutils.file_reader.read_lines", "line_number": 8, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 12, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 16, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 17, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 19, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 29, "usage_type": "call"}]} +{"seq_id": "71138642626", "text": "#!/usr/bin/env python\n# coding: utf-8\n\nfrom tqdm import tqdm \nimport pandas as pd\nimport re\nimport sys\nimport logging\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\nlogging.getLogger().setLevel(logging.INFO)\n\nhashtags = []\n\ndef get_hashtag_words(hashtag):\n if len(hashtag)==1 and type(hashtag)==list:\n hashtag = hashtag[0]\n hashtags.append(hashtag.replace(\"#\",''))\n else:\n for tag in hashtag:\n hashtags.append(tag.replace(\"#\",''))\n\n\n# pd.set_option('display.max_colwidth', -1)\n\n\nif __name__ == '__main__':\n \n filename = sys.argv[1]\n \n logging.info(\"Loading data...\")\n data = pd.read_csv(filename)\n \n logging.info(\"parsing hashtags...\")\n data['hashtags']=data['tweet'].apply(lambda x: re.findall(r'#[\\w]+',x))\n \n logging.info(\"removing tweets with no hashtags\")\n data = data[data.astype(str)['hashtags']!='[]']\n \n for row in tqdm(data['hashtags']):\n get_hashtag_words(row)\n\n if hashtags:\n pd.DataFrame(hashtags,columns=['hash'])['hash'].value_counts().reset_index().to_csv(\"hashtags_frequency.csv\")\n\n exit(0)", "repo_name": "mallaham/utilities", "sub_path": "get_hashtags.py", "file_name": "get_hashtags.py", "file_ext": "py", "file_size_in_byte": 1108, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "warnings.filterwarnings", "line_number": 11, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 12, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 12, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 30, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 32, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 33, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 35, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 36, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 38, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 41, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 45, "usage_type": "call"}]} +{"seq_id": "25843110064", "text": "import sys\nfrom collections import deque\n\ntestCase = int(input())\n\nfor _ in range(testCase):\n func = sys.stdin.readline().rstrip()\n func = func.replace(\"RR\", \"\")\n l = int(input())\n case = sys.stdin.readline().rstrip()[1:-1].split(',')\n d = -1\n if case == ['']:\n case = []\n else:\n case = deque(case)\n \n if len(case) < func.count('D'):\n print(\"error\")\n else:\n for f in func:\n if f == 'R':\n d *= -1\n else:\n if d == -1:\n case.popleft()\n else:\n case.pop()\n if d == -1:\n print(\"[\" + \",\".join(list(case)) + \"]\")\n else:\n print(\"[\" + \",\".join(list(case)[::-1]) + \"]\")\n\n", "repo_name": "j1mmyson/PS", "sub_path": "python/baekjoon/GOLD/G5_5430_AC.py", "file_name": "G5_5430_AC.py", "file_ext": "py", "file_size_in_byte": 759, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "sys.stdin.readline", "line_number": 7, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 7, "usage_type": "attribute"}, {"api_name": "sys.stdin.readline", "line_number": 10, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 10, "usage_type": "attribute"}, {"api_name": "collections.deque", "line_number": 15, "usage_type": "call"}]} +{"seq_id": "3692324066", "text": "from datetime import datetime, date\nfrom decimal import Decimal\nimport json\nimport logging\n\nfrom . import confit\n\nconfig = confit.Configuration('inventor', __name__, False)\n\nlog = logging.getLogger('inventor')\nformatter = logging.Formatter('%(levelname)s:%(module)s.%(funcName)s: %(message)s')\nhandler = logging.StreamHandler()\nhandler.setFormatter(formatter)\nlog.addHandler(handler)\n\nlog.setLevel(logging.DEBUG)\n\n#monkey patch the json encoder\ndef newdefault(self, obj):\n if isinstance(obj, (datetime, date)):\n return obj.isoformat() #this is redundant\n elif isinstance(obj, Decimal):\n return str(obj)\n # elif obj is None:\n # #None converted to empty string cause otherwise js\n # #will convert the None to null which results in a string\n # #with the value \"null\" being returned back making a mess of things\n # return ''\n raise TypeError(\n 'Object of type %s with value %s is not JSON serializable' %\n (type(obj), obj))\n\nsetattr(json.JSONEncoder, 'default', newdefault)\n# Force decoder to decode floats to decimal\ndef initd(self, *args, **kwargs):\n kwargs['parse_float'] = Decimal\n self.baseinit(*args, **kwargs)\nsetattr(json.JSONDecoder, 'baseinit', json.JSONDecoder.__init__)\nsetattr(json.JSONDecoder, '__init__', initd)\n\n", "repo_name": "steinitzu/inventor", "sub_path": "inventor/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 1298, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "logging.getLogger", "line_number": 10, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 11, "usage_type": "call"}, {"api_name": "logging.StreamHandler", "line_number": 12, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 16, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 20, "usage_type": "name"}, {"api_name": "datetime.date", "line_number": 20, "usage_type": "name"}, {"api_name": "decimal.Decimal", "line_number": 22, "usage_type": "argument"}, {"api_name": "json.JSONEncoder", "line_number": 33, "usage_type": "attribute"}, {"api_name": "decimal.Decimal", "line_number": 36, "usage_type": "name"}, {"api_name": "json.JSONDecoder", "line_number": 38, "usage_type": "attribute"}, {"api_name": "json.JSONDecoder", "line_number": 39, "usage_type": "attribute"}]} +{"seq_id": "39938411472", "text": "import discord, json, os, keep_alive\nfrom discord.ext import commands\n\nwith open('setting.json','r', encoding='utf8') as jfile:\n jdata = json.load(jfile)\n\nbot = commands.Bot(command_prefix='!')\nbot.remove_command('help')\n\n\n# @bot.event\n# async def on_ready():\n# print(\">> Bot is online <<\")\n\nfor Filename in os.listdir('./cmds'):\n if Filename.endswith('py'):\n bot.load_extension(f'cmds.{Filename[:-3]}')\n\n \n@bot.command()\nasync def load(ctx, extension):\n bot.load_extension(f'cmds.{extension}')\n await ctx.send(f'Loaded {extension} done')\n\n@bot.command()\nasync def unload(ctx, extension):\n bot.unload_extension(f'cmds.{extension}')\n await ctx.send(f'Unloaded {extension} done')\n\n@bot.command()\nasync def reload(ctx, extension):\n bot.reload_extension(f'cmds.{extension}')\n await ctx.send(f'Reloaded {extension} done')\n\nif __name__ == \"__main__\":\n keep_alive.keep_alive()\n bot.run(jdata['TOKEN'])\n", "repo_name": "neu-ma-tic/test9475", "sub_path": "62bf439b-7998-4c3a-9072-42fb53286850/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 935, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "json.load", "line_number": 5, "usage_type": "call"}, {"api_name": "discord.ext.commands.Bot", "line_number": 7, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 7, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 15, "usage_type": "call"}, {"api_name": "keep_alive.keep_alive", "line_number": 36, "usage_type": "call"}]} +{"seq_id": "73881951409", "text": "import serial\nimport time\nfrom math import *\nfrom vision import *\nimport cv2\n\n\ndef serial_push(ser, bytes, need_encode):\n return(None);\n if(need_encode == True):\n ser.write(bytes.encode());\n else:\n ser.write(bytes);\n\ndef serial_pull(ser):\n return(\"\");\n message = \"\";\n\n while(ser.inWaiting() > 0):\n message += ser.readline().decode().strip();\n return(message);\n\n\n#wheelchair = serial.Serial(port=\"/dev/cu.usbmodem1451\", baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=0.1, write_timeout=0.01);\nwheelchair = None;\n\ntime.sleep(1);\n\nthresh = 20;\n\ncam_control = False;\n\ndirection = 0;\n# 1 is forward, -1 is reverse, 0 is brake\n\nangle = 0;\n# 1 is turning left, 0 is forward, -1 is turning right\n\nbuttons = [];\n\nwith tf.Session() as session:\n\n print(\"Opening webcam for analysis...\");\n\n camera_port = 0;\n\n camera = cv2.VideoCapture(camera_port);\n\n saver.restore(session, path);\n\n try:\n while(True):\n\n if(cam_control == False):\n\n command = input('Choose a command: ').upper();\n\n if(command == 'F'):\n serial_push(wheelchair, 'F', True);\n\n if(command == 'B'):\n serial_push(wheelchair, 'B', True);\n\n if(command == 'R'):\n serial_push(wheelchair, 'R', True);\n\n if(command == 'E'):\n serial_push(wheelchair, 'E', True);\n\n if('W' in command):\n try:\n angle = int(input('Choose an angle: '));\n\n serial_push(wheelchair, bytes([ord('W'),angle + 127]), False);\n\n except:\n print(\"Invalid angle. Must be between 0-255.\");\n\n if(command == 'C'):\n cam_control = not cam_control;\n\n if(cam_control == True):\n print(\"Running on camera.\");\n else:\n print(\"Running on command.\");\n\n serial_push(wheelchair, 'P', True);\n\n else:\n\n _, img = camera.read();\n\n webcam1 = img[0:512, 0:256];\n webcam2 = img[0:512, 232:488];\n webcam3 = img[0:512, 464:720];\n\n cv2.imwrite(\"webcam1.jpg\", webcam1);\n cv2.imwrite(\"webcam2.jpg\", webcam2);\n cv2.imwrite(\"webcam3.jpg\", webcam3);\n\n '''cv2.imshow(\"webbcam1\", webcam1);\n cv2.waitKey(1);\n cv2.imshow(\"webbcam2\", webcam2);\n cv2.waitKey(1);\n cv2.imshow(\"webbcam3\", webcam3);\n cv2.waitKey(1);'''\n\n guess = prediction.eval(feed_dict={x:[decode_image(\"webcam1.jpg\").eval(), decode_image(\"webcam2.jpg\").eval(), decode_image(\"webcam3.jpg\").eval()], mode:False});\n\n left = 100 * np.mean(guess[0]);\n center = 100 * np.mean(guess[1]);\n right = 100 * np.mean(guess[2]);\n\n if(left > thresh and center > thresh and right > thresh):\n angle = -1 * left + 1 * right;\n else:\n angle = 0;\n print(\"No watermelon.\");\n\n if(left > thresh or center > thresh or right > thresh):\n print(\"Left: {:0.3f} | Center: {:0.3f} | Right: {:0.3f}\".format(left, center, right));\n\n serial_push(wheelchair, bytes([ord('W'),angle + 127]), False);\n\n time.sleep(0.1);\n\n message = serial_pull(wheelchair);\n if(message != \"\"):\n print(message);\n except:\n serial_push(wheelchair, 'B', True);\n print(\"Exiting.\");\n sys.exit();\n", "repo_name": "fletcheaston/CSC-400-Independent-Study", "sub_path": "wheelchair.py", "file_name": "wheelchair.py", "file_ext": "py", "file_size_in_byte": 3790, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "time.sleep", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 47, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 97, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 98, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 99, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 125, "usage_type": "call"}]} +{"seq_id": "22267664278", "text": "\"\"\"Contains sklearn-style transformer classes \nfor co-ordinate data preproccessing\"\"\"\n\n\n# Disable unused arguments only for this file\n# pylint: disable=unused-argument\n\n\nimport pickle\n\nimport numpy as np\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.cluster import KMeans\n\n\nclass NearestCluster(BaseEstimator, TransformerMixin):\n \"\"\"Calulates clusters and then calculates the \n nearest cluster to each house\"\"\"\n def __init__(self, n_clusters: int) -> None:\n super().__init__()\n self.kmeans = KMeans(\n n_clusters=n_clusters,\n n_init='auto'\n )\n\n def fit(self, X, y=None):\n self.kmeans.fit(X.loc[:, 'Latitude':'Longitude'])\n return self\n\n def transform(self, X):\n predictions = self.kmeans.predict(X.loc[:, 'Latitude':'Longitude'])\n # the line below may be slow for larger datasets\n centers = np.array([self.kmeans.cluster_centers_[pred] for pred in predictions])\n X['NearestClustLat'] = centers[:, 0]\n X['NearestClustLon'] = centers[:, 1]\n return X\n\n\nclass DistToCoastLoader(BaseEstimator, TransformerMixin):\n \"\"\"This class loads data about distance to the ocean\n from a given house that has already been calculated for the\n dataset. This is to save time recalculating this data.\"\"\"\n def __init__(self, filepath: str, extra_data: bool) -> None:\n super().__init__()\n self.filepath = filepath\n self.extra_data = extra_data\n\n def fit(self, X, y=None):\n return self\n\n def transform(self, X):\n with open(self.filepath, 'rb') as pckl:\n dist_to_coast = pickle.load(pckl)\n if self.extra_data:\n X['DistToCoast'] = dist_to_coast\n else:\n X['DistToCoast'] = dist_to_coast[:X.shape[0]]\n return X\n\n\nclass DistToCity(BaseEstimator, TransformerMixin):\n \"\"\"Calculates the distance that a house is from the nearest\n city provided in `city_coords`\"\"\"\n def __init__(self, city_coords: list[np.array]) -> None:\n super().__init__()\n self.city_coords = city_coords\n self.dist_to_city = None\n\n def fit(self, X, y=None):\n distances = np.zeros([X.shape[0], len(self.city_coords)])\n for i, city_coord in enumerate(self.city_coords):\n house_coord = X.loc[:, ['Longitude', 'Latitude']].to_numpy()\n manhattan = house_coord - np.expand_dims(city_coord, axis=0)\n distances[:, i] = np.linalg.norm(manhattan, ord=2, axis=1, keepdims=True).reshape(-1)\n for i in range(len(self.city_coords) - 1):\n self.dist_to_city = np.where(\n distances[:, i] < distances[:, i + 1],\n distances[:, i],\n distances[:, i + 1]\n )\n return self\n\n def transform(self, X):\n X['DistToMajorCity'] = self.dist_to_city\n return X\n", "repo_name": "ADPriceless/kaggle_pg_s3e1", "sub_path": "data_augmentation/coords.py", "file_name": "coords.py", "file_ext": "py", "file_size_in_byte": 2886, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "sklearn.base.BaseEstimator", "line_number": 16, "usage_type": "name"}, {"api_name": "sklearn.base.TransformerMixin", "line_number": 16, "usage_type": "name"}, {"api_name": "sklearn.cluster.KMeans", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 33, "usage_type": "call"}, {"api_name": "sklearn.base.BaseEstimator", "line_number": 39, "usage_type": "name"}, {"api_name": "sklearn.base.TransformerMixin", "line_number": 39, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 53, "usage_type": "call"}, {"api_name": "sklearn.base.BaseEstimator", "line_number": 61, "usage_type": "name"}, {"api_name": "sklearn.base.TransformerMixin", "line_number": 61, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 64, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 74, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 76, "usage_type": "call"}]} +{"seq_id": "28556730949", "text": "from keras.models import Sequential,Model\r\nfrom keras.layers import Dense\r\nimport networkx as nx\r\nimport numpy as np\r\nfrom keras.wrappers.scikit_learn import KerasClassifier\r\nfrom keras import backend as K, regularizers\r\nfrom keras.utils import np_utils\r\nfrom sklearn.preprocessing import LabelEncoder\r\nimport math\r\nimport networkx as nx\r\nimport numpy as np\r\nfrom functools import reduce\r\n\r\nimport keras\r\nfrom keras import backend as K, regularizers\r\nfrom keras.models import Model\r\nfrom keras.layers import Dense, Embedding, Input, Reshape, Lambda\r\n\r\n# Loss function\r\ndef build_reconstruction_loss(beta):\r\n \"\"\"\r\n return the loss function for 2nd order proximity\r\n\r\n beta: the definition below Equation 3\"\"\"\r\n assert beta > 1\r\n\r\n def reconstruction_loss(true_y, pred_y):\r\n diff = K.square(true_y - pred_y)\r\n\r\n # borrowed from https://github.com/suanrong/SDNE/blob/master/model/sdne.py#L93\r\n weight = true_y * (beta - 1) + 1\r\n\r\n weighted_diff = diff * weight\r\n return K.mean(K.sum(weighted_diff, axis=1)) # mean square error\r\n return reconstruction_loss\r\n\r\n\r\ndef edge_wise_loss(true_y, embedding_diff):\r\n \"\"\"1st order proximity\r\n \"\"\"\r\n # true_y supposed to be None\r\n # we don't use it\r\n return K.mean(K.sum(K.square(embedding_diff), axis=1)) # mean square error\r\n\r\n\r\ng = nx.read_edgelist('dataset/karate.edgelist', create_using=nx.Graph())\r\ng = nx.convert_node_labels_to_integers(g)\r\ngraph = g\r\nN = graph.number_of_nodes()\r\nadj_mat = nx.adjacency_matrix(graph).toarray()\r\n\r\n\r\nembedding_dim = 9\r\nencode_dims = [34,20,16]\r\ndecode_dims = [16,20,34]\r\n\r\nbeta=2\r\nalpha=2\r\nl2_param=1e-3\r\n\r\nencoding_layer_dims = encode_dims\r\ndecoding_layer_dims = decode_dims\r\n\r\n#edges = np.array(list(self.graph.edges_iter()))\r\n\r\nprint(adj_mat)\r\n\r\n#SDNE Model\r\nmodel = Sequential()\r\n\r\n# Creating Encoding Layers According to Requirement\r\nfor i, dim in enumerate(encoding_layer_dims):\r\n layer = Dense(dim, kernel_initializer='normal', activation='sigmoid',kernel_regularizer=regularizers.l2(l2_param), name='encoding-layer-{}'.format(i))\r\n model.add(layer)\r\n\r\n\r\nmodel.add(Dense(embedding_dim, kernel_initializer='normal', activation='sigmoid', name='encoder'))\r\n\r\n\r\n#Creating Decoding Layers Accordinng to Requirement\r\nfor i, dim in enumerate(decoding_layer_dims):\r\n layer = Dense(dim, kernel_initializer='normal', activation='sigmoid',kernel_regularizer=regularizers.l2(l2_param), name='decoding-layer-{}'.format(i))\r\n model.add(layer)\r\n\r\nreconstruction_loss_function = build_reconstruction_loss(beta)\r\n\r\nmodel.compile(loss=reconstruction_loss_function, optimizer='adadelta', metrics=['accuracy'])\r\nmodel.fit(adj_mat,adj_mat,epochs=100)\r\n\r\nprint(\"###############################################################################################\")\r\n\r\n#Encoder Model\r\nencoder=Model(model.input, model.get_layer('encoder').output)\r\n\r\n#print(encoder.predict(adj_mat))\r\n#Save the embedding\r\nembedding = encoder.predict(adj_mat)\r\nnp.savetxt('karate.embedding2',embedding)\r\n\r\n", "repo_name": "ajanyan/SDNE", "sub_path": "sdne.py", "file_name": "sdne.py", "file_ext": "py", "file_size_in_byte": 3057, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "keras.backend.square", "line_number": 28, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 28, "usage_type": "name"}, {"api_name": "keras.backend.mean", "line_number": 34, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 34, "usage_type": "name"}, {"api_name": "keras.backend.sum", "line_number": 34, "usage_type": "call"}, {"api_name": "keras.backend.mean", "line_number": 43, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 43, "usage_type": "name"}, {"api_name": "keras.backend.sum", "line_number": 43, "usage_type": "call"}, {"api_name": "keras.backend.square", "line_number": 43, "usage_type": "call"}, {"api_name": "networkx.read_edgelist", "line_number": 46, "usage_type": "call"}, {"api_name": "networkx.Graph", "line_number": 46, "usage_type": "call"}, {"api_name": "networkx.convert_node_labels_to_integers", "line_number": 47, "usage_type": "call"}, {"api_name": "networkx.adjacency_matrix", "line_number": 50, "usage_type": "call"}, {"api_name": "keras.models.Sequential", "line_number": 69, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 73, "usage_type": "call"}, {"api_name": "keras.regularizers.l2", "line_number": 73, "usage_type": "call"}, {"api_name": "keras.regularizers", "line_number": 73, "usage_type": "name"}, {"api_name": "keras.layers.Dense", "line_number": 77, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 82, "usage_type": "call"}, {"api_name": "keras.regularizers.l2", "line_number": 82, "usage_type": "call"}, {"api_name": "keras.regularizers", "line_number": 82, "usage_type": "name"}, {"api_name": "keras.models.Model", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 98, "usage_type": "call"}]} +{"seq_id": "40118929459", "text": "import matplotlib.pyplot as plt\nimport os\nimport pandas as pd\nimport seaborn as sns\nimport numpy as np\n\nfrom math import *\nfrom typing import List\n\nCB_color_cycle = ['#377eb8', '#ff7f00', '#4daf4a',\n '#f781bf', '#a65628', '#984ea3',\n '#999999', '#e41a1c', '#dede00']\n\npath=\"intersection2/tx_2/rx_3/1.csv\"\npath=\"M4_test_all_RX-TX_on_3_2/rx_1/1.csv\"\npath=\"M3_test_shield/B_ac/3.csv\"\ndir=\"M5_test_diff_pattern/\"\ndir = \"M4_test_all_RX-TX_on_3_2/\"\n\nstart_unpressed=200\nstart_pressed=6200\navg_size=500\n\ndef simple_plot(path:str)->None:\n df=pd.read_csv(path)\n df=df.iloc[5:,:]\n ymax=df.max()[1]+100\n df.plot(x=df.columns[0],y=df.columns[1])\n plt.xlabel('time (in millis)')\n plt.ylabel('Sensor Value')\n plt.legend(['Gain 15'])\n plt.show()\n\ndef simple_plot_dir(dir:str)->None:\n paths = get_all_files(dir,'.csv')\n for path in paths:\n simple_plot(dir+'/'+path)\n\ndef all_plot_dir(dir:str)->None:\n paths = get_all_files(dir,\".csv\")\n df = pd.DataFrame()\n for i, path in enumerate(paths):\n df_f = pd.read_csv(dir+'/'+path)\n df_f = df_f.iloc[5:,:]\n if i==0:\n df['time'] = df_f['time']\n df[path[:-4]] = df_f['sensor']\n df_mean = df.loc[df['time']>2000]\n print(df_mean.describe())\n #.plot(x=df.columns[0],y=df.columns[1:])\n #plt.ylim(7000,7500)\n #plt.show()\n \n\ndef M5_plot()->None:\n dir = \"M5_test_diff_pattern/\"\n paths=['nsd/3','nsl/2','sd/3','sl/2']\n ymax=[]\n data = pd.DataFrame()\n mean ={}\n time_up = 2000\n time_down = 2000\n for path in paths:\n filename = dir+path+'.csv'\n time_pressed = get_time_pressed(filename)\n df=pd.read_csv(filename)\n df=df.iloc[5:,:]\n sensor_array = df.loc[(df['time']time_pressed-time_down)]['sensor'].array\n #df_unpressed = df.loc[(df['time']<2000) & (df['time']>1000)]\n #mean_unpressed = df_unpressed['sensor'].mean()\n #df_pressed = df.loc[(df['time']<6000) & (df['time']>3000)]\n #mean_pressed = df_pressed['sensor'].mean()\n #mean[path[:-2]]=[round(mean_unpressed),round(mean_pressed)]\n #ymax.append(df.max()[1]+100)\n if path == 'nsd/3':\n data['time'] = df['time'].loc[:len(sensor_array)+4]-time_pressed+400\n data[path[:-2].upper()] = sensor_array\n data['time'] =data['time'].div(1000)\n #data[[path[:-2].upper() for path in paths]].plot(color='red')\n data.plot(x='time',y=[path[:-2].upper() for path in paths], color=CB_color_cycle[:len(paths)+1])\n plt.xlabel('Time (in seconds)',fontsize=15)\n plt.ylabel('Sensor Value (a.u.)',fontsize=15)\n plt.xticks(fontsize=15)\n plt.yticks(fontsize=15)\n plt.legend(fontsize=15)\n plt.show()\n\ndef mean_intersection(filename:str)->float:\n df = pd.read_csv(filename)\n df = df[5:-3]\n return round(df['sensor'].mean(),1)\n\ndef means_columns(dir:str)->List[float]:\n means = []\n paths = get_all_files(dir,'.csv')\n for path in paths:\n means.append(mean_intersection(dir+path))\n return means\n\ndef means_matrix(dir:str)->np.ndarray:\n paths = os.listdir(dir)\n means = []\n for path in paths:\n subdir = dir+path+'/'\n means.append(means_columns(subdir))\n return np.array(means)\n\ndef M1_todict()->dict:\n SNR_dict = {'SNR':[],'pos':[],'Condition':[]}\n m1_dir = \"M1_test_curve\"\n pos = ['flat','d=13mm', 'd=26mm']\n conditions = os.listdir(m1_dir) #0,180,360\n for i, condition in enumerate(conditions):\n rx_dirs = os.listdir(m1_dir+'/'+condition)\n for rx in rx_dirs:\n SNR = get_SNR_dir(m1_dir+'/'+condition+'/'+rx+'/')\n SNR_dict['SNR'].extend(SNR)\n SNR_dict['Condition'].extend([pos[i]]*len(SNR))\n SNR_dict['pos'].extend([rx[0]+':'+rx[-1]]*len(SNR))\n return SNR_dict\n\ndef M1_plot()->None:\n SNR_dict = M1_todict()\n update = SNR_dict['SNR'][:10]+ [51.3] + SNR_dict['SNR'][11:18] + [51.3,50.2] + SNR_dict['SNR'][20:24] + [49] + SNR_dict['SNR'][25:]\n SNR_dict['SNR'] = update\n df_snr = pd.DataFrame(SNR_dict)\n df_n = df_snr.copy()\n df_n.loc[df_n['pos']=='3:2','SNR'] = np.nan\n sns.stripplot(df_n,x='Condition',y='SNR',hue='pos', hue_order=['5:2','3:2'], dodge=True,palette=[CB_color_cycle[1]],jitter=0.05, s=15, marker = 's', linewidth=1,edgecolor=\"gray\", size=10)\n sns.boxplot(showmeans=True,\n meanline=True,\n meanprops={'color': 'k', 'ls': '-', 'lw': 0.2},\n medianprops={'visible': False},\n whiskerprops={'visible': False},\n zorder=5,\n x=\"Condition\",\n y=\"SNR\",\n data=df_snr,\n showfliers=False,\n showbox=False,\n showcaps=False)\n df_p = df_snr.copy()\n df_p.loc[df_p['pos']=='5:2','SNR'] = np.nan\n print(df_p)\n sns.stripplot(df_p,x='Condition',y='SNR',hue='pos', hue_order=['5:2','3:2'], dodge=True,palette=[CB_color_cycle[0]],jitter=0.05, s=15, marker = 'o',linewidth=1,edgecolor=\"gray\")\n plt.ylim(1,60)\n plt.xticks(fontsize=15)\n plt.yticks(fontsize=15)\n plt.legend(fontsize=15, loc='center right', title='Intersection')\n plt.xlabel('Condition',fontsize=15)\n plt.ylabel('SNR',fontsize=15)\n plt.show()\n\ndef M4_plot()->None:\n dir = \"M4_test_all_RX-TX_on_3_2/\"\n means = means_matrix(dir)\n #df = pd.DataFrame(means,columns=os.listdir(dir))\n xticklabels = [('rx'+str(i)).upper() for i in range(1,8)]\n yticklabels = [('tx'+str(i)).upper() for i in range(1,5)]\n sns.set(style='whitegrid')\n sns.heatmap(data=means, vmin=5000, vmax=9000,annot=True,fmt='.1f',cmap='mako',xticklabels=xticklabels,yticklabels=yticklabels,annot_kws={\"fontsize\":15})#,linewidths=0.1, linecolor='white')\n plt.xticks(fontsize=20)\n plt.yticks(fontsize=20,rotation=0)\n plt.show()\n\ndef get_SNR(filename:str)->float:\n df=pd.read_csv(filename)\n df_unpressed=df.loc[(df['time']>start_unpressed) & (df['time']start_pressed) & (df['time']List[float]:\n snr_list=[]\n paths = get_all_files(dir,'.csv')\n for path in paths:\n snr=get_SNR(dir+path)\n snr_list.append(snr)\n return snr_list\n\ndef get_all_files(dir:str, format:str)->List[str]:\n paths=[]\n for file in os.listdir(dir):\n if file.endswith(format):\n paths.append(file)\n return paths\n\n\ndef SNR_gain(dir:str)->None:\n list_dir=os.listdir(dir)\n gain=0\n df_snr=pd.DataFrame(columns=['gain','snr'])\n for d in list_dir:\n if(\"gain_\" in d):\n try:\n gain=int(d.partition(\"_\")[2])\n except Exception as e:\n print(\"Error:\" +e)\n continue\n snr_dir=get_SNR_dir(dir+d+'/')\n df=pd.DataFrame(list(zip([gain]*len(snr_dir),snr_dir)),columns=['gain','snr'])\n df_snr=pd.concat([df_snr,df])\n df_snr.sort_values(by=['gain'])\n sns.set(style='whitegrid')\n sns.boxplot(x='gain',y='snr',data=df_snr)\n plt.show()\n\ndef SNR_intersection(path:str)->None:\n dirs = os.listdir(path)\n df_snr=pd.DataFrame(columns=['rx_1','rx_2','rx_3','rx_4'])\n for dir in dirs:\n subdirs=os.listdir(path+dir+'/')\n tab_means=[]\n for subdir in subdirs:\n list_snr=get_SNR_dir(path+dir+'/'+subdir+'/')\n mean=sum(list_snr)/len(list_snr)\n tab_means.append(mean)\n df=pd.DataFrame([tab_means],columns=subdirs,index=[dir])\n df_snr=pd.concat([df_snr,df])\n sns.heatmap(df_snr,vmin=0, vmax=60,annot=True)\n #df_snr.style.background_gradient(cmap='Greens')\n plt.show()\n #print(df_snr)\n\ndef get_time_pressed(filename:str, threshold:int=30)->int:\n df = pd.read_csv(filename)\n df=df[10:]\n df.reset_index(drop=True,inplace=True)\n return df.loc[df['sensor']dict:\n subdirs = os.listdir(dir+str(angle))\n sns_dic = {}\n for subdir in subdirs:\n path = dir+str(angle)+'/'+subdir+'/'\n sns_dic[subdir] = get_SNR_dir(path)\n return sns_dic\n\ndef snr_dic_curve()->dict:\n dir = 'M1_test_curve/'\n angles = os.listdir(dir)\n sns_dic = dict()\n for angle in angles:\n sns_dic[angle]=get_snr_curve(dir,angle)\n return sns_dic\n\ndef test():\n # Create a dataset\n df = sns.load_dataset(\"tips\")\n\n # Create a list of markers\n markers = [\"o\", \"s\", \"d\", \"^\", \"p\"]\n\n # Create the stripplot\n for i, (marker) in enumerate(markers):\n sns.scatterplot(x=\"day\", y=\"total_bill\", data=df, style='sex', markers=[marker], alpha = 0.5)\n plt.show()\n\n\n#simple_plot(path)\n#SNR_gain(\"data4/\")\n#SNR_gain(\"data5/\")\n#SNR_intersection(\"intersection2/\")\n#print(get_time_pressed(path))\n#dir = \"M3_test_shield/A_sc\"\n#simple_plot_dir(dir)\n#all_plot_dir(dir)\n#M5_plot()\n#M4_plot()\nM1_plot()\n# test()", "repo_name": "SensitivePen/Shield_CapacitiveTouch", "sub_path": "Experiments/Python/data_analyse.py", "file_name": "data_analyse.py", "file_ext": "py", "file_size_in_byte": 9160, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "pandas.read_csv", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 41, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 43, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 59, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 81, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 81, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 83, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 84, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 85, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 86, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 89, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 93, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 100, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 112, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 114, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 128, "usage_type": "attribute"}, {"api_name": "seaborn.stripplot", "line_number": 129, "usage_type": "call"}, {"api_name": "seaborn.boxplot", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 143, "usage_type": "attribute"}, {"api_name": "seaborn.stripplot", "line_number": 145, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 146, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 146, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 147, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 147, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 148, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 148, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 149, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 149, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 150, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 150, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 151, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 151, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 152, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 152, "usage_type": "name"}, {"api_name": "seaborn.set", "line_number": 160, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 161, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 162, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 162, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 163, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 163, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 164, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 164, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 167, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 175, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 185, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 183, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 192, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 194, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 203, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 204, "usage_type": "call"}, {"api_name": "seaborn.set", "line_number": 206, "usage_type": "call"}, {"api_name": "seaborn.boxplot", "line_number": 207, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 208, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 208, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 211, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 212, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 214, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 220, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 221, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 222, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 224, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 224, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 228, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 234, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 243, "usage_type": "call"}, {"api_name": "seaborn.load_dataset", "line_number": 251, "usage_type": "call"}, {"api_name": "seaborn.scatterplot", "line_number": 258, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 259, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 259, "usage_type": "name"}]} +{"seq_id": "29065835058", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 18 10:17:53 2019\n\n@author: mujirin|mujirin@ui.ac.id\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport datetime\n\n\ndef matrikG(list_data):\n '''\n Pembuatan matrik G\n G = [[ 0. , 0. ],\n [ 0.25 , 0.0625],\n [ 0.5 , 0.25 ],\n [ 0.75 , 0.5625],\n [ 1. , 1. ],\n [ 1.25 , 1.5625]]\n dari\n list_data = [[1, 1, 1], [2, 2, 2], ....]\n '''\n matrikG = np.array(list_data).transpose()\n return matrikG\n\n\ndef matrikM(G, d):\n '''\n Perhitungan matrix m\n G: Komponen\n d: Target\n G = [[ 0. , 0. ],\n [ 0.25 , 0.0625],\n [ 0.5 , 0.25 ],\n [ 0.75 , 0.5625],\n [ 1. , 1. ],\n [ 1.25 , 1.5625]]\n d = [[ 0. ],\n [ 0.75],\n [ 1.4 ],\n [ 1.94],\n [ 2.38],\n [-4.42]])\n '''\n # matrix Gt: G transpose\n G = np.array(G)\n Gt = G.transpose()\n\n # Inverse Gt*G\n # =============================================================================\n invGtG = np.linalg.inv(np.matmul(Gt, G))\n\n # m\n # =============================================================================\n m = np.matmul(np.matmul(invGtG, Gt), d)\n m = list(m)\n return m\n\n\ndef plot(z, T, line='o', name='gambar'):\n fig, ax = plt.subplots()\n ax.plot(z, T, line)\n ax.set(xlabel='Kedalaman (m)', ylabel='Temperatur (m)',\n title='Kedalaman vs Temperatur')\n ax.grid()\n fig.savefig(name + str(datetime.datetime.now()) + \".png\")\n plt.show()\n return None\n", "repo_name": "Muj1r1n/Metode-Inversi", "sub_path": "inversi/inversi.py", "file_name": "inversi.py", "file_ext": "py", "file_size_in_byte": 1620, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "numpy.array", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 53, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 68, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 68, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.show", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}]} +{"seq_id": "16030224091", "text": "\nfrom pyspark import SparkContext, SparkConf\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.types import *\nfrom pyspark.sql.functions import *\nimport pandas as pd\nimport os\nimport json\nimport sys\nprint(__name__)\nimport config\n\n#path = '/home/huasiyu/jintouwang_2019'\n#path = ('C:/Users/Hazewu/Desktop/spark_script/spark_script/jintouwang_2019')\nindexx = str(sys.path[0]).index('compute')\npath_d = str(sys.path[0])[:indexx] # 获取上一层路径\npath = path_d + 'resource/jintouwang_2019'\ndir_list = os.listdir(path)\nprint(path)\nprint(dir_list)\n\ndef part(line):\n lst = line.split(',')\n new_lst = []\n new_lst.append(lst[0].strip('报价'))\n date = lst[2]\n month = date.split('-')[1]\n day = date.split('-')[2]\n new_lst.append(int(month))\n new_lst.append(int(day))\n new_lst.append(float(lst[1].strip('.')))\n tup = tuple(new_lst)\n return tup\n\n\nconf = SparkConf().setAppName('2019_Fruit_Price.py').setMaster('local[*]')\nspark = SparkSession.builder.config(conf=conf).getOrCreate()\nsc = spark.sparkContext\nschema = StructType([StructField(\"type\", StringType(), False), StructField(\"month\", StringType(), False),\n StructField(\"day\", StringType(), False), StructField(\"price\", DoubleType(), False)])\n\nfor dir in dir_list:\n csv_path = 'file:///{}/{}'.format(path, dir)\n #df = spark.read.format('csv').option(\"header\", \"true\").schema(schema).load(csv_path)\n RDD = sc.textFile(csv_path)\n header = RDD.first()\n RDD = RDD.filter(lambda line : line != header)\n mappedRDD = RDD.map(part)\n df = spark.createDataFrame(mappedRDD, schema)\n df = df.sort(\"type\", \"month\", \"day\")\n df.show(10)\n '''\n prop = {}\n prop['user'] = 'root' # 表示用户名是root\n prop['password'] = '123' # 表示密码是123\n prop['driver'] = \"com.mysql.jdbc.Driver\" # 表示驱动程序是com.mysql.jdbc.Driver\n\n # 下面就可以连接数据库,采用append模式,表示追加记录到数据库dbtaobao的rebuy表中\n df.write.jdbc(\"jdbc:mysql://localhost:3306/datebase\", '2019_Fruit_Price', 'append', prop)\n '''\n prop = {}\n prop['user'] = config.user # 表示用户名是root\n prop['password'] = config.password # 表示密码是123\n prop['driver'] = \"com.mysql.jdbc.Driver\" # 表示驱动程序是com.mysql.jdbc.Driver\n\n df.write.jdbc(\"jdbc:mysql://localhost:3306/ffdbs?useUnicode=true&characterEncoding=utf-8\"\n , '2019_Fruit_Price'\n , 'append'\n , prop)", "repo_name": "YihengWang828/FruitFreedom", "sub_path": "FruitFree/compute/2019_Fruit_Price.py", "file_name": "2019_Fruit_Price.py", "file_ext": "py", "file_size_in_byte": 2507, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "sys.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "sys.path", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 18, "usage_type": "call"}, {"api_name": "pyspark.SparkConf", "line_number": 36, "usage_type": "call"}, {"api_name": "pyspark.sql.SparkSession.builder.config", "line_number": 37, "usage_type": "call"}, {"api_name": "pyspark.sql.SparkSession.builder", "line_number": 37, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession", "line_number": 37, "usage_type": "name"}, {"api_name": "config.user", "line_number": 62, "usage_type": "attribute"}, {"api_name": "config.password", "line_number": 63, "usage_type": "attribute"}]} +{"seq_id": "16171295764", "text": "# -*- coding: utf-8 -*-\n\"\"\"Installer for the fbk.policy package.\"\"\"\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\n\nlong_description = (\n open('README.rst').read()\n + '\\n' +\n 'Contributors\\n'\n '============\\n'\n + '\\n' +\n open('CONTRIBUTORS.rst').read()\n + '\\n' +\n open('CHANGES.rst').read()\n + '\\n')\n\n\nsetup(\n name='fbk.policy',\n version='0.1',\n description=\"Policy for Kinesiology Belgium website\",\n long_description=long_description,\n # Get more from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Environment :: Web Environment\",\n \"Framework :: Plone\",\n \"Framework :: Plone :: 4.3.6\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2.7\",\n ],\n keywords='Python Plone',\n author='Martin Peeters',\n author_email='martin.peeters@affinitic.be',\n url='http://github.com/affinitic/fbk.policy',\n license='GPL',\n packages=find_packages('src', exclude=['ez_setup']),\n namespace_packages=['fbk'],\n package_dir={'': 'src'},\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'collective.contact.core',\n 'collective.contact.membrane',\n 'collective.geotransform',\n 'collective.z3cform.datagridfield',\n 'cpskin.menu',\n 'eea.facetednavigation',\n 'fbk.theme',\n 'five.grok',\n 'plone.api',\n 'plone.app.contenttypes',\n 'plone.app.dexterity',\n 'plone.app.multilingual',\n 'plone.autoform',\n 'plone.z3ctable',\n 'python-dateutil',\n 'setuptools',\n 'z3c.jbot',\n 'z3c.table',\n 'z3c.unconfigure',\n ],\n extras_require={\n 'test': [\n 'plone.app.testing',\n 'plone.app.contenttypes',\n 'plone.app.robotframework[debug]',\n ],\n },\n entry_points=\"\"\"\n # -*- Entry points: -*-\n [z3c.autoinclude.plugin]\n target = plone\n \"\"\",\n)\n", "repo_name": "affinitic/fbk.policy", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 1995, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "setuptools.setup", "line_number": 20, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 38, "usage_type": "call"}]} +{"seq_id": "31792911238", "text": "import gym\n\n\ndef create(env_name):\n env = gym.make(env_name)\n env.reset()\n for _ in range(1000):\n env.render()\n env.step(env.action_space.sample())\n\n\ndef create_advanced(env_name):\n env = gym.make(env_name)\n for i_episode in range(20):\n observation = env.reset()\n for t in range(100):\n env.render()\n print(observation)\n action = env.action_space.sample()\n observation, reward, done, info = env.step(action)\n if done:\n print(\"Episode finished after {} timesteps\".format(t + 1))\n break\n\n\nif __name__ == \"__main__\":\n name1 = 'CartPole-v0'\n name2 = 'MountainCar-v0'\n name3 = 'MsPacman-v0'\n\n # create(name2)\n create_advanced(name1)\n", "repo_name": "chenkedi/machine-learning", "sub_path": "learn/gym/first_env.py", "file_name": "first_env.py", "file_ext": "py", "file_size_in_byte": 770, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "gym.make", "line_number": 5, "usage_type": "call"}, {"api_name": "gym.make", "line_number": 13, "usage_type": "call"}]} +{"seq_id": "28869750283", "text": "\"\"\"\nExample of running GROMACS with lithops\n\"\"\"\n\nimport lithops\nimport os\nimport zipfile\nimport time\nimport wget\nimport json\n\ntemp_dir = '/tmp'\niterdata = [1]\n\n\ndef sh_cmd_executor(x, param1, ibm_cos):\n lithops_config = json.loads(os.environ['LITHOPS_CONFIG'])\n bucket = lithops_config['lithops']['storage_bucket']\n print (bucket)\n print (param1)\n filename = 'benchMEM.zip'\n outfile = os.path.join(temp_dir, filename)\n\n if not os.path.isfile(filename):\n filename = wget.download('https://www.mpibpc.mpg.de/15101317/benchMEM.zip', out=outfile)\n print(filename, \"was downloaded\")\n with zipfile.ZipFile(outfile, 'r') as zip_ref:\n print('Extracting file to %s' % temp_dir)\n zip_ref.extractall(temp_dir)\n else:\n print(filename, \" already exists\")\n\n os.chdir(temp_dir)\n cmd = \"/usr/local/gromacs/bin/gmx mdrun -nt 4 -s benchMEM.tpr -nsteps 1000 -resethway\"\n\n st = time.time()\n import subprocess\n subprocess.call(cmd, shell=True)\n run_time = time.time() - st\n\n # upload results to IBM COS\n res = ['confout.gro', 'ener.edr', 'md.log', 'state.cpt']\n for name in res:\n f = open(os.path.join(temp_dir, name), \"rb\")\n ibm_cos.put_object(Bucket=bucket, Key=os.path.join('gmx-mem', name), Body=f)\n\n with open('md.log', 'r') as file:\n data = file.read()\n\n return {'run_time': run_time, 'md_log': data}\n\n\nif __name__ == '__main__':\n # Example of using benchMEM from https://www.mpibpc.mpg.de/grubmueller/bench\n\n param1 = 'param1 example'\n\n total_start = time.time()\n fexec = lithops.FunctionExecutor(runtime='ecenurarslan/gromacs-runtime:0.1', runtime_memory=2048)\n fexec.map(sh_cmd_executor, iterdata, extra_args=(param1,))\n res = fexec.get_result()\n fexec.clean()\n\n print (\"GROMACS execution time {}\".format(res[0]['run_time']))\n print (\"Total execution time {}\".format(time.time()-total_start))\n print (res[0]['md_log'])\n", "repo_name": "lithops-cloud/applications", "sub_path": "gromacs/gromacs.py", "file_name": "gromacs.py", "file_ext": "py", "file_size_in_byte": 1966, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "20", "api": [{"api_name": "json.loads", "line_number": 17, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "wget.download", "line_number": 25, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 27, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 33, "usage_type": "call"}, {"api_name": "time.time", "line_number": 36, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 38, "usage_type": "call"}, {"api_name": "time.time", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 58, "usage_type": "call"}, {"api_name": "lithops.FunctionExecutor", "line_number": 59, "usage_type": "call"}, {"api_name": "time.time", "line_number": 65, "usage_type": "call"}]} +{"seq_id": "40497302186", "text": "import unittest\nfrom time import sleep\nfrom datetime import date\nfrom termcolor import colored\nfrom src.root import prompt_to_disable_network, prompt_to_enable_network_and_setup\nfrom src.utility import SLEEP_INTERVAL, browser, close_modal, pick_random_dropdown_item, clear_inputs, click_update_button\nfrom src.helper import get_random_meter, get_back_previously_updated_meter\n\n\nclass MeterUpdateTest(unittest.TestCase):\n @staticmethod\n def test_1_no_network():\n print(colored('Running: test_1_no_network - estimate: 27s', 'yellow'))\n prompt_to_disable_network()\n\n for i in range(3):\n print(colored('\\trandom meter ' + str(i + 1), 'magenta'))\n get_random_meter()\n click_update_button()\n sleep(9+SLEEP_INTERVAL)\n\n confirmation = browser.switch_to_alert()\n\n print(colored('\\ttest_1_no_network: confirmation dialog - asserting...', 'blue'))\n assert \"Error occurred while updating meter\" in confirmation.text\n\n confirmation.accept()\n close_modal()\n\n print(colored('\\ttest_1_no_network: passed.', 'cyan'))\n prompt_to_enable_network_and_setup(browser, 'Factory/ManageMeter')\n\n @staticmethod\n def test_2_missing_primary_key():\n print(colored('Running: test_2_missing_primary_key - estimate: 27s', 'yellow'))\n\n for i in range(3):\n print(colored('\\trandom meter ' + str(i + 1), 'magenta'))\n get_random_meter()\n clear_inputs(['serial-number'], 'id')\n click_update_button()\n\n confirmation = browser.switch_to_alert()\n\n print(colored('\\ttest_2_missing_primary_key: confirmation dialog - asserting...', 'blue'))\n assert \"Error occurred while updating meter\" in confirmation.text\n\n confirmation.accept()\n close_modal()\n\n print(colored('\\ttest_2_missing_primary_key: passed.', 'cyan'))\n\n def test_3_device_model(self):\n print(colored('Running: test_3_device_model - estimate: 57s', 'yellow'))\n\n for i in range(3):\n print(colored('\\trandom meter ' + str(i + 1), 'magenta'))\n updated_serial = get_random_meter()\n random_model_value = pick_random_dropdown_item('device-model')\n click_update_button()\n\n print(colored('\\ttest_3_device_model: confirm update - asserting...', 'blue'))\n assert \"The Meter with Serial No. \" + updated_serial + \" has been updated successfully.\" in browser.page_source\n\n get_back_previously_updated_meter(updated_serial)\n\n updated_device_model = random_model_value # browser.find_element_by_id('device-model').get_attribute('innerHTML')\n print(colored('\\ttest_3_device_model: device models selected - asserting...', 'blue'))\n self.assertEqual(random_model_value, updated_device_model)\n\n close_modal()\n\n print(colored('\\ttest_3_device_model: passed.', 'cyan'))\n\n @staticmethod\n def test_4_dates():\n print(colored('Running: test_4_dates - estimate: 57s', 'yellow'))\n\n for i in range(3):\n print(colored('\\trandom meter ' + str(i + 1), 'magenta'))\n updated_serial = get_random_meter()\n\n installed_on_input = browser.find_element_by_id('installed-on')\n activated_on_input = browser.find_element_by_id('activated-on')\n\n installed_on_input.send_keys(date.today().strftime(\"%d/%m/%Y\"))\n activated_on_input.send_keys(date.today().strftime(\"%d/%m/%Y\"))\n\n sleep(SLEEP_INTERVAL)\n click_update_button()\n\n print(colored('\\ttest_4_dates: confirm delete - asserting...', 'blue'))\n assert \"The Meter with Serial No. \" + updated_serial + \" has been updated successfully.\" in browser.page_source\n\n # get_back_previously_updated_meter(updated_serial)\n #\n # new_installed_on = browser.find_element_by_id('installed-on').get_property('value')\n # new_activated_on = browser.find_element_by_id('activated-on').get_property('value')\n #\n # print(colored('\\ttest_4_dates: is dates correct - asserting...', 'blue'))\n # self.assertEqual(new_installed_on, date.today().strftime(\"%d/%m/%Y\"))\n # self.assertEqual(new_activated_on, date.today().strftime(\"%d/%m/%Y\"))\n #\n # close_modal()\n\n print(colored('\\ttest_4_dates: passed.', 'cyan'))\n\n @staticmethod\n def test_5_active_switch():\n print(colored('Running: test_5_active_switch - estimate: 57s', 'yellow'))\n\n for i in range(3):\n print(colored('\\trandom meter ' + str(i + 1), 'magenta'))\n updated_serial = get_random_meter()\n\n active_switch = browser.find_element_by_id('is-active')\n active_switch.click()\n sleep(SLEEP_INTERVAL)\n click_update_button()\n\n # the app need fix: active vs delete\n\n @staticmethod\n def test_6_input_validations():\n print(colored('Running: test_6_input_validations - estimate: 57s', 'yellow'))\n\n for i in range(3):\n print(colored('\\trandom meter ' + str(i + 1), 'magenta'))\n updated_serial = get_random_meter()\n\n # the app need update: verify inputs\n\n\nif __name__ == '__main__':\n runMeterUpdateTest = MeterUpdateTest()\n print(colored('MeterUpdateTest - ' + str(runMeterUpdateTest.countTestCases()) + ' tests in update meter.', 'green'))\n runMeterUpdateTest.test_1_no_network()\n runMeterUpdateTest.test_2_missing_primary_key()\n runMeterUpdateTest.test_3_device_model()\n runMeterUpdateTest.test_4_dates()\n # runMeterUpdateTest.test_5_active_switch()\n # runMeterUpdateTest.test_6_input_validations()\n", "repo_name": "jaynguyen89/TestAutomation-OOPy", "sub_path": "src/meter/meter_update.py", "file_name": "meter_update.py", "file_ext": "py", "file_size_in_byte": 5771, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "unittest.TestCase", "line_number": 10, "usage_type": "attribute"}, {"api_name": "termcolor.colored", "line_number": 13, "usage_type": "call"}, {"api_name": "src.root.prompt_to_disable_network", "line_number": 14, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 17, "usage_type": "call"}, {"api_name": "src.helper.get_random_meter", "line_number": 18, "usage_type": "call"}, {"api_name": "src.utility.click_update_button", "line_number": 19, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 20, "usage_type": "call"}, {"api_name": "src.utility.SLEEP_INTERVAL", "line_number": 20, "usage_type": "name"}, {"api_name": "src.utility.browser.switch_to_alert", "line_number": 22, "usage_type": "call"}, {"api_name": "src.utility.browser", "line_number": 22, "usage_type": "name"}, {"api_name": "termcolor.colored", "line_number": 24, "usage_type": "call"}, {"api_name": "src.utility.close_modal", "line_number": 28, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 30, "usage_type": "call"}, {"api_name": "src.root.prompt_to_enable_network_and_setup", "line_number": 31, "usage_type": "call"}, {"api_name": "src.utility.browser", "line_number": 31, "usage_type": "argument"}, {"api_name": "termcolor.colored", "line_number": 35, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 38, "usage_type": "call"}, {"api_name": "src.helper.get_random_meter", "line_number": 39, "usage_type": "call"}, {"api_name": "src.utility.clear_inputs", "line_number": 40, "usage_type": "call"}, {"api_name": "src.utility.click_update_button", "line_number": 41, "usage_type": "call"}, {"api_name": "src.utility.browser.switch_to_alert", "line_number": 43, "usage_type": "call"}, {"api_name": "src.utility.browser", "line_number": 43, "usage_type": "name"}, {"api_name": "termcolor.colored", "line_number": 45, "usage_type": "call"}, {"api_name": "src.utility.close_modal", "line_number": 49, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 51, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 54, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 57, "usage_type": "call"}, {"api_name": "src.helper.get_random_meter", "line_number": 58, "usage_type": "call"}, {"api_name": "src.utility.pick_random_dropdown_item", "line_number": 59, "usage_type": "call"}, {"api_name": "src.utility.click_update_button", "line_number": 60, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 62, "usage_type": "call"}, {"api_name": "src.utility.browser.page_source", "line_number": 63, "usage_type": "attribute"}, {"api_name": "src.utility.browser", "line_number": 63, "usage_type": "name"}, {"api_name": "src.helper.get_back_previously_updated_meter", "line_number": 65, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 68, "usage_type": "call"}, {"api_name": "src.utility.close_modal", "line_number": 71, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 73, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 77, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 80, "usage_type": "call"}, {"api_name": "src.helper.get_random_meter", "line_number": 81, "usage_type": "call"}, {"api_name": "src.utility.browser.find_element_by_id", "line_number": 83, "usage_type": "call"}, {"api_name": "src.utility.browser", "line_number": 83, "usage_type": "name"}, {"api_name": "src.utility.browser.find_element_by_id", "line_number": 84, "usage_type": "call"}, {"api_name": "src.utility.browser", "line_number": 84, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 86, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 86, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 87, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 87, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 89, "usage_type": "call"}, {"api_name": "src.utility.SLEEP_INTERVAL", "line_number": 89, "usage_type": "argument"}, {"api_name": "src.utility.click_update_button", "line_number": 90, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 92, "usage_type": "call"}, {"api_name": "src.utility.browser.page_source", "line_number": 93, "usage_type": "attribute"}, {"api_name": "src.utility.browser", "line_number": 93, "usage_type": "name"}, {"api_name": "termcolor.colored", "line_number": 106, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 110, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 113, "usage_type": "call"}, {"api_name": "src.helper.get_random_meter", "line_number": 114, "usage_type": "call"}, {"api_name": "src.utility.browser.find_element_by_id", "line_number": 116, "usage_type": "call"}, {"api_name": "src.utility.browser", "line_number": 116, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 118, "usage_type": "call"}, {"api_name": "src.utility.SLEEP_INTERVAL", "line_number": 118, "usage_type": "argument"}, {"api_name": "src.utility.click_update_button", "line_number": 119, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 125, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 128, "usage_type": "call"}, {"api_name": "src.helper.get_random_meter", "line_number": 129, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 136, "usage_type": "call"}]} +{"seq_id": "72991115569", "text": "# import the following dependencies\nimport json\nimport time\nfrom web3 import Web3\nfrom web3.contract import Contract\nimport asyncio\n\n# add your blockchain connection information\ninfura_url = 'https://mainnet.infura.io/v3/584fdf9b4a15422fa39b2b0cad4f5197'\nweb3 = Web3(Web3.HTTPProvider(infura_url))\n\nPAIR_ADDR = web3.toChecksumAddress(\"0xa478c2975ab1ea89e8196811f51a7b7ade33eb11\")\nPAIR_NAME = \"WETH/USDT\"\nWETH_ADDR = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'\nUSDT_ADDR = '0xdac17f958d2ee523a2206206994597c13d831ec7'\nINTERVAL = 1000\n\n# uniswap address and abi\nuniswap_router = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D'\nuniswap_factory = '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f'\nuniswap_pair_str = open('../abi/IUniswapV2Pair.json')\nuniswap_pair_abi = json.load(uniswap_pair_str)\npair_contract: Contract = web3.eth.contract(address=PAIR_ADDR, abi=uniswap_pair_abi['abi'])\n\ndef main():\n \n token0reserve, token1reserve, _ = pair_contract.functions.getReserves().call()\n print(token0reserve, token1reserve)\n token0reserve = float(token0reserve)/(10**18)\n token1reserve = float(token1reserve)/(10**18)\n constant_product = token0reserve*token1reserve\n \n new_token1_reserve = constant_product/token0reserve\n print(new_token1_reserve)\n token1out = token1reserve-new_token1_reserve\n print(token1out)\n\nif __name__ == \"__main__\":\n for i in range(10):\n main()\n time.sleep(15)", "repo_name": "dipespandey/blockchain-analysis", "sub_path": "python/uniswapV2/price_by_reserves.py", "file_name": "price_by_reserves.py", "file_ext": "py", "file_size_in_byte": 1421, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "web3.Web3", "line_number": 10, "usage_type": "call"}, {"api_name": "web3.Web3.HTTPProvider", "line_number": 10, "usage_type": "call"}, {"api_name": "web3.toChecksumAddress", "line_number": 12, "usage_type": "call"}, {"api_name": "json.load", "line_number": 22, "usage_type": "call"}, {"api_name": "web3.contract.Contract", "line_number": 23, "usage_type": "name"}, {"api_name": "web3.eth.contract", "line_number": 23, "usage_type": "call"}, {"api_name": "web3.eth", "line_number": 23, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 41, "usage_type": "call"}]} +{"seq_id": "30542098987", "text": "import argparse\nimport random\nfrom tqdm import tqdm\n\n\ndef read_words(filepath):\n with open(filepath, 'r', encoding='utf-8') as fin:\n return [l.strip() for l in fin.readlines()]\n\n\ndef generate_title(adjectives, nouns, verbs):\n return random.choice(adjectives) + ' ' + random.choice(nouns) + ' ' + random.choice(verbs) + 's'\n\n\ndef generate_iswc():\n return 'T' + ''.join([str(random.randint(0, 9)) for _ in range(11)])\n\n\ndef generate_work_with_duplicates(adjectives, nouns, verbs, contributors):\n n_duplicates = random.randint(1, 10)\n result = []\n title = generate_title(adjectives, nouns, verbs)\n iswc = generate_iswc()\n work_contributors = list(set(random.choices(contributors, k=random.randint(1, 10))))\n for _ in range(n_duplicates):\n record_contruibutors = set(random.choices(work_contributors, k=random.randint(1, len(work_contributors))))\n record_iswc = iswc\n if random.random() > 0.5:\n record_iswc = ''\n result.append((title, '|'.join(record_contruibutors), record_iswc))\n return set(result)\n\n\ndef generate_contributors(N):\n boy_names = read_words('words_lists/boy_names.txt')\n girl_names = read_words('words_lists/girl_names.txt')\n surnames = read_words('words_lists/surnames.txt')\n result = []\n for _ in range(N):\n if random.random() > 0.5:\n names = boy_names\n else:\n names = girl_names\n name = random.choices(names, k=2)\n surname = random.choice(surnames)\n result.append(' '.join([name[0], name[1], surname]))\n return result\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Generates works metadata\")\n parser.add_argument(\"-n\", type=int, help=\"Number of works to generate\")\n parser.add_argument(\"-s\", '--shuffle', action='store_true', help=\"If results should be shuffled\")\n parser.add_argument(\"output\", help=\"out file\")\n\n args = parser.parse_args()\n N = args.n\n filepath = args.output\n shuffling = args.shuffle\n\n adjectives = read_words('words_lists/words_adj.txt')\n nouns = read_words('words_lists/words_noun.txt')\n verbs = read_words('words_lists/words_verbs.txt')\n contributors = generate_contributors(max(1, N // 5))\n\n result = []\n with tqdm(total=N) as pbar:\n while len(result) < N:\n work = generate_work_with_duplicates(adjectives, nouns, verbs, contributors)\n result += work\n pbar.update(len(work))\n result = result[:N]\n if shuffling:\n random.shuffle(result)\n with open(filepath, 'w', encoding='utf-8') as fout:\n print('title', 'contributors', 'iswc', sep=',', file=fout)\n for line in result:\n print(*line, sep=',', file=fout)\n", "repo_name": "VukW/bmat", "sub_path": "data/generate_test_data.py", "file_name": "generate_test_data.py", "file_ext": "py", "file_size_in_byte": 2744, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "random.choice", "line_number": 12, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 16, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 20, "usage_type": "call"}, {"api_name": "random.choices", "line_number": 24, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 24, "usage_type": "call"}, {"api_name": "random.choices", "line_number": 26, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 26, "usage_type": "call"}, {"api_name": "random.random", "line_number": 28, "usage_type": "call"}, {"api_name": "random.random", "line_number": 40, "usage_type": "call"}, {"api_name": "random.choices", "line_number": 44, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 45, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 51, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 67, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 74, "usage_type": "call"}]} +{"seq_id": "74908212208", "text": "import numpy as np\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\nfrom flask import Flask, jsonify\n# engine = create_engine('sqlite:////var/www/homepage/blog.db?check_same_thread=False')\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite?check_same_thread=False\")\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)\n\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n\nsession = Session(engine)\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef welcome():\n return (\n f\"Welcome to the Climate App API!
    \"\n f\"Available Routes:
    \"\n f\"/api/v1.0/precipitation
    \"\n f\"/api/v1.0/stations
    \"\n f\"/api/v1.0/tobs
    \"\n f\"
    \"\n f\"/api/v1.0/single_date/
    \"\n f\"
    \"\n f\"Enter a date in the format YYYY-MM-DD.
    \" \n f\"For example: /api/v1.0/start_date/2012-01-01
    \"\n f\"
    \"\n f\"/api/v1.0/date_range/
    \"\n f\"
    \"\n f\"Enter a starting date followed by / and an ending date.
    \"\n f\"For example: /api/v1.0/date_range/2012-01-01/2014-12-31\"\n )\n\n@app.route(\"/api/v1.0/precipitation\")\ndef precipitation():\n precipitation = []\n results = session.query(Measurement.date, Measurement.prcp).\\\n filter(Measurement.date >= \"2016-08-23\").all()\n for row in results:\n precipitation.append({row[0]:row[1]})\n return jsonify(precipitation) \n\n@app.route(\"/api/v1.0/stations\")\ndef stations():\n stations = []\n results = session.query(Measurement.station,).group_by(Measurement.station)\\\n .order_by(Measurement.station).all()\n for row in results:\n stations.append(row) \n return jsonify(stations) \n\n@app.route(\"/api/v1.0/tobs\")\ndef temp_observations():\n temp = []\n results = session.query(Measurement.date, Measurement.tobs).\\\n filter(Measurement.date >= \"2016-08-23\").all()\n for row in results:\n temp.append({row[0]:row[1]})\n return jsonify(temp) \n\n@app.route(\"/api/v1.0/single_date/\")\ndef start_date(start_date):\n results = session.query(func.min(Measurement.tobs),func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start_date).all()\n if start_date <= \"2017-08-23\" and start_date >= \"2010-01-01\": \n return jsonify(results) \n\n return jsonify({\"error\": f\"The date {start_date} isn't in the dataset. The dataset begins at 2010-01-01 and ends at 2017-08-23. Please enter a valid date.\"}), 404\n\n\n@app.route(\"/api/v1.0/date_range//\")\ndef range(range_start, range_end):\n results = session.query(func.min(Measurement.tobs),func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= range_start).filter(Measurement.date <= range_end).all()\n if range_start >= \"2010-01-01\" and range_start <= \"2017-08-23\" and range_end <= \"2017-08-23\" and range_end >= \"2010-01-01\" and range_start <= range_end and range_end >= range_start: \n return jsonify(results) \n\n return jsonify({\"error\": f\"A value entered isn't in the dataset or start date is greater than end date. The dataset begins at 2010-01-01 and ends at 2017-08-23. Please enter valid dates.\"}), 404\n\nif __name__ == \"__main__\":\n app.run(debug=True) ", "repo_name": "kmclewis/Advanced-Data-Storage-Retrieval", "sub_path": "flask_api.py", "file_name": "flask_api.py", "file_ext": "py", "file_size_in_byte": 3404, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "sqlalchemy.create_engine", "line_number": 8, "usage_type": "call"}, {"api_name": "sqlalchemy.ext.automap.automap_base", "line_number": 10, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 17, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 19, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 49, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 58, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 67, "usage_type": "call"}, {"api_name": "sqlalchemy.func.min", "line_number": 71, "usage_type": "call"}, {"api_name": "sqlalchemy.func", "line_number": 71, "usage_type": "name"}, {"api_name": "sqlalchemy.func.avg", "line_number": 71, "usage_type": "call"}, {"api_name": "sqlalchemy.func.max", "line_number": 71, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 74, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 76, "usage_type": "call"}, {"api_name": "sqlalchemy.func.min", "line_number": 81, "usage_type": "call"}, {"api_name": "sqlalchemy.func", "line_number": 81, "usage_type": "name"}, {"api_name": "sqlalchemy.func.avg", "line_number": 81, "usage_type": "call"}, {"api_name": "sqlalchemy.func.max", "line_number": 81, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 84, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 86, "usage_type": "call"}]} +{"seq_id": "41599962604", "text": "import os\nimport json\nimport librosa\nimport numpy as np\nfrom sklearn import preprocessing\n\ndef amplitude_envelope(signal, frame_size= 1024, hop_length = 512):\n amplitude_envelope = []\n #calculate AE for each frame\n for i in range(0, len(signal), hop_length):\n current_frame_amplitude_envelope = max(signal[i:i+frame_size])\n amplitude_envelope.append(current_frame_amplitude_envelope)\n\n return np.array(amplitude_envelope)\n\ndef create_normalized_envelope(signal):\n return preprocessing.MinMaxScaler().fit_transform(np.array(signal).reshape(-1,1)).reshape(1,-1)[0]\n\ndef stretch_sample(array, new_length):\n original_array = array\n old_indices = np.arange(len(original_array))\n new_indices = np.linspace(0, len(original_array) - 1, new_length)\n expanded_array = np.interp(new_indices, old_indices, original_array)\n return expanded_array\n\ndef ae_per_time_windows(amplitude_envelope, sr, time_window = 1):\n activations = []\n for i in range(0, len(amplitude_envelope), int(sr * time_window)):\n activations.append(max(amplitude_envelope[i: int(i + sr * time_window)]))\n return activations\n\ndef process_activations(signal, sr, time_window = 1):\n \n ae = amplitude_envelope(signal)\n normalized_envelope = create_normalized_envelope(ae)\n stretched_envelope = stretch_sample(normalized_envelope, len(signal))\n activations = ae_per_time_windows(stretched_envelope, sr, time_window)\n\n return activations\n\ndef calculate_mfccs(signal, sr, n_mfcc = 13, n_fft = 2048, hop_length = 512):\n mfccs = librosa.feature.mfcc(signal, sr, n_fft = n_fft, hop_length = hop_length, n_mfcc = n_mfcc)\n return mfccs.T\n\n\ndef process_mfccs(signal, sr, time_window = 1):\n mfccs = []\n for i in range(0, len(signal), int(sr * time_window)):\n mfccs.append(calculate_mfccs(signal[i: int(i + sr * time_window)], sr).tolist())\n return mfccs\n\n\n\ndef main(output_file, mixture_path, drums_path, bass_path, rest_path, vocals_path):\n\n song_names = [arquivo for arquivo in os.listdir(mixture_path) if os.path.isfile(os.path.join(mixture_path, arquivo))]; song_names.sort()\n \n drums_activation = []\n bass_activation = []\n rest_activation = []\n vocals_activation = []\n\n mfccs = []\n i = 0\n for song_path in song_names:\n print(f\"Processing song {i + 1} of {len(song_names)}\")\n \n # calculate activations for each stem\n drums_signal, sr = librosa.load(drums_path + song_path)\n drums_activation += list(process_activations(drums_signal, sr))\n\n bass_signal, _ = librosa.load(bass_path + song_path)\n bass_activation += list(process_activations(bass_signal, sr))\n \n rest_signal, _ = librosa.load(rest_path + song_path)\n rest_activation += list(process_activations(rest_signal, sr))\n\n vocals_signal, _ = librosa.load(vocals_path + song_path)\n vocals_activation += list(process_activations(vocals_signal, sr))\n\n # calculate mfccs for each frame\n mixture_signal, sr = librosa.load(mixture_path + song_path)\n mfccs.append(process_mfccs(mixture_signal ,sr))\n i+=1\n\n activations = np.array([drums_activation, bass_activation, rest_activation, vocals_activation]).T.tolist()\n \n mfccs_agrregated = []\n \n for m in mfccs:\n mfccs_agrregated+= m\n\n data = {\n \"targets\": [\"drums\", \"bass\", \"rest\", \"vocals\"],\n \"activations\" : activations,\n \"mfccs\": mfccs_agrregated\n }\n\n with open(output_file, 'w') as fp:\n json.dump(data, fp, indent=4)\n\nif(__name__ == \"__main__\"):\n type_ = \"validation\"\n\n main(\n f\"data_{type_}.json\",\n f\"full_dataset_wav/{type_}/mixture/\",\n f\"full_dataset_wav/{type_}/drums/\",\n f\"full_dataset_wav/{type_}/bass/\" ,\n f\"full_dataset_wav/{type_}/rest/\",\n f\"full_dataset_wav/{type_}/vocals/\"\n )\n\n", "repo_name": "yvson18/instrument_activity_detection", "sub_path": "preprocessing.py", "file_name": "preprocessing.py", "file_ext": "py", "file_size_in_byte": 3883, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "numpy.array", "line_number": 14, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.MinMaxScaler", "line_number": 17, "usage_type": "call"}, {"api_name": "sklearn.preprocessing", "line_number": 17, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.interp", "line_number": 23, "usage_type": "call"}, {"api_name": "librosa.feature.mfcc", "line_number": 42, "usage_type": "call"}, {"api_name": "librosa.feature", "line_number": 42, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path", "line_number": 56, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 56, "usage_type": "call"}, {"api_name": "librosa.load", "line_number": 69, "usage_type": "call"}, {"api_name": "librosa.load", "line_number": 72, "usage_type": "call"}, {"api_name": "librosa.load", "line_number": 75, "usage_type": "call"}, {"api_name": "librosa.load", "line_number": 78, "usage_type": "call"}, {"api_name": "librosa.load", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 86, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 100, "usage_type": "call"}]} +{"seq_id": "6583148708", "text": "import asyncio\nimport datetime\nimport os\nimport time\nfrom threading import Lock\nfrom typing import List, Tuple, Dict\n\nfrom jinja2 import Template\nfrom loguru import logger\n\nfrom goodguy.pb import crawl_service_pb2\nfrom goodguy.service.crawl import get_recent_contest\nfrom goodguy.timer.scheduler import scheduler\nfrom goodguy.util.get_html_from_mjml import get_html_from_mjml\nfrom goodguy.util.const import PLATFORM_ALL\nfrom goodguy.util.send_email import send_all_email\nfrom goodguy.util.timestamp_to_date_string import timestamp_to_date_string, duration_to_string\n\n\n# 获取email内容\ndef get_contest_email(cts: List[Tuple[str, crawl_service_pb2.RecentContest]]) -> Tuple[str, str]:\n def get_email_object(pf: str, c: crawl_service_pb2.RecentContest, **kwargs) -> Dict[str, str]:\n start_dt = datetime.datetime.fromtimestamp(c.timestamp)\n end_dt: datetime.datetime = start_dt + datetime.timedelta(seconds=c.duration)\n t1, t2 = '%02d' % start_dt.hour, '%02d' % start_dt.minute\n t3, t4 = '%02d' % end_dt.hour, '%02d' % end_dt.minute\n if start_dt.date() != end_dt.date():\n t1 = str(start_dt.date()) + ' ' + t1\n t3 = str(end_dt.date()) + ' ' + t3\n return {\n **kwargs,\n \"name\": c.name,\n \"url\": c.url,\n \"start\": timestamp_to_date_string(c.timestamp),\n \"end\": timestamp_to_date_string(end_dt.timestamp()),\n \"t1\": t1,\n \"t2\": t2,\n \"t3\": t3,\n \"t4\": t4,\n \"platform\": pf,\n \"duration\": duration_to_string(c.duration),\n }\n\n path = os.path.dirname(os.path.abspath(__file__))\n with open(os.path.join(path, 'contest_email.jinja2'), 'r', encoding='utf-8') as file:\n e = file.read()\n template = Template(e)\n urgent = []\n common = []\n not_urgent = []\n now = time.time()\n for pf, c in cts:\n # 一天内的比赛\n if now - 60 * 60 - 10 < c.timestamp < now + 60 * 60 + 10:\n urgent.append(get_email_object(pf, c))\n elif c.timestamp < now + 60 * 60 * 24 + 10:\n common.append(get_email_object(pf, c))\n elif c.timestamp >= now + 60 * 60 * 24 + 10:\n not_urgent.append(get_email_object(pf, c))\n mjml = template.render({\n \"urgent\": urgent,\n \"common\": common,\n \"not_urgent\": not_urgent,\n })\n html = get_html_from_mjml(mjml)\n return f'GoodGuy - 最近比赛提醒({len(cts)}条)', html\n\n\n_LAST_SEND = 0\n_LAST_SEND_LOCK = Lock()\n\n\n# 定时任务\ndef remind_email_sender() -> None:\n async def crawl_jobs():\n async def crawl_job(platform: str) -> Tuple[str, crawl_service_pb2.RecentContest]:\n return platform, get_recent_contest(platform)\n\n tasks = [crawl_job(pf) for pf in PLATFORM_ALL]\n return await asyncio.gather(*tasks)\n\n global _LAST_SEND, _LAST_SEND_LOCK\n rsp = asyncio.run(crawl_jobs())\n ok = False\n cts = []\n now = time.time()\n # 遍历所有比赛\n for pf, rc in rsp:\n for c in rc.recent_contest:\n # 结束时间大于当前时间才可以被写进邮件中\n if c.timestamp + c.duration >= time.time():\n cts.append((pf, c))\n # 有一场比赛是在接下来一个小时内开始才写进邮件中\n if now <= c.timestamp <= now + 60 * 60 + 10:\n ok = True\n if len(cts) == 0 or not ok:\n return\n cts.sort(key=lambda x: x[1].timestamp)\n ok = False\n # 12小时内没有发送过邮件才可再发一次邮件\n with _LAST_SEND_LOCK:\n if _LAST_SEND + 60 * 60 * 12 - 10 < now:\n ok = True\n _LAST_SEND = now\n if ok:\n title, text = get_contest_email(cts)\n logger.debug(text)\n send_all_email('html', title, text)\n\n\ndef send_contest_remind_email(ts: int) -> None:\n # 在时间戳ts时添加定时任务\n dt = datetime.datetime.fromtimestamp(ts)\n scheduler().add_job(\n remind_email_sender,\n trigger='date',\n args=(),\n run_date=dt,\n )\n\n\nif __name__ == '__main__':\n # logging.getLogger().setLevel(logging.DEBUG)\n remind_email_sender()\n", "repo_name": "goodguy-project/goodguy", "sub_path": "goodguy/timer/contest/email_job.py", "file_name": "email_job.py", "file_ext": "py", "file_size_in_byte": 4188, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 15, "dataset": "github-code", "pt": "20", "api": [{"api_name": "typing.List", "line_number": 21, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 21, "usage_type": "name"}, {"api_name": "goodguy.pb.crawl_service_pb2.RecentContest", "line_number": 21, "usage_type": "attribute"}, {"api_name": "goodguy.pb.crawl_service_pb2", "line_number": 21, "usage_type": "name"}, {"api_name": "goodguy.pb.crawl_service_pb2.RecentContest", "line_number": 22, "usage_type": "attribute"}, {"api_name": "goodguy.pb.crawl_service_pb2", "line_number": 22, "usage_type": "name"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 23, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 24, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 24, "usage_type": "call"}, {"api_name": "goodguy.util.timestamp_to_date_string.timestamp_to_date_string", "line_number": 34, "usage_type": "call"}, {"api_name": "goodguy.util.timestamp_to_date_string.timestamp_to_date_string", "line_number": 35, "usage_type": "call"}, {"api_name": "goodguy.util.timestamp_to_date_string.duration_to_string", "line_number": 41, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 22, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "jinja2.Template", "line_number": 47, "usage_type": "call"}, {"api_name": "time.time", "line_number": 51, "usage_type": "call"}, {"api_name": "goodguy.util.get_html_from_mjml.get_html_from_mjml", "line_number": 65, "usage_type": "call"}, {"api_name": "threading.Lock", "line_number": 70, "usage_type": "call"}, {"api_name": "goodguy.service.crawl.get_recent_contest", "line_number": 77, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 76, "usage_type": "name"}, {"api_name": "goodguy.pb.crawl_service_pb2.RecentContest", "line_number": 76, "usage_type": "attribute"}, {"api_name": "goodguy.pb.crawl_service_pb2", "line_number": 76, "usage_type": "name"}, {"api_name": "goodguy.util.const.PLATFORM_ALL", "line_number": 79, "usage_type": "name"}, {"api_name": "asyncio.gather", "line_number": 80, "usage_type": "call"}, {"api_name": "asyncio.run", "line_number": 83, "usage_type": "call"}, {"api_name": "time.time", "line_number": 86, "usage_type": "call"}, {"api_name": "time.time", "line_number": 91, "usage_type": "call"}, {"api_name": "loguru.logger.debug", "line_number": 107, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 107, "usage_type": "name"}, {"api_name": "goodguy.util.send_email.send_all_email", "line_number": 108, "usage_type": "call"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 113, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 113, "usage_type": "attribute"}, {"api_name": "goodguy.timer.scheduler.scheduler", "line_number": 114, "usage_type": "call"}]} +{"seq_id": "40070888765", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 9 23:44:06 2020\r\n\r\n@author: Jie.Hu\r\n\"\"\"\r\n\r\n\r\n''' 4: Support Vector Machine'''\r\nfrom sklearn.metrics import roc_auc_score, f1_score, accuracy_score, classification_report\r\nfrom sklearn.model_selection import StratifiedKFold, cross_val_score, GridSearchCV\r\nfrom sklearn.svm import SVC\r\nclf_svc = SVC(random_state = 1337)\r\nclf_svc.fit(X, y)\r\n\r\n# Predicting the train set results\r\ny_pred = clf_svc.predict(X)\r\nroc_auc_score(y, y_pred)\r\n\r\nskf = StratifiedKFold(n_splits=5)\r\nacc = cross_val_score(estimator = clf_svc, X = X, y = y, cv = skf, scoring='roc_auc')\r\nacc.mean(), acc.std()\r\n\r\n\r\n# KF n GS\r\nparameters = [{'kernel': ['linear'], 'C': [1, 10, 100, 1000]},\r\n {'kernel': ['poly'], 'C': [1, 10, 100, 1000], 'gamma': ['auto', 'scale'], 'degree': [1,2,3]},\r\n {'kernel': ['rbf'], 'C': [1, 10, 100, 1000], 'gamma': ['auto', 'scale']}]\r\n\r\ngrid_search = GridSearchCV(estimator = clf_svc,\r\n param_grid = parameters,\r\n scoring='f1',\r\n cv = 5,\r\n n_jobs = -1)\r\n\r\ngrid_search = grid_search.fit(X, y)\r\ngrid_search.best_params_, grid_search.best_score_\r\n\r\n# last step\r\nclf_svc = SVC(kernel = 'poly',\r\n C = 1000,\r\n gamma = 'scale', \r\n random_state = 1337)\r\nclf_svc.fit(X, y)\r\ny_pred = clf_svc.predict(X)\r\nroc_auc_score(y, y_pred)\r\n\r\nprint(classification_report(y, y_pred))\r\n", "repo_name": "jieuhyl/Machine_Learning", "sub_path": "Supervised/Classification/SupportVectorMachine_v2.py", "file_name": "SupportVectorMachine_v2.py", "file_ext": "py", "file_size_in_byte": 1477, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "sklearn.svm.SVC", "line_number": 13, "usage_type": "call"}, {"api_name": "sklearn.metrics.roc_auc_score", "line_number": 18, "usage_type": "call"}, {"api_name": "sklearn.model_selection.StratifiedKFold", "line_number": 20, "usage_type": "call"}, {"api_name": "sklearn.model_selection.cross_val_score", "line_number": 21, "usage_type": "call"}, {"api_name": "sklearn.model_selection.GridSearchCV", "line_number": 30, "usage_type": "call"}, {"api_name": "sklearn.svm.SVC", "line_number": 40, "usage_type": "call"}, {"api_name": "sklearn.metrics.roc_auc_score", "line_number": 46, "usage_type": "call"}, {"api_name": "sklearn.metrics.classification_report", "line_number": 48, "usage_type": "call"}]} +{"seq_id": "73844166450", "text": "import numpy as np \nimport torch\nfrom torchvision import transforms, models\nimport importlib\nfrom algorithms.utils.utils import *\nfrom PIL import Image\nimport itertools\n\nimport pdb\n\nclass A2CPolicyNetwork(torch.nn.Module):\n def __init__(self, dtype, action_dim, obs_dim, aux_dim):\n super(A2CPolicyNetwork, self).__init__()\n self.action_dim = action_dim\n self.obs_dim = obs_dim\n\n self.batchnorm0 = torch.nn.BatchNorm2d(1)\n self.conv1 = torch.nn.Conv2d(1, 24, 8, stride=4)\n self.pool1 = torch.nn.AvgPool2d(8,4)\n self.batchnorm1 = torch.nn.BatchNorm2d(24)\n self.conv2 = torch.nn.Conv2d(24, 48, 4, stride=2)\n self.pool2 = torch.nn.AvgPool2d(4,2)\n self.batchnorm2 = torch.nn.BatchNorm2d(48)\n self.conv3 = torch.nn.Conv2d(48, 48, 4, stride=2)\n self.pool3 = torch.nn.AvgPool2d(4,2)\n self.batchnorm3 = torch.nn.BatchNorm2d(48)\n self.conv4 = torch.nn.Conv2d(48, 48, 4, stride=2)\n self.pool4 = torch.nn.AvgPool2d(4,2)\n self.batchnorm4 = torch.nn.BatchNorm2d(48)\n self.lstm1 = torch.nn.LSTM(192, 128, 1)\n self.fc1 = torch.nn.Linear(192, 128)\n self.fc2 = torch.nn.Linear(128, 128)\n self.fc3 = torch.nn.Linear(128, self.action_dim*2+aux_dim)\n \n torch.nn.init.xavier_uniform(self.conv1.weight)\n torch.nn.init.xavier_uniform(self.conv2.weight)\n torch.nn.init.xavier_uniform(self.conv3.weight)\n torch.nn.init.xavier_uniform(self.conv4.weight)\n torch.nn.init.xavier_uniform(self.fc1.weight)\n torch.nn.init.xavier_uniform(self.fc2.weight)\n torch.nn.init.uniform(self.fc3.weight, -3e-4, 3e-4)\n\n self.transform = transforms.Compose([transforms.ToPILImage(), transforms.Resize((64,64)), transforms.Grayscale(1), transforms.ToTensor()])\n self.loss_fn_aux = torch.torch.nn.MSELoss() \n\n def model(self, x):\n x = self.batchnorm0(x)\n x = torch.nn.functional.relu(self.batchnorm1( self.conv1(x) + torch.cat([self.pool1(x)]*24,1) ))\n x = torch.nn.functional.relu(self.batchnorm2( self.conv2(x) + torch.cat([self.pool2(x)]*2,1) ))\n x = torch.nn.functional.relu(self.batchnorm3( self.conv3(x) + torch.cat([self.pool3(x)]*1,1) ))\n # x = torch.nn.functional.relu(self.batchnorm4( self.conv4(x) + torch.cat([self.pool4(x)]*1,1) ))\n x = x.view(-1, int(192))\n x = x.unsqueeze(1)\n x = self.lstm1(x)[0]\n x = x.view(-1, int(128))\n # x = torch.nn.functional.relu(self.fc1(x))\n x = torch.nn.functional.relu(self.fc2(x))\n x = self.fc3(x)\n\n return x\n \n def forward(self, x):\n return self.model(x)\n\n def multi_frame(self, obs_batch, num_frame=3):\n new_obs_batch = []\n for i in range(len(obs_batch)):\n new_obs_batch.append(torch.cat(list(reversed(obs_batch[max(i+1-num_frame,0):i+1])) + [obs_batch[0]]*max(0,num_frame-i-1)))\n return new_obs_batch\n\n def compute(self, observation):\n\n # num_frame = 3\n # i = len(obs_batch)-1\n\n # stacked_obs = list(reversed(obs_batch[max(i+1-num_frame,0):i+1])) + [obs_batch[0]]*max(0,num_frame-i-1)\n\n observation = self.transform(observation)\n\n observation = torch.autograd.Variable(observation,volatile=True).type(torch.FloatTensor).unsqueeze(0)\n\n # plt.imshow(observation.data.cpu().squeeze(0).permute(1, 2, 0).numpy(),interpolation='none')\n model_out = self.forward(observation).squeeze()\n mean, std_dev = model_out[:self.action_dim].data, torch.log(torch.exp(model_out[self.action_dim:2*self.action_dim])+1).data\n # std_dev = std_dev*0 + 0.3\n\n distribution = torch.distributions.Normal(mean, std_dev)\n\n return distribution.sample().cpu().numpy()\n \n def train(self, observations_batch, actions_batch, advantages_batch, learning_rate, auxs_batch):\n optimizer = torch.optim.Adam(self.parameters(), learning_rate)\n\n advantages_batch = np.squeeze(np.array(advantages_batch))\n actions_batch = np.array(actions_batch)\n auxs_batch = np.array(auxs_batch)\n observations_batch = [self.transform(obs) for obs in observations_batch]\n # observations_batch = self.multi_frame(observations_batch)\n observations_batch = torch.stack(observations_batch)\n\n # rand_idx = np.random.permutation(observations_batch.shape[0])\n # advantages_batch = advantages_batch[rand_idx]\n # actions_batch = actions_batch[rand_idx]\n # observations_batch = observations_batch[rand_idx,:,:,:]\n # auxs_batch = auxs_batch[rand_idx,:]\n\n obs = torch.autograd.Variable(observations_batch).type(torch.FloatTensor)\n action = torch.autograd.Variable(torch.Tensor(actions_batch)).type(torch.FloatTensor) \n advantage = torch.autograd.Variable(torch.Tensor(advantages_batch)).type(torch.FloatTensor) \n model_out = self.model(obs)\n mean, std_dev = model_out[:,:self.action_dim], torch.log(torch.exp(model_out[:,self.action_dim:2*self.action_dim])+1)\n # std_dev = std_dev*0 + 0.3\n distribution = torch.distributions.Normal(mean, std_dev)\n optimizer.zero_grad()\n aux_target = torch.autograd.Variable(torch.Tensor(auxs_batch)).type(torch.FloatTensor)\n loss = torch.mean(-distribution.log_prob(action)*advantage.unsqueeze(1)) + 10*self.loss_fn_aux(model_out[:,2*self.action_dim:], aux_target)\n loss.backward()\n optimizer.step()\n policy_network_loss = loss.cpu().data.numpy()[0]\n\n return policy_network_loss\n \n", "repo_name": "DanielDworakowski/flot", "sub_path": "workspace/rl/algorithms/utils/PolicyNetwork.py", "file_name": "PolicyNetwork.py", "file_ext": "py", "file_size_in_byte": 5575, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "torch.nn", "line_number": 11, "usage_type": "attribute"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 17, "usage_type": "attribute"}, {"api_name": "torch.nn.Conv2d", "line_number": 18, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 18, "usage_type": "attribute"}, {"api_name": "torch.nn.AvgPool2d", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 19, "usage_type": "attribute"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "attribute"}, {"api_name": "torch.nn.Conv2d", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "attribute"}, {"api_name": "torch.nn.AvgPool2d", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "attribute"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "attribute"}, {"api_name": "torch.nn.Conv2d", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 24, "usage_type": "attribute"}, {"api_name": "torch.nn.AvgPool2d", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 25, "usage_type": "attribute"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 26, "usage_type": "attribute"}, {"api_name": "torch.nn.Conv2d", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 27, "usage_type": "attribute"}, {"api_name": "torch.nn.AvgPool2d", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "attribute"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 29, "usage_type": "attribute"}, {"api_name": "torch.nn.LSTM", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 30, "usage_type": "attribute"}, {"api_name": "torch.nn.Linear", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 31, "usage_type": "attribute"}, {"api_name": "torch.nn.Linear", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 32, "usage_type": "attribute"}, {"api_name": "torch.nn.Linear", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 33, "usage_type": "attribute"}, {"api_name": "torch.nn.init.xavier_uniform", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 35, "usage_type": "attribute"}, {"api_name": "torch.nn.init.xavier_uniform", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "attribute"}, {"api_name": "torch.nn.init.xavier_uniform", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 37, "usage_type": "attribute"}, {"api_name": "torch.nn.init.xavier_uniform", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 38, "usage_type": "attribute"}, {"api_name": "torch.nn.init.xavier_uniform", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 39, "usage_type": "attribute"}, {"api_name": "torch.nn.init.xavier_uniform", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 40, "usage_type": "attribute"}, {"api_name": "torch.nn.init.uniform", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 41, "usage_type": "attribute"}, {"api_name": "torchvision.transforms.Compose", "line_number": 43, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 43, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToPILImage", "line_number": 43, "usage_type": "call"}, {"api_name": "torchvision.transforms.Resize", "line_number": 43, "usage_type": "call"}, {"api_name": "torchvision.transforms.Grayscale", "line_number": 43, "usage_type": "call"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.torch.nn.MSELoss", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.torch", "line_number": 44, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.relu", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 48, "usage_type": "attribute"}, {"api_name": "torch.cat", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 49, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 49, "usage_type": "attribute"}, {"api_name": "torch.cat", "line_number": 49, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 50, "usage_type": "attribute"}, {"api_name": "torch.cat", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.nn.functional.relu", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 57, "usage_type": "attribute"}, {"api_name": "torch.cat", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 80, "usage_type": "attribute"}, {"api_name": "torch.FloatTensor", "line_number": 80, "usage_type": "attribute"}, {"api_name": "torch.log", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.distributions.Normal", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.distributions", "line_number": 87, "usage_type": "attribute"}, {"api_name": "torch.optim.Adam", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 92, "usage_type": "attribute"}, {"api_name": "numpy.squeeze", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 99, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 107, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 107, "usage_type": "attribute"}, {"api_name": "torch.FloatTensor", "line_number": 107, "usage_type": "attribute"}, {"api_name": "torch.autograd.Variable", "line_number": 108, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 108, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 108, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 108, "usage_type": "attribute"}, {"api_name": "torch.autograd.Variable", "line_number": 109, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 109, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 109, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 109, "usage_type": "attribute"}, {"api_name": "torch.log", "line_number": 111, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 111, "usage_type": "call"}, {"api_name": "torch.distributions.Normal", "line_number": 113, "usage_type": "call"}, {"api_name": "torch.distributions", "line_number": 113, "usage_type": "attribute"}, {"api_name": "torch.autograd.Variable", "line_number": 115, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 115, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 115, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 115, "usage_type": "attribute"}, {"api_name": "torch.mean", "line_number": 116, "usage_type": "call"}]} +{"seq_id": "11534284591", "text": "import argparse\r\nimport cv2\r\nimport time\r\nimport os\r\nimport shutil\r\nfrom gooey import Gooey, GooeyParser\r\nimport PySimpleGUI as sg \r\n\r\n@Gooey(program_name=\"Few-Shot UI\")\r\ndef parse_args():\r\n parser = GooeyParser(description='this script is based on FSPBT')#argparse.ArgumentParser(description='arguments')\r\n files = parser.add_argument_group('fileselection', gooey_options={'show_border': bool,'show_underline': bool,'label_color': '#FF9900','columns': 2})\r\n size = parser.add_argument_group('size', gooey_options={'show_border': bool,'show_underline': bool,'label_color': '#FF9900','columns': 1})\r\n settings = parser.add_argument_group('settings', gooey_options={'show_border': bool,'show_underline': bool,'label_color': '#FF9900','columns': 3})\r\n mysterysettings = parser.add_argument_group('mystery settings', gooey_options={'show_border': bool,'show_underline': bool,'label_color': '#FF9900','columns': 3})\r\n \r\n files.add_argument('--inputfile', widget=\"FileChooser\", type=str, help='path to your input video or gif, only up to 1000 frames for now',required=True)\r\n files.add_argument('--maskfile', widget=\"FileChooser\", type=str, help='path to your mask video (optional)(should be an alpha mask)')\r\n files.add_argument('--projectname', type=str, help='name of the project to create the directories',required=True)\r\n settings.add_argument('--framegap',default=5, widget=\"IntegerField\", gooey_options={'min': 0, 'max': 1000, 'increment': int}, type=int, help='number of how many frames are inbetween the style images')\r\n settings.add_argument('--precision', type=str, help='_flow takes more time to prepape but is much better and faster at training',choices=['detailed_flow','undetailed_flow', 'normal', 'normal_slow','webcam_test'],required=True,nargs='*')\r\n size.add_argument('--W', type=str,metavar='width', widget=\"IntegerField\", gooey_options={'min': 0, 'max': 1024, 'increment': int},default=512)\r\n size.add_argument('--H', type=str,metavar='height', widget=\"IntegerField\", gooey_options={'min': 0, 'max': 1024, 'increment': int},default=512)\r\n files.add_argument('--logpath', type=str, help='name of the path where your training happens',default = 'logs')\r\n settings.add_argument('--log_interval', type=str, help='path where your training happens',default = '10000', widget=\"IntegerField\", gooey_options={'min': 100, 'max': 80000, 'increment': int})\r\n \r\n mysterysettings.add_argument('--perception_loss_weight', help='test', default=6.0, widget=\"DecimalField\")\r\n mysterysettings.add_argument('--reconstruction_weight', help='test', default=4., widget=\"DecimalField\")\r\n mysterysettings.add_argument('--adversarial_weight', help='test', default=0.5, widget=\"DecimalField\")\r\n mysterysettings.add_argument('--append_smoothers', type=str,nargs='*', help='test',default = 'True', choices=['True', 'False'])\r\n mysterysettings.add_argument('--filters_layers', type=str,nargs='*', help='test',default = '[32, 64, 128, 128, 128, 64]', choices=['[32, 64, 128, 128, 128, 64]', '[32, 32, 32, 32, 32, 32]','[32, 64, 64, 64, 64, 64]'])\r\n mysterysettings.add_argument('--patch_size', type=str,nargs='*', help='test',default = '32', choices=['16','32','64','128'])\r\n mysterysettings.add_argument('--use_normalization', type=str,nargs='*', help='test',default = 'False', choices=['True', 'False'])\r\n mysterysettings.add_argument('--use_image_loss', type=str,nargs='*', help='test',default = 'True', choices=['True', 'False'])\r\n mysterysettings.add_argument('--tanh', type=str,nargs='*', help='test',default = 'True', choices=['True', 'False'])\r\n mysterysettings.add_argument('--use_bias', type=str,nargs='*', help='test',default = 'True', choices=['True', 'False'])\r\n return parser.parse_args()\r\n\r\nargs = parse_args()\r\n\r\ncwd = os.getcwd()\r\ntools_all = cwd + '/_tools/tools_all.py'\r\ntrainur = cwd + '/train.py'\r\ndisco1010 = cwd + '/_config/reference_P_disco1010.yaml'\r\ndisco1015 = cwd + '/_config/reference_P_disco1015.yaml'\r\n\r\nwebcam = cwd + '/_config/reference_webcam.yaml'\r\nnormal = cwd + '/_config/reference_P.yaml'\r\nnormal2 = cwd + '/_config/reference_F.yaml'\r\n\r\ndoc_path = os.path.expanduser('~\\Documents')\r\nif args.logpath:\r\n data_path = cwd+'/'+args.logpath\r\n if not os.path.exists(data_path):\r\n path999= cwd\r\n os.chdir(path999)\r\n newfolder_999=data_path\r\n os.makedirs(newfolder_999)\r\nelse:\r\n data_path = os.path.expanduser('~\\Documents/visionsofchaos/fewshot/data')\r\n\r\n if not os.path.exists(doc_path+'/'+'visionsofchaos'):\r\n path10= doc_path\r\n os.chdir(path10)\r\n newfolder_10='visionsofchaos'\r\n os.makedirs(newfolder_10)\r\n if not os.path.exists(doc_path+'/'+'visionsofchaos'+'/'+'fewshot'):\r\n path11= doc_path+'/'+'visionsofchaos'\r\n os.chdir(path11)\r\n newfolder_11='fewshot'\r\n os.makedirs(newfolder_11)\r\n if not os.path.exists(doc_path+'/'+'visionsofchaos'+'/'+'fewshot'+'/'+'data'):\r\n path12= doc_path+'/'+'visionsofchaos'+'/'+'fewshot'\r\n os.chdir(path12)\r\n newfolder_12='data'\r\n os.makedirs(newfolder_12)\r\n\r\n\r\n\r\n#make subdirectories\r\npath1= data_path\r\nos.chdir(path1)\r\nnewfolder=str(args.projectname)+'_train'\r\nos.makedirs(newfolder)\r\n #to make folders inside the other folders\r\npath2=path1+'/'+newfolder\r\nos.chdir(path2)\r\nnewfolder_2='input_filtered'\r\nos.makedirs(newfolder_2)\r\n\r\npath3=path1+'/'+newfolder\r\nos.chdir(path2)\r\nnewfolder_3='mask'\r\nos.makedirs(newfolder_3) \r\n\r\npath4=path1+'/'+newfolder\r\nos.chdir(path2)\r\nnewfolder_4='output'\r\nos.makedirs(newfolder_4) \r\n\r\n\r\npath5= data_path\r\nos.chdir(path5)\r\nnewfolder_5=str(args.projectname)+'_gen'\r\nos.makedirs(newfolder_5)\r\n\r\n \r\npath6= data_path + '/' + args.projectname + '_gen'\r\nos.chdir(path6)\r\n#newfolder_6='input'\r\n#os.makedirs(newfolder_6)\r\n\r\npath13= data_path + '/' + args.projectname + '_gen'\r\nos.chdir(path13)\r\nnewfolder_13='input_filtered'\r\nos.makedirs(newfolder_13)\r\n\r\n\r\npath7= data_path + '/' + args.projectname + '_gen'\r\nos.chdir(path6)\r\nnewfolder_7='mask'\r\nos.makedirs(newfolder_7) \r\n\r\npath8= data_path + '/' + args.projectname + '_gen'\r\nos.chdir(path6)\r\n#newfolder_8='output'\r\n#os.makedirs(newfolder_8) \r\n\r\nif args.precision == ['detailed_flow']:\r\n flow = True\r\nelif args.precision == ['undetailed_flow']:\r\n flow = True\r\nelse:\r\n flow = False\r\n \r\nif flow == True: \r\n path9= data_path\r\n os.chdir(path9)\r\n newfolder_9=str(args.projectname)+'_flow'\r\n os.makedirs(newfolder_9)\r\n\r\n path9= data_path\r\n os.chdir(path9)\r\n newfolder_30=str(args.projectname)+'_flow/flowfwd'\r\n os.makedirs(newfolder_30)\r\n\r\n path9= data_path\r\n os.chdir(path9)\r\n newfolder_31=str(args.projectname)+'_flow/flowbwd'\r\n os.makedirs(newfolder_31)\r\n if args.precision == ['detailed_flow']:\r\n path14= data_path + '/' + args.projectname + '_gen'\r\n os.chdir(path14)\r\n newfolder_14='input_gdisko_gauss_r10_s10'\r\n os.makedirs(newfolder_14)\r\n\r\n path16= data_path + '/' + args.projectname + '_train'\r\n os.chdir(path16)\r\n newfolder_16='input_gdisko_gauss_r10_s10'\r\n os.makedirs(newfolder_16)\r\n elif args.precision == ['undetailed_flow']:\r\n path15= data_path + '/' + args.projectname + '_gen'\r\n os.chdir(path15)\r\n newfolder_15='input_gdisko_gauss_r10_s15'\r\n os.makedirs(newfolder_15)\r\n\r\n path17= data_path + '/' + args.projectname + '_train'\r\n os.chdir(path17)\r\n newfolder_17='input_gdisko_gauss_r10_s15'\r\n os.makedirs(newfolder_17)\r\n\r\n\r\ntrain_filtered = data_path+str(args.projectname)+'_train'+'/'+'input_filtered'\r\n\r\nimport moviepy.editor as mp\r\ninputfile = args.inputfile\r\nif inputfile.endswith('.gif'):\r\n clip = mp.VideoFileClip(args.inputfile)\r\n clip.write_videofile(\"myvideo.mp4\")\r\n\r\n#convert video\r\ndef video_to_frames(input_loc, output_loc):\r\n args = parse_args()\r\n #Function to extract frames from input video file\r\n #and save them as separate frames in an output directory.\r\n #Args:\r\n # input_loc: Input video file.\r\n # output_loc: Output directory to save the frames.\r\n #Returns:\r\n # None\r\n import moviepy.editor as mp\r\n clip = mp.VideoFileClip(input_loc1)\r\n clip_resized = clip.resize((args.W,args.H)) # make the height 360px ( According to moviePy documenation The width is then computed so that the width/height ratio is conserved.)\r\n clip_resized.write_videofile(\"movie_resized.mp4\")\r\n try:\r\n os.mkdir(output_loc)\r\n except OSError:\r\n pass\r\n # Log the time\r\n time_start = time.time()\r\n # Start capturing the feed\r\n cap = cv2.VideoCapture(input_loc)\r\n # Find the number of frames\r\n video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1\r\n print (\"Number of frames: \", video_length)\r\n count = 0\r\n print (\"Converting video..\\n\")\r\n # Start converting the video\r\n while cap.isOpened():\r\n # Extract the frame\r\n ret, frame = cap.read()\r\n if not ret:\r\n continue\r\n # Write the results back to output location.\r\n cv2.imwrite(output_loc + \"/%#03d.png\" % (count+1), frame)\r\n count = count + 1\r\n # If there are no more frames left\r\n if (count > (video_length-1)):\r\n # Log the time again\r\n time_end = time.time()\r\n # Release the feed\r\n cap.release()\r\n # Print stats\r\n print (\"Done extracting frames.\\n%d frames extracted\" % count)\r\n print (\"It took %d seconds forconversion.\" % (time_end-time_start))\r\n break\r\nif __name__==\"__main__\":\r\n if inputfile.endswith('.gif'):\r\n input_loc1 = \"myvideo.mp4\"\r\n input_loc = \"movie_resized.mp4\"\r\n else:\r\n input_loc1 = args.inputfile\r\n input_loc = \"movie_resized.mp4\"\r\n output_loc = data_path + '/' + args.projectname + '_gen/input_filtered'\r\n video_to_frames(input_loc, output_loc)\r\n\r\n\r\n \r\nimport os\r\nimport shutil\r\n\r\nprint (\" \")\r\nprint (\"making frames with your --framegap value to gen_filtered folder\")\r\n\r\ngen = data_path + '/' + args.projectname + '_gen/'\r\ntrain = data_path + '/' + args.projectname + '_train/'\r\ntrain_filtered = data_path+'/'+str(args.projectname)+'_train'+'/'+'input_filtered/'\r\ngen_filtered = data_path + '/' + args.projectname + '_gen/input_filtered/'\r\ngen_filtered_batch = data_path + '/' + args.projectname + '_gen/input_filtered/*'\r\ngen_mask = data_path + '/' + args.projectname + '_gen/mask/'\r\ngen_mask2 = data_path + '/' + args.projectname + '_gen/mask'\r\ntrain_output = data_path+'/'+str(args.projectname)+'_train'+'/'+'output/'\r\ntrain_output_batch = data_path+'/'+str(args.projectname)+'_train'+'/'+'output/*'\r\ntrain_filtered = data_path + '/' + args.projectname + '_train/input_filtered/'\r\ntrain_filtered_batch = data_path + '/' + args.projectname + '_train/input_filtered/*'\r\ntrain_mask = data_path + '/' + args.projectname + '_train/mask/'\r\ntrain_root = data_path + '/' + args.projectname + '_train/'\r\n\r\nif flow == True:\r\n disco1010path = data_path + '/' + args.projectname + '_gen/res__P_disco1010'\r\n disco1015path = data_path + '/' + args.projectname + '_gen/res__P_disco1015'\r\nresppath = data_path + '/' + args.projectname + '_gen/res__P'\r\nresfpath = data_path + '/' + args.projectname + '_gen/res__F'\r\n\r\n\r\nvideo_length = len(os.listdir(gen_filtered))\r\nprint (\"Number of frames: \", video_length)\r\n\r\nif args.framegap:\r\n print (\"exporting framegap frames\")\r\n\r\n if video_length <100:\r\n for i in range(1, 9, args.framegap):\r\n print (i) \r\n shutil.copy2(gen_filtered+'/'+'00'+str(i)+'.png', train_filtered)\r\n for i in range(10, video_length, args.framegap):\r\n print (i) \r\n shutil.copy2(gen_filtered+'/'+'0'+str(i)+'.png', train_filtered)\r\n \r\n if video_length >100:\r\n for i in range(1, 9, args.framegap):\r\n print (i) \r\n shutil.copy2(gen_filtered+'/'+'00'+str(i)+'.png', train_filtered)\r\n for i in range(10, 99, args.framegap):\r\n print (i) \r\n shutil.copy2(gen_filtered+'/'+'0'+str(i)+'.png', train_filtered)\r\n for i in range(100, video_length, args.framegap):\r\n print (i) \r\n shutil.copy2(gen_filtered+'/'+str(i)+'.png', train_filtered)\r\n print (\"exported framegap frames to \" ,train_filtered) \r\nelse:\r\n print(\"you didn't provide a framegap value so you'll have to choose the frames that you display the style on yourself\")\r\n print(\"choose a couple frames in \",gen_filtered,\"and put them in\",train_filtered)\r\n frowframe_run1 = (input(\"have your read the above and put your frames in the folder? press ENTER if you do\"))\r\n\r\nimport subprocess\r\n\r\n\r\nresizesize = args.W + 'x' + args.H + '!'\r\nimageread = gen_filtered +'001.png'\r\nimport cv2\r\nimg = cv2.imread(imageread)\r\nprint(img.shape)\r\n'''if( img.shape != (args.H, args.W, 3) ):\r\n subprocess.run([\"magick\", \"mogrify\", \"-resize\", resizesize, \"-quality\", \"100\", gen_filtered_batch])#, \"*.png\", \"-quality\", \"100\", gen_filtered])\r\n print (\"frames in \",gen_filtered, \"resized\") \r\n subprocess.run([\"magick\", \"mogrify\", \"-resize\", resizesize, \"-quality\", \"100\", train_filtered_batch])#, \"*.png\", \"-quality\", \"100\", train_filtered])\r\n print (\"frames in \",train_filtered, \"resized\")\r\nif( img.shape == (args.H, args.W, 3) ):\r\n print('no resizing needed')'''\r\n\r\nif args.maskfile:\r\n input_loc1 = args.maskfile\r\n input_loc = \"movie_resized.mp4\"\r\n output_loc = data_path + '/' + args.projectname + '_gen/mask'\r\n video_to_frames(input_loc, output_loc)\r\n if args.framegap:\r\n if video_length <100:\r\n for i in range(1, 9, args.framegap):\r\n print (i) \r\n shutil.copy2(gen_mask2+'/'+'00'+str(i)+'.png', train_mask)\r\n for i in range(10, video_length, args.framegap):\r\n print (i) \r\n shutil.copy2(gen_mask2+'/'+'0'+str(i)+'.png', train_mask)\r\n \r\n if video_length >100:\r\n for i in range(1, 9, args.framegap):\r\n print (i) \r\n shutil.copy2(gen_mask2+'/'+'00'+str(i)+'.png', train_mask)\r\n for i in range(10, 99, args.framegap):\r\n print (i) \r\n shutil.copy2(gen_mask2+'/'+'0'+str(i)+'.png', train_mask)\r\n for i in range(100, video_length, args.framegap):\r\n print (i) \r\n shutil.copy2(gen_mask2+'/'+str(i)+'.png', train_mask)\r\n print (\"exported framegap frames to \" ,train_mask) \r\n else:\r\n print(\"you didn't provide a framegap value so you'll have to choose the frames that you display the style on yourself\")\r\n print(\"copy your previously chosen framenumbers but now in this folder = \",gen_mask2,\"and put them in\",train_mask)\r\n frowframe_run1 = (input(\"have your read the above and put your frames in the folder? press ENTER if you do\"))\r\nelse: \r\n import shutil\r\n import os\r\n if os.path.exists(gen_mask): \r\n os.rmdir(gen_mask)\r\n if os.path.exists(train_mask): \r\n os.rmdir(train_mask)\r\n # path to source directory\r\n src_dir = gen_filtered\r\n \r\n # path to destination directory\r\n dest_dir = gen_mask\r\n \r\n # getting all the files in the source directory\r\n files = os.listdir(src_dir)\r\n \r\n shutil.copytree(src_dir, dest_dir)\r\n \r\n src_dir2 = train_filtered\r\n \r\n \r\n dest_dir2 = train_mask\r\n \r\n files = os.listdir(src_dir2)\r\n \r\n shutil.copytree(src_dir2, dest_dir2)\r\n #import pytesseract\r\n from PIL import Image, ImageEnhance\r\n import glob\r\n images = glob.glob(gen_mask+'/*.png')\r\n\r\n for image in images:\r\n jpg_path = os.path.join(gen_mask, image)\r\n if os.path.isfile(jpg_path):\r\n #head_tail = os.path.basename(file)\r\n \r\n img = Image.open(jpg_path)\r\n contrast = ImageEnhance.Contrast(img)\r\n factor = 0\r\n img = contrast.enhance(factor)\r\n enhancer = ImageEnhance.Brightness(img)\r\n factor2 = 1000 #brightens the image\r\n img = enhancer.enhance(factor2)\r\n img.save(jpg_path)\r\n #print(jpg_path)\r\n print (\"masks in \" ,gen_mask, \"made\") \r\n images2 = glob.glob(train_mask+'/*.png')\r\n\r\n for image in images2:\r\n jpg_path = os.path.join(train_mask, image)\r\n if os.path.isfile(jpg_path):\r\n #head_tail = os.path.basename(file)\r\n \r\n img = Image.open(jpg_path)\r\n contrast = ImageEnhance.Contrast(img)\r\n factor = 0\r\n img = contrast.enhance(factor)\r\n enhancer = ImageEnhance.Brightness(img)\r\n factor2 = 1000 #brightens the image\r\n img = enhancer.enhance(factor2)\r\n img.save(jpg_path)\r\n #print(jpg_path)\r\n #im_output.save(file)\r\n #subprocess.run(['magick', 'mogrify', '-brightness-contrast', '200x0', '-path', gen_mask, '-format','png', gen_filtered_batch])\r\n #print (\"masks in \" ,gen_mask, \"made\") \r\n #subprocess.run(['magick', 'mogrify', '-brightness-contrast', '200x0', '-path', train_mask, '-format','png', train_filtered_batch])\r\n print (\"masks in \" ,train_mask, \"made\") \r\n\r\nprjnm = str(args.projectname)\r\nfrmgp = str(args.framegap)\r\nvideo_length2 = str(video_length)\r\nlogpath = str(data_path)\r\n\r\nif flow == True:\r\n deletevideo = train+\"movie_resized.mp4\"\r\nelse:\r\n deletevideo = gen+\"movie_resized.mp4\"\r\nos.remove(deletevideo)\r\n\r\n \r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"!!!!!important!!!!!\")\r\nprint(\"\")\r\nprint(\"preparation done, apply desired effects on the images that are in '\",train_filtered,\"' and export those to '\",train_output,\"'\")\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"\")\r\n\r\nif args.precision == ['detailed_flow']: \r\n window=sg.Window('READ',\r\n [ [sg.Text('the frame movement prediction takes a while to render but it renders on CPU, so u can create the export frames with effects with your GPU in the meanwhile')],\r\n [sg.Text('COPY THE PATHS BELOW !!!!!important!!!!! IN THE STATUS WINDOW AND DO WHAT IT SAYS')],\r\n #[sg.Text('preparation done, apply desired effects on the images that are in \"',int(train_filtered),'\" and export those to \"',int(train_output),'\"')],\r\n [sg.Text('have your read the above and understand? press Submit if you do')],\r\n [sg.Submit()]])\r\n event, values = window.Read()\r\n window.Close() \r\n print(\"\")\r\n print(\"\")\r\n print(\"\")\r\n print(\"\")\r\n print(\"STARTING PREPARATION\")\r\nelif args.precision == ['undetailed_flow']:\r\n window=sg.Window('READ',\r\n [ [sg.Text('the frame movement prediction takes a while to render but it renders on CPU, so u can create the export frames with effects with your GPU in the meanwhile')],\r\n [sg.Text('COPY THE PATHS BELOW !!!!!important!!!!! IN THE STATUS WINDOW AND DO WHAT IT SAYS')],\r\n #[sg.Text('preparation done, apply desired effects on the images that are in \"',int(train_filtered),'\" and export those to \"',int(train_output),'\"')],\r\n [sg.Text('have your read the above and understand? press Submit if you do')],\r\n [sg.Submit()]])\r\n event, values = window.Read()\r\n window.Close() \r\n print(\"\")\r\n print(\"\")\r\n print(\"\")\r\n print(\"\")\r\n print(\"STARTING PREPARATION\")\r\nelse:\r\n \"\"\"R=fedit(title='READ',\r\n comment=\"webcam_test, normal, normal_slow don't use movement prediction but you still have to process the images\",\r\n data= [(None, None),\r\n (None, \"COPY THE PATHS IN THE STATUS WINDOW AND DO WHAT IT SAYS\"),\r\n (None, None),\r\n (None, 'have your read the above and understand? press OK if you do'),\r\n ])\"\"\"\r\n window=sg.Window('READ',\r\n [ [sg.Text(\"webcam_test, normal, normal_slow don't use movement prediction but you still have to process the images\")],\r\n [sg.Text('COPY THE PATHS BELOW !!!!!important!!!!! IN THE STATUS WINDOW AND DO WHAT IT SAYS')],\r\n #[sg.Text('preparation done, apply desired effects on the images that are in \"',int(train_filtered),'\" and export those to \"',int(train_output),'\"')],\r\n [sg.Text('have your read the above and understand? press Submit if you do')],\r\n [sg.Submit()]])\r\n event, values = window.Read()\r\n window.Close() \r\n\"\"\"print(\"\")\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"\")\r\nif args.precision == 'detailed_flow': \r\n print(\"the frame movement prediction takes a while to render but it renders on CPU, so u can create the export frames with effects with your GPU in the meanwhile\")\r\nelif args.precision == 'undetailed_flow': \r\n print(\"the frame movement prediction takes a while to render but it renders on CPU, so u can create the export frames with effects with your GPU in the meanwhile\")\r\nprint(\"\")\r\nprint(\"\")\r\nfrowframe_run1 = (input(\"have your read the above and understand? press ENTER if you do\"))\r\nprint(\"\")\r\nprint(\"\")\r\nif frowframe_run1:\r\n print(\"\")\r\n print(\"\")\r\nfrowframe_run2 = (input(\"are you sure u read it? press ENTER\"))\r\nprint(\"\")\r\nprint(\"\")\r\nif frowframe_run2:\r\n print(\"\")\r\n print(\"\") \r\nif args.precision == 'detailed_flow': \r\n frowframe_run = (input(\"press ENTER to start rendering the movement prediction frames\"))\r\nelif args.precision == 'undetailed_flow':\r\n frowframe_run = (input(\"press ENTER to start rendering the movement prediction frames\"))\r\nelse:\r\n print(\"\")\r\n print(\"\")\r\nif args.precision == 'detailed_flow': \r\n if frowframe_run:\r\n print(\"\")\r\n print(\"\") \r\nelif args.precision == 'undetailed_flow': \r\n if frowframe_run:\r\n print(\"\")\r\n print(\"\") \"\"\"\r\nif args.precision == ['detailed_flow']:\r\n if args.framegap:\r\n if args.maskfile:\r\n subprocess.run(['python', tools_all, '--projectname', prjnm, '--frames', video_length2, '--extension', 'png','--framegap', frmgp, '--precision', 'detailed_flow','--logpath',logpath,'--mask', '1'], shell=True)\r\n else:\r\n subprocess.run(['python', tools_all, '--projectname', prjnm, '--frames', video_length2, '--extension', 'png','--framegap', frmgp, '--precision', 'detailed_flow','--logpath',logpath], shell=True) #add choice for precision and add '--export_path', args.export_path\r\n else:\r\n if args.maskfile:\r\n subprocess.run(['python', tools_all, '--projectname', prjnm, '--frames', video_length2, '--extension', 'png', '--precision', 'detailed_flow','--logpath',logpath,'--mask', '1'], shell=True)\r\n else:\r\n subprocess.run(['python', tools_all, '--projectname', prjnm, '--frames', video_length2, '--extension', 'png', '--precision', 'detailed_flow','--logpath',logpath]) #add choice for precision and add '--export_path', args.export_path\r\nelif args.precision == ['undetailed_flow']:\r\n if args.framegap:\r\n if args.maskfile:\r\n subprocess.run(['python', tools_all, '--projectname', prjnm, '--frames', video_length2, '--extension', 'png','--framegap', frmgp, '--precision', 'undetailed_flow','--logpath',logpath,'--mask', '1'], shell=True)\r\n else:\r\n subprocess.run(['python', tools_all, '--projectname', prjnm, '--frames', video_length2, '--extension', 'png','--framegap', frmgp, '--precision', 'undetailed_flow','--logpath',logpath], shell=True) #add choice for precision and add '--export_path', args.export_path\r\n else:\r\n if args.maskfile:\r\n subprocess.run(['python', tools_all, '--projectname', prjnm, '--frames', video_length2, '--extension', 'png', '--precision', 'undetailed_flow','--logpath',logpath,'--mask', '1'], shell=True)\r\n else:\r\n subprocess.run(['python', tools_all, '--projectname', prjnm, '--frames', video_length2, '--extension', 'png', '--precision', 'undetailed_flow','--logpath',logpath], shell=True) #add choice for precision and add '--export_path', args.export_path\r\nelse:\r\n print(\"webcam_test, normal, normal_slow don't use movement prediction, skipping..\")\r\n\r\n\r\n\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"!!!!!important!!!!!\")\r\nprint(\"\")\r\nprint(\"a reminder to put the styled export frames into\", train_output)\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"\")\r\n\r\nif args.precision == ['detailed_flow']:\r\n window=sg.Window('READ',\r\n [ [sg.Text('the frame movement prediction takes a while to render but it renders on CPU, so u can create the export frames with effects with your GPU in the meanwhile')],\r\n [sg.Text('COPY THE PATHS IN THE STATUS WINDOW AND DO WHAT IT SAYS')],\r\n #[sg.Text('preparation done, apply desired effects on the images that are in \"',int(train_filtered),'\" and export those to \"',int(train_output),'\"')],\r\n [sg.Text('have your read the above and understand? press Submit if you do')],\r\n [sg.Submit()]])\r\n event, values = window.Read()\r\n window.Close() \r\nelif args.precision == ['undetailed_flow']:\r\n window=sg.Window('READ',\r\n [ [sg.Text('the frame movement prediction takes a while to render but it renders on CPU, so u can create the export frames with effects with your GPU in the meanwhile')],\r\n [sg.Text('COPY THE PATHS IN THE STATUS WINDOW AND DO WHAT IT SAYS')],\r\n #[sg.Text('preparation done, apply desired effects on the images that are in \"',int(train_filtered),'\" and export those to \"',int(train_output),'\"')],\r\n [sg.Text('have your read the above and understand? press Submit if you do')],\r\n [sg.Submit()]])\r\n event, values = window.Read()\r\n window.Close() \r\n#export_done = (input(\"are you done with creating the styled frames? press ENTER to start patch based training\"))\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"\")\r\n\"\"\"if export_done:\r\n print(\"\")\r\n \r\n print(\"\")\"\"\"\r\nimageread1 = train_output +'001.png'\r\nimport cv2\r\nimg1 = cv2.imread(imageread1)\r\nlog_interval = args.log_interval\r\nreconstruction_weight = args.reconstruction_weight\r\nadversarial_weight = args.adversarial_weight\r\nperception_loss_weight = args.perception_loss_weight\r\nif args.append_smoothers == ['True'] :\r\n append_smoothers = 'True'\r\nelif args.append_smoothers == ['False'] :\r\n append_smoothers = 'False'\r\n \r\nif args.use_normalization == ['False']:\r\n use_normalization = 'False'\r\nelif args.use_normalization == ['True']:\r\n use_normalization = 'True'\r\nif args.use_image_loss == ['False']:\r\n use_image_loss = 'False'\r\nelif args.use_image_loss == ['True']:\r\n use_image_loss = 'True' \r\nif args.tanh == ['False']:\r\n tanh = 'False'\r\nelif args.tanh == ['True']:\r\n tanh = 'True'\r\nif args.use_bias == ['False']:\r\n use_bias = 'False'\r\nelif args.use_bias == ['True']:\r\n use_bias = 'True'\r\n \r\n\r\nif args.filters_layers == ['[32, 64, 128, 128, 128, 64]'] :\r\n filters_layers = '326412812812864'\r\nelif args.filters_layers == ['[32, 32, 32, 32, 32, 32]'] :\r\n filters_layers = '323232323232'\r\nelif args.filters_layers == ['[32, 64, 64, 64, 64, 64]'] :\r\n filters_layers = '326464646464'\r\n \r\nif args.patch_size == ['128']:\r\n patch_size = '128'\r\nelif args.patch_size == ['16']:\r\n patch_size = '16'\r\nelif args.patch_size == ['32']:\r\n patch_size = '32'\r\nelif args.patch_size == ['64']:\r\n patch_size = '64'\r\n \r\n#print(img1.shape)\r\n#print(args.H, args.W, \"3\")\r\nif( img1.shape != (args.H, args.W, 3) ):\r\n subprocess.run([\"magick\",\"mogrify\", \"-resize\", resizesize, \"-quality\", \"100\", train_output_batch], shell=True) # magick mogrify -resize 512x1024! -quality 100 C:\\deepdream-test\\Few-Shot-Patch-Based-Training-master\\logs\\kind_train\\output/*\r\nelse:\r\n print(\"W and H are the same, skipping resize\")\r\nif args.precision == ['detailed_flow']:\r\n print(\"results will appear in \",disco1010path,\"every\" ,log_interval,\"steps\")\r\n print(\"\")\r\n print(\"\")\r\n print('python', '-B', trainur, '--config', disco1010, '--data_root', train_root, '--log_interval', log_interval, '--log_folder', 'logs_reference_P','--projectname', prjnm,'--logpath',logpath,'--perception_loss_weight',perception_loss_weight,'--reconstruction_weight',reconstruction_weight,'--adversarial_weight',adversarial_weight,'--append_smoothers',append_smoothers,'--filters_layers',filters_layers,'--patch_size',patch_size,'--use_normalization',use_normalization, '--use_image_loss',use_image_loss, '--tanh',tanh, '--use_bias',use_bias)\r\n print(\"\")\r\n print(\"\")\r\n subprocess.run(['python', '-B', trainur, '--config', disco1010, '--data_root', train_root, '--log_interval', log_interval, '--log_folder', 'logs_reference_P','--projectname', prjnm,'--logpath',logpath,'--perception_loss_weight',perception_loss_weight,'--reconstruction_weight',reconstruction_weight,'--adversarial_weight',adversarial_weight,'--append_smoothers',append_smoothers,'--filters_layers',filters_layers,'--patch_size',patch_size,'--use_normalization',use_normalization, '--use_image_loss',use_image_loss, '--tanh',tanh, '--use_bias',use_bias], shell=True)\r\nelif args.precision == ['webcam_test']:\r\n print(\"results will appear in \",resppath,\"every\" ,log_interval,\"steps\")\r\n print(\"\")\r\n print(\"\")\r\n print('python', '-B', trainur, '--config', webcam, '--data_root', train_root, '--log_interval', log_interval, '--log_folder', 'logs_reference_P','--projectname', prjnm,'--logpath',logpath,'--perception_loss_weight',perception_loss_weight,'--reconstruction_weight',reconstruction_weight,'--adversarial_weight',adversarial_weight,'--append_smoothers',append_smoothers,'--filters_layers',filters_layers,'--patch_size',patch_size,'--use_normalization',use_normalization, '--use_image_loss',use_image_loss, '--tanh',tanh, '--use_bias',use_bias)\r\n print(\"\")\r\n print(\"\")\r\n subprocess.run(['python', '-B', trainur, '--config', webcam, '--data_root', train_root, '--log_interval', log_interval, '--log_folder', 'logs_reference_P','--projectname', prjnm,'--logpath',logpath,'--perception_loss_weight',perception_loss_weight,'--reconstruction_weight',reconstruction_weight,'--adversarial_weight',adversarial_weight,'--append_smoothers',append_smoothers,'--filters_layers',filters_layers,'--patch_size',patch_size,'--use_normalization',use_normalization, '--use_image_loss',use_image_loss, '--tanh',tanh, '--use_bias',use_bias], shell=True)\r\nelif args.precision == ['undetailed_flow']:\r\n print(\"results will appear in \",disco1015path,\"every\" ,log_interval,\"steps\")\r\n print(\"\")\r\n print(\"\")\r\n print('python', '-B', trainur, '--config', disco1015, '--data_root', train_root, '--log_interval', log_interval, '--log_folder', 'logs_reference_P','--projectname', prjnm,'--logpath',logpath,'--perception_loss_weight',perception_loss_weight,'--reconstruction_weight',reconstruction_weight,'--adversarial_weight',adversarial_weight,'--append_smoothers',append_smoothers,'--filters_layers',filters_layers,'--patch_size',patch_size,'--use_normalization',use_normalization, '--use_image_loss',use_image_loss, '--tanh',tanh, '--use_bias',use_bias)\r\n print(\"\")\r\n print(\"\")\r\n subprocess.run(['python', '-B', trainur, '--config', disco1015, '--data_root', train_root, '--log_interval', log_interval, '--log_folder', 'logs_reference_P','--projectname', prjnm,'--logpath',logpath,'--perception_loss_weight',perception_loss_weight,'--reconstruction_weight',reconstruction_weight,'--adversarial_weight',adversarial_weight,'--append_smoothers',append_smoothers,'--filters_layers',filters_layers,'--patch_size',patch_size,'--use_normalization',use_normalization, '--use_image_loss',use_image_loss, '--tanh',tanh, '--use_bias',use_bias], shell=True)\r\nelif args.precision == ['normal']:\r\n print(\"results will appear in \",resppath,\"every\" ,log_interval,\"steps\")\r\n print(\"\")\r\n print(\"\")\r\n print('python', '-B', trainur, '--config', normal, '--data_root', train_root, '--log_interval', log_interval, '--log_folder', 'logs_reference_P','--projectname', prjnm,'--logpath',logpath,'--perception_loss_weight',perception_loss_weight,'--reconstruction_weight',reconstruction_weight,'--adversarial_weight',adversarial_weight,'--append_smoothers',append_smoothers,'--filters_layers',filters_layers,'--patch_size',patch_size,'--use_normalization',use_normalization, '--use_image_loss',use_image_loss, '--tanh',tanh, '--use_bias',use_bias)\r\n print(\"\")\r\n print(\"\")\r\n subprocess.run(['python', '-B', trainur, '--config', normal, '--data_root', train_root, '--log_interval', log_interval, '--log_folder', 'logs_reference_P','--projectname', prjnm,'--logpath',logpath,'--perception_loss_weight',perception_loss_weight,'--reconstruction_weight',reconstruction_weight,'--adversarial_weight',adversarial_weight,'--append_smoothers',append_smoothers,'--filters_layers',filters_layers,'--patch_size',patch_size,'--use_normalization',use_normalization, '--use_image_loss',use_image_loss, '--tanh',tanh, '--use_bias',use_bias], shell=True)\r\nelif args.precision == ['normal_slow']:\r\n print(\"results will appear in \",resfpath,\"every\" ,log_interval,\"steps\")\r\n print(\"\")\r\n print(\"\")\r\n print('python', '-B', trainur, '--config', normal2, '--data_root', train_root, '--log_interval', log_interval, '--log_folder', 'logs_reference_P','--projectname', prjnm,'--logpath',logpath,'--perception_loss_weight',perception_loss_weight,'--reconstruction_weight',reconstruction_weight,'--adversarial_weight',adversarial_weight,'--append_smoothers',append_smoothers,'--filters_layers',filters_layers,'--patch_size',patch_size,'--use_normalization',use_normalization, '--use_image_loss',use_image_loss, '--tanh',tanh, '--use_bias',use_bias)\r\n print(\"\")\r\n print(\"\")\r\n subprocess.run(['python', '-B', trainur, '--config', normal2, '--data_root', train_root, '--log_interval', log_interval, '--log_folder', 'logs_reference_P','--projectname', prjnm,'--logpath',logpath,'--perception_loss_weight',perception_loss_weight,'--reconstruction_weight',reconstruction_weight,'--adversarial_weight',adversarial_weight,'--append_smoothers',append_smoothers,'--filters_layers',filters_layers,'--patch_size',patch_size,'--use_normalization',use_normalization, '--use_image_loss',use_image_loss, '--tanh',tanh, '--use_bias',use_bias], shell=True)\r\n ", "repo_name": "HelixNGC7293/Few-Shot-Patch-Based-Training", "sub_path": "_tools/fewshot_UI.py", "file_name": "fewshot_UI.py", "file_ext": "py", "file_size_in_byte": 34727, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "25", "api": [{"api_name": "gooey.GooeyParser", "line_number": 11, "usage_type": "call"}, {"api_name": "gooey.Gooey", "line_number": 9, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path.expanduser", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path", "line_number": 51, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path", "line_number": 54, "usage_type": "attribute"}, {"api_name": "os.chdir", "line_number": 56, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path.expanduser", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path", "line_number": 60, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path", "line_number": 62, "usage_type": "attribute"}, {"api_name": "os.chdir", "line_number": 64, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 67, "usage_type": "call"}, {"api_name": "os.path", "line_number": 67, "usage_type": "attribute"}, {"api_name": "os.chdir", "line_number": 69, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 71, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path", "line_number": 72, "usage_type": "attribute"}, {"api_name": "os.chdir", "line_number": 74, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 76, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 82, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 84, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 87, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 89, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 92, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 94, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 97, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 99, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 103, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 105, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 109, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 114, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 116, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 120, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 122, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 125, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 138, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 140, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 143, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 145, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 148, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 150, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 153, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 155, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 158, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 160, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 163, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 165, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 168, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 170, "usage_type": "call"}, {"api_name": "moviepy.editor.VideoFileClip", "line_number": 178, "usage_type": "call"}, {"api_name": "moviepy.editor", "line_number": 178, "usage_type": "name"}, {"api_name": "moviepy.editor.VideoFileClip", "line_number": 192, "usage_type": "call"}, {"api_name": "moviepy.editor", "line_number": 192, "usage_type": "name"}, {"api_name": "os.mkdir", "line_number": 196, "usage_type": "call"}, {"api_name": "time.time", "line_number": 200, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 202, "usage_type": "call"}, {"api_name": "cv2.CAP_PROP_FRAME_COUNT", "line_number": 204, "usage_type": "attribute"}, {"api_name": "cv2.imwrite", "line_number": 215, "usage_type": "call"}, {"api_name": "time.time", "line_number": 220, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 266, "usage_type": "call"}, {"api_name": "shutil.copy2", "line_number": 275, "usage_type": "call"}, {"api_name": "shutil.copy2", "line_number": 278, "usage_type": "call"}, {"api_name": "shutil.copy2", "line_number": 283, "usage_type": "call"}, {"api_name": "shutil.copy2", "line_number": 286, "usage_type": "call"}, {"api_name": "shutil.copy2", "line_number": 289, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 302, "usage_type": "call"}, {"api_name": "shutil.copy2", "line_number": 321, "usage_type": "call"}, {"api_name": "shutil.copy2", "line_number": 324, "usage_type": "call"}, {"api_name": "shutil.copy2", "line_number": 329, "usage_type": "call"}, {"api_name": "shutil.copy2", "line_number": 332, "usage_type": "call"}, {"api_name": "shutil.copy2", "line_number": 335, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 344, "usage_type": "call"}, {"api_name": "os.path", "line_number": 344, "usage_type": "attribute"}, {"api_name": "os.rmdir", "line_number": 345, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 346, "usage_type": "call"}, {"api_name": "os.path", "line_number": 346, "usage_type": "attribute"}, {"api_name": "os.rmdir", "line_number": 347, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 355, "usage_type": "call"}, {"api_name": "shutil.copytree", "line_number": 357, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 364, "usage_type": "call"}, {"api_name": "shutil.copytree", "line_number": 366, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 370, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 373, "usage_type": "call"}, {"api_name": "os.path", "line_number": 373, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 374, "usage_type": "call"}, {"api_name": "os.path", "line_number": 374, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 377, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 377, "usage_type": "name"}, {"api_name": "PIL.ImageEnhance.Contrast", "line_number": 378, "usage_type": "call"}, {"api_name": "PIL.ImageEnhance", "line_number": 378, "usage_type": "name"}, {"api_name": "PIL.ImageEnhance.Brightness", "line_number": 381, "usage_type": "call"}, {"api_name": "PIL.ImageEnhance", "line_number": 381, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 387, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 390, "usage_type": "call"}, {"api_name": "os.path", "line_number": 390, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 391, "usage_type": "call"}, {"api_name": "os.path", "line_number": 391, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 394, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 394, "usage_type": "name"}, {"api_name": "PIL.ImageEnhance.Contrast", "line_number": 395, "usage_type": "call"}, {"api_name": "PIL.ImageEnhance", "line_number": 395, "usage_type": "name"}, {"api_name": "PIL.ImageEnhance.Brightness", "line_number": 398, "usage_type": "call"}, {"api_name": "PIL.ImageEnhance", "line_number": 398, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 418, "usage_type": "call"}, {"api_name": "PySimpleGUI.Window", "line_number": 434, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 435, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 436, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 438, "usage_type": "call"}, {"api_name": "PySimpleGUI.Submit", "line_number": 439, "usage_type": "call"}, {"api_name": "PySimpleGUI.Window", "line_number": 448, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 449, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 450, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 452, "usage_type": "call"}, {"api_name": "PySimpleGUI.Submit", "line_number": 453, "usage_type": "call"}, {"api_name": "PySimpleGUI.Window", "line_number": 469, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 470, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 471, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 473, "usage_type": "call"}, {"api_name": "PySimpleGUI.Submit", "line_number": 474, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 518, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 520, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 523, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 525, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 529, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 531, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 534, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 536, "usage_type": "call"}, {"api_name": "PySimpleGUI.Window", "line_number": 554, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 555, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 556, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 558, "usage_type": "call"}, {"api_name": "PySimpleGUI.Submit", "line_number": 559, "usage_type": "call"}, {"api_name": "PySimpleGUI.Window", "line_number": 563, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 564, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 565, "usage_type": "call"}, {"api_name": "PySimpleGUI.Text", "line_number": 567, "usage_type": "call"}, {"api_name": "PySimpleGUI.Submit", "line_number": 568, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 583, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 630, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 640, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 648, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 656, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 664, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 672, "usage_type": "call"}]} +{"seq_id": "11528210676", "text": "import requests\nimport os\nfrom datetime import datetime\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n\nAPI_KEY = os.environ[\"SHEETY_API_KEY\"]\nAPP_ID = os.environ[\"SHEETY_APP_ID\"]\nENDPOINT = os.environ[\"SHEETY_ENDPOINT\"]\nSHEETY_WORKOUT_ENDPOINT = os.environ[\"SHEETY_WORKOUT_ENDPOINT\"]\n\ntoday = datetime(year=2023, month=5, day=1)\ntoday_dated_formated = today.strftime(\"%d/%m/%Y\")\nnow_time = datetime.now().strftime(\"%X\")\n\nHEADERS = {\n \"x-app-id\": APP_ID,\n \"x-app-key\": API_KEY, \n}\n\nuser_input = input(\"Tell me what exercise you did: \")\n\nPARAMETERS = {\n \"query\": user_input\n}\n\nresponse = requests.post(url=ENDPOINT, json=PARAMETERS, headers=HEADERS)\nresponse.raise_for_status()\ndata = response.json()\n\nexercise = data[\"exercises\"][0][\"name\"].title()\nduration = data[\"exercises\"][0][\"duration_min\"]\ncalories = data[\"exercises\"][0][\"nf_calories\"]\n\n\n\n\nSHEETY_PARAMETERS = {\n\"workout\": {\n \"date\": today_dated_formated,\n \"time\": now_time,\n \"exercise\": exercise,\n \"duration\": duration,\n \"calories\": calories,\n }\n}\n\n\n\n\nsheety_response = requests.post(url=SHEETY_WORKOUT_ENDPOINT, json=SHEETY_PARAMETERS)\nsheety_response.raise_for_status()\nprint(sheety_response.text)", "repo_name": "freddyflo/back-to-python", "sub_path": "workout-tracker/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1186, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "dotenv.load_dotenv", "line_number": 6, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 12, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 16, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 29, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 53, "usage_type": "call"}]} +{"seq_id": "29416893592", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport time\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport pdb\n\n\nCUDA = torch.cuda.is_available()\n\n\nclass ConvKB(nn.Module):\n def __init__(self, input_dim, input_seq_len, in_channels, out_channels, drop_prob, alpha_leaky):\n super().__init__()\n\n self.conv_layer = nn.Conv2d(\n in_channels, out_channels, (1, input_seq_len)) # kernel size -> 1*input_seq_length(i.e. 2)\n self.dropout = nn.Dropout(drop_prob)\n self.non_linearity = nn.ReLU()\n self.fc_layer = nn.Linear((input_dim) * out_channels, 1)\n\n nn.init.xavier_uniform_(self.fc_layer.weight, gain=1.414)\n nn.init.xavier_uniform_(self.conv_layer.weight, gain=1.414)\n\n def forward(self, conv_input):\n\n batch_size, length, dim = conv_input.size()\n # assuming inputs are of the form ->\n conv_input = conv_input.transpose(1, 2)\n # batch * length(which is 3 here -> entity,relation,entity) * dim\n # To make tensor of size 4, where second dim is for input channels\n conv_input = conv_input.unsqueeze(1)\n\n out_conv = self.dropout(\n self.non_linearity(self.conv_layer(conv_input)))\n\n input_fc = out_conv.squeeze(-1).view(batch_size, -1)\n output = self.fc_layer(input_fc)\n return output\n\n\nclass SpecialSpmmFunctionFinal(torch.autograd.Function):\n \"\"\"Special function for only sparse region backpropataion layer.\"\"\"\n @staticmethod\n def forward(ctx, edge, edge_w, N, E, out_features):\n # assert indices.requires_grad == False\n a = torch.sparse_coo_tensor(\n edge, edge_w, torch.Size([N, N, out_features]))\n b = torch.sparse.sum(a, dim=1)\n ctx.N = b.shape[0]\n ctx.outfeat = b.shape[1]\n ctx.E = E\n ctx.indices = a._indices()[0, :]\n\n return b.to_dense()\n\n @staticmethod\n def backward(ctx, grad_output):\n grad_values = None\n if ctx.needs_input_grad[1]:\n edge_sources = ctx.indices\n\n if(CUDA):\n edge_sources = edge_sources.cuda()\n\n grad_values = grad_output[edge_sources]\n # grad_values = grad_values.view(ctx.E, ctx.outfeat)\n # print(\"Grad Outputs-> \", grad_output)\n # print(\"Grad values-> \", grad_values)\n return None, grad_values, None, None, None\n\nclass SpecialSpmmFunctionFinal_rel(torch.autograd.Function):\n \"\"\"Special function for only sparse region backpropataion layer.\"\"\"\n @staticmethod\n def forward(ctx, edge, edge_w, N1, N2, E, out_features):\n # assert indices.requires_grad == False\n a = torch.sparse_coo_tensor(\n edge, edge_w, torch.Size([N1, N2, out_features]))\n b = torch.sparse.sum(a, dim=1)\n ctx.N = b.shape[0]\n ctx.outfeat = b.shape[1]\n ctx.E = E\n ctx.indices = a._indices()[0, :]\n\n return b.to_dense()\n\n @staticmethod\n def backward(ctx, grad_output):\n grad_values = None\n if ctx.needs_input_grad[1]:\n edge_sources = ctx.indices\n\n if(CUDA):\n edge_sources = edge_sources.cuda()\n\n grad_values = grad_output[edge_sources]\n # grad_values = grad_values.view(ctx.E, ctx.outfeat)\n # print(\"Grad Outputs-> \", grad_output)\n # print(\"Grad values-> \", grad_values)\n return None, grad_values, None, None, None, None\n\n\nclass SpecialSpmmFinal(nn.Module):\n def forward(self, edge, edge_w, N, E, out_features):\n return SpecialSpmmFunctionFinal.apply(edge, edge_w, N, E, out_features)\n\nclass SpecialSpmmFinal_rel(nn.Module):\n def forward(self, edge, edge_w, N1, N2, E, out_features):\n return SpecialSpmmFunctionFinal_rel.apply(edge, edge_w, N1, N2, E, out_features)\n\n\nclass SpGraphAttentionLayer(nn.Module):\n \"\"\"\n Sparse version GAT layer, similar to https://arxiv.org/abs/1710.10903\n \"\"\"\n\n def __init__(self, num_nodes, in_features, out_features, nrela_dim, dropout, alpha, concat=True, n_path=1):\n super(SpGraphAttentionLayer, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.num_nodes = num_nodes\n self.alpha = alpha\n self.concat = concat\n self.nrela_dim = nrela_dim\n\n self.a = nn.Parameter(torch.zeros(\n size=(out_features, 2 * in_features + nrela_dim)))\n nn.init.xavier_normal_(self.a.data, gain=1.414)\n # self.a_reverse = nn.Parameter(torch.zeros(\n # size=(out_features, 2 * in_features + nrela_dim)))\n # nn.init.xavier_normal_(self.a_reverse.data, gain=1.414)\n\n self.a_2 = nn.Parameter(torch.zeros(size=(1, out_features)))\n nn.init.xavier_normal_(self.a_2.data, gain=1.414)\n # self.a_2_reverse = nn.Parameter(torch.zeros(size=(1, out_features)))\n # nn.init.xavier_normal_(self.a_2_reverse.data, gain=1.414)\n\n\n self.dropout = nn.Dropout(dropout)\n self.leakyrelu = nn.LeakyReLU(self.alpha)\n self.special_spmm_final = SpecialSpmmFinal()\n\n\n # pdb.set_trace()\n if n_path>0:\n self.W_h_e = nn.Parameter(torch.zeros(\n size=(self.out_features * 2, self.out_features*2)))\n nn.init.xavier_uniform_(self.W_h_e.data, gain=1.414)\n self.W_h_p = nn.Parameter(torch.zeros(\n size=(self.out_features * 2, self.out_features*2)))\n nn.init.xavier_uniform_(self.W_h_e.data, gain=1.414)\n self.W_h_b = nn.Parameter(torch.zeros(\n size=(1, self.out_features*2)))\n nn.init.xavier_uniform_(self.W_h_b.data, gain=1.414)\n\n\n self.W_h = nn.Parameter(torch.zeros(\n size=(self.out_features * 2, self.out_features)))\n nn.init.xavier_uniform_(self.W_h.data, gain=1.414)\n else:\n self.W_h = nn.Parameter(torch.zeros(\n size=(self.out_features * 2, self.out_features)))\n nn.init.xavier_uniform_(self.W_h.data, gain=1.414)\n\n\n def forward(self, input, edge, edge_embed, edge_reverse, edge_embed_reverse,\n edge_list_nhop, edge_embed_nhop, edge_list_reverse_nhop, edge_embed_reverse_nhop,\n edge_path, all_node_path_toedge, all_rel_path):\n N = input.size()[0]\n # pdb.set_trace()\n # Self-attention on the nodes - Shared attention mechanism\n if len(edge_list_nhop)>0:\n edge = torch.cat((edge[:, :], edge_list_nhop[:, :]), dim=1)\n edge_embed = torch.cat((edge_embed[:, :], edge_embed_nhop[:, :]), dim=0)\n edge_h = torch.cat((input[edge[0, :], :], input[edge[1, :], :], edge_embed[:, :]), dim=1).t()\n\n if len(edge_list_reverse_nhop) > 0:\n edge_reverse = torch.cat((edge_reverse[:, :], edge_list_reverse_nhop[:, :]), dim=1)\n edge_embed_reverse = torch.cat((edge_embed_reverse[:, :], edge_embed_reverse_nhop[:, :]), dim=0)\n edge_h_reverse = torch.cat((input[edge_reverse[0, :], :], input[edge_reverse[1, :], :], edge_embed_reverse[:, :]), dim=1).t()\n\n\n if len(edge_path)>0:\n # for path, a path attention or path + neighbor attention with neighbor\n edge_path_h = torch.cat((all_node_path_toedge[:,:], all_rel_path[:,:]),dim=1).t()\n edge_path_h_reverse = edge_path_h\n edge_path = edge_path.t()\n edge_path_reverse = torch.cat((edge_path[1, :].unsqueeze(0), edge_path[0, :].unsqueeze(0)), dim=0)\n\n edge_path_m = self.a.mm(edge_path_h)\n edge_path_m_reverse = self.a.mm(edge_path_h_reverse)\n\n powers_path = -self.leakyrelu(self.a_2.mm(edge_path_m).squeeze())\n powers_path_reverse = -self.leakyrelu(self.a_2.mm(edge_path_m_reverse).squeeze())\n\n edge_path_e = torch.exp(powers_path).unsqueeze(1)\n edge_path_e_reverse = torch.exp(powers_path_reverse).unsqueeze(1)\n assert not torch.isnan(edge_path_e).any()\n assert not torch.isnan(edge_path_e_reverse).any()\n\n e_path_rowsum = self.special_spmm_final(\n edge_path, edge_path_e, N, edge_path_e.shape[0], 1)\n e_path_rowsum[e_path_rowsum == 0.0] = 1e-12\n\n e_path_rowsum_reverse = self.special_spmm_final(\n edge_path_reverse, edge_path_e_reverse, N, edge_path_e_reverse.shape[0], 1)\n e_path_rowsum_reverse[e_path_rowsum_reverse == 0.0] = 1e-12\n\n e_path_rowsum = e_path_rowsum\n e_path_rowsum_reverse = e_path_rowsum_reverse\n\n edge_path_e = edge_path_e.squeeze(1)\n edge_path_e = self.dropout(edge_path_e)\n\n edge_path_e_reverse = edge_path_e_reverse.squeeze(1)\n edge_path_e_reverse = self.dropout(edge_path_e_reverse)\n\n edge_path_w = (edge_path_e * edge_path_m).t()\n edge_path_w_reverse = (edge_path_e_reverse * edge_path_m_reverse).t()\n\n h_path_prime = self.special_spmm_final(\n edge_path, edge_path_w, N, edge_path_w.shape[0], self.out_features)\n h_path_prime_reverse = self.special_spmm_final(\n edge_path_reverse, edge_path_w_reverse, N, edge_path_w_reverse.shape[0], self.out_features)\n assert not torch.isnan(h_path_prime).any()\n assert not torch.isnan(h_path_prime_reverse).any()\n\n h_path_prime = h_path_prime.div(e_path_rowsum)\n h_path_prime_reverse = h_path_prime_reverse.div(e_path_rowsum_reverse)\n\n\n # edge_h: (2*in_dim + nrela_dim) x E\n edge_m = self.a.mm(edge_h)\n edge_m_reverse = self.a.mm(edge_h_reverse)\n # edge_m: D * E\n\n # to be checked later\n powers = -self.leakyrelu(self.a_2.mm(edge_m).squeeze())\n powers_reverse = -self.leakyrelu(self.a_2.mm(edge_m_reverse).squeeze())\n\n edge_e = torch.exp(powers).unsqueeze(1)\n edge_e_reverse = torch.exp(powers_reverse).unsqueeze(1)\n\n assert not torch.isnan(edge_e).any()\n assert not torch.isnan(edge_e_reverse).any()\n # edge_e: E\n\n # pdb.set_trace()\n e_rowsum = self.special_spmm_final(\n edge, edge_e, N, edge_e.shape[0], 1)\n e_rowsum[e_rowsum == 0.0] = 1e-12\n\n e_rowsum_reverse = self.special_spmm_final(\n edge_reverse, edge_e_reverse, N, edge_e_reverse.shape[0], 1)\n e_rowsum_reverse[e_rowsum_reverse == 0.0] = 1e-12\n\n e_rowsum = e_rowsum\n e_rowsum_reverse = e_rowsum_reverse\n\n # e_rowsum: N x 1\n edge_e = edge_e.squeeze(1)\n edge_e = self.dropout(edge_e)\n # edge_e: E\n edge_e_reverse = edge_e_reverse.squeeze(1)\n edge_e_reverse = self.dropout(edge_e_reverse)\n\n edge_w = (edge_e * edge_m).t()\n edge_w_reverse = (edge_e_reverse * edge_m_reverse).t()\n # edge_w: E * D\n\n h_prime = self.special_spmm_final(\n edge, edge_w, N, edge_w.shape[0], self.out_features)\n h_prime_reverse = self.special_spmm_final(\n edge_reverse, edge_w_reverse, N, edge_w_reverse.shape[0], self.out_features)\n\n assert not torch.isnan(h_prime).any()\n assert not torch.isnan(h_prime_reverse).any()\n\n # h_prime: N x out\n h_prime = h_prime.div(e_rowsum)\n h_prime_reverse = h_prime_reverse.div(e_rowsum_reverse)\n\n # pdb.set_trace()\n # h_prime: N x out\n if len(edge_path) > 0:\n h_prime_e = torch.cat((h_prime, h_prime_reverse),dim=-1)\n h_prime_p = torch.cat((h_path_prime,h_path_prime_reverse), dim=-1)\n ht=torch.sigmoid(h_prime_e.mm(self.W_h_e)+h_prime_p.mm(self.W_h_p)+self.W_h_b)\n h_prime = ht*h_prime_e + (1-ht)*h_prime_p\n # h_prime = h_prime_p\n\n # h_prime = torch.cat((h_prime, h_prime_reverse, h_path_prime,h_path_prime_reverse), dim=-1)\n else:\n h_prime = torch.cat((h_prime, h_prime_reverse), dim=-1)\n h_prime = h_prime.mm(self.W_h)\n\n assert not torch.isnan(h_prime).any()\n if self.concat:\n # if this layer is not last layer,\n return F.elu(h_prime)\n else:\n # if this layer is last layer,\n return h_prime\n\n def __repr__(self):\n return self.__class__.__name__ + ' (' + str(self.in_features) + ' -> ' + str(self.out_features) + ')'\n\n\nclass SpGraphAttentionLayer_rel(nn.Module):\n \"\"\"\n Sparse version GAT layer, similar to https://arxiv.org/abs/1710.10903\n \"\"\"\n\n def __init__(self, in_features, out_features, dropout, alpha):\n super(SpGraphAttentionLayer_rel, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.alpha = alpha\n\n self.a = nn.Parameter(torch.zeros(\n size=(out_features, in_features+out_features)))\n nn.init.xavier_normal_(self.a.data, gain=1.414)\n self.a_2 = nn.Parameter(torch.zeros(size=(1, out_features)))\n nn.init.xavier_normal_(self.a_2.data, gain=1.414)\n\n self.dropout = nn.Dropout(dropout)\n self.leakyrelu = nn.LeakyReLU(self.alpha)\n self.special_spmm_final_rel = SpecialSpmmFinal_rel()\n\n def forward(self, input, edge, edge_embed):\n N1 = input.size()[0]\n N2 = max(edge[1,:]).tolist()+1\n\n # Self-attention on the nodes - Shared attention mechanism\n # pdb.set_trace()\n edge_h = torch.cat((input[edge[0, :], :], edge_embed[:, :]), dim=1).t()\n # edge_h: (2*in_dim + nrela_dim) x E\n\n edge_m = self.a.mm(edge_h)\n # edge_m: D * E\n\n # to be checked later\n powers = -self.leakyrelu(self.a_2.mm(edge_m).squeeze())\n edge_e = torch.exp(powers).unsqueeze(1)\n assert not torch.isnan(edge_e).any()\n # edge_e: E\n\n e_rowsum = self.special_spmm_final_rel(\n edge, edge_e, N1, N2, edge_e.shape[0], 1)\n e_rowsum[e_rowsum == 0.0] = 1e-12\n\n e_rowsum = e_rowsum\n # e_rowsum: N x 1\n edge_e = edge_e.squeeze(1)\n\n edge_e = self.dropout(edge_e)\n # edge_e: E\n\n edge_w = (edge_e * edge_m).t()\n # edge_w: E * D\n\n h_prime = self.special_spmm_final_rel(\n edge, edge_w, N1, N2, edge_w.shape[0], self.out_features)\n\n assert not torch.isnan(h_prime).any()\n # h_prime: N x out\n h_prime = h_prime.div(e_rowsum)\n # h_prime: N x out\n\n assert not torch.isnan(h_prime).any()\n # if this layer is last layer,\n return h_prime\n", "repo_name": "feiwangyuzhou/GGAE", "sub_path": "layers.py", "file_name": "layers.py", "file_ext": "py", "file_size_in_byte": 14454, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "20", "api": [{"api_name": "torch.cuda.is_available", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 10, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 13, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 13, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 17, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_uniform_", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 23, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.nn.init.xavier_uniform_", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 24, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 24, "usage_type": "name"}, {"api_name": "torch.autograd", "line_number": 43, "usage_type": "attribute"}, {"api_name": "torch.sparse_coo_tensor", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.Size", "line_number": 49, "usage_type": "call"}, {"api_name": "torch.sparse.sum", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.sparse", "line_number": 50, "usage_type": "attribute"}, {"api_name": "torch.autograd", "line_number": 73, "usage_type": "attribute"}, {"api_name": "torch.sparse_coo_tensor", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.Size", "line_number": 79, "usage_type": "call"}, {"api_name": "torch.sparse.sum", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.sparse", "line_number": 80, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 104, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 104, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 108, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 108, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 113, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 113, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 127, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 127, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 127, "usage_type": "call"}, {"api_name": "torch.nn.init.xavier_normal_", "line_number": 129, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 129, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 129, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 134, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 134, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 134, "usage_type": "call"}, {"api_name": "torch.nn.init.xavier_normal_", "line_number": 135, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 135, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 135, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 140, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 140, "usage_type": "name"}, {"api_name": "torch.nn.LeakyReLU", "line_number": 141, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 141, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 147, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.nn.init.xavier_uniform_", "line_number": 149, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 149, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 149, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 150, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 150, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 150, "usage_type": "call"}, {"api_name": "torch.nn.init.xavier_uniform_", "line_number": 152, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 152, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 152, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 153, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 153, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 153, "usage_type": "call"}, {"api_name": "torch.nn.init.xavier_uniform_", "line_number": 155, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 155, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 155, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 158, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 158, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 158, "usage_type": "call"}, {"api_name": "torch.nn.init.xavier_uniform_", "line_number": 160, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 160, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 160, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 162, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.nn.init.xavier_uniform_", "line_number": 164, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 164, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 164, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 174, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 175, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 176, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 179, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 180, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 181, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 186, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 189, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 197, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 198, "usage_type": "call"}, {"api_name": "torch.isnan", "line_number": 199, "usage_type": "call"}, {"api_name": "torch.isnan", "line_number": 200, "usage_type": "call"}, {"api_name": "torch.isnan", "line_number": 226, "usage_type": "call"}, {"api_name": "torch.isnan", "line_number": 227, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 242, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 243, "usage_type": "call"}, {"api_name": "torch.isnan", "line_number": 245, "usage_type": "call"}, {"api_name": "torch.isnan", "line_number": 246, "usage_type": "call"}, {"api_name": "torch.isnan", "line_number": 277, "usage_type": "call"}, {"api_name": "torch.isnan", "line_number": 278, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 287, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 288, "usage_type": "call"}, {"api_name": "torch.sigmoid", "line_number": 289, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 295, "usage_type": "call"}, {"api_name": "torch.isnan", "line_number": 298, "usage_type": "call"}, {"api_name": "torch.nn.functional.elu", "line_number": 301, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 301, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 310, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 310, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 321, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 321, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 321, "usage_type": "call"}, {"api_name": "torch.nn.init.xavier_normal_", "line_number": 323, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 323, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 323, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 324, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 324, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 324, "usage_type": "call"}, {"api_name": "torch.nn.init.xavier_normal_", "line_number": 325, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 325, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 325, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 327, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 327, "usage_type": "name"}, {"api_name": "torch.nn.LeakyReLU", "line_number": 328, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 328, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 337, "usage_type": "call"}, {"api_name": "torch.exp", "line_number": 345, "usage_type": "call"}, {"api_name": "torch.isnan", "line_number": 346, "usage_type": "call"}, {"api_name": "torch.isnan", "line_number": 366, "usage_type": "call"}, {"api_name": "torch.isnan", "line_number": 371, "usage_type": "call"}]} +{"seq_id": "40757088760", "text": "from discord.ext import commands\r\n\r\n\r\nclass GuildCog(commands.Cog):\r\n \"\"\"Extension designated for commands that interact with the guild.\"\"\"\r\n\r\n __slots__ = \"client\"\r\n\r\n def __init__(self, client):\r\n self.client = client\r\n\r\n @commands.command()\r\n @commands.guild_only()\r\n @commands.has_permissions(manage_guild=True)\r\n @commands.cooldown(1, 2, commands.BucketType.guild)\r\n async def leave(self, ctx):\r\n \"\"\"Makes me leave the guild.\"\"\"\r\n\r\n await ctx.send(desc=f\"You sure you want me to leave, {ctx.author}?\")\r\n confirmation = await self.client.wait_for(\"message\", check=lambda msg: msg.author == ctx.author)\r\n\r\n if confirmation.content.startswith(\"y\"):\r\n await ctx.send(desc=f\"Alright, leaving. {ctx.reactions.get('ok')}\", reaction=ctx.reactions.get(\"check\"))\r\n await ctx.guild.leave()\r\n else:\r\n await ctx.send(desc=f\"Didn't get an answer starting with 'y'. Guess I'll stay. {ctx.reactions.get('ok')}\")\r\n\r\n @commands.command()\r\n @commands.cooldown(1, 2, commands.BucketType.guild)\r\n @commands.check(lambda x: x.author.id == 700091773695033505 or x.author.guild_permissions.manage_guild)\r\n async def prefix(self, ctx, new_prefix):\r\n \"\"\"Edit the guild prefix.\"\"\"\r\n\r\n await ctx.send(desc=f\"Are you sure you wanna make the new guild prefix '{new_prefix}'\")\r\n\r\n response = await self.client.wait_for(\"message\", check=lambda m: m.author == ctx.author)\r\n\r\n if response.content.startswith(\"y\"):\r\n await self.client.db.execute(\r\n \"\"\"\r\n INSERT INTO guilds(id, prefix)\r\n VALUES($1, $2)\r\n ON CONFLICT (id)\r\n DO UPDATE\r\n SET prefix=$2\r\n \"\"\",\r\n ctx.guild.id,\r\n new_prefix\r\n )\r\n\r\n self.client.cache[\"prefix\"][ctx.guild.id] = new_prefix\r\n await ctx.send(desc=\"Alright, the new guild prefix is set.\", reaction=ctx.reactions.get(\"check\"))\r\n else:\r\n await ctx.send(desc=\"Alright, I didn't change anything.\")\r\n\r\n\r\ndef setup(client):\r\n client.add_cog(GuildCog(client))\r\n", "repo_name": "wellinthatcase/ft.-Gunna", "sub_path": "extensions/guild.py", "file_name": "guild.py", "file_ext": "py", "file_size_in_byte": 2186, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "discord.ext.commands.Cog", "line_number": 4, "usage_type": "attribute"}, {"api_name": "discord.ext.commands", "line_number": 4, "usage_type": "name"}, {"api_name": "discord.ext.commands.command", "line_number": 12, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 12, "usage_type": "name"}, {"api_name": "discord.ext.commands.guild_only", "line_number": 13, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 13, "usage_type": "name"}, {"api_name": "discord.ext.commands.has_permissions", "line_number": 14, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 14, "usage_type": "name"}, {"api_name": "discord.ext.commands.cooldown", "line_number": 15, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 15, "usage_type": "name"}, {"api_name": "discord.ext.commands.BucketType", "line_number": 15, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.command", "line_number": 28, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 28, "usage_type": "name"}, {"api_name": "discord.ext.commands.cooldown", "line_number": 29, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 29, "usage_type": "name"}, {"api_name": "discord.ext.commands.BucketType", "line_number": 29, "usage_type": "attribute"}, {"api_name": "discord.ext.commands.check", "line_number": 30, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 30, "usage_type": "name"}]} +{"seq_id": "40515147633", "text": "from django.shortcuts import render\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef home(request):\n # thi url old version\n #url = 'https://www.urdupoint.com/islam/dhaka-ramadan-calendar-sehar-aftar-timing.html'\n #this url in updated\n url = 'https://www.urdupoint.com/islam/ramadan-calendar-sehar-aftar-timings-up.html'\n data = requests.get(url)\n soup = BeautifulSoup(data.content,'html.parser')\n ramadan = soup.find('table')\n ramadan_head = [i.text for i in ramadan.find_all('th')]\n ramadan_doc = [x.text for x in ramadan.find_all('td')]\n output = {}\n for rh in range(len(ramadan_head)):\n if ramadan_head[2] == ramadan_head[rh]:\n mydata = ramadan_doc[2]\n output[ramadan_head[rh]] = f'{int(mydata[:2])-12}{mydata[2:]} PM'\n print(f'{ramadan_head[rh]} = {int(mydata[:2])-12}{mydata[2:]}')\n else:\n output[ramadan_head[rh]] = f'{ramadan_doc[rh]} AM'\n print(f'{ramadan_head[rh]} = {ramadan_doc[rh]}')\n print('This is output:',output)\n return render(request,'index.html',context={'finaloutput':output})", "repo_name": "MehediMK/Django_Ramadan_schedule_API", "sub_path": "ramadan/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1107, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "requests.get", "line_number": 10, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 11, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "73337404210", "text": "import os\nimport sys\nfrom collections import namedtuple\n\nfrom Cryptodome.Cipher import AES\nfrom django.apps import apps as django_apps\nfrom django.conf import settings\nfrom django.core.checks import Critical, Error\n\nfrom .cryptor import Cryptor\nfrom .persist_key_path import (\n DjangoCryptoFieldsKeyPathChangeError,\n DjangoCryptoFieldsKeyPathError,\n persist_key_path,\n)\n\nerr = namedtuple(\"Err\", \"id cls\")\n\nerror_configs = dict(\n key_path_check=err(\"django_crypto_fields.C001\", Critical),\n encryption_keys_check=err(\"django_crypto_fields.E001\", Error),\n aes_mode_check=err(\"django_crypto_fields.E002\", Error),\n)\n\n\ndef testing():\n if \"test\" in sys.argv:\n return True\n if \"runtests\" in sys.argv:\n return True\n return False\n\n\ndef key_path_check(app_configs, **kwargs):\n errors = []\n if not settings.DEBUG:\n app_config = django_apps.get_app_config(\"django_crypto_fields\")\n key_path = app_config.key_path\n error = error_configs.get(\"key_path_check\")\n check_failed = False\n filename = os.path.join(settings.ETC_DIR, \"django_crypto_fields\")\n hint = f\"settings.KEY_PATH does not match the path stored in {filename}.\"\n try:\n persist_key_path(key_path=key_path, filename=filename)\n except (\n DjangoCryptoFieldsKeyPathChangeError,\n DjangoCryptoFieldsKeyPathError,\n ) as e:\n error_msg = str(e)\n check_failed = True\n if check_failed:\n errors.append(error.cls(error_msg, hint=hint, obj=None, id=error.id))\n return errors\n\n\ndef encryption_keys_check(app_configs, **kwargs):\n app_config = django_apps.get_app_config(\"django_crypto_fields\")\n key_files = app_config.key_files\n errors = []\n check_failed = None\n try:\n auto_create_keys = settings.AUTO_CREATE_KEYS\n except AttributeError:\n auto_create_keys = None\n if key_files.key_files_exist and auto_create_keys and not testing():\n error = error_configs.get(\"encryption_keys_check\")\n error_msg = \"settings.AUTO_CREATE_KEYS may not be 'True' when encryption keys exist.\"\n hint = (\n \"Did you backup your keys? Perhaps you just created new keys, \"\n \"to continue, set AUTO_CREATE_KEYS=False and restart.\"\n )\n check_failed = True\n if check_failed:\n errors.append(error.cls(error_msg, hint=hint, obj=None, id=error.id))\n return errors\n\n\ndef aes_mode_check(app_configs, **kwargs):\n error = error_configs.get(\"aes_mode_check\")\n errors = []\n hint = \"See django_crypto_fields.cryptor.py and comments in pycryptodomex.blockalgo.py.\"\n cryptor = Cryptor()\n if cryptor.aes_encryption_mode == AES.MODE_CFB:\n error_msg = \"Encryption mode MODE_CFB should not be used.\"\n errors.append(error.cls(error_msg, hint=hint, obj=None, id=error.id))\n return errors\n", "repo_name": "erikvw/django-crypto-fields", "sub_path": "django_crypto_fields/system_checks.py", "file_name": "system_checks.py", "file_ext": "py", "file_size_in_byte": 2892, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 24, "dataset": "github-code", "pt": "20", "api": [{"api_name": "collections.namedtuple", "line_number": 17, "usage_type": "call"}, {"api_name": "django.core.checks.Critical", "line_number": 20, "usage_type": "argument"}, {"api_name": "django.core.checks.Error", "line_number": 21, "usage_type": "argument"}, {"api_name": "django.core.checks.Error", "line_number": 22, "usage_type": "argument"}, {"api_name": "sys.argv", "line_number": 27, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 29, "usage_type": "attribute"}, {"api_name": "django.conf.settings.DEBUG", "line_number": 36, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 36, "usage_type": "name"}, {"api_name": "django.apps.apps.get_app_config", "line_number": 37, "usage_type": "call"}, {"api_name": "django.apps.apps", "line_number": 37, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "attribute"}, {"api_name": "django.conf.settings.ETC_DIR", "line_number": 41, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 41, "usage_type": "name"}, {"api_name": "persist_key_path.persist_key_path", "line_number": 44, "usage_type": "call"}, {"api_name": "persist_key_path.DjangoCryptoFieldsKeyPathChangeError", "line_number": 46, "usage_type": "name"}, {"api_name": "persist_key_path.DjangoCryptoFieldsKeyPathError", "line_number": 47, "usage_type": "name"}, {"api_name": "django.apps.apps.get_app_config", "line_number": 57, "usage_type": "call"}, {"api_name": "django.apps.apps", "line_number": 57, "usage_type": "name"}, {"api_name": "django.conf.settings.AUTO_CREATE_KEYS", "line_number": 62, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 62, "usage_type": "name"}, {"api_name": "cryptor.Cryptor", "line_number": 82, "usage_type": "call"}, {"api_name": "cryptor.aes_encryption_mode", "line_number": 83, "usage_type": "attribute"}, {"api_name": "Cryptodome.Cipher.AES.MODE_CFB", "line_number": 83, "usage_type": "attribute"}, {"api_name": "Cryptodome.Cipher.AES", "line_number": 83, "usage_type": "name"}]} +{"seq_id": "41296121895", "text": "import logging\nfrom enum import Enum\n\n# /v1/skyatp/infected_hosts/{list_type}\n\nlog = logging.getLogger(__name__)\n\n\nclass ListType(Enum):\n WHITELIST = 0\n BLACKLIST = 1\n\n\nclass JuniperSkyAtpClient(object):\n def __init__(self, session=None, api_token=None, url=None, log_level=None):\n self.session = session\n self.api_token = api_token\n self.url = url if url else \"https://api.sky.junipersecurity.net\"\n self.headers = {\n \"Authorization\": \"Bearer \" + self.api_token,\n \"content-type\" : \"application/json\"\n }\n log.setLevel(logging.INFO if not log_level else log_level)\n\n # /v1/skyatp/infected_hosts/\n def infected_hosts_wlbl(self, listtype=None):\n if not listtype:\n listtype = ListType.BLACKSLIT\n uri = \"/v1/skyatp/infected_hosts/\" + listtype.name.lower()\n\n response = self.session.get(url=self.url + uri, headers=self.headers)\n log.debug(\"get_report: response = %s \" % response)\n return response.json()\n\n def get_infected_hosts(self):\n uri = \"/v1/skatp/infected_hosts\"\n response = self.session.get(url=self.url + uri,headers=self.headers)\n return response.json()\n\n def update_infected_hosts_wlbl(self, update, listtype=None):\n if not listtype:\n listtype = ListType.BLACKLIST\n uri = \"/v1/skyatp/infected_hosts/\" + listtype.name.lower()\n response = self.session.patch(url=self.url + uri, headers=self.headers, data=update)\n return response.json()\n\n def remove_infected_hosts_wlbl(self, remove, listtype=None):\n if not listtype:\n listtype = ListType.BLACKLIST\n uri = \"/v1/skyatp/infected_hosts/\" + listtype.name.lower()\n response = self.session.delete(url=self.url + uri, headers=self.headers, data=remove)\n return response.json()\n", "repo_name": "carbonblack/cb-skyatp-connector", "sub_path": "cbopensource/connectors/skyatp/skyatp_api.py", "file_name": "skyatp_api.py", "file_ext": "py", "file_size_in_byte": 1856, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "logging.getLogger", "line_number": 6, "usage_type": "call"}, {"api_name": "enum.Enum", "line_number": 9, "usage_type": "name"}, {"api_name": "logging.INFO", "line_number": 23, "usage_type": "attribute"}]} +{"seq_id": "24701371926", "text": "from __future__ import print_function\n\nimport random\nimport gym\nimport numpy as np\nimport tensorflow as tf\nfrom keras import backend as K\nimport models\n\nsess = tf.Session()\nK.set_session(sess)\n\nrun_name = \"mentor_qnet\"\nsummary_name = run_name + \"_accuracy\"\nmodel_save_name = run_name + \".h5\"\n\n# some params\nmax_episodes = 2500\nbatch_size = 1\nepsilon = 0.1\nepisode_len = 1000\ndiscount = True\nstandardize = True\n\nenv = gym.make('CartPole-v0')\nepisode_rewards = []\n\n# helper Methods\ndef predict(model, input):\n # print (model)\n # print (input)\n # print (model.inbound_nodes)\n # print (len(model.layers))\n # for l in model.layers:\n # print (l, l.inbound_nodes)\n input = input[np.newaxis,:]\n return model.predict(input)\n\n\ndef sample(x):\n assert isinstance(x, np.ndarray)\n x = np.squeeze(x)\n assert x.ndim == 1\n # renormalize to avoid 'does not sum to 1 errors'\n return np.random.choice(len(x), 1, p=x/x.sum())\n\n\ndef rollout_env_with_policy(env, policy, episode_len=np.inf, render=True, verbose=False):\n \"\"\"\n Runs environment to completion and returns reward under given policy\n Returns the sequence of rewards, states, raw actions (direct from the policy),\n and processed actions (actions sent to the env)\n \"\"\"\n ep_rewards = []\n ep_states = []\n ep_raw_actions = []\n ep_processed_actions = []\n\n # episode_reward = 0.0\n done = False\n obs = env.reset()\n episode_itr = 0\n while not done and episode_itr < episode_len:\n if render:\n env.render()\n\n ep_states.append(obs)\n # print (policy)\n # print (obs)\n action = sess.run(policy, feed_dict={states: obs.reshape(1, len(obs))})\n # action = predict(policy, obs) #policy.predict(obs)\n\n # import sys\n # sys.exit()\n\n ep_raw_actions.append(action)\n action = sample(action)\n action = int(action)\n ep_processed_actions.append(action)\n\n obs, reward, done, _ = env.step(action)\n ep_rewards.append(reward)\n\n episode_itr += 1\n\n if verbose:\n print ('Game finished, reward: %f' % (sum(ep_rewards)))\n\n return ep_states, ep_raw_actions, ep_processed_actions, ep_rewards\n\n\ndef discount_rewards(rewards, gamma=0.9):\n \"\"\"\n Take 1D float array of rewards and compute the sum of discounted rewards\n at each timestep\n \"\"\"\n discounted_r = np.zeros_like(rewards)\n for i in xrange(rewards.size):\n rew_sum = 0.0\n for j in xrange(i, rewards.size):\n rew_sum += rewards[j] * gamma ** j\n discounted_r[i] = rew_sum\n return discounted_r\n\n\ndef standardize_rewards(rewards):\n \"\"\"\n Subtract the mean and divide by the stddev of the given rewards\n \"\"\"\n rew_mean = np.mean(rewards)\n rew_std = np.std(rewards)\n rewards -= rew_mean\n if rew_std != 0:\n rewards /= rew_std\n return rewards\n\n\n# Policy gradient operations\n\nobs_shape = tuple([None]+list(env.observation_space.shape))\nstates = tf.placeholder(tf.float32, shape=obs_shape) #(None, env.observation_space.shape[0]))\n# states = models.obs_cartpole\nactions = tf.placeholder(tf.float32, shape=(None, env.action_space.n))\nrewards = tf.placeholder(tf.float32, shape=(None))\n\n# n_input = 4\n# n_hidden_1 = 8\n# n_hidden_2 = 8\n# n_classes = 2\n# weights = {\n# 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),\n# 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),\n# 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))\n# }\n# biases = {\n# 'b1': tf.Variable(tf.random_normal([n_hidden_1])),\n# 'b2': tf.Variable(tf.random_normal([n_hidden_2])),\n# 'out': tf.Variable(tf.random_normal([n_classes]))\n# }\n# # Hidden layer with RELU activation\n# layer_1 = tf.add(tf.matmul(states, weights['h1']), biases['b1'])\n# layer_1 = tf.nn.relu(layer_1)\n# # Hidden layer with RELU activation\n# layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])\n# layer_2 = tf.nn.relu(layer_2)\n# # Output layer with softmax activation\n# out_layer = tf.matmul(layer_2, weights['out']) + biases['out']\n# probs = tf.nn.softmax(out_layer)\n\n\napprox = models.build_mentor_model_dqn(states)\nprobs = approx.output #approx(states) #.output #approx_pred\naction_probs = tf.mul(probs, actions)\nreduced_action_probs = tf.reduce_sum(action_probs, reduction_indices=[1])\nlogprobs = tf.log(reduced_action_probs)\n\n# vanilla gradient = mul(sum(logprobs * rewards))\nL = -tf.reduce_sum(tf.mul(logprobs, rewards))\nopt = tf.train.AdamOptimizer(0.01)\n\n# do gradient update separately so do apply custom function to gradients?\ngrads_and_vars = opt.compute_gradients(L)\nclipped_grads_and_vars = [(tf.clip_by_value(gv[0], -1.0, 1.0), gv[1]) for gv in grads_and_vars]\nupdate = opt.apply_gradients(clipped_grads_and_vars)\n\nsess.run(tf.initialize_all_variables())\n\nepisode = 0\nwhile episode < max_episodes:\n ep_states, ep_raw_actions, ep_processed_actions, ep_rewards = rollout_env_with_policy(env,\n probs,\n episode_len=episode_len)\n\n total_reward = sum(ep_rewards)\n episode_rewards.append(total_reward)\n\n if discount:\n ep_rewards = discount_rewards(np.array(ep_rewards))\n\n formatted_actions = np.zeros((len(ep_raw_actions), env.action_space.n))\n for i in range(len(ep_processed_actions)):\n formatted_actions[i][ep_processed_actions[i]] = 1.0\n\n formatted_rewards = ep_rewards\n if standardize:\n formatted_rewards = standardize_rewards(formatted_rewards)\n\n sess.run(update, feed_dict={actions: formatted_actions,\n states: ep_states,\n rewards: formatted_rewards})\n\n print (\"Episode: \", episode, \", reward: \", total_reward)\n if episode % 100 == 0:\n print (\"Saving model\")\n approx.save(\"mentor_polgrad.h5\")\n\n episode += 1\n\n\n\nimport matplotlib.pyplot as plt\nrewards = np.array(episode_rewards)\nplt.plot(rewards)\nplt.show()\n", "repo_name": "tpbarron/mentee_networks", "sub_path": "polgrad_mentor.py", "file_name": "polgrad_mentor.py", "file_ext": "py", "file_size_in_byte": 6079, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "tensorflow.Session", "line_number": 10, "usage_type": "call"}, {"api_name": "keras.backend.set_session", "line_number": 11, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 11, "usage_type": "name"}, {"api_name": "gym.make", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 36, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 41, "usage_type": "attribute"}, {"api_name": "numpy.squeeze", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 45, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 48, "usage_type": "attribute"}, {"api_name": "numpy.zeros_like", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 111, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 121, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 121, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 123, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 123, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 124, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 124, "usage_type": "attribute"}, {"api_name": "models.build_mentor_model_dqn", "line_number": 151, "usage_type": "call"}, {"api_name": "tensorflow.mul", "line_number": 153, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 154, "usage_type": "call"}, {"api_name": "tensorflow.log", "line_number": 155, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 158, "usage_type": "call"}, {"api_name": "tensorflow.mul", "line_number": 158, "usage_type": "call"}, {"api_name": "tensorflow.train.AdamOptimizer", "line_number": 159, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 159, "usage_type": "attribute"}, {"api_name": "tensorflow.clip_by_value", "line_number": 163, "usage_type": "call"}, {"api_name": "tensorflow.initialize_all_variables", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 178, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 180, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 202, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 203, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 203, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 204, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 204, "usage_type": "name"}]} +{"seq_id": "34809689924", "text": "import os\nimport time\nimport pybullet as p\nimport numpy as np\nimport functools\nimport gym\nimport collections\nfrom gym import spaces \nfrom enum import Enum\n\nfrom manipulation_main.common import io_utils\nfrom manipulation_main.common import transformations\nfrom manipulation_main.common import transform_utils\nfrom manipulation_main.gripperEnv import sensor, actuator\nfrom manipulation_main.simulation.simulation import World \nfrom manipulation_main.gripperEnv.rewards import Reward, SimplifiedReward, ShapedCustomReward\nfrom manipulation_main.gripperEnv.curriculum import WorkspaceCurriculum\n\ndef _reset(robot, actuator, depth_sensor, skip_empty_states=False):\n \"\"\"Reset until an object is within the fov of the camera.\"\"\"\n ok = False\n while not ok:\n robot.reset_sim() #world + scene reset\n robot.reset_model() #robot model\n actuator.reset()\n _, _, mask = depth_sensor.get_state()\n ok = len(np.unique(mask)) > 2 # plane and gripper are always visible\n\n if not skip_empty_states:\n ok = True\n\nclass RobotEnv(World):\n\n class Events(Enum):\n START_OF_EPISODE = 0\n END_OF_EPISODE = 1\n CLOSE = 2\n CHECKPOINT = 3\n\n class Status(Enum):\n RUNNING = 0\n SUCCESS = 1\n FAIL = 2\n TIME_LIMIT = 3\n\n def __init__(self, config, evaluate=False, test=False, validate=False):\n if not isinstance(config, dict):\n config = io_utils.load_yaml(config)\n \n super().__init__(config, evaluate=evaluate, test=test, validate=validate)\n self._step_time = collections.deque(maxlen=10000)\n self.time_horizon = config['time_horizon']\n self._workspace = {'lower': np.array([-1., -1., -1]),\n 'upper': np.array([1., 1., 1.])}\n self.model_path = config['robot']['model_path']\n self._simplified = config['simplified']\n self.depth_obs = config.get('depth_observation', False)\n self.full_obs = config.get('full_observation', False)\n self._initial_height = 0.3\n self._init_ori = transformations.quaternion_from_euler(np.pi, 0., 0.)\n self.main_joints = [0, 1, 2, 3] #FIXME make it better\n self._left_finger_id = 7\n self._right_finger_id = 9\n self._fingers = [self._left_finger_id, self._right_finger_id]\n\n self._model = None\n self._joints = None\n self._left_finger, self._right_finger = None, None\n self._actuator = actuator.Actuator(self, config, self._simplified)\n\n self._camera = sensor.RGBDSensor(config['sensor'], self)\n\n # Assign the reward fn\n if self._simplified:\n self._reward_fn = SimplifiedReward(config['reward'], self)\n elif config['reward']['custom']:\n self._reward_fn = ShapedCustomReward(config['reward'], self)\n else: \n self._reward_fn = Reward(config['reward'], self)\n\n # Assign the sensors\n if self.depth_obs or self.full_obs:\n self._sensors = [self._camera]\n else:\n self._encoder = sensor.EncodedDepthImgSensor(\n config, self._camera, self)\n self._sensors = [self._encoder]\n if not self._simplified:\n self._sensors.append(self._actuator)\n\n self.curriculum = WorkspaceCurriculum(config['curriculum'], self, evaluate)\n\n self.history = self.curriculum._history\n self._callbacks = {RobotEnv.Events.START_OF_EPISODE: [],\n RobotEnv.Events.END_OF_EPISODE: [],\n RobotEnv.Events.CLOSE: [],\n RobotEnv.Events.CHECKPOINT: []}\n self.register_events(evaluate, config)\n self.sr_mean = 0.\n self.setup_spaces()\n\n def register_events(self, evaluate, config):\n # Setup the reset function\n skip_empty_states = True if evaluate else config['skip_empty_initial_state']\n reset = functools.partial(_reset, self, self._actuator, self._camera,\n skip_empty_states)\n\n # Register callbacks\n self.register_callback(RobotEnv.Events.START_OF_EPISODE, reset)\n self.register_callback(RobotEnv.Events.START_OF_EPISODE, self._camera.reset)\n self.register_callback(RobotEnv.Events.START_OF_EPISODE, self._reward_fn.reset)\n self.register_callback(RobotEnv.Events.END_OF_EPISODE, self.curriculum.update)\n self.register_callback(RobotEnv.Events.CLOSE, super().close)\n\n def reset(self):\n self._trigger_event(RobotEnv.Events.START_OF_EPISODE)\n self.episode_step = 0\n self.episode_rewards = np.zeros(self.time_horizon)\n self.status = RobotEnv.Status.RUNNING\n self.obs = self._observe()\n\n return self.obs\n\n def reset_model(self):\n \"\"\"Reset the task.\n\n Returns:\n Observation of the initial state.\n \"\"\"\n self.endEffectorAngle = 0.\n start_pos = [0., 0., self._initial_height]\n self._model = self.add_model(self.model_path, start_pos, self._init_ori)\n self._joints = self._model.joints\n self.robot_id = self._model.model_id\n self._left_finger = self._model.joints[self._left_finger_id]\n self._right_finger = self._model.joints[self._right_finger_id]\n\n def _trigger_event(self, event, *event_args):\n for fn, args, kwargs in self._callbacks[event]:\n fn(*(event_args + args), **kwargs)\n\n def register_callback(self, event, fn, *args, **kwargs):\n \"\"\"Register a callback associated with the given event.\"\"\"\n self._callbacks[event].append((fn, args, kwargs))\n\n def step(self, action):\n \"\"\"Advance the Task by one step.\n\n Args:\n action (np.ndarray): The action to be executed.\n\n Returns:\n A tuple (obs, reward, done, info), where done is a boolean flag\n indicating whether the current episode finished.\n \"\"\"\n if self._model is None:\n self.reset()\n\n self._actuator.step(action)\n\n new_obs = self._observe()\n\n reward, self.status = self._reward_fn(self.obs, action, new_obs)\n self.episode_rewards[self.episode_step] = reward\n\n if self.status != RobotEnv.Status.RUNNING:\n done = True\n elif self.episode_step == self.time_horizon - 1:\n done, self.status = True, RobotEnv.Status.TIME_LIMIT\n else:\n done = False\n\n if done:\n self._trigger_event(RobotEnv.Events.END_OF_EPISODE, self)\n\n self.episode_step += 1\n self.obs = new_obs\n if len(self.curriculum._history) != 0:\n self.sr_mean = np.mean(self.curriculum._history)\n super().step_sim()\n return self.obs, reward, done, {\"is_success\":self.status==RobotEnv.Status.SUCCESS, \"episode_step\": self.episode_step, \"episode_rewards\": self.episode_rewards, \"status\": self.status}\n\n def _observe(self):\n if not self.depth_obs and not self.full_obs:\n obs = np.array([])\n for sensor in self._sensors:\n obs = np.append(obs, sensor.get_state())\n return obs\n else:\n rgb, depth, _ = self._camera.get_state()\n sensor_pad = np.zeros(self._camera.state_space.shape[:2])\n if self._simplified:\n #FIXME one dimensional depth observation is not working properly\n # depth = depth[:, :, np.newaxis]\n obs_stacked = np.dstack((depth, sensor_pad))\n return obs_stacked\n # return depth\n\n sensor_pad = np.zeros(self._camera.state_space.shape[:2])\n sensor_pad[0][0] = self._actuator.get_state()\n if self.full_obs:\n obs_stacked = np.dstack((rgb, depth, sensor_pad))\n else:\n obs_stacked = np.dstack((depth, sensor_pad))\n return obs_stacked\n\n def setup_spaces(self):\n self.action_space = self._actuator.setup_action_space()\n if not self.depth_obs and not self.full_obs:\n low, high = np.array([]), np.array([])\n for sensor in self._sensors:\n low = np.append(low, sensor.state_space.low)\n high = np.append(high, sensor.state_space.high)\n self.observation_space = gym.spaces.Box(low, high, dtype=np.float32)\n else:\n shape = self._camera.state_space.shape\n if self._simplified:\n # Depth\n # self.observation_space = self._camera.state_space\n self.observation_space = gym.spaces.Box(low=0, high=255,\n shape=(shape[0], shape[1], 2))\n else:\n if self.full_obs: # RGB + Depth + Actuator\n self.observation_space = gym.spaces.Box(low=0, high=255,\n shape=(shape[0], shape[1], 5))\n else: # Depth + Actuator obs\n self.observation_space = gym.spaces.Box(low=0, high=255,\n shape=(shape[0], shape[1], 2))\n\n def reset_robot_pose(self, target_pos, target_orn):\n \"\"\" Reset the world coordination of the robot base. Useful for test purposes \"\"\"\n self.reset_base(self._model.model_id, target_pos, target_orn)\n self.run(0.1)\n\n def absolute_pose(self, target_pos, target_orn):\n # target_pos = self._enforce_constraints(target_pos)\n\n target_pos[1] *= -1\n target_pos[2] = -1 * (target_pos[2] - self._initial_height)\n\n # _, _, yaw = transform_utils.euler_from_quaternion(target_orn)\n # yaw *= -1\n yaw = target_orn\n comp_pos = np.r_[target_pos, yaw]\n\n for i, joint in enumerate(self.main_joints):\n self._joints[joint].set_position(comp_pos[i])\n \n self.run(0.1)\n\n def relative_pose(self, translation, yaw_rotation):\n pos, orn = self._model.get_pose()\n _, _, yaw = transform_utils.euler_from_quaternion(orn)\n #Calculate transformation matrices\n T_world_old = transformations.compose_matrix(\n angles=[np.pi, 0., yaw], translate=pos)\n T_old_to_new = transformations.compose_matrix(\n angles=[0., 0., yaw_rotation], translate=translation)\n T_world_new = np.dot(T_world_old, T_old_to_new)\n self.endEffectorAngle += yaw_rotation\n target_pos, target_orn = transform_utils.to_pose(T_world_new)\n self.absolute_pose(target_pos, self.endEffectorAngle)\n\n def close_gripper(self):\n self.gripper_close = True\n self._target_joint_pos = 0.05\n self._left_finger.set_position(self._target_joint_pos)\n self._right_finger.set_position(self._target_joint_pos)\n\n self.run(0.2)\n\n def open_gripper(self):\n self.gripper_close = False\n self._target_joint_pos = 0.0\n self._left_finger.set_position(self._target_joint_pos)\n self._right_finger.set_position(self._target_joint_pos)\n\n self.run(0.2)\n\n def _enforce_constraints(self, position):\n \"\"\"Enforce constraints on the next robot movement.\"\"\"\n if self._workspace:\n position = np.clip(position,\n self._workspace['lower'],\n self._workspace['upper'])\n return position\n \n def get_gripper_width(self):\n \"\"\"Query the current opening width of the gripper.\"\"\"\n left_finger_pos = 0.05 - self._left_finger.get_position()\n right_finger_pos = 0.05 - self._right_finger.get_position()\n\n return left_finger_pos + right_finger_pos\n\n def object_detected(self, tol=0.005):\n \"\"\"Grasp detection by checking whether the fingers stalled while closing.\"\"\"\n return self._target_joint_pos == 0.05 and self.get_gripper_width() > tol\n\n def get_pose(self):\n return self._model.get_pose()\n\n def is_simplified(self):\n return self._simplified\n\n def is_discrete(self):\n return self._actuator.is_discrete()", "repo_name": "BarisYazici/deep-rl-grasping", "sub_path": "manipulation_main/gripperEnv/robot.py", "file_name": "robot.py", "file_ext": "py", "file_size_in_byte": 12061, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 161, "dataset": "github-code", "pt": "20", "api": [{"api_name": "manipulation_main.gripperEnv.actuator.reset", "line_number": 25, "usage_type": "call"}, {"api_name": "manipulation_main.gripperEnv.actuator", "line_number": 25, "usage_type": "name"}, {"api_name": "numpy.unique", "line_number": 27, "usage_type": "call"}, {"api_name": "manipulation_main.simulation.simulation.World", "line_number": 32, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 34, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 40, "usage_type": "name"}, {"api_name": "manipulation_main.common.io_utils.load_yaml", "line_number": 48, "usage_type": "call"}, {"api_name": "manipulation_main.common.io_utils", "line_number": 48, "usage_type": "name"}, {"api_name": "collections.deque", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 54, "usage_type": "call"}, {"api_name": "manipulation_main.common.transformations.quaternion_from_euler", "line_number": 60, "usage_type": "call"}, {"api_name": "manipulation_main.common.transformations", "line_number": 60, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 60, "usage_type": "attribute"}, {"api_name": "manipulation_main.gripperEnv.actuator.Actuator", "line_number": 69, "usage_type": "call"}, {"api_name": "manipulation_main.gripperEnv.actuator", "line_number": 69, "usage_type": "name"}, {"api_name": "manipulation_main.gripperEnv.sensor.RGBDSensor", "line_number": 71, "usage_type": "call"}, {"api_name": "manipulation_main.gripperEnv.sensor", "line_number": 71, "usage_type": "name"}, {"api_name": "manipulation_main.gripperEnv.rewards.SimplifiedReward", "line_number": 75, "usage_type": "call"}, {"api_name": "manipulation_main.gripperEnv.rewards.ShapedCustomReward", "line_number": 77, "usage_type": "call"}, {"api_name": "manipulation_main.gripperEnv.rewards.Reward", "line_number": 79, "usage_type": "call"}, {"api_name": "manipulation_main.gripperEnv.sensor.EncodedDepthImgSensor", "line_number": 85, "usage_type": "call"}, {"api_name": "manipulation_main.gripperEnv.sensor", "line_number": 85, "usage_type": "name"}, {"api_name": "manipulation_main.gripperEnv.curriculum.WorkspaceCurriculum", "line_number": 91, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 179, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 185, "usage_type": "call"}, {"api_name": "manipulation_main.gripperEnv.sensor", "line_number": 186, "usage_type": "name"}, {"api_name": "numpy.append", "line_number": 187, "usage_type": "call"}, {"api_name": "manipulation_main.gripperEnv.sensor.get_state", "line_number": 187, "usage_type": "call"}, {"api_name": "manipulation_main.gripperEnv.sensor", "line_number": 187, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 191, "usage_type": "call"}, {"api_name": "numpy.dstack", "line_number": 195, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 199, "usage_type": "call"}, {"api_name": "numpy.dstack", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.dstack", "line_number": 204, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 210, "usage_type": "call"}, {"api_name": "manipulation_main.gripperEnv.sensor", "line_number": 211, "usage_type": "name"}, {"api_name": "numpy.append", "line_number": 212, "usage_type": "call"}, {"api_name": "manipulation_main.gripperEnv.sensor.state_space", "line_number": 212, "usage_type": "attribute"}, {"api_name": "manipulation_main.gripperEnv.sensor", "line_number": 212, "usage_type": "name"}, {"api_name": "numpy.append", "line_number": 213, "usage_type": "call"}, {"api_name": "manipulation_main.gripperEnv.sensor.state_space", "line_number": 213, "usage_type": "attribute"}, {"api_name": "manipulation_main.gripperEnv.sensor", "line_number": 213, "usage_type": "name"}, {"api_name": "gym.spaces.Box", "line_number": 214, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 214, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 214, "usage_type": "attribute"}, {"api_name": "gym.spaces.Box", "line_number": 220, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 220, "usage_type": "attribute"}, {"api_name": "gym.spaces.Box", "line_number": 224, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 224, "usage_type": "attribute"}, {"api_name": "gym.spaces.Box", "line_number": 227, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 227, "usage_type": "attribute"}, {"api_name": "numpy.r_", "line_number": 244, "usage_type": "attribute"}, {"api_name": "manipulation_main.common.transform_utils.euler_from_quaternion", "line_number": 253, "usage_type": "call"}, {"api_name": "manipulation_main.common.transform_utils", "line_number": 253, "usage_type": "name"}, {"api_name": "manipulation_main.common.transformations.compose_matrix", "line_number": 255, "usage_type": "call"}, {"api_name": "manipulation_main.common.transformations", "line_number": 255, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 256, "usage_type": "attribute"}, {"api_name": "manipulation_main.common.transformations.compose_matrix", "line_number": 257, "usage_type": "call"}, {"api_name": "manipulation_main.common.transformations", "line_number": 257, "usage_type": "name"}, {"api_name": "numpy.dot", "line_number": 259, "usage_type": "call"}, {"api_name": "manipulation_main.common.transform_utils.to_pose", "line_number": 261, "usage_type": "call"}, {"api_name": "manipulation_main.common.transform_utils", "line_number": 261, "usage_type": "name"}, {"api_name": "numpy.clip", "line_number": 283, "usage_type": "call"}]} +{"seq_id": "7849479561", "text": "from django.urls import path\nfrom django.contrib.auth import views as auth_views\n\nfrom .views import *\n\n\nurlpatterns = [\n path('signin', signIn, name='signIn'),\n\n \n path('home', home, name=\"home\"),\n path('dashboard', dashboard, name='dashboard'),\n path(\"logout/\", auth_views.LogoutView.as_view(), name=\"logout\"),\n \n path('', index, name='index'),\n path('all-categories', all_categories, name='all_categories'),\n path('categories-details:', categories_details, name='categories_details'),\n \n path('mcdashboard', mcdashboard, name='mcdashboard'),\n \n path('twilliomsg', twilliomsg, name='twilliomsg'),\n \n path('register', register, name='register'),\n path('log-in', log_in, name='log-in'),\n path('Providerdashboard', Providerdashboard, name='Providerdashboard'),\n path('Service', ProviderService, name='ProviderService'),\n path('CreateService', CreateService, name='CreateService'),\n path('delete_service/', delete_service, name='delete_service'),\n path('EditService/', EditService, name='EditService'),\n \n \n \n \n \n \n \n \n]", "repo_name": "asimraza336/Allo_hrafi", "sub_path": "Users/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 1129, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "django.contrib.auth.views.LogoutView.as_view", "line_number": 13, "usage_type": "call"}, {"api_name": "django.contrib.auth.views.LogoutView", "line_number": 13, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.views", "line_number": 13, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 15, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 16, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 17, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 19, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 21, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 23, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 24, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 25, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 26, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 27, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 28, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 29, "usage_type": "call"}]} +{"seq_id": "12323998759", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nname: ThinkPHP 代码执行漏洞\nreferer: http://zone.wooyun.org/index.php?do=view&id=44\nauthor: Lucifer\ndescription: ThinkPHP 版本3.0~3.1开启Lite模式后preg_replace使用了/e选项,同时第二个参数使用双引号,所以造成了代码执行,可直接GETSHELL\n'''\nimport sys\nimport requests\nimport warnings\n\n \n\nclass code_exec:\n def __init__(self, url):\n self.url = url\n\n def run(self):\n result = ['speedcms list文件参数cid SQL注入','','']\n payload = \"/index.php/Index/index/name/$%7B@phpinfo%28%29%7D\"\n vulnurl = self.url + payload\n try:\n req = requests.get(vulnurl, timeout=10, verify=False)\n\n if r\"Configuration File (php.ini) Path\" in req.text:\n result[2]= '存在'\n result[1] = vulnurl\n return result\n else:\n result[2]= '不存在'\n\n except:\n result[2]='不存在'\n return result\n\nif __name__ == \"__main__\":\n warnings.filterwarnings(\"ignore\")\n testVuln = code_exec(sys.argv[1])\n testVuln.run()", "repo_name": "muyuxx/FrameScan-GUI", "sub_path": "Plugins/thinkphp/code_exec.py", "file_name": "code_exec.py", "file_ext": "py", "file_size_in_byte": 1144, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "20", "api": [{"api_name": "requests.get", "line_number": 24, "usage_type": "call"}, {"api_name": "warnings.filterwarnings", "line_number": 38, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 39, "usage_type": "attribute"}]} +{"seq_id": "37930132968", "text": "import requests\nfrom bs4 import BeautifulSoup\nimport urllib.request\nimport re\nimport csv\n\ndef coupe_spider(max_pages):\n page = 1\n while page <= max_pages:\n url = 'http://www.cars-data.com/en/coupe-cars/page' + str(page) + '.html'\n source_code = requests.get(url)\n plain_text = source_code.text\n soup = BeautifulSoup(plain_text, \"lxml\")\n for link in soup.findAll('a', {'class':'col-4'}):\n href = link.get('href')\n title = link.get('title')\n print(href)\n print(title)\n page += 1\n\ndef coupe_spider_links():\n html_page = urllib.request.urlopen('http://www.cars-data.com/en/coupe-cars/page2.html')\n soup = BeautifulSoup(html_page)\n links = []\n for link in soup.findAll('a', attrs={'href': re.compile(\"^http://\")}):\n links.append(link.get('href'))\n print(links)\n\ndef coupe_text_grabber():\n html_page = urllib.request.urlopen('http://www.cars-data.com/en/coupe-cars/page2.html')\n soup = BeautifulSoup(html_page)\n links = []\n for link in soup.findAll('a', attrs={'href': re.compile(\"^http://www.cars-data.com/pictures/\")}):\n links.append(link.get('href'))\n print(links)\n\ndef coupe_spider_titles_audi():\n html_page = urllib.request.urlopen('http://www.cars-data.com/en/coupe-cars/page2.html')\n soup = BeautifulSoup(html_page, \"lxml\")\n titles = []\n for link in soup.findAll('a', attrs={'title': re.compile(\"Audi\")}):\n titles.append(link.get('title'))\n print(titles)\n\ncoupe_spider_titles_audi()\n\ndef coupe_spider_titles_bmw():\n html_page = urllib.request.urlopen('http://www.cars-data.com/en/coupe-cars/page2.html')\n soup = BeautifulSoup(html_page, \"lxml\")\n titles = []\n for link in soup.findAll('a', attrs={'title': re.compile(\"BMW\")}):\n titles.append(link.get('title'))\n print(titles)\n\ncoupe_spider_titles_bmw()\n\ndef coupe_spider_titles_porsche():\n html_page = urllib.request.urlopen('http://www.cars-data.com/en/coupe-cars/page2.html')\n soup = BeautifulSoup(html_page, \"lxml\")\n titles = []\n for link in soup.findAll('a', attrs={'title': re.compile(\"Porsche\")}):\n titles.append(link.get('title'))\n print(titles)\n\ncoupe_spider_titles_porsche()\n\n\n\ndef write_csv():\n with open(file_path, 'a') as outcsv:\n writer = csv.writer(outcsv, delimiter = ',', quotechar='|', quoting= csv.QUOTE_MINIMAL, lineterminator='\\n')\n writer.writerow(['number', 'text', 'number'])\n for item in list:\n #Write item to outcsv\n writer.writerow([item[0], item[1], item[2]])\n", "repo_name": "nbanks2/FuelEngine", "sub_path": "WebCrawler.py", "file_name": "WebCrawler.py", "file_ext": "py", "file_size_in_byte": 2622, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "requests.get", "line_number": 11, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 13, "usage_type": "call"}, {"api_name": "urllib.request.request.urlopen", "line_number": 22, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 22, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 22, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 23, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 25, "usage_type": "call"}, {"api_name": "urllib.request.request.urlopen", "line_number": 30, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 30, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 30, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 31, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 33, "usage_type": "call"}, {"api_name": "urllib.request.request.urlopen", "line_number": 38, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 38, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 38, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 39, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 41, "usage_type": "call"}, {"api_name": "urllib.request.request.urlopen", "line_number": 48, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 48, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 48, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 49, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 51, "usage_type": "call"}, {"api_name": "urllib.request.request.urlopen", "line_number": 58, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 58, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 58, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 59, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 61, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 71, "usage_type": "call"}, {"api_name": "csv.QUOTE_MINIMAL", "line_number": 71, "usage_type": "attribute"}]} +{"seq_id": "29400037967", "text": "\"\"\"\nDefines steps take to perform data integrity tests on the metric beat service\n\"\"\"\n# pylint: disable=function-redefined,undefined-variable\n\nfrom behave import *\nfrom elasticsearch_dsl import Index, connections, Text, Document, Search\nfrom func_timeout import func_timeout, FunctionTimedOut\nimport time\nimport uuid\nimport json\nfrom datetime import datetime, timedelta\nfrom dateutil.parser import parse\nfrom Tests.utils.ElasticInterface.index_interface import IndexInterface\n\n@when('I retrieve a {metric} log')\ndef step_impl(context, metric):\n elastic = IndexInterface(\"metricbeat-*\")\n logs = elastic.get_logs()\n for hit in logs:\n res = hit.to_dict()\n if res[\"metricset\"][\"name\"] == metric and res[\"service\"][\"type\"] == context.module:\n context.result = res\n break\n\n@then('I should expect to not see any null values in the response')\ndef step_impl(context):\n response = context.result\n assert(response != None)\n checkValues = iterate(response)\n assert(checkValues == True)\n\ndef iterate(dictionary):\n \"\"\"\n Iterates through a Json object as a dictionary. \n Returns if any field has null values\n\n :param dictionary: JSON object as a dictionary\n \"\"\"\n for key, value in dictionary.items():\n if isinstance(value, dict):\n #print('key {!r} -> value {!r}'.format(key, value)) \n valueCheck = iterate(value)\n if(valueCheck == False):\n return False\n continue\n else:\n #print('key {!r} -> value {!r}'.format(key, value))\n if(value == None):\n return False\n return True\n\n@then('I should expect to see a timestamp field in the response')\ndef step_impl(context):\n response = context.result['@timestamp']\n isDate = is_date(response)\n assert(isDate == True)\n\ndef is_date(string, fuzzy=False):\n \"\"\"\n Return whether the string can be interpreted as a date.\n\n :param string: str, string to check for date\n :param fuzzy: bool, ignore unknown tokens in string if True\n \"\"\"\n try:\n parse(string, fuzzy=fuzzy)\n return True\n\n except ValueError:\n return False\n\n@then('I should expect to see a agent.type field in the response with a value of metricbeat')\ndef step_impl(context):\n response = context.result['agent']['type']\n assert( response == \"metricbeat\")\n\n@then('I should expect to see a agent.version field in the response with a value of 7.3.1')\ndef step_impl(context):\n response = context.result['agent']['version']\n assert( response == \"7.3.1\")\n", "repo_name": "rysantos/elasticsearch-tests-behave", "sub_path": "Tests/metricbeat_tests/features/steps/integrity.py", "file_name": "integrity.py", "file_ext": "py", "file_size_in_byte": 2574, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "Tests.utils.ElasticInterface.index_interface.IndexInterface", "line_number": 18, "usage_type": "call"}, {"api_name": "dateutil.parser.parse", "line_number": 67, "usage_type": "call"}]} +{"seq_id": "30935385057", "text": "import subprocess\nimport psutil\nimport time\nfrom tkinter import *\n\n\nall_processes = []\n\n# Класс можно свернуть\nclass Example(Frame):\n def __init__(self, parent):\n Frame.__init__(self, parent)\n self.parent = parent\n self.initUI()\n\n def initUI(self):\n self.parent.title(\"Консольный месенджер v0.02 pre-alpha\")\n self.parent.geometry(\"400x190\")\n\n self.columnconfigure(0, pad=3)\n self.columnconfigure(1, pad=3)\n self.columnconfigure(2, pad=3)\n\n button_s = Button(\n self,\n text=\"Запустить сервер и клиенты\",\n background=\"#555\",\n foreground=\"#ccc\",\n padx=\"20\",\n pady=\"8\",\n font=\"16\",\n height=2,\n width=40,\n command=click_s)\n button_s.grid(row=2, column=0)\n button_x = Button(\n self,\n text=\"Закрыть все окна\",\n background=\"#555\",\n foreground=\"#ccc\",\n padx=\"20\",\n pady=\"8\",\n font=\"16\",\n height=2,\n width=40,\n command=click_x)\n button_x.grid(row=3, column=0)\n button_q = Button(\n self,\n text=\"Выход\",\n background=\"#555\",\n foreground=\"#ccc\",\n padx=\"20\",\n pady=\"8\",\n font=\"16\",\n height=2,\n width=40,\n command=click_q)\n button_q.grid(row=4, column=0)\n\n self.pack()\n\n\n# s - запустить сервер и клиенты\ndef click_s():\n all_processes.append(\n subprocess.Popen(\n 'python hw_3_1_server.py',\n creationflags=subprocess.CREATE_NEW_CONSOLE))\n time.sleep(0.1)\n all_processes.append(\n subprocess.Popen(\n 'python hw_3_1_client.py -n cl_1',\n creationflags=subprocess.CREATE_NEW_CONSOLE))\n time.sleep(0.1)\n all_processes.append(\n subprocess.Popen(\n 'python hw_3_1_client.py -n cl_2',\n creationflags=subprocess.CREATE_NEW_CONSOLE))\n time.sleep(0.1)\n all_processes.append(\n subprocess.Popen(\n 'python hw_3_1_client.py -n cl_3',\n creationflags=subprocess.CREATE_NEW_CONSOLE))\n\n print(all_processes)\n\n\n# x - закрыть все окна\ndef click_x():\n # останавливается процесс /bin/sh, процессы клиентов и сервера продолжают\n # работать (**доработать**)\n for p in all_processes:\n main_process = psutil.Process(p.pid)\n print(print(p.pid), main_process)\n for child_process in main_process.children(recursive=True):\n child_process.terminate()\n\n all_processes.clear()\n print(all_processes)\n\n\n# q - выход\ndef click_q():\n quit()\n\n\ndef main():\n root = Tk()\n app = Example(root)\n root.mainloop()\n\n\nif __name__ == '__main__':\n main()\n", "repo_name": "SKO7OPENDRA/python_messanger", "sub_path": "hw/hw_07/launcher.py", "file_name": "launcher.py", "file_ext": "py", "file_size_in_byte": 3021, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "subprocess.Popen", "line_number": 67, "usage_type": "call"}, {"api_name": "subprocess.CREATE_NEW_CONSOLE", "line_number": 69, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 70, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 72, "usage_type": "call"}, {"api_name": "subprocess.CREATE_NEW_CONSOLE", "line_number": 74, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 75, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 77, "usage_type": "call"}, {"api_name": "subprocess.CREATE_NEW_CONSOLE", "line_number": 79, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 80, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 82, "usage_type": "call"}, {"api_name": "subprocess.CREATE_NEW_CONSOLE", "line_number": 84, "usage_type": "attribute"}, {"api_name": "psutil.Process", "line_number": 94, "usage_type": "call"}]} +{"seq_id": "43999916035", "text": "import datasets\n\n\nlogger = datasets.logging.get_logger(__name__)\n\n\n_CITATION = \"\"\"\\\n@inproceedings{xing2018adaptive,\n title={Adaptive multi-task transfer learning for Chinese word segmentation in medical text},\n author={Xing, Junjie and Zhu, Kenny and Zhang, Shaodian},\n booktitle={Proceedings of the 27th International Conference on Computational Linguistics},\n pages={3619--3630},\n year={2018}\n}\n\"\"\"\n\n_DESCRIPTION = \"\"\"\\\nChinese word segmentation (CWS) trained from open source corpus faces dramatic performance drop\nwhen dealing with domain text, especially for a domain with lots of special terms and diverse\nwriting styles, such as the biomedical domain. However, building domain-specific CWS requires\nextremely high annotation cost. In this paper, we propose an approach by exploiting domain-invariant\nknowledge from high resource to low resource domains. Extensive experiments show that our mode\nachieves consistently higher accuracy than the single-task CWS and other transfer learning\nbaselines, especially when there is a large disparity between source and target domains.\n\nThis dataset is the accompanied medical Chinese word segmentation (CWS) dataset.\nThe tags are in BIES scheme.\n\nFor more details see https://www.aclweb.org/anthology/C18-1307/\n\"\"\"\n\n_URL = \"https://raw.githubusercontent.com/adapt-sjtu/AMTTL/master/medical_data/\"\n_TRAINING_FILE = \"forum_train.txt\"\n_DEV_FILE = \"forum_dev.txt\"\n_TEST_FILE = \"forum_test.txt\"\n\n\nclass AmttlConfig(datasets.BuilderConfig):\n \"\"\"BuilderConfig for AMTTL\"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"BuilderConfig for AMTTL.\n\n Args:\n **kwargs: keyword arguments forwarded to super.\n \"\"\"\n super(AmttlConfig, self).__init__(**kwargs)\n\n\nclass Amttl(datasets.GeneratorBasedBuilder):\n \"\"\"AMTTL Chinese Word Segmentation dataset.\"\"\"\n\n BUILDER_CONFIGS = [\n AmttlConfig(\n name=\"amttl\",\n version=datasets.Version(\"1.0.0\"),\n description=\"AMTTL medical Chinese word segmentation dataset\",\n ),\n ]\n\n def _info(self):\n return datasets.DatasetInfo(\n description=_DESCRIPTION,\n features=datasets.Features(\n {\n \"id\": datasets.Value(\"string\"),\n \"tokens\": datasets.Sequence(datasets.Value(\"string\")),\n \"tags\": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n \"B\",\n \"I\",\n \"E\",\n \"S\",\n ]\n )\n ),\n }\n ),\n supervised_keys=None,\n homepage=\"https://www.aclweb.org/anthology/C18-1307/\",\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n \"\"\"Returns SplitGenerators.\"\"\"\n urls_to_download = {\n \"train\": f\"{_URL}{_TRAINING_FILE}\",\n \"dev\": f\"{_URL}{_DEV_FILE}\",\n \"test\": f\"{_URL}{_TEST_FILE}\",\n }\n downloaded_files = dl_manager.download_and_extract(urls_to_download)\n\n return [\n datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={\"filepath\": downloaded_files[\"train\"]}),\n datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={\"filepath\": downloaded_files[\"dev\"]}),\n datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={\"filepath\": downloaded_files[\"test\"]}),\n ]\n\n def _generate_examples(self, filepath):\n logger.info(\"⏳ Generating examples from = %s\", filepath)\n with open(filepath, encoding=\"utf-8\") as f:\n guid = 0\n tokens = []\n tags = []\n for line in f:\n line_stripped = line.strip()\n if line_stripped == \"\":\n if tokens:\n yield guid, {\n \"id\": str(guid),\n \"tokens\": tokens,\n \"tags\": tags,\n }\n guid += 1\n tokens = []\n tags = []\n else:\n splits = line_stripped.split(\"\\t\")\n if len(splits) == 1:\n splits.append(\"O\")\n tokens.append(splits[0])\n tags.append(splits[1])\n # last example\n yield guid, {\n \"id\": str(guid),\n \"tokens\": tokens,\n \"tags\": tags,\n }\n", "repo_name": "XingxingZhang/hf_datasets", "sub_path": "datasets/amttl/amttl.py", "file_name": "amttl.py", "file_ext": "py", "file_size_in_byte": 4659, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "datasets.logging.get_logger", "line_number": 4, "usage_type": "call"}, {"api_name": "datasets.logging", "line_number": 4, "usage_type": "attribute"}, {"api_name": "datasets.BuilderConfig", "line_number": 38, "usage_type": "attribute"}, {"api_name": "datasets.GeneratorBasedBuilder", "line_number": 50, "usage_type": "attribute"}, {"api_name": "datasets.Version", "line_number": 56, "usage_type": "call"}, {"api_name": "datasets.DatasetInfo", "line_number": 62, "usage_type": "call"}, {"api_name": "datasets.Features", "line_number": 64, "usage_type": "call"}, {"api_name": "datasets.Value", "line_number": 66, "usage_type": "call"}, {"api_name": "datasets.Sequence", "line_number": 67, "usage_type": "call"}, {"api_name": "datasets.Value", "line_number": 67, "usage_type": "call"}, {"api_name": "datasets.Sequence", "line_number": 68, "usage_type": "call"}, {"api_name": "datasets.features.ClassLabel", "line_number": 69, "usage_type": "call"}, {"api_name": "datasets.features", "line_number": 69, "usage_type": "attribute"}, {"api_name": "datasets.SplitGenerator", "line_number": 95, "usage_type": "call"}, {"api_name": "datasets.Split", "line_number": 95, "usage_type": "attribute"}, {"api_name": "datasets.SplitGenerator", "line_number": 96, "usage_type": "call"}, {"api_name": "datasets.Split", "line_number": 96, "usage_type": "attribute"}, {"api_name": "datasets.SplitGenerator", "line_number": 97, "usage_type": "call"}, {"api_name": "datasets.Split", "line_number": 97, "usage_type": "attribute"}]} +{"seq_id": "38555708603", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport env\n\n\n# In[15]:\n\n\nprint('new_logs_data()' '\\n' 'get_logs_data()' \"\\n\" 'prepare(df)')\n\n\n# In[2]:\n\n\nurl = f'mysql+pymysql://{env.username}:{env.password}@{env.host}/curriculum_logs'\n\n\n# In[ ]:\n\n\ndef prepare(df):\n df.date = pd.to_datetime(df.date)\n df = df.set_index(df.date)\n df = df.drop(columns = ['cohort_id', 'id', 'deleted_at', 'date', 'slack', 'created_at', 'updated_at'])\n df.rename(columns = {'path':'endpoint', 'user_id':'user', 'ip':'source_ip', 'name':'cohort_name'}, inplace =True)\n return df\n\n\n# In[16]:\n\n\ndef new_logs_data():\n return pd.read_sql('''select * FROM logs LEFT JOIN cohorts ON logs.cohort_id = cohorts.id;\n\n''', url)\n\n\nimport os\n\ndef get_logs_data():\n filename = \"logs.csv\"\n \n # if file is available locally, read it\n if os.path.isfile(filename):\n df = pd.read_csv(filename, index_col=0)\n df.index = pd.to_datetime(df.index)\n return df\n \n # if file not available locally, acquire data from SQL database\n # and write it as csv locally for future use\n else:\n # read the SQL query into a dataframe\n df_logs = new_logs_data()\n \n #prepare new logs\n df_logs_p = prepare(df_logs)\n \n # Write that dataframe to disk for later. Called \"caching\" the data for later.\n df_logs_p.to_csv(filename)\n\n # Return the dataframe to the calling code\n return df_logs_p\n\n\n# In[4]:\n\n\n#df = new_logs_data()\n\n\n# In[5]:\n\n\n#df.to_csv('logs_unprepared.csv')\n\n\n# In[6]:\n\n\n#df.head()\n\n\n# In[ ]:\n\n\n#df = prepare(df)\n\n\n# In[ ]:\n\n\n#df.head()\n\n\n# In[ ]:\n\n\n#df.to_csv('logs.csv')\n\n\n# In[ ]:\n\n\n\n\n\n# In[12]:\n\n\n#df = get_logs_data()\n\n\n# In[13]:\n\n\n#df.head()\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n", "repo_name": "Team-Ferret-Kalpana/Logs_archive", "sub_path": "wrangle_z.py", "file_name": "wrangle_z.py", "file_ext": "py", "file_size_in_byte": 2102, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "env.username", "line_number": 22, "usage_type": "attribute"}, {"api_name": "env.password", "line_number": 22, "usage_type": "attribute"}, {"api_name": "env.host", "line_number": 22, "usage_type": "attribute"}, {"api_name": "pandas.to_datetime", "line_number": 29, "usage_type": "call"}, {"api_name": "pandas.read_sql", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path", "line_number": 51, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 52, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 53, "usage_type": "call"}]} +{"seq_id": "37149024218", "text": "#ftp-v4.py - Mark Harris. This script is used to send the rpi's IP and hostname to a central location, ftp server.\n# Obsolete script and no longer used on the LiveSectional platform. Saved for posterity sake only.\n\n# Updated to work under Python 3.7\n# This is used for multiple LiveSectional maps all on the same local network so the editors will\n# populate a dropdown box for easy selection of which board to edit. If only one board is present\n# then there will be no dropdown box in the editor.\n# This script will be executed by webapp.py, which once executed will read the local_file and\n# populate a dropdown box in the editors with all the map's IP addresses to make it easier to switch.\n# Added Logging capabilities which is stored in /NeoSectional/logfile.log\n\n#required imports\nimport ftplib\nimport socket\nimport time\nimport sys\nimport config\nimport logging\nimport logzero\nfrom logzero import logger\nimport os\nimport admin\n\n# Setup rotating logfile with 3 rotations, each with a maximum filesize of 1MB:\nversion = admin.version #Software version\nloglevel = config.loglevel\nloglevels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR]\nlogzero.loglevel(loglevels[loglevel]) #Choices in order; DEBUG, INFO, WARNING, ERROR\nlogzero.logfile('/NeoSectional/logfile.log', maxBytes=1e6, backupCount=1)\nlogger.info(\"\\nStartup of metar-v4.py Script, Version \" + version)\nlogger.info(\"Log Level Set To: \" + str(loglevels[loglevel]))\n\nuse_ftp = admin.use_ftp #0 = No, 1 = Yes. Use this script for admin and debug only.\n\n#ftp credentials etc. which comes from admin.py\nhostname = admin.hostname\nusername = admin.username\npassword = admin.password\nremote_dir = admin.remote_dir\nlogger.debug(hostname)\n\n#misc settings\ncounter = 0 #used to count up to max_delay_time for checking internet connectivity\ndelay_time = 60 #delay in Seconds for checking internet connectivity\nlocal_file = '/NeoSectional/lsinfo.txt' #holds the ip addresses for other maps on local network.\nremote_file = 'lsinfo.txt'\nipaddresses = []\n\n#Functions\ndef uploadfile():\n with open(local_file, 'rb') as fp:\n res = ftp.storlines(\"STOR \" + remote_file, fp)\n if not res.startswith('226'):\n logger.error('ERROR - Upload failed')\n# ftp.close()\n\ndef downloadfile():\n with open(local_file, 'w+') as fp:\n res = ftp.retrlines('RETR ' + remote_file, lambda s, w=fp.write: w(s+'\\n'))\n if not res.startswith('226'):\n logger.error('ERROR - Download failed')\n if os.path.isfile(local_file):\n os.remove(local_file)\n# fp.close()\n\n#start of execution\nif use_ftp == 1: #use this for admin and development only.\n\n #Get machine's IP address and hostname to store.\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n ipadd = s.getsockname()[0]\n rpi_name = socket.gethostname()\n logger.debug(ipadd)\n\n #start ftp session, give it 3 attempts with a delay between.\n try:\n ftp = ftplib.FTP(hostname, username, password)\n logger.info('FTP Connection Secured on first try on ' + hostname)\n except:\n #verify internet is available before moving on.\n logger.warning('Server unavailable. Try 1. Checking again in ' + str(delay_time) + ' seconds')\n time.sleep(delay_time)\n\n try:\n ftp = ftplib.FTP(hostname, username, password)\n logger.info('FTP Connection Secured on second try')\n except:\n #verify internet is available before moving on.\n logger.warning('Server unavailable. Try 2. Checking again in ' + str(delay_time) + ' seconds')\n time.sleep(delay_time)\n\n try:\n ftp = ftplib.FTP(hostname, username, password)\n logger.info('FTP Connection Secured on third try')\n except ftplib.all_errors as e:\n logger.error('FTP error:', e)\n logger.error('Ending ftp-v4.py Script')\n sys.exit() #End script\n\n #change the ftp's directory if necessary\n if remote_dir != \"\":\n ftp.cwd(remote_dir)\n\n #check to see if file is on the ftp server or not.\n file_list = ftp.nlst()\n if remote_file in file_list:\n logger.info('Remote File is Present on FTP Server')\n #download file from ftp server\n downloadfile()\n logger.info(local_file + ' Downloaded to RPI')\n\n else:\n logger.info('Remote File is Missing from ' + hostname)\n uploadfile() #create file on ftp server\n logger.info('Data File has been uploaded to ' + hostname)\n\n #read local file and compare to local rpi address to see if its' already in the file.\n #if it is, then we are done. If not, then add it to the file and upload it to the ftp server.\n try:\n with open(local_file) as fp:\n for line in fp:\n ipaddresses.append(line.strip())\n fp.close()\n except IOError as error:\n logger.error(local_file + ' file could not be loaded.')\n logger.error(error)\n\n info = ipadd + ' ' + rpi_name #create line for file with space separating info\n\n if info in ipaddresses:\n pass\n else:\n ipaddresses.append(info)\n\n fp = open(local_file, 'w+')\n for j in range(len(ipaddresses)):\n fp.write(ipaddresses[j])\n fp.write('\\n')\n fp.close()\n\n logger.debug(ipaddresses)\n uploadfile() #upload updated file back to the ftp server.\n logger.info(local_file + ' Uploaded to ' + hostname)\n\n logger.info('ftp-v4.py Completed')\n\nelse:\n logger.info('ftp-v4.py Not Run')\n", "repo_name": "markyharris/livesectional", "sub_path": "ftp-v4.py", "file_name": "ftp-v4.py", "file_ext": "py", "file_size_in_byte": 5883, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 12, "dataset": "github-code", "pt": "20", "api": [{"api_name": "admin.version", "line_number": 25, "usage_type": "attribute"}, {"api_name": "config.loglevel", "line_number": 26, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 27, "usage_type": "attribute"}, {"api_name": "logging.INFO", "line_number": 27, "usage_type": "attribute"}, {"api_name": "logging.WARNING", "line_number": 27, "usage_type": "attribute"}, {"api_name": "logging.ERROR", "line_number": 27, "usage_type": "attribute"}, {"api_name": "logzero.loglevel", "line_number": 28, "usage_type": "call"}, {"api_name": "logzero.logfile", "line_number": 29, "usage_type": "call"}, {"api_name": "logzero.logger.info", "line_number": 30, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 30, "usage_type": "name"}, {"api_name": "logzero.logger.info", "line_number": 31, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 31, "usage_type": "name"}, {"api_name": "admin.use_ftp", "line_number": 33, "usage_type": "attribute"}, {"api_name": "admin.hostname", "line_number": 36, "usage_type": "attribute"}, {"api_name": "admin.username", "line_number": 37, "usage_type": "attribute"}, {"api_name": "admin.password", "line_number": 38, "usage_type": "attribute"}, {"api_name": "admin.remote_dir", "line_number": 39, "usage_type": "attribute"}, {"api_name": "logzero.logger.debug", "line_number": 40, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 40, "usage_type": "name"}, {"api_name": "logzero.logger.error", "line_number": 54, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 54, "usage_type": "name"}, {"api_name": "logzero.logger.error", "line_number": 61, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 61, "usage_type": "name"}, {"api_name": "os.path.isfile", "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": "socket.socket", "line_number": 70, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 70, "usage_type": "attribute"}, {"api_name": "socket.SOCK_DGRAM", "line_number": 70, "usage_type": "attribute"}, {"api_name": "socket.gethostname", "line_number": 73, "usage_type": "call"}, {"api_name": "logzero.logger.debug", "line_number": 74, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 74, "usage_type": "name"}, {"api_name": "ftplib.FTP", "line_number": 78, "usage_type": "call"}, {"api_name": "logzero.logger.info", "line_number": 79, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 79, "usage_type": "name"}, {"api_name": "logzero.logger.warning", "line_number": 82, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 82, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 83, "usage_type": "call"}, {"api_name": "ftplib.FTP", "line_number": 86, "usage_type": "call"}, {"api_name": "logzero.logger.info", "line_number": 87, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 87, "usage_type": "name"}, {"api_name": "logzero.logger.warning", "line_number": 90, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 90, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 91, "usage_type": "call"}, {"api_name": "ftplib.FTP", "line_number": 94, "usage_type": "call"}, {"api_name": "logzero.logger.info", "line_number": 95, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 95, "usage_type": "name"}, {"api_name": "ftplib.all_errors", "line_number": 96, "usage_type": "attribute"}, {"api_name": "logzero.logger.error", "line_number": 97, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 97, "usage_type": "name"}, {"api_name": "logzero.logger.error", "line_number": 98, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 98, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 99, "usage_type": "call"}, {"api_name": "logzero.logger.info", "line_number": 108, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 108, "usage_type": "name"}, {"api_name": "logzero.logger.info", "line_number": 111, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 111, "usage_type": "name"}, {"api_name": "logzero.logger.info", "line_number": 114, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 114, "usage_type": "name"}, {"api_name": "logzero.logger.info", "line_number": 116, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 116, "usage_type": "name"}, {"api_name": "logzero.logger.error", "line_number": 126, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 126, "usage_type": "name"}, {"api_name": "logzero.logger.error", "line_number": 127, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 127, "usage_type": "name"}, {"api_name": "logzero.logger.debug", "line_number": 142, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 142, "usage_type": "name"}, {"api_name": "logzero.logger.info", "line_number": 144, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 144, "usage_type": "name"}, {"api_name": "logzero.logger.info", "line_number": 146, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 146, "usage_type": "name"}, {"api_name": "logzero.logger.info", "line_number": 149, "usage_type": "call"}, {"api_name": "logzero.logger", "line_number": 149, "usage_type": "name"}]} +{"seq_id": "17636008830", "text": "import logging\nimport os\nimport time\n\nfrom autotest_lib.client.bin import test, utils\nfrom autotest_lib.client.common_lib import error\nfrom autotest_lib.client.cros.graphics import graphics_utils\nfrom autotest_lib.client.cros.image_comparison import pdiff_image_comparer\n\ndef get_percent_difference(file1, file2):\n \"\"\"\n Performs pixel comparison of two files, given by their paths |file1|\n and |file2| using terminal tool 'perceptualdiff' and returns percentage\n difference of the total file size.\n\n @param file1: path to image\n @param file2: path to secondary image\n @return: percentage difference of total file size.\n @raise ValueError: if image dimensions are not the same\n @raise OSError: if file does not exist or cannot be opened.\n\n \"\"\"\n # Using pdiff image comparer to compare the two images. This class\n # invokes the terminal tool perceptualdiff.\n pdi = pdiff_image_comparer.PdiffImageComparer()\n diff_bytes = pdi.compare(file1, file2)[0]\n return round(100. * diff_bytes / os.path.getsize(file1))\n\n\nclass platform_TabletMode(test.test):\n \"\"\"\n Verify that tablet mode toggles appropriately.\n \"\"\"\n version = 1\n _WAIT = 5\n _SHORT_WAIT = 1\n SPOOF_CMD = 'ectool motionsense spoof '\n # Disable spoof mode and return into laptop state.\n RESET_SENSOR_0 = '-- 0 0'\n RESET_SENSOR_1 = '-- 1 0'\n # Spoof sensor 1 to force laptop into landscape tablet mode.\n LANDSCAPE_SENSOR_1 = '-- 1 1 32 -16256 -224'\n # Spoof sensor 0 and sensor 1 to force laptop into portrait tablet mode.\n PORTRAIT_SENSOR_0 = '-- 0 1 -7760 -864 -14112'\n PORTRAIT_SENSOR_1 = '-- 1 1 -7936 848 14480'\n ERRORS = []\n\n def _revert_laptop(self):\n \"\"\"Resets sensors to revert back to laptop mode.\"\"\"\n utils.system(self.SPOOF_CMD + self.RESET_SENSOR_0)\n time.sleep(self._SHORT_WAIT)\n utils.system(self.SPOOF_CMD + self.RESET_SENSOR_1)\n time.sleep(self._WAIT)\n\n def _spoof_tablet_landscape(self):\n \"\"\"Spoofs sensors to change into tablet landscape mode.\"\"\"\n utils.system(self.SPOOF_CMD + self.LANDSCAPE_SENSOR_1)\n time.sleep(self._WAIT)\n\n def _spoof_tablet_portrait(self):\n \"\"\"Spoofs sensors to change into tablet portrait mode.\"\"\"\n utils.system(self.SPOOF_CMD + self.PORTRAIT_SENSOR_0)\n time.sleep(self._SHORT_WAIT)\n utils.system(self.SPOOF_CMD + self.PORTRAIT_SENSOR_1)\n time.sleep(self._WAIT)\n\n def _take_screenshot(self, suffix):\n \"\"\"\n Captures a screenshot of the current VT screen in BMP format.\n\n @param suffixcurrent_vt: desired vt for screenshot.\n\n @returns the path of the screenshot file.\n\n \"\"\"\n extension = 'bmp'\n return graphics_utils.take_screenshot(self.resultsdir,\n suffix + '_tablet_mode',\n extension)\n\n def _verify_difference(self, screenshot1, screenshot2,\n difference_percent_threshold=5):\n \"\"\"\n Make sure screenshots are sufficiently different.\n\n @param screenshot1: path to screenshot.\n @param screenshot2: path to screenshot.\n @param difference_percent_threshold: threshold for difference.\n\n @returns number of errors found (0 or 1).\n\n \"\"\"\n filename1 = screenshot1.split('/')[-1]\n filename2 = screenshot2.split('/')[-1]\n diff = get_percent_difference(screenshot1, screenshot2)\n logging.info(\"Screenshot 1 and 2 diff: %s\" % diff)\n if not diff >= difference_percent_threshold:\n error = ('Screenshots differ by %d %%: %s vs %s'\n % (diff, filename1, filename2))\n self.ERRORS.append(error)\n\n def _verify_similarity(self, screenshot1, screenshot2,\n similarity_percent_threshold=5):\n \"\"\"\n Make sure screenshots are the same or similar.\n\n @param screenshot1: path to screenshot.\n @param screenshot2: path to screenshot.\n @param difference_percent_threshold: threshold for similarity.\n\n @returns number of errors found (0 or 1).\n\n \"\"\"\n filename1 = screenshot1.split('/')[-1]\n filename2 = screenshot2.split('/')[-1]\n diff = get_percent_difference(screenshot1, screenshot2)\n logging.info(\"Screenshot 1 and 2 similarity diff: %s\" % diff)\n if not diff <= similarity_percent_threshold:\n error = ('Screenshots differ by %d %%: %s vs %s'\n % (diff, filename1, filename2))\n self.ERRORS.append(error)\n\n def run_once(self):\n \"\"\"\n Run tablet mode test to spoof various tablet modes and ensure\n device changes accordingly.\n \"\"\"\n\n # Ensure we start in laptop mode.\n self._revert_laptop()\n\n logging.info(\"Take screenshot for initial laptop mode.\")\n laptop_start = self._take_screenshot('laptop_start')\n\n logging.info(\"Entering landscape mode.\")\n self._spoof_tablet_landscape()\n landscape = self._take_screenshot('landscape')\n\n self._revert_laptop()\n\n logging.info(\"Entering portrait mode.\")\n self._spoof_tablet_portrait()\n portrait = self._take_screenshot('portrait')\n\n self._revert_laptop()\n laptop_end = self._take_screenshot('laptop_end')\n\n # Compare screenshots and determine the number of errors.\n self._verify_similarity(laptop_start, laptop_end)\n self._verify_difference(laptop_start, landscape)\n self._verify_difference(landscape, portrait)\n self._verify_difference(portrait, laptop_end)\n\n if self.ERRORS:\n raise error.TestFail('; '.join(set(self.ERRORS)))\n\n def cleanup(self):\n self._revert_laptop()\n", "repo_name": "kindle4jerry/honor-play-kernel-9.0-kindle4jerry", "sub_path": "external/autotest/client/site_tests/platform_TabletMode/platform_TabletMode.py", "file_name": "platform_TabletMode.py", "file_ext": "py", "file_size_in_byte": 5798, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "20", "api": [{"api_name": "autotest_lib.client.cros.image_comparison.pdiff_image_comparer.PdiffImageComparer", "line_number": 25, "usage_type": "call"}, {"api_name": "autotest_lib.client.cros.image_comparison.pdiff_image_comparer", "line_number": 25, "usage_type": "name"}, {"api_name": "os.path.getsize", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path", "line_number": 27, "usage_type": "attribute"}, {"api_name": "autotest_lib.client.bin.test.test", "line_number": 30, "usage_type": "attribute"}, {"api_name": "autotest_lib.client.bin.test", "line_number": 30, "usage_type": "name"}, {"api_name": "autotest_lib.client.bin.utils.system", "line_number": 50, "usage_type": "call"}, {"api_name": "autotest_lib.client.bin.utils", "line_number": 50, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 51, "usage_type": "call"}, {"api_name": "autotest_lib.client.bin.utils.system", "line_number": 52, "usage_type": "call"}, {"api_name": "autotest_lib.client.bin.utils", "line_number": 52, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 53, "usage_type": "call"}, {"api_name": "autotest_lib.client.bin.utils.system", "line_number": 57, "usage_type": "call"}, {"api_name": "autotest_lib.client.bin.utils", "line_number": 57, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 58, "usage_type": "call"}, {"api_name": "autotest_lib.client.bin.utils.system", "line_number": 62, "usage_type": "call"}, {"api_name": "autotest_lib.client.bin.utils", "line_number": 62, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 63, "usage_type": "call"}, {"api_name": "autotest_lib.client.bin.utils.system", "line_number": 64, "usage_type": "call"}, {"api_name": "autotest_lib.client.bin.utils", "line_number": 64, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 65, "usage_type": "call"}, {"api_name": "autotest_lib.client.cros.graphics.graphics_utils.take_screenshot", "line_number": 77, "usage_type": "call"}, {"api_name": "autotest_lib.client.cros.graphics.graphics_utils", "line_number": 77, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 96, "usage_type": "call"}, {"api_name": "autotest_lib.client.common_lib.error", "line_number": 98, "usage_type": "name"}, {"api_name": "autotest_lib.client.common_lib.error", "line_number": 100, "usage_type": "argument"}, {"api_name": "logging.info", "line_number": 117, "usage_type": "call"}, {"api_name": "autotest_lib.client.common_lib.error", "line_number": 119, "usage_type": "name"}, {"api_name": "autotest_lib.client.common_lib.error", "line_number": 121, "usage_type": "argument"}, {"api_name": "logging.info", "line_number": 132, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 135, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 141, "usage_type": "call"}, {"api_name": "autotest_lib.client.common_lib.error.TestFail", "line_number": 155, "usage_type": "call"}, {"api_name": "autotest_lib.client.common_lib.error", "line_number": 155, "usage_type": "name"}]} +{"seq_id": "41162926458", "text": "import sys\nimport os\nimport json\nfrom ament_index_python.packages import get_package_share_directory\n\nfrom launch import LaunchDescription, actions, conditions\nfrom launch.substitutions.launch_configuration import LaunchConfiguration\nfrom launch.actions import IncludeLaunchDescription, DeclareLaunchArgument\nfrom launch.substitutions import PythonExpression, LocalSubstitution, TextSubstitution, PathJoinSubstitution\nfrom launch.launch_description_sources import PythonLaunchDescriptionSource\n\npkg_hyperion_interrogator = get_package_share_directory('hyperion_interrogator')\npkg_needle_shape_publisher = get_package_share_directory('needle_shape_publisher')\n\n# Determine numChs and numAAs from needleParamFile\ndef determineCHsAAs(needleParamFile: str):\n \"\"\" Determine the number of channels and active areas available \"\"\"\n with open(needleParamFile, 'r') as paramFile:\n params = json.load(paramFile) \n numChs = params['# channels']\n numAAs = params['# active areas']\n return numChs, numAAs\n\ndef generate_launch_description():\n ld = LaunchDescription()\n\n # Set numChs and numAAs\n numCHs, numAAs = 3, 4\n for arg in sys.argv:\n if arg.startswith('needleParamFile:='):\n needleParamFile = arg.split(':=')[1]\n numCHs, numAAs = determineCHsAAs(needleParamFile)\n\n # Arguments\n arg_simlevel = DeclareLaunchArgument(\n 'sim_level',\n default_value ='2',\n description = 'Simulation level: 1 - virtual sensors (demo), 2 - real sensors'\n )\n arg_params = DeclareLaunchArgument(\n 'needleParamFile',\n default_value = '3CH-4AA-0005_needle_params_2022-01-26_Jig-Calibration_best_weights.json',\n description = 'The shape-sensing needle parameter json file' \n ) \n arg_interrIP = DeclareLaunchArgument(\n 'interrogatorIP', \n default_value = '10.0.0.55',\n description = \"Interrogator IP\" \n )\n\n # Needle shape publisher\n ld_needlepub = IncludeLaunchDescription( # needle shape publisher\n PythonLaunchDescriptionSource(\n os.path.join(pkg_needle_shape_publisher, 'needle.launch.py')),\n launch_arguments = {\n 'needleParamFile': LaunchConfiguration('needleParamFile'),\n }.items()\n )\n\n # Hyperion Interrogator\n ld_hyperiondemo = IncludeLaunchDescription( # Virtual demo (sim_level_needle = 1)\n PythonLaunchDescriptionSource(os.path.join(pkg_hyperion_interrogator, 'hyperion_demo.launch.py')),\n condition = conditions.IfCondition(\n PythonExpression([LaunchConfiguration('sim_level'), \" == 1\"])\n ),\n launch_arguments = {\n 'numCH': TextSubstitution(text=str(numCHs)), \n 'numAA': TextSubstitution(text=str(numAAs))\n }.items()\n )\n\n ld_hyperionstream = IncludeLaunchDescription( # Real hardware (sim_level_needle = 2)\n PythonLaunchDescriptionSource(os.path.join(pkg_hyperion_interrogator, 'hyperion_streamer.launch.py')),\n condition=conditions.IfCondition(\n PythonExpression([LaunchConfiguration('sim_level'), \" == 2\"])\n ),\n launch_arguments = {\n 'ip': LaunchConfiguration('interrogatorIP')\n }.items()\n )\n\n # Add to launch description\n ld.add_action(arg_simlevel)\n ld.add_action(arg_params)\n ld.add_action(arg_interrIP)\n \n ld.add_action(ld_needlepub)\n ld.add_action(ld_hyperiondemo)\n ld.add_action(ld_hyperionstream) \n\n return ld\n", "repo_name": "maribernardes/trajcontrol_jhu", "sub_path": "launch/jhu_needle.launch.py", "file_name": "jhu_needle.launch.py", "file_ext": "py", "file_size_in_byte": 3493, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "ament_index_python.packages.get_package_share_directory", "line_number": 12, "usage_type": "call"}, {"api_name": "ament_index_python.packages.get_package_share_directory", "line_number": 13, "usage_type": "call"}, {"api_name": "json.load", "line_number": 19, "usage_type": "call"}, {"api_name": "launch.LaunchDescription", "line_number": 25, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 29, "usage_type": "attribute"}, {"api_name": "launch.actions.DeclareLaunchArgument", "line_number": 35, "usage_type": "call"}, {"api_name": "launch.actions.DeclareLaunchArgument", "line_number": 40, "usage_type": "call"}, {"api_name": "launch.actions.DeclareLaunchArgument", "line_number": 45, "usage_type": "call"}, {"api_name": "launch.actions.IncludeLaunchDescription", "line_number": 52, "usage_type": "call"}, {"api_name": "launch.launch_description_sources.PythonLaunchDescriptionSource", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path", "line_number": 54, "usage_type": "attribute"}, {"api_name": "launch.substitutions.launch_configuration.LaunchConfiguration", "line_number": 56, "usage_type": "call"}, {"api_name": "launch.actions.IncludeLaunchDescription", "line_number": 61, "usage_type": "call"}, {"api_name": "launch.launch_description_sources.PythonLaunchDescriptionSource", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path", "line_number": 62, "usage_type": "attribute"}, {"api_name": "launch.conditions.IfCondition", "line_number": 63, "usage_type": "call"}, {"api_name": "launch.conditions", "line_number": 63, "usage_type": "name"}, {"api_name": "launch.substitutions.PythonExpression", "line_number": 64, "usage_type": "call"}, {"api_name": "launch.substitutions.launch_configuration.LaunchConfiguration", "line_number": 64, "usage_type": "call"}, {"api_name": "launch.substitutions.TextSubstitution", "line_number": 67, "usage_type": "call"}, {"api_name": "launch.substitutions.TextSubstitution", "line_number": 68, "usage_type": "call"}, {"api_name": "launch.actions.IncludeLaunchDescription", "line_number": 72, "usage_type": "call"}, {"api_name": "launch.launch_description_sources.PythonLaunchDescriptionSource", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path", "line_number": 73, "usage_type": "attribute"}, {"api_name": "launch.conditions.IfCondition", "line_number": 74, "usage_type": "call"}, {"api_name": "launch.conditions", "line_number": 74, "usage_type": "name"}, {"api_name": "launch.substitutions.PythonExpression", "line_number": 75, "usage_type": "call"}, {"api_name": "launch.substitutions.launch_configuration.LaunchConfiguration", "line_number": 75, "usage_type": "call"}, {"api_name": "launch.substitutions.launch_configuration.LaunchConfiguration", "line_number": 78, "usage_type": "call"}]} +{"seq_id": "74849774769", "text": "import asyncio\nimport logging\nfrom contextlib import asynccontextmanager\nfrom dataclasses import dataclass\nfrom typing import AsyncGenerator, AsyncIterator\n\nfrom .buffer import TelegramBuffer\nfrom .exceptions import ReadTimeout\nfrom .telegram import Telegram\n\nLOGGER = logging.getLogger(__name__)\n\n\n@dataclass(frozen=True, kw_only=True)\nclass StreamerOptions:\n \"\"\"Configurable options for `TelegramStreamer`.\"\"\"\n\n buffer_size: int = 256\n read_timeout: int = 10\n\n\nclass TelegramStreamer:\n def __init__(\n self,\n reader: asyncio.StreamReader,\n *,\n streamer_options: StreamerOptions | None = None,\n _buffer: TelegramBuffer | None = None,\n ):\n self.reader = reader\n self.options = streamer_options or StreamerOptions()\n self.buffer = _buffer or TelegramBuffer()\n\n self._is_streaming: bool = True\n\n async def _read(self) -> str:\n try:\n data = await asyncio.wait_for(\n self.reader.read(self.options.buffer_size),\n self.options.read_timeout,\n )\n except asyncio.TimeoutError as exc:\n LOGGER.info(\"Read timeout\")\n raise ReadTimeout() from exc\n return data.decode()\n\n async def __aiter__(self) -> AsyncIterator[Telegram]:\n while self._is_streaming:\n data = await self._read()\n self.buffer.append(data)\n\n for telegram in self.buffer.drain():\n LOGGER.debug(\"Received telegram\")\n yield telegram\n\n def stop(self):\n self._is_streaming = False\n\n\n@asynccontextmanager\nasync def managed_telegram_streamer(\n host: str,\n port: int,\n) -> AsyncGenerator[TelegramStreamer, None]:\n LOGGER.debug(\"Opening connection\")\n\n reader, writer = await asyncio.open_connection(host, port)\n\n LOGGER.info(\"Opened connection\")\n\n try:\n yield TelegramStreamer(reader)\n finally:\n LOGGER.info(\"Closing streamer\")\n\n writer.close()\n await writer.wait_closed()\n\n LOGGER.info(\"Closed streamer\")\n", "repo_name": "iw108/dsmr", "sub_path": "dsmr_client/streamer.py", "file_name": "streamer.py", "file_ext": "py", "file_size_in_byte": 2063, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "logging.getLogger", "line_number": 11, "usage_type": "call"}, {"api_name": "dataclasses.dataclass", "line_number": 14, "usage_type": "call"}, {"api_name": "asyncio.StreamReader", "line_number": 25, "usage_type": "attribute"}, {"api_name": "buffer.TelegramBuffer", "line_number": 28, "usage_type": "name"}, {"api_name": "buffer.TelegramBuffer", "line_number": 32, "usage_type": "call"}, {"api_name": "asyncio.wait_for", "line_number": 38, "usage_type": "call"}, {"api_name": "asyncio.TimeoutError", "line_number": 42, "usage_type": "attribute"}, {"api_name": "exceptions.ReadTimeout", "line_number": 44, "usage_type": "call"}, {"api_name": "typing.AsyncIterator", "line_number": 47, "usage_type": "name"}, {"api_name": "telegram.Telegram", "line_number": 47, "usage_type": "name"}, {"api_name": "asyncio.open_connection", "line_number": 67, "usage_type": "call"}, {"api_name": "contextlib.asynccontextmanager", "line_number": 60, "usage_type": "name"}, {"api_name": "typing.AsyncGenerator", "line_number": 64, "usage_type": "name"}]} +{"seq_id": "17758234535", "text": "import copy\n\nimport numpy as np\nimport datetime\nimport gym\n\nfrom simple_model_functions import calc_arid, calc_yield, calc_ref_evapotranspiration, calc_transpiration, \\\n calc_f_temp, calc_f_co2, calc_f_heat, calc_f_water, calc_plant_available_water, calc_f_solar_water, calc_f_solar, \\\n calc_biomass_rate, calc_cumulative_biomass, calc_rad_50p_senescence, delta_cumulative_temp\n\n\nclass SimpleCropModelEnv(gym.Env):\n def __init__(self, sowing_date,\n num_growing_days,\n weather_schedule,\n weather_forecast_stds,\n latitude,\n elevation,\n crop_parameters,\n initial_biomass=0, # Kg\n initial_cumulative_temp=0, # degrees C day\n # initial_f_solar=0, # unit-less; todo: paper says this is an init param, but where would it be used?\n initial_available_water_content=None, # not an initial parameter in SIMPLE, but reasonable to vary,\n # https://acsess.onlinelibrary.wiley.com/doi/full/10.2134/agronj2011.0286 assumes initial value to\n # be equal to the available water capacity (AWC) in their crop model comparison\n seed=None,\n cumulative_biomass_std=1.0,\n plant_available_water_std=1.0):\n\n # simulation parameters\n self.num_growing_days = num_growing_days\n\n # location parameters\n self.latitude = latitude\n self.elevation = elevation\n\n # crop parameters\n self.crop_temp_base = crop_parameters.temp_base\n self.crop_temp_opt = crop_parameters.temp_opt\n self.crop_RUE = crop_parameters.RUE\n self.crop_rad_50p_growth = crop_parameters.rad_50p_growth\n self.crop_rad_50p_senescence = crop_parameters.rad_50p_senescence\n self.crop_maturity_temp = crop_parameters.maturity_temp\n self.crop_rad_50p_max_heat = crop_parameters.rad_50p_max_heat\n self.crop_rad_50p_max_water = crop_parameters.rad_50p_max_water\n self.crop_heat_stress_thresh = crop_parameters.heat_stress_thresh\n self.crop_heat_stress_extreme = crop_parameters.heat_stress_extreme\n self.crop_drought_stress_sensitivity = crop_parameters.drought_stress_sensitivity\n self.crop_deep_drainage_coef = crop_parameters.deep_drainage_coef\n self.crop_water_holding_capacity = crop_parameters.water_holding_capacity\n self.crop_runoff_curve_number = crop_parameters.runoff_curve_number\n self.crop_root_zone_depth = crop_parameters.root_zone_depth\n self.crop_co2_sensitivity = crop_parameters.co2_sensitivity\n self.crop_harvest_index = crop_parameters.harvest_index\n\n # variables for reset\n self.init_cumulative_temp = initial_cumulative_temp\n self.init_crop_rad_50p_senescence = crop_parameters.rad_50p_senescence\n self.init_biomass = initial_biomass\n self.sowing_date = sowing_date\n\n # root zone available water (W_i) = root zone available water content (theta^{ad}_{a, i}) times the root\n # zone depth (RZD), i.e. W_i = theta^{ad}_{a, i} * RZD. See:\n # https://acsess.onlinelibrary.wiley.com/doi/full/10.2134/agronj2011.0286, which also justifies the initial\n # condition shown here in the crop comparison section\n if initial_available_water_content is None:\n initial_available_water_content = self.crop_water_holding_capacity\n self.initial_available_water_content = initial_available_water_content # unused, but saved for reference\n self.initial_plant_available_water = initial_available_water_content * self.crop_root_zone_depth\n\n # tracking variables\n self.cumulative_mean_temp = None # TT variable in paper\n self.cumulative_biomass = None\n self.plant_available_water = None\n self.date = None\n self.day = None\n\n # Randomization parameters\n self.cumulative_biomass_sigma = cumulative_biomass_std\n self.plant_available_water_sigma = plant_available_water_std\n self.rng = np.random.default_rng(seed)\n\n # weather data\n self.weather_schedule = weather_schedule\n self.weather_forecast_stds = weather_forecast_stds\n\n # gym parameters\n self.observation_space = gym.spaces.Box(-np.inf, np.inf, shape=(30,), dtype=np.float64)\n self.action_space = gym.spaces.Box(0, 100, shape=(1,), dtype=np.float64)\n self.reward_range = (-np.inf, np.inf)\n self.metadata = {}\n\n def weather_info(self, day, noisy=False):\n \"\"\"return a weather info for a certain day\"\"\"\n if day >= self.num_growing_days:\n return np.array([0, 0, 0, 0, 0, 0, 0, 0])\n if not noisy:\n return np.array(\n [self.weather_schedule.max_temp[day], # degrees C\n self.weather_schedule.min_temp[day], # degrees C\n self.weather_schedule.precipitation[day], # mm\n self.weather_schedule.radiation[day], # MJ/(m**2 * day)\n self.weather_schedule.co2[day], # PPM\n self.weather_schedule.avg_vapor_pressure[day], # hPa\n self.weather_schedule.mean_temp[day], # degrees C; not in SIMPLE model\n self.weather_schedule.avg_wind[day] # m/s; not in SIMPLE model\n ]\n )\n else:\n return np.array(\n [self.rng.normal(self.weather_schedule.max_temp[day], self.weather_forecast_stds.max_temp),\n self.rng.normal(self.weather_schedule.min_temp[day], self.weather_forecast_stds.min_temp),\n max(0.0, self.rng.normal(self.weather_schedule.precipitation[day],\n self.weather_forecast_stds.precipitation)),\n max(0.0, self.rng.normal(self.weather_schedule.radiation[day], self.weather_forecast_stds.radiation)),\n max(0.0, self.rng.normal(self.weather_schedule.co2[day], self.weather_forecast_stds.co2)),\n max(0.0, self.rng.normal(self.weather_schedule.avg_vapor_pressure[day],\n self.weather_forecast_stds.avg_vapor_pressure)),\n self.rng.normal(self.weather_schedule.mean_temp[day], self.weather_forecast_stds.mean_temp),\n max(0.0, self.rng.normal(self.weather_schedule.avg_wind[day], self.weather_forecast_stds.avg_wind))\n ]\n )\n\n def create_dict_state(self):\n \"\"\"\n Things to include in the state would be:\n - Actual cumulative biomass\n - Noisy reading of cumulative biomass (such as might be estimated from an image of the plant?)\n - Cumulative mean temp (seems relatively measurable)\n - Days since sowing date\n - Weather from last day\n - Next day's weather forecast (perfect)\n - Noisy \"prediction\" of next day's weather forecast\n - Root zone available water reading (like a soil measurement?)\n - Noisy reading of root zone available water\n \"\"\"\n return {'cumulative_biomass': np.array(self.cumulative_biomass).reshape((1,)),\n 'cumulative_biomass_noisy':\n np.array(max(0, self.rng.normal(self.cumulative_biomass,\n self.cumulative_biomass_sigma))).reshape((1,)),\n 'cumulative_mean_temp': np.array(self.cumulative_mean_temp).reshape((1,)),\n 'day': np.array(self.day).reshape((1,)),\n 'weather_today': self.weather_info(self.day),\n 'weather_tomorrow': self.weather_info(self.day + 1),\n 'weather_tomorrow_forecast': self.weather_info(self.day + 1, noisy=True),\n 'plant_available_water': np.array(self.plant_available_water).reshape((1,)),\n 'plant_available_water_noisy':\n np.array(max(0,\n self.rng.normal(self.plant_available_water,\n self.plant_available_water_sigma))).reshape((1,))\n }\n\n @staticmethod\n def create_numpy_state(dict_state: dict):\n return np.concatenate([v for v in dict_state.values()])\n\n @staticmethod\n def create_info(dict_state: dict, additional_info: dict):\n info = copy.deepcopy(dict_state)\n info.update(additional_info)\n return info\n\n def irrigation_reward(self, irrigation):\n # assume irrigation is for a non-towable center pivot, and consider\n # http://h2oinitiative.com/wp-content/uploads/2018/05/Estimating-Irrigation-Costs-Tacker-et-al.pdf\n # even though it is from Arkansas...\n # 9 inch irrigation season is $116/acre ~ $286.64/hectare assuming 2.471 acres per hectare\n # 9 inches is 22.86 cm, or 0.2286 m, and 1 hectare = 10,000 m**2, so price per mm for 1 square meter plot is\n # $286.64/(10,000 m**2 * 228.6 mm) = $0.000125 / mm / m**2\n return -0.000125 * irrigation\n\n def step(self, action):\n rad_day = self.weather_schedule.radiation[self.day]\n mean_temp_day = self.weather_schedule.mean_temp[self.day]\n max_temp_day = self.weather_schedule.max_temp[self.day]\n min_temp_day = self.weather_schedule.min_temp[self.day]\n avg_vapor_pressure = self.weather_schedule.avg_vapor_pressure[self.day]\n avg_wind = self.weather_schedule.avg_wind[self.day]\n precipitation = self.weather_schedule.precipitation[self.day]\n irrigation = action[0]\n co2_day = self.weather_schedule.co2[self.day]\n\n if irrigation < 0:\n raise ValueError(\"Action cannot be negative! Got {}\".format(irrigation))\n\n self.cumulative_mean_temp += delta_cumulative_temp(mean_temp_day, self.crop_temp_base)\n f_heat = calc_f_heat(max_temp_day, self.crop_heat_stress_thresh, self.crop_heat_stress_extreme)\n ref_evapotranspiration = calc_ref_evapotranspiration(self.date, self.latitude, self.elevation, min_temp_day,\n max_temp_day, rad_day, avg_vapor_pressure, avg_wind)\n transpiration = calc_transpiration(ref_evapotranspiration, self.plant_available_water) # use PAW from today\n # update PAW\n self.plant_available_water = calc_plant_available_water(self.plant_available_water,\n precipitation, irrigation,\n transpiration,\n self.crop_deep_drainage_coef,\n self.crop_root_zone_depth,\n self.crop_water_holding_capacity,\n self.crop_runoff_curve_number)\n arid_index = calc_arid(transpiration, ref_evapotranspiration)\n f_water = calc_f_water(self.crop_drought_stress_sensitivity, arid_index)\n f_solar, senescence = calc_f_solar(self.cumulative_mean_temp, self.crop_rad_50p_growth, self.crop_maturity_temp,\n self.crop_rad_50p_senescence)\n if senescence: # Note: Not sure if this is how to correctly designate growth vs senescence periods\n self.crop_rad_50p_senescence = calc_rad_50p_senescence(self.crop_rad_50p_senescence,\n self.crop_rad_50p_max_heat,\n self.crop_rad_50p_max_water,\n f_heat,\n f_water)\n f_co2 = calc_f_co2(self.crop_co2_sensitivity, co2_day)\n f_temp = calc_f_temp(mean_temp_day, self.crop_temp_base, self.crop_temp_opt)\n f_solar_water = calc_f_solar_water(f_water)\n biomass_rate = calc_biomass_rate(rad_day, f_solar, f_solar_water, self.crop_RUE, f_co2, f_temp, f_heat, f_water)\n self.cumulative_biomass = calc_cumulative_biomass(self.cumulative_biomass, biomass_rate)\n\n # do this before updating day to get accurate states\n dict_state = self.create_dict_state()\n state = self.create_numpy_state(dict_state)\n info = self.create_info(dict_state, {'arid_index': arid_index, 'f_solar': f_solar})\n\n if self.day >= self.num_growing_days - 1:\n reward = calc_yield(self.cumulative_biomass, self.crop_harvest_index) + self.irrigation_reward(irrigation)\n return state, reward, True, info\n\n self.day += 1\n self.date += datetime.timedelta(days=1)\n return state, self.irrigation_reward(irrigation), False, info\n\n def reset(self):\n self.cumulative_mean_temp = self.init_cumulative_temp # TT variable in paper\n self.cumulative_biomass = self.init_biomass\n self.crop_rad_50p_senescence = self.init_crop_rad_50p_senescence\n # root zone available water (W_i) = root zone available water content (theta^{ad}_{a, i} or PAW) times the root\n # zone depth (RZD)\n self.plant_available_water = self.initial_plant_available_water\n self.date = self.sowing_date\n self.day = 0\n return self.create_numpy_state(self.create_dict_state())\n\n def render(self, mode='human'):\n pass\n", "repo_name": "iscoe/croprl", "sub_path": "simple_model_env.py", "file_name": "simple_model_env.py", "file_ext": "py", "file_size_in_byte": 13513, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "20", "api": [{"api_name": "gym.Env", "line_number": 12, "usage_type": "attribute"}, {"api_name": "numpy.random.default_rng", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 81, "usage_type": "attribute"}, {"api_name": "gym.spaces.Box", "line_number": 88, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 88, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 88, "usage_type": "attribute"}, {"api_name": "numpy.float64", "line_number": 88, "usage_type": "attribute"}, {"api_name": "gym.spaces.Box", "line_number": 89, "usage_type": "call"}, {"api_name": "gym.spaces", "line_number": 89, "usage_type": "attribute"}, {"api_name": "numpy.float64", "line_number": 89, "usage_type": "attribute"}, {"api_name": "numpy.inf", "line_number": 90, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 146, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 155, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 159, "usage_type": "call"}, {"api_name": "simple_model_functions.delta_cumulative_temp", "line_number": 186, "usage_type": "call"}, {"api_name": "simple_model_functions.calc_f_heat", "line_number": 187, "usage_type": "call"}, {"api_name": "simple_model_functions.calc_ref_evapotranspiration", "line_number": 188, "usage_type": "call"}, {"api_name": "simple_model_functions.calc_transpiration", "line_number": 190, "usage_type": "call"}, {"api_name": "simple_model_functions.calc_plant_available_water", "line_number": 192, "usage_type": "call"}, {"api_name": "simple_model_functions.calc_arid", "line_number": 199, "usage_type": "call"}, {"api_name": "simple_model_functions.calc_f_water", "line_number": 200, "usage_type": "call"}, {"api_name": "simple_model_functions.calc_f_solar", "line_number": 201, "usage_type": "call"}, {"api_name": "simple_model_functions.calc_rad_50p_senescence", "line_number": 204, "usage_type": "call"}, {"api_name": "simple_model_functions.calc_f_co2", "line_number": 209, "usage_type": "call"}, {"api_name": "simple_model_functions.calc_f_temp", "line_number": 210, "usage_type": "call"}, {"api_name": "simple_model_functions.calc_f_solar_water", "line_number": 211, "usage_type": "call"}, {"api_name": "simple_model_functions.calc_biomass_rate", "line_number": 212, "usage_type": "call"}, {"api_name": "simple_model_functions.calc_cumulative_biomass", "line_number": 213, "usage_type": "call"}, {"api_name": "simple_model_functions.calc_yield", "line_number": 221, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 225, "usage_type": "call"}]} +{"seq_id": "43939993778", "text": "from datetime import datetime\nfrom pprint import pprint\n\ndef parse_coin_cc(data=None, currency='USD'):\n update_time = datetime.fromtimestamp(data['LASTUPDATE']).strftime('%Y-%m-%d %H:%M:%S')\n\n coin = {\n 'symbol': data['FROMSYMBOL'],\n 'value': data['PRICE'],\n 'time': update_time\n }\n return coin\n\ndef parse_coin_cmc(data=None, currency='USD'):\n _coin = data['quotes'][currency]\n\n name = data['name']\n percent_change_1h = _coin['percent_change_1h']\n percent_change_24h = _coin['percent_change_24h']\n percent_change_7d = _coin['percent_change_7d']\n\n coin = {\n 'name': name,\n 'percent_change_1h': percent_change_1h,\n 'percent_change_24h': percent_change_24h,\n 'percent_change_7d': percent_change_7d\n }\n return coin\n\ndef clear_cmc_list(coins=None):\n coin_list = []\n for coin in coins:\n my_dict = {\n '_id': coin['id'],\n 'name': coin['name'],\n 'symbol': coin['symbol']\n }\n\n coin_list.append(my_dict)\n return coin_list\n\ndef clear_cc_list(coins=None):\n coin_list = []\n for coin in coins.items():\n my_dict = {\n '_id': coin[1]['Id'],\n 'name': coin[1]['CoinName'],\n 'symbol': coin[1]['Symbol']\n }\n coin_list.append(my_dict)\n return coin_list\n\ndef url_generator(url_type=None, symbol=None, coin_id=None, currency='USD'):\n url = {\n 'cc_single_coin' : \"https://min-api.cryptocompare.com/data/pricemultifull?fsyms={}&tsyms={}\".format(symbol, currency),\n 'cc_multiple_coin':\"https://min-api.cryptocompare.com/data/pricemultifull?fsyms={}&tsyms={}\".format(symbol, currency),\n 'cmc_single_coin' : \"https://api.coinmarketcap.com/v2/ticker/{}/?convert={}\".format(coin_id, currency),\n 'top_10' : \"https://api.coinmarketcap.com/v2/ticker/?structure=array&limit=10\",\n 'all_coins' : \"https://api.coinmarketcap.com/v2/listings/\",\n 'hour_graph' : \"https://min-api.cryptocompare.com/data/histominute?fsym={}&tsym={}&limit=59\".format(symbol, currency),\n 'day_graph' : \"https://min-api.cryptocompare.com/data/histominute?fsym={}&tsym={}&limit=1440\".format(symbol, currency),\n 'week_graph' : \"https://min-api.cryptocompare.com/data/histohour?fsym={}&tsym={}&limit=168\".format(symbol, currency),\n 'month_graph' : \"https://min-api.cryptocompare.com/data/histohour?fsym={}&tsym={}&limit=720\".format(symbol, currency),\n 'advanced_graph' : \"https://min-api.cryptocompare.com/data/histoday?fsym={}&tsym={}&limit=180\".format(symbol, currency)\n }\n return url[url_type]\n", "repo_name": "dcorral3/CryptoPTB", "sub_path": "service_utils.py", "file_name": "service_utils.py", "file_ext": "py", "file_size_in_byte": 2796, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "20", "api": [{"api_name": "datetime.datetime.fromtimestamp", "line_number": 5, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 5, "usage_type": "name"}]} +{"seq_id": "6836818303", "text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport h5py\r\nimport scipy\r\nfrom PIL import Image\r\nfrom scipy import ndimage\r\nimport tkinter as tk\r\nfrom tkinter import filedialog\r\n\r\ndef load_dataset():\r\n train_dataset = h5py.File('C:/Users/prate/OneDrive/Documents/Python Projects/cat-vs-noncat-classification-logistic-regression/datasets/train_catvnoncat.h5', \"r\")\r\n train_set_x_orig = np.array(train_dataset[\"train_set_x\"][:]) \r\n train_set_y_orig = np.array(train_dataset[\"train_set_y\"][:])\r\n\r\n test_dataset = h5py.File('C:/Users/prate/OneDrive/Documents/Python Projects/cat-vs-noncat-classification-logistic-regression/datasets/test_catvnoncat.h5', \"r\")\r\n test_set_x_orig = np.array(test_dataset[\"test_set_x\"][:])\r\n test_set_y_orig = np.array(test_dataset[\"test_set_y\"][:])\r\n\r\n classes = np.array(test_dataset[\"list_classes\"][:])\r\n \r\n train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))\r\n test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))\r\n \r\n return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes\r\n\r\ntrain_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()\r\n\r\nm_train = train_set_x_orig.shape[0]\r\nm_test = test_set_x_orig.shape[0]\r\nnum_px = train_set_x_orig.shape[1]\r\n\r\ntrain_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T\r\ntest_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T\r\n\r\ntrain_set_x = train_set_x_flatten/255.\r\ntest_set_x = test_set_x_flatten/255.\r\n\r\ndef sigmoid(z):\r\n \r\n s = 1/(1 + np.exp(- z))\r\n \r\n return s\r\n\r\ndef initialize_with_zeros(dim):\r\n \r\n w = np.zeros((dim, 1))\r\n b = 0\r\n \r\n\r\n assert(w.shape == (dim, 1))\r\n assert(isinstance(b, float) or isinstance(b, int))\r\n \r\n return w, b\r\n\r\ndef propagate(w, b, X, Y):\r\n \r\n m = X.shape[1]\r\n A = sigmoid( np.dot(w.T, X) + b) \r\n cost = (- 1/ m) * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A)) # compute cost\r\n dw = (1/ m) * np.dot(X, (A - Y).T)\r\n db = (1/ m) * np.sum(A - Y)\r\n \r\n assert(dw.shape == w.shape)\r\n assert(db.dtype == float)\r\n cost = np.squeeze(cost)\r\n assert(cost.shape == ())\r\n \r\n grads = {\"dw\": dw,\r\n \"db\": db}\r\n \r\n return grads, cost\r\n\r\ndef optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):\r\n \r\n costs = []\r\n \r\n for i in range(num_iterations):\r\n grads, cost = propagate(w, b, X, Y)\r\n \r\n dw = grads[\"dw\"]\r\n db = grads[\"db\"]\r\n \r\n w = w - learning_rate * dw\r\n b = b - learning_rate * db\r\n if i % 100 == 0:\r\n costs.append(cost)\r\n if print_cost and i % 100 == 0:\r\n print (\"Cost after iteration %i: %f\" %(i, cost))\r\n \r\n params = {\"w\": w,\r\n \"b\": b}\r\n \r\n grads = {\"dw\": dw,\r\n \"db\": db}\r\n \r\n return params, grads, costs\r\n\r\ndef predict(w, b, X):\r\n \r\n \r\n m = X.shape[1]\r\n Y_prediction = np.zeros((1,m))\r\n w = w.reshape(X.shape[0], 1)\r\n A = sigmoid(np.dot((w.T), X) + b)\r\n \r\n for i in range(A.shape[1]):\r\n if(A[0, i] <= 0.5):\r\n Y_prediction[0, i] = 0\r\n else:\r\n Y_prediction[0, i] = 1\r\n \r\n assert(Y_prediction.shape == (1, m))\r\n \r\n return Y_prediction\r\n\r\ndef model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):\r\n w, b = initialize_with_zeros(X_train.shape[0])\r\n parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations= 2000, learning_rate = 0.5, print_cost = False)\r\n \r\n w = parameters[\"w\"]\r\n b = parameters[\"b\"]\r\n Y_prediction_test = predict(w, b, X_test)\r\n Y_prediction_train = predict(w, b, X_train)\r\n print(\"train accuracy: {} %\".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))\r\n print(\"test accuracy: {} %\".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))\r\n\r\n \r\n d = {\"costs\": costs,\r\n \"Y_prediction_test\": Y_prediction_test, \r\n \"Y_prediction_train\" : Y_prediction_train, \r\n \"w\" : w, \r\n \"b\" : b,\r\n \"learning_rate\" : learning_rate,\r\n \"num_iterations\": num_iterations}\r\n \r\n return d\r\n\r\nimages = \"C:/Users/prate/OneDrive/Documents/Python Projects/cat-vs-noncat-classification-logistic-regression/test-images\"\r\n\r\ndef load_file(testimage):\r\n testimage = tk.filedialog.askopenfilename(initialdir = images)\r\n return testimage\r\n\r\ntestimage = \"C:/Users/prate/OneDrive/Documents/Python Projects/cat-vs-noncat-classification-logistic-regression/test-images/cat\"\r\nmy_image = load_file(testimage)\r\nimage = np.array(ndimage.imread(my_image, flatten=False))\r\nmy_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((1, num_px*num_px*3)).T\r\nd = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)\r\nmy_predicted_image = predict(d[\"w\"], d[\"b\"], my_image)\r\n\r\nplt.imshow(image)\r\nprint(\"y = \" + str(np.squeeze(my_predicted_image)) + \", your algorithm predicts a \\\"\" + classes[int(np.squeeze(my_predicted_image)),].decode(\"utf-8\") + \"\\\" picture.\")\r\n \r\n\r\n\r\n\r\n", "repo_name": "prateeksawhney97/cat-vs-noncat-classification-logistic", "sub_path": "temp.py", "file_name": "temp.py", "file_ext": "py", "file_size_in_byte": 5273, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "20", "api": [{"api_name": "h5py.File", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 13, "usage_type": "call"}, {"api_name": "h5py.File", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 125, "usage_type": "call"}, {"api_name": "tkinter.filedialog.askopenfilename", "line_number": 141, "usage_type": "call"}, {"api_name": "tkinter.filedialog", "line_number": 141, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 146, "usage_type": "call"}, {"api_name": "scipy.ndimage.imread", "line_number": 146, "usage_type": "call"}, {"api_name": "scipy.ndimage", "line_number": 146, "usage_type": "name"}, {"api_name": "scipy.misc.imresize", "line_number": 147, "usage_type": "call"}, {"api_name": "scipy.misc", "line_number": 147, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 151, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 151, "usage_type": "name"}, {"api_name": "numpy.squeeze", "line_number": 152, "usage_type": "call"}]} +{"seq_id": "36821887849", "text": "from fastapi import APIRouter , status , Response\nfrom typing import Optional\nfrom enum import Enum\n\nrouter = APIRouter(\n prefix='/blog',\n tags=['Blogs']\n)\n\n@router.get('/all')\ndef get_all_blogs(page =1, page_size:Optional[int]=None):\n return {'message':f'all {page_size} blog belongs to page {page} !'}\n\n\n@router.get('/{id}/comment_id/{comment_id}')\ndef get_comment(id : int, comment_id : int, valid:bool = True, username:Optional[str]=None):\n return {'message':f' blog_id {id} , comment_id {comment_id} , valid {valid} , username {username}'}\n\n\n@router.get('/{id}', status_code=status.HTTP_200_OK)\ndef get_blogs_data(id:int , response:Response):\n if id > 5 :\n response.status_code = status.HTTP_404_NOT_FOUND\n return {'error' : f'blog {id} not found'}\n else:\n response.status_code = status.HTTP_200_OK\n return {'message':f'blog with id {id} !'}\n\n\n\n@router.get('/all',tags=['Comments'])\ndef get_all_blogs_2():\n \"\"\"\n Simulate retriving the blog\n - **id** mandatory path peremeter\n - **comment_id** mandatory path peremeter\n \"\"\"\n return {'message':'all blogs provided !'}", "repo_name": "lucklaksh/project", "sub_path": "router/blog_get.py", "file_name": "blog_get.py", "file_ext": "py", "file_size_in_byte": 1134, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "fastapi.APIRouter", "line_number": 5, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 11, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 16, "usage_type": "name"}, {"api_name": "fastapi.Response", "line_number": 21, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_404_NOT_FOUND", "line_number": 23, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 23, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 26, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 26, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 20, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 20, "usage_type": "name"}]} +{"seq_id": "2771892147", "text": "# -*- coding:utf-8 -*-\n\n'''\n1.寻找发http请求库`requests\n2.调用接口\n验证协议层,验证状态吗,验证功能层时间是否符合\n\n\n3.验证接口是否正确\n\n\n...'''\nimport requests\ndef get_listusers_text():\n url = 'https://reqres.in/api/users?page=2'\n\n rep = requests.get(url)\n assert 200 == rep.status_code#响应状态码\n assert 2==rep.json()['page']#测试返回值\n print(rep.url)#返回url\n print(rep.text)#返回的响应以文本显示\n print (rep.cookies) # 缓存\n print (rep.content)#二进制\n print ( rep.headers)#头信息\n print(rep.encoding)#编码\n\n\n assert 50>rep.elapsed.total_seconds()#测试响应时间\ndef post_createuser_text():\n url = 'https://reqres.in/api/users'\n data={\n \"name\": \"lindafang\",\n \"job\": \"leader\"\n }\n rep = requests.post(url,data=data)\n assert 201 == rep.status_code\n assert 'linda' in rep.json()['name']\n assert 50 > rep.elapsed.total_seconds()\ndef put_text():\n url = 'https://reqres.in/api/users/2'\n data = {\n \"name\": \"linda\",\n \"job\": \"zion resident\"\n}\n rep = requests.put(url, data=data)\n print(rep.status_code)\n assert 200 == rep.status_code\n assert 'linda' in rep.json()['name']\n assert 50 > rep.elapsed.total_seconds()\n\n\ndef patch_text():\n url = 'https://reqres.in//api/users/2'\n data = {\n \"name\": \"linda\",\n \"job\": \"zion resident\"\n}\n rep = requests.patch(url, data=data)\n assert 200 == rep.status_code\n assert 'linda' in rep.json()['name']\n assert 50 > rep.elapsed.total_seconds()\n\ndef del_text():\n url = 'https://reqres.in//api/users/2'\n\n rep = requests.delete(url)\n assert 201 == rep.status_code\n assert 50 > rep.elapsed.total_seconds()\ndef request_get_datadriven():\n url = \"https://reqres.in/api/users?page=2\"\n headers = {\"Referer\": \"https://reqres.in/\",\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36\"}\n\n # 这是一个将所有请求方法封装后的统一写法。\n rep=requests.request(method='get',url=url,headers=headers)\n print(rep.json())\n\nif __name__ == '__main__':\n get_listusers_text()\n\n\n", "repo_name": "Jwyszm/ceshi", "sub_path": "理论文件/8月份/t8_20.py", "file_name": "t8_20.py", "file_ext": "py", "file_size_in_byte": 2227, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "requests.get", "line_number": 17, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 35, "usage_type": "call"}, {"api_name": "requests.put", "line_number": 45, "usage_type": "call"}, {"api_name": "requests.patch", "line_number": 58, "usage_type": "call"}, {"api_name": "requests.delete", "line_number": 66, "usage_type": "call"}, {"api_name": "requests.request", "line_number": 75, "usage_type": "call"}]} +{"seq_id": "32519636387", "text": "import os\nimport datetime\nimport numpy as np\nfrom himawari_api.alias import PROTOCOLS, _satellites, _sectors, _channels\n\n\ndef _check_protocol(protocol):\n \"\"\"Check protocol validity.\"\"\"\n if protocol is not None:\n if not isinstance(protocol, str):\n raise TypeError(\"`protocol` must be a string.\")\n if protocol not in PROTOCOLS:\n raise ValueError(f\"Valid `protocol` are {PROTOCOLS}.\")\n if protocol == \"local\":\n protocol = \"file\" # for fsspec LocalFS compatibility\n return protocol\n\n\ndef _check_base_dir(base_dir):\n \"\"\"Check base_dir validity.\"\"\"\n if base_dir is not None:\n if not isinstance(base_dir, str):\n raise TypeError(\"`base_dir` must be a string.\")\n if not os.path.exists(base_dir):\n raise OSError(f\"`base_dir` {base_dir} does not exist.\")\n if not os.path.isdir(base_dir):\n raise OSError(f\"`base_dir` {base_dir} is not a directory.\")\n return base_dir\n\n\ndef _check_satellite(satellite):\n \"\"\"Check satellite validity.\"\"\"\n if not isinstance(satellite, str):\n raise TypeError(\"`satellite` must be a string.\")\n # Retrieve satellite key accounting for possible aliases\n satellite_key = None\n for key, possible_values in _satellites.items():\n if satellite.upper() in possible_values:\n satellite_key = key\n break\n if satellite_key is None:\n valid_satellite_key = list(_satellites.keys())\n raise ValueError(f\"Available satellite: {valid_satellite_key}\")\n return satellite_key\n\n\ndef _check_sector(sector, product=None): \n \"\"\"Check sector validity.\"\"\"\n from himawari_api.info import available_sectors \n \n if sector is None: \n raise ValueError(\"'sector' must be specified.\")\n\n if not isinstance(sector, str):\n raise TypeError(\"`sector` must be a string.\")\n # Retrieve sector key accounting for possible aliases\n sector_key = None\n for key, possible_values in _sectors.items():\n if sector.upper() in possible_values:\n sector_key = key\n break\n # Raise error if provided unvalid sector key\n if sector_key is None:\n valid_sector_keys = list(_sectors.keys())\n raise ValueError(f\"Available sectors: {valid_sector_keys}\")\n # Check the sector is valid for a given product (if specified)\n valid_sectors = available_sectors(product=product)\n if product is not None:\n if sector_key not in valid_sectors:\n raise ValueError(\n f\"Valid sectors for product {product} are {valid_sectors}.\"\n )\n return sector_key\n\n\ndef _check_product_level(product_level, product=None):\n \"\"\"Check product_level validity.\"\"\"\n from himawari_api.info import get_dict_product_level_products\n \n if not isinstance(product_level, str):\n raise TypeError(\"`product_level` must be a string.\")\n product_level = product_level.capitalize()\n if product_level not in [\"L1b\", \"L2\"]:\n raise ValueError(\"Available product levels are ['L1b', 'L2'].\")\n if product is not None:\n if product not in get_dict_product_level_products()[product_level]:\n raise ValueError(\n f\"`product_level` '{product_level}' does not include product '{product}'.\"\n )\n return product_level\n\n\ndef _check_product_levels(product_levels):\n \"\"\"Check product_levels validity.\"\"\"\n if isinstance(product_levels, str):\n product_levels = [product_levels]\n product_levels = [\n _check_product_level(product_level) for product_level in product_levels\n ]\n return product_levels\n\ndef _check_product(product, product_level=None):\n \"\"\"Check product validity.\"\"\"\n from himawari_api.info import available_products \n \n if not isinstance(product, str):\n raise TypeError(\"`product` must be a string.\")\n valid_products = available_products(product_levels=product_level)\n # Retrieve product by accounting for possible aliases (upper/lower case)\n product_key = None\n for possible_values in valid_products:\n if possible_values.upper() == product.upper():\n product_key = possible_values\n break\n if product_key is None:\n if product_level is None:\n raise ValueError(f\"Available products: {valid_products}\")\n else:\n product_level = \"\" if product_level is None else product_level\n raise ValueError(f\"Available {product_level} products: {valid_products}\")\n return product_key\n\n\ndef _check_time(time):\n \"\"\"Check time validity.\"\"\"\n if not isinstance(time, (datetime.datetime, datetime.date, np.datetime64, str)):\n raise TypeError(\n \"Specify time with datetime.datetime objects or a \"\n \"string of format 'YYYY-MM-DD hh:mm:ss'.\"\n )\n # If np.datetime, convert to datetime.datetime\n if isinstance(time, np.datetime64):\n time = time.astype('datetime64[s]').tolist()\n # If datetime.date, convert to datetime.datetime\n if not isinstance(time, (datetime.datetime, str)):\n time = datetime.datetime(time.year, time.month, time.day, 0, 0, 0)\n if isinstance(time, str):\n try:\n time = datetime.datetime.fromisoformat(time)\n except ValueError:\n raise ValueError(\"The time string must have format 'YYYY-MM-DD hh:mm:ss'\")\n \n # Set resolution to seconds\n time = time.replace(microsecond=0)\n \n # Round seconds to 00 / 30\n time = _correct_time_seconds(time)\n\n return time\n\n\ndef _correct_time_seconds(time):\n \"\"\"Round datetime seconds to 00 or 30\n \n If [0-15] --> 00 \n If [15-45] --> 30 \n If [45-59] --> 0 (and add 1 minute)\n \"\"\"\n if time.second > 45:\n time = time.replace(second = 0) \n time = time + datetime.timedelta(minutes=1)\n elif time.second > 15 and time.second < 45:\n time = time.replace(second = 30) \n elif time.second < 15:\n time = time.replace(second = 0) \n return time\n\n\ndef _check_start_end_time(start_time, end_time):\n \"\"\"Check start_time and end_time validity.\"\"\"\n # Format input\n start_time = _check_time(start_time)\n end_time = _check_time(end_time)\n \n # Check start_time and end_time are chronological\n if start_time > end_time:\n raise ValueError(\"Provide start_time occuring before of end_time\")\n \n # Check start_time and end_time are in the past\n if start_time > datetime.datetime.utcnow():\n raise ValueError(\"Provide a start_time occuring in the past.\")\n # if end_time > datetime.datetime.utcnow():\n # raise ValueError(\"Provide a end_time occuring in the past.\")\n return (start_time, end_time)\n\n\ndef _check_channel(channel):\n \"\"\"Check channel validity.\"\"\"\n if not isinstance(channel, str):\n raise TypeError(\"`channel` must be a string.\")\n # Check channel follow standard name\n channel = channel.upper()\n if channel in list(_channels.keys()):\n return channel\n # Retrieve channel key accounting for possible aliases\n else:\n channel_key = None\n for key, possible_values in _channels.items():\n if channel.upper() in possible_values:\n channel_key = key\n break\n if channel_key is None:\n valid_channels_key = list(_channels.keys())\n raise ValueError(f\"Available channels: {valid_channels_key}\")\n return channel_key\n\n\ndef _check_channels(channels=None):\n \"\"\"Check channels validity.\"\"\"\n if channels is None:\n return channels\n if isinstance(channels, str):\n channels = [channels]\n channels = [_check_channel(channel) for channel in channels]\n return channels\n\n\ndef _check_scene_abbr(scene_abbr, sector=None): \n \"\"\"Check AHI Japan, Target and Landmark sector scene_abbr validity.\"\"\"\n if scene_abbr is None:\n return scene_abbr\n if sector is not None:\n if sector == \"FLDK\": \n raise ValueError(\"`scene_abbr` must be specified only for Japan and Target sectors !\")\n if not isinstance(scene_abbr, (str, list)):\n raise TypeError(\"Specify `scene_abbr` as string or list.\")\n if isinstance(scene_abbr, str):\n scene_abbr = [scene_abbr]\n valid_scene_abbr = [\"R1\", \"R2\", \"R3\", \"R4\", \"R5\"]\n if not np.all(np.isin(scene_abbr, valid_scene_abbr)):\n raise ValueError(f\"Valid `scene_abbr` values are {valid_scene_abbr}.\")\n if sector is not None:\n if sector == \"Japan\": \n valid_scene_abbr = [\"R1\", \"R2\"]\n if not np.all(np.isin(scene_abbr, valid_scene_abbr)):\n raise ValueError(f\"Valid `scene_abbr` for Japan sector are {valid_scene_abbr}.\")\n if sector == \"Target\":\n valid_scene_abbr = [\"R3\"]\n not np.all(np.isin(scene_abbr, valid_scene_abbr))\n raise ValueError(f\"Valid `scene_abbr` for Target sector are {valid_scene_abbr}.\")\n if sector == \"Landmark\":\n valid_scene_abbr = [\"R4\", \"R5\"]\n not np.all(np.isin(scene_abbr, valid_scene_abbr))\n raise ValueError(f\"Valid `scene_abbr` for Landmark sector are {valid_scene_abbr}.\")\n \n return scene_abbr\n\n\ndef _check_filter_parameters(filter_parameters, sector): \n \"\"\"Check filter parameters validity.\n\n It ensures that channels and scene_abbr are valid lists (or None).\n \"\"\"\n if not isinstance(filter_parameters, dict):\n raise TypeError(\"filter_parameters must be a dictionary.\")\n channels = filter_parameters.get(\"channels\")\n scene_abbr = filter_parameters.get(\"scene_abbr\")\n if channels:\n filter_parameters[\"channels\"] = _check_channels(channels)\n if scene_abbr:\n filter_parameters[\"scene_abbr\"] = _check_scene_abbr(scene_abbr, sector=sector)\n return filter_parameters\n\n\ndef _check_group_by_key(group_by_key):\n \"\"\"Check group_by_key validity.\"\"\"\n from himawari_api.info import available_group_keys\n \n if not isinstance(group_by_key, (str, type(None))):\n raise TypeError(\"`group_by_key`must be a string or None.\")\n if group_by_key is not None:\n valid_group_by_key = available_group_keys()\n if group_by_key not in valid_group_by_key:\n raise ValueError(\n f\"{group_by_key} is not a valid group_by_key. \"\n f\"Valid group_by_key are {valid_group_by_key}.\"\n )\n return group_by_key\n\n\ndef _check_connection_type(connection_type, protocol):\n \"\"\"Check cloud bucket connection_type validity.\"\"\"\n if not isinstance(connection_type, (str, type(None))):\n raise TypeError(\"`connection_type` must be a string (or None).\")\n if protocol is None:\n connection_type = None\n if protocol in [\"file\", \"local\"]:\n connection_type = None # set default\n if protocol in [\"s3\"]:\n # Set default connection type\n if connection_type is None:\n connection_type = \"bucket\" # set default\n valid_connection_type = [\"bucket\", \"https\", \"nc_bytes\"]\n if connection_type not in valid_connection_type:\n raise ValueError(f\"Valid `connection_type` are {valid_connection_type}.\")\n return connection_type\n\n\ndef _check_interval_regularity(list_datetime):\n \"\"\"Check regularity of a list of timesteps.\"\"\"\n # TODO: raise info when missing between ... and ...\n if len(list_datetime) < 2:\n return None\n list_datetime = sorted(list_datetime)\n list_timedelta = np.diff(list_datetime)\n list_unique_timedelta = np.unique(list_timedelta)\n if len(list_unique_timedelta) != 1:\n raise ValueError(\"The time interval is not regular!\")\n", "repo_name": "ghiggi/himawari_api", "sub_path": "himawari_api/checks.py", "file_name": "checks.py", "file_ext": "py", "file_size_in_byte": 11661, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "26", "api": [{"api_name": "himawari_api.alias.PROTOCOLS", "line_number": 12, "usage_type": "name"}, {"api_name": "himawari_api.alias.PROTOCOLS", "line_number": 13, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "himawari_api.alias._satellites.items", "line_number": 37, "usage_type": "call"}, {"api_name": "himawari_api.alias._satellites", "line_number": 37, "usage_type": "name"}, {"api_name": "himawari_api.alias._satellites.keys", "line_number": 42, "usage_type": "call"}, {"api_name": "himawari_api.alias._satellites", "line_number": 42, "usage_type": "name"}, {"api_name": "himawari_api.alias._sectors.items", "line_number": 58, "usage_type": "call"}, {"api_name": "himawari_api.alias._sectors", "line_number": 58, "usage_type": "name"}, {"api_name": "himawari_api.alias._sectors.keys", "line_number": 64, "usage_type": "call"}, {"api_name": "himawari_api.alias._sectors", "line_number": 64, "usage_type": "name"}, {"api_name": "himawari_api.info.available_sectors", "line_number": 67, "usage_type": "call"}, {"api_name": "himawari_api.info.get_dict_product_level_products", "line_number": 86, "usage_type": "call"}, {"api_name": "himawari_api.info.available_products", "line_number": 108, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 126, "usage_type": "attribute"}, {"api_name": "datetime.date", "line_number": 126, "usage_type": "attribute"}, {"api_name": "numpy.datetime64", "line_number": 126, "usage_type": "attribute"}, {"api_name": "numpy.datetime64", "line_number": 132, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 135, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 136, "usage_type": "call"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 139, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 139, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 161, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 180, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 180, "usage_type": "attribute"}, {"api_name": "himawari_api.alias._channels.keys", "line_number": 193, "usage_type": "call"}, {"api_name": "himawari_api.alias._channels", "line_number": 193, "usage_type": "name"}, {"api_name": "himawari_api.alias._channels.items", "line_number": 198, "usage_type": "call"}, {"api_name": "himawari_api.alias._channels", "line_number": 198, "usage_type": "name"}, {"api_name": "himawari_api.alias._channels.keys", "line_number": 203, "usage_type": "call"}, {"api_name": "himawari_api.alias._channels", "line_number": 203, "usage_type": "name"}, {"api_name": "numpy.all", "line_number": 230, "usage_type": "call"}, {"api_name": "numpy.isin", "line_number": 230, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 235, "usage_type": "call"}, {"api_name": "numpy.isin", "line_number": 235, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 239, "usage_type": "call"}, {"api_name": "numpy.isin", "line_number": 239, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 243, "usage_type": "call"}, {"api_name": "numpy.isin", "line_number": 243, "usage_type": "call"}, {"api_name": "himawari_api.info.available_group_keys", "line_number": 272, "usage_type": "call"}, {"api_name": "numpy.diff", "line_number": 305, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 306, "usage_type": "call"}]} +{"seq_id": "42563671491", "text": "from tkinter import Label, Menubutton, Tk, Scrollbar\nfrom tkinter import *\nimport array\nimport tkinter.messagebox\nfrom datetime import *\nimport calendar\nimport sqlite3\nimport datetime\nfrom datetime import date\nfrom capability6 import room\nfrom c3 import reservationSystem\n\n\ndef RoomAvailibity():\n currentDate= datetime.datetime.now()\n currentDay= date.today()#current date for schedule\n nextDay1=date.today() + datetime.timedelta(days=1)\n nextDay2=date.today() + datetime.timedelta(days=2)\n nextDay3=date.today() + datetime.timedelta(days=3)\n nextDay4=date.today() + datetime.timedelta(days=4)\n nextDay5=date.today() + datetime.timedelta(days=5)\n nextDay6=date.today() + datetime.timedelta(days=6)\n nextDay7=date.today() + datetime.timedelta(days=7)\n\n year = currentDate.year\n day= currentDate.day\n month= currentDate.month\n\n # root=Tk()\n # root.title(\"Key\")\n # root.geometry(\"200x200+1000+100\")\n c2window= Tk()\n c2window.title(\"Available rooms\")\n c2window.geometry(\"1000x600+10+100\")\n conn = sqlite3.connect('hotel.db')\n cur = conn.cursor()\n sql = ' SELECT * FROM Room'\n cur.execute(sql)\n getAll = cur.fetchall()\n print(getAll[0])\n\n def checkIn(h):\n c2window.destroy()\n room(h)\n \n \n a=99\n\n for row in range (22):\n\n for column in range (9):\n\n if row == 0 : #day of the week\n lable0= Label(c2window, text=\"Room Number\",bg=\"black\",fg=\"white\",padx= 3,pady=3)\n lable0.grid(row=0, column=0,sticky= \"nsew\",padx= 1,pady=1)\n lable3 = Label(c2window, text=currentDay.strftime('%A'),bg=\"black\",fg=\"white\",padx= 3,pady=3 )\n lable3.grid(row=0, column=1,sticky= \"nsew\",padx= 1,pady=1)\n lable4 = Label(c2window, text=nextDay1.strftime('%A'),bg=\"black\",fg=\"white\",padx= 3,pady=3 )\n lable4.grid(row=0, column=2,sticky= \"nsew\",padx= 1,pady=1)\n lable3 = Label(c2window, text=nextDay2.strftime('%A'),bg=\"black\",fg=\"white\",padx= 3,pady=3 )\n lable3.grid(row=0, column=3,sticky= \"nsew\",padx= 1,pady=1)\n lable3 = Label(c2window, text=nextDay3.strftime('%A'),bg=\"black\",fg=\"white\",padx= 3,pady=3 )\n lable3.grid(row=0, column=4,sticky= \"nsew\",padx= 1,pady=1)\n lable3 = Label(c2window, text=nextDay4.strftime('%A'),bg=\"black\",fg=\"white\",padx= 3,pady=3 )\n lable3.grid(row=0, column=5,sticky= \"nsew\",padx= 1,pady=1)\n lable3 = Label(c2window, text=nextDay5.strftime('%A'),bg=\"black\",fg=\"white\",padx= 3,pady=3 )\n lable3.grid(row=0, column=6,sticky= \"nsew\",padx= 1,pady=1)\n lable3 = Label(c2window, text=nextDay6.strftime('%A'),bg=\"black\",fg=\"white\",padx= 3,pady=3 )\n lable3.grid(row=0, column=7,sticky= \"nsew\",padx= 1,pady=1)\n lable3 = Label(c2window, text=nextDay7.strftime('%A'),bg=\"black\",fg=\"white\",padx= 3,pady=3 )\n lable3.grid(row=0, column=8,sticky= \"nsew\",padx= 1,pady=1)\n elif row == 1:#date\n lable2= Label(c2window, text=str(currentDay.month) +\"/\" + str(currentDay.day))\n lable2.grid(row= 1, column= 1,sticky= \"nsew\",padx= 1,pady=1)\n lable2= Label(c2window, text=str(nextDay1.month) +\"/\" + str(nextDay1.day))\n lable2.grid(row= 1, column= 2,sticky= \"nsew\",padx= 1,pady=1)\n lable2= Label(c2window, text=str(nextDay2.month) +\"/\" + str(nextDay2.day))\n lable2.grid(row= 1, column= 3,sticky= \"nsew\",padx= 1,pady=1)\n lable2= Label(c2window, text=str(nextDay3.month) +\"/\" + str(nextDay3.day))\n lable2.grid(row= 1, column= 4,sticky= \"nsew\",padx= 1,pady=1)\n lable2= Label(c2window, text=str(nextDay4.month) +\"/\" + str(nextDay4.day))\n lable2.grid(row= 1, column= 5,sticky= \"nsew\",padx= 1,pady=1)\n lable2= Label(c2window, text=str(nextDay5.month) +\"/\" + str(nextDay5.day))\n lable2.grid(row= 1, column= 6,sticky= \"nsew\",padx= 1,pady=1)\n lable2= Label(c2window,text=str(nextDay6.month) +\"/\" + str(nextDay6.day))\n lable2.grid(row= 1, column= 7,sticky= \"nsew\",padx= 1,pady=1)\n lable2= Label(c2window,text=str(nextDay7.month) +\"/\" + str(nextDay7.day))\n lable2.grid(row= 1, column= 8,sticky= \"nsew\",padx= 1,pady=1)\n \n\n elif column==0:\n a+=1\n label= Label(c2window, text=a)\n label.grid (row=row, column =column,sticky= \"nsew\",padx= 1,pady=1)\n else:\n \n label6 = Menubutton(c2window,text=\"Available\")\n label6.grid(row=row, column= column,sticky= \"nsew\",padx= 1,pady=1)\n c2window.grid_columnconfigure(column, weight= 1, uniform =1)\n label6.menu= Menu (label6)\n label6[\"menu\"]= label6.menu\n if column==1:\n label6.menu.add_command (label = \"check In\",command=lambda roomNumber= a :checkIn(roomNumber))\n else:\n label6.menu.add_command (label = \"Reservation\",command=lambda roomNumber= a : reservationSystem())\n # lambda h = h ,row= row, column=column, l= label : availableRoom(row,column,h,l))\n # label.menu.add_command (label = \"Reservation\", command=lambda h= h, row= row, column=column, l= label : occupiedRoom(row,column,h,l))\n\n def loadCheckin():\n conn = sqlite3.connect('hotel.db')\n cur = conn.cursor()\n sql = ' SELECT * FROM Room WHERE CheckIN = '+str(1)\n cur.execute(sql)\n result = cur.fetchall()\n def loadrooms(row,column,first_name):\n widget= c2window.grid_slaves(row=row, column=column)[0]\n widget.configure(bg=\"blue\",fg=\"white\",text=first_name)\n\n for row in result:\n if row[2] == 'Unavailable/Occupied':\n cur = conn.cursor()\n # sql = 'SELECT first_name, last_name FROM guests WHERE guest_id=' + str(row[6])\n # sql= 'SELECT CheckInDate , CheckOutDate from Room UNION ALL SELECT first_name, last_name from guests WHERE guest_id=' +str(row[6])\n sql= 'SELECT RoomNumber,first_name, last_name, CheckInDate, CheckOutDate from guests INNER JOIN Room on Room.guestID = guests.guest_id'\n cur.execute(sql)\n guest = cur.fetchall()\n\n for row in guest:\n print(row)\n year1, month1, day1 = map(int, row[4].split('/'))\n d= date(year1,month1,day1)\n year, month, day = map(int, row[3].split('/'))\n c=date(year, month, day)\n days=(d-c).days\n cur = conn.cursor()\n # sql = 'SELECT first_name, last_name FROM guests WHERE guest_id=' + str(row[6])\n # sql= 'SELECT CheckInDate , CheckOutDate from Room UNION ALL SELECT first_name, last_name from guests WHERE guest_id=' +str(row[6])\n sql= 'SELECT RowX, ColumnY FROM RoomAvailability WHERE RoomNumber ='+ row[0]\n cur.execute(sql)\n roomHere = cur.fetchall()\n print(days)\n if days==0:\n loadrooms(roomHere[0][0],roomHere[0][1],row[1])\n elif days==1:\n loadrooms(roomHere[0][0],roomHere[0][1],row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+1,row[1])\n \n elif days==2:\n loadrooms(roomHere[0][0],roomHere[0][1],row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+1,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+2,row[1])\n elif days==3:\n loadrooms(roomHere[0][0],roomHere[0][1],row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+1,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+2,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+3,row[1])\n elif days==4:\n loadrooms(roomHere[0][0],roomHere[0][1],row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+1,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+2,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+3,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+4,row[1])\n elif days==5:\n loadrooms(roomHere[0][0],roomHere[0][1],row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+1,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+2,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+3,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+4,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+5,row[1])\n elif days==6:\n loadrooms(roomHere[0][0],roomHere[0][1],row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+1,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+2,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+3,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+4,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+5,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+6,row[1])\n elif days==7:\n loadrooms(roomHere[0][0],roomHere[0][1],row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+1,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+2,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+3,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+4,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+5,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+6,row[1])\n loadrooms(roomHere[0][0],roomHere[0][1]+7,row[1])\n loadCheckin() \n \n", "repo_name": "cowbinn/Antares-Hotel-DBMS", "sub_path": "Room.py", "file_name": "Room.py", "file_ext": "py", "file_size_in_byte": 9840, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "datetime.datetime.now", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 15, "usage_type": "attribute"}, {"api_name": "datetime.date.today", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 16, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 17, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 17, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 17, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 18, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 19, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 20, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 20, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 20, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 21, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 21, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 21, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 22, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 22, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 22, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 23, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 23, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 32, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 35, "usage_type": "call"}, {"api_name": "capability6.room", "line_number": 44, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 54, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 56, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 58, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 60, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 62, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 64, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 66, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 68, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 70, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 73, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 75, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 77, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 79, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 81, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 83, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 85, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 87, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 93, "usage_type": "call"}, {"api_name": "tkinter.Menubutton", "line_number": 97, "usage_type": "call"}, {"api_name": "c3.reservationSystem", "line_number": 105, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 110, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 131, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 133, "usage_type": "call"}]} +{"seq_id": "24340677983", "text": "import sqlite3 as sql\n\nfrom mysql.connector import OperationalError\n\n\ndef googleMaxIdGetir():\n\ttry:\n\t\tvt = sql.connect('/home/celal/.config/google-chrome/Default/History-yedek',timeout=1)\n\t\tim = vt.cursor()\n\t\tim.execute(\"\"\"select max(id) from visits \"\"\")\n\t\tfor i in im:\n\t\t\treturn i[0]\n\texcept Exception:\n\t\tpass\ndef googleGetirById(i):\n\tvt = sql.connect('/home/celal/.config/google-chrome/Default/History-yedek',timeout=1)\n\tim = vt.cursor()\n\tim.execute('select m.url,h.visit_time from visits h inner join urls m on h.url=m.id WHERE h.id=?',(int(i),))\n\tliste = []\n\tliste.clear()\n\tfor (url,visit_date) in im:\n\t\tliste.append(url)\n\t\tliste.append(visit_date)\n\treturn liste", "repo_name": "sistem-progamlama/browser-history-phyton", "sub_path": "browser-history/GoogleDatabaseController.py", "file_name": "GoogleDatabaseController.py", "file_ext": "py", "file_size_in_byte": 666, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "20", "api": [{"api_name": "sqlite3.connect", "line_number": 8, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 16, "usage_type": "call"}]} +{"seq_id": "1182710084", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import models, transforms\nfrom collections import OrderedDict\n\nclass HierarchyCNN(nn.Module):\n def __init__(self, backbone='vgg', use_pretrained=True):\n super(HierarchyCNN, self).__init__()\n self.backbone = backbone\n if self.backbone == 'vgg':\n # coarse\n self.coarse_backbone, self.coarse_avgpool, self.coarse_classifier = self._make_vgg_backbone('coarse', use_pretrained)\n # fine\n self.fine_backbone, self.fine_avgpool, self.fine_classifier = self._make_vgg_backbone('fine', use_pretrained)\n \n self.fine_11conv = nn.Conv2d(1024, 512, (1, 1))\n elif self.backbone == 'wide_resnet_50':\n # coarse\n self.coarse_backbone, self.coarse_avgpool, self.coarse_classifier = self._make_wrs_backbone('coarse', use_pretrained)\n # fine\n self.fine_backbone, self.fine_avgpool, self.fine_classifier = self._make_wrs_backbone('fine', use_pretrained)\n self.fine_11conv = nn.Conv2d(3072, 2048, (1, 1))\n # self.fine_11conv = nn.Conv2d(4096, 2048, (1, 1)) # exp2\n \n \n def _make_wrs_backbone(self, type_, use_pretrained):\n wrn50 = models.wide_resnet50_2(pretrained = use_pretrained)\n \n if type_ == 'coarse':\n wrn50_backbone = nn.Sequential(OrderedDict(list(wrn50._modules.items())[:-3]))\n classifier = nn.Linear(in_features=1024, out_features=20)\n \n # wrn50_backbone = nn.Sequential(OrderedDict(list(wrn50._modules.items())[:-2])) # exp2 \n # classifier = nn.Linear(in_features=2048, out_features=20) # exp2\n \n elif type_ == 'fine':\n wrn50_backbone = nn.Sequential(OrderedDict(list(wrn50._modules.items())[:-2]))\n classifier = nn.Linear(in_features=2048, out_features=100)\n \n if use_pretrained:\n wrn50_backbone.requires_grad = False\n \n if type_ == 'coarse':\n for layer_name, layer_ in wrn50_backbone.named_parameters(): # exp1\n if 'layer3' in layer_name :\n layer_.requires_grad = True\n else :\n layer_.requires_grad = False\n else :\n wrn50_backbone.requires_grad = False\n \n # if type_ == 'coarse':\n # for module_name, modules in wrn50_backbone.named_children(): # exp2\n # if module_name == 'layer4':\n # modules.requires_grad = True\n # else :\n # modules.requires_grad = False\n # else :\n # wrn50_backbone.requires_grad = False\n \n avg_pool = nn.AdaptiveAvgPool2d((1, 1))\n classifier = classifier.apply(self._init_weight)\n \n return wrn50_backbone, avg_pool, classifier\n \n def _make_vgg_backbone(self, type_, use_pretrained):\n if type_ == 'coarse':\n vgg = models.vgg13_bn(pretrained = use_pretrained)\n num_classes = 20\n\n elif type_ == 'fine':\n vgg = models.vgg16_bn(pretrained = use_pretrained)\n num_classes = 100\n \n backbone = vgg.features\n if use_pretrained:\n backbone.requires_grad = False\n avg_pool = vgg.avgpool\n classifier = nn.Sequential(\n nn.Linear(25088, 4096),\n nn.ReLU(inplace=True),\n nn.Dropout(0.5),\n nn.Linear(4096, 4096),\n nn.ReLU(inplace=True),\n nn.Dropout(0.5),\n nn.Linear(4096, num_classes)\n )\n classifier = classifier.apply(self._init_weight)\n \n return backbone, avg_pool, classifier\n\n def _init_weight(self, layer):\n if isinstance(layer, nn.Linear):\n torch.nn.init.kaiming_normal_(layer.weight)\n torch.nn.init.zeros_(layer.bias)\n \n def forward(self, x, only_fine=False):\n \n if only_fine:\n fine_out = self.fine_backbone(x)\n fine_out = self.fine_avgpool(fine_out)\n fine_out = torch.flatten(fine_out, 1)\n fine_out = self.fine_classifier(fine_out)\n \n return fine_out\n \n else :\n # coarse\n coarse_out = self.coarse_backbone(x)\n coarse_cat = coarse_out.clone().detach()\n coarse_out = self.coarse_avgpool(coarse_out)\n coarse_out = torch.flatten(coarse_out, 1)\n coarse_out = self.coarse_classifier(coarse_out)\n \n # fine\n fine_out = self.fine_backbone(x)\n if self.backbone == 'wide_resnet_50':\n coarse_cat = F.max_pool2d(coarse_cat, (3,3), 2, 1) # exp2\n fine_out = torch.cat((fine_out, coarse_cat), dim=1)\n fine_out = self.fine_11conv(fine_out)\n fine_out = self.fine_avgpool(fine_out)\n fine_out = torch.flatten(fine_out, 1)\n fine_out = self.fine_classifier(fine_out)\n \n return coarse_out, fine_out", "repo_name": "ljh415/Hierarchical_CNN", "sub_path": "model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 5215, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "torch.nn.Module", "line_number": 7, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 7, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 17, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 17, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torchvision.models.wide_resnet50_2", "line_number": 28, "usage_type": "call"}, {"api_name": "torchvision.models", "line_number": 28, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 31, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 38, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 39, "usage_type": "name"}, {"api_name": "torch.nn.AdaptiveAvgPool2d", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 62, "usage_type": "name"}, {"api_name": "torchvision.models.vgg13_bn", "line_number": 69, "usage_type": "call"}, {"api_name": "torchvision.models", "line_number": 69, "usage_type": "name"}, {"api_name": "torchvision.models.vgg16_bn", "line_number": 73, "usage_type": "call"}, {"api_name": "torchvision.models", "line_number": 73, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 80, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 81, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 81, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 82, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 82, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 83, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 83, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 84, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 85, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 85, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 86, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 86, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 87, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 94, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 94, "usage_type": "name"}, {"api_name": "torch.nn.init.kaiming_normal_", "line_number": 95, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 95, "usage_type": "attribute"}, {"api_name": "torch.nn.init.zeros_", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 96, "usage_type": "attribute"}, {"api_name": "torch.flatten", "line_number": 103, "usage_type": "call"}, {"api_name": "torch.flatten", "line_number": 113, "usage_type": "call"}, {"api_name": "torch.nn.functional.max_pool2d", "line_number": 119, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 119, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 120, "usage_type": "call"}, {"api_name": "torch.flatten", "line_number": 123, "usage_type": "call"}]} +{"seq_id": "73266254769", "text": "import discord\r\nimport random\r\nfrom discord.ext import commands\r\n\r\nintents = discord.Intents(messages = True, guilds = True, reactions = True, members = True, presences = True)\r\nclient = commands.Bot(command_prefix = '.', intents = intents)\r\n\r\n@client.event\r\nasync def on_ready():\r\n print('Bot is ready.')\r\n\r\n@client.event\r\nasync def on_message(message):\r\n ctx = await client.get_context(message)\r\n\r\n #replace user discriminator below as a string\r\n discriminator = 'USER DISCRIMINATOR'\r\n message_author = message.author\r\n #The program only works for small discord servers in which everyone has a distinct discriminator\r\n\r\n #end the function if the users do not match\r\n if message_author.discriminator != discriminator:\r\n return\r\n\r\n #replace the user's message with a message from the bot\r\n text = message.content\r\n await ctx.channel.purge(limit = 1)\r\n await ctx.send(text)\r\n\r\n#replace bot token below as a string\r\nclient.run('BOT TOKEN')\r\n", "repo_name": "siddharthnandy/FakeUser", "sub_path": "FakeUser.py", "file_name": "FakeUser.py", "file_ext": "py", "file_size_in_byte": 982, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "discord.Intents", "line_number": 5, "usage_type": "call"}, {"api_name": "discord.ext.commands.Bot", "line_number": 6, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 6, "usage_type": "name"}]} +{"seq_id": "3780300342", "text": "import json\nimport pymongo\nfrom settings import *\nfrom logger import logger\n\ndef seeder():\n s_list = json.load(open('data.json', 'r'))['school']\n client = pymongo.MongoClient(\"mongodb://{}:{}@{}:{}\".format(\n DB_USER,\n DB_PASSWORD,\n DB_HOST,\n DB_PORT\n ))\n\n db = client[DB_NAME]\n s_col = db['school']\n\n logger.info('start insert school data')\n\n for data in s_list:\n if not s_col.count_documents({'e_name': data['e_name']}):\n logger.info('insert school {}'.format(data['e_name']))\n s_col.insert_one(data)\n else:\n logger.info('update school {}'.format(data['e_name']))\n s_col.update_one({'e_name': data['e_name']}, {'$set': data})\n\n logger.info('end insert school')\n\nif __name__ == \"__main__\":\n seeder()\n", "repo_name": "arasHi87/SCISTBot", "sub_path": "seed.py", "file_name": "seed.py", "file_ext": "py", "file_size_in_byte": 813, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "json.load", "line_number": 7, "usage_type": "call"}, {"api_name": "pymongo.MongoClient", "line_number": 8, "usage_type": "call"}, {"api_name": "logger.logger.info", "line_number": 18, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 18, "usage_type": "name"}, {"api_name": "logger.logger.info", "line_number": 22, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 22, "usage_type": "name"}, {"api_name": "logger.logger.info", "line_number": 25, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 25, "usage_type": "name"}, {"api_name": "logger.logger.info", "line_number": 28, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 28, "usage_type": "name"}]} +{"seq_id": "29736387407", "text": "# -*- coding:utf-8 -*-\r\nimport random\r\n\r\nimport requests\r\nimport json\r\nimport time\r\n\r\n\"\"\"\r\n爬取小鸡词典,自定义搜索内容\r\napi搜索目标网址:https://api.jikipedia.com/go/search_definitions\r\n@:param post请求\r\n@:param Request Payload数据格式\r\n\"\"\"\r\nheaders = {\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36\",\r\n \"Origin\": \"https://jikipedia.com/\",\r\n \"XID\": \"xAYJ+2jp7sHGhXQIUdWjzqoLootZvsez9tyRVfeecfyKrjMz98w1vsYWAgAiIh9Eh/aPHRldSRnnGS+vrGSuxXgsagL4yi/Sp2f35tEI0x4=\",\r\n \"Content-Type\": \"application/json;charset=UTF-8\",\r\n \"Host\": \"api.jikipedia.com\"\r\n}\r\nurl = \"https://api.jikipedia.com/go/search_definitions\"\r\n\r\n\r\ndef get_info(keyWord, pages):\r\n try:\r\n for page in range(1, pages + 1):\r\n params = {\r\n # 搜索关键字\r\n \"phrase\": keyWord,\r\n # 查询页数\r\n \"page\": page\r\n }\r\n print(\"\\033[1;31;40m正在打印第%d页数据...\\033[0m\" % page)\r\n # 发送post请求\r\n response = requests.post(url=url, headers=headers, data=json.dumps(params), timeout=10)\r\n if response.status_code == 200:\r\n result = response.json()\r\n \"\"\"\r\n 通过放回的json数据,可以猜测到利用的是sql分页查询语句:\r\n select * from table_name \r\n limit page,size \r\n \"\"\"\r\n print(\"目标搜索总数目:\", result[\"total\"])\r\n print(\"本页搜索总数目:\", result[\"size\"])\r\n print(\"起始索引:\", result[\"from\"])\r\n print(\"���止索引:\", result[\"to\"])\r\n print(\"当前页数:\", result[\"current_page\"])\r\n print(\"总页数:\", result[\"last_page\"])\r\n # 循环打印当前页面的内容\r\n for i in result[\"data\"]:\r\n print(\"===============\")\r\n print(\"标题:\", i[\"term\"][\"title\"])\r\n print(\"内容详情:\", i[\"content\"])\r\n time.sleep(random.randint(1,4))\r\n print(\"\\033[1;32;40m===========================\\033[0m\")\r\n print(\"\")\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\nif __name__ == '__main__':\r\n kw = input(\"请输入查询关键词:药水哥~~\").strip()\r\n number = int(input(\"请输入查询页数:\"))\r\n get_info(kw, number)\r\n", "repo_name": "FioraLove/Net-Spider", "sub_path": "小鸡词典/xiaojiDocument.py", "file_name": "xiaojiDocument.py", "file_ext": "py", "file_size_in_byte": 2505, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 692, "dataset": "github-code", "pt": "20", "api": [{"api_name": "requests.post", "line_number": 35, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 35, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 54, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 54, "usage_type": "call"}]} +{"seq_id": "30242664323", "text": "\"\"\"Just a demo of the new PyVLX module.\"\"\"\nimport asyncio\nimport logging\n\nfrom pyvlx import PYVLXLOG, PyVLX\n\n\nasync def main(loop):\n \"\"\"Log packets from Bus.\"\"\"\n # Setting debug\n PYVLXLOG.setLevel(logging.DEBUG)\n stream_handler = logging.StreamHandler()\n stream_handler.setLevel(logging.DEBUG)\n PYVLXLOG.addHandler(stream_handler)\n\n # Connecting to KLF 200\n pyvlx = PyVLX('pyvlx.yaml', loop=loop)\n await pyvlx.load_scenes()\n await pyvlx.load_nodes()\n\n # and wait, increase this timeout if you want to\n # log for a longer time.:)\n await asyncio.sleep(90)\n\n # Cleanup, KLF 200 is terrible in handling lost connections\n await pyvlx.disconnect()\n\n\nif __name__ == '__main__':\n # pylint: disable=invalid-name\n LOOP = asyncio.get_event_loop()\n LOOP.run_until_complete(main(LOOP))\n LOOP.close()\n", "repo_name": "Julius2342/pyvlx", "sub_path": "examples/monitor.py", "file_name": "monitor.py", "file_ext": "py", "file_size_in_byte": 844, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 68, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pyvlx.PYVLXLOG.setLevel", "line_number": 11, "usage_type": "call"}, {"api_name": "pyvlx.PYVLXLOG", "line_number": 11, "usage_type": "name"}, {"api_name": "logging.DEBUG", "line_number": 11, "usage_type": "attribute"}, {"api_name": "logging.StreamHandler", "line_number": 12, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 13, "usage_type": "attribute"}, {"api_name": "pyvlx.PYVLXLOG.addHandler", "line_number": 14, "usage_type": "call"}, {"api_name": "pyvlx.PYVLXLOG", "line_number": 14, "usage_type": "name"}, {"api_name": "pyvlx.PyVLX", "line_number": 17, "usage_type": "call"}, {"api_name": "pyvlx.load_scenes", "line_number": 18, "usage_type": "call"}, {"api_name": "pyvlx.load_nodes", "line_number": 19, "usage_type": "call"}, {"api_name": "asyncio.sleep", "line_number": 23, "usage_type": "call"}, {"api_name": "pyvlx.disconnect", "line_number": 26, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "22472074869", "text": "import json, time\r\nimport paho.mqtt.client as mqtt\r\nimport RPi.GPIO as GPIO\r\n\r\ng_buzzer_event = 0x00\r\n\r\nSET_BUZZER = 0x01\r\n\r\ng_set_buzzer_val = 0\r\n\r\n#---SET Pin-------------------------------------------------------------\r\nBuzzer_pin = 11 # Direct Connect\r\n\r\nGPIO.setmode(GPIO.BCM)\r\nGPIO.setup(Buzzer_pin, GPIO.OUT)\r\n#-----------------------------------------------------------------------\r\n\r\n#---Buzzer--------------------------------------------------------------\r\ndef buzzer(val):\r\n\tfreq = [1936, 2094, 1760]#[988, 1047, 880]\r\n \r\n\ttry:\r\n\t\t# print(Buzzer_pin)\r\n\t\tp = GPIO.PWM(Buzzer_pin, 600) \r\n\t\tp.start(50)\r\n\r\n\t\tfor i in range(len(freq)):\r\n\t\t\tp.ChangeFrequency(freq[i])\r\n\t\t\ttime.sleep(0.23)\r\n\t\t\t\r\n\t\tp.stop()\r\n\t\ttime.sleep(0.4)\r\n\t\tp.start(50)\r\n\t\r\n\t\tfor i in range(len(freq)):\r\n\t\t\tp.ChangeFrequency(freq[i])\r\n\t\t\ttime.sleep(0.23)\r\n\r\n\t\tp.stop()\r\n\r\n\texcept KeyboardInterrupt:\r\n\t\tGPIO.cleanup()\r\n#-----------------------------------------------------------------------\r\n\r\n#---Parse Data----------------------------------------------------------\r\ndef json_to_val(json_val):\r\n\tpayloadData = json.loads(json_val)\r\n\r\n\tif (len(payloadData) == 1):\r\n\t\tval = payloadData['val']\r\n\t\treturn (val)\r\n\telif (len(payloadData) == 2):\r\n\t\tval = payloadData['val']\r\n\t\tval2 = payloadData['val2']\r\n\t\treturn (val, val2)\r\n\telif (len(payloadData) == 3):\r\n\t\tval = payloadData['val']\r\n\t\tval2 = payloadData['val2']\r\n\t\tval3 = payloadData['val3']\r\n\t\treturn (val, val2, val3)\t\r\n\r\ndef val_to_json(val,val2=None):\r\n\tif (val2 != None):\r\n\t\tjson_val = {\"val\":val,\"val2\":val2}\r\n\telse:\r\n\t\tjson_val = {\"val\":val}\r\n\tjson_val = json.dumps(json_val)\r\n\t\r\n\treturn (json_val)\r\n\t\r\n#---MQTT----------------------------------------------------------------\r\n\r\ndef on_connect(client,userdata,flags, rc):\r\n\tprint('[dry_mqtt_connect] connect to ', broker_address)\r\n\r\n\r\ndef on_disconnect(client, userdata, flags, rc=0):\r\n\tprint(str(rc))\r\n\r\n\r\ndef on_subscribe(client, userdata, mid, granted_qos):\r\n\tprint(\"subscribed: \" + str(mid) + \" \" + str(granted_qos))\r\n\r\n\r\ndef on_message(client, userdata, _msg):\r\n\tglobal g_buzzer_event\r\n\tglobal g_set_buzzer_val\r\n\r\n\tif _msg.topic == '/set_buzzer':\r\n# \t\tbuzzer_running = 1\r\n\t\tdata = _msg.payload.decode('utf-8').replace(\"'\", '\"')\r\n\t\tg_set_buzzer_val = json_to_val(data)\r\n\t\tg_buzzer_event |= SET_BUZZER\r\n\r\n#\tfunc_set_q(_msg)\r\n#-----------------------------------------------------------------------\r\n\r\n#=======================================================================\r\nglobal dry_client\r\nbroker_address = \"localhost\"\r\nport = 1883\r\n\r\ndry_client = mqtt.Client()\r\ndry_client.on_connect = on_connect\r\ndry_client.on_disconnect = on_disconnect\r\ndry_client.on_subscribe = on_subscribe\r\ndry_client.on_message = on_message\r\ndry_client.connect(broker_address, port)\r\n\r\ndry_client.subscribe(\"/set_buzzer\")\r\n\r\ndry_client.loop_start()\r\n\r\ndef core_func():\r\n\tglobal g_buzzer_event\r\n\tglobal g_set_buzzer_val\r\n\r\n\twhile True:\r\n\t\tif g_buzzer_event & SET_BUZZER:\r\n\t\t\tg_buzzer_event &= (~SET_BUZZER)\r\n\t\t\tbuzzer(g_set_buzzer_val)\r\n\r\nif __name__ == \"__main__\":\r\n\tprint(\"Start exec_buzzer.py...\")\r\n\tcore_func()\r\n", "repo_name": "dnjstjr93/nCube-dry-100", "sub_path": "exec_buzzer.py", "file_name": "exec_buzzer.py", "file_ext": "py", "file_size_in_byte": 3082, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "RPi.GPIO.setmode", "line_number": 14, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 14, "usage_type": "name"}, {"api_name": "RPi.GPIO.BCM", "line_number": 14, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.setup", "line_number": 15, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 15, "usage_type": "name"}, {"api_name": "RPi.GPIO.OUT", "line_number": 15, "usage_type": "attribute"}, {"api_name": "RPi.GPIO.PWM", "line_number": 24, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 24, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 29, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 32, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 37, "usage_type": "call"}, {"api_name": "RPi.GPIO.cleanup", "line_number": 42, "usage_type": "call"}, {"api_name": "RPi.GPIO", "line_number": 42, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 47, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 67, "usage_type": "call"}, {"api_name": "paho.mqtt.client.Client", "line_number": 103, "usage_type": "call"}, {"api_name": "paho.mqtt.client", "line_number": 103, "usage_type": "name"}]} +{"seq_id": "38397350999", "text": "from multiprocessing import dummy as multiprocessing\nimport time\nfrom cav import CAV, get_or_train_cav\nimport run_params\nimport tensorflow as tf\nimport utils\n\nclass TCAV():\n\t\"\"\"\n\tRun TCAV for one target and a set of concepts.\n\t\"\"\"\n\t@staticmethod\n\tdef get_dir_derivative_sign(black_box, act, cav, concept, class_id):\n\t\t\"\"\"\n\t\tGet the sign of directional derivative.\n\n\t\t:param black_box: a model class instance\n\t\t:param act: activations of one bottleneck to get gradient w.r.t.\n\t\t:param cav: an instance of cav\n\t\t:param concept: a concept\n\t\t:param class_id: index of the class of interest (target) in logit layer\n\t\t:return: sign of the directional derivative\n\t\t\"\"\"\n\t\tgrad = np.reshape(black_box.get_gradient(act, [class_id], cav.bottleneck), -1)\n\t\tdot_prod = np.dot(grad, cav.get_direction(concept))\n\t\treturn dot_prod < 0\n\n\t@staticmethod\n\tdef compute_tcav_score(black_box, target_class, concept, cav,\n\t\t\t\t\t\t class_acts, run_parallel=True, num_workers=20):\n\t\t\"\"\"\n\t\tCompute TCAV score.\n\n\t\t:param black_box: a model class instance\n\t\t:param target_class: one target class\n\t\t:param concept: a concept\n\t\t:param cav: an instance of cav\n\t\t:param class_acts: activations of the images in the target class\n\t\t:param run_parallel: run this in parallel\n\t\t:param num_workers: number of workers if we run in parallel\n\t\t:return: TCAV score\n\t\t\"\"\"\n\t\tcount = 0\n\t\tclass_id = black_box.label_to_id(target_class)\n\t\tif run_parallel:\n\t\t\tpool = multiprocessing.Pool(num_workers)\n\t\t\tdirections = pool.map(\n\t\t\t\tlambda act: TCAV.get_dir_derivative_sign(\n\t\t\t\t\t\t\t\tblack_box, [act], cav,\n\t\t\t\t\t\t\t\tconcept, class_id),\n\t\t\t\tclass_acts)\n\t\t\treturn sum(directions) / len(class_acts)\n\t\telse:\n\t\t\tfor i in range(len(class_acts)):\n\t\t\t\tact = np.expand_dims(class_acts[i], 0)\n\t\t\t\tif TCAV.get_dir_derivative_sign(black_box, act, cav, concept, class_id):\n\t\t\t\t\tcount += 1\n\t\t\treturn count / len(class_acts)\n\n\t@staticmethod\n\tdef get_dir_derivative(black_box, target_class, concept, cav, class_acts):\n\t\t\"\"\"\n\t\tReturn the list of values of directional derivatives.\n\n\t\t:param black_box: a model class instance \n\t\t:param target_class: a target class \n\t\t:param concept: a concept \n\t\t:param cav: an instance of cav \n\t\t:param class_acts: activations of the images in the target class\n\t\t:return: list of values of directional derivatives \n\t\t\"\"\"\n\t\tclass_id = black_box.label_to_id(target_class)\n\t\tdir_derivative_vals = []\n\t\tfor i in range(len(class_acts)):\n\t\t\tact = np.expand_dims(class_acts[i], 0)\n\t\t\tgrad = np.reshape(\n\t\t\t\tblack_box.get_gradient(act, [class_id], cav.bottleneck), -1)\n\t\t\tdir_derivative_vals.append(np.dot(grad, cav.get_direction(concept)))\n\t\treturn dir_derivative_vals\n\n\tdef __init__(self, target, concepts, bottlenecks, model_instance,\n\t\t\t\t activation_generator, alphas, random_counterpart,\n\t\t\t\t cav_dir=None, num_random_exp=5):\n\t\t\"\"\"\n\t\tInitialize tcav class.\n\n\t\t:param target: a target class\n\t\t:param concepts: a concept\n\t\t:param bottlenecks: name of a bottleneck of interest\n\t\t:param model_instance: an instance of model class\n\t\t:param activation_generator: a function handler to return activations\n\t\t:param alphas: list of hyper-parameters to run\n\t\t:param random_counterpart: the random concept to run against\n\t\t\t\t\t\t\t the concepts for statistical testing\n\t\t:param cav_dir: the path to store CAVs\n\t\t:param num_random_exp: number of random experiments to compare against\n\t\t\"\"\"\n\t\tself.target = target\n\t\tself.concepts = concepts\n\t\tself.bottlenecks = bottlenecks\n\t\tself.activation_generator = activation_generator\n\t\tself.cav_dir = cav_dir\n\t\tself.alphas = alphas\n\t\tself.random_counterpart = random_counterpart\n\t\tself.black_box = model_instance\n\t\tself.model_to_rum = self.black_box.model_name\n\n\t\tself._process_what_to_run_expand(num_random_exp=num_random_exp)\n\t\tself.params = self.get_params()\n\t\ttf.logging.info('TCAV will %s params' % len(self.params))\n\n\tdef run(self, run_parallel=False, num_workers=10):\n\t\t\"\"\"\n\t\tRun TCAV for all parameters (concept and random), write results to html\n\n\t\t:param run_parallel: run this in parallel\n\t\t:param num_workers: number of workers if we run in parallel\n\t\t:return results: result directory\n\t\t\"\"\"\n\t\ttf.logging.info('running %s params' % len(self.params))\n\t\tnow = time.time()\n\t\tif run_parallel:\n\t\t\tpool = multiprocessing.Pool(num_workers)\n\t\t\tresults = pool.map(lambda param: self._run_single_set(param), self.params)\n\t\telse:\n\t\t\tresults = []\n\t\t\tfor param in self.params:\n\t\t\t\tresults.append(self._run_single_set(param))\n\t\ttf.logging.info('Done running %s params. Took %s seconds...' % \n\t\t\t\t\t\t(len(self.params), time.time() - now))\n\t\treturn results\n\n\tdef _run_single_set(self, params):\n\t\t\"\"\"\n\t\tRun TCAV with provided for one set of (target, concepts).\n\n\t\t:param params: parameters to run\n\t\t:return: a dict of results (pandas dataframe)\n\t\t\"\"\"\n\t\tbottleneck = params.bottleneck\n\t\tconcepts = params.concepts\n\t\ttarget_class = params.target_class\n\t\tactivation_generator = params.activation_generator\n\t\talpha = params.alpha\n\t\tblack_box = params.black_box\n\t\tcav_dir = params.cav_dir\n\n\t\ttf.logging.info('running %s %s' % (target_class, concepts))\n\n\t\tacts = activation_generator(black_box, bottlenecks, concepts + [target_class])\n\t\tcav_hparams = CAV.default_hparams()\n\t\tcav_hparams.alpha = alpha\n\t\tcav_instance = get_or_train_cav(\n\t\t\tconcepts, bottlenecks, acts, cav_dir=cav_dir, cav_hparams=cav_hparams)\n\t\t\n\t\tfor concept in concepts:\n\t\t\tdel acts[concept]\n\n\t\ta_cav_key = CAV.cav_key(concepts, bottlenecks, cav_hparams.model_type,\n\t\t\t\t\t\t\t\tcav_hparams.alpha)\n\t\ttarget_class_for_compute_tcav_score = target_class\n\n\t\tfor cav_concept in concepts:\n\t\t\tif cav_concept is self.random_counterpart or 'random' not in cav_concept:\n\t\t\t\ti_up = self.compute_tcav_score(\n\t\t\t\t\tblack_box, target_class_for_compute_tcav_score, cav_concept.\n\t\t\t\t\tcav_instance, acts[target_class][cav_instance.bottleneck])\n\t\t\t\tval_dir_derivatives = self.get_dir_derivative(\n\t\t\t\t\tblack_box, target_class_for_compute_tcav_score, cav_concept.\n\t\t\t\t\tcav_instance, acts[target_class][cav_instance.bottleneck])\n\t\t\t\tresult = {\n\t\t\t\t\t'cav_key': a_cav_key,\n\t\t\t\t\t'cav_concept': cav_concept,\n\t\t\t\t\t'target_class': target_class,\n\t\t\t\t\t'i_up': i_up,\n\t\t\t\t\t'val_dir_derivatives_abs_mean': np.mean(np.abs(val_dir_derivatives)),\n\t\t\t\t\t'val_dir_derivatives_mean': np.mean(val_dir_derivatives),\n\t\t\t\t\t'val_dir_derivatives_std': np.std(val_dir_derivatives),\n\t\t\t\t\t'note': 'alpha_%s' % (alpha),\n\t\t\t\t\t'alpha': alpha,\n\t\t\t\t\t'bottleneck': bottlenecks\n\t\t\t\t} \n\t\tdel acts\n\t\treturn result\n\n\tdef _process_what_to_run_expand(self, num_random_exp=100):\n\t\t\"\"\"\n\t\tGet tuples of parameters to run TCAV with.\n\n\t\t:param num_random_exp: number of random experiments to run to compare.\n\t\t\"\"\"\n\t\ttarget_concept_pairs = [(self.target, self.concepts)]\n\t\tall_concepts_concepts, pairs_to_run_concepts = utils.process_what_to_run_expand(\n\t\t\tutils.process_what_to_run_concepts(target_concept_pairs),\n\t\t\tself.random_counterpart, num_random_exp=num_random_exp)\n\t\tall_concepts_randoms, pairs_to_run_randoms = utils.process_what_to_run_expand(\n\t\t\tutils.process_what_to_run_randoms(target_concept_pairs, self.random_counterpart),\n\t\t\tself.random_counterpart, num_random_exp=num_random_exp)\n\t\tself.all_concepts = list(set(all_concepts_concepts + all_concepts_randoms))\n\t\tself.pairs_to_test = pairs_to_run_concepts + pairs_to_run_randoms\n\n\tdef get_params(self):\n\t\t\"\"\"\n\t\tEnumerate parameters for the run function.\n\n\t\t:return: parameters\n\t\t\"\"\"\n\t\tparams = []\n\t\tfor bottleneck in self.bottlenecks:\n\t\t\tfor target_in_test, concept_in_test in self.pairs_to_test:\n\t\t\t\tfor alpha in self.alphas:\n\t\t\t\t\ttf.logging.info('%s %s %s %s', bottleneck, concept_in_test,\n\t\t\t\t\t\t\t\t\ttarget_in_test, alpha)\n\t\t\t\t\tparams.append(run_params.RunParams(\n\t\t\t\t\t\tbottleneck, concept_in_test, target_in_test,\n\t\t\t\t\t\tself.activation_generator, self.cav_dir,\n\t\t\t\t\t\talpha, self.black_box))\n\t\treturn params\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "repo_name": "MotJuMi/TCAV", "sub_path": "tcav.py", "file_name": "tcav.py", "file_ext": "py", "file_size_in_byte": 7817, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "20", "api": [{"api_name": "cav.bottleneck", "line_number": 24, "usage_type": "attribute"}, {"api_name": "cav.get_direction", "line_number": 25, "usage_type": "call"}, {"api_name": "multiprocessing.dummy.Pool", "line_number": 46, "usage_type": "call"}, {"api_name": "multiprocessing.dummy", "line_number": 46, "usage_type": "name"}, {"api_name": "cav.bottleneck", "line_number": 77, "usage_type": "attribute"}, {"api_name": "cav.get_direction", "line_number": 78, "usage_type": "call"}, {"api_name": "tensorflow.logging.info", "line_number": 110, "usage_type": "call"}, {"api_name": "tensorflow.logging", "line_number": 110, "usage_type": "attribute"}, {"api_name": "tensorflow.logging.info", "line_number": 120, "usage_type": "call"}, {"api_name": "tensorflow.logging", "line_number": 120, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 121, "usage_type": "call"}, {"api_name": "multiprocessing.dummy.Pool", "line_number": 123, "usage_type": "call"}, {"api_name": "multiprocessing.dummy", "line_number": 123, "usage_type": "name"}, {"api_name": "tensorflow.logging.info", "line_number": 129, "usage_type": "call"}, {"api_name": "tensorflow.logging", "line_number": 129, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 130, "usage_type": "call"}, {"api_name": "tensorflow.logging.info", "line_number": 148, "usage_type": "call"}, {"api_name": "tensorflow.logging", "line_number": 148, "usage_type": "attribute"}, {"api_name": "cav.CAV.default_hparams", "line_number": 151, "usage_type": "call"}, {"api_name": "cav.CAV", "line_number": 151, "usage_type": "name"}, {"api_name": "cav.get_or_train_cav", "line_number": 153, "usage_type": "call"}, {"api_name": "cav.CAV.cav_key", "line_number": 159, "usage_type": "call"}, {"api_name": "cav.CAV", "line_number": 159, "usage_type": "name"}, {"api_name": "utils.process_what_to_run_expand", "line_number": 193, "usage_type": "call"}, {"api_name": "utils.process_what_to_run_concepts", "line_number": 194, "usage_type": "call"}, {"api_name": "utils.process_what_to_run_expand", "line_number": 196, "usage_type": "call"}, {"api_name": "utils.process_what_to_run_randoms", "line_number": 197, "usage_type": "call"}, {"api_name": "tensorflow.logging.info", "line_number": 212, "usage_type": "call"}, {"api_name": "tensorflow.logging", "line_number": 212, "usage_type": "attribute"}, {"api_name": "run_params.RunParams", "line_number": 214, "usage_type": "call"}]} +{"seq_id": "38861744605", "text": "# -*- coding:utf-8 -*-\n# --author: jingfeng \n# time: 2018/11/11\n\nimport requests\nfrom lxml import etree\nfrom fake_useragent import UserAgent\nimport re\nimport pymysql\n\nconn = pymysql.connect(\n host='localhost',\n port=3306,\n user='root',\n password='*********',\n db='51job',\n charset='UTF8'\n\n)\n\ncursor = conn.cursor()\n\nua = UserAgent()\nheaders = {'User-Agent': ua.random}\nprint(headers)\n\n\ndef get_page_number():\n url = 'https://search.51job.com/list/000000,000000,0000,00,9,99,python,2,1.html'\n response = requests.get(url, headers=headers)\n response.encoding = 'gbk'\n html = response.text\n number = re.findall('(.*?)', html)[0]\n page = re.search(r'(\\d+)', number).group()\n print(page)\n\n results = get_info(page)\n\n for result in results:\n # with open(r'G:\\python3code\\爬虫实战\\51job\\python_jobs.txt', 'a', encoding='utf-8')as f:\n # f.write(str(result)+'\\n')\n try:\n values = ','.join(['\"%s\"'] * len(result))\n\n sql = 'insert into python_jobs(`job`,`company_name`,`adress`,`money`,`time`) VALUES (%s)' % (values)\n cursor.execute(sql,\n (result['job'], result['company_name'], result['adress'], result['money'], result['time']))\n conn.commit()\n except Exception as e:\n print(e)\n conn.rollback()\n print(result)\n\n\ndef get_info(numbers):\n for i in range(1, eval(numbers) + 1):\n url = 'https://search.51job.com/list/000000,000000,0000,00,9,99,python,2,{}.html'.format(i)\n print('爬取第{}页'.format(i))\n\n response = requests.get(url, headers=headers)\n response.encoding = 'gbk'\n html = response.text\n\n # print(html)\n selector = etree.HTML(html)\n\n # 职位 公司名 工作地点 薪资 发布时间\n # print(html)\n jobs = selector.xpath('//p[contains(@class,\"t1\")]/span/a[@target=\"_blank\"]/text()')\n company_names = selector.xpath('//span[@class=\"t2\"]/a[@target=\"_blank\"]/text()')\n adresses = selector.xpath('//span[@class=\"t3\"]/text()')[1:]\n moneys = re.findall(r'(.*?)', html)[1:]\n\n times = selector.xpath('//span[@class=\"t5\"]/text()')[1:]\n # print(len(jobs))\n # print(len(company_names))\n # print(len(adresses))\n # print(len(moneys))\n # print(len(times))\n for job, company_name, adress, money, time in zip(jobs, company_names, adresses, moneys, times):\n yield {\n 'job': job.strip(),\n 'company_name': company_name,\n 'adress': adress,\n 'money': money,\n 'time': time\n\n }\n\nget_page_number()\n\nconn.close()\n", "repo_name": "jingfenghan/python3code", "sub_path": "51job/python_job.py", "file_name": "python_job.py", "file_ext": "py", "file_size_in_byte": 2771, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "pymysql.connect", "line_number": 11, "usage_type": "call"}, {"api_name": "fake_useragent.UserAgent", "line_number": 23, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 30, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 33, "usage_type": "call"}, {"api_name": "re.search", "line_number": 34, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 60, "usage_type": "call"}, {"api_name": "lxml.etree.HTML", "line_number": 65, "usage_type": "call"}, {"api_name": "lxml.etree", "line_number": 65, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 72, "usage_type": "call"}]} +{"seq_id": "69933610625", "text": "# vim: set fileencoding=utf-8 :\n\nfrom __future__ import absolute_import, print_function, unicode_literals\n\nimport arrow\nimport logbook\n\nimport stethoscope.configurator\nimport stethoscope.plugins.sources.jamf.utils as jutils\nimport stethoscope.utils\nimport stethoscope.validation\n\n\nlogger = logbook.Logger(__name__)\n\n\ndef inject_last_updated(data, last_updated):\n data['last_updated'] = last_updated\n return data\n\n\nclass JAMFDataSourceBase(stethoscope.configurator.Configurator):\n\n config_keys = (\n 'JAMF_API_USERNAME',\n 'JAMF_API_PASSWORD',\n 'JAMF_API_HOSTADDR',\n )\n\n def _check_uptodate(self, raw):\n updates = raw['computer']['software']['available_software_updates']\n\n data = {'value': (len(updates) == 0)}\n if len(updates) > 0:\n data['details'] = \"Missing Updates:\\n\"\n for update in updates:\n data['details'] += \" {!s}\\n\".format(update)\n return data\n\n def _check_autoupdate(self, attributes):\n attrs = [\n ('1 Auto Check For Updates Enabled', 'True', 'Automatically check for updates'),\n ('2 Get New Updates in Background Enabled', 'True',\n 'Download newly available updates in background'),\n ('3 Install App Updates Enabled', 'False', 'Install app updates'),\n ('4 Install OS X Updates Enabled', 'False', 'Install OS X updates'),\n ('5 Install Security Updates Enabled', 'True', 'Install security updates'),\n ('6 Install System Data Files Enabled', 'True', 'Install system data files'),\n ]\n\n values = list()\n for (attr, default, _) in attrs:\n value = attributes.get(attr)\n values.append(value if value in ['True', 'False'] else default)\n\n data = {'value': all(value == \"True\" for value in values)}\n if not data['value']:\n data['details'] = \"Disabled settings:\\n\" + \"\\n\".join(\" {!s}\".format(label)\n for value, (_, _, label) in zip(values, attrs) if value != 'True')\n return data\n\n def _check_encryption(self, raw):\n data = {}\n\n try:\n storage = raw['computer']['hardware']['storage']\n except KeyError:\n pass\n else:\n details = list()\n encrypted = list()\n for drive in storage:\n if drive['drive_capacity_mb'] > 0 and 'partition' in drive:\n # hack to work around bug in JAMF\n if drive['partition']['name'] in ('Recovery', 'Recovery HD'):\n continue\n\n encrypted.append(drive['partition']['filevault2_status'] == \"Encrypted\")\n\n # hack to work around bug in JAMF\n status = drive['partition']['filevault2_status']\n if status == \"Not Supported\":\n status = \"Not Encrypted\"\n\n details.append(\"{name!s}: {status:s} ({filevault2_percent:d}%)\"\n \"\".format(status=status, **drive['partition']))\n\n data['value'] = all(encrypted)\n data['details'] = '\\n'.join(details)\n\n return data\n\n def _normalize_software_entry(self, entry):\n \"\"\"Convert software information returned from JAMF to common software list format.\"\"\"\n return entry\n\n def _process_device(self, raw):\n if raw is None:\n return None\n data = {'_raw': raw} if self._debug else {}\n\n computer = raw['computer']\n # logger.debug(\"computer:\\n{:s}\".format(pprint.pformat(computer)))\n\n attributes = jutils._parse_parameter_list(computer['extension_attributes'])\n # logger.debug(\"extension attributes:\\n{:s}\".format(pprint.pformat(attributes)))\n\n # INFORMATION\n data['model'] = computer['hardware']['model']\n\n data.update(stethoscope.utils.copy_partial_dict(computer['general'], {\n 'platform': 'platform',\n 'serial': 'serial_number',\n 'name': 'name',\n }))\n\n data.update(stethoscope.utils.copy_partial_dict(computer['hardware'], {\n 'os': 'os_name',\n 'os_version': 'os_version',\n }))\n\n email = computer.get('location', {}).get('email_address')\n if email is not None:\n data['email'] = email\n\n try:\n last_updated = arrow.get(computer['general']['report_date_utc'])\n except arrow.parser.ParserError:\n last_updated = None\n\n data['last_sync'] = last_updated\n\n # PRACTICES\n data['practices'] = dict()\n data['practices']['encryption'] = inject_last_updated(self._check_encryption(raw), last_updated)\n data['practices']['uptodate'] = inject_last_updated(self._check_uptodate(raw), last_updated)\n data['practices']['autoupdate'] = inject_last_updated(self._check_autoupdate(attributes),\n last_updated)\n\n data['software'] = {'last_scan_date': last_updated}\n data['software']['installed'] = [self._normalize_software_entry(entry) for entry in\n raw['computer']['software']['applications']]\n data['software']['services'] = [{'name': service} for service in\n raw['computer']['software']['running_services']]\n\n try:\n practice = {'value': int(attributes['Firewall Status']) > 0}\n except (KeyError, ValueError):\n practice = {}\n data['practices']['firewall'] = inject_last_updated(practice, last_updated)\n\n for key, attr, ok_value in [\n ('screenlock', 'Screen Saver Lock Enabled', 'Enabled'),\n ('remotelogin', 'Remote Login', 'Off'),\n ]:\n practice = {} if attr not in attributes else {'value': attributes[attr] == ok_value}\n data['practices'][key] = inject_last_updated(practice, last_updated)\n\n # IDENTIFIERS\n mac_addrs = list(stethoscope.validation.filter_macaddrs(set(map(\n stethoscope.validation.canonicalize_macaddr,\n filter(lambda addr: addr != '', [\n computer['general'].get('mac_address', ''),\n computer['general'].get('alt_mac_address', ''),\n attributes.get('Wireless Mac Address', ''),\n ])\n ))))\n\n data['identifiers'] = {\n 'serial': computer['general']['serial_number'],\n 'mac_addresses': mac_addrs,\n 'udid': computer['general']['udid'],\n }\n\n data['source'] = 'jamf'\n # logger.debug(\"returned info:\\n{:s}\".format(pprint.pformat(data)))\n return data\n\n @staticmethod\n def _extract_device_ids_from_userinfo(userinfo_response):\n return JAMFDataSourceBase._extract_device_ids_from_response(\n userinfo_response.get('user', {}).get('links', {})\n )\n\n @staticmethod\n def _extract_device_ids_from_response(search_response):\n return [computer['id'] for computer in search_response.get('computers', [])]\n", "repo_name": "Netflix-Skunkworks/stethoscope", "sub_path": "stethoscope/plugins/sources/jamf/base.py", "file_name": "base.py", "file_ext": "py", "file_size_in_byte": 6302, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1999, "dataset": "github-code", "pt": "25", "api": [{"api_name": "logbook.Logger", "line_number": 14, "usage_type": "call"}, {"api_name": "stethoscope.configurator.configurator", "line_number": 22, "usage_type": "attribute"}, {"api_name": "stethoscope.configurator", "line_number": 22, "usage_type": "name"}, {"api_name": "stethoscope.plugins.sources.jamf.utils._parse_parameter_list", "line_number": 105, "usage_type": "call"}, {"api_name": "stethoscope.plugins.sources.jamf.utils", "line_number": 105, "usage_type": "name"}, {"api_name": "stethoscope.configurator.utils.copy_partial_dict", "line_number": 111, "usage_type": "call"}, {"api_name": "stethoscope.configurator.utils", "line_number": 111, "usage_type": "attribute"}, {"api_name": "stethoscope.configurator", "line_number": 111, "usage_type": "name"}, {"api_name": "stethoscope.configurator.utils.copy_partial_dict", "line_number": 117, "usage_type": "call"}, {"api_name": "stethoscope.configurator.utils", "line_number": 117, "usage_type": "attribute"}, {"api_name": "stethoscope.configurator", "line_number": 117, "usage_type": "name"}, {"api_name": "arrow.get", "line_number": 127, "usage_type": "call"}, {"api_name": "arrow.parser", "line_number": 128, "usage_type": "attribute"}, {"api_name": "stethoscope.configurator.validation.filter_macaddrs", "line_number": 160, "usage_type": "call"}, {"api_name": "stethoscope.configurator.validation", "line_number": 160, "usage_type": "attribute"}, {"api_name": "stethoscope.configurator", "line_number": 160, "usage_type": "name"}, {"api_name": "stethoscope.configurator.validation", "line_number": 161, "usage_type": "attribute"}, {"api_name": "stethoscope.configurator", "line_number": 161, "usage_type": "name"}]} +{"seq_id": "10342706187", "text": "#!/usr/bin/env python3\n\nimport torch\nimport torch.nn as nn\n\n\nclass NormLayer(nn.Module):\n\t\"\"\"\n\t\tImplementation of Layer Normalization (https://arxiv.org/abs/1607.06450)\n\t\tIt consists of Batch Normalization Transform to speed up learning with mean and std computed according to the above paper\n\n\t\tnormWeights:\n\t\t\tweights for this normalization layer which will be learnt during training\n\t\tnormBias:\n\t\t\tbias for this normalization layer which will be learnt during training\n\t\tepsilon:\n\t\t\tnumerical stability parameter to avoid division by zero\n\t\"\"\"\n\n\tdef __init__(self, hiddenSize, epsilon=1e-12):\n\t\tsuper(NormLayer, self).__init__()\n\t\tself.weight = nn.Parameter(torch.ones(hiddenSize))\n\t\tself.bias = nn.Parameter(torch.zeros(hiddenSize))\n\t\tself.epsilon = epsilon\n\n\n\tdef forward(self, input):\n\t\tmu = input.mean(-1, keepdim=True)\n\t\tstdArg = (input - mu).pow(2).mean(-1, keepdim=True) + self.epsilon\n\t\tstd = torch.sqrt(stdArg)\n\t\tinput = (input - mu) / std\n\t\treturn self.weight * input + self.bias\n\n", "repo_name": "simonepreite/QABERT", "sub_path": "NormLayer.py", "file_name": "NormLayer.py", "file_ext": "py", "file_size_in_byte": 994, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "torch.nn.Module", "line_number": 7, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 7, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.ones", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn.Parameter", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.sqrt", "line_number": 30, "usage_type": "call"}]} +{"seq_id": "4147267448", "text": "\"\"\"\r\nGiven a characters array letters that is sorted in non-decreasing order and a character target,\r\nreturn the smallest character in the array that is larger than target.\r\n\r\nNote that the letters wrap around.\r\n\r\nFor example, if target == 'z' and letters == ['a', 'b'], the answer is 'a'.\r\n\r\n\r\nExample 1:\r\n\r\nInput: letters = [\"c\",\"f\",\"j\"], target = \"a\"\r\nOutput: \"c\"\r\nExample 2:\r\n\r\nInput: letters = [\"c\",\"f\",\"j\"], target = \"c\"\r\nOutput: \"f\"\r\nExample 3:\r\n\r\nInput: letters = [\"c\",\"f\",\"j\"], target = \"d\"\r\nOutput: \"f\"\r\nExample 4:\r\n\r\nInput: letters = [\"c\",\"f\",\"j\"], target = \"g\"\r\nOutput: \"j\"\r\nExample 5:\r\n\r\nInput: letters = [\"c\",\"f\",\"j\"], target = \"j\"\r\nOutput: \"c\"\r\n\r\n\r\nConstraints:\r\n\r\n2 <= letters.length <= 104\r\nletters[i] is a lowercase English letter.\r\nletters is sorted in non-decreasing order.\r\nletters contains at least two different characters.\r\ntarget is a lowercase English letter.\r\n\"\"\"\r\nfrom typing import List\r\n\r\n\r\nclass Solution:\r\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\r\n letters = list(set(letters))\r\n string_lowercase = 'abcdefghijklmnopqrstuvwxyz'\r\n lst_str = list(string_lowercase)\r\n i = 0\r\n while i < 26:\r\n if target == lst_str[i]:\r\n j = i + 1\r\n if j == 26:\r\n j = 0\r\n while j < 26:\r\n if lst_str[j] in letters:\r\n return lst_str[j]\r\n j += 1\r\n if j == 25 or j == 26:\r\n j = 0\r\n i += 1\r\n if i == 26:\r\n i = 0\r\n\r\n\r\narr = [\r\n [[\"c\", \"f\", \"j\"], \"a\"],\r\n [[\"c\", \"f\", \"j\"], \"c\"],\r\n [[\"c\", \"f\", \"j\"], \"d\"],\r\n [[\"c\", \"f\", \"j\"], \"g\"],\r\n [[\"c\", \"f\", \"j\"], \"j\"],\r\n [[\"a\", \"b\"], \"z\"],\r\n [[\"e\", \"e\", \"e\", \"e\", \"e\", \"e\", \"n\", \"n\", \"n\", \"n\"], \"y\"]\r\n]\r\n\r\nsol = Solution()\r\nfor el in arr:\r\n print(sol.nextGreatestLetter(el[0], el[1]))\r\n", "repo_name": "ZF-1000/GIT-repository_Leet_Code", "sub_path": "744. Find Smallest Letter Greater Than Target.py", "file_name": "744. Find Smallest Letter Greater Than Target.py", "file_ext": "py", "file_size_in_byte": 1934, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "typing.List", "line_number": 44, "usage_type": "name"}]} +{"seq_id": "6562083351", "text": "\"\"\" Imports required for basket_contents \"\"\"\nfrom decimal import Decimal\nfrom django.shortcuts import get_object_or_404\nfrom django.contrib import messages\nfrom products.models import Vinyl\n\n\ndef basket_contents(request):\n \"\"\" Make basket contents and totals available to all templates \"\"\"\n basket_products = []\n total = 0\n product_count = 0\n basket = request.session.get('basket', {})\n basket_bin = []\n\n # Iterate through basket.items getting required info and adding to\n # basket_products\n for product_id, quantity in basket.items():\n product = get_object_or_404(Vinyl, pk=product_id)\n # Check stock still available and not been bought by someone else\n # since added to basket.\n if quantity <= product.stock_quantity:\n product_name = product.title.replace(\" \", \"_\").lower\n total += Decimal(quantity) * product.price\n item_total = Decimal(quantity) * product.price\n product_count += int(quantity)\n product_images = product.image_set.all()\n # Get quantity available for quantity select input\n stock_quantity_list = []\n for value in range(1, (product.stock_quantity + 1)):\n stock_quantity_list.append(value)\n basket_products.append({\n 'product_id': product_id,\n 'quantity': quantity,\n 'product': product,\n 'product_images': product_images,\n 'item_total': item_total,\n 'product_name': product_name,\n 'stock_quantity_list': stock_quantity_list\n })\n else:\n # If stock no longer available since user had added to basket\n # Error message shown to user and added to bin.\n messages.error(request, (\n f'Sorry { product.title} no longer has { quantity }'\n ' left in stock.'))\n basket_bin.append(product_id)\n\n # If products in bin, remove from session 'basket'\n if basket_bin:\n for product_id in basket_bin:\n basket.pop(product_id)\n request.session['basket'] = basket\n\n # Calculate shipping based on number of items\n delivery = 4.95 + ((product_count - 1)/2)\n grand_total = round((total + Decimal(delivery)), 2)\n\n # Info now available to our templates\n context = {\n 'basket_products': basket_products,\n 'total': total,\n 'product_count': product_count,\n 'delivery': delivery,\n 'grand_total': grand_total\n }\n\n return context\n", "repo_name": "natalie-kate/music_to_my_ears", "sub_path": "basket/contexts.py", "file_name": "contexts.py", "file_ext": "py", "file_size_in_byte": 2569, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "26", "api": [{"api_name": "django.shortcuts.get_object_or_404", "line_number": 19, "usage_type": "call"}, {"api_name": "products.models.Vinyl", "line_number": 19, "usage_type": "argument"}, {"api_name": "decimal.Decimal", "line_number": 24, "usage_type": "call"}, {"api_name": "decimal.Decimal", "line_number": 25, "usage_type": "call"}, {"api_name": "django.contrib.messages.error", "line_number": 44, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 44, "usage_type": "name"}, {"api_name": "decimal.Decimal", "line_number": 57, "usage_type": "call"}]} +{"seq_id": "13028679302", "text": "# -*- coding: utf-8 -*-\n\nfrom flask import Flask, request, flash, jsonify, make_response\nfrom flask_sqlalchemy import SQLAlchemy\n\nimport guest_book_improved.config as config\n\napp = Flask(__name__, template_folder='templates')\napp.config.from_object(config)\n\ndb = SQLAlchemy(app)\n\n\n@app.route('/items', methods=['GET', 'POST', 'PUT'])\ndef index():\n from guest_book_improved.models import GuestBookItem\n from guest_book_improved.forms import ItemFullForm\n\n # Создание новой записи\n if request.method == 'POST':\n form = ItemFullForm(request.form)\n\n if form.validate():\n item = GuestBookItem(**form.data)\n db.session.add(item)\n db.session.commit()\n\n flash('Запись добавлена.')\n\n # Возвращаем код 201 после создания поста\n resp = make_response(jsonify(item.to_dict()), 201)\n # В заголовке Location выдаем адрес созданной страницы\n resp.headers['Location'] = '/items/{}'.format(item.id)\n return resp\n\n else:\n flash('Форма не валидна! Запись не была добавлена.')\n flash(str(form.errors))\n\n # Удаление всех записей\n if request.method == 'PUT':\n # Записи удаляются, если клиент передал пустое тело запроса\n if not request.form:\n GuestBookItem.query.delete()\n db.session.commit()\n\n items = GuestBookItem.query.all()\n\n # Вывод всех записей в формате JSON\n return jsonify([i.to_dict() for i in items])\n\n\n# Маршрутизация для доступа к конкретной записи по id\n@app.route('/items/', methods=['GET', 'PUT', 'PATCH', 'DELETE'])\ndef show_item(item_id):\n from guest_book_improved.forms import ItemFullForm, ItemPatchForm\n from datetime import datetime\n\n # Получение записи по id из базы данных\n item = GuestBookItem.query.filter_by(id=item_id).first()\n\n # Если по такому id записи нет, то возвращаем код 204 или 404 в зависимости от метода\n if item is None:\n if request.method != 'DELETE':\n return 'Запись не найдена.', 404\n else:\n return 'Запись не найдена.', 204\n\n # Редактирование содержания конкретной записи\n if request.method == 'PATCH':\n form = ItemPatchForm(request.form)\n\n if form.validate():\n # Изменение содержания\n item.content = request.form['content']\n # Обновление поля updated at\n item.updated_at = datetime.now()\n\n db.session.commit()\n flash('Запись изменена.')\n\n else:\n flash('Форма не валидна! Запись не была изменена.')\n flash(str(form.errors))\n\n # Полная замена записи, сохраняется только id\n if request.method == 'PUT':\n form = ItemFullForm(request.form)\n\n if form.validate():\n item.author = request.form['author']\n item.content = request.form['content']\n item.date_created = datetime.now()\n item.updated_at = datetime.now()\n item.deleted = False\n\n db.session.commit()\n\n flash('Запись заменена.')\n\n else:\n flash('Форма не валидна! Запись не была заменена.')\n flash(str(form.errors))\n\n # \"Удаление\" записи, изменяются параметры видимости\n if request.method == 'DELETE':\n item.deleted = True\n db.session.commit()\n\n # Вывод конкретной записи\n return jsonify(item.to_dict())\n\n\nif __name__ == '__main__':\n from guest_book_improved.models import *\n db.create_all()\n\n app.run()\n", "repo_name": "skantaev/homework13", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 4179, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "flask.Flask", "line_number": 8, "usage_type": "call"}, {"api_name": "guest_book_improved.config", "line_number": 9, "usage_type": "argument"}, {"api_name": "flask_sqlalchemy.SQLAlchemy", "line_number": 11, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 20, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 20, "usage_type": "name"}, {"api_name": "guest_book_improved.forms.ItemFullForm", "line_number": 21, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 21, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 21, "usage_type": "name"}, {"api_name": "guest_book_improved.models.GuestBookItem", "line_number": 24, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 28, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 31, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 31, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 37, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 38, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 41, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 41, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 43, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 43, "usage_type": "name"}, {"api_name": "guest_book_improved.models.GuestBookItem.query.delete", "line_number": 44, "usage_type": "call"}, {"api_name": "guest_book_improved.models.GuestBookItem.query", "line_number": 44, "usage_type": "attribute"}, {"api_name": "guest_book_improved.models.GuestBookItem", "line_number": 44, "usage_type": "name"}, {"api_name": "guest_book_improved.models.GuestBookItem.query.all", "line_number": 47, "usage_type": "call"}, {"api_name": "guest_book_improved.models.GuestBookItem.query", "line_number": 47, "usage_type": "attribute"}, {"api_name": "guest_book_improved.models.GuestBookItem", "line_number": 47, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 50, "usage_type": "call"}, {"api_name": "guest_book_improved.models.GuestBookItem.query.filter_by", "line_number": 60, "usage_type": "call"}, {"api_name": "guest_book_improved.models.GuestBookItem.query", "line_number": 60, "usage_type": "attribute"}, {"api_name": "guest_book_improved.models.GuestBookItem", "line_number": 60, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 64, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 64, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 70, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 70, "usage_type": "name"}, {"api_name": "guest_book_improved.forms.ItemPatchForm", "line_number": 71, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 71, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 71, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 75, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 75, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 77, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 77, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 80, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 83, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 84, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 87, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 87, "usage_type": "name"}, {"api_name": "guest_book_improved.forms.ItemFullForm", "line_number": 88, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 88, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 88, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 91, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 91, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 92, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 92, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 93, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 93, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 94, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 94, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 99, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 102, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 103, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 106, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 106, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 111, "usage_type": "call"}]} +{"seq_id": "9837941053", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 8 10:52:11 2020\n\n@author: HP\n\"\"\"\n\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_table\nfrom dash.dependencies import Input,Output\nimport base64\nimport dash_bootstrap_components as dbc\n\napp= dash.Dash(__name__,external_stylesheets=[dbc.themes.BOOTSTRAP])\n\nimage= base64.b64encode(open('1.jpg','rb').read())\n\ncard_one= dbc.Card([\n dbc.CardImg(src='data:image/png;base64,{}'.format(image.decode()),top=True, bottom=False,alt='Not working'),\n dbc.CardBody([\n html.H6('Batman is Awsome',className='card-title'),\n dbc.Button('Press Me',href='http://google.com',target='_blank',color='success')]\n )],outline=True\n )\n\nimage2= base64.b64encode(open('2.jpg','rb').read())\ncard_two= dbc.Card([\n dbc.CardImg(src='data:image/png;base64,{}'.format(image2.decode()),top=True, bottom=False,alt='Not working'),\n dbc.CardBody([\n html.H6('Batman is Awsome',className='card-title'),\n dbc.Button('Press Me',href='http://google.com',target='_blank',color='success')]\n )],outline=True\n )\n\napp.layout = html.Div(children=[\n dbc.Row(\n [\n dbc.Col(card_one),\n dbc.Col(card_two),\n dbc.Col(card_two)\n ]\n ),\n dbc.Row(\n [\n dbc.Col(card_one),\n dbc.Col(card_two),\n dbc.Col(card_two)\n ]\n ) \n]\n)\napp.run_server(debug=True)\n\n", "repo_name": "mohitnagarkotibca/Concepts", "sub_path": "dash/test_Ddpy.py", "file_name": "test_Ddpy.py", "file_ext": "py", "file_size_in_byte": 1463, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "dash.Dash", "line_number": 16, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.themes", "line_number": 16, "usage_type": "attribute"}, {"api_name": "base64.b64encode", "line_number": 18, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.Card", "line_number": 20, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.CardImg", "line_number": 21, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.CardBody", "line_number": 22, "usage_type": "call"}, {"api_name": "dash_html_components.H6", "line_number": 23, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.Button", "line_number": 24, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 28, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.Card", "line_number": 29, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.CardImg", "line_number": 30, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.CardBody", "line_number": 31, "usage_type": "call"}, {"api_name": "dash_html_components.H6", "line_number": 32, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.Button", "line_number": 33, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 37, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.Row", "line_number": 38, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.Col", "line_number": 40, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.Col", "line_number": 41, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.Col", "line_number": 42, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.Row", "line_number": 45, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.Col", "line_number": 47, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.Col", "line_number": 48, "usage_type": "call"}, {"api_name": "dash_bootstrap_components.Col", "line_number": 49, "usage_type": "call"}]} +{"seq_id": "26830041591", "text": "from pathlib import Path\nimport os\nimport glob\nwork_dir = Path.cwd()\n\nexport_pdf_dir = work_dir / 'pdf2'\nprint(export_pdf_dir)\nif not export_pdf_dir.exists():\n export_pdf_dir.mkdir()\n#file=open('fix.md','w') \n##向文件中写入字符 \n##file.write('test\\n') \n#for md_file in list(sorted(glob.glob('./*/*.md'))):\n# for line in open(md_file): \n# file.writelines(line) \n# file.write('\\n')\n#pdf_file = \"./Dive-into-DL-PyTorch.pdf\" \n#cmd = \"pandoc -N --template=template2.tex --variable mainfont='PingFang SC' --variable sansfont='Helvetica' --variable monofont='Menlo' --variable fontsize=12pt --variable version=2.0 '{}' --latex-engine=xelatex --toc -o '{}' \".format(\"fix.md\", pdf_file)\n#os.system(cmd)\n \nfor md_file in list(sorted(glob.glob('./*/*.md'))):\n print(md_file)\n md_file_name = md_file\n zhanjie=md_file_name.split(\"/\")[-2]\n print(zhanjie)\n pdf_file_name = md_file_name.replace('.md', '.pdf')\n pdf_file = export_pdf_dir/pdf_file_name\n os.makedirs(str(export_pdf_dir/zhanjie),exist_ok=True)\n print(pdf_file)\n cmd = \"pandoc '{}' -o '{}' -s --highlight-style pygments --latex-engine=xelatex -V mainfont='PingFang SC' --template=template.tex\".format(md_file, pdf_file)\n os.system(cmd)", "repo_name": "OUCMachineLearning/OUCML", "sub_path": "BOOK/batch-markdown-to-pdf.py", "file_name": "batch-markdown-to-pdf.py", "file_ext": "py", "file_size_in_byte": 1246, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4401, "dataset": "github-code", "pt": "26", "api": [{"api_name": "pathlib.Path.cwd", "line_number": 4, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 4, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 21, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 28, "usage_type": "call"}, {"api_name": "os.system", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "17324695339", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 8 12:10:55 2018\n\n@author: NicoS\n\"\"\"\nfrom netCDF4 import Dataset\nimport numpy as np\nimport os\n\n\nclass NETCDF:\n\tdef __init__ (self):\n\t\tself.masksload()\n\t\t\n\tdef masksload(self):\n\t\n\t\tfilename = 'X:/SnowCover/Masks/Region_Mask.msk'\n\t\twith open(filename, 'rb') as fr:\n\t\t\tself.regionmask = np.fromfile(fr, dtype='uint8')\n\t\tfilename = 'X:/SnowCover/Masks/Pixel_area_crop.msk'\n\t\twith open(filename, 'rb') as fr:\n\t\t\tself.pixelarea = np.fromfile(fr, dtype='uint16')\n\t\tfilename = 'X:/SnowCover/Masks/Latitude_Mask.msk'\n\t\twith open(filename, 'rb') as fr:\n\t\t\tself.Latitude_Mask = np.fromfile(fr, dtype='float32')\n\t\tfilename = 'X:/SnowCover/Masks/Longitude_Mask.msk'\n\t\twith open(filename, 'rb') as fr:\n\t\t\tself.Longitude_Mask = np.fromfile(fr, dtype='float32')\n\n\t\t\n\n\n\t\t\n\tdef NETCDF_creater(self):\n\t\trootgrp = Dataset(\"Snow_cover_days.nc\", \"w\", format=\"NETCDF4\")\n\t\trootgrp.description = 'total days covered by snow'\n\t\trootgrp.history = \"Created by Nico Sun 2018-11-27\"\n\t\t\n\t\tfcstgrp = rootgrp.createGroup(\"Snow Days\")\n\t\tyear = rootgrp.createDimension(\"year\", None)\n\t\txaxis = rootgrp.createDimension(\"xaxis\", 610)\n\t\tyaxis = rootgrp.createDimension(\"yaxis\", 450)\n\n\t\tlatitude = rootgrp.createVariable(\"latitude\",\"f4\",(\"xaxis\",\"yaxis\",))\n\t\tlongitude = rootgrp.createVariable(\"longitude\",\"f4\",(\"xaxis\",\"yaxis\",))\n\t\tareacello = rootgrp.createVariable(\"areacello\",\"f4\",(\"xaxis\",\"yaxis\",))\n\t\tregion = rootgrp.createVariable(\"Region\",\"u1\",(\"xaxis\",\"yaxis\",))\n\t\t\n\t\tareacello.units = \"gridcell area in km^2\"\n\t\t\n\t\t\n\t\tself.Latitude_Mask = self.Latitude_Mask.reshape(610,450)\n\t\tself.Longitude_Mask = self.Longitude_Mask.reshape(610,450)\n\t\tself.pixelarea = self.pixelarea.reshape(610,450)\n\t\tself.regionmask = self.regionmask.reshape(610,450)\n\t\t\n\t\tlatitude[:,:] = self.Latitude_Mask\n\t\tlongitude[:,:] = self.Longitude_Mask\n\t\tareacello[:,:] = self.pixelarea\n\t\tregion[:,:] = self.regionmask\n\t\t\n\t\tself.year = 1999\n\t\tself.yearcount = 19\n\t\tfilepath = 'X:/SnowCover/netcdf/'\n\t\tx = 0\n\t\twhile x < self.yearcount:\n\t\t\tSnow_Day = rootgrp.createVariable(varname=\"{}\".format(self.year),\n\t\t\t\t datatype=\"u2\",dimensions=(\"xaxis\",\"yaxis\",))\n\t\t\tSnow_Day.units = \"Days\"\n\n\t\t\tfilename = 'Snow_cover_days_{}.bin'.format(self.year)\n\t\t\twith open(os.path.join(filepath,filename), 'rb') as fr:\n\t\t\t\tSnow_Day_load = np.fromfile(fr, dtype='uint16')\n\t\t\t\tSnow_Day_load = Snow_Day_load.reshape(610,450)\n\t\t\t\tSnow_Day[:,:] = Snow_Day_load\n\t\t\t\n\t\t\tx += 1\n\t\t\tself.year += 1\n\n\t\trootgrp.close()\n\t\t#print ('temp shape before adding data = ', temp.shape)\n\t\t\n\n\naction = NETCDF()\naction.NETCDF_creater()\n", "repo_name": "NicoSun/CryosphereComputing", "sub_path": "SnowCover/Tools/Snow_cover_netcdf.py", "file_name": "Snow_cover_netcdf.py", "file_ext": "py", "file_size_in_byte": 2576, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "26", "api": [{"api_name": "numpy.fromfile", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.fromfile", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.fromfile", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.fromfile", "line_number": 29, "usage_type": "call"}, {"api_name": "netCDF4.Dataset", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path", "line_number": 73, "usage_type": "attribute"}, {"api_name": "numpy.fromfile", "line_number": 74, "usage_type": "call"}]} +{"seq_id": "38972744634", "text": "import inspect\nimport os\nimport pytest\nimport yaml\nfrom schema import SchemaMissingKeyError\nfrom griptape.tasks import ActionSubtask, ToolkitTask\nfrom tests.mocks.mock_tool.tool import MockTool\nfrom tests.utils import defaults\n\n\nclass TestBaseTool:\n @pytest.fixture\n def tool(self):\n return MockTool(test_field=\"hello\", test_int=5, test_dict={\"foo\": \"bar\"})\n\n def test_off_prompt(self, tool):\n assert (\n ToolkitTask(task_memory=defaults.text_task_memory(\"TestMemory\"), tools=[MockTool()]).tools[0].output_memory\n )\n\n assert (\n not ToolkitTask(task_memory=defaults.text_task_memory(\"TestMemory\"), tools=[MockTool(off_prompt=False)])\n .tools[0]\n .output_memory\n )\n\n def test_manifest_path(self, tool):\n assert tool.manifest_path == os.path.join(tool.abs_dir_path, tool.MANIFEST_FILE)\n\n def test_requirements_path(self, tool):\n assert tool.requirements_path == os.path.join(tool.abs_dir_path, tool.REQUIREMENTS_FILE)\n\n def test_manifest(self, tool):\n with open(tool.manifest_path, \"r\") as yaml_file:\n assert tool.manifest == yaml.safe_load(yaml_file)\n\n def test_abs_file_path(self, tool):\n assert tool.abs_file_path == os.path.abspath(inspect.getfile(tool.__class__))\n\n def test_abs_dir_path(self, tool):\n assert tool.abs_dir_path == os.path.dirname(tool.abs_file_path)\n\n def test_name(self):\n assert MockTool().name == \"MockTool\"\n assert MockTool(name=\"FooBar\").name == \"FooBar\"\n\n def test_class_name(self):\n assert MockTool().class_name == \"MockTool\"\n assert MockTool(name=\"FooBar\").class_name == \"MockTool\"\n\n def test_validate(self, tool):\n assert tool.validate()\n\n def test_invalid_config(self):\n try:\n from tests.mocks.invalid_mock_tool.tool import InvalidMockTool\n\n assert False\n except SchemaMissingKeyError as e:\n assert True\n\n def test_memory(self):\n tool = MockTool(\n output_memory={\"test\": [defaults.text_task_memory(\"Memory1\"), defaults.text_task_memory(\"Memory2\")]}\n )\n\n assert len(tool.output_memory[\"test\"]) == 2\n\n def test_memory_validation(self):\n with pytest.raises(ValueError):\n MockTool(\n output_memory={\"test\": [defaults.text_task_memory(\"Memory1\"), defaults.text_task_memory(\"Memory1\")]}\n )\n\n with pytest.raises(ValueError):\n MockTool(output_memory={\"output_memory\": [defaults.text_task_memory(\"Memory1\")]})\n\n assert MockTool(\n output_memory={\n \"test\": [defaults.text_task_memory(\"Memory1\")],\n \"test_str_output\": [defaults.text_task_memory(\"Memory1\")],\n }\n )\n\n def test_find_input_memory(self):\n assert MockTool().find_input_memory(\"foo\") is None\n assert MockTool(input_memory=[defaults.text_task_memory(\"foo\")]).find_input_memory(\"foo\") is not None\n\n def test_execute(self, tool):\n assert tool.execute(tool.test_list_output, ActionSubtask(\"foo\")).to_text() == \"foo\\n\\nbar\"\n\n def test_schema(self, tool):\n tool = MockTool()\n\n assert tool.schema() == {\n \"description\": \"MockTool action schema.\",\n \"anyOf\": [\n {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"const\": \"MockTool\"},\n \"path\": {\"description\": \"test description: foo\", \"const\": \"test\"},\n \"input\": {\n \"type\": \"object\",\n \"properties\": {\n \"values\": {\n \"description\": \"Test input\",\n \"type\": \"object\",\n \"properties\": {\"test\": {\"type\": \"string\"}},\n \"required\": [\"test\"],\n \"additionalProperties\": False,\n }\n },\n \"required\": [\"values\"],\n \"additionalProperties\": False,\n },\n },\n \"required\": [\"name\", \"path\", \"input\"],\n \"additionalProperties\": False,\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"const\": \"MockTool\"},\n \"path\": {\"description\": \"test description: foo\", \"const\": \"test_error\"},\n \"input\": {\n \"type\": \"object\",\n \"properties\": {\n \"values\": {\n \"description\": \"Test input\",\n \"type\": \"object\",\n \"properties\": {\"test\": {\"type\": \"string\"}},\n \"required\": [\"test\"],\n \"additionalProperties\": False,\n }\n },\n \"required\": [\"values\"],\n \"additionalProperties\": False,\n },\n },\n \"required\": [\"name\", \"path\", \"input\"],\n \"additionalProperties\": False,\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"const\": \"MockTool\"},\n \"path\": {\"description\": \"test description\", \"const\": \"test_list_output\"},\n \"input\": {\"type\": \"object\", \"properties\": {}, \"required\": [], \"additionalProperties\": False},\n },\n \"required\": [\"name\", \"path\", \"input\"],\n \"additionalProperties\": False,\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"const\": \"MockTool\"},\n \"path\": {\"description\": \"test description\", \"const\": \"test_no_schema\"},\n \"input\": {\"type\": \"object\", \"properties\": {}, \"required\": [], \"additionalProperties\": False},\n },\n \"required\": [\"name\", \"path\", \"input\"],\n \"additionalProperties\": False,\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"const\": \"MockTool\"},\n \"path\": {\"description\": \"test description: foo\", \"const\": \"test_str_output\"},\n \"input\": {\n \"type\": \"object\",\n \"properties\": {\n \"values\": {\n \"description\": \"Test input\",\n \"type\": \"object\",\n \"properties\": {\"test\": {\"type\": \"string\"}},\n \"required\": [\"test\"],\n \"additionalProperties\": False,\n }\n },\n \"required\": [\"values\"],\n \"additionalProperties\": False,\n },\n },\n \"required\": [\"name\", \"path\", \"input\"],\n \"additionalProperties\": False,\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"const\": \"MockTool\"},\n \"path\": {\"description\": \"test description\", \"const\": \"test_without_default_memory\"},\n \"input\": {\n \"type\": \"object\",\n \"properties\": {\n \"values\": {\n \"description\": \"Test input\",\n \"type\": \"object\",\n \"properties\": {\"test\": {\"type\": \"string\"}},\n \"required\": [\"test\"],\n \"additionalProperties\": False,\n }\n },\n \"required\": [\"values\"],\n \"additionalProperties\": False,\n },\n },\n \"required\": [\"name\", \"path\", \"input\"],\n \"additionalProperties\": False,\n },\n ],\n \"$id\": \"MockTool Action Schema\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n }\n", "repo_name": "mvandermeulen/griptape", "sub_path": "tests/unit/tools/test_base_tool.py", "file_name": "test_base_tool.py", "file_ext": "py", "file_size_in_byte": 8844, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "26", "api": [{"api_name": "tests.mocks.mock_tool.tool.MockTool", "line_number": 14, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 12, "usage_type": "attribute"}, {"api_name": "griptape.tasks.ToolkitTask", "line_number": 18, "usage_type": "call"}, {"api_name": "tests.utils.defaults.text_task_memory", "line_number": 18, "usage_type": "call"}, {"api_name": "tests.utils.defaults", "line_number": 18, "usage_type": "name"}, {"api_name": "tests.mocks.mock_tool.tool.MockTool", "line_number": 18, "usage_type": "call"}, {"api_name": "griptape.tasks.ToolkitTask", "line_number": 22, "usage_type": "call"}, {"api_name": "tests.utils.defaults.text_task_memory", "line_number": 22, "usage_type": "call"}, {"api_name": "tests.utils.defaults", "line_number": 22, "usage_type": "name"}, {"api_name": "tests.mocks.mock_tool.tool.MockTool", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "yaml.safe_load", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path", "line_number": 38, "usage_type": "attribute"}, {"api_name": "inspect.getfile", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "attribute"}, {"api_name": "tests.mocks.mock_tool.tool.MockTool", "line_number": 44, "usage_type": "call"}, {"api_name": "tests.mocks.mock_tool.tool.MockTool", "line_number": 45, "usage_type": "call"}, {"api_name": "tests.mocks.mock_tool.tool.MockTool", "line_number": 48, "usage_type": "call"}, {"api_name": "tests.mocks.mock_tool.tool.MockTool", "line_number": 49, "usage_type": "call"}, {"api_name": "schema.SchemaMissingKeyError", "line_number": 59, "usage_type": "name"}, {"api_name": "tests.mocks.mock_tool.tool.MockTool", "line_number": 63, "usage_type": "call"}, {"api_name": "tests.utils.defaults.text_task_memory", "line_number": 64, "usage_type": "call"}, {"api_name": "tests.utils.defaults", "line_number": 64, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 70, "usage_type": "call"}, {"api_name": "tests.mocks.mock_tool.tool.MockTool", "line_number": 71, "usage_type": "call"}, {"api_name": "tests.utils.defaults.text_task_memory", "line_number": 72, "usage_type": "call"}, {"api_name": "tests.utils.defaults", "line_number": 72, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 75, "usage_type": "call"}, {"api_name": "tests.mocks.mock_tool.tool.MockTool", "line_number": 76, "usage_type": "call"}, {"api_name": "tests.utils.defaults.text_task_memory", "line_number": 76, "usage_type": "call"}, {"api_name": "tests.utils.defaults", "line_number": 76, "usage_type": "name"}, {"api_name": "tests.mocks.mock_tool.tool.MockTool", "line_number": 78, "usage_type": "call"}, {"api_name": "tests.utils.defaults.text_task_memory", "line_number": 80, "usage_type": "call"}, {"api_name": "tests.utils.defaults", "line_number": 80, "usage_type": "name"}, {"api_name": "tests.utils.defaults.text_task_memory", "line_number": 81, "usage_type": "call"}, {"api_name": "tests.utils.defaults", "line_number": 81, "usage_type": "name"}, {"api_name": "tests.mocks.mock_tool.tool.MockTool", "line_number": 86, "usage_type": "call"}, {"api_name": "tests.mocks.mock_tool.tool.MockTool", "line_number": 87, "usage_type": "call"}, {"api_name": "tests.utils.defaults.text_task_memory", "line_number": 87, "usage_type": "call"}, {"api_name": "tests.utils.defaults", "line_number": 87, "usage_type": "name"}, {"api_name": "griptape.tasks.ActionSubtask", "line_number": 90, "usage_type": "call"}, {"api_name": "tests.mocks.mock_tool.tool.MockTool", "line_number": 93, "usage_type": "call"}]} +{"seq_id": "31100812023", "text": "import json\n\nfrom core.management.commands import core_download_command\nfrom damumed import models\nfrom damumed.management.commands import damumed_browser_command\nfrom pages.damumed import MainPage, ReportsPage\n\n\nclass Command(damumed_browser_command.DamumedBrowserCommand, core_download_command.CoreDownloadCommand):\n download_settings_model = models.DownloadSettings\n\n def before_command(self, log_in_settings: models.LogInSettings) -> None:\n super().before_command(log_in_settings)\n main_page = MainPage(self.driver)\n main_page.open()\n main_page.driver.delete_all_cookies()\n main_page.open()\n with open(self.get_cookies_path(log_in_settings)) as file:\n cookies = json.load(file)\n main_page.set_cookies(cookies)\n\n def run(self, log_in_settings: models.LogInSettings) -> None:\n errors = []\n for report in models.Report.objects.filter(download = True):\n try:\n counter = 3\n while True:\n try:\n reports_page = ReportsPage(self.driver)\n reports_page.open_report(report)\n reports_page.set_period()\n reports_page.set_filters(report)\n reports_page.set_checkbox_filters(report)\n reports_page.set_multiple_filters(report)\n reports_page.download_report()\n\n self.wait_download()\n self.move(log_in_settings, report)\n # закрывает дополнительную вкладку\n self.driver.close()\n break\n except Exception as error:\n counter -= 1\n if counter <= 0:\n self.remove_not_downloaded()\n raise error\n except Exception as error:\n errors.append(error)\n if errors:\n raise core_download_command.DownloadNotFinishedException() from errors[0]\n", "repo_name": "Radislav123/kazakhstan_healthcare_1", "sub_path": "damumed/management/commands/damumed_reports_download.py", "file_name": "damumed_reports_download.py", "file_ext": "py", "file_size_in_byte": 2124, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "damumed.management.commands.damumed_browser_command.DamumedBrowserCommand", "line_number": 9, "usage_type": "attribute"}, {"api_name": "damumed.management.commands.damumed_browser_command", "line_number": 9, "usage_type": "name"}, {"api_name": "core.management.commands.core_download_command.CoreDownloadCommand", "line_number": 9, "usage_type": "attribute"}, {"api_name": "core.management.commands.core_download_command", "line_number": 9, "usage_type": "name"}, {"api_name": "damumed.models.DownloadSettings", "line_number": 10, "usage_type": "attribute"}, {"api_name": "damumed.models", "line_number": 10, "usage_type": "name"}, {"api_name": "damumed.models.LogInSettings", "line_number": 12, "usage_type": "attribute"}, {"api_name": "damumed.models", "line_number": 12, "usage_type": "name"}, {"api_name": "pages.damumed.MainPage", "line_number": 14, "usage_type": "call"}, {"api_name": "json.load", "line_number": 19, "usage_type": "call"}, {"api_name": "damumed.models.LogInSettings", "line_number": 22, "usage_type": "attribute"}, {"api_name": "damumed.models", "line_number": 22, "usage_type": "name"}, {"api_name": "damumed.models.Report.objects.filter", "line_number": 24, "usage_type": "call"}, {"api_name": "damumed.models.Report", "line_number": 24, "usage_type": "attribute"}, {"api_name": "damumed.models", "line_number": 24, "usage_type": "name"}, {"api_name": "pages.damumed.ReportsPage", "line_number": 29, "usage_type": "call"}, {"api_name": "core.management.commands.core_download_command.DownloadNotFinishedException", "line_number": 50, "usage_type": "call"}, {"api_name": "core.management.commands.core_download_command", "line_number": 50, "usage_type": "name"}]} +{"seq_id": "73510585030", "text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport redis, threading, traceback\nfrom log_tool import LogsTool\nfrom get_dvd_conf import get_config\n\nlog_redis = LogsTool('redis')\n\n\n# 目前只是简单的发布订阅模式\nclass Redis_tool(object):\n _instance_lock = threading.Lock()\n\n def __init__(self, config):\n self.config = config\n\n self.log_redis = LogsTool('redis').get_instance()\n\n with self._instance_lock:\n if not hasattr(self, '_redis_tmp'):\n self._connect()\n\n def __new__(cls, *args, **kwargs):\n # 单例设计是在这里实现的\n if len(args) != 1:\n raise Exception('创建类参数错误')\n\n with Redis_tool._instance_lock:\n if not hasattr(Redis_tool, \"config_d\"):\n Redis_tool.config_d = {}\n Redis_tool.config_d[args[0]] = object.__new__(cls)\n else:\n if not Redis_tool.config_d.has_key(args[0]):\n Redis_tool.config_d[args[0]] = object.__new__(cls)\n return Redis_tool.config_d[args[0]]\n\n def _connect(self):\n try:\n self._pool = redis.ConnectionPool(host=get_config(self.config, 'host'),\n port=get_config(self.config, 'port'),\n password=get_config(self.config, 'password'))\n self._redis_tmp = redis.Redis(connection_pool=self._pool)\n\n self.log_redis.info(\"[The Redis Connect success] [Config:{}]\".format(self.config))\n\n except Exception as e:\n self.log_redis.error(\n '[The Redis Connect failed] [Config:{}] [ErrorInfo:{}] [Trace:{}]'.format(self.config, e,\n traceback.format_exc()))\n\n def publish_t(self, channel, message):\n try:\n num = self._redis_tmp.publish(channel, message)\n self.log_redis.info(\n \"[Publish success] [Config:{}] [Channel:{}] [Message:{}] [Subscribe_num:{}]\".format(self.config,\n channel, message,\n num))\n return True\n except Exception as e:\n self.log_redis.error(\n '[Publish failed] [Config:{}] [ErrorInfo:{}] [Trace:{}]'.format(self.config, e, traceback.format_exc()))\n return False\n\n def subscribe_t(self, channel):\n try:\n pub = self._redis_tmp.pubsub()\n pub.subscribe(channel)\n pub.parse_response()\n return pub\n except Exception as e:\n self.log_redis.error(\n '[subscribe failed] [Config:{}] [ErrorInfo:{}] [Trace:{}]'.format(self.config, e,\n traceback.format_exc()))\n return False\n\n# 发布模式\n# r1 = Redis_tool()\n#\n# r1.publish('test','buaho')\n\n# 订阅模式\n# r2 = Redis_tool()\n#\n# pub=r2.subscribe('test')\n#\n# while True:\n#\n# print pub.parse_response()[2]\n", "repo_name": "iteemo/utility", "sub_path": "app/utils/redis_tool.py", "file_name": "redis_tool.py", "file_ext": "py", "file_size_in_byte": 3219, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "log_tool.LogsTool", "line_number": 8, "usage_type": "call"}, {"api_name": "threading.Lock", "line_number": 13, "usage_type": "call"}, {"api_name": "log_tool.LogsTool", "line_number": 18, "usage_type": "call"}, {"api_name": "redis.ConnectionPool", "line_number": 40, "usage_type": "call"}, {"api_name": "get_dvd_conf.get_config", "line_number": 40, "usage_type": "call"}, {"api_name": "get_dvd_conf.get_config", "line_number": 41, "usage_type": "call"}, {"api_name": "get_dvd_conf.get_config", "line_number": 42, "usage_type": "call"}, {"api_name": "redis.Redis", "line_number": 43, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 50, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 62, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 74, "usage_type": "call"}]} +{"seq_id": "4765822403", "text": "import unittest\nimport matplotlib.pyplot as plt\nimport numpy\n\nfrom store.actors.entrance import Entrance\nfrom store.builder import Builder\n\n\nclass TestPlacesToBe(unittest.TestCase):\n input_json = {\n \"length\": 10800,\n \"client_count\": 500,\n \"client_distribution\": {\n \"mean\": 5400,\n \"variance\": 3000\n }\n }\n\n def test_graph(self):\n builder = Builder(self.input_json)\n\n plot = plt.plot()\n bins = 40\n plt.title(\"Distribution of customer entry events\")\n events = builder.create_entry_events(builder.get_client_count())\n bins, e, v = plt.hist(events, bins, linewidth=1, edgecolor='black')\n plt.xlabel('Time')\n plt.ylabel('Customers entering')\n plt.xticks(range(0, builder.get_sim_length(), 540))\n plt.show()\n", "repo_name": "zkroliko/Store-simulation", "sub_path": "storeTests/loader/entrances_test.py", "file_name": "entrances_test.py", "file_ext": "py", "file_size_in_byte": 829, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "unittest.TestCase", "line_number": 9, "usage_type": "attribute"}, {"api_name": "store.builder.Builder", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}]} +{"seq_id": "3109067452", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 9 15:26:29 2020\r\n\r\n@author: XIANG\r\n\"\"\"\r\nimport torch.optim as optim\r\nfrom M1LapReg import callLapReg\r\nimport torch\r\nimport torch.nn as nn\r\nfrom os.path import dirname, join as pjoin\r\nfrom collections import OrderedDict\r\nimport time\r\nimport numpy as np\r\nfrom helpers import test_rescale, show_image_matrix\r\n#from torch.utils.tensorboard import SummaryWriter\r\nimport os\r\n\r\ndef l1_loss(pred, target, l1_weight):\r\n \"\"\"\r\n Compute L1 loss;\r\n l1_weigh default: 0.1\r\n \"\"\"\r\n err = torch.mean(torch.abs(pred - target))\r\n err = l1_weight * err\r\n return err\r\n\r\ndef tv_loss(img, tv_weight):\r\n \"\"\"\r\n Compute total variation loss.\r\n Inputs:\r\n - img: PyTorch Variable of shape (1, 3, H, W) holding an input image.\r\n - tv_weight: Scalar giving the weight w_t to use for the TV loss. 0.01 default.\r\n Returns:\r\n - loss: PyTorch Variable holding a scalar giving the total variation loss\r\n for img weighted by tv_weight.\r\n \"\"\"\r\n w_variance = torch.sum(torch.pow(img[:,:,:,:-1] - img[:,:,:,1:], 2))\r\n h_variance = torch.sum(torch.pow(img[:,:,:-1,:] - img[:,:,1:,:], 2))\r\n loss = tv_weight * (h_variance + w_variance)\r\n return loss\r\n\r\n\r\nclass Solver(object):\r\n def __init__(self, model, data_loader, args, test_data, test_images):\r\n assert args.model_name in ['FBPConv', 'ISTANet', 'FISTANet']\r\n\r\n self.model_name = args.model_name\r\n self.model = model\r\n self.data_loader = data_loader\r\n self.data_dir = args.data_dir\r\n self.num_epochs = args.num_epochs\r\n self.start_epoch = args.start_epoch\r\n self.lr = args.lr\r\n \r\n if self.model_name == 'FISTANet':\r\n # set different lr for regularization weights and network weights\r\n self.optimizer = optim.Adam([\r\n {'params': self.model.fcs.parameters()}, \r\n {'params': self.model.w_theta, 'lr': 0.001},\r\n {'params': self.model.b_theta, 'lr': 0.001},\r\n {'params': self.model.w_mu, 'lr': 0.001},\r\n {'params': self.model.b_mu, 'lr': 0.001},\r\n {'params': self.model.w_rho, 'lr': 0.001},\r\n {'params': self.model.b_rho, 'lr': 0.001}], \r\n lr=self.lr, weight_decay=0.001)\r\n else:\r\n self.optimizer = optim.Adam(self.model.parameters(), lr=self.lr, weight_decay=0.001)\r\n\r\n self.scheduler = torch.optim.lr_scheduler.StepLR(self.optimizer, step_size=10, gamma=0.9) # step-wise\r\n\r\n\r\n self.save_path = args.save_path\r\n self.multi_gpu = args.multi_gpu\r\n self.device = args.device\r\n self.log_interval = args.log_interval\r\n self.test_epoch = args.test_epoch\r\n self.test_data = test_data\r\n self.test_images = test_images\r\n self.train_loss = nn.MSELoss()\r\n\r\n def save_model(self, iter_):\r\n if not os.path.exists(self.save_path):\r\n os.makedirs(self.save_path)\r\n f = pjoin(self.save_path, 'epoch_{}.ckpt'.format(iter_))\r\n torch.save(self.model.state_dict(), f)\r\n \r\n def load_model(self, iter_):\r\n f = pjoin(self.save_path, 'epoch_{}.ckpt'.format(iter_))\r\n if self.multi_gpu:\r\n state_d = OrderedDict()\r\n for k, v in torch.load(f):\r\n n = k[7:]\r\n state_d[n] = v\r\n self.model.load_state_dict(state_d)\r\n else:\r\n self.model.load_state_dict(torch.load(f))\r\n \r\n \r\n def train(self):\r\n train_losses = []\r\n start_time = time.time()\r\n # set up Tensorboard\r\n #writer = SummaryWriter('runs/'+self.model_name)\r\n \r\n\r\n for epoch in range(1 + self.start_epoch, self.num_epochs + 1 + self.start_epoch):\r\n self.model.train(True)\r\n \r\n for batch_idx, (x_in, y_target) in enumerate(self.data_loader):\r\n \r\n # measured vector (104*1); add channels\r\n x_in = torch.unsqueeze(x_in, 1) \r\n x_in = torch.unsqueeze(x_in, 3)\r\n \r\n # initial image from one-step inversion\r\n x_img = callLapReg(data_dir=self.data_dir, y_test=x_in) \r\n \r\n # target image (64*64)\r\n y_target = torch.unsqueeze(y_target, 1)\r\n\r\n if epoch == 1 and batch_idx == 1:\r\n show_image_matrix('./figures/X0.png', [x_img, y_target], \r\n titles=['X0 FBP', 'y_target'], indices=slice(0,30)) \r\n\r\n\r\n x_img = torch.tensor(x_img, dtype=torch.float32, device=self.device)\r\n x_in = torch.tensor(x_in, dtype=torch.float32, device=self.device)\r\n y_target = torch.tensor(y_target, dtype=torch.float32, device=self.device)\r\n\r\n\r\n if self.model_name == 'FBPConv':\r\n\r\n pred = self.model(x_img) \r\n loss = self.train_loss(pred, y_target) + l1_loss(pred, y_target, 0.1)\r\n\r\n # predict and compute losses\r\n if self.model_name == 'ISTANet':\r\n [pred, loss_sym] = self.model(x_img, x_in)\r\n loss_discrepancy = self.train_loss(pred, y_target) + l1_loss(pred, y_target, 0.1)\r\n loss_constraint = 0\r\n for k, _ in enumerate(loss_sym, 0):\r\n loss_constraint += torch.mean(torch.pow(loss_sym[k], 2))\r\n\r\n loss = loss_discrepancy + 0.01 * loss_constraint\r\n\r\n if self.model_name == 'FISTANet':\r\n [pred, loss_layers_sym, loss_st] = self.model(x_img, x_in)\r\n\r\n # Compute loss, data consistency and regularizer constraints\r\n loss_discrepancy = self.train_loss(pred, y_target) + l1_loss(pred, y_target, 0.1)\r\n loss_constraint = 0\r\n for k, _ in enumerate(loss_layers_sym, 0):\r\n loss_constraint += torch.mean(torch.pow(loss_layers_sym[k], 2))\r\n \r\n sparsity_constraint = 0\r\n for k, _ in enumerate(loss_st, 0):\r\n sparsity_constraint += torch.mean(torch.abs(loss_st[k]))\r\n \r\n # loss = loss_discrepancy + gamma * loss_constraint\r\n loss = loss_discrepancy + 0.01 * loss_constraint + 0.001 * sparsity_constraint\r\n\r\n \r\n self.model.zero_grad()\r\n self.optimizer.zero_grad()\r\n \r\n # backpropagate the gradients\r\n loss.backward()\r\n self.optimizer.step()\r\n self.scheduler.step()\r\n train_losses.append(loss.item())\r\n \r\n\r\n # print processes \r\n if batch_idx % self.log_interval == 0:\r\n #writer.add_scalar('training loss', loss.data, epoch * len(self.data_loader) + batch_idx)\r\n\r\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tBatch Loss: {:.6f}\\t TIME:{:.1f}s'\r\n ''.format(epoch, batch_idx * len(x_in),\r\n len(self.data_loader.dataset),\r\n 100. * batch_idx / len(self.data_loader),\r\n loss.data,\r\n time.time() - start_time)) \r\n\r\n # print weight values of model\r\n if self.model_name == 'FISTANet':\r\n\r\n print(\"Threshold value w: {}\".format(self.model.w_theta))\r\n print(\"Threshold value b: {}\".format(self.model.b_theta))\r\n print(\"Gradient step w: {}\".format(self.model.w_mu))\r\n print(\"Gradient step b: {}\".format(self.model.b_mu))\r\n print(\"Two step update w: {}\".format(self.model.w_rho))\r\n print(\"Two step update b: {}\".format(self.model.b_rho))\r\n \r\n # save model\r\n if epoch % 1 == 0:\r\n\r\n self.save_model(epoch)\r\n np.save(pjoin(self.save_path, 'loss_{}_epoch.npy'.format(epoch)), np.array(train_losses))\r\n \r\n def test(self):\r\n self.load_model(self.test_epoch)\r\n self.model.eval()\r\n \r\n with torch.no_grad():\r\n # Must use the sample test dataset!!!\r\n x_test = callLapReg(data_dir=self.data_dir, y_test=self.test_data)\r\n x_test = torch.tensor(x_test, dtype=torch.float32, device=self.device)\r\n\r\n if self.model_name == \"ISTANet\":\r\n test_data = torch.tensor(self.test_data, dtype=torch.float32, device=self.device)\r\n [test_res, _] = self.model(x_test, test_data)\r\n\r\n elif self.model_name == 'FISTANet':\r\n test_data = torch.tensor(self.test_data, dtype=torch.float32, device=self.device)\r\n [test_res, _, _] = self.model(x_test, test_data)\r\n\r\n else:\r\n # other nets needs to do one-step inversion\r\n test_res = self.model(x_test)\r\n\r\n \r\n return test_res\r\n ", "repo_name": "jinxixiang/FISTA-Net", "sub_path": "solver.py", "file_name": "solver.py", "file_ext": "py", "file_size_in_byte": 9187, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 42, "dataset": "github-code", "pt": "26", "api": [{"api_name": "torch.mean", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.abs", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.pow", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.pow", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 58, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 68, "usage_type": "name"}, {"api_name": "torch.optim.lr_scheduler.StepLR", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 70, "usage_type": "attribute"}, {"api_name": "torch.nn.MSELoss", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 80, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 83, "usage_type": "call"}, {"api_name": "os.path", "line_number": 83, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 84, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 85, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 86, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 89, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 97, "usage_type": "call"}, {"api_name": "time.time", "line_number": 102, "usage_type": "call"}, {"api_name": "torch.unsqueeze", "line_number": 113, "usage_type": "call"}, {"api_name": "torch.unsqueeze", "line_number": 114, "usage_type": "call"}, {"api_name": "M1LapReg.callLapReg", "line_number": 117, "usage_type": "call"}, {"api_name": "torch.unsqueeze", "line_number": 120, "usage_type": "call"}, {"api_name": "helpers.show_image_matrix", "line_number": 123, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 127, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 127, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 128, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 128, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 129, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 129, "usage_type": "attribute"}, {"api_name": "torch.mean", "line_number": 143, "usage_type": "call"}, {"api_name": "torch.pow", "line_number": 143, "usage_type": "call"}, {"api_name": "torch.mean", "line_number": 154, "usage_type": "call"}, {"api_name": "torch.pow", "line_number": 154, "usage_type": "call"}, {"api_name": "torch.mean", "line_number": 158, "usage_type": "call"}, {"api_name": "torch.abs", "line_number": 158, "usage_type": "call"}, {"api_name": "time.time", "line_number": 183, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 199, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 199, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 199, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 205, "usage_type": "call"}, {"api_name": "M1LapReg.callLapReg", "line_number": 207, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 208, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 208, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 211, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 211, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 215, "usage_type": "call"}, {"api_name": "torch.float32", "line_number": 215, "usage_type": "attribute"}]} +{"seq_id": "5779919906", "text": "# Importing libraries\r\nfrom airflow import DAG\r\nfrom airflow.operators.bash import BashOperator\r\nfrom datetime import datetime, timedelta\r\n\r\n# Create a DAG and setting default parameters\r\nwith DAG(\r\n \"news_and_sentiment\",\r\n default_args={\r\n \"depends_on_past\": False,\r\n \"email\": [\"exemple@hotmail.com\"],\r\n \"email_on_failure\": False,\r\n \"email_on_retry\": False,\r\n \"retries\": 1,\r\n \"retry_delay\": timedelta(minutes=1)\r\n },\r\n description=\"Extração de noticias e identificação dos sentimentos por elas exprimidas\",\r\n schedule=\"0 0 * * *\",\r\n start_date=datetime(2023, 3, 8),\r\n end_date=datetime(2024, 1, 1),\r\n catchup=False,\r\n tags=['News', 'sentiment'],\r\n) as dag:\r\n # Creating tasks\r\n task1 = BashOperator(\r\n task_id=\"news\",\r\n bash_command=\"python3 ~/airflow/dags/script/news.py\",\r\n )\r\n task2 = BashOperator(\r\n task_id=\"sentiments\",\r\n bash_command=\"python3 ~/airflow/dags/script/sentiment.py\",\r\n retries=1,\r\n )\r\n task1 >> task2\r\n", "repo_name": "MatheusWenzel/news_and_sentiment", "sub_path": "news_sentiment.py", "file_name": "news_sentiment.py", "file_ext": "py", "file_size_in_byte": 1109, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "airflow.DAG", "line_number": 7, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 20, "usage_type": "call"}, {"api_name": "airflow.operators.bash.BashOperator", "line_number": 25, "usage_type": "call"}, {"api_name": "airflow.operators.bash.BashOperator", "line_number": 29, "usage_type": "call"}]} +{"seq_id": "2793643435", "text": "import numpy as np\nimport matplotlib as mp\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef plotSetup(xmin = -6.0, xmax = 6.0, ymin = -2.0, ymax = 4.0, size=(6,4)):\n \"\"\"\n basics of 2D plot setup\n defaults: xmin = -6.0, xmax = 6.0, ymin = -2.0, ymax = 4.0, size=(6,4)\n size is by default 6 inches by 4 inches\n \"\"\"\n fig = plt.figure(figsize=size)\n ax = fig.add_subplot(1, 1, 1)\n plt.xlim([xmin, xmax])\n plt.ylim([ymin, ymax])\n ax.axes.set_xlim([xmin, xmax])\n return ax\n\ndef formatEqn(coefs, b):\n \"\"\"\n format a set of coefficients as a linear equation in text\n \"\"\"\n leadingLabel = {-1: '-{} x_{}', 0: '', 1: '{} x_{}'}\n followingLabel = {-1: ' - {} x_{}', 0: '', 1: ' + {} x_{}'}\n nterms = len(coefs)\n i = 0\n # skip initial terms with coefficient zero\n while ((i < nterms) and (np.sign(coefs[i]) == 0)):\n i += 1\n # degenerate equation \n if (i == nterms):\n return '0 = {}'.format(b)\n # first term is formatted slightly differently\n if (np.abs(coefs[i]) == 1):\n label = leadingLabel[np.sign(coefs[i])].format('',i+1)\n else:\n label = leadingLabel[np.sign(coefs[i])].format(np.abs(coefs[i]),i+1)\n # and the rest of the terms if any exist\n for j in range(i+1,len(coefs)):\n if (np.abs(coefs[j]) == 1):\n label = label + followingLabel[np.sign(coefs[j])].format('',j+1)\n else:\n label = label + followingLabel[np.sign(coefs[j])].format(np.abs(coefs[j]),j+1)\n label = label + ' = {}'.format(b)\n return label\n\ndef plotPoint (ax, x1, x2, color='r'):\n ax.plot(x1, x2, '{}o'.format(color))\n\ndef plotVec (ax, x1, color='r'):\n ax.plot(x1[0], x1[1], '{}o'.format(color))\n\ndef plotArrow (ax, x1, x2):\n ax.arrow(0.0, 0.0, x1, x2)\n\ndef plotArrowVec(ax, v, start = [0,0], head_width=0.2, head_length=0.2, length_includes_head = True, color='Red'):\n try:\n ax.arrow(start[0],start[1],v[0]-start[0],v[1]-start[1],head_width=head_width, head_length=head_length, length_includes_head = length_includes_head, color=color)\n # if the arrow length is zero, raises an IndexError\n except IndexError:\n pass\n\ndef plotLinEqn (a1, a2, b, format='-', color='r'):\n \"\"\"\n plot line line corresponding to the linear equation\n a1 x + a2 y = b\n \"\"\"\n [xmin, xmax] = plt.xlim()\n x1 = xmin\n y1 = (b - (x1 * a1))/float(a2)\n x2 = xmax\n y2 = (b - (x2 * a1))/float(a2)\n plt.plot([x1, x2],[y1, y2], format, label='${}$'.format(formatEqn([a1, a2],b)),color=color)\n\ndef centerAxes (ax):\n ax.spines['left'].set_position('zero')\n ax.spines['right'].set_color('none')\n ax.spines['bottom'].set_position('zero')\n ax.spines['top'].set_color('none')\n ax.spines['left'].set_smart_bounds(True)\n ax.spines['bottom'].set_smart_bounds(True)\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n bounds = np.array([ax.axes.get_xlim(), ax.axes.get_ylim()])\n ax.plot(bounds[0][0],bounds[1][0],'')\n ax.plot(bounds[0][1],bounds[1][1],'')\n \ndef plotSetup3d(xmin = -3.0, xmax = 3.0, ymin = -3.0, ymax = 3.0, zmin = -3.0, zmax = 3.0, figsize=(6,4)):\n fig = plt.figure(figsize=figsize)\n ax = fig.add_subplot(111, projection='3d')\n ax.axes.set_xlim([xmin, xmax])\n ax.axes.set_ylim([ymin, ymax])\n ax.axes.set_zlim([zmin, zmax])\n ax.axes.set_xlabel('$x_1$',size=15)\n ax.axes.set_ylabel('$x_2$',size=15)\n ax.axes.set_zlabel('$x_3$',size=15)\n return ax\n\ndef plotPoint3d (ax, x1, x2, x3, color='r'):\n ax.plot([x1], [x2], '{}o'.format(color), zs=[x3])\n \ndef plotLinEqn3d(ax, l1, color='Green'):\n \"\"\"\n plot the plane corresponding to the linear equation\n a1 x + a2 y + a3 z = b\n where l1 = [a1, a3, a3, b]\n \"\"\"\n pts = intersectionPlaneCube(ax, l1)\n ptlist = np.array([np.array(i) for i in pts])\n x = ptlist[:,0]\n y = ptlist[:,1]\n z = ptlist[:,2]\n if (len(x) > 2):\n try:\n triang = mp.tri.Triangulation(x, y)\n except:\n # this happens where there are triangles parallel to the z axis\n # so some points in the x,y plane are repeated (which is illegal for a triangulation)\n # this is a hack but it works!\n try:\n triang = mp.tri.Triangulation(x, z)\n triang.y = y\n except:\n triang = mp.tri.Triangulation(z, y)\n triang.x = x\n ax.plot_trisurf(triang, z, color=color, alpha=0.3, linewidth=0, shade=False)\n\ndef intersectionPlaneCube(ax, l1):\n # returns the vertices of the polygon defined by the intersection of a plane\n # and the rectangular prism defined by the limits of the axes\n bounds = np.array([ax.axes.get_xlim(), ax.axes.get_ylim(), ax.axes.get_zlim()])\n coefs = l1[0:3]\n b = l1[3]\n points = []\n for x in [0, 1]:\n for y in [0, 1]:\n for z in [0, 1]:\n corner = [x, y, z]\n # 24 corner-pairs \n for i in range(3):\n # but only consider each edge once (12 unique edges)\n if corner[i] == 0:\n # we are looking for the intesection of the line defined by\n # the two constant values with the plane\n isect = (b - np.sum([coefs[k] * bounds[k][corner[k]] for k in range(3) if k != i]))/float(coefs[i])\n if ((isect >= bounds[i][0]) & (isect <= bounds[i][1])):\n pt = [bounds[k][corner[k]] for k in range(3)]\n pt[i] = isect\n points.append(tuple(pt))\n return set(points)\n\ndef plotIntersection3d(ax, eq1, eq2, type='-',color='Blue'):\n \"\"\"\n plot the intersection of two linear equations in 3d\n \"\"\"\n bounds = np.array([ax.axes.get_xlim(), ax.axes.get_ylim(), ax.axes.get_zlim()])\n tmp = np.array([np.array(eq1), np.array(eq2)])\n A = tmp[:,:-1]\n b = tmp[:,-1]\n ptlist = []\n for i in range(3):\n vars = [k for k in range(3) if k != i]\n A2 = A[:][:,vars]\n for j in range(2):\n b2 = b - bounds[i,j] * A[:,i]\n try:\n pt = np.linalg.inv(A2).dot(b2)\n except:\n continue\n if (pt[0] >= bounds[vars[0]][0]) & (pt[0] <= bounds[vars[0]][1]) & (pt[1] >= bounds[vars[1]][0]) & (pt[1] <= bounds[vars[1]][1]):\n point = [0,0,0]\n point[vars[0]] = pt[0]\n point[vars[1]] = pt[1]\n point[i] = bounds[i,j]\n ptlist.append(point)\n ptlist = np.array(ptlist).T\n ax.plot(ptlist[0,:], ptlist[1,:], type, zs = ptlist[2,:], color=color)\n\ndef plotCube(ax, pt, color='Blue'):\n \"\"\"\n plot a 3d wireframe parallelipiped with one corner on the origin\n \"\"\"\n endpoints = np.concatenate((np.array([[0,0,0]]),np.array([pt])))\n for x in [0, 1]:\n for y in [0, 1]:\n for z in [0, 1]:\n # we are plotting each line twice; not bothering to fix this\n corner = [endpoints[x,0],endpoints[y,1], endpoints[z,2]]\n # from each corner, plot the edges adjacent to that corner\n ax.plot([endpoints[x,0],endpoints[1-x,0]],[endpoints[y,1],endpoints[y,1]],zs=[endpoints[z,2],endpoints[z,2]],color=color)\n ax.plot([endpoints[x,0],endpoints[x,0]],[endpoints[y,1],endpoints[1-y,1]],zs=[endpoints[z,2],endpoints[z,2]],color=color)\n ax.plot([endpoints[x,0],endpoints[x,0]],[endpoints[y,1],endpoints[y,1]],zs=[endpoints[z,2],endpoints[1-z,2]],color=color)\n \ndef plotSpan3d(ax, u, v, color='Blue'):\n \"\"\"\n Plot the plane that is the span of u and v\n \"\"\"\n # we are looking for a single equation ax1 + bx2 + cx3 = 0\n # it is homogeneous because it is a subspace (span)\n # we have two solutions [a b c]'u = 0 and [a b c]'v = 0\n # this corresponds to a linear system in [a b c]\n # with coefficient matrix [u; v; 0]\n A = np.array([u, v])\n # put A in reduced row echelon form\n # assumes the line connecting the two points is\n # not parallel to any axes!\n A[0] = A[0]/A[0][0]\n A[1] = A[1] - A[1][0] * A[0]\n A[1] = A[1] / A[1][1]\n A[0] = A[0] - A[0][1] * A[1]\n # now use c=1 to fix a single solution\n a = -A[0][2]\n b = -A[1][2]\n c = 1.0\n plotLinEqn3d(ax, [a, b, c, 0.0], color)\n \n", "repo_name": "adamdavisonsmith/BU-CS506-Spring2018", "sub_path": "laUtilities.py", "file_name": "laUtilities.py", "file_ext": "py", "file_size_in_byte": 8412, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 22, "dataset": "github-code", "pt": "26", "api": [{"api_name": "matplotlib.pyplot.figure", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 14, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 15, "usage_type": "name"}, {"api_name": "numpy.sign", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.sign", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.sign", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.sign", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.sign", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 89, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 89, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.tri.Triangulation", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.tri", "line_number": 115, "usage_type": "attribute"}, {"api_name": "matplotlib.tri.Triangulation", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.tri", "line_number": 121, "usage_type": "attribute"}, {"api_name": "matplotlib.tri.Triangulation", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.tri", "line_number": 124, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 131, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 156, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 167, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 167, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 183, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 183, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 203, "usage_type": "call"}]} +{"seq_id": "13415586", "text": "\"\"\"Studying of SQL inject \"\"\"\n\nimport sqlite3\nimport os\n\n# init db\n\ntry:\n os.remove('sql_inject.db')\nexcept FileNotFoundError:\n pass\n\nconn = sqlite3.connect('sql_inject.db')\ncur = conn.cursor()\n\n# create the table\n\ncur.execute(\"CREATE TABLE users (\"\n \"username VARCHAR(30), \"\n \"admin BOOLEAN)\")\n\ncur.execute(\"INSERT INTO users (username, admin)\"\n \"VALUES \"\n \"('ran', True), \"\n \"('haki', False)\")\n\nconn.commit()\n\n# executing a query\ncur.execute(\"SELECT COUNT(*) FROM users\")\nres = cur.fetchone()\nprint(res)\n\n# get admin, BAD EXAMPLE!!!\ndef is_admin(username: str) -> bool:\n cur.execute(\"SELECT admin FROM users WHERE username = '%s'\" % username)\n res = cur.fetchone()\n if res is None:\n return False\n admin, = res\n return admin\n\n# existing users\nprint(is_admin('ran'))\nprint(is_admin('haki'))\n\n# non-existing user\nprint(is_admin('foo')) # error as fetchone() returned None, add the None case to is_admin\n\n# SQL inject see below\nprint(is_admin(\"' OR True; --\")) # this one query always returning True\n\n# to avoid this use placeholders: qmark or named\n# qmark style, variable as tuple is the second arg of execute method\n\ndef is_admin_qmark(username: str) -> bool:\n cur.execute(\"SELECT admin FROM users WHERE username = ?\", (username, ))\n res = cur.fetchone()\n if res is None:\n return False\n admin, = res\n return admin\n\n\nprint(is_admin_qmark(\"' OR True; --\")) # this wrong query returning False with qmark parametrization\n\n# named style of parametrization, second arg is a dict (or a subclass)\n# keys are column names of the table, values - row values\n# example for multiply rows using executemany(), data as a tuple of dictionaries\n\ndata_multi = (\n {\"username\": 'Bob', 'admin': True},\n {\"username\": 'Jack', 'admin': False},\n {\"username\": 'Sue', 'admin': False}\n)\n\ncur.executemany(\"INSERT INTO users (username, admin) \"\n \"VALUES (:username, :admin)\",\n data_multi)\nconn.commit()\n\n# ---- END OF STUDYING ----\n\n\n\n\n", "repo_name": "altilan-mne/bmconv", "sub_path": "studies/sql_inject.py", "file_name": "sql_inject.py", "file_ext": "py", "file_size_in_byte": 2057, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "os.remove", "line_number": 9, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 13, "usage_type": "call"}]} +{"seq_id": "4106896179", "text": "import vtk \nimport os\n\npath = '/Users/imageens/jy_data/4D FLOW/Amigo 1/Camcmorphv - 3983/4D_Flow_SAG_210/'\n# Read data in VTK format\nreader = vtk.vtkDICOMImageReader()\nreader.SetDirectoryName(path)\nreader.Update()\n\n\n# Start by creating a black/white lookup table.\nbw_lut = vtk.vtkLookupTable()\nbw_lut.SetTableRange(0, 2000)\nbw_lut.SetSaturationRange(0, 0)\nbw_lut.SetHueRange(0, 0)\nbw_lut.SetValueRange(0, 1)\nbw_lut.Build() # effective built\n\nsagittal_colors = vtk.vtkImageMapToColors()\nsagittal_colors.SetInputConnection(reader.GetOutputPort())\nsagittal_colors.SetLookupTable(bw_lut)\nsagittal_colors.Update()\n\nsagittal = vtk.vtkImageActor()\nsagittal.GetMapper().SetInputConnection(sagittal_colors.GetOutputPort())\n# sagittal.SetDisplayExtent(128, 128, 0, 255, 0, 92)\nsagittal.ForceOpaqueOn()\n\nrender = vtk.vtkRenderer()\nrenWin = vtk.vtkRenderWindow()\niren = vtk.vtkRenderWindowInteractor()\nrender.AddActor(sagittal)\nrender.SetBackground(255, 255, 255)\nrenWin.AddRenderer( render )\niren.SetRenderWindow(renWin)\nistyle = vtk.vtkInteractorStyleTrackballCamera()\niren.SetInteractorStyle(istyle)\n\niren.Initialize()\niren.Start()\n", "repo_name": "jeanyves-yang/pydicom-renderer", "sub_path": "twoDvisualizer_vtk.py", "file_name": "twoDvisualizer_vtk.py", "file_ext": "py", "file_size_in_byte": 1124, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "vtk.vtkDICOMImageReader", "line_number": 6, "usage_type": "call"}, {"api_name": "vtk.vtkLookupTable", "line_number": 12, "usage_type": "call"}, {"api_name": "vtk.vtkImageMapToColors", "line_number": 19, "usage_type": "call"}, {"api_name": "vtk.vtkImageActor", "line_number": 24, "usage_type": "call"}, {"api_name": "vtk.vtkRenderer", "line_number": 29, "usage_type": "call"}, {"api_name": "vtk.vtkRenderWindow", "line_number": 30, "usage_type": "call"}, {"api_name": "vtk.vtkRenderWindowInteractor", "line_number": 31, "usage_type": "call"}, {"api_name": "vtk.vtkInteractorStyleTrackballCamera", "line_number": 36, "usage_type": "call"}]} +{"seq_id": "25517526162", "text": "#!/usr/bin/python3\n\"\"\"\ntakes in a URL and an email address, sends a POST request to the passed URL with the email as a parameter, and finally displays the body of the response\n\"\"\"\nimport requests\nimport sys\n\nif len(sys.argv) < 3:\n print(\"Usage: python script.py \")\n sys.exit(1)\n\nurl = sys.argv[1]\nemail = sys.argv[2]\n\ndata = {'email': email}\n\ntry:\n response = requests.post(url, data=data)\n response.raise_for_status() # Raise HTTPError for bad requests\n\n print(f'Response body: {response.text}')\nexcept requests.exceptions.HTTPError as errh:\n print(f\"HTTP Error occurred: {errh}\")\nexcept requests.exceptions.ConnectionError as errc:\n print(f\"Error Connecting: {errc}\")\nexcept requests.exceptions.Timeout as errt:\n print(f\"Timeout Error: {errt}\")\nexcept requests.exceptions.RequestException as err:\n print(f\"Request Exception occurred: {err}\")\n", "repo_name": "wambui-g/alx-higher_level_programming", "sub_path": "0x11-python-network_1/6-post_email.py", "file_name": "6-post_email.py", "file_ext": "py", "file_size_in_byte": 885, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "sys.argv", "line_number": 8, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 10, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 12, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 13, "usage_type": "attribute"}, {"api_name": "requests.post", "line_number": 18, "usage_type": "call"}, {"api_name": "requests.exceptions", "line_number": 22, "usage_type": "attribute"}, {"api_name": "requests.exceptions", "line_number": 24, "usage_type": "attribute"}, {"api_name": "requests.exceptions", "line_number": 26, "usage_type": "attribute"}, {"api_name": "requests.exceptions", "line_number": 28, "usage_type": "attribute"}]} +{"seq_id": "24554269440", "text": "import os\nfrom torch.utils.data import Dataset, Sampler\nimport torch\nimport numpy as np\nimport random\nfrom random import shuffle\nimport json\nfrom torch.nn.utils.rnn import pad_sequence\nfrom astropy.wcs import WCS, utils\nfrom astropy.coordinates import SkyCoord\nfrom astropy.io import fits\nfrom copy import deepcopy\n\n# img preprocessing\ndef img_prep(hdus, fill_value=0.0, shape=(28, 28)):\n img = deepcopy(hdus[0].data)\n img = np.nan_to_num(img, nan=fill_value)\n\n # L_2 normalization\n #norm_img = img / np.sqrt(np.sum(img**2))\n\n # min max normalization\n norm_img = (img - np.min(img)) / (np.max(img) - np.min(img))\n\n #max normalization\n #norm_img = img / np.max(img)\n \n \n # std normalization\n #norm_img = (img - np.mean(img)) / np.std(img)\n \n \n # mu-+3sigma -> 0, 1\n #norm_img = (img - np.mean(img) + 3 * np.std(img)) / (6 * np.std(img))\n \n # fill img to shape\n cur_shape = norm_img.shape\n if cur_shape == shape:\n return norm_img\n\n coords = (hdus[0].header['OIDRA'], hdus[0].header['OIDDEC'])\n coord = SkyCoord(*coords, unit='deg', frame='icrs')\n currentWCS = WCS(hdus[0].header, hdus)\n pix_coord = utils.skycoord_to_pixel(coord, currentWCS)\n pix_coord = (int(pix_coord[0]), int(pix_coord[1]))\n\n if pix_coord[1] >= int((shape[1] - 1)/2):\n y_shift = 0\n else:\n y_shift = shape[1] - cur_shape[0]\n\n if pix_coord[0] >= int((shape[0] - 1)/2):\n x_shift = 0\n else:\n x_shift = shape[0] - cur_shape[1]\n\n filled_img = np.full(shape, fill_value)\n filled_img[y_shift:cur_shape[0]+y_shift, x_shift:cur_shape[1]+x_shift] = norm_img\n \n return filled_img\n\n\n# return frames sequence by path to obj dir\ndef get_frames_seq(path):\n frames = []\n frame_names = sorted(os.listdir(path))\n for name in frame_names:\n with fits.open(f'{path}/{name}') as f:\n frame = img_prep(f)\n frames.append(frame)\n\n return torch.tensor(np.array(frames)).reshape(-1, 1, 28, 28).float()\n######################################\n\n# Datasets\nclass AllFramesDataset(Dataset):\n def __init__(self, oids, path='data/', transform=None):\n self.oids = oids\n self.imgs_paths = []\n self.transform = transform\n for oid in oids:\n imgs_names = os.listdir(f'{path}{oid}')\n self.imgs_paths += [path + f'{oid}/' + name for name in imgs_names]\n \n def __getitem__(self,idx):\n with fits.open(self.imgs_paths[idx]) as f:\n item = img_prep(f)\n res = torch.tensor(item).reshape(1, 28, 28).float()\n\n if self.transform:\n res = self.transform(res)\n \n return res\n \n def __len__(self):\n return len(self.imgs_paths)\n\n\n\nclass EmbsSequenceData(Dataset):\n def __init__(self, oids, labels, path='embeddings_100ep/', label_type='long', return_oid=False):\n self.oids = oids\n if label_type == 'long':\n self.labels = torch.tensor(labels).long()\n elif label_type == 'float':\n self.labels = torch.tensor(labels).float()\n self.obj_path = [path + f'{oid}.npy' for oid in oids]\n self.return_oid = return_oid\n \n def __getitem__(self,idx):\n embs = np.load(self.obj_path[idx])\n label = self.labels[idx]\n if self.return_oid:\n return torch.tensor(embs), label, self.oids[idx]\n else:\n return torch.tensor(embs), label\n \n def __len__(self):\n return len(self.obj_path)\n \n \n\nclass FramesSequenceData(Dataset):\n def __init__(self, oids, labels, path='data/', return_oid=False):\n self.oids = oids\n self.labels = torch.tensor(labels).long()\n self.obj_path = [path + f'{oid}/' for oid in oids]\n self.return_oid = return_oid\n \n def __getitem__(self,idx):\n item = get_frames_seq(self.obj_path[idx])\n label = self.labels[idx]\n if self.return_oid:\n return item, label, self.oids[idx]\n else:\n return item, label\n \n def __len__(self):\n return len(self.obj_path)\n\n\n\nclass BySequenceLengthSampler(Sampler):\n\n def __init__(self, data_source, \n bucket_boundaries, batch_size=64, drop_last=True, shuffle=True, return_oid=False):\n self.data_source = data_source\n ind_n_len = []\n if return_oid:\n for i, (p, _, _) in enumerate(data_source):\n ind_n_len.append( (i, p.shape[0]) )\n else:\n for i, (p, _) in enumerate(data_source):\n ind_n_len.append( (i, p.shape[0]) )\n\n self.ind_n_len = ind_n_len\n self.bucket_boundaries = bucket_boundaries\n self.batch_size = batch_size\n self.drop_last = drop_last\n self.shuffle = shuffle\n \n if self.drop_last:\n print(\"WARNING: drop_last=True, dropping last non batch-size batch in every bucket ... \")\n\n self.boundaries = list(self.bucket_boundaries)\n self.buckets_min = torch.tensor([np.iinfo(np.int32).min] + self.boundaries)\n self.buckets_max = torch.tensor(self.boundaries + [np.iinfo(np.int32).max])\n self.boundaries = torch.tensor(self.boundaries)\n\n def shuffle_tensor(self, t):\n return t[torch.randperm(len(t))]\n \n def __iter__(self):\n data_buckets = dict()\n # where p is the id number and seq_len is the length of this id number. \n for p, seq_len in self.ind_n_len:\n pid = self.element_to_bucket_id(p, seq_len)\n if pid in data_buckets.keys():\n data_buckets[pid].append(p)\n else:\n data_buckets[pid] = [p]\n\n for k in data_buckets.keys():\n\n data_buckets[k] = torch.tensor(data_buckets[k])\n\n iter_list = []\n for k in data_buckets.keys():\n\n if self.shuffle:\n t = self.shuffle_tensor(data_buckets[k])\n batch = torch.split(t, self.batch_size, dim=0)\n else:\n batch = torch.split(data_buckets[k], self.batch_size, dim=0)\n\n if self.drop_last and len(batch[-1]) != self.batch_size:\n batch = batch[:-1]\n\n iter_list += batch\n\n if self.shuffle:\n shuffle(iter_list) # shuffle all the batches so they arent ordered by bucket size\n \n for i in iter_list: \n yield i.numpy().tolist() # as it was stored in an array\n \n def __len__(self):\n return len(self.data_source)\n \n def element_to_bucket_id(self, x, seq_length):\n\n valid_buckets = (seq_length >= self.buckets_min)*(seq_length < self.buckets_max)\n bucket_id = valid_buckets.nonzero()[0].item()\n\n return bucket_id\n\n\ndef collate(examples):\n labels = []\n seq_list = []\n for frame_seq, label in examples:\n labels += [label]\n seq_list += [frame_seq]\n return pad_sequence(seq_list, batch_first=True), torch.tensor(labels)\n\ndef collate_with_oid(examples):\n labels = []\n seq_list = []\n oids = []\n for frame_seq, label, oid in examples:\n labels += [label]\n seq_list += [frame_seq]\n oids += [oid]\n return pad_sequence(seq_list, batch_first=True), torch.tensor(labels), oids\n######################################\n\ndef check_if_r(oid):\n bands = {'1':'g', '2':'r', '3':'i'}\n str_oid = str(oid)\n if len(str_oid) != 15:\n return True if bands[str_oid[4]]=='r' else False\n\n else:\n return True if bands[str_oid[3]]=='r' else False\n\n#get oids and tags (in r filter) from json\ndef get_only_r_oids(filepath):\n file = open(filepath)\n obj_list = json.load(file)\n file.close()\n\n oids = []\n tags = []\n for data in obj_list:\n if check_if_r(data['oid']):\n oids.append(data['oid'])\n tags.append(data['tags'])\n\n targets = [] # 1-artefact, 0-transient\n for tag_list in tags:\n if 'artefact' in tag_list:\n targets.append(1)\n else:\n targets.append(0)\n \n return oids, targets\n\n\n\n\n\ndef set_random_seed(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n np.random.seed(seed)\n random.seed(seed)\n torch.backends.cudnn.deterministic = True\n", "repo_name": "semtim/RB_ZTF", "sub_path": "datasets.py", "file_name": "datasets.py", "file_ext": "py", "file_size_in_byte": 8248, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "copy.deepcopy", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.nan_to_num", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 23, "usage_type": "call"}, {"api_name": "astropy.coordinates.SkyCoord", "line_number": 42, "usage_type": "call"}, {"api_name": "astropy.wcs.WCS", "line_number": 43, "usage_type": "call"}, {"api_name": "astropy.wcs.utils.skycoord_to_pixel", "line_number": 44, "usage_type": "call"}, {"api_name": "astropy.wcs.utils", "line_number": 44, "usage_type": "name"}, {"api_name": "numpy.full", "line_number": 57, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 66, "usage_type": "call"}, {"api_name": "astropy.io.fits.open", "line_number": 68, "usage_type": "call"}, {"api_name": "astropy.io.fits", "line_number": 68, "usage_type": "name"}, {"api_name": "torch.tensor", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 72, "usage_type": "call"}, {"api_name": "torch.utils.data.Dataset", "line_number": 76, "usage_type": "name"}, {"api_name": "os.listdir", "line_number": 82, "usage_type": "call"}, {"api_name": "astropy.io.fits.open", "line_number": 86, "usage_type": "call"}, {"api_name": "astropy.io.fits", "line_number": 86, "usage_type": "name"}, {"api_name": "torch.tensor", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.utils.data.Dataset", "line_number": 100, "usage_type": "name"}, {"api_name": "torch.tensor", "line_number": 104, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 111, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 114, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 116, "usage_type": "call"}, {"api_name": "torch.utils.data.Dataset", "line_number": 123, "usage_type": "name"}, {"api_name": "torch.tensor", "line_number": 126, "usage_type": "call"}, {"api_name": "torch.utils.data.Sampler", "line_number": 143, "usage_type": "name"}, {"api_name": "random.shuffle", "line_number": 160, "usage_type": "name"}, {"api_name": "torch.tensor", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.iinfo", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 166, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 167, "usage_type": "call"}, {"api_name": "numpy.iinfo", "line_number": 167, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 167, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 168, "usage_type": "call"}, {"api_name": "torch.randperm", "line_number": 171, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 185, "usage_type": "call"}, {"api_name": "torch.split", "line_number": 192, "usage_type": "call"}, {"api_name": "torch.split", "line_number": 194, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 202, "usage_type": "call"}, {"api_name": "torch.nn.utils.rnn.pad_sequence", "line_number": 224, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 224, "usage_type": "call"}, {"api_name": "torch.nn.utils.rnn.pad_sequence", "line_number": 234, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 234, "usage_type": "call"}, {"api_name": "json.load", "line_number": 249, "usage_type": "call"}, {"api_name": "torch.manual_seed", "line_number": 273, "usage_type": "call"}, {"api_name": "torch.cuda.manual_seed", "line_number": 274, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 274, "usage_type": "attribute"}, {"api_name": "numpy.random.seed", "line_number": 275, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 275, "usage_type": "attribute"}, {"api_name": "random.seed", "line_number": 276, "usage_type": "call"}, {"api_name": "torch.backends", "line_number": 277, "usage_type": "attribute"}]} +{"seq_id": "31067248981", "text": "#Self Avoiding Random Walk in 1 dimensional space @Lukas Rane\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\ndef random_walk(n):\n #this function computes the random walk in 1 dimension\n x = 0\n xdistance = [ ]\n xdistance.append(x)\n for i in range(n):\n dx = 0\n dx = random.choice([-1,1])\n if xdistance[-1] != dx:\n x += dx\n xdistance.append(x)\n return xdistance\n\n\nkb = 1.38065 * (10**-23) #boltzman constant\nentropyvec = [ ] # entropy\nx = 0 #starts at the origin\n\nnumber_of_steps_vec = [ ] #all different number of steps used\nnumber_of_walks = 1000\nnumber_of_steps_vec.append(0)\n\nfor walk_lengths in range(number_of_walks): \n xdistance = random_walk(walk_lengths)\n number_of_steps_vec.append(walk_lengths)\n S = kb * math.log(2**(number_of_walks-2))/((number_of_walks -2) **2)\n entropyvec.append(S)\n\n\naveragedistance = (abs(sum(xdistance))/len(xdistance))\nprint('The average distance is: ',averagedistance)\n\nplt.figure(1)\nplt.plot(xdistance)\nplt.xlabel('Steps')\nplt.ylabel('Distance')\nplt.title('1-d random walk')\nplt.show() ", "repo_name": "Lukasranee/Self-Avoiding-Random-Walk", "sub_path": "SelfAvoidingRandomWalk1D.py", "file_name": "SelfAvoidingRandomWalk1D.py", "file_ext": "py", "file_size_in_byte": 1147, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "random.choice", "line_number": 14, "usage_type": "call"}, {"api_name": "math.log", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}]} +{"seq_id": "24282087048", "text": "#!/usr/bin/env python\n#coding:utf-8 \n#\n#pip install psutil\n\nimport time\nimport sys\ntry:\n import psutil\nexcept ImportError:\n print('Error: psutil module not found!')\n exit()\n\ndef get_key(): #每個介面累積流量Bytes\n key_info = psutil.net_io_counters(pernic=True).keys() # 網路介面訊息區域網路,bluebooth,WiFi\n recv = {}\n sent = {}\n #recv.setdefault(key, psutil.net_io_counters(pernic=False).bytes_recv) #總接收數\n #sent.setdefault(key, psutil.net_io_counters(pernic=False).bytes_sent) #總發射數\n for key in key_info:\n recv.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_recv) #各個介面累積流量Bytes\n sent.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_sent) #各個介面累積流量Bytes\n return key_info, recv, sent\n\ndef get_rate(func): #計算每個介面每秒收送速率MB/1s\n key_info, old_recv, old_sent = func() # 上一秒收集的数据\n time.sleep(1) \n key_info, now_recv, now_sent = func() # 当前所收集的数据\n net_in = {}\n net_out = {}\n for key in key_info:\n net_in.setdefault(key, (now_recv.get(key) - old_recv.get(key)) / 1024 / 1024) #每秒接收速率MB\n net_out.setdefault(key, (now_sent.get(key) - old_sent.get(key)) / 1024 / 1024) #每秒发送速率MB \n #old_recv.setdefault(key, now_recv.get(key))\n #old_sent.setdefault(key, now_sent.get(key))\n return key_info, net_in, net_out\n\ndef get_process_info(): #取得PID info\n from os.path import basename\n from psutil import net_connections,Process\n msg=\"\"\n for x in net_connections('all'):\n laddr, raddr, status, pid=x[3:]\n if not raddr:\n continue\n try:\n filename = basename(Process(pid).exe()) #專注於exe程序\n except:\n pass\n else:\n #msg += '''Process = {} Local = {} Remote = {} Connection = {}\\n'''.format(filename, laddr, raddr, status) \n msg += '''Process: {} Local: {} Remote: {} Connection: {}\\n'''.format(filename, laddr, raddr, status) \n return msg\n\n#net = psutil.net_io_counters() # 目前網路連線訊息(可能很多)\n#print(net)\n#net = psutil.net_connections() # 目前網路連線訊息(可能很多)\n#print(net)\nwhile True:\n time.sleep(10) #每10秒鐘運行此程序\n try:\n ip_file = open('networkstatus.txt','a')\n\n #key_info, net_in, net_out = get_key() #取出收送累積總量Bytes\n #ip_file.write(time.strftime(\"[%Y-%m-%d %H:%M:%S]\")+'\\n')\n #msg='''Interface: {}\\nReceived: {} Byte\\nTransmit: {} Byte\\n'''.format( key, net_in.get(key), net_out.get(key))\n #ip_file.write(msg)\n\n key_info, net_in, net_out = get_rate(get_key) #每秒收送速率MB\n for key in key_info: #各網路介面(區域網路2,bluebooth,WiFi,vEthernet)\n \n if net_in.get(key) >2 or net_out.get(key) >2: #2MB/unit\n ip_file.write(time.strftime(\"[%Y-%m-%d %H:%M:%S]\")+'\\n')\n msg='''Interface: {}\\nReceived: {} MB/s\\nTransmit: {} MB/s\\n'''.format( key, net_in.get(key), net_out.get(key))\n ip_file.write(msg)\n\n msg = get_process_info() #目前運行程序/local:IP/remote:IP 格式與上述不同\n ip_file.write(msg)\n ip_file.write('\\n')\n #msg='''Interface = {}\\nReceived = {} MB/s\\nTransmit = {} MB/s\\n'''.format( key, net_in.get(key), net_out.get(key)) #for get_rate\n #msg='''Interface = {}\\nReceived = {} Byte\\nTransmit = {} Byte\\n'''.format( key, net_in.get(key), net_out.get(key)) \n #ip_file.write(msg)\n \n ip_file.close() \n except KeyboardInterrupt:\n exit()", "repo_name": "louisopen/NetworkStatusWeb", "sub_path": "NetworkStatus.py", "file_name": "NetworkStatus.py", "file_ext": "py", "file_size_in_byte": 3785, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "26", "api": [{"api_name": "psutil.net_io_counters", "line_number": 15, "usage_type": "call"}, {"api_name": "psutil.net_io_counters", "line_number": 21, "usage_type": "call"}, {"api_name": "psutil.net_io_counters", "line_number": 22, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 27, "usage_type": "call"}, {"api_name": "psutil.net_connections", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 47, "usage_type": "call"}, {"api_name": "psutil.Process", "line_number": 47, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 60, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 73, "usage_type": "call"}]} +{"seq_id": "21851532160", "text": "# -*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\n\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nGITHUB_REQUIREMENT = \"{name} @ git+https://github.com/{author}/{name}.git\"\nREQUIREMENTS = [\n \"cython\",\n \"segmentation-models\",\n \"pydensecrf\",\n # GITHUB_REQUIREMENT.format(\n # author=\"berkeley-hipie\",\n # name=\"HIPIE\",\n # ),\n \"imgaug\",\n \"pycocotools\",\n \"pillow\",\n \"tensorflow==2.11.0\",\n \"opencv-python\",\n \"numpy\",\n \"h5py\",\n \"inflection\",\n]\n\nsetup(\n name=\"core-analysis\",\n version=\"0.0.1\",\n author=\"Victor Silva dos Santos, Jérome Simon\",\n author_email=\"victor.santos@inrs.ca, jerome.simon@inrs.ca\",\n description=\"Core analysis\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/groupeLIAMG/core-analysis\",\n packages=find_packages(),\n install_requires=REQUIREMENTS,\n setup_requires=[\"setuptools-git\"],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires=\"==3.7.16\",\n)\n", "repo_name": "groupeLIAMG/core-analysis", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 1188, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "setuptools.setup", "line_number": 28, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 37, "usage_type": "call"}]} +{"seq_id": "36664730016", "text": "import csv\nimport datetime\n\nfrom config import SWING_PATH, WHOOP_PATH\n\n\nclass Date:\n \"\"\"This class holds a date value, and all swings and health_data from that date\"\"\"\n def __init__(self, date):\n \"\"\"Initialize variables\"\"\"\n self.date = date\n self.swings = []\n self.health_data = None\n\n \"\"\"Methods called by default\"\"\"\n self.load_swings() # loads all swings of same date\n self.load_health_data() # loads health data of same date\n\n def load_swings(self):\n \"\"\"Reads SWING_PATH (csv file) and appends each swing to a list of all swings\"\"\"\n with open(SWING_PATH, mode='r', encoding='utf-8-sig') as swingFile: # open Blast file\n swings = csv.DictReader(swingFile) # read csv and store values as dict\n for swing in swings: # iterate through swings\n if self.date in datetime.datetime.strptime(swing.get(\"Date\"), \"%b %d, %Y %H:%M:%S %p\").strftime(\n \"%Y-%m-%d\"):\n self.swings.append(swing) # append swing if date equals date on Blast file\n\n def load_health_data(self):\n \"\"\"Reads WHOOP_PATH (csv file) and assigns data to self.health_data\"\"\"\n with open(WHOOP_PATH, mode='r', encoding='utf-8-sig') as healthFile: # open Whoop file\n health_data = csv.DictReader(healthFile) # read csv and store values as dict\n for data in health_data: # iterate through health_data\n if self.date in datetime.datetime.strptime(data.get(\"Date\"), \"%Y-%m-%d\").strftime(\"%Y-%m-%d\"):\n self.health_data = data # assign this data if date equals date on whoop file\n break\n\n def get_avg_value(self, value_name):\n \"\"\"Returns the average value of chosen parameter\"\"\"\n total_value = 0 # variable to track totals of all values\n for swing in self.swings: # iterate through all swings\n total_value += float(swing.get(value_name)) # total_value updated\n return total_value / len(self.swings) # return the average\n\n def get_max_value(self, value_name):\n \"\"\"Returns the maximum value of chosen parameter\"\"\"\n max_value = 0 # variable to track the maximum value\n for swing in self.swings: # iterate through all swings\n if float(swing.get(value_name)) > max_value: # if next value is greater than current max\n max_value = float(swing.get(value_name)) # update max_value\n return max_value\n", "repo_name": "apc721/whoopBlast", "sub_path": "date.py", "file_name": "date.py", "file_ext": "py", "file_size_in_byte": 2497, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "26", "api": [{"api_name": "config.SWING_PATH", "line_number": 21, "usage_type": "argument"}, {"api_name": "csv.DictReader", "line_number": 22, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 24, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 24, "usage_type": "attribute"}, {"api_name": "config.WHOOP_PATH", "line_number": 30, "usage_type": "argument"}, {"api_name": "csv.DictReader", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 33, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 33, "usage_type": "attribute"}]} +{"seq_id": "4101271389", "text": "import os\nimport pickle\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom plots.utils import setup_figure\n\n\ndef smooth_data(data, smoothing_weight=0.99):\n last = data[0]\n for i in range(1, data.shape[0]):\n data[i] = last * smoothing_weight + (1 - smoothing_weight) * data[i]\n last = data[i]\n\n return data\n\n\ndef main():\n figure_name = setup_figure(name='reward_distribution.pdf')\n\n budget_percent = 0.4 # 0.4 or 0.5\n num_agents = 7 # 3, 7, 10, 15, or 20\n queue_len = 25 # 25, 50 or 75\n file_name = os.path.join(f'../results/{budget_percent}_{num_agents}_{queue_len}.txt')\n with open(file_name, 'rb') as f:\n rewards = pickle.load(f)\n\n random_rewards = rewards[5001]\n greedy_rewards = rewards[5002]\n\n if len(np.array(rewards[:5003]).shape) == 2:\n rewards = np.array(rewards[:5003])\n # teleport_rewards1 = rewards[5003]\n # teleport_rewards2 = rewards[5004]\n rewards = rewards[:5000]\n else:\n for i in range(len(rewards)):\n if len(rewards[i]) != num_agents:\n break\n rewards = np.array(rewards[:i])\n\n fig, ax = plt.subplots()\n width = 0.35\n ax.bar(np.arange(num_agents) - width / 2, random_rewards, width / 2, label='Random')\n ax.bar(np.arange(num_agents), greedy_rewards, width / 2, label='Greedy')\n ax.bar(np.arange(num_agents) + width / 2, rewards[-1, :], width / 2, label='Model')\n lgd = ax.legend(bbox_to_anchor=(1.05, 1))\n ax.set_xticks(range(num_agents))\n ax.set_xticklabels([f'Agent {i}' for i in range(num_agents)], rotation=45)\n plt.savefig(fname=figure_name, dpi=300, bbox_extra_artists=(lgd,), bbox_inches='tight')\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n", "repo_name": "aduttaUNF12/MFG", "sub_path": "plots/reward_distribution.py", "file_name": "reward_distribution.py", "file_ext": "py", "file_size_in_byte": 1741, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "26", "api": [{"api_name": "plots.utils.setup_figure", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}]} +{"seq_id": "28228209533", "text": "import logging\nimport os\nimport pickle\n\nimport torch\nfrom d2go.config import CfgNode as CN\nfrom detectron2.utils.file_io import PathManager\nfrom mobile_cv.torch.utils_pytorch import comm\nfrom torch.cuda._memory_viz import segment_plot, trace_plot\n\nlogger: logging.Logger = logging.getLogger(__name__)\n\n\ndef add_memory_profiler_configs(_C: CN):\n _C.MEMORY_PROFILER = CN()\n _C.MEMORY_PROFILER.ENABLED = False\n # max number of trace entries in memory snapshot\n _C.MEMORY_PROFILER.TRACE_MAX_ENTRIES = 1000000\n # Configs to be used by d2go.utils.gpu_memory_profiler.D2GoGpuMemorySnapshot\n # determine the number of iterations to log memory snapshots for\n _C.MEMORY_PROFILER.LOG_N_STEPS = 3\n # determine at what iteration to start recording gpu memory\n _C.MEMORY_PROFILER.LOG_DURING_TRAIN_AT = 550\n\n\ndef add_zoomer_default_config(_C: CN):\n _C.ZOOMER = CN()\n _C.ZOOMER.ENABLE_STACK_TRACING = (\n False # Do not enable by default, since it may cause performance regression\n )\n _C.ZOOMER.ENABLE_MEMORY_PROFILING = False\n\n\ndef omm_logger_wrapper(output_dir):\n def oom_logger(\n device: int, alloc: int, device_alloc: int, device_free: int\n ) -> None:\n \"\"\"\n Log memory snapshot in the event of CUDA OOM.\n \"\"\"\n logger.info(\n f\"Saving memory snapshot device: {device}, alloc: {alloc}, device_alloc: {device_alloc}, device_free: {device_free}\"\n )\n try:\n log_memory_snapshot(output_dir, file_prefix=\"oom\")\n except Exception as e:\n logger.error(f\"Failed to log memory snapshot during OOM {e}\")\n\n return oom_logger\n\n\ndef log_memory_snapshot(output_dir: str, file_prefix: str = \"\") -> None:\n \"\"\"\n Log memory snapshots to output_dir\n \"\"\"\n if not torch.cuda.is_available():\n logger.info(\"CUDA unavailable. Not logging snapshot\")\n return\n\n try:\n rank = comm.get_rank()\n save_dir = os.path.join(\n output_dir, \"memory_snapshot\", f\"{file_prefix}_rank{rank}\"\n )\n logger.info(f\"Logging memory snapshot to {save_dir}\")\n snapshot = torch.cuda.memory._snapshot()\n dump_snapshot(save_dir, snapshot)\n except Exception as e:\n logger.error(f\"Failed to log memory snapshot to {save_dir}: {e}\")\n\n\ndef dump_snapshot(save_dir: str, snapshot):\n \"\"\"\n Dump memory snapshot and useful plots to save_dir.\n This is a rewrite of torch.cuda.memory._dump_snapshot() with PathManager.\n \"\"\"\n if not PathManager.exists(save_dir):\n PathManager.mkdirs(save_dir)\n with PathManager.open(os.path.join(save_dir, \"snapshot.pickle\"), \"wb\") as f:\n pickle.dump(snapshot, f)\n with PathManager.open(os.path.join(save_dir, \"trace_plot.html\"), \"w\") as f:\n f.write(trace_plot(snapshot))\n with PathManager.open(os.path.join(save_dir, \"segment_plot.html\"), \"w\") as f:\n f.write(segment_plot(snapshot))\n logger.info(f\"Saved memory snapshot to {save_dir}\")\n\n\ndef record_memory_history(trace_max_entries=1000000) -> None:\n \"\"\"\n Start recording memory history and stack traces.\n \"\"\"\n if not torch.cuda.is_available():\n logger.info(\"CUDA unavailable. Not recording memory history\")\n return\n\n torch.cuda.memory._record_memory_history(\n enabled=\"all\", max_entries=trace_max_entries\n )\n logger.info(\"Started recording memory history\")\n\n\ndef attach_oom_logger(output_dir, trace_max_entries=1000000) -> None:\n \"\"\"\n Start recording memory history and attach the OOM logger.\n \"\"\"\n if not torch.cuda.is_available():\n logger.info(\"CUDA unavailable. Not attaching OOM logger\")\n return\n\n record_memory_history(trace_max_entries)\n torch._C._cuda_attach_out_of_memory_observer(omm_logger_wrapper(output_dir))\n logger.info(\"Attached GPU OOM logger\")\n", "repo_name": "facebookresearch/d2go", "sub_path": "d2go/utils/gpu_memory_profiler.py", "file_name": "gpu_memory_profiler.py", "file_ext": "py", "file_size_in_byte": 3831, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 811, "dataset": "github-code", "pt": "26", "api": [{"api_name": "logging.Logger", "line_number": 11, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 11, "usage_type": "call"}, {"api_name": "d2go.config.CfgNode", "line_number": 14, "usage_type": "name"}, {"api_name": "d2go.config.CfgNode", "line_number": 15, "usage_type": "call"}, {"api_name": "d2go.config.CfgNode", "line_number": 26, "usage_type": "name"}, {"api_name": "d2go.config.CfgNode", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 56, "usage_type": "attribute"}, {"api_name": "mobile_cv.torch.utils_pytorch.comm.get_rank", "line_number": 61, "usage_type": "call"}, {"api_name": "mobile_cv.torch.utils_pytorch.comm", "line_number": 61, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path", "line_number": 62, "usage_type": "attribute"}, {"api_name": "torch.cuda.memory._snapshot", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 66, "usage_type": "attribute"}, {"api_name": "detectron2.utils.file_io.PathManager.exists", "line_number": 77, "usage_type": "call"}, {"api_name": "detectron2.utils.file_io.PathManager", "line_number": 77, "usage_type": "name"}, {"api_name": "detectron2.utils.file_io.PathManager.mkdirs", "line_number": 78, "usage_type": "call"}, {"api_name": "detectron2.utils.file_io.PathManager", "line_number": 78, "usage_type": "name"}, {"api_name": "detectron2.utils.file_io.PathManager.open", "line_number": 79, "usage_type": "call"}, {"api_name": "detectron2.utils.file_io.PathManager", "line_number": 79, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 79, "usage_type": "call"}, {"api_name": "os.path", "line_number": 79, "usage_type": "attribute"}, {"api_name": "pickle.dump", "line_number": 80, "usage_type": "call"}, {"api_name": "detectron2.utils.file_io.PathManager.open", "line_number": 81, "usage_type": "call"}, {"api_name": "detectron2.utils.file_io.PathManager", "line_number": 81, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 81, "usage_type": "call"}, {"api_name": "os.path", "line_number": 81, "usage_type": "attribute"}, {"api_name": "torch.cuda._memory_viz.trace_plot", "line_number": 82, "usage_type": "call"}, {"api_name": "detectron2.utils.file_io.PathManager.open", "line_number": 83, "usage_type": "call"}, {"api_name": "detectron2.utils.file_io.PathManager", "line_number": 83, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 83, "usage_type": "call"}, {"api_name": "os.path", "line_number": 83, "usage_type": "attribute"}, {"api_name": "torch.cuda._memory_viz.segment_plot", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 92, "usage_type": "attribute"}, {"api_name": "torch.cuda.memory._record_memory_history", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 96, "usage_type": "attribute"}, {"api_name": "torch.cuda.is_available", "line_number": 106, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 106, "usage_type": "attribute"}, {"api_name": "torch._C._cuda_attach_out_of_memory_observer", "line_number": 111, "usage_type": "call"}, {"api_name": "torch._C", "line_number": 111, "usage_type": "attribute"}]} +{"seq_id": "3556672694", "text": "import os\nimport logging\nimport copy\n\nfrom contextlib import contextmanager\nfrom filerockclient.databases.sqlite_driver import SQLiteDB\n\nTABLENAME = 'Override me!'\nKEY = u'pathname'\nSCHEMA = [u'pathname Text', u'field2 Text', u'filed3 Text']\n\n\nclass WrongNumberOfParameters(Exception):\n pass\n\n\nclass NonexistentKey(Exception):\n pass\n\n\nclass MissingSchema(Exception):\n pass\n\n\nclass MissingKey(Exception):\n pass\n\n\nclass NoSuchTable(Exception):\n pass\n\n\nclass UnknownColumn(Exception):\n pass\n\n\nclass WrongSchema(Exception):\n pass\n\n\nclass AbstractCache(object):\n \"\"\"A generic SQL-based store.\n\n \"Caches\" are databases used by FileRock to persistently store\n several kinds of data. Each database (which is implemented with\n SQLite) contains a set of \"records\", identified by a column called\n \"key\". A cache can be configured with the following parameters:\n\n TABLE: name of the cache (and of the underlying SQL table)\n SCHEMA: list of string, each defining a field of the records\n KEY: the field that identifies the records.\n\n Usually AbstractCache isn't used as is, but instead it's subclassed\n into \"concrete\" caches, which may expose higher-level functionalities.\n A common pattern in defining caches is defining the module-level\n constants TABLE, SCHEMA, KEY, making the constructor use them.\n\n @param database_file:\n absolute filesystem pathname to a file which\n will contain the database.\n @param table_name:\n name of the cache.\n @param table_schema:\n List of strings ['col_name col_type', 'col2_name col2_type']\n defining the fields of the records.\n @param key:\n Name of the field that identifies the records.\n \"\"\"\n\n def __init__(self,\n database_file, table_name, table_schema, key, logger=None):\n\n if logger is None:\n self.logger = logging.getLogger()\n self.logger.addHandler(logging.NullHandler())\n else:\n self.logger = logger\n self._table_name = table_name\n self._autocommit = True\n self._key = None\n self._columns = None\n self._schema = None\n self._db = SQLiteDB(database_file)\n self._filename = database_file\n self.recreated = False\n # Note: self.schema is a property object\n self.schema = table_schema\n self._check_schema() # possibly creating the table if it does not exist\n # Note: self.key is a property object\n self.key = key\n self._create_index_if_needed()\n \n # Remember not to vacuum from any other method than the constructor,\n # since it makes any open transaction commit!\n self._execute(\"VACUUM\")\n\n def _check_schema(self):\n \"\"\"\n Check the given table schema with the one present on db.\n\n Raises exception if declared table is not there or the schema is\n wrong.\n \"\"\"\n data = self._query(u\"SELECT sql FROM sqlite_master WHERE \"\n \"type='table' and name=?\", [self._table_name])\n if len(data) < 1:\n raise NoSuchTable()\n sql = data[0][0]\n sql = sql.split('(')[1]\n sql = sql.split(')')[0]\n sql = sql.split(',')\n found_schema = [' '.join(column_def.split()) for column_def in sql]\n if self._schema != found_schema:\n raise WrongSchema(\"expected: %s, found: %s\"\n % (self._schema, found_schema))\n\n @property\n def table_name(self):\n return self._table_name\n\n @property\n def schema(self):\n return self._schema\n\n @schema.setter\n def schema(self, schema):\n schema = [' '.join(column_def.split()) for column_def in schema]\n self._schema = schema\n self._schema_tostr = ', '.join(self._schema)\n self._columns = [string.split()[0] for string in self._schema]\n self._recreate_db_if_not_exists()\n\n @property\n def key(self):\n return self._key\n\n @key.setter\n def key(self, key):\n if self._columns is None:\n raise MissingSchema(u'Please define a schema')\n msg = u'key %s is not part of %s table' % (key, self.table_name)\n if key not in self._columns:\n raise NonexistentKey(msg)\n self._key = key\n self._key_index = self._columns.index(key)\n\n def _recreate_db_if_not_exists(self):\n must_recreate = False\n\n if not os.path.exists(self._filename):\n must_recreate = True\n else:\n try:\n self._db.query(\"SELECT * FROM %s LIMIT 1\" % self.table_name)\n must_recreate = False\n except Exception:\n must_recreate = True\n\n if must_recreate:\n self.logger.debug(\n u\"Initializing a new database \"\n u\"because no valid database could be found.\")\n self._initialize_new()\n self.recreated = True\n\n def _create_index_if_needed(self):\n \"\"\"Assuming the database is there and the schema is ok, \n it add a key index if it is not present.\"\"\"\n\n data=self._query(u\"SELECT sql FROM sqlite_master \"\n u\"WHERE type='index' and name=?\", \n [self._key+\"_index\"])\n \n if len(data)==0:\n self.logger.debug(\"adding index to %s\" % self._table_name)\n self._execute(u'CREATE INDEX \"%s_index\" on %s (%s ASC)' %\n (self._key, self._table_name, self._key))\n\n\n def _initialize_new(self):\n \"\"\"Initialize a new database table.\n \"\"\"\n self.logger.debug(u'Creating database table...')\n args = (self.table_name, self._schema_tostr)\n self._execute(u'CREATE TABLE %s (%s)' % args)\n self.logger.debug(u'Database table successfully created.')\n\n def update_record(self, *record):\n \"\"\"\n Write a record into the cache.\n\n If a record with the same key values already exists, it is\n overwritten.\n Raises WrongNumberOfParameters exception if a wrong number of\n fields is passed.\n\n @param record: a tuple of values (column1_value, column2_value, ...)\n \"\"\"\n number_of_field = len(record)\n if number_of_field != len(self.schema):\n raise WrongNumberOfParameters(\n u'Passed %s parameters, %s were required in the'\n ' following schema: %s'\n % (len(record), len(self.schema), self.schema))\n\n if not self.exist_record(record[self._key_index]):\n self._insert_record(record)\n else:\n self._update_record(record)\n\n def _insert_record(self, record):\n fields = ', '.join(['?'] * len(record))\n statement = ''.join([u'INSERT INTO %s VALUES (', fields, ')'])\n self._execute(statement % self.table_name, record)\n\n def _update_record(self, record):\n columns = u', '.join([\"%s = ?\" % column for column in self._columns])\n statement = u\"UPDATE %s SET %s WHERE %s = ?\"\n statement = statement % (self.table_name, columns, self.key)\n values = record + (record[self._key_index],)\n self._execute(statement, values)\n\n def update_record_fields(self, key_value, **fields):\n \"\"\"\n Updates the fields specified by the \"keyword args\" for the row\n with the given key_value.\n\n @param key_value: the value of the key column\n @param **fields: parameters with format: field_name=value\n \"\"\"\n if len(fields) == 0:\n raise WrongNumberOfParameters(\n u'You should pass at least 1 column to update')\n if len(fields) >= len(self._schema):\n raise WrongNumberOfParameters(\n u'You pass %s parameters, %s was required in the'\n ' following schema %s'\n % (len(fields), len(self.schema), self.schema))\n for key in fields.keys():\n if key not in self._columns:\n raise UnknownColumn(u'Column %s not in %s table'\n % (key, self._table_name))\n\n columns = u', '.join([\"%s = ?\" % column for column in fields])\n statement = u'UPDATE %s SET %s WHERE %s = ?' \\\n % (self.table_name, columns, self.key)\n values = fields.values()\n values.append(key_value)\n self._execute(statement, tuple(values))\n\n def delete_record(self, key_value):\n \"\"\"\n Delete a record from db with the given key value.\n\n @param key_value: the value of the key of the row to delete.\n \"\"\"\n statement = u'DELETE FROM %s WHERE %s=?' % (self.table_name, self.key)\n self._execute(statement, (key_value,))\n\n def delete_records(self, key_values):\n \"\"\"\n Delete all records with the given key values.\n\n @param key_values: an array of key values of the rows to delete\n \"\"\"\n if len(key_values) == 0:\n return\n statement = u\"DELETE FROM %s where %s=?\" % (self.table_name, self.key)\n eargs = [(unicode(x),) for x in key_values]\n self._execute(statement, eargs)\n\n def exist_record(self, key_value):\n \"\"\"\n Returns true if a there is a row with the given key value.\n\n @param key_value: the value of the key you are looking for\n @return: boolean\n \"\"\"\n statement = \"SELECT COUNT(*) FROM %s \"\"WHERE %s = ?\" \\\n % (self.table_name, self.key)\n result = self._query(statement, (key_value,))\n count = result[0][0]\n return count > 0\n\n def get_record(self, key_value):\n \"\"\"\n Return the record with the given key value.\n\n @param key_value: the value of the key column\n @return: a tuple representing the first row found with the given key\n or None if no row was found\n \"\"\"\n stm = u'SELECT * FROM %s WHERE %s=?' % (self.table_name, self.key)\n result = self._query(stm, [key_value])\n if len(result) == 0:\n return None\n if len(result) > 1:\n self.logger.warning(\n u'More than one record found for %s=\"%s\", returning the first.'\n % (self.key, key_value))\n return result[0]\n\n def get_all_records(self):\n return self._query(u\"SELECT * FROM %s\" % self.table_name)\n\n def get_all_keys(self):\n res = self._query(u\"SELECT %s FROM %s\" % (self.key, self.table_name))\n res = [record[0] for record in res]\n return res\n\n def clear(self):\n \"\"\" Delete all records from the database \"\"\"\n self._execute(u\"DELETE FROM %s\" % self.table_name)\n\n def destroy(self):\n \"\"\" Delete DB File \"\"\"\n if os.path.exists(self._filename):\n os.remove(self._filename)\n\n def _execute(self, statement, parameters=[]):\n if not self._autocommit:\n self._db.execute(statement, parameters)\n else:\n with self.transaction() as transactional_self:\n transactional_self._db.execute(statement, parameters)\n\n def _query(self, statement, parameters=[]):\n try:\n return self._db.query(statement, parameters)\n finally:\n if self._autocommit:\n self._db.close()\n\n @contextmanager\n def transaction(self, *caches_to_attach):\n \"\"\"Open a transaction on this cache.\n\n Modifications to a cache usually are immediate, that is, they\n get persisted just after being made. However sometimes there is\n need for making several modifications in a transactional fashion,\n so to rollback if any error happens during the process.\n Any modification to the cache made inside this context manager\n is automatically committed when the context is finished and is\n automatically rollbacked if an exception is raised.\n\n Calling the context manager returns a clone of this cache, which\n must be used in place of the original one in order for the\n transaction to be effective.\n E.g.: with mycache.transaction() as transactional_mycache: ...\n If other caches are passed to the context manager call, they\n are \"attached\" to this and become part of the same transaction\n (that is, either all caches are modified or none of them).\n E.g: with cache1.transaction(cache2) as (trans_c1, trans_c2): ...\n \"\"\"\n\n transactional_self = copy.copy(self)\n transactional_self._autocommit = False\n transactional_self._db.begin_transaction()\n\n attached_caches = [transactional_self]\n\n for cache in caches_to_attach:\n statement = \"ATTACH DATABASE '%s' as %s\" \\\n % (cache._filename, cache.__class__.__name__)\n transactional_self._execute(statement)\n transactional_cache = copy.copy(cache)\n transactional_cache._autocommit = False\n transactional_cache._db = self._db\n transactional_cache._table_name = \"%s.%s\" \\\n % (cache.__class__.__name__, cache._table_name)\n attached_caches.append(transactional_cache)\n\n try:\n if not caches_to_attach:\n yield transactional_self\n else:\n yield tuple(attached_caches)\n except:\n transactional_self._db.rollback_transaction()\n raise\n else:\n transactional_self._db.commit_transaction()\n finally:\n transactional_self._db.close()\n\n\nif __name__ == '__main__':\n pass\n", "repo_name": "filerock/FileRock-Client", "sub_path": "filerockclient/databases/abstract_cache.py", "file_name": "abstract_cache.py", "file_ext": "py", "file_size_in_byte": 13755, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 133, "dataset": "github-code", "pt": "26", "api": [{"api_name": "logging.getLogger", "line_number": 74, "usage_type": "call"}, {"api_name": "logging.NullHandler", "line_number": 75, "usage_type": "call"}, {"api_name": "filerockclient.databases.sqlite_driver.SQLiteDB", "line_number": 83, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 150, "usage_type": "call"}, {"api_name": "os.path", "line_number": 150, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 317, "usage_type": "call"}, {"api_name": "os.path", "line_number": 317, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 318, "usage_type": "call"}, {"api_name": "copy.copy", "line_number": 356, "usage_type": "call"}, {"api_name": "copy.copy", "line_number": 366, "usage_type": "call"}, {"api_name": "contextlib.contextmanager", "line_number": 334, "usage_type": "name"}]} +{"seq_id": "10162088618", "text": "import csv\nimport pickle\nimport random\nimport requests.exceptions\n\nimport os\nimport openai\nfrom django.contrib import auth, messages\nfrom django.contrib.auth.models import User\nfrom django.http import request, HttpResponse, HttpResponseServerError\nfrom django.shortcuts import redirect, render\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.hashers import make_password\nfrom django.urls import reverse\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\n\nfrom .models import UserDet, Data, DocDet, Researchers\nfrom django.utils import timezone\nfrom requests import session\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import metrics\n\n#openai.api_key = os.environ[\"OPENAI_API_KEY\"]\nopenai.api_key = \"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\"\n\n\n# Create your views here.\n\ndef login_user(request):\n title = 'Login'\n context = {\"title\": title}\n if request.method == 'POST':\n username = request.POST['username']\n password = request.POST['password']\n user = auth.authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n auth.login(request, user)\n if user.is_superuser:\n return redirect('dashboard1')\n else:\n return redirect('dashboard')\n else:\n messages.info(request, 'Your account is inactive and cannot login')\n return redirect('login_user')\n else:\n messages.info(request, 'Invalid Username or Password')\n return redirect('login_user')\n else:\n return render(request, 'login.html', context)\n\n\ndef logout_user(request):\n auth.logout(request)\n return redirect('index')\n\n\ndef home(request):\n return redirect('index')\n\n\ndef index(request):\n title = \"Home\"\n return render(request, 'index.html', context={'title': title})\n\n\n##@login_required(login_url='/login_user')\ndef dashboard(request):\n if request.user.is_authenticated:\n title = \"Dashboard\"\n return render(request, 'dashboard.html', context={'title': title})\n else:\n return redirect('login_user')\n\n\n##@login_required(login_url='/login_user')\ndef dashboard1(request):\n if request.user.is_authenticated:\n title = \"Dashboard\"\n users = DocDet.objects.all()\n return render(request, 'dashboard1.html', context={'title': title, \"users\": users})\n else:\n return redirect('login_user')\n\n\n# @login_required(login_url='/login_user')\ndef clients(request):\n if request.user.is_authenticated:\n title = \"Clients\"\n try:\n clients = UserDet.objects.all()\n except UserDet.DoesNotExist:\n clients = None\n return render(request, 'clients.html', context={'title': title, \"clients\": clients})\n else:\n return redirect('login_user')\n\n\n# @login_required(login_url='/login_user')\ndef report(request):\n if request.user.is_authenticated:\n title = \"Reports\"\n try:\n reports = Data.objects.all()\n except Data.DoesNotExist:\n reports = None\n return render(request, 'reports.html', context={'title': title, \"reports\": reports})\n else:\n return redirect('login_user')\n\n\n# @login_required(login_url='/login_user')\ndef detailreport(request, did):\n if request.user.is_authenticated:\n title = \"Detail Report\"\n gender = Data.objects.values('sex').get(did=did)\n sex = gender.get('sex')\n cgender = \"\"\n if sex == 1:\n cgender = \"Male\"\n elif sex == 0:\n cgender = \"Female\"\n cage = Data.objects.values('age').get(did=did)\n age = cage.get('age')\n chistory = Data.objects.values('history').get(did=did)\n history = chistory.get('history')\n chypertension = Data.objects.values('hypertension').get(did=did)\n hypertension = chypertension.get('hypertension')\n cinactivity = Data.objects.values('inactivity').get(did=did)\n inactivity = cinactivity.get('inactivity')\n ccardiovascular = Data.objects.values('cardiovascular').get(did=did)\n cardiovascular = ccardiovascular.get('cardiovascular')\n chyperlidermia = Data.objects.values('hyperlidermia').get(did=did)\n hyperlidermia = chyperlidermia.get('hyperlidermia')\n calcohol = Data.objects.values('alcohol').get(did=did)\n alcohol = calcohol.get('alcohol')\n ctia = Data.objects.values('tia').get(did=did)\n tia = ctia.get('tia')\n cmsyndrome = Data.objects.values('msyndrome').get(did=did)\n msyndrome = cmsyndrome.get('msyndrome')\n catherosclerosis = Data.objects.values('atherosclerosis').get(did=did)\n atherosclerosis = catherosclerosis.get('atherosclerosis')\n caf = Data.objects.values('af').get(did=did)\n af = caf.get('af')\n clvh = Data.objects.values('lvh').get(did=did)\n lvh = clvh.get('lvh')\n cdiabetes = Data.objects.values('diabetes').get(did=did)\n diabetes = cdiabetes.get('diabetes')\n csmoking = Data.objects.values('smoking').get(did=did)\n smoking = csmoking.get('smoking')\n cstroke = Data.objects.values('stroke').get(did=did)\n stroke = cstroke.get('stroke')\n cadvice = Data.objects.values('advice').get(did=did)\n advice = cadvice.get('advice')\n cphone = Data.objects.values('phone_id').get(did=did)\n phone = cphone.get('phone_id')\n model = pickle.load(open('model.pkl', 'rb'))\n probability = model.predict_proba([\n [history, hypertension, inactivity, cardiovascular, hyperlidermia, alcohol, tia, msyndrome, atherosclerosis,\n sex, age, af,\n lvh, diabetes, smoking]])\n prob = probability[0][1]\n prob = float(prob * 100)\n prob =round(prob,2)\n\n return render(request, 'detailreport.html',\n context={'title': title, \"sex\": sex, \"age\": age, \"history\": history, \"hypertension\": hypertension,\n \"inactivity\": inactivity, \"cardiovascular\": cardiovascular,\n \"hyperlidermia\": hyperlidermia, \"alcohol\": alcohol, \"tia\": tia, \"msyndrome\": msyndrome,\n \"atherosclerosis\": atherosclerosis, \"af\": af, \"lvh\": lvh,\n \"diabetes\": diabetes, \"smoking\": smoking, \"stroke\": stroke, \"percent\": prob,\n \"phone\": phone,\n \"advice\": advice, \"cgender\": cgender, \"did\": did})\n else:\n return redirect('login_user')\n\n\n# @login_required(login_url='/login_user')\ndef printreport(request, did):\n if request.user.is_authenticated:\n title = \"Print Report\"\n gender = Data.objects.values('sex').get(did=did)\n sex = gender.get('sex')\n cgender = \"\"\n if sex == 1:\n cgender = \"Male\"\n elif sex == 0:\n cgender = \"Female\"\n cage = Data.objects.values('age').get(did=did)\n age = cage.get('age')\n chistory = Data.objects.values('history').get(did=did)\n history = chistory.get('history')\n chypertension = Data.objects.values('hypertension').get(did=did)\n hypertension = chypertension.get('hypertension')\n cinactivity = Data.objects.values('inactivity').get(did=did)\n inactivity = cinactivity.get('inactivity')\n ccardiovascular = Data.objects.values('cardiovascular').get(did=did)\n cardiovascular = ccardiovascular.get('cardiovascular')\n chyperlidermia = Data.objects.values('hyperlidermia').get(did=did)\n hyperlidermia = chyperlidermia.get('hyperlidermia')\n calcohol = Data.objects.values('alcohol').get(did=did)\n alcohol = calcohol.get('alcohol')\n ctia = Data.objects.values('tia').get(did=did)\n tia = ctia.get('tia')\n cmsyndrome = Data.objects.values('msyndrome').get(did=did)\n msyndrome = cmsyndrome.get('msyndrome')\n catherosclerosis = Data.objects.values('atherosclerosis').get(did=did)\n atherosclerosis = catherosclerosis.get('atherosclerosis')\n caf = Data.objects.values('af').get(did=did)\n af = caf.get('af')\n clvh = Data.objects.values('lvh').get(did=did)\n lvh = clvh.get('lvh')\n cdiabetes = Data.objects.values('diabetes').get(did=did)\n diabetes = cdiabetes.get('diabetes')\n csmoking = Data.objects.values('smoking').get(did=did)\n smoking = csmoking.get('smoking')\n cstroke = Data.objects.values('stroke').get(did=did)\n stroke = cstroke.get('stroke')\n cadvice = Data.objects.values('advice').get(did=did)\n advice = cadvice.get('advice')\n cphone = Data.objects.values('phone_id').get(did=did)\n phone = cphone.get('phone_id')\n model = pickle.load(open('model.pkl', 'rb'))\n probability = model.predict_proba([\n [history, hypertension, inactivity, cardiovascular, hyperlidermia, alcohol, tia, msyndrome, atherosclerosis,\n sex, age, af,\n lvh, diabetes, smoking]])\n prob = probability[0][1]\n prob = float(prob * 100)\n prob = round(prob, 2)\n\n return render(request, 'printreport.html',\n context={'title': title, \"sex\": sex, \"age\": age, \"history\": history, \"hypertension\": hypertension,\n \"inactivity\": inactivity, \"cardiovascular\": cardiovascular,\n \"hyperlidermia\": hyperlidermia, \"alcohol\": alcohol, \"tia\": tia, \"msyndrome\": msyndrome,\n \"atherosclerosis\": atherosclerosis, \"af\": af, \"lvh\": lvh,\n \"diabetes\": diabetes, \"smoking\": smoking, \"stroke\": stroke, \"percent\": prob,\n \"phone\": phone,\n \"advice\": advice, \"cgender\": cgender, \"did\": did})\n else:\n return redirect('login_user')\n\n\ndef dataset(request):\n title = \"Clients\"\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=\"strokedataset.csv\"'\n writer = csv.writer(response)\n writer.writerow(\n ['ID', 'Sex', 'Age', 'Family History', 'Hypertension', \"Physical Inactivity\", \"Cardiovascular Disease\",\n \"Hyperlidermia\",\n \"Alcohol Comsuption\", \"History of TIA\", \"Metabolic Syndrome\", \"Atherosclerosis\", \"Atrial Fibrillation\",\n \"Left Ventricular Hypertrophy\", \"Diabetes\",\n \"Smoking\", \"Stroke\"])\n try:\n dataset = Data.objects.all()\n\n for data in dataset:\n writer.writerow(\n [data.did, data.sex, data.age, data.history, data.hypertension, data.inactivity, data.cardiovascular,\n data.hyperlidermia, data.alcohol, data.tia, data.msyndrome, data.atherosclerosis, data.af, data.lvh,\n data.diabetes, data.smoking, data.stroke])\n except Data.DoesNotExist:\n writer.writerow([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n return response\n\n\n# @login_required(login_url='/login_user')\ndef users(request):\n if request.user.is_authenticated:\n title = 'New User'\n # users = User.objects.filter(is_superuser=False)\n users = DocDet.objects.all()\n context = {'title': title, \"users\": users}\n if request.method == \"POST\":\n username = request.POST.get('username')\n password = request.POST.get('password')\n cpassword = request.POST.get('cpassword')\n firstname = request.POST.get('firstname')\n lastname = request.POST.get('lastname')\n email = request.POST.get('email')\n phone = request.POST.get('phone')\n if password == cpassword:\n if User.objects.filter(username=username).exists():\n messages.info(request, 'Username already exist')\n return redirect('users')\n else:\n password = make_password(password)\n u = User.objects.create(first_name=firstname, password=password, is_superuser=False,\n username=username,\n last_name=lastname, email=email, is_staff=True, is_active=True,\n date_joined=timezone.now())\n u.save()\n user = User.objects.get(username=username)\n userid = user.id\n ph = DocDet.objects.create(userid_id=userid, phone=phone)\n ph.save()\n messages.info(request, 'User added successfully')\n return redirect(reverse('users'))\n else:\n messages.info(request, 'Password mismatch error')\n return redirect('users')\n else:\n return render(request, 'users.html', context)\n else:\n return redirect('login_user')\n\n\n# @login_required(login_url='/login_user')\ndef deluser(request, id):\n try:\n user = User.objects.filter(id=id).delete()\n return redirect('users')\n except User.DoesNotExist:\n messages.info(request, 'User does not exist')\n return redirect('users')\n\n\ndef register(request):\n title = 'User Details'\n context = {'title': title}\n if request.method == \"POST\":\n name = request.POST.get('name')\n phone = request.POST.get('phone')\n if UserDet.objects.filter(phone=phone).exists():\n request.session['phone'] = phone\n return redirect('age')\n else:\n udet = UserDet.objects.create(phone=phone, name=name)\n request.session['phone'] = phone\n return redirect('age')\n return render(request, 'register.html', context)\n\n\ndef about():\n title = \"About\"\n return render(request, 'about.html', context={'title': title})\n\n\ndef message(request):\n title = \"Message\"\n return render(request, 'message.html', context={'title': title})\n\n\ndef age(request):\n title = \"Age\"\n if request.method == 'POST':\n # age = request.form['1']\n request.session[\"age\"] = request.POST.get(\"age\")\n # request.session = qst1\n return redirect('sex')\n return render(request, 'age.html', context={'title': title})\n\n\ndef sex(request):\n title = \"Gender\"\n if request.method == 'POST':\n request.session[\"sex\"] = request.POST.get(\"sex\")\n # request.session = qst1\n return redirect('question1')\n return render(request, 'gender.html', context={'title': title})\n\n\ndef question1(request):\n if request.method == 'POST':\n # qst1 = request.form['1']\n request.session[\"qst1\"] = request.POST.get(\"1\")\n # request.session = qst1\n return redirect('question2')\n return render(request, 'question1.html')\n\n\ndef question2(request):\n if request.method == 'POST':\n request.session[\"qst2\"] = request.POST.get(\"2\")\n # request.session = qst1\n return redirect('question3')\n return render(request, 'question2.html')\n\n\ndef question3(request):\n if request.method == 'POST':\n request.session[\"qst3\"] = request.POST.get(\"3\")\n return redirect('question4')\n return render(request, 'question3.html')\n\n\ndef question4(request):\n if request.method == 'POST':\n request.session[\"qst4\"] = request.POST.get(\"4\")\n return redirect('question5')\n return render(request, 'question4.html')\n\n\ndef question5(request):\n if request.method == 'POST':\n request.session[\"qst5\"] = request.POST.get(\"5\")\n return redirect('question6')\n return render(request, 'question5.html')\n\n\ndef question6(request):\n if request.method == 'POST':\n request.session[\"qst6\"] = request.POST.get(\"6\")\n return redirect('question7')\n return render(request, 'question6.html')\n\n\ndef question7(request):\n if request.method == 'POST':\n request.session[\"qst7\"] = request.POST.get(\"7\")\n return redirect('question8')\n return render(request, 'question7.html')\n\n\ndef question8(request):\n if request.method == 'POST':\n request.session[\"qst8\"] = request.POST.get(\"8\")\n return redirect('question9')\n return render(request, 'question8.html')\n\n\ndef question9(request):\n if request.method == 'POST':\n request.session[\"qst9\"] = request.POST.get(\"9\")\n return redirect('question10')\n return render(request, 'question9.html')\n\n\ndef question10(request):\n if request.method == 'POST':\n request.session[\"qst10\"] = request.POST.get(\"10\")\n return redirect('question11')\n return render(request, 'question10.html')\n\n\ndef question11(request):\n if request.method == 'POST':\n request.session[\"qst11\"] = request.POST.get(\"11\")\n return redirect('question12')\n return render(request, 'question11.html')\n\n\ndef question12(request):\n if request.method == 'POST':\n request.session[\"qst12\"] = request.POST.get(\"12\")\n return redirect('question13')\n return render(request, 'question12.html')\n\n\ndef question13(request):\n if request.method == 'POST':\n request.session[\"qst13\"] = request.POST.get(\"13\")\n return redirect('predict')\n return render(request, 'question13.html')\n\n\ndef predict(request):\n # collect prediction data from client\n random_number = random.randint(1000000000, 9999999999)\n id = str(random_number)\n history = int(request.session[\"qst1\"])\n hypertension = int(request.session[\"qst2\"])\n inactivity = int(request.session[\"qst3\"])\n cardiovascular = int(request.session[\"qst4\"])\n hyperlidermia = int(request.session[\"qst5\"])\n alcohol = int(request.session[\"qst6\"])\n tia = int(request.session[\"qst7\"])\n msyndrome = int(request.session[\"qst8\"])\n atherosclerosis = int(request.session[\"qst9\"])\n af = int(request.session[\"qst10\"])\n lvh = int(request.session[\"qst11\"])\n diabetes = int(request.session[\"qst12\"])\n smoking = int(request.session[\"qst13\"])\n sex = int(request.session[\"sex\"])\n age = int(request.session[\"age\"])\n # Load model\n model = pickle.load(open('model.pkl', 'rb'))\n # Make predictions\n pred = model.predict([\n [history, hypertension, inactivity, cardiovascular, hyperlidermia, alcohol, tia, msyndrome, atherosclerosis,\n sex, age, af,\n lvh, diabetes, smoking]])\n probability = model.predict_proba([\n [history, hypertension, inactivity, cardiovascular, hyperlidermia, alcohol, tia, msyndrome, atherosclerosis,\n sex, age, af,\n lvh, diabetes, smoking]])\n pred = round(pred[0])\n prob = probability[0][1]\n prob = float(prob * 100)\n prob = round(prob, 2)\n\n result = \"False\"\n if prob < 50:\n result = \"True\"\n else:\n result = \"False\"\n print('result', result)\n phone = request.session['phone']\n uname = UserDet.objects.values('name').get(phone=phone)\n name = uname.get('name')\n chance_stroke = ''\n chance_stroke += \"As a stroke counselor, I would like to provide recommendations for \" + name + \" \" + str(\n age) + \" years old patient with a probability of having a stroke of \" + str(prob) + \"%. \" + name + \" is \"\n if sex == 1:\n chance_stroke += 'a Male '\n if sex == 0:\n chance_stroke += 'a Female '\n if history == 1:\n chance_stroke += ' with a family history of stroke,'\n if history == 0:\n chance_stroke += ' with no family history of stroke,'\n if history == 2:\n chance_stroke += ' with an unsure family history of stroke,'\n if hypertension == 1:\n chance_stroke += ' hypertensive,'\n if hypertension == 0:\n chance_stroke += ' not hypertensive,'\n if inactivity == 0:\n chance_stroke += ' not exercising.'\n if inactivity == 1:\n chance_stroke += ' exercises regularly.'\n if cardiovascular == 0:\n chance_stroke += ' has not been diagnosed of cardiovascular disease.'\n if cardiovascular == 1:\n chance_stroke += ' has been diagnosed of cardiovascular disease.'\n if hyperlidermia == 0:\n chance_stroke += 'Additionally, ' + name + ' doesn\\'t have hyperlipidemia,'\n if hyperlidermia == 1:\n chance_stroke += 'Additionally, ' + name + ' suffers from hyperlipidemia,'\n if alcohol == 0:\n chance_stroke += ' doesn\\'t consume alcohol,'\n if alcohol == 1:\n chance_stroke += ' consumes alcohol,'\n if tia == 0:\n chance_stroke += ' has no history of Transient Ischemic Stroke(TIA), '\n if tia == 1:\n chance_stroke += ' has a history of Transient Ischemic Stroke(TIA), '\n if msyndrome == 0:\n chance_stroke += ' not diagnosed of metabolic Syndrome, '\n if msyndrome == 1:\n chance_stroke += ' suffers from metabolic syndrome, '\n if atherosclerosis == 0:\n chance_stroke += ' does not suffer from atherosclerosis, '\n if atherosclerosis == 1:\n chance_stroke += ' suffers from atherosclerosis, '\n if af == 0:\n chance_stroke += ' has no case of atrial fibrillation, '\n if af == 1:\n chance_stroke += ' reported to have atrial fibrillation, '\n if lvh == 0:\n chance_stroke += ' does not suffer from Left Ventricular Hypertrophy, '\n if lvh == 1:\n chance_stroke += ' suffers from Left Ventricular Hypertrophy, '\n if diabetes == 0:\n chance_stroke += ' is not diabetic. '\n if diabetes == 1:\n chance_stroke += ' is diabetic. '\n if smoking == 0:\n chance_stroke += 'Finally, ' + name + ' doesn\\'t smoke.'\n if smoking == 1:\n chance_stroke += 'Finally, ' + name + ' is a smoker.'\n chance_stroke += \" Could you please provide detailed diet recommendations and any other advice that would help \" \\\n \"manage the risk factors associated with stroke in \" + name + \"\\'s case? \"\n try:\n counseling_response = \"\"\n response = openai.Completion.create(\n # model name used here is text-davinci-003\n # there are many other models available under the\n # umbrella of GPT-3\n model=\"text-davinci-003\",\n # passing the user input\n prompt=chance_stroke,\n # generated output can have \"max_tokens\" number of tokens\n max_tokens=2000,\n temperature=0.5,\n # number of outputs generated in one call\n n=5\n )\n # creating a list to store all the outputs\n # output = \"\"\n # for k in response['choices']:\n # output += k['text'].strip()\n counseling_response = response[\"choices\"][0][\"text\"]\n\n newdata = Data.objects.create(did=id, history=history, hypertension=hypertension, inactivity=inactivity,\n cardiovascular=cardiovascular, hyperlidermia=hyperlidermia, alcohol=alcohol,\n tia=tia,\n msyndrome=msyndrome, atherosclerosis=atherosclerosis,\n sex=sex, age=age, af=af, lvh=lvh, diabetes=diabetes, smoking=smoking, stroke=pred,\n percent=prob,\n phone_id=phone, advice=counseling_response)\n newdata.save()\n return redirect('results', conseling=counseling_response, pred=pred, phone=phone, prob=prob, result=result,\n id=id)\n except ConnectionError as e:\n counseling_response = \"Network Error\"\n messages.info(request, counseling_response)\n return render(request, 'message.html')\n except requests.exceptions.RequestException as e:\n # Handle network-related errors (including DNS resolution) from the requests library\n error_message = \"Network Error: \" + str(e)\n messages.info(request, error_message)\n return render(request, 'message.html')\n except openai.OpenAIError as e:\n error_message = \"OpenAI API Error: \" + str(e)\n messages.info(request, error_message)\n return render(request, 'message.html')\n except openai.OpenAIError as e:\n # Handle the OpenAI API key error gracefully\n error_message = \"OpenAI API Key Error: \" + str(e)\n messages.info(request, error_message)\n return render(request, 'message.html')\n\n\ndef results(request, conseling, pred, phone, prob, result, id):\n title = \"Results\"\n try:\n users = DocDet.objects.all()\n except DocDet.DoesNotExist:\n users = None\n return render(request, 'results.html',\n context={\"title\": title, \"conseling\": conseling, 'pred': pred, 'users': users, 'phone': phone,\n 'prob': prob, 'result': result, \"id\": id})\n\n\ndef comp(PROMPT, MaxToken, outputs):\n # using OpenAI's Completion module that helps execute\n # any tasks involving text\n try:\n\n response = openai.Completion.create(\n # model name used here is text-davinci-003\n # there are many other models available under the\n # umbrella of GPT-3\n model=\"text-davinci-003\",\n # passing the user input\n prompt=PROMPT,\n # generated output can have \"max_tokens\" number of tokens\n max_tokens=MaxToken,\n temperature=0.5,\n # number of outputs generated in one call\n n=outputs\n )\n # creating a list to store all the outputs\n # output = \"\"\n # for k in response['choices']:\n # output += k['text'].strip()\n return response[\"choices\"][0][\"text\"]\n except requests.exceptions.RequestException as e:\n # Handle network-related errors (including DNS resolution) from the requests library\n error_message = \"Network Error: \" + str(e)\n return error_message\n except openai.OpenAIError as e:\n error_message = \"OpenAI API Error: \" + str(e)\n return error_message\n except openai.OpenAIError as e:\n # Handle the OpenAI API key error gracefully\n error_message = \"OpenAI API Key Error: \" + str(e)\n return error_message\n\n\ndef printureport(request, id):\n title = \"Detail Report\"\n gender = Data.objects.values('sex').get(did=id)\n sex = gender.get('sex')\n cgender = \"\"\n if sex == 1:\n cgender = \"Male\"\n elif sex == 0:\n cgender = \"Female\"\n cage = Data.objects.values('age').get(did=id)\n age = cage.get('age')\n chistory = Data.objects.values('history').get(did=id)\n history = chistory.get('history')\n chypertension = Data.objects.values('hypertension').get(did=id)\n hypertension = chypertension.get('hypertension')\n cinactivity = Data.objects.values('inactivity').get(did=id)\n inactivity = cinactivity.get('inactivity')\n ccardiovascular = Data.objects.values('cardiovascular').get(did=id)\n cardiovascular = ccardiovascular.get('cardiovascular')\n chyperlidermia = Data.objects.values('hyperlidermia').get(did=id)\n hyperlidermia = chyperlidermia.get('hyperlidermia')\n calcohol = Data.objects.values('alcohol').get(did=id)\n alcohol = calcohol.get('alcohol')\n ctia = Data.objects.values('tia').get(did=id)\n tia = ctia.get('tia')\n cmsyndrome = Data.objects.values('msyndrome').get(did=id)\n msyndrome = cmsyndrome.get('msyndrome')\n\n catherosclerosis = Data.objects.values('atherosclerosis').get(did=id)\n atherosclerosis = catherosclerosis.get('atherosclerosis')\n caf = Data.objects.values('af').get(did=id)\n af = caf.get('af')\n clvh = Data.objects.values('lvh').get(did=id)\n lvh = clvh.get('lvh')\n cdiabetes = Data.objects.values('diabetes').get(did=id)\n diabetes = cdiabetes.get('diabetes')\n csmoking = Data.objects.values('smoking').get(did=id)\n smoking = csmoking.get('smoking')\n cstroke = Data.objects.values('stroke').get(did=id)\n stroke = cstroke.get('stroke')\n cadvice = Data.objects.values('advice').get(did=id)\n advice = cadvice.get('advice')\n cphone = Data.objects.values('phone_id').get(did=id)\n phone = cphone.get('phone_id')\n model = pickle.load(open('model.pkl', 'rb'))\n probability = model.predict_proba([\n [history, hypertension, inactivity, cardiovascular, hyperlidermia, alcohol, tia, msyndrome, atherosclerosis,\n sex, age, af,\n lvh, diabetes, smoking]])\n prob = probability[0][1]\n prob = float(prob * 100)\n prob = round(prob, 2)\n # result = prob < 70\n return render(request, 'printureport.html',\n context={'title': title, \"sex\": sex, \"age\": age, \"history\": history, \"hypertension\": hypertension,\n \"inactivity\": inactivity, \"cardiovascular\": cardiovascular,\n \"hyperlidermia\": hyperlidermia, \"alcohol\": alcohol, \"tia\": tia, \"msyndrome\": msyndrome,\n \"atherosclerosis\": atherosclerosis, \"af\": af, \"lvh\": lvh,\n \"diabetes\": diabetes, \"smoking\": smoking, \"stroke\": stroke, \"phone\": phone,\n \"advice\": advice, \"cgender\": cgender, 'prob': prob})\n\n\ndef requestdataset(request):\n title = 'New Researcher'\n # users = User.objects.filter(is_superuser=False)\n context = {'title': title}\n if request.method == \"POST\":\n name = request.POST.get('name')\n email = request.POST.get('email')\n u = Researchers.objects.create(email=email, name=name, date=timezone.now())\n u.save()\n return redirect(reverse('dataset'))\n else:\n return render(request, 'requestdataset.html', context)\n\n\ndef viewallreports(request):\n title = \"View Reports\"\n reports = Data.objects.all()\n context = {'title': title, 'reports': reports}\n return render(request, \"viewallreports.html\", context)\n", "repo_name": "sammylofy/Stroke_analysis", "sub_path": "predictor/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 29903, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "20", "api": [{"api_name": "openai.api_key", "line_number": 29, "usage_type": "attribute"}, {"api_name": "django.http.request.method", "line_number": 37, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 37, "usage_type": "name"}, {"api_name": "django.http.request.POST", "line_number": 38, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 38, "usage_type": "name"}, {"api_name": "django.http.request.POST", "line_number": 39, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 39, "usage_type": "name"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 40, "usage_type": "call"}, {"api_name": "django.contrib.auth", "line_number": 40, "usage_type": "name"}, {"api_name": "django.contrib.auth.login", "line_number": 43, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 43, "usage_type": "argument"}, {"api_name": "django.contrib.auth", "line_number": 43, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 45, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 47, "usage_type": "call"}, {"api_name": "django.contrib.messages.info", "line_number": 49, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 49, "usage_type": "argument"}, {"api_name": "django.contrib.messages", "line_number": 49, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 50, "usage_type": "call"}, {"api_name": "django.contrib.messages.info", "line_number": 52, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 52, "usage_type": "argument"}, {"api_name": "django.contrib.messages", "line_number": 52, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 53, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 55, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 55, "usage_type": "argument"}, {"api_name": "django.contrib.auth.logout", "line_number": 59, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 59, "usage_type": "argument"}, {"api_name": "django.contrib.auth", "line_number": 59, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 60, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 64, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 69, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 69, "usage_type": "argument"}, {"api_name": "django.http.request.user", "line_number": 74, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 74, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 76, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 76, "usage_type": "argument"}, {"api_name": "django.shortcuts.redirect", "line_number": 78, "usage_type": "call"}, {"api_name": "django.http.request.user", "line_number": 83, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 83, "usage_type": "name"}, {"api_name": "models.DocDet.objects.all", "line_number": 85, "usage_type": "call"}, {"api_name": "models.DocDet.objects", "line_number": 85, "usage_type": "attribute"}, {"api_name": "models.DocDet", "line_number": 85, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 86, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 86, "usage_type": "argument"}, {"api_name": "django.shortcuts.redirect", "line_number": 88, "usage_type": "call"}, {"api_name": "django.http.request.user", "line_number": 93, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 93, "usage_type": "name"}, {"api_name": "models.UserDet.objects.all", "line_number": 96, "usage_type": "call"}, {"api_name": "models.UserDet.objects", "line_number": 96, "usage_type": "attribute"}, {"api_name": "models.UserDet", "line_number": 96, "usage_type": "name"}, {"api_name": "models.UserDet.DoesNotExist", "line_number": 97, "usage_type": "attribute"}, {"api_name": "models.UserDet", "line_number": 97, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 99, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 99, "usage_type": "argument"}, {"api_name": "django.shortcuts.redirect", "line_number": 101, "usage_type": "call"}, {"api_name": "django.http.request.user", "line_number": 106, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 106, "usage_type": "name"}, {"api_name": "models.Data.objects.all", "line_number": 109, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 109, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 109, "usage_type": "name"}, {"api_name": "models.Data.DoesNotExist", "line_number": 110, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 110, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 112, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 112, "usage_type": "argument"}, {"api_name": "django.shortcuts.redirect", "line_number": 114, "usage_type": "call"}, {"api_name": "django.http.request.user", "line_number": 119, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 119, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 121, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 121, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 121, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 128, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 128, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 128, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 130, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 130, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 130, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 132, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 132, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 132, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 134, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 134, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 134, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 136, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 136, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 136, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 138, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 138, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 138, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 140, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 140, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 140, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 142, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 142, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 142, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 144, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 144, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 144, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 146, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 146, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 146, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 148, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 148, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 148, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 150, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 150, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 150, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 152, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 152, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 152, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 154, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 154, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 154, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 156, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 156, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 156, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 158, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 158, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 158, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 160, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 160, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 160, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 162, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 171, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 171, "usage_type": "argument"}, {"api_name": "django.shortcuts.redirect", "line_number": 180, "usage_type": "call"}, {"api_name": "django.http.request.user", "line_number": 185, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 185, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 187, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 187, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 187, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 194, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 194, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 194, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 196, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 196, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 196, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 198, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 198, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 198, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 200, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 200, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 200, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 202, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 202, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 202, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 204, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 204, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 204, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 206, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 206, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 206, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 208, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 208, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 208, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 210, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 210, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 210, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 212, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 212, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 212, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 214, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 214, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 214, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 216, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 216, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 216, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 218, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 218, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 218, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 220, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 220, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 220, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 222, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 222, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 222, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 224, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 224, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 224, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 226, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 226, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 226, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 228, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 237, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 237, "usage_type": "argument"}, {"api_name": "django.shortcuts.redirect", "line_number": 246, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 251, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 253, "usage_type": "call"}, {"api_name": "models.Data.objects.all", "line_number": 261, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 261, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 261, "usage_type": "name"}, {"api_name": "models.Data.DoesNotExist", "line_number": 268, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 268, "usage_type": "name"}, {"api_name": "django.http.request.user", "line_number": 275, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 275, "usage_type": "name"}, {"api_name": "models.DocDet.objects.all", "line_number": 278, "usage_type": "call"}, {"api_name": "models.DocDet.objects", "line_number": 278, "usage_type": "attribute"}, {"api_name": "models.DocDet", "line_number": 278, "usage_type": "name"}, {"api_name": "django.http.request.method", "line_number": 280, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 280, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 281, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 281, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 281, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 282, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 282, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 282, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 283, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 283, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 283, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 284, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 284, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 284, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 285, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 285, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 285, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 286, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 286, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 286, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 287, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 287, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 287, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.filter", "line_number": 289, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 289, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 289, "usage_type": "name"}, {"api_name": "django.contrib.messages.info", "line_number": 290, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 290, "usage_type": "argument"}, {"api_name": "django.contrib.messages", "line_number": 290, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 291, "usage_type": "call"}, {"api_name": "django.contrib.auth.hashers.make_password", "line_number": 293, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.create", "line_number": 294, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 294, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 294, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 297, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 297, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 299, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 299, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 299, "usage_type": "name"}, {"api_name": "models.DocDet.objects.create", "line_number": 301, "usage_type": "call"}, {"api_name": "models.DocDet.objects", "line_number": 301, "usage_type": "attribute"}, {"api_name": "models.DocDet", "line_number": 301, "usage_type": "name"}, {"api_name": "django.contrib.messages.info", "line_number": 303, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 303, "usage_type": "argument"}, {"api_name": "django.contrib.messages", "line_number": 303, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 304, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 304, "usage_type": "call"}, {"api_name": "django.contrib.messages.info", "line_number": 306, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 306, "usage_type": "argument"}, {"api_name": "django.contrib.messages", "line_number": 306, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 307, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 309, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 309, "usage_type": "argument"}, {"api_name": "django.shortcuts.redirect", "line_number": 311, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.filter", "line_number": 317, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 317, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 317, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 318, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.DoesNotExist", "line_number": 319, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 319, "usage_type": "name"}, {"api_name": "django.contrib.messages.info", "line_number": 320, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 320, "usage_type": "argument"}, {"api_name": "django.contrib.messages", "line_number": 320, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 321, "usage_type": "call"}, {"api_name": "django.http.request.method", "line_number": 327, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 327, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 328, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 328, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 328, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 329, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 329, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 329, "usage_type": "name"}, {"api_name": "models.UserDet.objects.filter", "line_number": 330, "usage_type": "call"}, {"api_name": "models.UserDet.objects", "line_number": 330, "usage_type": "attribute"}, {"api_name": "models.UserDet", "line_number": 330, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 331, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 331, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 332, "usage_type": "call"}, {"api_name": "models.UserDet.objects.create", "line_number": 334, "usage_type": "call"}, {"api_name": "models.UserDet.objects", "line_number": 334, "usage_type": "attribute"}, {"api_name": "models.UserDet", "line_number": 334, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 335, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 335, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 336, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 337, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 337, "usage_type": "argument"}, {"api_name": "django.shortcuts.render", "line_number": 342, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 342, "usage_type": "argument"}, {"api_name": "django.shortcuts.render", "line_number": 347, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 347, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 352, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 352, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 354, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 354, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 354, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 354, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 356, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 357, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 357, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 362, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 362, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 363, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 363, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 363, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 363, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 365, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 366, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 366, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 370, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 370, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 372, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 372, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 372, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 372, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 374, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 375, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 375, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 379, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 379, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 380, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 380, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 380, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 380, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 382, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 383, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 383, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 387, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 387, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 388, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 388, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 388, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 388, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 389, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 390, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 390, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 394, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 394, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 395, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 395, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 395, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 395, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 396, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 397, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 397, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 401, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 401, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 402, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 402, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 402, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 402, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 403, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 404, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 404, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 408, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 408, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 409, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 409, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 409, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 409, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 410, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 411, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 411, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 415, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 415, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 416, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 416, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 416, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 416, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 417, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 418, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 418, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 422, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 422, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 423, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 423, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 423, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 423, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 424, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 425, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 425, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 429, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 429, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 430, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 430, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 430, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 430, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 431, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 432, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 432, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 436, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 436, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 437, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 437, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 437, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 437, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 438, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 439, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 439, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 443, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 443, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 444, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 444, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 444, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 444, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 445, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 446, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 446, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 450, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 450, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 451, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 451, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 451, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 451, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 452, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 453, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 453, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 457, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 457, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 458, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 458, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 458, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 458, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 459, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 460, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 460, "usage_type": "argument"}, {"api_name": "random.randint", "line_number": 465, "usage_type": "call"}, {"api_name": "django.http.request.session", "line_number": 467, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 467, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 468, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 468, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 469, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 469, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 470, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 470, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 471, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 471, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 472, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 472, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 473, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 473, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 474, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 474, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 475, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 475, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 476, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 476, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 477, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 477, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 478, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 478, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 479, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 479, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 480, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 480, "usage_type": "name"}, {"api_name": "django.http.request.session", "line_number": 481, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 481, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 483, "usage_type": "call"}, {"api_name": "django.http.request.session", "line_number": 504, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 504, "usage_type": "name"}, {"api_name": "models.UserDet.objects.values", "line_number": 505, "usage_type": "call"}, {"api_name": "models.UserDet.objects", "line_number": 505, "usage_type": "attribute"}, {"api_name": "models.UserDet", "line_number": 505, "usage_type": "name"}, {"api_name": "openai.Completion.create", "line_number": 572, "usage_type": "call"}, {"api_name": "openai.Completion", "line_number": 572, "usage_type": "attribute"}, {"api_name": "models.Data.objects.create", "line_number": 591, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 591, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 591, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 599, "usage_type": "call"}, {"api_name": "django.contrib.messages.info", "line_number": 603, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 603, "usage_type": "argument"}, {"api_name": "django.contrib.messages", "line_number": 603, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 604, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 604, "usage_type": "argument"}, {"api_name": "requests.exceptions.exceptions", "line_number": 605, "usage_type": "attribute"}, {"api_name": "requests.exceptions", "line_number": 605, "usage_type": "name"}, {"api_name": "django.contrib.messages.info", "line_number": 608, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 608, "usage_type": "argument"}, {"api_name": "django.contrib.messages", "line_number": 608, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 609, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 609, "usage_type": "argument"}, {"api_name": "openai.OpenAIError", "line_number": 610, "usage_type": "attribute"}, {"api_name": "django.contrib.messages.info", "line_number": 612, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 612, "usage_type": "argument"}, {"api_name": "django.contrib.messages", "line_number": 612, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 613, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 613, "usage_type": "argument"}, {"api_name": "openai.OpenAIError", "line_number": 614, "usage_type": "attribute"}, {"api_name": "django.contrib.messages.info", "line_number": 617, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 617, "usage_type": "argument"}, {"api_name": "django.contrib.messages", "line_number": 617, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 618, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 618, "usage_type": "argument"}, {"api_name": "models.DocDet.objects.all", "line_number": 624, "usage_type": "call"}, {"api_name": "models.DocDet.objects", "line_number": 624, "usage_type": "attribute"}, {"api_name": "models.DocDet", "line_number": 624, "usage_type": "name"}, {"api_name": "models.DocDet.DoesNotExist", "line_number": 625, "usage_type": "attribute"}, {"api_name": "models.DocDet", "line_number": 625, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 627, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 627, "usage_type": "argument"}, {"api_name": "openai.Completion.create", "line_number": 637, "usage_type": "call"}, {"api_name": "openai.Completion", "line_number": 637, "usage_type": "attribute"}, {"api_name": "requests.exceptions.exceptions", "line_number": 655, "usage_type": "attribute"}, {"api_name": "requests.exceptions", "line_number": 655, "usage_type": "name"}, {"api_name": "openai.OpenAIError", "line_number": 659, "usage_type": "attribute"}, {"api_name": "openai.OpenAIError", "line_number": 662, "usage_type": "attribute"}, {"api_name": "models.Data.objects.values", "line_number": 670, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 670, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 670, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 677, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 677, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 677, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 679, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 679, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 679, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 681, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 681, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 681, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 683, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 683, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 683, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 685, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 685, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 685, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 687, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 687, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 687, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 689, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 689, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 689, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 691, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 691, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 691, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 693, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 693, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 693, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 696, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 696, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 696, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 698, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 698, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 698, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 700, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 700, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 700, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 702, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 702, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 702, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 704, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 704, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 704, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 706, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 706, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 706, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 708, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 708, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 708, "usage_type": "name"}, {"api_name": "models.Data.objects.values", "line_number": 710, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 710, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 710, "usage_type": "name"}, {"api_name": "pickle.load", "line_number": 712, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 721, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 721, "usage_type": "argument"}, {"api_name": "django.http.request.method", "line_number": 734, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 734, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 735, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 735, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 735, "usage_type": "name"}, {"api_name": "django.http.request.POST.get", "line_number": 736, "usage_type": "call"}, {"api_name": "django.http.request.POST", "line_number": 736, "usage_type": "attribute"}, {"api_name": "django.http.request", "line_number": 736, "usage_type": "name"}, {"api_name": "models.Researchers.objects.create", "line_number": 737, "usage_type": "call"}, {"api_name": "models.Researchers.objects", "line_number": 737, "usage_type": "attribute"}, {"api_name": "models.Researchers", "line_number": 737, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 737, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 737, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 739, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 739, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 741, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 741, "usage_type": "argument"}, {"api_name": "models.Data.objects.all", "line_number": 746, "usage_type": "call"}, {"api_name": "models.Data.objects", "line_number": 746, "usage_type": "attribute"}, {"api_name": "models.Data", "line_number": 746, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 748, "usage_type": "call"}, {"api_name": "django.http.request", "line_number": 748, "usage_type": "argument"}]} +{"seq_id": "35582002449", "text": "import os\nimport pdb\nimport sys\nimport time\nimport pickle\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport transformer.Constants as Constants\nfrom transformer.Models import Transformer\nimport Utils\nfrom matplotlib import pyplot as plt\nfrom tqdm import tqdm\n\nfrom scipy.stats import lognorm,gamma\nfrom scipy.optimize import brentq\nfrom datetime import datetime as dt\n\nimport THP_plot_code\n######################################################\n### Data Generator\n######################################################\ndef generate_stationary_poisson():\n np.random.seed(seed=32)\n tau = np.random.exponential(size=100000)\n T = tau.cumsum()\n score = 1\n return [T,score]\n\ndef generate_nonstationary_poisson():\n np.random.seed(seed=32)\n L = 20000\n amp = 0.99\n l_t = lambda t: np.sin(2*np.pi*t/L)*amp + 1\n l_int = lambda t1,t2: - L/(2*np.pi)*( np.cos(2*np.pi*t2/L) - np.cos(2*np.pi*t1/L) )*amp + (t2-t1)\n while 1:\n T = np.random.exponential(size=210000).cumsum()*0.5\n r = np.random.rand(210000)\n index = r < l_t(T)/2.0\n \n if index.sum() > 100000:\n T = T[index][:100000]\n score = - ( np.log(l_t(T[80000:])).sum() - l_int(T[80000-1],T[-1]) )/20000\n break\n \n return [T,score]\n\ndef generate_stationary_renewal():\n np.random.seed(seed=32)\n s = np.sqrt(np.log(6*6+1))\n mu = -s*s/2\n tau = lognorm.rvs(s=s,scale=np.exp(mu),size=100000)\n lpdf = lognorm.logpdf(tau,s=s,scale=np.exp(mu))\n T = tau.cumsum()\n score = - np.mean(lpdf[80000:])\n \n return [T,score]\n\ndef generate_nonstationary_renewal():\n np.random.seed(seed=32)\n L = 20000\n amp = 0.99\n l_t = lambda t: np.sin(2*np.pi*t/L)*amp + 1\n l_int = lambda t1,t2: - L/(2*np.pi)*( np.cos(2*np.pi*t2/L) - np.cos(2*np.pi*t1/L) )*amp + (t2-t1)\n\n T = []\n lpdf = []\n x = 0\n\n k = 4\n rs = gamma.rvs(k,size=100000)\n lpdfs = gamma.logpdf(rs,k)\n rs = rs/k\n lpdfs = lpdfs + np.log(k)\n\n for i in range(100000):\n x_next = brentq(lambda t: l_int(x,t) - rs[i],x,x+1000)\n l = l_t(x_next)\n T.append(x_next)\n lpdf.append( lpdfs[i] + np.log(l) ) \n x = x_next\n\n T = np.array(T)\n lpdf = np.array(lpdf)\n score = - lpdf[80000:].mean()\n \n return [T,score]\n\ndef generate_self_correcting():\n np.random.seed(seed=32)\n \n def self_correcting_process(mu,alpha,n):\n \n t = 0; x = 0;\n T = [];\n log_l = [];\n Int_l = [];\n \n for i in range(n):\n e = np.random.exponential()\n tau = np.log( e*mu/np.exp(x) + 1 )/mu # e = ( np.exp(mu*tau)- 1 )*np.exp(x) /mu\n t = t+tau\n T.append(t)\n x = x + mu*tau\n log_l.append(x)\n Int_l.append(e)\n x = x -alpha\n\n return [np.array(T),np.array(log_l),np.array(Int_l)]\n \n [T,log_l,Int_l] = self_correcting_process(1,1,100000)\n score = - ( log_l[80000:] - Int_l[80000:] ).sum() / 20000\n \n return [T,score]\n\ndef generate_hawkes1():\n np.random.seed(seed=32)\n [T,LL] = simulate_hawkes(100000,0.2,[0.8,0.0],[1.0,20.0])\n score = - LL[80000:].mean()\n return [T,score]\n\ndef generate_hawkes2():\n np.random.seed(seed=32)\n [T,LL] = simulate_hawkes(100000,0.2,[0.4,0.4],[1.0,20.0])\n score = - LL[80000:].mean()\n return [T,score]\n\ndef simulate_hawkes(n,mu,alpha,beta):\n T = []\n LL = []\n \n x = 0\n l_trg1 = 0\n l_trg2 = 0\n l_trg_Int1 = 0\n l_trg_Int2 = 0\n mu_Int = 0\n count = 0\n \n while 1:\n l = mu + l_trg1 + l_trg2\n step = np.random.exponential()/l\n x = x + step\n \n l_trg_Int1 += l_trg1 * ( 1 - np.exp(-beta[0]*step) ) / beta[0]\n l_trg_Int2 += l_trg2 * ( 1 - np.exp(-beta[1]*step) ) / beta[1]\n mu_Int += mu * step\n l_trg1 *= np.exp(-beta[0]*step)\n l_trg2 *= np.exp(-beta[1]*step)\n l_next = mu + l_trg1 + l_trg2\n \n if np.random.rand() < l_next/l: #accept\n T.append(x)\n LL.append( np.log(l_next) - l_trg_Int1 - l_trg_Int2 - mu_Int )\n l_trg1 += alpha[0]*beta[0]\n l_trg2 += alpha[1]*beta[1]\n l_trg_Int1 = 0\n l_trg_Int2 = 0\n mu_Int = 0\n count += 1\n \n if count == n:\n break\n \n return [np.array(T),np.array(LL)]\n\ndef generate_hawkes_modes():\n np.random.seed(seed=32)\n [T,LL,L_TRG1] = simulate_hawkes_modes(100000,0.2,[0.8,0.0],[1.0,20.0])\n score = - LL[80000:].mean()\n return [T,score]\n\ndef simulate_hawkes_modes(n,mu,alpha,beta,short_thre=1,long_thre=5):\n T = []\n LL = []\n L_TRG1 = []\n \n x = 0\n l_trg1 = 0\n l_trg2 = 0\n l_trg_Int1 = 0\n l_trg_Int2 = 0\n mu_Int = 0\n count = 0\n is_long_mode = 0\n \n while 1:\n l = mu + l_trg1 + l_trg2\n #step = np.random.exponential(scale=1)/l\n\n if l_trg1 > long_thre:\n is_long_mode = 1\n\n if l_trg1 < short_thre:\n is_long_mode = 0\n\n if is_long_mode: # long mode\n step = step = np.random.exponential(scale=2)/l\n else: # short mode\n step = np.random.exponential(scale=0.5)/l\n\n x = x + step\n \n l_trg_Int1 += l_trg1 * ( 1 - np.exp(-beta[0]*step) ) / beta[0]\n l_trg_Int2 += l_trg2 * ( 1 - np.exp(-beta[1]*step) ) / beta[1]\n mu_Int += mu * step\n l_trg1 *= np.exp(-beta[0]*step)\n l_trg2 *= np.exp(-beta[1]*step)\n l_next = mu + l_trg1 + l_trg2\n \n if np.random.rand() < l_next/l: #accept\n T.append(x)\n LL.append( np.log(l_next) - l_trg_Int1 - l_trg_Int2 - mu_Int )\n L_TRG1.append(l_trg1)\n l_trg1 += alpha[0]*beta[0]\n l_trg2 += alpha[1]*beta[1]\n l_trg_Int1 = 0\n l_trg_Int2 = 0\n mu_Int = 0\n count += 1\n \n if count == n:\n break\n \n return [np.array(T),np.array(LL),np.array(L_TRG1)]\n\ndef generate_hawkes_modes05():\n np.random.seed(seed=32)\n [T,LL,L_TRG1] = simulate_hawkes_modes05(100000,0.2,[0.8,0.0],[1.0,20.0])\n score = - LL[80000:].mean()\n return [T,score]\n\ndef simulate_hawkes_modes05(n,mu,alpha,beta,short_thre=1,long_thre=5):\n T = []\n LL = []\n L_TRG1 = []\n \n x = 0\n l_trg1 = 0\n l_trg2 = 0\n l_trg_Int1 = 0\n l_trg_Int2 = 0\n mu_Int = 0\n count = 0\n is_long_mode = 0\n \n while 1:\n l = mu + l_trg1 + l_trg2\n #step = np.random.exponential(scale=1)/l\n\n if l_trg1 > long_thre:\n is_long_mode = 1\n\n if l_trg1 < short_thre:\n is_long_mode = 0\n\n if is_long_mode: # long mode\n step = step = np.random.exponential(scale=2)/l\n else: # short mode\n step = np.random.exponential(scale=0.25)/l\n\n x = x + step\n \n l_trg_Int1 += l_trg1 * ( 1 - np.exp(-beta[0]*step) ) / beta[0]\n l_trg_Int2 += l_trg2 * ( 1 - np.exp(-beta[1]*step) ) / beta[1]\n mu_Int += mu * step\n l_trg1 *= np.exp(-beta[0]*step)\n l_trg2 *= np.exp(-beta[1]*step)\n l_next = mu + l_trg1 + l_trg2\n \n if np.random.rand() < l_next/l: #accept\n T.append(x)\n LL.append( np.log(l_next) - l_trg_Int1 - l_trg_Int2 - mu_Int )\n L_TRG1.append(l_trg1)\n l_trg1 += alpha[0]*beta[0]\n l_trg2 += alpha[1]*beta[1]\n l_trg_Int1 = 0\n l_trg_Int2 = 0\n mu_Int = 0\n count += 1\n \n if count == n:\n break\n \n return [np.array(T),np.array(LL),np.array(L_TRG1)]\n\ndef generate_data(data_type,opt):\n def rolling_matrix(x,time_step):\n x = x.flatten()\n n = x.shape[0]\n stride = x.strides[0]\n return np.lib.stride_tricks.as_strided(x, shape=(n-time_step+1, time_step), strides=(stride,stride) ).copy()\n def transform_data(T,n_train,n_validation,n_test,time_step,batch_size):\n\n T_train = T[:n_train]\n T_valid = T[n_train:n_train+n_validation]\n T_test = T[n_train+n_validation:n_train+n_validation+n_test]\n dT_train = np.ediff1d(T_train)\n \n train_data = torch.tensor(rolling_matrix(dT_train,time_step)).to(torch.double)\n dT_valid = np.ediff1d(T_valid)\n valid_data = torch.tensor(rolling_matrix(dT_valid,time_step)).to(torch.double)\n\n \n dT_test = np.ediff1d(T_test)\n \n test_data = torch.tensor(rolling_matrix(dT_test,time_step)).to(torch.double)\n return torch.utils.data.DataLoader(train_data,num_workers=os.cpu_count(),batch_size=batch_size,pin_memory=True,shuffle=True),\\\n torch.utils.data.DataLoader(valid_data,num_workers=os.cpu_count(),batch_size=batch_size,pin_memory=True,shuffle=False), \\\n torch.utils.data.DataLoader(test_data,num_workers=os.cpu_count(),batch_size=batch_size,pin_memory=True,shuffle=False)\\\n ,dT_train.max()\n \n if data_type == 'sp':\n [T,score_ref] = generate_stationary_poisson()\n elif data_type == 'nsp':\n [T,score_ref] = generate_nonstationary_poisson()\n elif data_type == 'sr':\n [T,score_ref] = generate_stationary_renewal()\n elif data_type == 'nsr':\n [T,score_ref]=generate_nonstationary_renewal()\n elif data_type == 'sc':\n [T,score_ref]=generate_self_correcting()\n elif data_type == 'h1':\n [T,score_ref]=generate_hawkes1()\n elif data_type == 'h2':\n [T,score_ref]=generate_hawkes2()\n elif data_type == 'h_fix':\n [T,score_ref]=generate_hawkes_modes()\n elif data_type == 'h_fix05':\n [T,score_ref]=generate_hawkes_modes05()\n n = T.shape[0]\n time_step=opt.time_step\n batch_size=opt.batch_size\n\n training_data, valid_data, test_data ,train_max = transform_data(T,int(n*0.8),int(n*0.1),int(n*0.1),time_step,batch_size) # A sequence is divided into training and test data.\n \n return training_data,valid_data, test_data,train_max\ndef set_date_class(df,opt):\n def rolling_matrix(x,time_step):\n x = x.flatten()\n n = x.shape[0]\n stride = x.strides[0]\n return np.lib.stride_tricks.as_strided(x, shape=(n-time_step+1, time_step), strides=(stride,stride) ).copy()\n \n df[\"dt64\"] = df[\"dtt64\"].map(pd.Timestamp.timestamp)/3600##UNIX変換\n \n #df[\"MT\"]=df[\"MagType\"].map({'ML': 0, 'Md': 1, 'Mx': 2, 'Mh': 3, 'Mw': 4, 'Unk': 5})\n\n df_train=df[:int(len(df)*0.8)]\n dT_train=np.ediff1d(df_train[\"dt64\"])\n train_data = torch.tensor(rolling_matrix(dT_train,opt.time_step)).to(torch.double)\n \n train_dataset = torch.utils.data.TensorDataset(train_data)\n df_valid=df[int(len(df)*0.8):int(len(df)*0.9)]\n dT_valid=np.ediff1d(df_valid[\"dt64\"])\n rT_valid = torch.tensor(rolling_matrix(dT_valid,opt.time_step)).to(torch.double)\n \n df_test = df[int(len(df)*0.9):]\n df_test = df_test.reset_index()\n \n dT_test = np.ediff1d(df_test[\"dt64\"])\n rT_test = torch.tensor(rolling_matrix(dT_test,opt.time_step)).to(torch.double)\n \n if opt.train==True:\n trainloader = torch.utils.data.DataLoader(train_data,num_workers=os.cpu_count(),batch_size=opt.batch_size,pin_memory=True,shuffle=True)\n validloader = torch.utils.data.DataLoader(rT_valid,num_workers=os.cpu_count(),batch_size=opt.batch_size,pin_memory=True,shuffle=False)\n testloader = torch.utils.data.DataLoader(rT_test,num_workers=os.cpu_count(),batch_size=opt.batch_size,pin_memory=True,shuffle=False)\n train_max=dT_train.max()\n return trainloader, validloader,testloader,train_max\n trainloader = torch.utils.data.DataLoader(train_data,num_workers=os.cpu_count(),batch_size=opt.batch_size,pin_memory=True,shuffle=True)\n validloader = torch.utils.data.DataLoader(rT_valid,num_workers=os.cpu_count(),batch_size=opt.batch_size,pin_memory=True,shuffle=False)\n testloader = torch.utils.data.DataLoader(rT_test,num_workers=os.cpu_count(),batch_size=opt.batch_size,pin_memory=True,shuffle=False)\n train_max=dT_train.max()\n return trainloader, validloader,testloader,train_max\n \n################\n### Early Stop\n################\nclass EarlyStopping:\n def __init__(self,patience=10, verbose=False, path='c_model.pth'):\n self.patience = patience\n self.verbose = verbose\n self.counter = 0\n self.best_score = None\n self.early_stop = False\n self.val_loss_min = np.Inf\n self.path = path\n def __call__(self, val_loss, model):\n score = -val_loss\n if self.best_score is None:\n self.best_score = score\n self.checkpoint(val_loss, model)\n elif score < self.best_score: # ベストスコアを更新できなかった場合\n self.counter += 1\n if self.verbose: #表示を有b効にした場合は経過を表示\n print(f'EarlyStopping counter: {self.counter} out of {self.patience}') #現在のカウンタを表示する \n if self.counter >= self.patience:\n self.early_stop = True\n else:\n self.best_score = score\n self.checkpoint(val_loss, model)\n self.counter = 0\n def checkpoint(self, val_loss, model):\n if self.verbose:\n print(f'Validation loss decreased ({self.val_loss_min:.6f} --> {val_loss:.6f}). Saving model ...')\n torch.save(model.state_dict(), self.path) #ベストモデルを指定したpathに保存\n self.val_loss_min = val_loss #その時のlossを記録する\n\n################\n### Train\n################\ndef train_epoch(model, training_data, optimizer, opt):\n \"\"\" Epoch operation in training phase. \"\"\"\n model.train()\n\n scaler = torch.cuda.amp.GradScaler()\n\n total_event_ll = 0 # cumulative event log-likelihood\n total_time_se = 0 # cumulative time prediction squared-error\n total_time_ae = 0\n total_num_event = 0 # number of total events\n #total_num_pred = 0 # number of predictions\n \n for batch in tqdm(training_data, mininterval=2,\n desc='-(Training) ', leave=False):\n \"\"\" prepare data \"\"\"\n event_time = batch.to(opt.device, non_blocking=True)\n train_input = event_time[:,:-1]#[B,Seqence-1]\n train_target = event_time[:,-1:]#[B,1]\n #train_target = train_target.unsqueeze(-1)\n \"\"\" forward \"\"\"\n optimizer.zero_grad()\n \n #model_output [B,L,M], prediction[B,1]\n model_output, prediction = model(train_input,train_target)\n \n \"\"\" backward \"\"\"\n # negative log-likelihood\n #event_ll[B,1,1], non_event_ll.shape[B,1,1]\n \n event_ll, non_event_ll = Utils.log_likelihood(model, model_output, train_input, train_target)\n event_loss = -torch.sum(event_ll - non_event_ll)#[]\n # time prediction\n se = Utils.time_loss_se(prediction, train_input, train_target)#[]\n ae = Utils.time_loss_ae(prediction, train_input, train_target)#[]\n # SE is usually large, scale it to stabilize training\n loss = event_loss + ae / opt.loss_scale\n loss.backward()\n \"\"\" update parameters \"\"\"\n optimizer.step()\n\n \"\"\" note keeping \"\"\"\n total_event_ll += -event_loss.item()\n total_time_se += se.item()\n total_time_ae += ae.item()\n total_num_event += event_time.shape[0] \n \n rmse = np.sqrt(total_time_se / total_num_event)\n mae = total_time_ae / total_num_event\n return total_event_ll / total_num_event, mae, rmse\n################\n### Evaluation\n################\ndef eval_epoch(model, validation_data, opt):\n \"\"\" Epoch operation in evaluation phase. \"\"\"\n\n model.eval()\n\n total_event_ll = 0 # cumulative event log-likelihood\n total_time_se = 0 # cumulative time prediction squared-error\n total_time_ae = 0\n total_num_event = 0 # number of total events\n total_num_pred = 0 # number of predictions\n with torch.no_grad():\n for batch in tqdm(validation_data, mininterval=2,\n desc=' - (Validation) ', leave=False):\n \"\"\" prepare data \"\"\"\n \n event_time = batch.to(opt.device,non_blocking=True)\n train_input = event_time[:,:-1]\n train_target = event_time[:,-1:]\n\n \"\"\" forward \"\"\"\n output, prediction = model(train_input,train_target)\n \"\"\" compute loss \"\"\"\n event_ll, non_event_ll = Utils.log_likelihood(model, output, train_input, train_target)\n event_loss = -torch.sum(event_ll - non_event_ll) \n \n # time prediction\n se = Utils.time_loss_se(prediction, train_input, train_target)\n ae = Utils.time_loss_ae(prediction, train_input, train_target)\n \n \"\"\" note keeping \"\"\"\n total_event_ll += -event_loss.item()\n total_time_se += se.item()\n total_time_ae += ae.item()\n total_num_event += event_time.shape[0]\n \n rmse = np.sqrt(total_time_se / total_num_event)\n mae = total_time_ae / total_num_event\n return total_event_ll / total_num_event, mae, rmse\n\n\n################\n### train-eval-plot-earlystop\n################\ndef train(model, training_data, validation_data, test_data, optimizer, scheduler, opt):\n \"\"\" Start training. \"\"\"\n\n valid_event_losses = [] # validation log-likelihood\n valid_mae_history = [] # validation event time prediction MAE\n valid_rmse_history = [] # validation event time prediction RMSE\n if opt.train==True:\n\n torch.backends.cudnn.benchmark = True\n \n es = EarlyStopping(verbose=True,path=\"checkpoint/tau/\"+opt.wp+'.pth')\n for epoch_i in range(opt.epoch):\n epoch = epoch_i + 1\n print('[ Epoch', epoch, ']')\n\n start = time.time()\n \n train_event, train_mae ,train_rmse= train_epoch(model, training_data, optimizer, opt)\n print(' - (Training) loglikelihood: {ll: 8.5f}, '\n ' MAE: {mae: 8.5f},'\n 'RMSE: {rmse: 8.5f}, '\n 'elapse: {elapse:3.3f} min'\n .format(ll=train_event, mae=train_mae, rmse=train_rmse, elapse=(time.time() - start) / 60))\n \n start = time.time()\n valid_event, valid_mae, valid_rmse = eval_epoch(model, validation_data, opt)\n print(' - (Testing) loglikelihood: {ll: 8.5f}, '\n ' MAE: {mae: 8.5f},'\n ' RMSE: {rmse: 8.5f}, '\n 'elapse: {elapse:3.3f} min'\n .format(ll=valid_event, mae=valid_mae, rmse=valid_rmse, elapse=(time.time() - start) / 60))\n\n valid_event_losses += [valid_event]\n valid_mae_history += [valid_mae]\n valid_rmse_history += [valid_rmse]\n print(' - [Info] Maximum ll: {event: 8.5f}, Minimum MAE: {mae: 8.5f}, Minimum RMSE:{rmse: 8.5f}'\n .format(event=max(valid_event_losses), mae=min(valid_mae_history), rmse=min(valid_rmse_history)))\n\n # logging\n with open(opt.log, 'a') as f:\n f.write(\"train : \"+'{epoch}, {loss: 8.5f}, {ll: 8.5f}, {mae: 8.5f}, {rmse: 8.5f}\\n'\n .format(epoch=epoch,loss=-train_event+train_mae/opt.loss_scale, ll=train_event, mae=train_mae, rmse=train_rmse))\n f.write(\"validation: \"+'{epoch}, {loss: 8.5f}, {ll: 8.5f}, {mae: 8.5f}, {rmse: 8.5f}\\n\\n'\n .format(epoch=epoch,loss=-valid_event+ valid_mae/opt.loss_scale, ll=valid_event, mae=valid_mae, rmse=valid_rmse))\n \n\n scheduler.step()\n print(valid_event)\n ## EarlyStopping\n es( -valid_event+ valid_mae/opt.loss_scale ,model)\n if es.early_stop: #ストップフラグがTrueの場合、breakでforループを抜ける\n print(\"Early Stopping!\")\n break\n model_path=\"checkpoint/tau/\"+opt.wp+'.pth'\n model.load_state_dict(torch.load(model_path))\n model.eval()\n test_event, test_mae, test_rmse = eval_epoch(model, test_data, opt)\n print(' - (testing ) Loss:{loss: 8.5f},loglikelihood: {ll: 8.5f}, '\n ' MAE: {mae: 8.5f},'\n ' RMSE: {rmse: 8.5f}, '\n 'elapse: {elapse:3.3f} min'\n .format(loss=-test_event+ test_mae/opt.loss_scale, ll=test_event, mae=test_mae, rmse=test_rmse, elapse=(time.time() - start) / 60))\n with open(opt.log, 'a') as f:\n f.write(\"testing: \"+'{epoch}, {loss: 8.5f}, {ll: 8.5f}, {mae: 8.5f}, {rmse: 8.5f}\\n'\n .format(epoch=epoch,loss=-test_event+ test_mae/opt.loss_scale, ll=test_event, mae=test_mae, rmse=test_rmse))\n else:\n model_path=\"checkpoint/tau/\"+opt.wp+'.pth'\n model.load_state_dict(torch.load(model_path))\n model.eval()\n start = time.time()\n test_event, test_mae, test_rmse = eval_epoch(model, test_data, opt)\n print(' - (Testing) loglikelihood: {ll: 8.5f}, '\n ' MAE: {mae: 8.5f},'\n ' RMSE: {rmse: 8.5f}, '\n 'elapse: {elapse:3.3f} min'\n .format(ll=test_event, mae=test_mae, rmse=test_rmse, elapse=(time.time() - start) / 60))\n \ndef test_step(model, training_data, validation_data, test_data, optimizer, scheduler, opt):\n model_path=\"checkpoint/tau/\"+opt.wp+'.pth'\n model.load_state_dict(torch.load(model_path))\n model.eval()\n start = time.time()\n test_event, test_mae, test_rmse = eval_epoch(model, test_data, opt)\n print(' - (Testing) loglikelihood: {ll: 8.5f}, '\n ' MAE: {mae: 8.5f},'\n ' RMSE: {rmse: 8.5f}, '\n 'elapse: {elapse:3.3f} min'\n .format(ll=test_event, mae=test_mae, rmse=test_rmse, elapse=(time.time() - start) / 60))\n #THP_plot_code.t_SNE(model,test_data,opt)\n #THP_plot_code.Compare_event_GT_pred(model,test_data,opt)\n\n#################\n### python Main.py -gene=h1 --train --pre_attn\n### python Main.py -gene=jisin --pre_attn --train\n### python Main.py --train -imp=kanseih2 -batch_size=32 -d_model=64 -d_inner_hid=128 -d_k=16 -d_v=16 -lr=1e-4 --pickle_F\n### python Main.py -imp=paraim -d_model=512 -d_inner_hid=2048 \n#################\ndef main():\n \"\"\" Main function. \"\"\"\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-epoch', type=int, default=1000)\n parser.add_argument('-batch_size', type=int, default=128)#32\n parser.add_argument('-loss_scale',type=int,default=1)\n\n parser.add_argument('-d_model', type=int, default=64)#512\n parser.add_argument('-d_inner_hid', type=int, default=64)#1024\n parser.add_argument('-d_k', type=int, default=8)#512\n parser.add_argument('-d_v', type=int, default=8)#512\n\n parser.add_argument('-n_head', type=int, default=8)\n parser.add_argument('-n_layers', type=int, default=4)#2\n\n parser.add_argument('-dropout', type=float, default=0.1)\n parser.add_argument('-lr', type=float, default=1e-4)#1e-5\n parser.add_argument('-smooth', type=float, default=0.1)\n parser.add_argument('-gene', type=str, default='h1')\n parser.add_argument('-log', type=str, default='log/log.txt')\n parser.add_argument('-wp', type=str, default='_')\n\n parser.add_argument('-imp', type=str, default='_')\n parser.add_argument(\"-train_mean\", type=float, default=0)\n parser.add_argument(\"-train_max\", type=float, default=0)\n\n parser.add_argument(\"-gentei_magni\", type=float, default=10.0)\n\n parser.add_argument(\"-time_step\", type=int, default=30)\n\n\n #parser.add_argument(\"-ys\",type=str, default=\"All\")\n parser.add_argument(\"-pst\",type=str, default=\"lon\")\n parser.add_argument(\"-Dishi\",type=int, default=4)\n parser.add_argument(\"--train\",action=\"store_true\")\n parser.add_argument(\"--pickle_F\",action='store_true')\n parser.add_argument(\"-method\",type=str, default=\"THP\")\n parser.add_argument(\"--miman\",action='store_true')\n parser.add_argument(\"--pre_attn\",action='store_true')\n opt = parser.parse_args()\n\n # default device is CUDA\n opt.device = torch.device('cuda:0')\n \n print('[Info] parameters: {}'.format(opt))\n\n pickle_Flag=False\n \"\"\" prepare dataloader \"\"\"\n if opt.gene==\"jisin\":\n df = pd.read_csv(\"/data1/nishizawa/Desktop/Transtrans/Transformer-Hawkes-Process/data/date_jisin.90016\")\n df[\"dtt64\"] = pd.to_datetime(df[\"DateTime\"])\n trainloader, validloader, testloader, opt.train_max = set_date_class(df,opt)\n opt.gene = \"jisin\"\n \n elif opt.gene==\"911_All\":\n pickle_Flag= True\n train_path = \"/data1/nishizawa/Desktop/Transtrans/Transformer-Hawkes-Process/data/Call_All100_sliding_train.pkl\"\n valid_path = \"/data1/nishizawa/Desktop/Transtrans/Transformer-Hawkes-Process/data/Call_All100_sliding_valid.pkl\"\n test_path = \"/data1/nishizawa/Desktop/Transtrans/Transformer-Hawkes-Process/data/Call_All100_sliding_test.pkl\"\n \n elif opt.gene==\"911_1\":\n pickle_Flag= True\n train_path = \"/data1/nishizawa/Desktop/Transtrans/Transformer-Hawkes-Process/data/Call_1_freq_sliding_train.pkl\"\n valid_path = \"/data1/nishizawa/Desktop/Transtrans/Transformer-Hawkes-Process/data/Call_1_freq_sliding_valid.pkl\"\n test_path = \"/data1/nishizawa/Desktop/Transtrans/Transformer-Hawkes-Process/data/Call_1_freq_sliding_test.pkl\"\n\n elif opt.gene==\"911_50\":\n pickle_Flag= True\n train_path = \"/data1/nishizawa/Desktop/Transtrans/Transformer-Hawkes-Process/data/Call_50_freq_sliding_train.pkl\"\n valid_path = \"/data1/nishizawa/Desktop/Transtrans/Transformer-Hawkes-Process/data/Call_50_freq_sliding_valid.pkl\"\n test_path = \"/data1/nishizawa/Desktop/Transtrans/Transformer-Hawkes-Process/data/Call_50_freq_sliding_test.pkl\"\n \n elif opt.gene==\"911_100\":\n pickle_Flag= True\n train_path = \"/data1/nishizawa/Desktop/Transtrans/Transformer-Hawkes-Process/data/Call_100_freq_sliding_train.pkl\"\n valid_path = \"/data1/nishizawa/Desktop/Transtrans/Transformer-Hawkes-Process/data/Call_100_freq_sliding_valid.pkl\"\n test_path = \"/data1/nishizawa/Desktop/Transtrans/Transformer-Hawkes-Process/data/Call_100_freq_sliding_test.pkl\"\n\n else:\n trainloader, validloader, testloader, opt.train_max = generate_data(opt.gene,opt)\n \n if pickle_Flag==True:\n with open(train_path, 'rb') as f:\n train_data = pickle.load(f)\n with open(valid_path, 'rb') as f:\n valid_data = pickle.load(f)\n with open(test_path, 'rb') as f:\n test_data = pickle.load(f)\n opt.train_max=train_data.max()\n opt.train_min=train_data.min()\n opt.train_med=np.median(train_data)\n train_torch = torch.tensor(train_data).to(torch.double)\n valid_torch = torch.tensor(valid_data).to(torch.double) \n test_torch = torch.tensor(test_data).to(torch.double) \n trainloader = torch.utils.data.DataLoader(train_torch,num_workers=os.cpu_count(),batch_size=opt.batch_size,pin_memory=True,shuffle=True)\n validloader = torch.utils.data.DataLoader(valid_torch,num_workers=os.cpu_count(),batch_size=opt.batch_size,pin_memory=True,shuffle=False)\n testloader = torch.utils.data.DataLoader(test_torch,num_workers=os.cpu_count(),batch_size=opt.batch_size,pin_memory=True,shuffle=False)\n \n opt.log = \"log/tau/\"+str(opt.d_model)+'_'+str(opt.d_inner_hid)+'_'+str(opt.d_k)+'_'+str(opt.d_v)+\"_\"+str(opt.n_head)+'_'+opt.gene+'_'+opt.method+'_'+opt.imp+'_'+str(opt.epoch)+\"_\"+str(opt.time_step)\n\n if opt.pre_attn == True:\n opt.log+=\"_preLN\"\n else:\n opt.log+=\"_postLN\"\n opt.wp = opt.log\n opt.log+=\"_log.txt\"\n\n # setup the log file\n if opt.train==True:\n with open(opt.log, 'w') as f:\n f.write('Epoch, Log-likelihood, MAE, RMSE\\n')\n else:\n print(\"Not training\")\n\n \"\"\" prepare model \"\"\"\n model = Transformer(\n d_model=opt.d_model,\n d_inner=opt.d_inner_hid,\n n_layers=opt.n_layers,\n n_head=opt.n_head,\n d_k=opt.d_k,\n d_v=opt.d_v,\n dropout=opt.dropout,\n time_step=opt.time_step,\n device=opt.device,\n train_max=opt.train_max,\n normalize_before=opt.pre_attn\n )\n model.to(opt.device)\n\n\n \"\"\" optimizer and scheduler \"\"\"\n optimizer = optim.Adam(filter(lambda x: x.requires_grad, model.parameters()),\n opt.lr, betas=(0.9, 0.999), eps=1e-05)\n \n scheduler = optim.lr_scheduler.StepLR(optimizer, 10, gamma=0.5)\n\n\n \"\"\" number of parameters \"\"\"\n num_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n print('[Info] Number of parameters: {}'.format(num_params))\n\n \"\"\" train the model \"\"\"\n if opt.train==True:\n train(model, trainloader, validloader, testloader, optimizer, scheduler, opt)\n else:\n test_step(model, trainloader, validloader, testloader, optimizer, scheduler, opt)\n\nif __name__ == '__main__':\n plt.switch_backend('agg')\n plt.figure()\n main()", "repo_name": "chihhar/2022Works", "sub_path": "related_works/THP/THP.py", "file_name": "THP.py", "file_ext": "py", "file_size_in_byte": 29093, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "numpy.random.seed", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 27, "usage_type": "attribute"}, {"api_name": "numpy.random.exponential", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 28, "usage_type": "attribute"}, {"api_name": "numpy.random.seed", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 34, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 37, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 38, "usage_type": "attribute"}, {"api_name": "numpy.cos", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.random.exponential", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 40, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 41, "usage_type": "attribute"}, {"api_name": "numpy.log", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 52, "usage_type": "attribute"}, {"api_name": "numpy.sqrt", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 53, "usage_type": "call"}, {"api_name": "scipy.stats.lognorm.rvs", "line_number": 55, "usage_type": "call"}, {"api_name": "scipy.stats.lognorm", "line_number": 55, "usage_type": "name"}, {"api_name": "numpy.exp", "line_number": 55, "usage_type": "call"}, {"api_name": "scipy.stats.lognorm.logpdf", "line_number": 56, "usage_type": "call"}, {"api_name": "scipy.stats.lognorm", "line_number": 56, "usage_type": "name"}, {"api_name": "numpy.exp", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 63, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 66, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 67, "usage_type": "attribute"}, {"api_name": "numpy.cos", "line_number": 67, "usage_type": "call"}, {"api_name": "scipy.stats.gamma.rvs", "line_number": 74, "usage_type": "call"}, {"api_name": "scipy.stats.gamma", "line_number": 74, "usage_type": "name"}, {"api_name": "scipy.stats.gamma.logpdf", "line_number": 75, "usage_type": "call"}, {"api_name": "scipy.stats.gamma", "line_number": 75, "usage_type": "name"}, {"api_name": "numpy.log", "line_number": 77, "usage_type": "call"}, {"api_name": "scipy.optimize.brentq", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 93, "usage_type": "attribute"}, {"api_name": "numpy.random.exponential", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 103, "usage_type": "attribute"}, {"api_name": "numpy.log", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 120, "usage_type": "attribute"}, {"api_name": "numpy.random.seed", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 126, "usage_type": "attribute"}, {"api_name": "numpy.random.exponential", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 145, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 149, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 152, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 155, "usage_type": "attribute"}, {"api_name": "numpy.log", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 168, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 171, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 171, "usage_type": "attribute"}, {"api_name": "numpy.random.exponential", "line_number": 201, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 201, "usage_type": "attribute"}, {"api_name": "numpy.random.exponential", "line_number": 203, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 203, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 207, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 208, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 210, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 214, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 214, "usage_type": "attribute"}, {"api_name": "numpy.log", "line_number": 216, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 228, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 231, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 231, "usage_type": "attribute"}, {"api_name": "numpy.random.exponential", "line_number": 261, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 261, "usage_type": "attribute"}, {"api_name": "numpy.random.exponential", "line_number": 263, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 263, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 267, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 268, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 270, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 271, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 274, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 274, "usage_type": "attribute"}, {"api_name": "numpy.log", "line_number": 276, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 288, "usage_type": "call"}, {"api_name": "numpy.lib.stride_tricks.as_strided", "line_number": 295, "usage_type": "call"}, {"api_name": "numpy.lib", "line_number": 295, "usage_type": "attribute"}, {"api_name": "numpy.ediff1d", "line_number": 301, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 303, "usage_type": "call"}, {"api_name": "torch.double", "line_number": 303, "usage_type": "attribute"}, {"api_name": "numpy.ediff1d", "line_number": 304, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 305, "usage_type": "call"}, {"api_name": "torch.double", "line_number": 305, "usage_type": "attribute"}, {"api_name": "numpy.ediff1d", "line_number": 308, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 310, "usage_type": "call"}, {"api_name": "torch.double", "line_number": 310, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 311, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 311, "usage_type": "attribute"}, {"api_name": "os.cpu_count", "line_number": 311, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 312, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 312, "usage_type": "attribute"}, {"api_name": "os.cpu_count", "line_number": 312, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 313, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 313, "usage_type": "attribute"}, {"api_name": "os.cpu_count", "line_number": 313, "usage_type": "call"}, {"api_name": "numpy.lib.stride_tricks.as_strided", "line_number": 346, "usage_type": "call"}, {"api_name": "numpy.lib", "line_number": 346, "usage_type": "attribute"}, {"api_name": "pandas.Timestamp", "line_number": 348, "usage_type": "attribute"}, {"api_name": "numpy.ediff1d", "line_number": 353, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 354, "usage_type": "call"}, {"api_name": "torch.double", "line_number": 354, "usage_type": "attribute"}, {"api_name": "torch.utils.data.TensorDataset", "line_number": 356, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 356, "usage_type": "attribute"}, {"api_name": "numpy.ediff1d", "line_number": 358, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 359, "usage_type": "call"}, {"api_name": "torch.double", "line_number": 359, "usage_type": "attribute"}, {"api_name": "numpy.ediff1d", "line_number": 364, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 365, "usage_type": "call"}, {"api_name": "torch.double", "line_number": 365, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 368, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 368, "usage_type": "attribute"}, {"api_name": "os.cpu_count", "line_number": 368, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 369, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 369, "usage_type": "attribute"}, {"api_name": "os.cpu_count", "line_number": 369, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 370, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 370, "usage_type": "attribute"}, {"api_name": "os.cpu_count", "line_number": 370, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 373, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 373, "usage_type": "attribute"}, {"api_name": "os.cpu_count", "line_number": 373, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 374, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 374, "usage_type": "attribute"}, {"api_name": "os.cpu_count", "line_number": 374, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 375, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 375, "usage_type": "attribute"}, {"api_name": "os.cpu_count", "line_number": 375, "usage_type": "call"}, {"api_name": "numpy.Inf", "line_number": 389, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 409, "usage_type": "call"}, {"api_name": "torch.cuda.amp.GradScaler", "line_number": 419, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 419, "usage_type": "attribute"}, {"api_name": "tqdm.tqdm", "line_number": 427, "usage_type": "call"}, {"api_name": "Utils.log_likelihood", "line_number": 444, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 445, "usage_type": "call"}, {"api_name": "Utils.time_loss_se", "line_number": 447, "usage_type": "call"}, {"api_name": "Utils.time_loss_ae", "line_number": 448, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 461, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 477, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 478, "usage_type": "call"}, {"api_name": "Utils.log_likelihood", "line_number": 489, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 490, "usage_type": "call"}, {"api_name": "Utils.time_loss_se", "line_number": 493, "usage_type": "call"}, {"api_name": "Utils.time_loss_ae", "line_number": 494, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 502, "usage_type": "call"}, {"api_name": "torch.backends", "line_number": 518, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 525, "usage_type": "call"}, {"api_name": "time.time", "line_number": 532, "usage_type": "call"}, {"api_name": "time.time", "line_number": 534, "usage_type": "call"}, {"api_name": "time.time", "line_number": 540, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 564, "usage_type": "call"}, {"api_name": "time.time", "line_number": 571, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 577, "usage_type": "call"}, {"api_name": "time.time", "line_number": 579, "usage_type": "call"}, {"api_name": "time.time", "line_number": 585, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 589, "usage_type": "call"}, {"api_name": "time.time", "line_number": 591, "usage_type": "call"}, {"api_name": "time.time", "line_number": 597, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 610, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 651, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 658, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 659, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 692, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 694, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 696, "usage_type": "call"}, {"api_name": "numpy.median", "line_number": 699, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 700, "usage_type": "call"}, {"api_name": "torch.double", "line_number": 700, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 701, "usage_type": "call"}, {"api_name": "torch.double", "line_number": 701, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 702, "usage_type": "call"}, {"api_name": "torch.double", "line_number": 702, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 703, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 703, "usage_type": "attribute"}, {"api_name": "os.cpu_count", "line_number": 703, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 704, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 704, "usage_type": "attribute"}, {"api_name": "os.cpu_count", "line_number": 704, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 705, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 705, "usage_type": "attribute"}, {"api_name": "os.cpu_count", "line_number": 705, "usage_type": "call"}, {"api_name": "transformer.Models.Transformer", "line_number": 724, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 741, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 741, "usage_type": "name"}, {"api_name": "torch.optim.lr_scheduler.StepLR", "line_number": 744, "usage_type": "call"}, {"api_name": "torch.optim.lr_scheduler", "line_number": 744, "usage_type": "attribute"}, {"api_name": "torch.optim", "line_number": 744, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.switch_backend", "line_number": 758, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 758, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 759, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 759, "usage_type": "name"}]} +{"seq_id": "12645706617", "text": "from io import BytesIO\nimport os\nimport copy\nimport random\nimport uuid\nimport unittest.mock as mock\n\nimport pandas as pd\n\nfrom django.contrib.auth import get_user_model\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.core.files import File\n\nfrom rest_framework.exceptions import ValidationError\n\nfrom constants import DB_RESOURCE_KEY_TO_HUMAN_READABLE, \\\n OBSERVATION_SET_KEY, \\\n FEATURE_SET_KEY, \\\n PARENT_OP_KEY, \\\n RESOURCE_KEY, \\\n TSV_FORMAT, \\\n CSV_FORMAT, \\\n WILDCARD, \\\n UNSPECIFIED_FORMAT, \\\n MATRIX_KEY, \\\n INTEGER_MATRIX_KEY, \\\n ANNOTATION_TABLE_KEY\n\nfrom data_structures.observation_set import ObservationSet\n\nfrom resource_types import RESOURCE_MAPPING, \\\n GeneralResource, \\\n AnnotationTable, \\\n Matrix, \\\n IntegerMatrix\n\nfrom api.models import Resource, \\\n ResourceMetadata, \\\n Operation as OperationDb, \\\n OperationResource\nfrom api.serializers.resource_metadata import ResourceMetadataSerializer\nfrom api.utilities.resource_utilities import initiate_resource_validation, \\\n handle_valid_resource, \\\n handle_invalid_resource, \\\n check_file_format_against_type, \\\n add_metadata_to_resource, \\\n get_resource_by_pk, \\\n write_resource, \\\n retrieve_resource_class_instance, \\\n check_resource_request_validity, \\\n delete_resource_by_pk, \\\n get_resource_view, \\\n retrieve_metadata, \\\n retrieve_resource_class_standard_format, \\\n check_if_resource_unset\nfrom exceptions import NoResourceFoundException, \\\n ResourceValidationException, \\\n InactiveResourceException, \\\n OwnershipException\nfrom api.tests.base import BaseAPITestCase\nfrom api.tests.test_helpers import associate_file_with_resource\n\nBASE_TESTDIR = os.path.dirname(__file__)\nTESTDIR = os.path.join(BASE_TESTDIR, 'operation_test_files')\nVALIDATION_TESTDIR = os.path.join(BASE_TESTDIR, 'resource_validation_test_files')\n\n\nclass TestResourceUtilities(BaseAPITestCase):\n '''\n Tests the functions contained in the api.utilities.resource_utilities\n module.\n '''\n def setUp(self):\n self.establish_clients()\n \n def get_unset_resource(self):\n all_resources = Resource.objects.all()\n unset_resources = []\n for r in all_resources:\n if not r.resource_type:\n unset_resources.append(r)\n \n if len(unset_resources) == 0:\n raise ImproperlyConfigured('Need at least one'\n ' Resource without a type to test properly.'\n )\n return unset_resources[0]\n\n @mock.patch('api.utilities.resource_utilities.get_resource_by_pk')\n def test_resource_request_validity(self, mock_get_resource_by_pk):\n '''\n Test that we receive the proper result when\n a api.models.Resource instance is requested.\n This function is used to ensure that users can only\n access their own Resource instances\n '''\n active_owned_resources = Resource.objects.filter(owner=self.regular_user_1, is_active=True)\n inactive_owned_resources = Resource.objects.filter(owner=self.regular_user_1, is_active=False)\n active_resource = active_owned_resources[0]\n inactive_resource = inactive_owned_resources[0]\n active_pk = str(active_resource.pk)\n inactive_pk = str(inactive_resource.pk)\n\n mock_get_resource_by_pk.return_value = active_resource\n result = check_resource_request_validity(self.regular_user_1, active_pk)\n self.assertEqual(active_resource, result)\n\n mock_get_resource_by_pk.return_value = inactive_resource\n with self.assertRaises(InactiveResourceException):\n result = check_resource_request_validity(self.regular_user_1, inactive_pk)\n\n mock_get_resource_by_pk.return_value = active_resource\n with self.assertRaises(OwnershipException):\n result = check_resource_request_validity(self.regular_user_2, active_pk)\n\n mock_get_resource_by_pk.side_effect = NoResourceFoundException\n with self.assertRaises(NoResourceFoundException):\n check_resource_request_validity(self.regular_user_1, active_pk)\n\n\n def test_get_resource_by_pk_works_for_all_resources(self):\n '''\n We use the api.utilities.resource_utilities.get_resource_by_pk\n function to check for the existence of all children of the \n AbstractResource class. Test that it all works as expected.\n '''\n with self.assertRaises(NoResourceFoundException):\n get_resource_by_pk(uuid.uuid4())\n\n r = Resource.objects.all()\n r = r[0]\n r2 = get_resource_by_pk(r.pk)\n self.assertEqual(r,r2)\n\n ops = OperationDb.objects.all()\n op = ops[0]\n r3 = OperationResource.objects.create(\n operation = op,\n input_field = 'foo',\n name = 'foo.txt',\n resource_type = 'MTX',\n file_format = TSV_FORMAT,\n datafile = File(BytesIO(), 'xyz.tsv')\n )\n r4 = get_resource_by_pk(r3.pk)\n self.assertEqual(r3,r4)\n\n @mock.patch('api.utilities.resource_utilities.alert_admins')\n @mock.patch('api.utilities.resource_utilities.get_resource_by_pk')\n def test_resource_delete(self, mock_get_resource_by_pk, mock_alert_admins):\n '''\n Tests that the function for deleting a database record works as expected\n '''\n # mock the simple/expected deletion\n mock_resource = mock.MagicMock()\n mock_get_resource_by_pk.return_value = mock_resource\n mock_pk = str(uuid.uuid4())\n delete_resource_by_pk(mock_pk)\n mock_get_resource_by_pk.assert_called_with(mock_pk)\n mock_resource.delete.assert_called()\n\n # mock that the resource was inactive. This function does NOT care about that.\n # Any deletion logic (e.g. disallowing for inactive files) should be implemented\n # prior to calling this function. Hence, the delete should succeed below:\n mock_resource = mock.MagicMock()\n mock_resource.is_active = False\n mock_get_resource_by_pk.return_value = mock_resource\n delete_resource_by_pk(mock_pk)\n mock_get_resource_by_pk.assert_called_with(mock_pk)\n mock_resource.delete.assert_called()\n\n # check that a database deletion failure will notify the admins\n mock_resource = mock.MagicMock()\n mock_resource.delete.side_effect = Exception('ack!')\n mock_get_resource_by_pk.return_value = mock_resource\n delete_resource_by_pk(mock_pk)\n mock_get_resource_by_pk.assert_called_with(mock_pk)\n mock_resource.delete.assert_called()\n mock_alert_admins.assert_called()\n\n def test_retrieve_metadata(self):\n mock_resource_class_instance = mock.MagicMock()\n mock_metadata = {\n 'mock_key': 'mock_value'\n }\n mock_resource_class_instance.extract_metadata.return_value = mock_metadata\n mock_path = '/some/mock/path.tsv'\n result = retrieve_metadata(mock_path, mock_resource_class_instance)\n self.assertDictEqual(result, mock_metadata)\n mock_resource_class_instance.extract_metadata.assert_called_with(mock_path)\n\n v = ValidationError({'key': 'val'})\n mock_resource_class_instance.extract_metadata.side_effect = v\n with self.assertRaisesRegex(ResourceValidationException, 'key:val') as ex:\n retrieve_metadata(mock_path, mock_resource_class_instance)\n\n mock_resource_class_instance.extract_metadata.side_effect = Exception('ack')\n with self.assertRaisesRegex(Exception, 'unexpected issue') as ex:\n retrieve_metadata(mock_path, mock_resource_class_instance)\n\n @mock.patch('api.utilities.resource_utilities.get_standard_format')\n def test_retrieve_standard_format(self, mock_get_standard_format):\n expected_format = 'foo_123'\n mock_type = 'foobar'\n mock_get_standard_format.return_value = expected_format\n result = retrieve_resource_class_standard_format(mock_type)\n self.assertEqual(result, expected_format)\n\n mock_get_standard_format.side_effect = KeyError('abc!')\n with self.assertRaisesRegex(Exception, mock_type):\n retrieve_resource_class_standard_format(mock_type)\n\n @mock.patch('resource_types.RESOURCE_MAPPING')\n def test_resource_preview_for_valid_resource_type(self, mock_resource_mapping):\n '''\n Tests that a proper preview dict is returned. Mocks out the \n method that does the reading of the resource path.\n '''\n all_resources = Resource.objects.all()\n resource = None\n for r in all_resources:\n if r.resource_type:\n resource = r\n break\n if not resource:\n raise ImproperlyConfigured('Need at least one resource with'\n ' a specified resource_type to run this test.'\n )\n\n expected_dict = {'a': 1, 'b':2}\n\n class mock_resource_type_class(object):\n def get_contents(self, resource, query_params={}, preview=False):\n return expected_dict\n\n mock_resource_mapping.__getitem__.return_value = mock_resource_type_class\n preview_dict = get_resource_view(r)\n self.assertDictEqual(expected_dict, preview_dict)\n\n\n def test_resource_preview_for_null_resource_type(self):\n '''\n Tests that a proper preview dict is returned. Mocks out the \n method that does the reading of the resource path.\n '''\n all_resources = Resource.objects.all()\n resource = None\n for r in all_resources:\n if r.resource_type is None:\n resource = r\n break\n if not resource:\n raise ImproperlyConfigured('Need at least one resource without'\n ' a specified resource_type to run this test.'\n )\n\n preview_dict = get_resource_view(r)\n self.assertIsNone(preview_dict)\n\n @mock.patch('api.utilities.resource_utilities.retrieve_resource_class_instance')\n @mock.patch('api.utilities.resource_utilities.handle_invalid_resource')\n @mock.patch('api.utilities.resource_utilities.perform_validation')\n @mock.patch('api.utilities.resource_utilities.handle_valid_resource')\n def test_invalid_handler_called(self, mock_handle_valid_resource, \\\n mock_perform_validation, \\\n mock_handle_invalid_resource, \\\n mock_retrieve_resource_class_instance):\n '''\n Here we test that a failure to validate the resource calls the proper\n handler function.\n '''\n unset_resource = self.get_unset_resource()\n\n mock_resource_class_instance = mock.MagicMock()\n mock_resource_class_instance.performs_validation.return_value = True\n mock_msg = 'some error message'\n mock_perform_validation.return_value = (False, mock_msg)\n mock_retrieve_resource_class_instance.return_value = mock_resource_class_instance\n\n initiate_resource_validation(unset_resource, 'MTX', 'csv')\n\n mock_handle_invalid_resource.assert_called_with(\n unset_resource,\n 'MTX',\n 'csv',\n mock_msg\n )\n mock_retrieve_resource_class_instance.assert_called_with('MTX')\n mock_handle_valid_resource.assert_not_called()\n\n # requery the resource\n r = Resource.objects.get(pk=unset_resource.pk)\n self.assertIsNone(r.resource_type)\n if unset_resource.file_format == '':\n self.assertEqual(r.file_format, '')\n else:\n self.assertIsNone(r.file_format)\n\n @mock.patch('api.utilities.resource_utilities.retrieve_resource_class_instance')\n @mock.patch('api.utilities.resource_utilities.handle_invalid_resource')\n @mock.patch('api.utilities.resource_utilities.check_file_format_against_type')\n @mock.patch('api.utilities.resource_utilities.perform_validation')\n @mock.patch('api.utilities.resource_utilities.handle_valid_resource')\n def test_valid_handler_called(self, mock_handle_valid_resource, \\\n mock_perform_validation, \\\n mock_check_file_format_against_type, \\\n mock_handle_invalid_resource, \\\n mock_retrieve_resource_class_instance):\n '''\n Here we test that a successful validation calls the proper\n handler function.\n '''\n unset_resource = self.get_unset_resource()\n\n mock_resource_class_instance = mock.MagicMock()\n mock_resource_class_instance.STANDARD_FORMAT = TSV_FORMAT\n mock_resource_class_instance.performs_validation.return_value = True\n mock_retrieve_resource_class_instance.return_value = mock_resource_class_instance\n \n mock_perform_validation.return_value = (True, None)\n\n initiate_resource_validation(unset_resource, 'MTX', TSV_FORMAT)\n\n mock_handle_valid_resource.assert_called_with(\n unset_resource,\n mock_resource_class_instance\n )\n mock_handle_invalid_resource.assert_not_called()\n\n # requery the resource\n r = Resource.objects.get(pk=unset_resource.pk)\n self.assertTrue(r.resource_type == 'MTX')\n self.assertTrue(r.file_format == TSV_FORMAT)\n\n @mock.patch('api.utilities.resource_utilities.retrieve_resource_class_instance')\n @mock.patch('api.utilities.resource_utilities.handle_valid_resource')\n @mock.patch('api.utilities.resource_utilities.handle_invalid_resource')\n @mock.patch('api.utilities.resource_utilities.check_file_format_against_type')\n def test_proper_exceptions_raised_case1(self, \\\n mock_check_file_format_against_type, \\\n mock_handle_invalid_resource, \\\n mock_handle_valid_resource, \\\n mock_retrieve_resource_class_instance):\n '''\n If unexpected errors (like connecting to cloud storage occur), check that we raise exceptions\n that provide helpful errors.\n\n Here, we test if the `check_file_format_against_type` function raises an exception. Note that if\n a predictable failure there (i.e. an inconsistent resource type and format were specified), then\n the function raises a ResourceValidationException. Since this exception is not expected, it is NOT\n of that type.\n '''\n mock_check_file_format_against_type.side_effect = [Exception('something unexpected!')]\n\n unset_resource = self.get_unset_resource()\n\n with self.assertRaisesRegex(Exception, 'something unexpected'):\n initiate_resource_validation(unset_resource, 'MTX', TSV_FORMAT)\n mock_handle_valid_resource.assert_not_called()\n mock_handle_invalid_resource.assert_not_called()\n mock_retrieve_resource_class_instance.assert_not_called()\n\n @mock.patch('api.utilities.resource_utilities.retrieve_resource_class_instance')\n @mock.patch('api.utilities.resource_utilities.handle_valid_resource')\n @mock.patch('api.utilities.resource_utilities.handle_invalid_resource')\n @mock.patch('api.utilities.resource_utilities.check_file_format_against_type')\n def test_proper_exceptions_raised_case2(self, \\\n mock_check_file_format_against_type, \\\n mock_handle_invalid_resource, \\\n mock_handle_valid_resource, \\\n mock_retrieve_resource_class_instance):\n '''\n If unexpected errors (like connecting to cloud storage occur), check that we raise exceptions\n that provide helpful errors.\n\n Here, we test if the `retrieve_resource_class_instance` function raises an exception from something\n unexpected\n '''\n mock_retrieve_resource_class_instance.side_effect = [Exception('ack'),]\n\n unset_resource = self.get_unset_resource()\n\n with self.assertRaisesRegex(Exception, 'ack'):\n initiate_resource_validation(unset_resource, 'MTX', TSV_FORMAT)\n mock_handle_valid_resource.assert_not_called()\n mock_handle_invalid_resource.assert_not_called()\n mock_retrieve_resource_class_instance.assert_called_with('MTX')\n\n\n @mock.patch('api.utilities.resource_utilities.retrieve_resource_class_instance')\n @mock.patch('api.utilities.resource_utilities.handle_valid_resource')\n @mock.patch('api.utilities.resource_utilities.handle_invalid_resource')\n @mock.patch('api.utilities.resource_utilities.check_file_format_against_type')\n def test_proper_exceptions_raised_case3(self, \\\n mock_check_file_format_against_type, \\\n mock_handle_invalid_resource, \\\n mock_handle_valid_resource, \\\n mock_retrieve_resource_class_instance):\n '''\n If unexpected errors (like connecting to cloud storage occur), check that we raise exceptions\n that provide helpful errors.\n\n Here, we test if the `retrieve_resource_class_instance` function raises an exception from an unknown\n resource type (a keyError). \n '''\n mock_retrieve_resource_class_instance.side_effect = [KeyError('ZZZ'),]\n\n unset_resource = self.get_unset_resource()\n\n with self.assertRaisesRegex(Exception, 'ZZZ'):\n initiate_resource_validation(unset_resource, 'ZZZ', TSV_FORMAT)\n mock_handle_valid_resource.assert_not_called()\n mock_handle_invalid_resource.assert_not_called()\n mock_retrieve_resource_class_instance.assert_called_with('ZZZ')\n \n @mock.patch('api.utilities.resource_utilities.handle_valid_resource')\n @mock.patch('api.utilities.resource_utilities.handle_invalid_resource')\n @mock.patch('api.utilities.resource_utilities.retrieve_resource_class_instance')\n @mock.patch('api.utilities.resource_utilities.perform_validation')\n @mock.patch('api.utilities.resource_utilities.check_file_format_against_type')\n def test_proper_exceptions_raised_case4(self, \\\n mock_check_file_format_against_type, \\\n mock_perform_validation, \\\n mock_retrieve_resource_class_instance, \\\n mock_handle_invalid_resource, \\\n mock_handle_valid_resource):\n '''\n If unexpected errors (like connecting to cloud storage occur), check that we raise exceptions\n that provide helpful errors.\n\n Here, we test if the validation method fails unexpectedly.\n '''\n mock_resource_class_instance = mock.MagicMock()\n mock_resource_class_instance.performs_validation.return_value = True\n mock_retrieve_resource_class_instance.return_value = mock_resource_class_instance\n\n err_msg = 'something unexpected.'\n mock_perform_validation.side_effect = [Exception(err_msg)]\n\n unset_resource = self.get_unset_resource()\n\n with self.assertRaisesRegex(Exception, err_msg):\n initiate_resource_validation(unset_resource, 'MTX', TSV_FORMAT)\n\n mock_perform_validation.assert_called_with(\n unset_resource,\n mock_resource_class_instance,\n TSV_FORMAT\n )\n mock_handle_valid_resource.assert_not_called()\n mock_handle_invalid_resource.assert_not_called()\n\n @mock.patch('api.utilities.resource_utilities.retrieve_resource_class_instance')\n @mock.patch('api.utilities.resource_utilities.handle_invalid_resource')\n @mock.patch('api.utilities.resource_utilities.check_file_format_against_type')\n @mock.patch('api.utilities.resource_utilities.perform_validation')\n @mock.patch('api.utilities.resource_utilities.handle_valid_resource')\n def test_proper_exceptions_raised_case5(self, mock_handle_valid_resource, \\\n mock_perform_validation, \\\n mock_check_file_format_against_type, \\\n mock_handle_invalid_resource, \\\n mock_retrieve_resource_class_instance):\n '''\n Here we test that a failure to extract metadata results in the resource\n not updating its fields. For instance, if we perform a 'standardization'\n but we ultimately cannot extract/save the metadata, we do NOT want to \n update the Resource.datafile attribute to that new standardized version. We only\n want to update the path to the standardized version if everything goes perfectly.\n '''\n\n def mock_save_in_standardized_format(resource, file_format):\n '''\n This allows us to avoid the actual implementation of the \n 'save_in_standardized_format' method.\n\n Here we just save some empty content which (since we are \n ultimately mocking a failure) doesn't matter. It does the \n same thing as the real method in that it re-assigns the\n datafile attribute to a new file.\n '''\n u = str(uuid.uuid4())\n with BytesIO() as b:\n resource.datafile = File(b,u)\n resource.save()\n\n unset_resource = self.get_unset_resource()\n original_path = unset_resource.datafile.name\n self.assertTrue(len(original_path)>0)\n\n mock_resource_class_instance = mock.MagicMock()\n mock_resource_class_instance.STANDARD_FORMAT = TSV_FORMAT\n mock_resource_class_instance.performs_validation.return_value = True\n mock_resource_class_instance.save_in_standardized_format = mock_save_in_standardized_format\n mock_retrieve_resource_class_instance.return_value = mock_resource_class_instance\n \n mock_perform_validation.return_value = (True, None)\n\n mock_handle_valid_resource.side_effect = Exception('something bad!')\n\n with self.assertRaisesRegex(Exception, 'something bad'):\n initiate_resource_validation(unset_resource, 'MTX', TSV_FORMAT)\n\n mock_handle_valid_resource.assert_called_with(\n unset_resource,\n mock_resource_class_instance\n )\n mock_handle_invalid_resource.assert_not_called()\n\n # requery the resource\n r = Resource.objects.get(pk=unset_resource.pk)\n\n # Note that the path did NOT remain the same.\n self.assertTrue(r.datafile.path != original_path)\n # the type and format were not set to the requested values:\n self.assertTrue(r.resource_type != 'MTX')\n self.assertTrue(r.file_format != TSV_FORMAT)\n\n @mock.patch('api.utilities.resource_utilities.check_if_resource_unset')\n def test_unset_resource_type_does_not_change_if_validation_fails(self, \\\n mock_check_if_resource_unset):\n '''\n For an unset resource (i.e. no resource_type or format) requesting\n a change that fails validation results in NO change to the resource_type\n attribute\n '''\n mock_check_if_resource_unset.return_value = True # True means previously unset\n unset_resource = self.get_unset_resource()\n\n with self.assertRaises(ResourceMetadata.DoesNotExist):\n metadata = ResourceMetadata.objects.get(resource=unset_resource)\n\n handle_invalid_resource(unset_resource, 'MTX', TSV_FORMAT, 'some error message')\n self.assertIsNone(unset_resource.resource_type)\n\n # now the metadata query should succeed\n metadata = ResourceMetadata.objects.get(resource=unset_resource)\n metadata = ResourceMetadataSerializer(metadata).data\n self.assertIsNone(metadata[PARENT_OP_KEY])\n self.assertIsNone(metadata[OBSERVATION_SET_KEY])\n self.assertIsNone(metadata[FEATURE_SET_KEY])\n self.assertEqual(metadata[RESOURCE_KEY], unset_resource.pk)\n\n def test_check_if_resource_unset(self):\n mock_resource = mock.MagicMock()\n self.assertTrue(check_if_resource_unset(mock_resource))\n\n mock_resource = mock.MagicMock()\n mock_resource.resource_type = MATRIX_KEY\n self.assertFalse(check_if_resource_unset(mock_resource))\n\n mock_resource = mock.MagicMock()\n mock_resource.file_format = TSV_FORMAT\n self.assertFalse(check_if_resource_unset(mock_resource))\n\n mock_resource = mock.MagicMock()\n mock_resource.resource_type = MATRIX_KEY\n mock_resource.file_format = TSV_FORMAT\n self.assertFalse(check_if_resource_unset(mock_resource))\n\n @mock.patch('api.utilities.resource_utilities.check_if_resource_unset')\n @mock.patch('api.utilities.resource_utilities.add_metadata_to_resource')\n def test_resource_type_does_not_change_if_validation_fails(self, \\\n mock_add_metadata_to_resource,\n mock_check_if_resource_unset\n ):\n '''\n If we had previously validated a resource successfully, requesting\n a change that fails validation results in NO change to the resource_type\n attribute\n '''\n mock_check_if_resource_unset.return_value = False\n\n all_resources = Resource.objects.all()\n set_resources = []\n for r in all_resources:\n if r.resource_type:\n set_resources.append(r)\n \n if len(set_resources) == 0:\n raise ImproperlyConfigured('Need at least one'\n ' Resource with a type to test properly.'\n )\n\n resource = set_resources[0]\n original_type = resource.resource_type\n other_type = original_type\n while other_type == original_type:\n other_type = random.choice(list(RESOURCE_MAPPING.keys()))\n handle_invalid_resource(resource, other_type, TSV_FORMAT, 'some error message')\n\n # we don't query for an 'updated' Resource since the `handle_invalid_resource`\n # function doesn't save. It only updates attributes.\n self.assertTrue(resource.resource_type == original_type)\n self.assertTrue(resource.status.startswith(Resource.REVERTED.format(\n requested_resource_type=DB_RESOURCE_KEY_TO_HUMAN_READABLE[other_type],\n original_resource_type = DB_RESOURCE_KEY_TO_HUMAN_READABLE[original_type],\n requested_file_format = TSV_FORMAT,\n file_format = resource.file_format\n )\n ))\n mock_add_metadata_to_resource.assert_not_called()\n\n\n @mock.patch.dict('api.utilities.resource_utilities.DB_RESOURCE_KEY_TO_HUMAN_READABLE', \\\n {'foo_type': 'Table'})\n @mock.patch('api.utilities.resource_utilities.format_is_acceptable_for_type')\n @mock.patch('api.utilities.resource_utilities.get_acceptable_formats')\n def test_inconsistent_file_extension_raises_proper_ex(self,\n mock_get_acceptable_formats,\n mock_format_is_acceptable_for_type):\n '''\n This tests the case where a user selects a resource type but the\n file does not have a format that is consistent with that type. We need\n to enforce canonical formats so we know how to try parsing files.\n '''\n mock_format_is_acceptable_for_type.return_value = False\n mock_get_acceptable_formats.return_value = ['tsv', 'csv', 'abc']\n requested_type = 'foo_type'\n human_readable_type = 'Table'\n file_format = 'xyz'\n with self.assertRaises(ResourceValidationException) as ex:\n check_file_format_against_type(requested_type, file_format)\n expected_status = Resource.UNKNOWN_FORMAT_ERROR.format(\n readable_resource_type = human_readable_type,\n fmt = resource.file_format,\n extensions_csv = 'tsv,csv,abc'\n )\n self.assertEqual(str(ex), expected_status)\n\n @mock.patch('api.utilities.resource_utilities.format_is_acceptable_for_type')\n def test_bad_resource_type_when_checking_type_and_format(self,\n mock_format_is_acceptable_for_type):\n '''\n This tests the case where a user selects a resource type that does not\n exist and the underlying function raises an exception\n '''\n mock_format_is_acceptable_for_type.side_effect = KeyError('ack')\n requested_type = 'foo_type'\n file_format = 'xyz'\n with self.assertRaisesRegex(ResourceValidationException, 'foo_type is not a known type'):\n check_file_format_against_type(requested_type, file_format)\n\n @mock.patch('api.utilities.resource_utilities.get_resource_type_instance')\n def test_bad_resource_type_when_retrieving_resource_type_instance(self,\n mock_get_resource_type_instance):\n '''\n This tests the case where a user selects a resource type that does not\n exist and the underlying function raises a KeyError\n '''\n mock_get_resource_type_instance.side_effect = KeyError('ack')\n requested_type = 'foo_type'\n with self.assertRaises(ResourceValidationException) as ex:\n retrieve_resource_class_instance(requested_type)\n expected_status = Resource.UNKNOWN_RESOURCE_TYPE_ERROR.format(\n requested_resource_type = requested_type\n )\n self.assertEqual(str(ex), expected_status)\n\n @mock.patch('api.utilities.resource_utilities.get_resource_type_instance')\n def test_unexpected_exception_when_retrieving_resource_type_instance(self,\n mock_get_resource_type_instance):\n '''\n This tests the case where a user selects a resource type that does not\n exist and the underlying function raises an exception\n '''\n mock_get_resource_type_instance.side_effect = Exception('ack')\n with self.assertRaises(Exception) as ex:\n retrieve_resource_class_instance(requested_type)\n\n @mock.patch('api.utilities.resource_utilities.retrieve_resource_class_instance')\n @mock.patch('api.utilities.resource_utilities.handle_valid_resource')\n @mock.patch('api.utilities.resource_utilities.check_file_format_against_type')\n def test_proper_steps_taken_with_wildcard_resource(self, \\\n mock_check_file_format_against_type, \\\n mock_handle_valid_resource, \\\n mock_retrieve_resource_class_instance):\n '''\n Here we test that a resource type with a \"wildcard\" type goes through the proper\n steps. That is, we should skip the validation, etc.\n '''\n all_resources = Resource.objects.all()\n r = all_resources[0]\n\n g = GeneralResource()\n mock_retrieve_resource_class_instance.return_value = g\n\n initiate_resource_validation(r, WILDCARD, UNSPECIFIED_FORMAT)\n\n mock_handle_valid_resource.assert_called_with(r,g)\n\n r = Resource.objects.get(pk=r.pk)\n self.assertTrue(r.resource_type == WILDCARD)\n self.assertTrue(r.file_format == UNSPECIFIED_FORMAT)\n\n def test_check_file_format_against_type_for_wildcard_resource(self):\n '''\n Checks that the type + format checking method just returns silently\n since we are trying to set to a wildcard/generic resource type\n '''\n self.assertIsNone(check_file_format_against_type(WILDCARD, ''))\n\n @mock.patch('api.utilities.resource_utilities.add_metadata_to_resource')\n @mock.patch('api.utilities.resource_utilities.retrieve_metadata')\n def test_check_handle_valid_resource_for_wildcard_type(self, \\\n mock_retrieve_metadata, \\\n mock_add_metadata_to_resource):\n '''\n Check that we do the proper things when we handle the apparently \n \"valid\" resource. For wildcard types, they are trivially valid, but\n we need to check that we are not calling any methods that wouldn't \n make sense in this context.\n '''\n mock_metadata = {\n 'dummy_key': 'dummy_value'\n }\n mock_retrieve_metadata.return_value = mock_metadata\n\n all_resources = Resource.objects.all()\n r = all_resources[0]\n g = GeneralResource()\n handle_valid_resource(r, g)\n\n mock_retrieve_metadata.assert_called()\n mock_add_metadata_to_resource.assert_called_with(\n r,\n mock_metadata\n )\n\n @mock.patch('api.utilities.resource_utilities.retrieve_metadata')\n @mock.patch('api.utilities.resource_utilities.add_metadata_to_resource')\n def test_metadata_addition_failure(self, \n mock_add_metadata_to_resource,\n mock_retrieve_metadata):\n '''\n Check that we do the proper things if the addition of the metadata\n to the resource fails.\n\n For instance, we had a case where the metadata extraction worked,\n but the sample IDs were too long. In that case, the `add_metadata_to_resource`\n function raised an uncaught exception and the Resource.path attribute\n was not set correctly.\n '''\n mock_metadata = {\n 'mock_key': 'mock_val'\n }\n mock_retrieve_metadata.return_value = mock_metadata\n mock_add_metadata_to_resource.side_effect = ValidationError('ack')\n\n all_resources = Resource.objects.all()\n r = all_resources[0]\n mock_path = '/some/path/to/file.tsv'\n mock_resource_class_instance = mock.MagicMock()\n with self.assertRaisesRegex(Exception, 'ack'):\n handle_valid_resource(r, mock_resource_class_instance)\n\n expected_calls = [\n mock.call(r, mock_metadata),\n mock.call(r, {RESOURCE_KEY: r.pk})\n ]\n mock_add_metadata_to_resource.assert_has_calls(expected_calls)\n mock_retrieve_metadata.assert_called_with(r, mock_resource_class_instance)\n\n def test_add_metadata(self):\n '''\n Test that we gracefully handle updates\n when associating metadata with a resource.\n\n Have a case where we update and we create a new ResourceMetadata\n '''\n # create a new Resource\n r = Resource.objects.create(\n name='foo.txt',\n owner = self.regular_user_1,\n datafile = File(BytesIO(), 'foo.txt')\n )\n rm = ResourceMetadata.objects.create(\n resource=r\n )\n rm_pk = rm.pk\n\n mock_obs_set = {\n 'elements': [\n {\n 'id': 'sampleA'\n },\n {\n 'id': 'sampleB'\n }\n ]\n }\n # verify that the mock above is valid\n oss = ObservationSet(mock_obs_set)\n\n add_metadata_to_resource(\n r, \n {\n OBSERVATION_SET_KEY:mock_obs_set\n }\n )\n\n # query again, see that it was updated\n rm2 = ResourceMetadata.objects.get(pk=rm_pk)\n expected_obs_set = copy.deepcopy(mock_obs_set)\n elements = expected_obs_set['elements']\n for el in elements:\n el.update({'attributes': {}})\n self.assertCountEqual(rm2.observation_set['elements'], elements)\n\n # OK, now get a Resource that does not already have metadata\n # associated with it: \n r = Resource.objects.create(\n name='bar.txt',\n owner = self.regular_user_1,\n datafile = File(BytesIO(), 'bar.txt')\n )\n with self.assertRaises(ResourceMetadata.DoesNotExist):\n ResourceMetadata.objects.get(resource=r)\n add_metadata_to_resource(\n r, \n {OBSERVATION_SET_KEY:mock_obs_set}\n )\n\n # query again, see that it was updated\n rm3 = ResourceMetadata.objects.get(resource=r)\n expected_obs_set = copy.deepcopy(mock_obs_set)\n elements = expected_obs_set['elements']\n for el in elements:\n el.update({'attributes': {}})\n self.assertCountEqual(rm3.observation_set['elements'], elements)\n\n def test_add_metadata_with_null(self):\n '''\n Test that we can successfully add resource metadata \n that contains null values.\n\n As an example, consider a basic annotation file where an entry is missing.\n The observation set we extract from that file will contain a null value\n '''\n # create a new Resource\n r = Resource.objects.create(\n name='foo.txt',\n owner = self.regular_user_1,\n datafile = File(BytesIO(), 'foo.txt')\n )\n rm = ResourceMetadata.objects.create(\n resource=r\n )\n rm_pk = rm.pk\n\n mock_obs_set = {\n 'elements': [\n {\n 'id': 'sampleA',\n 'attributes' : {\n \"alcohol_history\": {\n \"attribute_type\": \"UnrestrictedString\",\n \"value\": \"yes\"\n },\n \"age_at_index\": {\n \"attribute_type\": \"Float\",\n \"value\": 13.2\n },\n }\n },\n {\n 'id': 'sampleB',\n 'attributes' : {\n \"alcohol_history\": {\n \"attribute_type\": \"UnrestrictedString\",\n \"value\": \"yes\"\n },\n \"age_at_index\": {\n \"attribute_type\": \"Float\",\n \"value\": None\n },\n }\n }\n ]\n }\n # verify that the mock above is valid\n oss = ObservationSet(mock_obs_set, permit_null_attributes=True)\n\n # if no errors here, then we are ok\n add_metadata_to_resource(\n r, \n {\n OBSERVATION_SET_KEY:mock_obs_set\n }\n )\n\n @mock.patch('api.utilities.resource_utilities.retrieve_metadata')\n @mock.patch('api.utilities.resource_utilities.alert_admins')\n def test_catch_large_metadata_addition(self, \\\n mock_alert_admins, \\\n mock_retrieve_metadata\n ):\n '''\n Test that we gracefully handle problems when saving metadata\n\n This test stems from a bug where an annotation file (in tsv format) was\n parsed as a CSV. This produced a dataframe with shape (x,1), which is technically\n compliant. However, the metadata extracted from this table caused an issue saving\n in the database since the field exceeded the character limit. This was due to the \n fact that an entire row of the file was parsed as a single entry (a very long string)\n '''\n mock_obs_set = {\n 'multiple': True,\n 'elements': [\n {\n # this will cause metadata to fail since the ID is WAY too big\n 'id': 'sampleA'*5000 \n },\n {\n 'id': 'sampleB'\n }\n ]\n }\n mock_retrieve_metadata.return_value = {\n OBSERVATION_SET_KEY: mock_obs_set\n }\n\n # create a new Resource\n r = Resource.objects.create(\n name='foo.txt',\n owner = self.regular_user_1,\n datafile = File(BytesIO(), 'foo.txt')\n )\n # call the tested function\n resource_type = ANNOTATION_TABLE_KEY\n resource_class_instance = retrieve_resource_class_instance(resource_type)\n handle_valid_resource(r, resource_class_instance)\n mock_alert_admins.assert_called()\n\n rm = ResourceMetadata.objects.filter(resource=r)\n self.assertTrue(len(rm) == 1)\n rm0 = rm[0]\n self.assertIsNone(rm0.observation_set)\n self.assertTrue(rm0.resource == r)\n\n\n\n @mock.patch('api.utilities.resource_utilities.ResourceMetadataSerializer')\n @mock.patch('api.utilities.resource_utilities.alert_admins')\n def test_add_metadata_case2(self, mock_alert_admins, mock_serializer_cls):\n '''\n Test that we gracefully handle updates and save failures\n when associating metadata with a resource.\n\n Inspired by a runtime failure where the FeatureSet was too\n large for the database field. In such a case, we want to alert\n admins, but not stop a user from moving forward. Hence, we \n recover from the failure by saving a bare-minimum metadata\n payload.\n '''\n # create a new Resource\n r = Resource.objects.create(\n name='foo.txt',\n owner = self.regular_user_1,\n datafile = File(BytesIO(), 'foo.txt')\n )\n # ensure it has no associated metadata\n with self.assertRaises(ResourceMetadata.DoesNotExist):\n ResourceMetadata.objects.get(resource=r)\n\n # create some legitimate metadata to add. We ultimately \n # mock there being a failure when trying to save this,\n # but we at least give it real data here\n mock_obs_set = {\n 'elements': [\n {\n 'id': 'sampleA'\n },\n {\n 'id': 'sampleB'\n }\n ]\n }\n # verify that the mock above is valid\n oss = ObservationSet(mock_obs_set)\n\n # create a mock object that will raise an exception\n from django.db.utils import OperationalError\n mock_serializer1 = mock.MagicMock()\n mock_serializer1.is_valid.return_value = True\n mock_serializer1.save.side_effect = OperationalError\n # The first time we ask for a ResourceMetadataSerializer, we mock\n # out the implementation so that we can fake an issue with its save\n # method. The second time, we use the actual class so we can verify\n # that we save only \"basic\" data in the event of an OperationalError\n basic_data = {\n RESOURCE_KEY: r.pk\n }\n real_instance = ResourceMetadataSerializer(data=basic_data)\n mock_serializer_cls.side_effect = [mock_serializer1, real_instance]\n add_metadata_to_resource(\n r, \n {\n OBSERVATION_SET_KEY:mock_obs_set\n }\n )\n mock_alert_admins.assert_called()\n\n # check that we did actually persist the basic metadata to the db:\n rm = ResourceMetadata.objects.get(resource=r)\n rmd = ResourceMetadataSerializer(rm).data\n expected_metadata = {\n PARENT_OP_KEY: None,\n OBSERVATION_SET_KEY: None,\n FEATURE_SET_KEY: None,\n RESOURCE_KEY: r.pk\n }\n self.assertDictEqual(expected_metadata, rmd)\n\n @mock.patch('api.utilities.resource_utilities.ResourceMetadataSerializer')\n @mock.patch('api.utilities.resource_utilities.alert_admins')\n def test_add_metadata_case3(self, mock_alert_admins, mock_serializer_cls):\n '''\n Test that we gracefully handle updates and save failures\n when associating metadata with a resource.\n\n This covers the case where we encounter a generic Exception when\n trying to save the metadata. In such a case, we want to alert\n admins, but not stop a user from moving forward. Hence, we \n recover from the failure by saving a bare-minimum metadata\n payload.\n '''\n # create a new Resource\n r = Resource.objects.create(\n name='foo.txt',\n owner = self.regular_user_1,\n datafile = File(BytesIO(), 'foo.txt')\n )\n # ensure it has no associated metadata\n with self.assertRaises(ResourceMetadata.DoesNotExist):\n ResourceMetadata.objects.get(resource=r)\n\n # create some legitimate metadata to add. We ultimately \n # mock there being a failure when trying to save this,\n # but we at least give it real data here\n mock_obs_set = {\n 'elements': [\n {\n 'id': 'sampleA'\n },\n {\n 'id': 'sampleB'\n }\n ]\n }\n # verify that the mock above is valid\n oss = ObservationSet(mock_obs_set)\n\n # create a mock object that will raise an exception\n mock_serializer1 = mock.MagicMock()\n mock_serializer1.is_valid.return_value = True\n mock_serializer1.save.side_effect = Exception('ack!')\n # The first time we ask for a ResourceMetadataSerializer, we mock\n # out the implementation so that we can fake an issue with its save\n # method. The second time, we use the actual class so we can verify\n # that we save only \"basic\" data in the event of an unexpected Exception\n basic_data = {\n RESOURCE_KEY: r.pk\n }\n real_instance = ResourceMetadataSerializer(data=basic_data)\n mock_serializer_cls.side_effect = [mock_serializer1, real_instance]\n add_metadata_to_resource(\n r, \n {\n OBSERVATION_SET_KEY:mock_obs_set\n }\n )\n mock_alert_admins.assert_called()\n\n # check that we did actually persist the basic metadata to the db:\n rm = ResourceMetadata.objects.get(resource=r)\n rmd = ResourceMetadataSerializer(rm).data\n expected_metadata = {\n PARENT_OP_KEY: None,\n OBSERVATION_SET_KEY: None,\n FEATURE_SET_KEY: None,\n RESOURCE_KEY: r.pk\n }\n self.assertDictEqual(expected_metadata, rmd)\n\n\n @mock.patch('api.utilities.resource_utilities.make_local_directory')\n @mock.patch('api.utilities.resource_utilities.os')\n def test_resource_write_dir_fails(self, mock_os, mock_make_local_directory):\n '''\n Tests the case where we fail to create a directory\n to write into. Check that this is handled appropriately.\n '''\n mock_os.path.dirname.return_value = '/some/dir'\n mock_os.path.exists.return_value = False\n mock_make_local_directory.side_effect = Exception('something bad happened!')\n with self.assertRaises(Exception):\n write_resource('some content', '')\n\n @mock.patch('api.utilities.resource_utilities.make_local_directory')\n def test_resource_write_works_case1(self, mock_make_local_directory):\n '''\n Tests that we do, in fact, write correctly.\n Here, we use the /tmp folder, which exists\n '''\n self.assertTrue(os.path.exists('/tmp'))\n destination = '/tmp/some_file.txt'\n content = 'some content'\n write_resource(content, destination)\n self.assertTrue(os.path.exists(destination))\n read_content = open(destination).read()\n self.assertEqual(read_content, content)\n mock_make_local_directory.assert_not_called()\n # cleanup\n os.remove(destination)\n\n def test_resource_write_works_case2(self):\n '''\n Tests that we do, in fact, write correctly.\n Here, we write in a folder which doesn't already exist\n '''\n self.assertFalse(os.path.exists('/tmp/foo'))\n destination = '/tmp/foo/some_file.txt'\n content = 'some content'\n write_resource(content, destination)\n self.assertTrue(os.path.exists(destination))\n read_content = open(destination).read()\n self.assertEqual(read_content, content)\n # cleanup\n os.remove(destination)\n os.removedirs('/tmp/foo')\n\n def test_resource_write_only_writes_string(self):\n '''\n Tests that this function only handles strings.\n Below, we try to have it write a dict and that \n should not work\n '''\n destination = '/tmp/some_file.txt'\n content = {'some_key': 'some_val'}\n with self.assertRaises(AssertionError):\n write_resource(content, destination)\n\n\n @mock.patch('api.utilities.resource_utilities.check_file_format_against_type')\n @mock.patch('api.utilities.resource_utilities.retrieve_resource_class_instance')\n @mock.patch('api.utilities.resource_utilities.localize_resource')\n @mock.patch('api.utilities.resource_utilities.get_resource_size')\n def test_metadata_when_type_changed(self, mock_get_resource_size, \\\n mock_localize_resource, \\\n mock_retrieve_resource_class_instance, \\\n mock_check_file_format_against_type):\n '''\n Checks that the update of resource metadata is updated. Related to a bug where\n a file was initially set to a general type (and thus the metadata was effectively empty).\n After trying to validate it as an annotation type, it was raising json serializer errors.\n '''\n resource_path = os.path.join(VALIDATION_TESTDIR, 'test_annotation_valid.tsv')\n\n # define this mock function so we can patch the class\n # implementing the validation methods\n def mock_save_in_standardized_format(resource_instance, format):\n return None\n\n patched_ann_table_instance = AnnotationTable()\n patched_ann_table_instance.save_in_standardized_format = mock_save_in_standardized_format\n mock_retrieve_resource_class_instance.side_effect = [\n # note that we don't need to patch this since GeneralResource instances\n # do not perform validation\n GeneralResource(),\n patched_ann_table_instance\n ]\n\n mock_localize_resource.return_value = resource_path\n mock_size = 100\n mock_get_resource_size.return_value = mock_size\n\n # create an empty/dummy Resource\n r = Resource.objects.create(\n name = 'test_annotation_valid.tsv',\n owner = self.regular_user_1,\n is_active=True,\n datafile = File(BytesIO(), 'test_annotation_valid.tsv')\n )\n #...and associate it with the real file\n associate_file_with_resource(r, resource_path)\n\n initiate_resource_validation(r, WILDCARD, UNSPECIFIED_FORMAT)\n rm = ResourceMetadata.objects.get(resource=r)\n self.assertTrue(rm.observation_set is None)\n initiate_resource_validation(r, 'ANN', TSV_FORMAT)\n rm = ResourceMetadata.objects.get(resource=r)\n self.assertFalse(rm.observation_set is None)\n \n\n @mock.patch('api.utilities.resource_utilities.check_file_format_against_type')\n @mock.patch('api.utilities.resource_utilities.retrieve_resource_class_instance')\n @mock.patch('api.utilities.resource_utilities.localize_resource')\n @mock.patch('api.utilities.resource_utilities.get_resource_size')\n def test_metadata_when_type_changed_case2(self, mock_get_resource_size, \\\n mock_localize_resource, \\\n mock_retrieve_resource_class_instance, \\\n mock_check_file_format_against_type):\n\n resource_path = os.path.join(VALIDATION_TESTDIR, 'test_matrix.tsv')\n mock_localize_resource.return_value = resource_path\n\n # define this mock function so we can patch the class\n # implementing the validation methods\n def mock_save_in_standardized_format(local_path, format):\n return resource_path\n\n patched_mtx_instance = Matrix()\n patched_mtx_instance.save_in_standardized_format = mock_save_in_standardized_format\n mock_retrieve_resource_class_instance.side_effect = [\n # note that we don't need to patch this since GeneralResource instances\n # do not perform validation\n GeneralResource(),\n patched_mtx_instance\n ]\n mock_localize_resource.return_value = resource_path\n mock_get_resource_size.return_value = 100\n \n r = Resource.objects.create(\n name = 'test_matrix',\n owner = self.regular_user_1,\n is_active=True,\n datafile = File(BytesIO(), 'test_matrix')\n )\n associate_file_with_resource(r, resource_path)\n\n initiate_resource_validation(r, WILDCARD, UNSPECIFIED_FORMAT)\n rm = ResourceMetadata.objects.get(resource=r)\n self.assertTrue(rm.observation_set is None)\n initiate_resource_validation(r, 'MTX', TSV_FORMAT)\n rm = ResourceMetadata.objects.get(resource=r)\n obs_set = rm.observation_set\n samples = [x['id'] for x in obs_set['elements']]\n expected = ['SW1_Control','SW2_Control','SW3_Control','SW4_Treated','SW5_Treated','SW6_Treated']\n self.assertCountEqual(samples, expected)\n \n\n def test_resource_metadata_entered_in_db(self):\n '''\n Here we test that an instance of ResourceMetadata is created\n and tied to the appropriate resource. Not a \"true\" unit test in the sense\n that it doesn't mock out intermediate functions, etc. It uses real data.\n '''\n # create a Resource and give it our test integer matrix\n resource_path = os.path.join(VALIDATION_TESTDIR, 'test_integer_matrix.tsv')\n\n # note that we can't mock the class implementing the resource type, as\n # we need its implementation to get the metadata. HOWEVER, we need to ensure\n # that the file type above is ALREADY in the standardized format.\n file_format = TSV_FORMAT\n self.assertTrue(file_format == IntegerMatrix.STANDARD_FORMAT)\n\n resource_type = INTEGER_MATRIX_KEY\n file_format = TSV_FORMAT\n r = Resource.objects.create(\n datafile = File(BytesIO(), 'foo.tsv'),\n name = 'foo.tsv',\n resource_type = INTEGER_MATRIX_KEY,\n file_format = TSV_FORMAT,\n owner = get_user_model().objects.all()[0]\n )\n associate_file_with_resource(r, resource_path)\n\n # check the original count for ResourceMetadata\n rm = ResourceMetadata.objects.filter(resource=r)\n n0 = len(rm)\n self.assertTrue(n0 == 0)\n\n # call the tested function\n resource_class_instance = retrieve_resource_class_instance(resource_type)\n handle_valid_resource(r, resource_class_instance)\n\n rm = ResourceMetadata.objects.filter(resource=r)\n n1 = len(rm) \n self.assertTrue(n1 == 1)\n\n \n\n @mock.patch('api.utilities.resource_utilities.check_file_format_against_type')\n def test_resource_metadata_updated_in_db(self, mock_check_file_format_against_type):\n '''\n Here we test that an instance of ResourceMetadata is updated\n when it previously existed (for instance, upon update of a\n Resource type).\n\n Not a \"true\" unit test in the sense\n that it doesn't mock out intermediate functions, etc. It uses real data.\n '''\n\n # get one of the test resources (which has type of None):\n rr = Resource.objects.filter(owner=self.regular_user_1, resource_type=None)\n r = rr[0]\n\n # give that Resource our test integer matrix\n fname = 'test_integer_matrix.tsv'\n resource_path = os.path.join(VALIDATION_TESTDIR, fname)\n resource_type = INTEGER_MATRIX_KEY\n file_format = TSV_FORMAT\n r = Resource.objects.create(\n datafile = File(BytesIO(), fname),\n name = fname,\n resource_type = resource_type,\n file_format = file_format,\n owner = get_user_model().objects.all()[0]\n )\n associate_file_with_resource(r, resource_path)\n\n # note that we can't mock the class implementing the resource type, as\n # we need its implementation to get the metadata. HOWEVER, we need to ensure\n # that the file type above is ALREADY in the standardized format.\n self.assertTrue(r.file_format == IntegerMatrix.STANDARD_FORMAT)\n\n # create a ResourceMetadata instance associated with that Resource\n ResourceMetadata.objects.create(\n resource=r,\n parent_operation = None,\n observation_set = None,\n feature_set = None\n )\n\n # check the original count for ResourceMetadata\n rm = ResourceMetadata.objects.filter(resource=r)\n n0 = len(rm)\n self.assertEqual(n0, 1)\n rm_original = rm[0]\n\n # call the tested function\n resource_class_instance = retrieve_resource_class_instance(resource_type)\n handle_valid_resource(r, resource_class_instance)\n\n rm = ResourceMetadata.objects.filter(resource=r)\n n1 = len(rm) \n\n # check that no new ResourceMetadata objects were created\n self.assertEqual(n1-n0, 0)\n rm_final = rm[0]\n \n # check that the observation_set changed as expected:\n self.assertFalse(rm_original.observation_set == rm_final.observation_set)\n\n def test_full_validation_success(self):\n '''\n Here we test that the full process to validate executes.\n\n Not a \"true\" unit test in the sense\n that it doesn't mock out intermediate functions, etc. It uses real data.\n '''\n # get one of the test resources which is \"unset\" (no resource type or format)\n rr = Resource.objects.filter(\n owner=self.regular_user_1, \n resource_type=None\n )\n r = rr[0]\n self.assertTrue((r.file_format == '') or (r.file_format is None))\n self.assertIsNone(r.resource_type)\n\n # provide a real test integer matrix\n resource_path = os.path.join(VALIDATION_TESTDIR, 'test_integer_matrix.tsv')\n associate_file_with_resource(r,resource_path)\n r.name = 'test_integer_matrix.tsv'\n r.save()\n\n file_format = TSV_FORMAT\n self.assertTrue(file_format == IntegerMatrix.STANDARD_FORMAT)\n\n # check the original count for ResourceMetadata. Should be nothing.\n rm = ResourceMetadata.objects.filter(resource=r)\n n0 = len(rm)\n self.assertEqual(n0, 0)\n\n initiate_resource_validation(r, INTEGER_MATRIX_KEY, file_format)\n\n # Check that we now have metadata\n rm = ResourceMetadata.objects.filter(resource=r)\n n1 = len(rm) \n\n r = Resource.objects.get(pk=r.pk)\n self.assertTrue(r.resource_type == INTEGER_MATRIX_KEY)\n self.assertTrue(r.file_format == file_format)\n \n\n def test_full_validation_success_with_format_change(self):\n '''\n Here we test that the full process to validate executes. Here, the input\n file is a CSV and it correctly reads it as such. However, since we ultimately\n convert it to the standard format (TSV) then we need to ensure that the format\n attribute is correctly updated.\n\n Not a \"true\" unit test in the sense\n that it doesn't mock out intermediate functions, etc. It uses real data.\n '''\n # get one of the test resources which is \"unset\" (no resource type or format)\n rr = Resource.objects.filter(\n owner=self.regular_user_1, \n resource_type=None\n )\n r = rr[0]\n self.assertTrue((r.file_format == '') or (r.file_format is None))\n self.assertIsNone(r.resource_type)\n\n # provide a real test integer matrix\n resource_path = os.path.join(VALIDATION_TESTDIR, 'test_integer_matrix.csv')\n associate_file_with_resource(r,resource_path)\n r.name = 'test_integer_matrix.csv'\n r.save()\n\n orig_df = pd.read_csv(resource_path, index_col=0)\n\n file_format = CSV_FORMAT\n self.assertTrue(file_format != IntegerMatrix.STANDARD_FORMAT)\n\n # check the original count for ResourceMetadata. Should be nothing.\n rm = ResourceMetadata.objects.filter(resource=r)\n n0 = len(rm)\n self.assertEqual(n0, 0)\n\n initiate_resource_validation(r, INTEGER_MATRIX_KEY, file_format)\n\n # Check that we now have metadata\n rm = ResourceMetadata.objects.filter(resource=r)\n n1 = len(rm) \n\n r = Resource.objects.get(pk=r.pk)\n self.assertTrue(r.resource_type == INTEGER_MATRIX_KEY)\n self.assertTrue(r.file_format == TSV_FORMAT)\n\n # check that the file contents are the same:\n final_df = pd.read_table(r.datafile.open(), index_col=0)\n eq_df = orig_df == final_df\n self.assertTrue(all(eq_df))\n\n @mock.patch('api.utilities.resource_utilities.get_resource_size')\n def test_full_validation_failure_case1(self, mock_get_resource_size):\n '''\n Here we test that the full process to validate executes. In this case\n we simulate a situation where the user specified the wrong resource type.\n The actual file contains floats, but the user attempts to validate as\n an integer matrix\n Note the file is actually parsed and set, just like the \"success\" test\n above. Then we intentionally break it.\n\n Not a \"true\" unit test in the sense\n that it doesn't mock out intermediate functions, etc. It uses real data.\n '''\n rr = Resource.objects.filter(\n owner=self.regular_user_1, \n resource_type=None\n )\n r = rr[0]\n self.assertTrue((r.file_format == '') or (r.file_format is None))\n self.assertIsNone(r.resource_type)\n\n # provide a real test matrix with floats.\n resource_path = os.path.join(VALIDATION_TESTDIR, 'test_matrix.tsv')\n associate_file_with_resource(r,resource_path)\n r.name = 'test_matrix.tsv'\n r.save()\n\n file_format = TSV_FORMAT\n self.assertTrue(file_format == IntegerMatrix.STANDARD_FORMAT)\n\n # check the original count for ResourceMetadata. Should be nothing.\n rm = ResourceMetadata.objects.filter(resource=r)\n n0 = len(rm)\n self.assertEqual(n0, 0)\n\n mock_final_path = '/path/to/final/dir/file.tsv'\n mock_get_resource_size.return_value = 100\n\n # validate it. This should succeed since we are correctly validating\n # a float matrix\n initiate_resource_validation(r, MATRIX_KEY, file_format)\n\n # Check that we now have metadata\n rm = ResourceMetadata.objects.filter(resource=r)\n n1 = len(rm) \n self.assertEqual(n1,1)\n original_rm = rm[0]\n\n # check that all the fields are properly set:\n r = Resource.objects.get(pk=r.pk)\n self.assertTrue(r.resource_type == MATRIX_KEY)\n self.assertTrue(r.file_format == TSV_FORMAT)\n\n # Again we call the tested function. Note that we are trying to validate\n # a float matrix as an integer. It SHOULD fail.\n initiate_resource_validation(r, INTEGER_MATRIX_KEY, file_format)\n\n # Check that everything stayed the same:\n rm = ResourceMetadata.objects.filter(resource=r)\n n1 = len(rm)\n final_rm = rm[0]\n self.assertEqual(original_rm.observation_set, final_rm.observation_set)\n\n r = Resource.objects.get(pk=r.pk)\n self.assertTrue(r.resource_type == MATRIX_KEY)\n self.assertTrue(r.file_format == TSV_FORMAT)\n self.assertTrue('Reverting' in r.status)\n\n def test_full_validation_failure_case2(self):\n '''\n Here we test that the full process to validate executes. In this case\n we simulate a situation where the user specified the wrong resource type.\n The actual file contains floats, but the user attempts to validate as\n an integer matrix\n Note the file was not previously validated\n\n Not a \"true\" unit test in the sense\n that it doesn't mock out intermediate functions, etc. It uses real data.\n '''\n # get one of the test resources which is \"unset\" (no resource type or format)\n rr = Resource.objects.filter(\n owner=self.regular_user_1, \n resource_type=None\n )\n r = rr[0]\n self.assertTrue((r.file_format == '') or (r.file_format is None))\n self.assertIsNone(r.resource_type)\n\n # provide a real test float matrix\n resource_path = os.path.join(VALIDATION_TESTDIR, 'test_matrix.tsv')\n associate_file_with_resource(r,resource_path)\n r.name = 'test_matrix.tsv'\n r.save()\n\n file_format = TSV_FORMAT\n\n # check the original count for ResourceMetadata. Should be nothing.\n rm = ResourceMetadata.objects.filter(resource=r)\n n0 = len(rm)\n self.assertEqual(n0, 0)\n\n # call the tested function. Note that we are trying to validate\n # a float matrix as an integer. It SHOULD fail.\n initiate_resource_validation(r, INTEGER_MATRIX_KEY, file_format)\n\n # Check that we now have metadata, but it's trivial:\n rm = ResourceMetadata.objects.filter(resource=r)\n n1 = len(rm)\n rm = rm[0]\n self.assertIsNone(rm.observation_set)\n self.assertIsNone(rm.feature_set)\n self.assertIsNone(rm.parent_operation)\n\n r = Resource.objects.get(pk=r.pk)\n self.assertIsNone(r.resource_type)\n self.assertTrue(\n (r.file_format == '')\n |\n (r.file_format is None)\n ) \n self.assertTrue('contained non-integer entries' in r.status)\n \n\n def test_success_after_failure(self):\n '''\n Here we test that the full process to validate executes. In this case\n we simulate a situation where the user specified the wrong resource type.\n The actual file contains floats, but the user attempts to validate as\n an integer matrix. The user then initiates a proper request. Check\n that everything is filled out properly\n\n Not a \"true\" unit test in the sense\n that it doesn't mock out intermediate functions, etc. It uses real data.\n '''\n # get one of the test resources which is \"unset\" (no resource type or format)\n rr = Resource.objects.filter(\n owner=self.regular_user_1, \n resource_type=None\n )\n r = rr[0]\n self.assertTrue((r.file_format == '') or (r.file_format is None))\n self.assertIsNone(r.resource_type)\n\n # provide a real test float matrix\n resource_path = os.path.join(VALIDATION_TESTDIR, 'test_matrix.tsv')\n associate_file_with_resource(r,resource_path)\n # r.name = 'test_matrix.tsv'\n # r.save()\n\n file_format = TSV_FORMAT\n\n # check the original count for ResourceMetadata. Should be nothing.\n rm = ResourceMetadata.objects.filter(resource=r)\n n0 = len(rm)\n self.assertEqual(n0, 0)\n\n # call the tested function. Note that we are trying to validate\n # a float matrix as an integer. It SHOULD fail.\n initiate_resource_validation(r, INTEGER_MATRIX_KEY, file_format)\n\n # Check that we now have metadata, but it's trivial:\n rm = ResourceMetadata.objects.filter(resource=r)\n n1 = len(rm)\n rm = rm[0]\n self.assertIsNone(rm.observation_set)\n self.assertIsNone(rm.feature_set)\n self.assertIsNone(rm.parent_operation)\n\n r = Resource.objects.get(pk=r.pk)\n self.assertIsNone(r.resource_type)\n self.assertTrue(\n (r.file_format == '')\n |\n (r.file_format is None)\n )\n self.assertTrue('contained non-integer entries' in r.status)\n\n # Now validate as a float matrix:\n initiate_resource_validation(r, MATRIX_KEY, file_format)\n\n # Check that the metadata updated everything stayed the same:\n rm = ResourceMetadata.objects.filter(resource=r)\n n1 = len(rm)\n final_rm = rm[0]\n self.assertTrue(len(final_rm.observation_set) > 0)\n\n r = Resource.objects.get(pk=r.pk)\n self.assertTrue(r.resource_type == MATRIX_KEY)\n self.assertTrue(r.file_format == TSV_FORMAT)\n\n \n\n @mock.patch('api.utilities.resource_utilities.retrieve_metadata')\n def test_full_metadata_failure(self, mock_retrieve_metadata):\n '''\n Here we test that the full process to validate executes. In this test, we set \n it up such that the file validates properly, but there is an issue when \n extracting metadata. There are some edge cases where a file is technically \n compliant with the type+format, but breaks when we attempt to create\n metadata\n\n Not a \"true\" unit test in the sense\n that it doesn't mock out intermediate functions, etc. It uses real data.\n '''\n # get one of the test resources which is \"unset\" (no resource type or format)\n rr = Resource.objects.filter(\n owner=self.regular_user_1, \n resource_type=None\n )\n r = rr[0]\n self.assertTrue((r.file_format == '') or (r.file_format is None))\n self.assertIsNone(r.resource_type)\n\n # provide a real test integer matrix\n resource_path = os.path.join(VALIDATION_TESTDIR, 'test_integer_matrix.tsv')\n associate_file_with_resource(r, resource_path)\n r.name = 'test_integer_matrix.tsv'\n r.save()\n\n file_format = TSV_FORMAT\n self.assertTrue(file_format == IntegerMatrix.STANDARD_FORMAT)\n\n # check the original count for ResourceMetadata. Should be nothing.\n rm = ResourceMetadata.objects.filter(resource=r)\n n0 = len(rm)\n self.assertEqual(n0, 0)\n\n mock_retrieve_metadata.side_effect = Exception('something bad!')\n\n with self.assertRaises(Exception):\n initiate_resource_validation(r, INTEGER_MATRIX_KEY, file_format)\n\n # Check that we still don't have metadata\n rm = ResourceMetadata.objects.filter(resource=r)\n n1 = len(rm) \n self.assertEqual(n0, 0)\n\n r = Resource.objects.get(pk=r.pk)\n self.assertIsNone(r.resource_type)\n self.assertTrue(\n (r.file_format == '')\n |\n (r.file_format is None)\n )", "repo_name": "web-mev/mev-backend", "sub_path": "mev/api/tests/test_resource_utils.py", "file_name": "test_resource_utils.py", "file_ext": "py", "file_size_in_byte": 68998, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "20", "api": [{"api_name": "os.path.dirname", "line_number": 63, "usage_type": "call"}, {"api_name": "os.path", "line_number": 63, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path", "line_number": 64, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "api.tests.base.BaseAPITestCase", "line_number": 68, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.all", "line_number": 77, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 77, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 77, "usage_type": "name"}, {"api_name": "django.core.exceptions.ImproperlyConfigured", "line_number": 84, "usage_type": "call"}, {"api_name": "api.models.Resource.objects.filter", "line_number": 97, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 97, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 97, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.filter", "line_number": 98, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 98, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 98, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.check_resource_request_validity", "line_number": 105, "usage_type": "call"}, {"api_name": "exceptions.InactiveResourceException", "line_number": 109, "usage_type": "argument"}, {"api_name": "api.utilities.resource_utilities.check_resource_request_validity", "line_number": 110, "usage_type": "call"}, {"api_name": "exceptions.OwnershipException", "line_number": 113, "usage_type": "argument"}, {"api_name": "api.utilities.resource_utilities.check_resource_request_validity", "line_number": 114, "usage_type": "call"}, {"api_name": "exceptions.NoResourceFoundException", "line_number": 116, "usage_type": "name"}, {"api_name": "exceptions.NoResourceFoundException", "line_number": 117, "usage_type": "argument"}, {"api_name": "api.utilities.resource_utilities.check_resource_request_validity", "line_number": 118, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 89, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 89, "usage_type": "name"}, {"api_name": "exceptions.NoResourceFoundException", "line_number": 127, "usage_type": "argument"}, {"api_name": "api.utilities.resource_utilities.get_resource_by_pk", "line_number": 128, "usage_type": "call"}, {"api_name": "uuid.uuid4", "line_number": 128, "usage_type": "call"}, {"api_name": "api.models.Resource.objects.all", "line_number": 130, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 130, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 130, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.get_resource_by_pk", "line_number": 132, "usage_type": "call"}, {"api_name": "api.models.Operation.objects.all", "line_number": 135, "usage_type": "call"}, {"api_name": "api.models.Operation.objects", "line_number": 135, "usage_type": "attribute"}, {"api_name": "api.models.Operation", "line_number": 135, "usage_type": "name"}, {"api_name": "api.models.OperationResource.objects.create", "line_number": 137, "usage_type": "call"}, {"api_name": "api.models.OperationResource.objects", "line_number": 137, "usage_type": "attribute"}, {"api_name": "api.models.OperationResource", "line_number": 137, "usage_type": "name"}, {"api_name": "constants.TSV_FORMAT", "line_number": 142, "usage_type": "name"}, {"api_name": "django.core.files.File", "line_number": 143, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 143, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.get_resource_by_pk", "line_number": 145, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 155, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 155, "usage_type": "name"}, {"api_name": "uuid.uuid4", "line_number": 157, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.delete_resource_by_pk", "line_number": 158, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 165, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 165, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.delete_resource_by_pk", "line_number": 168, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 173, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 173, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.delete_resource_by_pk", "line_number": 176, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 148, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 148, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 149, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 149, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 182, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 182, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.retrieve_metadata", "line_number": 188, "usage_type": "call"}, {"api_name": "rest_framework.exceptions.ValidationError", "line_number": 192, "usage_type": "call"}, {"api_name": "exceptions.ResourceValidationException", "line_number": 194, "usage_type": "argument"}, {"api_name": "api.utilities.resource_utilities.retrieve_metadata", "line_number": 195, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.retrieve_metadata", "line_number": 199, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.retrieve_resource_class_standard_format", "line_number": 206, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.retrieve_resource_class_standard_format", "line_number": 211, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 201, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 201, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.all", "line_number": 219, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 219, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 219, "usage_type": "name"}, {"api_name": "django.core.exceptions.ImproperlyConfigured", "line_number": 226, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.get_resource_view", "line_number": 237, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 213, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 213, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.all", "line_number": 246, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 246, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 246, "usage_type": "name"}, {"api_name": "django.core.exceptions.ImproperlyConfigured", "line_number": 253, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.get_resource_view", "line_number": 257, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 274, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 274, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 280, "usage_type": "call"}, {"api_name": "api.models.Resource.objects.get", "line_number": 292, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 292, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 292, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 260, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 260, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 261, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 261, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 262, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 262, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 263, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 263, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 315, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 315, "usage_type": "name"}, {"api_name": "constants.TSV_FORMAT", "line_number": 316, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 322, "usage_type": "call"}, {"api_name": "constants.TSV_FORMAT", "line_number": 322, "usage_type": "argument"}, {"api_name": "api.models.Resource.objects.get", "line_number": 331, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 331, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 331, "usage_type": "name"}, {"api_name": "constants.TSV_FORMAT", "line_number": 333, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 299, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 299, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 300, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 300, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 301, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 301, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 302, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 302, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 303, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 303, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 358, "usage_type": "call"}, {"api_name": "constants.TSV_FORMAT", "line_number": 358, "usage_type": "argument"}, {"api_name": "unittest.mock.patch", "line_number": 335, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 335, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 336, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 336, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 337, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 337, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 338, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 338, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 384, "usage_type": "call"}, {"api_name": "constants.TSV_FORMAT", "line_number": 384, "usage_type": "argument"}, {"api_name": "unittest.mock.patch", "line_number": 363, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 363, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 364, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 364, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 365, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 365, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 366, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 366, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 411, "usage_type": "call"}, {"api_name": "constants.TSV_FORMAT", "line_number": 411, "usage_type": "argument"}, {"api_name": "unittest.mock.patch", "line_number": 390, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 390, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 391, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 391, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 392, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 392, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 393, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 393, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 433, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 433, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 443, "usage_type": "call"}, {"api_name": "constants.TSV_FORMAT", "line_number": 443, "usage_type": "argument"}, {"api_name": "constants.TSV_FORMAT", "line_number": 448, "usage_type": "argument"}, {"api_name": "unittest.mock.patch", "line_number": 416, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 416, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 417, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 417, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 418, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 418, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 419, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 419, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 420, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 420, "usage_type": "name"}, {"api_name": "uuid.uuid4", "line_number": 481, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 482, "usage_type": "call"}, {"api_name": "django.core.files.File", "line_number": 483, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 490, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 490, "usage_type": "name"}, {"api_name": "constants.TSV_FORMAT", "line_number": 491, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 501, "usage_type": "call"}, {"api_name": "constants.TSV_FORMAT", "line_number": 501, "usage_type": "argument"}, {"api_name": "api.models.Resource.objects.get", "line_number": 510, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 510, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 510, "usage_type": "name"}, {"api_name": "constants.TSV_FORMAT", "line_number": 516, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 453, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 453, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 454, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 454, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 455, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 455, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 456, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 456, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 457, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 457, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.DoesNotExist", "line_number": 529, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 529, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.get", "line_number": 530, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 530, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 530, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.handle_invalid_resource", "line_number": 532, "usage_type": "call"}, {"api_name": "constants.TSV_FORMAT", "line_number": 532, "usage_type": "argument"}, {"api_name": "api.models.ResourceMetadata.objects.get", "line_number": 536, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 536, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 536, "usage_type": "name"}, {"api_name": "api.serializers.resource_metadata.ResourceMetadataSerializer", "line_number": 537, "usage_type": "call"}, {"api_name": "constants.PARENT_OP_KEY", "line_number": 538, "usage_type": "name"}, {"api_name": "constants.OBSERVATION_SET_KEY", "line_number": 539, "usage_type": "name"}, {"api_name": "constants.FEATURE_SET_KEY", "line_number": 540, "usage_type": "name"}, {"api_name": "constants.RESOURCE_KEY", "line_number": 541, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 518, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 518, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 544, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 544, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.check_if_resource_unset", "line_number": 545, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 547, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 547, "usage_type": "name"}, {"api_name": "constants.MATRIX_KEY", "line_number": 548, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.check_if_resource_unset", "line_number": 549, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 551, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 551, "usage_type": "name"}, {"api_name": "constants.TSV_FORMAT", "line_number": 552, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.check_if_resource_unset", "line_number": 553, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 555, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 555, "usage_type": "name"}, {"api_name": "constants.MATRIX_KEY", "line_number": 556, "usage_type": "name"}, {"api_name": "constants.TSV_FORMAT", "line_number": 557, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.check_if_resource_unset", "line_number": 558, "usage_type": "call"}, {"api_name": "api.models.Resource.objects.all", "line_number": 573, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 573, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 573, "usage_type": "name"}, {"api_name": "django.core.exceptions.ImproperlyConfigured", "line_number": 580, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 588, "usage_type": "call"}, {"api_name": "resource_types.RESOURCE_MAPPING.keys", "line_number": 588, "usage_type": "call"}, {"api_name": "resource_types.RESOURCE_MAPPING", "line_number": 588, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.handle_invalid_resource", "line_number": 589, "usage_type": "call"}, {"api_name": "constants.TSV_FORMAT", "line_number": 589, "usage_type": "argument"}, {"api_name": "api.models.Resource.REVERTED.format", "line_number": 594, "usage_type": "call"}, {"api_name": "api.models.Resource.REVERTED", "line_number": 594, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 594, "usage_type": "name"}, {"api_name": "constants.DB_RESOURCE_KEY_TO_HUMAN_READABLE", "line_number": 595, "usage_type": "name"}, {"api_name": "constants.DB_RESOURCE_KEY_TO_HUMAN_READABLE", "line_number": 596, "usage_type": "name"}, {"api_name": "constants.TSV_FORMAT", "line_number": 597, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 560, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 560, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 561, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 561, "usage_type": "name"}, {"api_name": "exceptions.ResourceValidationException", "line_number": 621, "usage_type": "argument"}, {"api_name": "api.utilities.resource_utilities.check_file_format_against_type", "line_number": 622, "usage_type": "call"}, {"api_name": "api.models.Resource.UNKNOWN_FORMAT_ERROR.format", "line_number": 623, "usage_type": "call"}, {"api_name": "api.models.Resource.UNKNOWN_FORMAT_ERROR", "line_number": 623, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 623, "usage_type": "name"}, {"api_name": "unittest.mock.patch.dict", "line_number": 604, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 604, "usage_type": "attribute"}, {"api_name": "unittest.mock", "line_number": 604, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 606, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 606, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 607, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 607, "usage_type": "name"}, {"api_name": "exceptions.ResourceValidationException", "line_number": 640, "usage_type": "argument"}, {"api_name": "api.utilities.resource_utilities.check_file_format_against_type", "line_number": 641, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 630, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 630, "usage_type": "name"}, {"api_name": "exceptions.ResourceValidationException", "line_number": 652, "usage_type": "argument"}, {"api_name": "api.utilities.resource_utilities.retrieve_resource_class_instance", "line_number": 653, "usage_type": "call"}, {"api_name": "api.models.Resource.UNKNOWN_RESOURCE_TYPE_ERROR.format", "line_number": 654, "usage_type": "call"}, {"api_name": "api.models.Resource.UNKNOWN_RESOURCE_TYPE_ERROR", "line_number": 654, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 654, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 643, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 643, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.retrieve_resource_class_instance", "line_number": 668, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 659, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 659, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.all", "line_number": 681, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 681, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 681, "usage_type": "name"}, {"api_name": "resource_types.GeneralResource", "line_number": 684, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 687, "usage_type": "call"}, {"api_name": "constants.WILDCARD", "line_number": 687, "usage_type": "argument"}, {"api_name": "constants.UNSPECIFIED_FORMAT", "line_number": 687, "usage_type": "argument"}, {"api_name": "api.models.Resource.objects.get", "line_number": 691, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 691, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 691, "usage_type": "name"}, {"api_name": "constants.WILDCARD", "line_number": 692, "usage_type": "name"}, {"api_name": "constants.UNSPECIFIED_FORMAT", "line_number": 693, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 670, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 670, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 671, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 671, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 672, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 672, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.check_file_format_against_type", "line_number": 700, "usage_type": "call"}, {"api_name": "constants.WILDCARD", "line_number": 700, "usage_type": "argument"}, {"api_name": "api.models.Resource.objects.all", "line_number": 718, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 718, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 718, "usage_type": "name"}, {"api_name": "resource_types.GeneralResource", "line_number": 720, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.handle_valid_resource", "line_number": 721, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 702, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 702, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 703, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 703, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.ValidationError", "line_number": 747, "usage_type": "call"}, {"api_name": "api.models.Resource.objects.all", "line_number": 749, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 749, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 749, "usage_type": "name"}, {"api_name": "unittest.mock.MagicMock", "line_number": 752, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 752, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.handle_valid_resource", "line_number": 754, "usage_type": "call"}, {"api_name": "unittest.mock.call", "line_number": 757, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 757, "usage_type": "name"}, {"api_name": "unittest.mock.call", "line_number": 758, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 758, "usage_type": "name"}, {"api_name": "constants.RESOURCE_KEY", "line_number": 758, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 729, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 729, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 730, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 730, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.create", "line_number": 771, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 771, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 771, "usage_type": "name"}, {"api_name": "django.core.files.File", "line_number": 774, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 774, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects.create", "line_number": 776, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 776, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 776, "usage_type": "name"}, {"api_name": "data_structures.observation_set.ObservationSet", "line_number": 792, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.add_metadata_to_resource", "line_number": 794, "usage_type": "call"}, {"api_name": "constants.OBSERVATION_SET_KEY", "line_number": 797, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.get", "line_number": 802, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 802, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 802, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 803, "usage_type": "call"}, {"api_name": "api.models.Resource.objects.create", "line_number": 811, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 811, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 811, "usage_type": "name"}, {"api_name": "django.core.files.File", "line_number": 814, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 814, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.DoesNotExist", "line_number": 816, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 816, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.get", "line_number": 817, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 817, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 817, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.add_metadata_to_resource", "line_number": 818, "usage_type": "call"}, {"api_name": "constants.OBSERVATION_SET_KEY", "line_number": 820, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.get", "line_number": 824, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 824, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 824, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 825, "usage_type": "call"}, {"api_name": "api.models.Resource.objects.create", "line_number": 840, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 840, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 840, "usage_type": "name"}, {"api_name": "django.core.files.File", "line_number": 843, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 843, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects.create", "line_number": 845, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 845, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 845, "usage_type": "name"}, {"api_name": "data_structures.observation_set.ObservationSet", "line_number": 881, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.add_metadata_to_resource", "line_number": 884, "usage_type": "call"}, {"api_name": "constants.OBSERVATION_SET_KEY", "line_number": 887, "usage_type": "name"}, {"api_name": "constants.OBSERVATION_SET_KEY", "line_number": 919, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.create", "line_number": 923, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 923, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 923, "usage_type": "name"}, {"api_name": "django.core.files.File", "line_number": 926, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 926, "usage_type": "call"}, {"api_name": "constants.ANNOTATION_TABLE_KEY", "line_number": 929, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.retrieve_resource_class_instance", "line_number": 930, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.handle_valid_resource", "line_number": 931, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 934, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 934, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 934, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 891, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 891, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 892, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 892, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.create", "line_number": 956, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 956, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 956, "usage_type": "name"}, {"api_name": "django.core.files.File", "line_number": 959, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 959, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.DoesNotExist", "line_number": 962, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 962, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.get", "line_number": 963, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 963, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 963, "usage_type": "name"}, {"api_name": "data_structures.observation_set.ObservationSet", "line_number": 979, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 983, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 983, "usage_type": "name"}, {"api_name": "django.db.utils.OperationalError", "line_number": 985, "usage_type": "name"}, {"api_name": "constants.RESOURCE_KEY", "line_number": 991, "usage_type": "name"}, {"api_name": "api.serializers.resource_metadata.ResourceMetadataSerializer", "line_number": 993, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.add_metadata_to_resource", "line_number": 995, "usage_type": "call"}, {"api_name": "constants.OBSERVATION_SET_KEY", "line_number": 998, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.get", "line_number": 1004, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1004, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1004, "usage_type": "name"}, {"api_name": "api.serializers.resource_metadata.ResourceMetadataSerializer", "line_number": 1005, "usage_type": "call"}, {"api_name": "constants.PARENT_OP_KEY", "line_number": 1007, "usage_type": "name"}, {"api_name": "constants.OBSERVATION_SET_KEY", "line_number": 1008, "usage_type": "name"}, {"api_name": "constants.FEATURE_SET_KEY", "line_number": 1009, "usage_type": "name"}, {"api_name": "constants.RESOURCE_KEY", "line_number": 1010, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 942, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 942, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 943, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 943, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.create", "line_number": 1028, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1028, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1028, "usage_type": "name"}, {"api_name": "django.core.files.File", "line_number": 1031, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 1031, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.DoesNotExist", "line_number": 1034, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1034, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.get", "line_number": 1035, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1035, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1035, "usage_type": "name"}, {"api_name": "data_structures.observation_set.ObservationSet", "line_number": 1051, "usage_type": "call"}, {"api_name": "unittest.mock.MagicMock", "line_number": 1054, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1054, "usage_type": "name"}, {"api_name": "constants.RESOURCE_KEY", "line_number": 1062, "usage_type": "name"}, {"api_name": "api.serializers.resource_metadata.ResourceMetadataSerializer", "line_number": 1064, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.add_metadata_to_resource", "line_number": 1066, "usage_type": "call"}, {"api_name": "constants.OBSERVATION_SET_KEY", "line_number": 1069, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.get", "line_number": 1075, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1075, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1075, "usage_type": "name"}, {"api_name": "api.serializers.resource_metadata.ResourceMetadataSerializer", "line_number": 1076, "usage_type": "call"}, {"api_name": "constants.PARENT_OP_KEY", "line_number": 1078, "usage_type": "name"}, {"api_name": "constants.OBSERVATION_SET_KEY", "line_number": 1079, "usage_type": "name"}, {"api_name": "constants.FEATURE_SET_KEY", "line_number": 1080, "usage_type": "name"}, {"api_name": "constants.RESOURCE_KEY", "line_number": 1081, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 1014, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1014, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 1015, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1015, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.write_resource", "line_number": 1097, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 1086, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1086, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 1087, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1087, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 1105, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1105, "usage_type": "attribute"}, {"api_name": "api.utilities.resource_utilities.write_resource", "line_number": 1108, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 1109, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1109, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 1114, "usage_type": "call"}, {"api_name": "unittest.mock.patch", "line_number": 1099, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1099, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 1121, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1121, "usage_type": "attribute"}, {"api_name": "api.utilities.resource_utilities.write_resource", "line_number": 1124, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 1125, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1125, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 1129, "usage_type": "call"}, {"api_name": "os.removedirs", "line_number": 1130, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.write_resource", "line_number": 1141, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1157, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1157, "usage_type": "attribute"}, {"api_name": "resource_types.AnnotationTable", "line_number": 1164, "usage_type": "call"}, {"api_name": "resource_types.GeneralResource", "line_number": 1169, "usage_type": "call"}, {"api_name": "api.models.Resource.objects.create", "line_number": 1178, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1178, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1178, "usage_type": "name"}, {"api_name": "django.core.files.File", "line_number": 1182, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 1182, "usage_type": "call"}, {"api_name": "api.tests.test_helpers.associate_file_with_resource", "line_number": 1185, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 1187, "usage_type": "call"}, {"api_name": "constants.WILDCARD", "line_number": 1187, "usage_type": "argument"}, {"api_name": "constants.UNSPECIFIED_FORMAT", "line_number": 1187, "usage_type": "argument"}, {"api_name": "api.models.ResourceMetadata.objects.get", "line_number": 1188, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1188, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1188, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 1190, "usage_type": "call"}, {"api_name": "constants.TSV_FORMAT", "line_number": 1190, "usage_type": "argument"}, {"api_name": "api.models.ResourceMetadata.objects.get", "line_number": 1191, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1191, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1191, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 1144, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1144, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 1145, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1145, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 1146, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1146, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 1147, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1147, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 1204, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1204, "usage_type": "attribute"}, {"api_name": "resource_types.Matrix", "line_number": 1212, "usage_type": "call"}, {"api_name": "resource_types.GeneralResource", "line_number": 1217, "usage_type": "call"}, {"api_name": "api.models.Resource.objects.create", "line_number": 1223, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1223, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1223, "usage_type": "name"}, {"api_name": "django.core.files.File", "line_number": 1227, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 1227, "usage_type": "call"}, {"api_name": "api.tests.test_helpers.associate_file_with_resource", "line_number": 1229, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 1231, "usage_type": "call"}, {"api_name": "constants.WILDCARD", "line_number": 1231, "usage_type": "argument"}, {"api_name": "constants.UNSPECIFIED_FORMAT", "line_number": 1231, "usage_type": "argument"}, {"api_name": "api.models.ResourceMetadata.objects.get", "line_number": 1232, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1232, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1232, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 1234, "usage_type": "call"}, {"api_name": "constants.TSV_FORMAT", "line_number": 1234, "usage_type": "argument"}, {"api_name": "api.models.ResourceMetadata.objects.get", "line_number": 1235, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1235, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1235, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 1195, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1195, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 1196, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1196, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 1197, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1197, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 1198, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1198, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 1249, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1249, "usage_type": "attribute"}, {"api_name": "constants.TSV_FORMAT", "line_number": 1254, "usage_type": "name"}, {"api_name": "resource_types.IntegerMatrix.STANDARD_FORMAT", "line_number": 1255, "usage_type": "attribute"}, {"api_name": "resource_types.IntegerMatrix", "line_number": 1255, "usage_type": "name"}, {"api_name": "constants.INTEGER_MATRIX_KEY", "line_number": 1257, "usage_type": "name"}, {"api_name": "constants.TSV_FORMAT", "line_number": 1258, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.create", "line_number": 1259, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1259, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1259, "usage_type": "name"}, {"api_name": "django.core.files.File", "line_number": 1260, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 1260, "usage_type": "call"}, {"api_name": "constants.INTEGER_MATRIX_KEY", "line_number": 1262, "usage_type": "name"}, {"api_name": "constants.TSV_FORMAT", "line_number": 1263, "usage_type": "name"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 1264, "usage_type": "call"}, {"api_name": "api.tests.test_helpers.associate_file_with_resource", "line_number": 1266, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1269, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1269, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1269, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.retrieve_resource_class_instance", "line_number": 1274, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.handle_valid_resource", "line_number": 1275, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1277, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1277, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1277, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.filter", "line_number": 1295, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1295, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1295, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 1300, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1300, "usage_type": "attribute"}, {"api_name": "constants.INTEGER_MATRIX_KEY", "line_number": 1301, "usage_type": "name"}, {"api_name": "constants.TSV_FORMAT", "line_number": 1302, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.create", "line_number": 1303, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1303, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1303, "usage_type": "name"}, {"api_name": "django.core.files.File", "line_number": 1304, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 1304, "usage_type": "call"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 1308, "usage_type": "call"}, {"api_name": "api.tests.test_helpers.associate_file_with_resource", "line_number": 1310, "usage_type": "call"}, {"api_name": "resource_types.IntegerMatrix.STANDARD_FORMAT", "line_number": 1315, "usage_type": "attribute"}, {"api_name": "resource_types.IntegerMatrix", "line_number": 1315, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.create", "line_number": 1318, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1318, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1318, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1326, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1326, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1326, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.retrieve_resource_class_instance", "line_number": 1332, "usage_type": "call"}, {"api_name": "api.utilities.resource_utilities.handle_valid_resource", "line_number": 1333, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1335, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1335, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1335, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 1283, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1283, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.filter", "line_number": 1353, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1353, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1353, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 1362, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1362, "usage_type": "attribute"}, {"api_name": "api.tests.test_helpers.associate_file_with_resource", "line_number": 1363, "usage_type": "call"}, {"api_name": "constants.TSV_FORMAT", "line_number": 1367, "usage_type": "name"}, {"api_name": "resource_types.IntegerMatrix.STANDARD_FORMAT", "line_number": 1368, "usage_type": "attribute"}, {"api_name": "resource_types.IntegerMatrix", "line_number": 1368, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1371, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1371, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1371, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 1375, "usage_type": "call"}, {"api_name": "constants.INTEGER_MATRIX_KEY", "line_number": 1375, "usage_type": "argument"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1378, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1378, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1378, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.get", "line_number": 1381, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1381, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1381, "usage_type": "name"}, {"api_name": "constants.INTEGER_MATRIX_KEY", "line_number": 1382, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.filter", "line_number": 1397, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1397, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1397, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 1406, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1406, "usage_type": "attribute"}, {"api_name": "api.tests.test_helpers.associate_file_with_resource", "line_number": 1407, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 1411, "usage_type": "call"}, {"api_name": "constants.CSV_FORMAT", "line_number": 1413, "usage_type": "name"}, {"api_name": "resource_types.IntegerMatrix.STANDARD_FORMAT", "line_number": 1414, "usage_type": "attribute"}, {"api_name": "resource_types.IntegerMatrix", "line_number": 1414, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1417, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1417, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1417, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 1421, "usage_type": "call"}, {"api_name": "constants.INTEGER_MATRIX_KEY", "line_number": 1421, "usage_type": "argument"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1424, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1424, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1424, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.get", "line_number": 1427, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1427, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1427, "usage_type": "name"}, {"api_name": "constants.INTEGER_MATRIX_KEY", "line_number": 1428, "usage_type": "name"}, {"api_name": "constants.TSV_FORMAT", "line_number": 1429, "usage_type": "name"}, {"api_name": "pandas.read_table", "line_number": 1432, "usage_type": "call"}, {"api_name": "api.models.Resource.objects.filter", "line_number": 1449, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1449, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1449, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 1458, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1458, "usage_type": "attribute"}, {"api_name": "api.tests.test_helpers.associate_file_with_resource", "line_number": 1459, "usage_type": "call"}, {"api_name": "constants.TSV_FORMAT", "line_number": 1463, "usage_type": "name"}, {"api_name": "resource_types.IntegerMatrix.STANDARD_FORMAT", "line_number": 1464, "usage_type": "attribute"}, {"api_name": "resource_types.IntegerMatrix", "line_number": 1464, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1467, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1467, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1467, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 1476, "usage_type": "call"}, {"api_name": "constants.MATRIX_KEY", "line_number": 1476, "usage_type": "argument"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1479, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1479, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1479, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.get", "line_number": 1485, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1485, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1485, "usage_type": "name"}, {"api_name": "constants.MATRIX_KEY", "line_number": 1486, "usage_type": "name"}, {"api_name": "constants.TSV_FORMAT", "line_number": 1487, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 1491, "usage_type": "call"}, {"api_name": "constants.INTEGER_MATRIX_KEY", "line_number": 1491, "usage_type": "argument"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1494, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1494, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1494, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.get", "line_number": 1499, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1499, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1499, "usage_type": "name"}, {"api_name": "constants.MATRIX_KEY", "line_number": 1500, "usage_type": "name"}, {"api_name": "constants.TSV_FORMAT", "line_number": 1501, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 1436, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1436, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.filter", "line_number": 1516, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1516, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1516, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 1525, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1525, "usage_type": "attribute"}, {"api_name": "api.tests.test_helpers.associate_file_with_resource", "line_number": 1526, "usage_type": "call"}, {"api_name": "constants.TSV_FORMAT", "line_number": 1530, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1533, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1533, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1533, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 1539, "usage_type": "call"}, {"api_name": "constants.INTEGER_MATRIX_KEY", "line_number": 1539, "usage_type": "argument"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1542, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1542, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1542, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.get", "line_number": 1549, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1549, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1549, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.filter", "line_number": 1571, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1571, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1571, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 1580, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1580, "usage_type": "attribute"}, {"api_name": "api.tests.test_helpers.associate_file_with_resource", "line_number": 1581, "usage_type": "call"}, {"api_name": "constants.TSV_FORMAT", "line_number": 1585, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1588, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1588, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1588, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 1594, "usage_type": "call"}, {"api_name": "constants.INTEGER_MATRIX_KEY", "line_number": 1594, "usage_type": "argument"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1597, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1597, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1597, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.get", "line_number": 1604, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1604, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1604, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 1614, "usage_type": "call"}, {"api_name": "constants.MATRIX_KEY", "line_number": 1614, "usage_type": "argument"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1617, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1617, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1617, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.get", "line_number": 1622, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1622, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1622, "usage_type": "name"}, {"api_name": "constants.MATRIX_KEY", "line_number": 1623, "usage_type": "name"}, {"api_name": "constants.TSV_FORMAT", "line_number": 1624, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.filter", "line_number": 1641, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1641, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1641, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 1650, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1650, "usage_type": "attribute"}, {"api_name": "api.tests.test_helpers.associate_file_with_resource", "line_number": 1651, "usage_type": "call"}, {"api_name": "constants.TSV_FORMAT", "line_number": 1655, "usage_type": "name"}, {"api_name": "resource_types.IntegerMatrix.STANDARD_FORMAT", "line_number": 1656, "usage_type": "attribute"}, {"api_name": "resource_types.IntegerMatrix", "line_number": 1656, "usage_type": "name"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1659, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1659, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1659, "usage_type": "name"}, {"api_name": "api.utilities.resource_utilities.initiate_resource_validation", "line_number": 1666, "usage_type": "call"}, {"api_name": "constants.INTEGER_MATRIX_KEY", "line_number": 1666, "usage_type": "argument"}, {"api_name": "api.models.ResourceMetadata.objects.filter", "line_number": 1669, "usage_type": "call"}, {"api_name": "api.models.ResourceMetadata.objects", "line_number": 1669, "usage_type": "attribute"}, {"api_name": "api.models.ResourceMetadata", "line_number": 1669, "usage_type": "name"}, {"api_name": "api.models.Resource.objects.get", "line_number": 1673, "usage_type": "call"}, {"api_name": "api.models.Resource.objects", "line_number": 1673, "usage_type": "attribute"}, {"api_name": "api.models.Resource", "line_number": 1673, "usage_type": "name"}, {"api_name": "unittest.mock.patch", "line_number": 1628, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 1628, "usage_type": "name"}]} +{"seq_id": "41852908852", "text": "###### IMPORT ######\n\nimport pygame\nimport random\nimport time\nfrom math import *\nimport numpy as np\nimport copy\n\n\n###### SETUP ######\npygame.init()\n\nwindowSize = (1280, 720)\n\npygame.display.set_caption(\"intersectionTest\") # Sets title of window\nscreen = pygame.display.set_mode(windowSize) # Sets the dimensions of the window to the windowSize\n\nfont = pygame.font.Font(None, 36)\n\nfps = 1\nclock = pygame.time.Clock()\n\n\n###### FUNCTIONS ######\ndef getIntersectionPoint(line1, line2):\n x1 = line1[0]\n y1 = line1[1]\n x2 = line1[2]\n y2 = line1[3]\n\n x3 = line2[0]\n y3 = line2[1]\n x4 = line2[2]\n y4 = line2[3]\n\n denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)\n\n if denominator == 0:\n return None # No intersection (lines are parallel)\n\n t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / denominator\n\n x = x1 + t * (x2 - x1)\n y = y1 + t * (y2 - y1)\n\n if 0 <= t <= 1:\n return (x, y) # Return the intersection point\n else:\n return (x, y) # No intersection within line segments (lines are not parallel, but they don't intersect in the specified segments)\n \n###### INITIALIZE ######\n\ndef initialize():\n global pointX1,pointX2,pointY1,pointY2,pointX3,pointX4,pointY3,pointY4,x5,y5\n pointX1 = random.randint(340,940)\n pointY1 = random.randint(160,560)\n pointX2 = random.randint(340,940)\n pointY2 = random.randint(160,560)\n\n pointX3 = random.randint(340,940)\n pointY3 = random.randint(160,560)\n pointX4 = random.randint(340,940)\n pointY4 = random.randint(160,560)\n\n x5,y5 = getIntersectionPoint((pointX1,pointY1,pointX2,pointY2),(pointX3,pointY3,pointX4,pointY4))\n\n\n###### MAINLOOP ######\nrunning = True # Runs the game loop\nwhile running:\n\n initialize()\n screen.fill((0,0,0))\n\n pygame.draw.aaline(screen, (255, 255, 255), (pointX1, pointY1), (pointX2, pointY2), 5)\n pygame.draw.aaline(screen, (255, 255, 255), (pointX3, pointY3), (pointX4, pointY4), 5)\n pygame.draw.circle(screen, (255, 255, 255), (x5, y5), 5)\n\n for event in pygame.event.get(): # checks if program is quit, if so stops the code\n if event.type == pygame.QUIT:\n running = False\n # runs framerate wait time\n clock.tick(fps)\n # update the screen\n pygame.display.update()\n #time.sleep(1)\n \n\n# quit Pygame\npygame.quit()", "repo_name": "AjayaRamachandran/Soft-Body-Simulation", "sub_path": "src/intersectionTest.py", "file_name": "intersectionTest.py", "file_ext": "py", "file_size_in_byte": 2339, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pygame.init", "line_number": 12, "usage_type": "call"}, {"api_name": "pygame.display.set_caption", "line_number": 16, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 16, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 17, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 17, "usage_type": "attribute"}, {"api_name": "pygame.font.Font", "line_number": 19, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 19, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 22, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 22, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 56, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 57, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 58, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 59, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 61, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 62, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 63, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 64, "usage_type": "call"}, {"api_name": "pygame.draw.aaline", "line_number": 76, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 76, "usage_type": "attribute"}, {"api_name": "pygame.draw.aaline", "line_number": 77, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 77, "usage_type": "attribute"}, {"api_name": "pygame.draw.circle", "line_number": 78, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 78, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 80, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 80, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 81, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 86, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 86, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 91, "usage_type": "call"}]} +{"seq_id": "74555686450", "text": "from item import Item, FireBallController\nimport pygame as pg\nimport constants as c\n\n\nclass Mario(pg.sprite.Sprite):\n def __init__(self, game_objects, map_layer, map_group, screen):\n pg.sprite.Sprite.__init__(self)\n self.sprite_sheet = pg.image.load('images/mario_bros.png')\n if self.sprite_sheet.get_alpha():\n self.sprite_sheet = self.sprite_sheet.convert_alpha()\n else:\n self.sprite_sheet = self.sprite_sheet.convert()\n self.sprite_sheet.set_colorkey((255, 0, 255))\n self.SFX = None\n self.load_sounds()\n self.game_objects = game_objects\n self.map_layer = map_layer\n self.screen = screen\n self.screen_rect = self.screen.get_rect()\n # fireball controller allows the throwing of fireballs when possible\n self.fireball_controller = FireBallController(screen, map_group,\n game_objects['collide_objs'], game_objects['floors'], self,\n goomba=game_objects['goomba'], koopa=game_objects['koopa'])\n self.screen_shift = 0\n self.left_bound = 0\n self.timers = {}\n self.state_info = {}\n self.sprites_about_to_die_group = pg.sprite.Group()\n\n self.shell = pg.sprite.Group()\n\n self.right_small_normal_frames = None\n self.left_small_normal_frames = None\n self.right_small_red_frames = None\n self.left_small_red_frames = None\n self.right_small_black_frames = None\n self.left_small_black_frames = None\n\n self.right_big_normal_frames = None\n self.left_big_normal_frames = None\n self.right_big_red_frames = None\n self.left_big_red_frames = None\n self.right_big_black_frames = None\n self.left_big_black_frames = None\n\n self.right_fire_frames = None\n self.left_fire_frames = None\n\n self.normal_small_frames = None\n self.red_small_frames = None\n self.black_small_frames = None\n self.invincible_small_frames_list = None\n self.normal_big_frames = None\n self.red_big_frames = None\n self.black_big_frames = None\n self.fire_frames = None\n self.invincible_big_frames_list = None\n self.all_images = None\n self.right_frames = None\n self.left_frames = None\n\n self.frame_index = 0\n self.invincible_index = 0\n self.fire_transition_index = 0\n self.fireball_count = 0\n self.flag_pole_right = 0\n\n self.x_vel = None\n self.y_vel = None\n self.max_x_vel = None\n self.max_y_vel = None\n self.x_accel = None\n self.jump_vel = None\n self.gravity = None\n\n self.setup_timers()\n self.setup_state_booleans()\n self.setup_forces()\n self.setup_counters()\n self.load_images_from_sheet()\n\n self.state = c.WALK\n self.image = self.right_frames[self.frame_index]\n self.rect = self.image.get_rect()\n self.mask = pg.mask.from_surface(self.image)\n\n self.key_timer = 0\n self.keybinding = {\n 'action': pg.K_LSHIFT,\n 'jump': pg.K_SPACE,\n 'left': pg.K_LEFT,\n 'right': pg.K_RIGHT,\n 'down': pg.K_DOWN\n }\n\n self.score = 0\n\n def setup_timers(self):\n \"\"\"Sets up timers for animations\"\"\"\n self.timers['walking'] = 0\n self.timers['invincible_animation'] = 0\n self.timers['invincible_start'] = 0\n self.timers['fire_transition'] = 0\n self.timers['death'] = 0\n self.timers['transition'] = 0\n self.timers['last_fireball'] = 0\n self.timers['hurt_invincible_1'] = 0\n self.timers['hurt_invincible_2'] = 0\n self.timers['flag_pole'] = 0\n\n def setup_state_booleans(self):\n \"\"\"Sets up booleans that affect Mario's behavior\"\"\"\n self.state_info['facing_right'] = True\n self.state_info['allow_jump'] = True\n self.state_info['dead'] = False\n self.state_info['death_finish'] = False\n self.state_info['invincible'] = False\n self.state_info['big'] = False\n self.state_info['fire'] = False\n self.state_info['allow_fireball'] = True\n self.state_info['in_transition'] = False\n self.state_info['hurt_invincible'] = False\n self.state_info['in_castle'] = False\n self.state_info['crouching'] = False\n self.state_info['losing_invincibility'] = False\n\n def setup_forces(self):\n \"\"\"Sets up forces that affect Mario's velocity\"\"\"\n self.x_vel = 0\n self.y_vel = 0\n self.max_x_vel = c.MAX_WALK_SPEED\n self.max_y_vel = c.MAX_Y_VEL\n self.x_accel = c.WALK_ACCEL\n self.jump_vel = c.JUMP_VEL\n self.gravity = c.GRAVITY\n\n def setup_counters(self):\n \"\"\"These keep track of various total for important values\"\"\"\n self.frame_index = 0\n self.invincible_index = 0\n self.fire_transition_index = 0\n self.fireball_count = 0\n self.flag_pole_right = 0\n\n def load_sounds(self):\n \"\"\"Load all Mario sound effects into a dictionary for later playback\"\"\"\n self.SFX = {\n 'big_jump': pg.mixer.Sound('audio/Big-Mario-Jump.wav'),\n 'coin': pg.mixer.Sound('audio/Coin.wav'),\n 'small_jump': pg.mixer.Sound('audio/Small-Mario-Jump.wav'),\n 'fireball': pg.mixer.Sound('audio/Fireball.wav'),\n 'kick': pg.mixer.Sound('audio/Mario-Kick-Shell.wav'),\n 'stomp': pg.mixer.Sound('audio/Mario-Stomp.wav'),\n 'powerup': pg.mixer.Sound('audio/Get-Powerup.wav'),\n 'shrink': pg.mixer.Sound('audio/Mario-Shrink.wav')\n }\n\n def load_images_from_sheet(self):\n \"\"\"Extracts Mario images from his sprite sheet and assigns\n them to appropriate lists\"\"\"\n self.right_frames = []\n self.left_frames = []\n\n self.right_small_normal_frames = []\n self.left_small_normal_frames = []\n self.right_small_red_frames = []\n self.left_small_red_frames = []\n self.right_small_black_frames = []\n self.left_small_black_frames = []\n\n self.right_big_normal_frames = []\n self.left_big_normal_frames = []\n self.right_big_red_frames = []\n self.left_big_red_frames = []\n self.right_big_black_frames = []\n self.left_big_black_frames = []\n\n self.right_fire_frames = []\n self.left_fire_frames = []\n\n # Images for normal small mario#\n\n self.right_small_normal_frames.append(\n self.get_image(178, 32, 12, 16)) # Right [0]\n self.right_small_normal_frames.append(\n self.get_image(80, 32, 15, 16)) # Right walking 1 [1]\n self.right_small_normal_frames.append(\n self.get_image(96, 32, 16, 16)) # Right walking 2 [2]\n self.right_small_normal_frames.append(\n self.get_image(112, 32, 16, 16)) # Right walking 3 [3]\n self.right_small_normal_frames.append(\n self.get_image(144, 32, 16, 16)) # Right jump [4]\n self.right_small_normal_frames.append(\n self.get_image(130, 32, 14, 16)) # Right skid [5]\n self.right_small_normal_frames.append(\n self.get_image(160, 32, 15, 16)) # Death frame [6]\n self.right_small_normal_frames.append(\n self.get_image(320, 8, 16, 24)) # Transition small to big [7]\n self.right_small_normal_frames.append(\n self.get_image(241, 33, 16, 16)) # Transition big to small [8]\n self.right_small_normal_frames.append(\n self.get_image(194, 32, 12, 16)) # Frame 1 of flag pole Slide [9]\n self.right_small_normal_frames.append(\n self.get_image(210, 33, 12, 16)) # Frame 2 of flag pole slide [10]\n\n # Images for small mario (for invincible animation)#\n\n self.right_small_red_frames.append(\n self.get_image(178, 272, 12, 16)) # Right standing [0]\n self.right_small_red_frames.append(\n self.get_image(80, 272, 15, 16)) # Right walking 1 [1]\n self.right_small_red_frames.append(\n self.get_image(96, 272, 16, 16)) # Right walking 2 [2]\n self.right_small_red_frames.append(\n self.get_image(112, 272, 15, 16)) # Right walking 3 [3]\n self.right_small_red_frames.append(\n self.get_image(144, 272, 16, 16)) # Right jump [4]\n self.right_small_red_frames.append(\n self.get_image(130, 272, 14, 16)) # Right skid [5]\n\n # Images for small black mario (for invincible animation)#\n\n self.right_small_black_frames.append(\n self.get_image(178, 176, 12, 16)) # Right standing [0]\n self.right_small_black_frames.append(\n self.get_image(80, 176, 15, 16)) # Right walking 1 [1]\n self.right_small_black_frames.append(\n self.get_image(96, 176, 16, 16)) # Right walking 2 [2]\n self.right_small_black_frames.append(\n self.get_image(112, 176, 15, 16)) # Right walking 3 [3]\n self.right_small_black_frames.append(\n self.get_image(144, 176, 16, 16)) # Right jump [4]\n self.right_small_black_frames.append(\n self.get_image(130, 176, 14, 16)) # Right skid [5]\n\n # Images for normal big Mario\n\n self.right_big_normal_frames.append(\n self.get_image(176, 0, 16, 32)) # Right standing [0]\n self.right_big_normal_frames.append(\n self.get_image(81, 0, 16, 32)) # Right walking 1 [1]\n self.right_big_normal_frames.append(\n self.get_image(97, 0, 15, 32)) # Right walking 2 [2]\n self.right_big_normal_frames.append(\n self.get_image(113, 0, 15, 32)) # Right walking 3 [3]\n self.right_big_normal_frames.append(\n self.get_image(144, 0, 16, 32)) # Right jump [4]\n self.right_big_normal_frames.append(\n self.get_image(128, 0, 16, 32)) # Right skid [5]\n self.right_big_normal_frames.append(\n self.get_image(336, 0, 16, 32)) # Right throwing [6]\n self.right_big_normal_frames.append(\n self.get_image(160, 10, 16, 22)) # Right crouching [7]\n self.right_big_normal_frames.append(\n self.get_image(272, 2, 16, 29)) # Transition big to small [8]\n self.right_big_normal_frames.append(\n self.get_image(193, 2, 16, 30)) # Frame 1 of flag pole slide [9]\n self.right_big_normal_frames.append(\n self.get_image(209, 2, 16, 29)) # Frame 2 of flag pole slide [10]\n\n # Images for red big Mario#\n\n self.right_big_red_frames.append(\n self.get_image(176, 240, 16, 32)) # Right standing [0]\n self.right_big_red_frames.append(\n self.get_image(81, 240, 16, 32)) # Right walking 1 [1]\n self.right_big_red_frames.append(\n self.get_image(97, 240, 15, 32)) # Right walking 2 [2]\n self.right_big_red_frames.append(\n self.get_image(113, 240, 15, 32)) # Right walking 3 [3]\n self.right_big_red_frames.append(\n self.get_image(144, 240, 16, 32)) # Right jump [4]\n self.right_big_red_frames.append(\n self.get_image(128, 240, 16, 32)) # Right skid [5]\n self.right_big_red_frames.append(\n self.get_image(336, 240, 16, 32)) # Right throwing [6]\n self.right_big_red_frames.append(\n self.get_image(160, 250, 16, 22)) # Right crouching [7]\n\n # Images for black big Mario#\n\n self.right_big_black_frames.append(\n self.get_image(176, 144, 16, 32)) # Right standing [0]\n self.right_big_black_frames.append(\n self.get_image(81, 144, 16, 32)) # Right walking 1 [1]\n self.right_big_black_frames.append(\n self.get_image(97, 144, 15, 32)) # Right walking 2 [2]\n self.right_big_black_frames.append(\n self.get_image(113, 144, 15, 32)) # Right walking 3 [3]\n self.right_big_black_frames.append(\n self.get_image(144, 144, 16, 32)) # Right jump [4]\n self.right_big_black_frames.append(\n self.get_image(128, 144, 16, 32)) # Right skid [5]\n self.right_big_black_frames.append(\n self.get_image(336, 144, 16, 32)) # Right throwing [6]\n self.right_big_black_frames.append(\n self.get_image(160, 154, 16, 22)) # Right Crouching [7]\n\n # Images for Fire Mario#\n\n self.right_fire_frames.append(\n self.get_image(176, 48, 16, 32)) # Right standing [0]\n self.right_fire_frames.append(\n self.get_image(81, 48, 16, 32)) # Right walking 1 [1]\n self.right_fire_frames.append(\n self.get_image(97, 48, 15, 32)) # Right walking 2 [2]\n self.right_fire_frames.append(\n self.get_image(113, 48, 15, 32)) # Right walking 3 [3]\n self.right_fire_frames.append(\n self.get_image(144, 48, 16, 32)) # Right jump [4]\n self.right_fire_frames.append(\n self.get_image(128, 48, 16, 32)) # Right skid [5]\n self.right_fire_frames.append(\n self.get_image(336, 48, 16, 32)) # Right throwing [6]\n self.right_fire_frames.append(\n self.get_image(160, 58, 16, 22)) # Right crouching [7]\n self.right_fire_frames.append(\n self.get_image(0, 0, 0, 0)) # Place holder [8]\n self.right_fire_frames.append(\n self.get_image(193, 50, 16, 29)) # Frame 1 of flag pole slide [9]\n self.right_fire_frames.append(\n self.get_image(209, 50, 16, 29)) # Frame 2 of flag pole slide [10]\n\n # The left image frames are numbered the same as the right\n # frames but are simply reversed.\n\n for frame in self.right_small_normal_frames:\n new_image = pg.transform.flip(frame, True, False)\n self.left_small_normal_frames.append(new_image)\n\n for frame in self.right_small_red_frames:\n new_image = pg.transform.flip(frame, True, False)\n self.left_small_red_frames.append(new_image)\n\n for frame in self.right_small_black_frames:\n new_image = pg.transform.flip(frame, True, False)\n self.left_small_black_frames.append(new_image)\n\n for frame in self.right_big_normal_frames:\n new_image = pg.transform.flip(frame, True, False)\n self.left_big_normal_frames.append(new_image)\n\n for frame in self.right_big_red_frames:\n new_image = pg.transform.flip(frame, True, False)\n self.left_big_red_frames.append(new_image)\n\n for frame in self.right_big_black_frames:\n new_image = pg.transform.flip(frame, True, False)\n self.left_big_black_frames.append(new_image)\n\n for frame in self.right_fire_frames:\n new_image = pg.transform.flip(frame, True, False)\n self.left_fire_frames.append(new_image)\n\n self.normal_small_frames = [self.right_small_normal_frames,\n self.left_small_normal_frames]\n\n self.red_small_frames = [self.right_small_red_frames,\n self.left_small_red_frames]\n\n self.black_small_frames = [self.right_small_black_frames,\n self.left_small_black_frames]\n\n self.invincible_small_frames_list = [self.normal_small_frames,\n self.red_small_frames,\n self.black_small_frames]\n\n self.normal_big_frames = [self.right_big_normal_frames,\n self.left_big_normal_frames]\n\n self.red_big_frames = [self.right_big_red_frames,\n self.left_big_red_frames]\n\n self.black_big_frames = [self.right_big_black_frames,\n self.left_big_black_frames]\n\n self.fire_frames = [self.right_fire_frames,\n self.left_fire_frames]\n\n self.invincible_big_frames_list = [self.normal_big_frames,\n self.red_big_frames,\n self.black_big_frames]\n\n self.all_images = [self.right_big_normal_frames,\n self.right_big_black_frames,\n self.right_big_red_frames,\n self.right_small_normal_frames,\n self.right_small_red_frames,\n self.right_small_black_frames,\n self.left_big_normal_frames,\n self.left_big_black_frames,\n self.left_big_red_frames,\n self.left_small_normal_frames,\n self.left_small_red_frames,\n self.left_small_black_frames]\n\n self.right_frames = self.normal_small_frames[0]\n self.left_frames = self.normal_small_frames[1]\n\n def get_image(self, x, y, width, height):\n \"\"\"Extracts image from sprite sheet\"\"\"\n image = pg.Surface([width, height])\n rect = image.get_rect()\n\n image.blit(self.sprite_sheet, (0, 0), (x, y, width, height))\n image.set_colorkey(c.BLACK)\n image = pg.transform.scale(image,\n (int(rect.width * c.SIZE_MULTIPLIER),\n int(rect.height * c.SIZE_MULTIPLIER)))\n return image\n\n def reset(self, map_layer, game_objects, reset_booleans=True):\n \"\"\"Reset states back to original\"\"\"\n if reset_booleans:\n self.setup_state_booleans()\n self.state = c.WALK\n self.map_layer = map_layer\n self.game_objects = game_objects\n self.left_bound = 0\n self.screen_shift = 0\n\n def update(self, keys):\n \"\"\"Updates Mario's states and animations once per frame\"\"\"\n self.handle_state(keys)\n if not self.state == c.DEATH_JUMP:\n self.check_for_special_state()\n self.animation()\n if self.state not in (c.SMALL_TO_BIG, c.BIG_TO_FIRE, c.BIG_TO_SMALL):\n self.check_fall()\n self.adjust_mario_position()\n if self.rect.right > self.screen_shift:\n self.screen_shift = self.rect.right + 1\n self.left_bound = self.rect.right - int(self.screen_rect.width * 0.45)\n self.map_layer.center((self.rect.centerx, self.rect.centery))\n if self.rect.top > self.screen.get_height():\n self.start_death_jump()\n self.fireball_controller.update_fireballs()\n\n def check_fall(self):\n \"\"\"Check if falling, apply gravity if so\"\"\"\n falling = True\n\n for flr_rect in self.game_objects['floors']:\n if self.rect.bottom >= flr_rect.top and (flr_rect.left < self.rect.left < flr_rect.right) and \\\n not self.rect.top >= flr_rect.bottom:\n self.rect.bottom = flr_rect.top\n self.y_vel = 0\n falling = False\n break\n if falling:\n for obj in self.game_objects['collide_objs']:\n if self.rect.bottom >= obj.rect.top and (obj.rect.left < self.rect.left < obj.rect.right) and \\\n not self.rect.top >= obj.rect.bottom:\n self.rect.bottom = obj.rect.top\n self.y_vel = 0\n falling = False\n break\n if falling:\n self.state = c.JUMP # using jump state instead of fall\n self.y_vel += c.GRAVITY\n self.frame_index = 4\n elif self.state == c.JUMP:\n self.state = c.WALK\n self.rect.y += self.y_vel\n\n def handle_state(self, keys):\n \"\"\"Determines Mario's behavior based on his state\"\"\"\n if self.state == c.STAND:\n self.standing(keys)\n elif self.state == c.WALK:\n self.walking(keys)\n elif self.state == c.JUMP:\n self.jumping(keys)\n elif self.state == c.DEATH_JUMP:\n self.jumping_to_death()\n elif self.state == c.SMALL_TO_BIG:\n self.changing_to_big()\n elif self.state == c.BIG_TO_FIRE:\n self.changing_to_fire()\n elif self.state == c.BIG_TO_SMALL:\n self.changing_to_small()\n elif self.state == c.FLAGPOLE:\n self.flag_pole_sliding()\n elif self.state == c.BOTTOM_OF_POLE:\n self.sitting_at_bottom_of_pole()\n elif self.state == c.WALKING_TO_CASTLE:\n self.walking_to_castle()\n elif self.state == c.END_OF_LEVEL_FALL:\n self.falling_at_end_of_level()\n\n def standing(self, keys):\n \"\"\"This function is called if Mario is standing still\"\"\"\n self.check_to_allow_jump(keys)\n self.check_to_allow_fireball(keys)\n\n self.frame_index = 0\n\n if keys[self.keybinding['action']]:\n if self.state_info['fire'] and self.state_info['allow_fireball']:\n self.shoot_fireball()\n\n if keys[self.keybinding['down']]:\n self.state_info['crouching'] = True\n\n if keys[self.keybinding['left']]:\n self.state_info['facing_right'] = False\n self.get_out_of_crouch()\n self.state = c.WALK\n elif keys[self.keybinding['right']]:\n self.state_info['facing_right'] = True\n self.get_out_of_crouch()\n self.state = c.WALK\n elif keys[self.keybinding['jump']]:\n if self.state_info['allow_jump']:\n if self.state_info['big']:\n self.SFX['big_jump'].play()\n else:\n self.SFX['small_jump'].play()\n self.state = c.JUMP\n self.y_vel = c.JUMP_VEL\n self.rect.y -= 1\n else:\n self.state = c.STAND\n\n if not keys[self.keybinding['down']]:\n self.get_out_of_crouch()\n\n def get_out_of_crouch(self):\n \"\"\"Get out of crouch\"\"\"\n bottom = self.rect.bottom\n left = self.rect.x\n if self.state_info['facing_right']:\n self.image = self.right_frames[0]\n else:\n self.image = self.left_frames[0]\n self.rect = self.image.get_rect()\n self.rect.bottom = bottom\n self.rect.x = left\n self.state_info['crouching'] = False\n\n def check_to_allow_jump(self, keys):\n \"\"\"Check to allow Mario to jump\"\"\"\n if not keys[self.keybinding['jump']]:\n self.state_info['allow_jump'] = True\n\n def check_to_allow_fireball(self, keys):\n \"\"\"Check to allow the shooting of a fireball\"\"\"\n if not keys[self.keybinding['action']]:\n self.state_info['allow_fireball'] = True\n\n def shoot_fireball(self):\n \"\"\"Shoots fireball, allowing no more than two to exist at once\"\"\"\n if (pg.time.get_ticks() - self.timers['last_fireball']) > 200:\n if self.fireball_controller.throw_fireball():\n self.SFX['fireball'].play()\n self.state_info['allow_fireball'] = False\n self.timers['last_fireball'] = pg.time.get_ticks()\n\n self.frame_index = 6\n if self.state_info['facing_right']:\n self.image = self.right_frames[self.frame_index]\n else:\n self.image = self.left_frames[self.frame_index]\n\n def walking(self, keys):\n \"\"\"This function is called when Mario is in a walking state\n It changes the frame, checks for holding down the run button,\n checks for a jump, then adjusts the state if necessary\"\"\"\n\n self.check_to_allow_jump(keys)\n self.check_to_allow_fireball(keys)\n\n if self.frame_index == 0:\n self.frame_index += 1\n self.timers['walking'] = pg.time.get_ticks()\n else:\n if (pg.time.get_ticks() - self.timers['walking'] >\n self.calculate_animation_speed()):\n if self.frame_index < 3:\n self.frame_index += 1\n else:\n self.frame_index = 1\n\n self.timers['walking'] = pg.time.get_ticks()\n\n if keys[self.keybinding['action']]:\n self.max_x_vel = c.MAX_RUN_SPEED\n self.x_accel = c.RUN_ACCEL\n if self.state_info['fire'] and self.state_info['allow_fireball']:\n self.shoot_fireball()\n else:\n self.max_x_vel = c.MAX_WALK_SPEED\n self.x_accel = c.WALK_ACCEL\n\n if keys[self.keybinding['jump']]:\n if self.state_info['allow_jump']:\n if self.state_info['big']:\n self.SFX['big_jump'].play()\n else:\n self.SFX['small_jump'].play()\n self.state = c.JUMP\n if self.x_vel > 4.5 or self.x_vel < -4.5:\n self.y_vel = c.JUMP_VEL - .5\n else:\n self.y_vel = c.JUMP_VEL\n self.rect.y -= 1\n\n if keys[self.keybinding['left']]:\n self.get_out_of_crouch()\n self.state_info['facing_right'] = False\n if self.x_vel > 0:\n self.frame_index = 5\n self.x_accel = c.SMALL_TURNAROUND\n else:\n self.x_accel = c.WALK_ACCEL\n\n if self.x_vel > (self.max_x_vel * -1):\n self.x_vel -= self.x_accel\n if self.x_vel > -0.5:\n self.x_vel = -0.5\n elif self.x_vel < (self.max_x_vel * -1):\n self.x_vel += self.x_accel\n\n elif keys[self.keybinding['right']]:\n self.get_out_of_crouch()\n self.state_info['facing_right'] = True\n if self.x_vel < 0:\n self.frame_index = 5\n self.x_accel = c.SMALL_TURNAROUND\n else:\n self.x_accel = c.WALK_ACCEL\n\n if self.x_vel < self.max_x_vel:\n self.x_vel += self.x_accel\n if self.x_vel < 0.5:\n self.x_vel = 0.5\n elif self.x_vel > self.max_x_vel:\n self.x_vel -= self.x_accel\n\n else:\n if self.state_info['facing_right']:\n if self.x_vel > 0:\n self.x_vel -= self.x_accel\n else:\n self.x_vel = 0\n self.state = c.STAND\n else:\n if self.x_vel < 0:\n self.x_vel += self.x_accel\n else:\n self.x_vel = 0\n self.state = c.STAND\n\n def check_left_side(self):\n \"\"\"Check if Mario is toward the left side of the screen\"\"\"\n return self.rect.left <= self.left_bound\n\n def calculate_animation_speed(self):\n \"\"\"Used to make walking animation speed be in relation to\n Mario's x-vel\"\"\"\n if self.x_vel == 0:\n animation_speed = 130\n elif self.x_vel > 0:\n animation_speed = 130 - (self.x_vel * 13)\n else:\n animation_speed = 130 - (self.x_vel * 13 * -1)\n\n return animation_speed\n\n def jumping(self, keys):\n \"\"\"Called when Mario is in a JUMP state.\"\"\"\n self.state_info['allow_jump'] = False\n self.frame_index = 4\n self.check_to_allow_fireball(keys)\n\n if keys[self.keybinding['left']]:\n if self.x_vel > (self.max_x_vel * - 1):\n self.x_vel -= self.x_accel\n\n elif keys[self.keybinding['right']]:\n if self.x_vel < self.max_x_vel:\n self.x_vel += self.x_accel\n\n if keys[self.keybinding['action']]:\n if self.state_info['fire'] and self.state_info['allow_fireball']:\n self.shoot_fireball()\n\n def jumping_to_death(self):\n \"\"\"Called when Mario is in a DEATH_JUMP state\"\"\"\n if self.timers['death'] == 0:\n self.timers['death'] = pg.time.get_ticks()\n elif (pg.time.get_ticks() - self.timers['death']) > 500:\n self.rect.y += self.y_vel\n self.y_vel += self.gravity\n if not self.state_info['death_finish'] and self.rect.y > self.screen.get_height() * 2:\n self.state_info['death_finish'] = True\n\n def start_death_jump(self):\n \"\"\"Used to put Mario in a DEATH_JUMP state\"\"\"\n self.state_info['dead'] = True\n self.y_vel = -11\n self.x_vel = 0\n self.gravity = .5\n self.frame_index = 6\n self.right_frames = self.right_small_normal_frames\n self.image = self.right_frames[self.frame_index]\n self.state = c.DEATH_JUMP\n self.state_info['in_transition'] = True\n pg.mixer.music.stop()\n\n def changing_to_big(self):\n \"\"\"Changes Mario's image attribute based on time while\n transitioning to big\"\"\"\n self.state_info['in_transition'] = True\n\n if self.timers['transition'] == 0:\n self.timers['transition'] = pg.time.get_ticks()\n elif self.timer_between_these_two_times(135, 200):\n self.set_mario_to_middle_image()\n elif self.timer_between_these_two_times(200, 365):\n self.set_mario_to_small_image()\n elif self.timer_between_these_two_times(365, 430):\n self.set_mario_to_middle_image()\n elif self.timer_between_these_two_times(430, 495):\n self.set_mario_to_small_image()\n elif self.timer_between_these_two_times(495, 560):\n self.set_mario_to_middle_image()\n elif self.timer_between_these_two_times(560, 625):\n self.set_mario_to_big_image()\n elif self.timer_between_these_two_times(625, 690):\n self.set_mario_to_small_image()\n elif self.timer_between_these_two_times(690, 755):\n self.set_mario_to_middle_image()\n elif self.timer_between_these_two_times(755, 820):\n self.set_mario_to_big_image()\n elif self.timer_between_these_two_times(820, 885):\n self.set_mario_to_small_image()\n elif self.timer_between_these_two_times(885, 950):\n self.set_mario_to_big_image()\n self.state = c.WALK\n self.state_info['in_transition'] = False\n self.timers['transition'] = 0\n self.become_big()\n\n def become_big(self):\n self.state_info['big'] = True\n self.right_frames = self.right_big_normal_frames\n self.left_frames = self.left_big_normal_frames\n bottom = self.rect.bottom\n left = self.rect.x\n image = self.right_frames[0]\n self.rect = image.get_rect()\n self.rect.bottom = bottom\n self.rect.x = left\n\n def timer_between_these_two_times(self, start_time, end_time):\n \"\"\"Checks if the timer is at the right time for the action.\"\"\"\n if start_time <= (pg.time.get_ticks() - self.timers['transition']) < end_time:\n return True\n return False\n\n def set_mario_to_middle_image(self):\n \"\"\"During a change from small to big, sets mario's image to the\n transition/middle size\"\"\"\n if self.state_info['facing_right']:\n self.image = self.normal_small_frames[0][7]\n else:\n self.image = self.normal_small_frames[1][7]\n bottom = self.rect.bottom\n centerx = self.rect.centerx\n self.rect = self.image.get_rect()\n self.rect.bottom = bottom\n self.rect.centerx = centerx\n\n def set_mario_to_big_image(self):\n \"\"\"During a change from small to big, sets mario's image to big\"\"\"\n if self.state_info['facing_right']:\n self.image = self.normal_big_frames[0][0]\n else:\n self.image = self.normal_big_frames[1][0]\n bottom = self.rect.bottom\n centerx = self.rect.centerx\n self.rect = self.image.get_rect()\n self.rect.bottom = bottom\n self.rect.centerx = centerx\n\n def set_mario_to_small_image(self):\n \"\"\"During a change from small to big, sets mario's image to small\"\"\"\n if self.state_info['facing_right']:\n self.image = self.normal_small_frames[0][0]\n else:\n self.image = self.normal_small_frames[1][0]\n bottom = self.rect.bottom\n centerx = self.rect.centerx\n self.rect = self.image.get_rect()\n self.rect.bottom = bottom\n self.rect.centerx = centerx\n\n def changing_to_fire(self):\n \"\"\"Called when Mario is in a BIG_TO_FIRE state (i.e. when\n he obtains a fire flower)\"\"\"\n self.state_info['in_transition'] = True\n\n if self.state_info['facing_right']:\n frames = [self.right_big_normal_frames[0],\n self.fire_frames[0][0]]\n else:\n frames = [self.left_big_normal_frames[0],\n self.fire_frames[0][1]]\n\n if self.timers['fire_transition'] == 0:\n self.timers['fire_transition'] = pg.time.get_ticks()\n elif (pg.time.get_ticks() - self.timers['fire_transition']) > 65 and (\n pg.time.get_ticks() - self.timers['fire_transition']) < 130:\n self.image = frames[0]\n elif (pg.time.get_ticks() - self.timers['fire_transition']) < 195:\n self.image = frames[1]\n elif (pg.time.get_ticks() - self.timers['fire_transition']) < 260:\n self.image = frames[0]\n elif (pg.time.get_ticks() - self.timers['fire_transition']) < 325:\n self.image = frames[1]\n elif (pg.time.get_ticks() - self.timers['fire_transition']) < 390:\n self.image = frames[0]\n elif (pg.time.get_ticks() - self.timers['fire_transition']) < 455:\n self.image = frames[1]\n elif (pg.time.get_ticks() - self.timers['fire_transition']) < 520:\n self.image = frames[0]\n elif (pg.time.get_ticks() - self.timers['fire_transition']) < 585:\n self.image = frames[1]\n elif (pg.time.get_ticks() - self.timers['fire_transition']) < 650:\n self.image = frames[0]\n elif (pg.time.get_ticks() - self.timers['fire_transition']) < 715:\n self.image = frames[1]\n elif (pg.time.get_ticks() - self.timers['fire_transition']) < 780:\n self.image = frames[0]\n elif (pg.time.get_ticks() - self.timers['fire_transition']) < 845:\n self.image = frames[1]\n elif (pg.time.get_ticks() - self.timers['fire_transition']) < 910:\n self.image = frames[0]\n elif (pg.time.get_ticks() - self.timers['fire_transition']) < 975:\n self.image = frames[1]\n elif (pg.time.get_ticks() - self.timers['fire_transition']) < 1040:\n self.image = frames[1]\n self.state_info['fire'] = True\n self.state_info['in_transition'] = False\n self.state = c.WALK\n self.timers['transition'] = 0\n\n def changing_to_small(self):\n \"\"\"Mario's state and animation when he shrinks from big to small\n after colliding with an enemy\"\"\"\n self.state_info['in_transition'] = True\n self.state_info['hurt_invincible'] = True\n self.state = c.BIG_TO_SMALL\n\n if self.state_info['facing_right']:\n frames = [self.right_big_normal_frames[4],\n self.right_big_normal_frames[8],\n self.right_small_normal_frames[8]\n ]\n else:\n frames = [self.left_big_normal_frames[4],\n self.left_big_normal_frames[8],\n self.left_small_normal_frames[8]\n ]\n\n if self.timers['transition'] == 0:\n self.timers['transition'] = pg.time.get_ticks()\n elif (pg.time.get_ticks() - self.timers['transition']) < 265:\n self.image = frames[0]\n self.hurt_invincible_check()\n self.adjust_rect()\n elif (pg.time.get_ticks() - self.timers['transition']) < 330:\n self.image = frames[1]\n self.hurt_invincible_check()\n self.adjust_rect()\n elif (pg.time.get_ticks() - self.timers['transition']) < 395:\n self.image = frames[2]\n self.hurt_invincible_check()\n self.adjust_rect()\n elif (pg.time.get_ticks() - self.timers['transition']) < 460:\n self.image = frames[1]\n self.hurt_invincible_check()\n self.adjust_rect()\n elif (pg.time.get_ticks() - self.timers['transition']) < 525:\n self.image = frames[2]\n self.hurt_invincible_check()\n self.adjust_rect()\n elif (pg.time.get_ticks() - self.timers['transition']) < 590:\n self.image = frames[1]\n self.hurt_invincible_check()\n self.adjust_rect()\n elif (pg.time.get_ticks() - self.timers['transition']) < 655:\n self.image = frames[2]\n self.hurt_invincible_check()\n self.adjust_rect()\n elif (pg.time.get_ticks() - self.timers['transition']) < 720:\n self.image = frames[1]\n self.hurt_invincible_check()\n self.adjust_rect()\n elif (pg.time.get_ticks() - self.timers['transition']) < 785:\n self.image = frames[2]\n self.hurt_invincible_check()\n self.adjust_rect()\n elif (pg.time.get_ticks() - self.timers['transition']) < 850:\n self.image = frames[1]\n self.hurt_invincible_check()\n self.adjust_rect()\n elif (pg.time.get_ticks() - self.timers['transition']) < 915:\n self.image = frames[2]\n self.adjust_rect()\n self.state_info['in_transition'] = False\n self.state = c.WALK\n self.state_info['big'] = False\n self.timers['transition'] = 0\n self.timers['hurt_invincible_1'] = 0\n self.become_small()\n\n def adjust_rect(self):\n \"\"\"Makes sure new Rect has the same bottom and left\n location as previous Rect\"\"\"\n x = self.rect.x\n bottom = self.rect.bottom\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.bottom = bottom\n\n def become_small(self):\n self.state_info['big'] = False\n self.right_frames = self.right_small_normal_frames\n self.left_frames = self.left_small_normal_frames\n bottom = self.rect.bottom\n left = self.rect.x\n image = self.right_frames[0]\n self.rect = image.get_rect()\n self.rect.bottom = bottom\n self.rect.x = left\n\n def flag_pole_sliding(self):\n \"\"\"State where Mario is sliding down the flag pole\"\"\"\n self.state = c.FLAGPOLE\n self.state_info['in_transition'] = True\n self.x_vel = 0\n self.y_vel = 0\n if self.state_info['big'] and not self.state_info['fire']:\n self.right_frames = self.right_fire_frames\n elif self.state_info['big']:\n self.right_frames = self.right_big_normal_frames\n else:\n self.right_frames = self.right_small_normal_frames\n\n if self.timers['flag_pole'] == 0:\n self.timers['flag_pole'] = pg.time.get_ticks()\n elif self.rect.bottom < 493:\n if (pg.time.get_ticks() - self.timers['flag_pole']) < 65:\n self.image = self.right_frames[9]\n elif (pg.time.get_ticks() - self.timers['flag_pole']) < 130:\n self.image = self.right_frames[10]\n elif (pg.time.get_ticks() - self.timers['flag_pole']) >= 130:\n self.timers['flag_pole'] = pg.time.get_ticks()\n\n self.rect.right = self.flag_pole_right\n self.y_vel = 5\n self.rect.y += self.y_vel\n\n if self.rect.bottom >= 488:\n self.timers['flag_pole'] = pg.time.get_ticks()\n\n elif self.rect.bottom >= 493:\n self.image = self.right_frames[10]\n\n def sitting_at_bottom_of_pole(self):\n \"\"\"State when mario is at the bottom of the flag pole\"\"\"\n if self.timers['flag_pole'] == 0:\n self.timers['flag_pole'] = pg.time.get_ticks()\n self.image = self.left_frames[10]\n elif (pg.time.get_ticks() - self.timers['flag_pole']) < 210:\n self.image = self.left_frames[10]\n else:\n self.state_info['in_transition'] = False\n if self.rect.bottom < 485:\n self.state = c.END_OF_LEVEL_FALL\n else:\n self.state = c.WALKING_TO_CASTLE\n\n def set_state_to_bottom_of_pole(self):\n \"\"\"Sets Mario to the BOTTOM_OF_POLE state\"\"\"\n self.image = self.left_frames[9]\n right = self.rect.right\n # self.rect.bottom = 493\n self.rect.x = right\n if self.state_info['big']:\n self.rect.x -= 10\n self.timers['flag_pole'] = 0\n self.state = c.BOTTOM_OF_POLE\n\n def walking_to_castle(self):\n \"\"\"State when Mario walks to the castle to end the level\"\"\"\n self.max_x_vel = 5\n self.x_accel = c.WALK_ACCEL\n\n if self.x_vel < self.max_x_vel:\n self.x_vel += self.x_accel\n\n if self.timers['walking'] == 0 or (pg.time.get_ticks() - self.timers['walking']) > 200:\n self.timers['walking'] = pg.time.get_ticks()\n\n elif (pg.time.get_ticks() - self.timers['walking']) > \\\n self.calculate_animation_speed():\n if self.frame_index < 3:\n self.frame_index += 1\n else:\n self.frame_index = 1\n self.timers['walking'] = pg.time.get_ticks()\n\n def falling_at_end_of_level(self):\n \"\"\"State when Mario is falling from the flag pole base\"\"\"\n self.y_vel += c.GRAVITY\n\n def check_for_special_state(self):\n \"\"\"Determines if Mario is invincible, Fire Mario or recently hurt\"\"\"\n self.check_if_invincible()\n self.check_if_fire()\n self.check_if_hurt_invincible()\n self.check_if_crouching()\n\n def check_if_invincible(self):\n if self.state_info['invincible']:\n if (pg.time.get_ticks() - self.timers['invincible_start']) < 10000:\n self.state_info['losing_invincibility'] = False\n self.change_frame_list(30)\n elif (pg.time.get_ticks() - self.timers['invincible_start']) < 12000:\n self.state_info['losing_invincibility'] = True\n self.change_frame_list(100)\n else:\n self.state_info['losing_invincibility'] = False\n self.state_info['invincible'] = False\n else:\n if self.state_info['big']:\n self.right_frames = self.invincible_big_frames_list[0][0]\n self.left_frames = self.invincible_big_frames_list[0][1]\n else:\n self.right_frames = self.invincible_small_frames_list[0][0]\n self.left_frames = self.invincible_small_frames_list[0][1]\n\n def change_frame_list(self, frame_switch_speed):\n if (pg.time.get_ticks() - self.timers['invincible_animation']) > frame_switch_speed:\n if self.invincible_index < (len(self.invincible_small_frames_list) - 1):\n self.invincible_index += 1\n else:\n self.invincible_index = 0\n\n if self.state_info['big']:\n frames = self.invincible_big_frames_list[self.invincible_index]\n else:\n frames = self.invincible_small_frames_list[self.invincible_index]\n\n self.right_frames = frames[0]\n self.left_frames = frames[1]\n\n self.timers['invincible_animation'] = pg.time.get_ticks()\n\n def check_if_fire(self):\n if self.state_info['fire'] and not self.state_info['invincible']:\n self.right_frames = self.fire_frames[0]\n self.left_frames = self.fire_frames[1]\n\n def check_if_hurt_invincible(self):\n \"\"\"Check if Mario is still temporarily invincible after getting hurt\"\"\"\n if self.state_info['hurt_invincible'] and self.state != c.BIG_TO_SMALL:\n if self.timers['hurt_invincible_2'] == 0:\n self.timers['hurt_invincible_2'] = pg.time.get_ticks()\n elif (pg.time.get_ticks() - self.timers['hurt_invincible_2']) < 2000:\n self.hurt_invincible_check()\n else:\n self.state_info['hurt_invincible'] = False\n self.timers['hurt_invincible_1'] = 0\n self.timers['hurt_invincible_2'] = 0\n for frames in self.all_images:\n for image in frames:\n image.set_alpha(255)\n\n def hurt_invincible_check(self):\n \"\"\"Makes Mario invincible on a fixed interval\"\"\"\n if self.timers['hurt_invincible_1'] == 0:\n self.timers['hurt_invincible_1'] = pg.time.get_ticks()\n elif (pg.time.get_ticks() - self.timers['hurt_invincible_1']) < 35:\n self.image.set_alpha(0)\n elif (pg.time.get_ticks() - self.timers['hurt_invincible_1']) < 70:\n self.image.set_alpha(255)\n self.timers['hurt_invincible_1'] = pg.time.get_ticks()\n\n def check_if_crouching(self):\n \"\"\"Checks if mario is crouching\"\"\"\n if self.state_info['crouching'] and self.state_info['big']:\n bottom = self.rect.bottom\n left = self.rect.x\n if self.state_info['facing_right']:\n self.image = self.right_frames[7]\n else:\n self.image = self.left_frames[7]\n self.rect = self.image.get_rect()\n self.rect.bottom = bottom\n self.rect.x = left\n\n def animation(self):\n \"\"\"Adjusts Mario's image for animation\"\"\"\n if self.state == c.DEATH_JUMP \\\n or self.state == c.SMALL_TO_BIG \\\n or self.state == c.BIG_TO_FIRE \\\n or self.state == c.BIG_TO_SMALL \\\n or self.state == c.FLAGPOLE \\\n or self.state == c.BOTTOM_OF_POLE \\\n or self.state_info['crouching']:\n pass\n elif self.state_info['facing_right']:\n self.image = self.right_frames[self.frame_index]\n else:\n self.image = self.left_frames[self.frame_index]\n\n def check_wall(self):\n \"\"\"Check if Mario is attempting to walk through a wall\"\"\"\n for obj in self.game_objects['collide_objs']:\n pts = [obj.rect.midleft, obj.rect.midright]\n for pt in pts:\n if self.rect.collidepoint(pt):\n print('collide obj')\n print(obj.rect.x, obj.rect.y)\n if obj.rect.right > self.rect.right:\n self.rect.right = obj.rect.left\n else:\n self.rect.left = obj.rect.right + 1\n return True\n return False\n\n def adjust_mario_position(self):\n \"\"\"Adjusts Mario's position based on his x, y velocities and\n potential collisions\"\"\"\n # self.last_x_position = self.rect.right\n if not self.check_left_side() and not self.check_wall():\n self.rect.x += round(self.x_vel * 2)\n # self.rect.x += round(self.x_vel)\n self.check_mario_x_collisions()\n\n if not self.state_info['in_transition']:\n self.rect.y += round(self.y_vel)\n self.check_mario_y_collisions()\n\n def check_mario_x_collisions(self):\n \"\"\"Check for collisions after Mario is moved on the x axis\"\"\"\n koopa = None\n for k in self.game_objects['koopa']:\n k_pts = [k.rect.midleft, k.rect.midright]\n for pt in k_pts:\n if self.rect.collidepoint(pt):\n koopa = k\n break\n if koopa:\n break\n goomba = None\n for g in self.game_objects['goomba']:\n g_pts = [g.rect.midleft, g.rect.midright]\n for pt in g_pts:\n if self.rect.collidepoint(pt):\n goomba = g\n break\n if goomba:\n break\n power_up = pg.sprite.spritecollideany(self, self.game_objects['items'])\n\n if (goomba and not goomba.player_enemy_kill) or (koopa and not koopa.player_enemy_kill):\n target = goomba or koopa\n if target not in self.sprites_about_to_die_group:\n if self.state_info['invincible']:\n self.SFX['kick'].play()\n self.sprites_about_to_die_group.add(target)\n target.player_enemy_kill = True\n elif self.state_info['big']:\n self.SFX['shrink'].play()\n self.state_info['fire'] = False\n self.y_vel = -1\n self.state = c.BIG_TO_SMALL\n elif self.state_info['hurt_invincible']:\n pass\n else:\n self.start_death_jump()\n elif power_up and not power_up.item_type == Item.ONE_UP:\n if power_up.item_type == Item.STARMAN:\n self.state_info['invincible'] = True\n pg.mixer.music.load('audio/Star-Theme.ogg')\n pg.mixer.music.play()\n self.timers['invincible_start'] = pg.time.get_ticks()\n elif power_up.item_type == Item.MUSHROOM:\n self.SFX['powerup'].play()\n self.y_vel = -1\n self.state = c.SMALL_TO_BIG\n self.state_info['in_transition'] = True\n elif power_up.item_type == Item.FIRE_FLOWER:\n self.SFX['powerup'].play()\n if self.state_info['big'] and not self.state_info['fire']:\n self.state = c.BIG_TO_FIRE\n self.state_info['in_transition'] = True\n elif not self.state_info['big']:\n self.state = c.SMALL_TO_BIG\n self.state_info['in_transition'] = True\n power_up.kill()\n\n def adjust_mario_for_x_collisions(self, collider):\n \"\"\"Puts Mario flush next to the collider after moving on the x axis\"\"\"\n if self.rect.x < collider.rect.x:\n self.rect.right = collider.rect.left\n else:\n self.rect.left = collider.rect.right\n\n self.x_vel = 0\n\n def check_mario_y_collisions(self):\n \"\"\"Checks for collisions when Mario moves along the y-axis\"\"\"\n enemy = None\n for g in self.game_objects['goomba']:\n if self.rect.collidepoint(g.rect.midtop):\n enemy = g\n break\n if not enemy:\n for k in self.game_objects['koopa']:\n if self.rect.collidepoint(k.rect.midtop):\n enemy = k\n break\n if enemy and not enemy.player_enemy_kill:\n print('enemy')\n enemy.set_killed()\n self.adjust_mario_for_y_enemy_collisions(enemy)\n\n def check_if_enemy_on_brick(self, brick):\n \"\"\"Kills enemy if on a bumped or broken brick\"\"\"\n brick.rect.y -= 5\n\n enemy = pg.sprite.spritecollideany(brick, self.game_objects['goomba'], self.game_objects['koopa'])\n\n if enemy:\n self.SFX['kick'].play()\n enemy.kill()\n self.sprites_about_to_die_group.add(enemy)\n if self.rect.centerx > brick.rect.centerx:\n enemy.start_death_jump('right')\n else:\n enemy.start_death_jump('left')\n\n brick.rect.y += 5\n\n def adjust_mario_for_y_ground_pipe_collisions(self, collider):\n \"\"\"Mario collisions with pipes on the y-axis\"\"\"\n if collider.rect.bottom > self.rect.bottom:\n self.y_vel = 0\n self.rect.bottom = collider.rect.top\n if self.state == c.END_OF_LEVEL_FALL:\n self.state = c.WALKING_TO_CASTLE\n else:\n self.state = c.WALK\n elif collider.rect.top < self.rect.top:\n self.y_vel = 7\n self.rect.top = collider.rect.bottom\n self.state = c.FALL\n\n def adjust_mario_for_y_enemy_collisions(self, enemy):\n \"\"\"Mario collisions with all enemies on the y-axis\"\"\"\n self.SFX['stomp'].play()\n self.rect.bottom = enemy.rect.top - 1\n self.state = c.JUMP\n self.y_vel = -7\n", "repo_name": "CristopherH95/CPSC-386-Super-Mario", "sub_path": "mario.py", "file_name": "mario.py", "file_ext": "py", "file_size_in_byte": 52248, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "pygame.sprite", "line_number": 6, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Sprite.__init__", "line_number": 8, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 9, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 9, "usage_type": "attribute"}, {"api_name": "item.FireBallController", "line_number": 22, "usage_type": "call"}, {"api_name": "pygame.sprite.Group", "line_number": 29, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 29, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Group", "line_number": 31, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 31, "usage_type": "attribute"}, {"api_name": "constants.WALK", "line_number": 83, "usage_type": "attribute"}, {"api_name": "pygame.mask.from_surface", "line_number": 86, "usage_type": "call"}, {"api_name": "pygame.mask", "line_number": 86, "usage_type": "attribute"}, {"api_name": "pygame.K_LSHIFT", "line_number": 90, "usage_type": "attribute"}, {"api_name": "pygame.K_SPACE", "line_number": 91, "usage_type": "attribute"}, {"api_name": "pygame.K_LEFT", "line_number": 92, "usage_type": "attribute"}, {"api_name": "pygame.K_RIGHT", "line_number": 93, "usage_type": "attribute"}, {"api_name": "pygame.K_DOWN", "line_number": 94, "usage_type": "attribute"}, {"api_name": "constants.MAX_WALK_SPEED", "line_number": 132, "usage_type": "attribute"}, {"api_name": "constants.MAX_Y_VEL", "line_number": 133, "usage_type": "attribute"}, {"api_name": "constants.WALK_ACCEL", "line_number": 134, "usage_type": "attribute"}, {"api_name": "constants.JUMP_VEL", "line_number": 135, "usage_type": "attribute"}, {"api_name": "constants.GRAVITY", "line_number": 136, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 149, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 149, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 150, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 150, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 151, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 151, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 152, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 152, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 153, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 153, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 154, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 154, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 155, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 155, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 156, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 156, "usage_type": "attribute"}, {"api_name": "pygame.transform.flip", "line_number": 329, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 329, "usage_type": "attribute"}, {"api_name": "pygame.transform.flip", "line_number": 333, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 333, "usage_type": "attribute"}, {"api_name": "pygame.transform.flip", "line_number": 337, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 337, "usage_type": "attribute"}, {"api_name": "pygame.transform.flip", "line_number": 341, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 341, "usage_type": "attribute"}, {"api_name": "pygame.transform.flip", "line_number": 345, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 345, "usage_type": "attribute"}, {"api_name": "pygame.transform.flip", "line_number": 349, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 349, "usage_type": "attribute"}, {"api_name": "pygame.transform.flip", "line_number": 353, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 353, "usage_type": "attribute"}, {"api_name": "pygame.Surface", "line_number": 403, "usage_type": "call"}, {"api_name": "constants.BLACK", "line_number": 407, "usage_type": "attribute"}, {"api_name": "pygame.transform.scale", "line_number": 408, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 408, "usage_type": "attribute"}, {"api_name": "constants.SIZE_MULTIPLIER", "line_number": 409, "usage_type": "attribute"}, {"api_name": "constants.SIZE_MULTIPLIER", "line_number": 410, "usage_type": "attribute"}, {"api_name": "constants.WALK", "line_number": 417, "usage_type": "attribute"}, {"api_name": "constants.DEATH_JUMP", "line_number": 426, "usage_type": "attribute"}, {"api_name": "constants.SMALL_TO_BIG", "line_number": 429, "usage_type": "attribute"}, {"api_name": "constants.BIG_TO_FIRE", "line_number": 429, "usage_type": "attribute"}, {"api_name": "constants.BIG_TO_SMALL", "line_number": 429, "usage_type": "attribute"}, {"api_name": "constants.JUMP", "line_number": 460, "usage_type": "attribute"}, {"api_name": "constants.GRAVITY", "line_number": 461, "usage_type": "attribute"}, {"api_name": "constants.JUMP", "line_number": 463, "usage_type": "attribute"}, {"api_name": "constants.WALK", "line_number": 464, "usage_type": "attribute"}, {"api_name": "constants.STAND", "line_number": 469, "usage_type": "attribute"}, {"api_name": "constants.WALK", "line_number": 471, "usage_type": "attribute"}, {"api_name": "constants.JUMP", "line_number": 473, "usage_type": "attribute"}, {"api_name": "constants.DEATH_JUMP", "line_number": 475, "usage_type": "attribute"}, {"api_name": "constants.SMALL_TO_BIG", "line_number": 477, "usage_type": "attribute"}, {"api_name": "constants.BIG_TO_FIRE", "line_number": 479, "usage_type": "attribute"}, {"api_name": "constants.BIG_TO_SMALL", "line_number": 481, "usage_type": "attribute"}, {"api_name": "constants.FLAGPOLE", "line_number": 483, "usage_type": "attribute"}, {"api_name": "constants.BOTTOM_OF_POLE", "line_number": 485, "usage_type": "attribute"}, {"api_name": "constants.WALKING_TO_CASTLE", "line_number": 487, "usage_type": "attribute"}, {"api_name": "constants.END_OF_LEVEL_FALL", "line_number": 489, "usage_type": "attribute"}, {"api_name": "constants.WALK", "line_number": 509, "usage_type": "attribute"}, {"api_name": "constants.WALK", "line_number": 513, "usage_type": "attribute"}, {"api_name": "constants.JUMP", "line_number": 520, "usage_type": "attribute"}, {"api_name": "constants.JUMP_VEL", "line_number": 521, "usage_type": "attribute"}, {"api_name": "constants.STAND", "line_number": 524, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 554, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 554, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 558, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 558, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 576, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 576, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 578, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 578, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 585, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 585, "usage_type": "attribute"}, {"api_name": "constants.MAX_RUN_SPEED", "line_number": 588, "usage_type": "attribute"}, {"api_name": "constants.RUN_ACCEL", "line_number": 589, "usage_type": "attribute"}, {"api_name": "constants.MAX_WALK_SPEED", "line_number": 593, "usage_type": "attribute"}, {"api_name": "constants.WALK_ACCEL", "line_number": 594, "usage_type": "attribute"}, {"api_name": "constants.JUMP", "line_number": 602, "usage_type": "attribute"}, {"api_name": "constants.JUMP_VEL", "line_number": 604, "usage_type": "attribute"}, {"api_name": "constants.JUMP_VEL", "line_number": 606, "usage_type": "attribute"}, {"api_name": "constants.SMALL_TURNAROUND", "line_number": 614, "usage_type": "attribute"}, {"api_name": "constants.WALK_ACCEL", "line_number": 616, "usage_type": "attribute"}, {"api_name": "constants.SMALL_TURNAROUND", "line_number": 630, "usage_type": "attribute"}, {"api_name": "constants.WALK_ACCEL", "line_number": 632, "usage_type": "attribute"}, {"api_name": "constants.STAND", "line_number": 647, "usage_type": "attribute"}, {"api_name": "constants.STAND", "line_number": 653, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 692, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 692, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 693, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 693, "usage_type": "attribute"}, {"api_name": "constants.DEATH_JUMP", "line_number": 708, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.stop", "line_number": 710, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 710, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 718, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 718, "usage_type": "attribute"}, {"api_name": "constants.WALK", "line_number": 741, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 759, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 759, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 813, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 813, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 814, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 814, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 815, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 815, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 817, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 817, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 819, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 819, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 821, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 821, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 823, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 823, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 825, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 825, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 827, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 827, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 829, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 829, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 831, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 831, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 833, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 833, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 835, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 835, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 837, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 837, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 839, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 839, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 841, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 841, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 843, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 843, "usage_type": "attribute"}, {"api_name": "constants.WALK", "line_number": 847, "usage_type": "attribute"}, {"api_name": "constants.BIG_TO_SMALL", "line_number": 855, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 869, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 869, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 870, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 870, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 874, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 874, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 878, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 878, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 882, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 882, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 886, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 886, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 890, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 890, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 894, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 894, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 898, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 898, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 902, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 902, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 906, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 906, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 910, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 910, "usage_type": "attribute"}, {"api_name": "constants.WALK", "line_number": 914, "usage_type": "attribute"}, {"api_name": "constants.FLAGPOLE", "line_number": 942, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 954, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 954, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 956, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 956, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 958, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 958, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 960, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 960, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 961, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 961, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 968, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 968, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 976, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 976, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 978, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 978, "usage_type": "attribute"}, {"api_name": "constants.END_OF_LEVEL_FALL", "line_number": 983, "usage_type": "attribute"}, {"api_name": "constants.WALKING_TO_CASTLE", "line_number": 985, "usage_type": "attribute"}, {"api_name": "constants.BOTTOM_OF_POLE", "line_number": 996, "usage_type": "attribute"}, {"api_name": "constants.WALK_ACCEL", "line_number": 1001, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 1006, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 1006, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 1007, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 1007, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 1009, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 1009, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 1015, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 1015, "usage_type": "attribute"}, {"api_name": "constants.GRAVITY", "line_number": 1019, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 1030, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 1030, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 1033, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 1033, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 1048, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 1048, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 1062, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 1062, "usage_type": "attribute"}, {"api_name": "constants.BIG_TO_SMALL", "line_number": 1071, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 1073, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 1073, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 1074, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 1074, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 1087, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 1087, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 1088, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 1088, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 1090, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 1090, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 1092, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 1092, "usage_type": "attribute"}, {"api_name": "constants.DEATH_JUMP", "line_number": 1109, "usage_type": "attribute"}, {"api_name": "constants.SMALL_TO_BIG", "line_number": 1110, "usage_type": "attribute"}, {"api_name": "constants.BIG_TO_FIRE", "line_number": 1111, "usage_type": "attribute"}, {"api_name": "constants.BIG_TO_SMALL", "line_number": 1112, "usage_type": "attribute"}, {"api_name": "constants.FLAGPOLE", "line_number": 1113, "usage_type": "attribute"}, {"api_name": "constants.BOTTOM_OF_POLE", "line_number": 1114, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollideany", "line_number": 1170, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 1170, "usage_type": "attribute"}, {"api_name": "constants.BIG_TO_SMALL", "line_number": 1183, "usage_type": "attribute"}, {"api_name": "item.Item.ONE_UP", "line_number": 1188, "usage_type": "attribute"}, {"api_name": "item.Item", "line_number": 1188, "usage_type": "name"}, {"api_name": "item.Item.STARMAN", "line_number": 1189, "usage_type": "attribute"}, {"api_name": "item.Item", "line_number": 1189, "usage_type": "name"}, {"api_name": "pygame.mixer.music.load", "line_number": 1191, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 1191, "usage_type": "attribute"}, {"api_name": "pygame.mixer.music.play", "line_number": 1192, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 1192, "usage_type": "attribute"}, {"api_name": "pygame.time.get_ticks", "line_number": 1193, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 1193, "usage_type": "attribute"}, {"api_name": "item.Item.MUSHROOM", "line_number": 1194, "usage_type": "attribute"}, {"api_name": "item.Item", "line_number": 1194, "usage_type": "name"}, {"api_name": "constants.SMALL_TO_BIG", "line_number": 1197, "usage_type": "attribute"}, {"api_name": "item.Item.FIRE_FLOWER", "line_number": 1199, "usage_type": "attribute"}, {"api_name": "item.Item", "line_number": 1199, "usage_type": "name"}, {"api_name": "constants.BIG_TO_FIRE", "line_number": 1202, "usage_type": "attribute"}, {"api_name": "constants.SMALL_TO_BIG", "line_number": 1205, "usage_type": "attribute"}, {"api_name": "pygame.sprite.spritecollideany", "line_number": 1239, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 1239, "usage_type": "attribute"}, {"api_name": "constants.END_OF_LEVEL_FALL", "line_number": 1257, "usage_type": "attribute"}, {"api_name": "constants.WALKING_TO_CASTLE", "line_number": 1258, "usage_type": "attribute"}, {"api_name": "constants.WALK", "line_number": 1260, "usage_type": "attribute"}, {"api_name": "constants.FALL", "line_number": 1264, "usage_type": "attribute"}, {"api_name": "constants.JUMP", "line_number": 1270, "usage_type": "attribute"}]} +{"seq_id": "33910761758", "text": "\"\"\"\nWiP.\n\nSoon.\n\"\"\"\n\n# region [Imports]\n\n# * Standard Library Imports ---------------------------------------------------------------------------->\nimport os\nfrom typing import TYPE_CHECKING, Mapping\nfrom pathlib import Path\nfrom datetime import datetime\n\n# * Third Party Imports --------------------------------------------------------------------------------->\nfrom frozendict import frozendict\nfrom playhouse.sqlite_ext import SqliteExtDatabase\n\n# * Type-Checking Imports --------------------------------------------------------------------------------->\nif TYPE_CHECKING:\n from gidapptools.custom_types import PATH_TYPE\n\n# endregion[Imports]\n\n# region [TODO]\n\n\n# endregion [TODO]\n\n# region [Logging]\n\n\n# endregion[Logging]\n\n# region [Constants]\n\nTHIS_FILE_DIR = Path(__file__).parent.absolute()\nAPSW_AVAILABLE = os.getenv(\"_APSW_AVAILABLE\", \"0\") == \"1\"\n\n\n# endregion[Constants]\n\nSTD_DEFAULT_PRAGMAS = frozendict({\n \"cache_size\": -1 * 128000,\n \"journal_mode\": 'wal',\n \"synchronous\": 0,\n \"ignore_check_constraints\": 0,\n \"foreign_keys\": 1,\n \"temp_store\": \"MEMORY\",\n \"mmap_size\": 268435456 * 8,\n \"journal_size_limit\": 209_715_200,\n \"wal_autocheckpoint\": 1000,\n \"page_size\": 32768 * 2,\n \"analysis_limit\": 100_000\n})\n\nSTD_DEFAULT_EXTENSIONS = frozendict({\"c_extensions\": True,\n \"rank_functions\": True,\n \"hash_functions\": True,\n \"json_contains\": True,\n \"bloomfilter\": True,\n \"regexp_function\": True})\n\n\nclass GidSqliteDatabase(SqliteExtDatabase):\n default_pragmas: Mapping[str, object] = frozendict(**STD_DEFAULT_PRAGMAS)\n default_extensions: Mapping[str, bool] = frozendict(**STD_DEFAULT_EXTENSIONS)\n default_backup_folder_name: str = \"backup\"\n\n def __init__(self,\n database_path: \"PATH_TYPE\",\n backup_folder: \"PATH_TYPE\" = None,\n thread_safe: bool = True,\n autoconnect: bool = True,\n autorollback: bool = None,\n timeout: int = 100,\n pragmas: Mapping = None,\n extensions: Mapping = None):\n\n self._db_path = Path(database_path).resolve()\n self._backup_folder = Path(backup_folder).resolve() if backup_folder is not None else None\n pragmas = pragmas or {}\n extensions = extensions or {}\n\n super().__init__(database=self.db_string_path,\n autoconnect=autoconnect,\n autorollback=autorollback,\n thread_safe=thread_safe,\n timeout=timeout,\n pragmas=dict(self.default_pragmas | pragmas),\n **dict(self.default_extensions | extensions))\n\n @property\n def db_path(self) -> Path:\n return self._db_path\n\n @property\n def backup_folder(self) -> Path:\n if self._backup_folder is not None:\n backup_folder = self._backup_folder\n else:\n backup_folder = self._get_default_backup_folder()\n backup_folder.mkdir(exist_ok=True, parents=True)\n return backup_folder\n\n @property\n def db_string_path(self) -> str:\n return os.fspath(self._db_path)\n\n def _get_default_backup_folder(self) -> Path:\n return self.db_path.parent.joinpath(self.default_backup_folder_name).resolve()\n\n def _get_backup_name(self) -> str:\n suffix = self.db_path.suffix\n stem = datetime.now().strftime(\"%Y-%m-%dT%H-%M-%S\") + '_' + self.db_path.stem + \"_backup\"\n return stem + suffix\n\n def set_backup_folder(self, backup_folder: \"PATH_TYPE\") -> None:\n\n if backup_folder is None:\n self._backup_folder = backup_folder\n else:\n backup_folder = Path(backup_folder).resolve()\n if backup_folder.suffix != \"\":\n raise NotADirectoryError(f\"backup_folder {os.fspath(backup_folder)!r} is not a directory\")\n self._backup_folder = backup_folder\n\n\nif APSW_AVAILABLE is True:\n pass\n\n# region[Main_Exec]\n\n\nif __name__ == '__main__':\n x = GidSqliteDatabase(THIS_FILE_DIR.joinpath(\"blah.db\"))\n print(x._get_backup_name())\n# endregion[Main_Exec]\n", "repo_name": "Giddius/GidAppTools", "sub_path": "gidapptools/gid_database/sqlite_database.py", "file_name": "sqlite_database.py", "file_ext": "py", "file_size_in_byte": 4301, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "25", "api": [{"api_name": "typing.TYPE_CHECKING", "line_number": 20, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 37, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 38, "usage_type": "call"}, {"api_name": "frozendict.frozendict", "line_number": 43, "usage_type": "call"}, {"api_name": "frozendict.frozendict", "line_number": 57, "usage_type": "call"}, {"api_name": "playhouse.sqlite_ext.SqliteExtDatabase", "line_number": 65, "usage_type": "name"}, {"api_name": "typing.Mapping", "line_number": 66, "usage_type": "name"}, {"api_name": "frozendict.frozendict", "line_number": 66, "usage_type": "call"}, {"api_name": "typing.Mapping", "line_number": 67, "usage_type": "name"}, {"api_name": "frozendict.frozendict", "line_number": 67, "usage_type": "call"}, {"api_name": "typing.Mapping", "line_number": 77, "usage_type": "name"}, {"api_name": "typing.Mapping", "line_number": 78, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 80, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 81, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 94, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 98, "usage_type": "name"}, {"api_name": "os.fspath", "line_number": 108, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 110, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 115, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 115, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 123, "usage_type": "call"}, {"api_name": "os.fspath", "line_number": 125, "usage_type": "call"}]} +{"seq_id": "21877057449", "text": "# coding: utf-8\n\nimport six\n\nfrom huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization\n\n\nclass CreatePrivateZoneReq:\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n sensitive_list = []\n\n openapi_types = {\n 'name': 'str',\n 'description': 'str',\n 'zone_type': 'str',\n 'email': 'str',\n 'ttl': 'int',\n 'router': 'Router',\n 'proxy_pattern': 'str',\n 'tags': 'list[Tag]',\n 'enterprise_project_id': 'str'\n }\n\n attribute_map = {\n 'name': 'name',\n 'description': 'description',\n 'zone_type': 'zone_type',\n 'email': 'email',\n 'ttl': 'ttl',\n 'router': 'router',\n 'proxy_pattern': 'proxy_pattern',\n 'tags': 'tags',\n 'enterprise_project_id': 'enterprise_project_id'\n }\n\n def __init__(self, name=None, description=None, zone_type=None, email=None, ttl=None, router=None, proxy_pattern=None, tags=None, enterprise_project_id=None):\n \"\"\"CreatePrivateZoneReq\n\n The model defined in huaweicloud sdk\n\n :param name: 待创建的域名。\n :type name: str\n :param description: 域名的描述信息。\n :type description: str\n :param zone_type: 域名类型。取值:private。\n :type zone_type: str\n :param email: 管理该zone的管理员邮箱。\n :type email: str\n :param ttl: 用于填写默认生成的SOA记录中有效缓存时间,以秒为单位。\n :type ttl: int\n :param router: \n :type router: :class:`huaweicloudsdkdns.v2.Router`\n :param proxy_pattern: 内网Zone的子域名递归解析代理模式。 取值范围: AUTHORITY:当前Zone不进行递归解析 RECURSIVE:开启递归解析代理\n :type proxy_pattern: str\n :param tags: 资源标签。\n :type tags: list[:class:`huaweicloudsdkdns.v2.Tag`]\n :param enterprise_project_id: 域名关联的企业项目ID,长度不超过36个字符。 默认值为0。\n :type enterprise_project_id: str\n \"\"\"\n \n \n\n self._name = None\n self._description = None\n self._zone_type = None\n self._email = None\n self._ttl = None\n self._router = None\n self._proxy_pattern = None\n self._tags = None\n self._enterprise_project_id = None\n self.discriminator = None\n\n self.name = name\n if description is not None:\n self.description = description\n self.zone_type = zone_type\n if email is not None:\n self.email = email\n if ttl is not None:\n self.ttl = ttl\n self.router = router\n if proxy_pattern is not None:\n self.proxy_pattern = proxy_pattern\n if tags is not None:\n self.tags = tags\n if enterprise_project_id is not None:\n self.enterprise_project_id = enterprise_project_id\n\n @property\n def name(self):\n \"\"\"Gets the name of this CreatePrivateZoneReq.\n\n 待创建的域名。\n\n :return: The name of this CreatePrivateZoneReq.\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this CreatePrivateZoneReq.\n\n 待创建的域名。\n\n :param name: The name of this CreatePrivateZoneReq.\n :type name: str\n \"\"\"\n self._name = name\n\n @property\n def description(self):\n \"\"\"Gets the description of this CreatePrivateZoneReq.\n\n 域名的描述信息。\n\n :return: The description of this CreatePrivateZoneReq.\n :rtype: str\n \"\"\"\n return self._description\n\n @description.setter\n def description(self, description):\n \"\"\"Sets the description of this CreatePrivateZoneReq.\n\n 域名的描述信息。\n\n :param description: The description of this CreatePrivateZoneReq.\n :type description: str\n \"\"\"\n self._description = description\n\n @property\n def zone_type(self):\n \"\"\"Gets the zone_type of this CreatePrivateZoneReq.\n\n 域名类型。取值:private。\n\n :return: The zone_type of this CreatePrivateZoneReq.\n :rtype: str\n \"\"\"\n return self._zone_type\n\n @zone_type.setter\n def zone_type(self, zone_type):\n \"\"\"Sets the zone_type of this CreatePrivateZoneReq.\n\n 域名类型。取值:private。\n\n :param zone_type: The zone_type of this CreatePrivateZoneReq.\n :type zone_type: str\n \"\"\"\n self._zone_type = zone_type\n\n @property\n def email(self):\n \"\"\"Gets the email of this CreatePrivateZoneReq.\n\n 管理该zone的管理员邮箱。\n\n :return: The email of this CreatePrivateZoneReq.\n :rtype: str\n \"\"\"\n return self._email\n\n @email.setter\n def email(self, email):\n \"\"\"Sets the email of this CreatePrivateZoneReq.\n\n 管理该zone的管理员邮箱。\n\n :param email: The email of this CreatePrivateZoneReq.\n :type email: str\n \"\"\"\n self._email = email\n\n @property\n def ttl(self):\n \"\"\"Gets the ttl of this CreatePrivateZoneReq.\n\n 用于填写默认生成的SOA记录中有效缓存时间,以秒为单位。\n\n :return: The ttl of this CreatePrivateZoneReq.\n :rtype: int\n \"\"\"\n return self._ttl\n\n @ttl.setter\n def ttl(self, ttl):\n \"\"\"Sets the ttl of this CreatePrivateZoneReq.\n\n 用于填写默认生成的SOA记录中有效缓存时间,以秒为单位。\n\n :param ttl: The ttl of this CreatePrivateZoneReq.\n :type ttl: int\n \"\"\"\n self._ttl = ttl\n\n @property\n def router(self):\n \"\"\"Gets the router of this CreatePrivateZoneReq.\n\n :return: The router of this CreatePrivateZoneReq.\n :rtype: :class:`huaweicloudsdkdns.v2.Router`\n \"\"\"\n return self._router\n\n @router.setter\n def router(self, router):\n \"\"\"Sets the router of this CreatePrivateZoneReq.\n\n :param router: The router of this CreatePrivateZoneReq.\n :type router: :class:`huaweicloudsdkdns.v2.Router`\n \"\"\"\n self._router = router\n\n @property\n def proxy_pattern(self):\n \"\"\"Gets the proxy_pattern of this CreatePrivateZoneReq.\n\n 内网Zone的子域名递归解析代理模式。 取值范围: AUTHORITY:当前Zone不进行递归解析 RECURSIVE:开启递归解析代理\n\n :return: The proxy_pattern of this CreatePrivateZoneReq.\n :rtype: str\n \"\"\"\n return self._proxy_pattern\n\n @proxy_pattern.setter\n def proxy_pattern(self, proxy_pattern):\n \"\"\"Sets the proxy_pattern of this CreatePrivateZoneReq.\n\n 内网Zone的子域名递归解析代理模式。 取值范围: AUTHORITY:当前Zone不进行递归解析 RECURSIVE:开启递归解析代理\n\n :param proxy_pattern: The proxy_pattern of this CreatePrivateZoneReq.\n :type proxy_pattern: str\n \"\"\"\n self._proxy_pattern = proxy_pattern\n\n @property\n def tags(self):\n \"\"\"Gets the tags of this CreatePrivateZoneReq.\n\n 资源标签。\n\n :return: The tags of this CreatePrivateZoneReq.\n :rtype: list[:class:`huaweicloudsdkdns.v2.Tag`]\n \"\"\"\n return self._tags\n\n @tags.setter\n def tags(self, tags):\n \"\"\"Sets the tags of this CreatePrivateZoneReq.\n\n 资源标签。\n\n :param tags: The tags of this CreatePrivateZoneReq.\n :type tags: list[:class:`huaweicloudsdkdns.v2.Tag`]\n \"\"\"\n self._tags = tags\n\n @property\n def enterprise_project_id(self):\n \"\"\"Gets the enterprise_project_id of this CreatePrivateZoneReq.\n\n 域名关联的企业项目ID,长度不超过36个字符。 默认值为0。\n\n :return: The enterprise_project_id of this CreatePrivateZoneReq.\n :rtype: str\n \"\"\"\n return self._enterprise_project_id\n\n @enterprise_project_id.setter\n def enterprise_project_id(self, enterprise_project_id):\n \"\"\"Sets the enterprise_project_id of this CreatePrivateZoneReq.\n\n 域名关联的企业项目ID,长度不超过36个字符。 默认值为0。\n\n :param enterprise_project_id: The enterprise_project_id of this CreatePrivateZoneReq.\n :type enterprise_project_id: str\n \"\"\"\n self._enterprise_project_id = enterprise_project_id\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n if attr in self.sensitive_list:\n result[attr] = \"****\"\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n import simplejson as json\n if six.PY2:\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)\n\n def __repr__(self):\n \"\"\"For `print`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, CreatePrivateZoneReq):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n", "repo_name": "huaweicloud/huaweicloud-sdk-python-v3", "sub_path": "huaweicloud-sdk-dns/huaweicloudsdkdns/v2/model/create_private_zone_req.py", "file_name": "create_private_zone_req.py", "file_ext": "py", "file_size_in_byte": 10342, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 104, "dataset": "github-code", "pt": "20", "api": [{"api_name": "six.iteritems", "line_number": 295, "usage_type": "call"}, {"api_name": "six.PY2", "line_number": 321, "usage_type": "attribute"}, {"api_name": "sys.setdefaultencoding", "line_number": 324, "usage_type": "call"}, {"api_name": "simplejson.dumps", "line_number": 325, "usage_type": "call"}, {"api_name": "huaweicloudsdkcore.utils.http_utils.sanitize_for_serialization", "line_number": 325, "usage_type": "call"}]} +{"seq_id": "38604362548", "text": "import cv2\nimport numpy as np\nimport os\nfrom matplotlib import pyplot as plt\nimport time\nimport mediapipe as mp\nimport threading\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv1D, MaxPooling1D, GRU, Dense, Dropout, BatchNormalization, Flatten\nfrom tensorflow.keras.regularizers import L2\nfrom tensorflow.keras.callbacks import TensorBoard\nfrom keras import regularizers\n\n\nmp_holistic = mp.solutions.holistic # Holistic model\nmp_drawing = mp.solutions.drawing_utils # Drawing utilities\n\n\nactions = np.array(['Angry','Happy','Sad'])\nlabel_map = {label:num for num, label in enumerate(actions)}\nlog_dir = os.path.join('Logs')\ntb_callback = TensorBoard(log_dir=log_dir)\n\ninput_shape = (30, 1662)\n\nmodel = Sequential()\n\n# CNN layers\nmodel.add(Conv1D(64, kernel_size=3, activation='relu', input_shape=input_shape))\nmodel.add(MaxPooling1D(pool_size=2))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\n\nmodel.add(Conv1D(128, kernel_size=3, activation='relu'))\nmodel.add(MaxPooling1D(pool_size=2))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\n\nmodel.add(Conv1D(256, kernel_size=3, activation='relu'))\nmodel.add(MaxPooling1D(pool_size=2))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\n\n# GRU layers\nmodel.add(GRU(256, return_sequences=True))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\n\nmodel.add(GRU(128, return_sequences=False))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(64, activation='relu', activity_regularizer=L2(0.01)))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(32, activation='relu', activity_regularizer=L2(0.01)))\n\nmodel.add(Dense(actions.shape[0], activation='softmax'))\n\nmodel.compile(optimizer='Adam', loss='categorical_crossentropy', metrics=['categorical_accuracy'])\n\nmodel.load_weights('/Users/kevynkrancenblum/Desktop/Data Science/Final Project/Body_Language_recognition/modelsSaved/BodyModelv5.h5')\n\ndef mediapipe_detection(image, model):\n if image.size == 0:\n raise ValueError(\"Input image is empty\")\n try:\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # COLOR CONVERSION BGR 2 RGB\n image.flags.writeable = False # Image is no longer writeable\n results = model.process(image) # Make prediction\n return image, results\n except:\n raise RuntimeError(\"Failed to make a prediction with mediapipe model\")\n \ndef draw_styled_landmarks(image, results):\n # Draw face connections\n mp_drawing.draw_landmarks(image, results.face_landmarks, mp_holistic.FACEMESH_CONTOURS, \n mp_drawing.DrawingSpec(color=(80,110,10), thickness=1, circle_radius=1), \n mp_drawing.DrawingSpec(color=(80,256,121), thickness=1, circle_radius=1)\n ) \n # Draw pose connections\n mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS,\n mp_drawing.DrawingSpec(color=(80,22,10), thickness=2, circle_radius=4), \n mp_drawing.DrawingSpec(color=(80,44,121), thickness=2, circle_radius=2)\n ) \n # Draw left hand connections\n mp_drawing.draw_landmarks(image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS, \n mp_drawing.DrawingSpec(color=(121,22,76), thickness=2, circle_radius=4), \n mp_drawing.DrawingSpec(color=(121,44,250), thickness=2, circle_radius=2)\n ) \n # Draw right hand connections \n mp_drawing.draw_landmarks(image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS, \n mp_drawing.DrawingSpec(color=(245,117,66), thickness=2, circle_radius=4), \n mp_drawing.DrawingSpec(color=(245,66,230), thickness=2, circle_radius=2)\n ) \n \ndef extract_keypoints(results):\n pose = np.array([[res.x, res.y, res.z, res.visibility] for res in results.pose_landmarks.landmark]).flatten() if results.pose_landmarks else np.zeros(33*4)\n face = np.array([[res.x, res.y, res.z] for res in results.face_landmarks.landmark]).flatten() if results.face_landmarks else np.zeros(468*3)\n lh = np.array([[res.x, res.y, res.z] for res in results.left_hand_landmarks.landmark]).flatten() if results.left_hand_landmarks else np.zeros(21*3)\n rh = np.array([[res.x, res.y, res.z] for res in results.right_hand_landmarks.landmark]).flatten() if results.right_hand_landmarks else np.zeros(21*3)\n return np.concatenate([pose,face, lh, rh])\n \ncolors = [(245,117,16), (117,245,16), (16,117,245)]\n\n\nimport cv2\n\ndef prob_viz(res, actions, input_frame, colors):\n output_frame = input_frame.copy()\n for num, prob in enumerate(res):\n y_start = 120 + num * 40 # Adjusted Y-coordinate for rectangle start\n y_end = 150 + num * 40 # Adjusted Y-coordinate for rectangle end\n text_y = 135 + num * 40 # Adjusted Y-coordinate for text\n \n cv2.rectangle(output_frame, (0, y_start), (int(prob*100), y_end), colors[num], -1)\n cv2.putText(output_frame, actions[num], (0, text_y), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)\n \n return output_frame\n\n\n\n\ndef InferenceVideo(results,test,image):\n keypoints = extract_keypoints(results)\n sequence.append(keypoints)\n print(sequence)\n sequence = sequence[-50:]\n if len(sequence) == 50:\n res = model.predict(np.expand_dims(sequence, axis=0))[0]\n prediction=actions[np.argmax(res)]\n print(actions[np.argmax(res)]) \n #3. Viz logic\n if res[np.argmax(res)] > 0.6: \n if len(sentence) > 0: \n if actions[np.argmax(res)] != sentence[-1]:\n sentence.append(actions[np.argmax(res)])\n if len(sentence )> 15:\n test.append(sentence)\n\n else:\n sentence.append(actions[np.argmax(res)])\n\n if len(sentence) > 5: \n sentence = sentence[-5:]\n\n # Viz probabilities\n image = prob_viz(res, actions, image, colors)\n return results,test,image", "repo_name": "KevynKrancen/Sound-it", "sub_path": "Soundit-Models/Final Project/UISoundIT/keypointsdetection.py", "file_name": "keypointsdetection.py", "file_ext": "py", "file_size_in_byte": 6193, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "20", "api": [{"api_name": "mediapipe.solutions", "line_number": 15, "usage_type": "attribute"}, {"api_name": "mediapipe.solutions", "line_number": 16, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.callbacks.TensorBoard", "line_number": 22, "usage_type": "call"}, {"api_name": "tensorflow.keras.models.Sequential", "line_number": 26, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Conv1D", "line_number": 29, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.MaxPooling1D", "line_number": 30, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.BatchNormalization", "line_number": 31, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dropout", "line_number": 32, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Conv1D", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.MaxPooling1D", "line_number": 35, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.BatchNormalization", "line_number": 36, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dropout", "line_number": 37, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Conv1D", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.MaxPooling1D", "line_number": 40, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.BatchNormalization", "line_number": 41, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dropout", "line_number": 42, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.GRU", "line_number": 45, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.BatchNormalization", "line_number": 46, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dropout", "line_number": 47, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.GRU", "line_number": 49, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.BatchNormalization", "line_number": 50, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dropout", "line_number": 51, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.keras.regularizers.L2", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dropout", "line_number": 54, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 55, "usage_type": "call"}, {"api_name": "tensorflow.keras.regularizers.L2", "line_number": 55, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 57, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 67, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 67, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 101, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 115, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 116, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 116, "usage_type": "attribute"}, {"api_name": "cv2.LINE_AA", "line_number": 116, "usage_type": "attribute"}, {"api_name": "numpy.expand_dims", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 131, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 133, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 141, "usage_type": "call"}]} +{"seq_id": "21207492416", "text": "import numpy as np\nimport mdtraj as md\nfrom sklearn import preprocessing\n\n\n\ndef read_traj(file_nc,file_top):\n \n traj = md.load(file_nc,top=file_top)[:100]\n \n return traj\n\n\ndef dis_bias(traj1, traj2):\n \n traj_after = md.Trajectory.superpose(traj1+traj2, traj1+traj2, frame=0)\n traj_after1 = traj_after[:len(traj1)]\n traj_after2 = traj_after[len(traj1):]\n \n return traj_after1, traj_after2\n\n\n\ntrs = [[2.0413690, -0.5649464, -0.3446944], \n [-0.9692660, 1.8760108, 0.0415560],\n [0.0134474, -0.1183897, 1.0154096]]\n\n# trs = [[2.493478, -0.931556, -0.402658], \n# [-0.829621, -0.829621, 0.023600],\n# [0.035842, -0.076161, 0.956927]]\n\ndef xyz_to_rgb(xyz, trs=trs):\n\n # rgb = trs * xyz\n rgb = []\n for i in range(3):\n tmp = xyz[0] * trs[i][0] + xyz[1] * trs[i][1] + xyz[2] * trs[i][2]\n rgb.append(tmp)\n \n return rgb\n\n\ndef sca_xyz(xyz, min=0, max=255):\n\n x = np.array(xyz)\n\n min_max_scaler = preprocessing.MinMaxScaler(feature_range=(min,max))\n x_minmax = min_max_scaler.fit_transform(x)\n x_minmax2 = []\n for item in x_minmax:\n x_minmax2.append([int(item[0]),int(item[1]),int(item[2])])\n \n return x_minmax2\n\n\ndef flt_to_int(tup):\n for i in range(len(tup)):\n tup[i] = int(tup[i])*10\n \n return tup\n\n\ndef rgb_to_hex(rgb):\n string = ''\n digit = list(map(str, range(10))) + list(\"ABCDEF\")\n for i in rgb:\n a1 = i // 16\n a2 = i % 16\n string += digit[a1] + digit[a2]\n return string\n\n\ndef traj_to_hex(traj):\n\n traj = traj.xyz\n \n traj1 = []\n # xyz->rgb)\n for item in traj:\n item1 = []\n for atom in item:\n atom1 = xyz_to_rgb(atom)\n item1.append(atom1)\n traj1.append(item1)\n # print('traj ready')\n \n traj2 = []\n #(0,255)\n for item in traj1:\n item2 = sca_xyz(item, min=0, max=255)\n traj2.append(item2)\n # print(2)\n pixel_map = traj2\n \n traj_hex = []\n for item in traj2:\n tep = []\n for atom in item:\n atom1 = rgb_to_hex(tuple(atom))\n rgb_dec = int(atom1.upper(), 16)\n tep.append([rgb_dec])\n traj_hex.append(tep)\n \n \n return traj_hex, pixel_map\n\n\ndef load_traj(file0_1, file1_1, file0_2, file1_2):\n # =============================================================================\n # traj0\n file0_traj = read_traj(file0_1, file0_2)\n # traj1\n file1_traj = read_traj(file1_1, file1_2)\n\n print('Info of traj_anta:')\n print(file0_traj)\n print('Info of traj_actv:')\n print(file1_traj)\n print(\"Pixel-representation Start.\")\n # =============================================================================\n\n # =============================================================================\n file0_traj, file1_traj = dis_bias(file0_traj, file1_traj)\n # print(len(file0_traj.xyz),len(file0_traj.xyz[0]))\n # =============================================================================\n\n # ============================================================================\n import time\n start = time.time()\n\n traj0_hex, pixel_map0 = traj_to_hex(file0_traj)\n traj1_hex, pixel_map1 = traj_to_hex(file1_traj)\n\n end = time.time()\n print('time:', end-start,'s')\n # =============================================================================\n\n return traj0_hex, traj1_hex, pixel_map0, pixel_map1\n\n\ndef traj_to_pic(traj0_hex, traj1_hex, pixel0, pixel1):\n # size*size\n atom_n = len(traj0_hex[0])\n import math\n size = math.ceil(atom_n**0.5)\n traj0_pic = []\n for item in range(len(traj0_hex)):\n for ti in range(size*size-atom_n):\n traj0_hex[item].append([0])\n pic = []\n for i in range(size):\n line = []\n for j in range(size):\n line.append(traj0_hex[item][i*size+j])\n pic.append(line)\n traj0_pic.append(pic)\n \n traj1_pic = []\n for item in range(len(traj1_hex)):\n for ti in range(size*size-atom_n):\n traj1_hex[item].append([0])\n pic = []\n for i in range(size):\n line = []\n for j in range(size):\n line.append(traj1_hex[item][i*size+j])\n pic.append(line)\n traj1_pic.append(pic)\n \n pixel_map0 = []\n for item in range(len(pixel0)):\n for ti in range(size*size-atom_n):\n pixel0[item].append([0,0,0])\n pic = []\n for i in range(size):\n line = []\n for j in range(size):\n line.append(pixel0[item][i*size+j])\n pic.append(line)\n pixel_map0.append(pic)\n \n pixel_map1 = []\n for item in range(len(pixel1)):\n for ti in range(size*size-atom_n):\n pixel1[item].append([0,0,0])\n pic = []\n for i in range(size):\n line = []\n for j in range(size):\n line.append(pixel1[item][i*size+j])\n pic.append(line)\n pixel_map1.append(pic)\n \n \n return traj0_pic, traj1_pic, pixel_map0, pixel_map1\n\n\ndef data_split(traj0_pic, traj1_pic, pixel_map0, pixel_map1):\n from sklearn.model_selection import train_test_split\n X_all = []\n y_all = []\n pixel_map_all = []\n for i in range(len(traj0_pic)):\n X_all.append(traj0_pic[i])\n pixel_map_all.append(pixel_map0[i])\n y_all.append(0)\n for i in range(len(traj1_pic)):\n X_all.append(traj1_pic[i])\n pixel_map_all.append(pixel_map1[i])\n y_all.append(1)\n\n# X_train, X_test, y_train, y_test = train_test_split(X_all, y_all, test_size=0.8)\n\n# print('set1:', len(X_train), ', set2:', len(X_test))\n# print('ok')\n \n# return X_train, y_train, X_test, y_test\n return X_all, y_all, pixel_map_all\n\ndef data_split_dnn(traj0_pic, traj1_pic):\n from sklearn.model_selection import train_test_split\n\n # traj0-0, traj1-1\n X_all = []\n y_all = []\n for i in range(len(traj0_pic)):\n X_all.append(traj0_pic[i])\n y_all.append(0)\n for i in range(len(traj1_pic)):\n X_all.append(traj1_pic[i])\n y_all.append(1)\n\n# X_train, X_test, y_train, y_test = train_test_split(X_all, y_all, test_size=0.8)\n\n# print('set1:', len(X_train), ', set2:', len(X_test))\n# print('ok')\n \n# return X_train, y_train, X_test, y_test\n return X_all, y_all, pixel_map_all\n\n\ndef traj_pre(file0_1, file1_1, file0_2, file1_2):\n import numpy as np\n\n traj0_hex, traj1_hex, pixel0, pixel1 = load_traj(file0_1, file1_1, file0_2, file1_2)\n traj0_pic, traj1_pic, pixel_map0, pixel_map1 = traj_to_pic(traj0_hex, traj1_hex, pixel0, pixel1)\n# X_train, y_train, X_test, y_test = data_split(traj0_pic, traj1_pic)\n X_all, y_all, pixel_map_all = data_split(traj0_pic, traj1_pic, pixel_map0, pixel_map1)\n# X_train = np.array(X_train)\n# y_train = np.array(y_train)\n# X_test = np.array(X_test)\n# y_test = np.array(y_test)\n X_all = np.array(X_all)\n y_all = np.array(y_all)\n# return X_train, y_train, X_test, y_test\n return X_all, y_all, np.array(pixel_map_all)\n", "repo_name": "Jane-Liu97/ICNNMD", "sub_path": "Codes/traj_utils.py", "file_name": "traj_utils.py", "file_ext": "py", "file_size_in_byte": 7158, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "20", "api": [{"api_name": "mdtraj.load", "line_number": 9, "usage_type": "call"}, {"api_name": "mdtraj.Trajectory.superpose", "line_number": 16, "usage_type": "call"}, {"api_name": "mdtraj.Trajectory", "line_number": 16, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 45, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.MinMaxScaler", "line_number": 47, "usage_type": "call"}, {"api_name": "sklearn.preprocessing", "line_number": 47, "usage_type": "name"}, {"api_name": "time.time", "line_number": 129, "usage_type": "call"}, {"api_name": "time.time", "line_number": 134, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 253, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 254, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 256, "usage_type": "call"}]} +{"seq_id": "43390658192", "text": "import tkinter\nimport sqlite3\nfrom tkinter import messagebox\nfrom PIL import Image, ImageTk\n\ndef appointment_family_ui():\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font9 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global appointment_family_page\n\n appointment_family_page = tkinter.Tk()\n appointment_family_page.title('Family Appointments Page')\n appointment_family_page.attributes('-fullscreen', True)\n appointment_family_page.configure(background=\"#2d3436\")\n\n back_button = tkinter.Button(appointment_family_page, command=appointment_family_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n appointment_family_listbox = tkinter.Listbox(appointment_family_page)\n appointment_family_listbox.place(relx=0.050, rely=0.205, relheight=0.552, relwidth=0.9)\n appointment_family_listbox.configure(cursor=\"spider\")\n appointment_family_listbox.configure(font=font9)\n appointment_family_listbox.configure(justify='center')\n appointment_family_listbox.configure(relief=\"flat\")\n appointment_family_listbox.configure(selectbackground=\"#dfe6e9\")\n appointment_family_listbox.configure(setgrid=\"1\")\n\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n \n cursor.execute(f\"SELECT User.first_name, User.last_name, User.phone_number, Doctor.first_name, Doctor.last_name, Appointment.appointment_date FROM Appointment, User, Doctor WHERE User.phone_number = Appointment.phone_number AND Doctor.username = Appointment.username AND Doctor.medical_council_code = Appointment.medical_council_code AND Appointment.phone_number IN (SELECT phone_number_2 FROM USER_USER WHERE phone_number_1 = '{current_phone_number}')\")\n family_appointments = cursor.fetchall()\n\n for family_appointment in family_appointments:\n first_name_text = f'{family_appointment[0]}'\n last_name_text = f'{family_appointment[1]}'\n phone_number_text= f'{family_appointment[2]}'\n appointment_date_text = f'{family_appointment[5]}'\n doctor_firstname_text = f'{family_appointment[3]}'\n doctor_lastname_text = f'{family_appointment[4]}'\n \n for i in range(14):\n if i == len(appointment_date_text) - 1:\n appointment_date_text += ' '\n if i == len(doctor_firstname_text) - 1:\n doctor_firstname_text += ' '\n if i == len(doctor_lastname_text) - 1:\n doctor_lastname_text += ' '\n if i == len(phone_number_text) - 1:\n phone_number_text += ' '\n if i == len(first_name_text) - 1:\n first_name_text += ' '\n if i == len(last_name_text) - 1:\n last_name_text += ' '\n\n appointment_family_listbox.insert(tkinter.END, f'Appointment Date: {appointment_date_text}| Doctor First Name: {doctor_firstname_text}| Doctor Last Name: {doctor_lastname_text}| Patient Phone Number: {phone_number_text}| Patient First Name: {first_name_text}| Patient Last Name: {last_name_text}')\n\n\n connection.commit()\n connection.close()\n\n return\n\n\ndef my_appointments_by_others_ui():\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font9 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global appointment_by_others_page\n\n appointment_by_others_page = tkinter.Tk()\n appointment_by_others_page.title('Appointment by Others Page')\n appointment_by_others_page.attributes('-fullscreen', True)\n appointment_by_others_page.configure(background=\"#2d3436\")\n\n back_button = tkinter.Button(appointment_by_others_page, command=appointment_by_others_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n appointment_by_others_listbox = tkinter.Listbox(appointment_by_others_page)\n appointment_by_others_listbox.place(relx=0.050, rely=0.205, relheight=0.552, relwidth=0.9)\n appointment_by_others_listbox.configure(cursor=\"spider\")\n appointment_by_others_listbox.configure(font=font9)\n appointment_by_others_listbox.configure(justify='center')\n appointment_by_others_listbox.configure(relief=\"flat\")\n appointment_by_others_listbox.configure(selectbackground=\"#dfe6e9\")\n appointment_by_others_listbox.configure(setgrid=\"1\")\n\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n \n cursor.execute(f\"SELECT Appointment.getter_phone_number, Doctor.first_name, Doctor.last_name, Appointment.appointment_date FROM Appointment, User, Doctor WHERE User.phone_number = Appointment.phone_number AND Doctor.username = Appointment.username AND Doctor.medical_council_code = Appointment.medical_council_code AND Appointment.getter_phone_number IN (SELECT phone_number_1 FROM USER_USER) AND Appointment.getter_phone_number NOT IN ('{current_phone_number}') AND Appointment.phone_number IN ('{current_phone_number}')\")\n by_others_appointments = cursor.fetchall()\n\n if len(by_others_appointments) == 0:\n by_others_appointments = []\n\n for i in range(len(by_others_appointments)):\n\n appointment_date_text = f'{by_others_appointments[i][3]}'\n doctor_firstname_text = f'{by_others_appointments[i][1]}'\n doctor_lastname_text = f'{by_others_appointments[i][2]}'\n getter_phone_number_text = f'{by_others_appointments[i][0]}'\n \n getter_phone_number = by_others_appointments[i][0]\n cursor.execute(f\"SELECT first_name, last_name FROM User WHERE phone_number = '{getter_phone_number}';\")\n getter_data = cursor.fetchone()\n\n getter_firstname_text = f'{getter_data[0]}'\n getter_lastname_text = f'{getter_data[1]}'\n\n for i in range(15):\n if i == len(appointment_date_text) - 1:\n appointment_date_text += ' '\n if i == len(doctor_firstname_text) - 1:\n doctor_firstname_text += ' '\n if i == len(doctor_lastname_text) - 1:\n doctor_lastname_text += ' '\n if i == len(getter_phone_number_text) - 1:\n getter_phone_number_text += ' '\n if i == len(getter_firstname_text) - 1:\n getter_firstname_text += ' '\n if i == len(getter_lastname_text) - 1:\n getter_lastname_text += ' '\n\n appointment_by_others_listbox.insert(tkinter.END, f'Appointment Date: {appointment_date_text}| Doctor First Name: {doctor_firstname_text}| Doctor Last Name: {doctor_lastname_text}| Getter Phone Number: {getter_phone_number_text}| getter First Name: {getter_firstname_text}| getter Last Name: {getter_lastname_text}\\n')\n\n connection.commit()\n connection.close()\n \n return\n\n\ndef edit_profile_db(first_name, last_name, insurance_id, gender, image_path):\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n \n cursor.execute(f\"SELECT insurance_id FROM Insurance WHERE name = '{insurance_id}';\")\n insurance_id = cursor.fetchone()[0]\n\n cursor.execute(f\"SELECT gender_id FROM Gender WHERE title = '{gender}';\")\n gender_id = cursor.fetchone()\n if gender_id != None:\n gender_id = gender_id[0]\n else:\n gender_id = 0\n \n cursor.execute(f\"UPDATE User SET first_name = '{first_name}', last_name = '{last_name}', insurance_id = {insurance_id}, photo = '{image_path}', gender_id = {gender_id} WHERE phone_number = '{current_phone_number}';\")\n\n connection.commit()\n connection.close()\n\n edit_profile_page.destroy()\n \n return\n\n\ndef edit_profile_ui():\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font10 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n font9 = \"-family ubvazir -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT first_name, last_name, insurance_id, gender_id, birthday, photo FROM User WHERE phone_number = '{current_phone_number}';\")\n temp_user_data = cursor.fetchone()\n\n user_data = []\n for temp in temp_user_data:\n if temp != None:\n user_data.append(temp)\n else:\n user_data.append('')\n \n cursor.execute(f\"SELECT name FROM Insurance WHERE insurance_id = {user_data[2]};\")\n insurance_data = cursor.fetchone()\n\n \n if not (user_data[3] == None or len(str(user_data[3])) == 0):\n cursor.execute(f\"SELECT title FROM Gender WHERE gender_id = {user_data[3]};\")\n gender_data = cursor.fetchone()\n else:\n gender_data = None\n\n global edit_profile_page\n\n edit_profile_page = tkinter.Toplevel()\n edit_profile_page.title('Edit Profile Page')\n edit_profile_page.attributes('-fullscreen', True)\n edit_profile_page.configure(background=\"#2d3436\")\n\n if not (len(user_data[5]) == 0 or user_data[5] == None):\n image_path = str(user_data[5])\n profile_image = Image.open(image_path)\n profile_image = profile_image.resize((150, 150), Image.ANTIALIAS)\n profile_image = ImageTk.PhotoImage(image=profile_image)\n profile_label = tkinter.Label(edit_profile_page,image=profile_image)\n profile_label.image = profile_image\n profile_label.place(relx=0.4675, rely=0.125)\n\n back_button = tkinter.Button(edit_profile_page, command=edit_profile_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n Frame1 = tkinter.Frame(edit_profile_page)\n Frame1.place(relx=0.365, rely=0.325, relheight=0.500, relwidth=0.273)\n Frame1.configure(relief='flat')\n Frame1.configure(borderwidth=\"2\")\n Frame1.configure(background=\"#ffffff\")\n\n firstname_label = tkinter.Label(Frame1)\n firstname_label.place(relx=0.0, rely=0.03, height=54, width=98)\n firstname_label.configure(background=\"#ffffff\")\n firstname_label.configure(font=font9)\n firstname_label.configure(text='''First Name''')\n\n lastname_label = tkinter.Label(Frame1)\n lastname_label.place(relx=-0.019, rely=0.14, height=74, width=118)\n lastname_label.configure(activebackground=\"#f9f9f9\")\n lastname_label.configure(background=\"#ffffff\")\n lastname_label.configure(font=font9)\n lastname_label.configure(text='''Last Name''')\n\n insurance_label = tkinter.Label(Frame1)\n insurance_label.place(relx=0.0, rely=0.36, height=54, width=98)\n insurance_label.configure(activebackground=\"#f9f9f9\")\n insurance_label.configure(background=\"#ffffff\")\n insurance_label.configure(font=font9)\n insurance_label.configure(text='''Insurance''')\n\n phone_number_label = tkinter.Label(Frame1)\n phone_number_label.place(relx=0.0, rely=0.25, height=54, width=108)\n phone_number_label.configure(activebackground=\"#f9f9f9\")\n phone_number_label.configure(background=\"#ffffff\")\n phone_number_label.configure(font=font9)\n phone_number_label.configure(text='''Phone Number''')\n\n gender_label = tkinter.Label(Frame1)\n gender_label.place(relx=0.0, rely=0.47, height=54, width=108)\n gender_label.configure(activebackground=\"#f9f9f9\")\n gender_label.configure(background=\"#ffffff\")\n gender_label.configure(font=font9)\n gender_label.configure(text='''Gender''')\n\n birthday_label = tkinter.Label(Frame1)\n birthday_label.place(relx=0.0, rely=0.58, height=54, width=108)\n birthday_label.configure(activebackground=\"#f9f9f9\")\n birthday_label.configure(background=\"#ffffff\")\n birthday_label.configure(font=font9)\n birthday_label.configure(text='''Birthday''')\n\n image_label = tkinter.Label(Frame1)\n image_label.place(relx=0.0, rely=0.69, height=54, width=108)\n image_label.configure(activebackground=\"#f9f9f9\")\n image_label.configure(background=\"#ffffff\")\n image_label.configure(font=font9)\n image_label.configure(text='''Image Path''')\n\n firstname_entry = tkinter.Entry(Frame1)\n firstname_entry.place(relx=0.21, rely=0.03, height=53, relwidth=0.754)\n firstname_entry.configure(background=\"#dfe6e9\")\n firstname_entry.configure(font=font10)\n firstname_entry.configure(foreground=\"#ffffff\")\n firstname_entry.configure(justify='center')\n firstname_entry.configure(relief=\"flat\")\n firstname_entry.insert(0, user_data[0])\n\n lastname_entry = tkinter.Entry(Frame1)\n lastname_entry.place(relx=0.21, rely=0.14, height=53, relwidth=0.754)\n lastname_entry.configure(background=\"#dfe6e9\")\n lastname_entry.configure(cursor=\"fleur\")\n lastname_entry.configure(font=font10)\n lastname_entry.configure(foreground=\"#ffffff\")\n lastname_entry.configure(justify='center')\n lastname_entry.configure(relief=\"flat\")\n lastname_entry.configure(selectbackground=\"#c4c4c4\")\n lastname_entry.insert(0, user_data[1])\n\n phone_number_entry = tkinter.Entry(Frame1)\n phone_number_entry.place(relx=0.21, rely=0.25, height=53, relwidth=0.754)\n phone_number_entry.configure(background=\"#dfe6e9\")\n phone_number_entry.configure(font=font10)\n phone_number_entry.configure(justify='center')\n phone_number_entry.configure(relief=\"flat\")\n phone_number_entry.configure(selectbackground=\"#c4c4c4\")\n phone_number_entry.insert(0, current_phone_number)\n phone_number_entry.configure(state='readonly')\n phone_number_entry.configure(foreground=\"#ffffff\")\n\n insurance_entry = tkinter.Entry(Frame1)\n insurance_entry.place(relx=0.21, rely=0.36, height=53, relwidth=0.754)\n insurance_entry.configure(background=\"#dfe6e9\")\n insurance_entry.configure(font=font10)\n insurance_entry.configure(foreground=\"#ffffff\")\n insurance_entry.configure(justify='center')\n insurance_entry.configure(relief=\"flat\")\n insurance_entry.configure(selectbackground=\"#c4c4c4\")\n if insurance_data != None:\n insurance_entry.insert(0, insurance_data[0])\n\n gender_entry = tkinter.Entry(Frame1)\n gender_entry.place(relx=0.21, rely=0.47, height=53, relwidth=0.754)\n gender_entry.configure(background=\"#dfe6e9\")\n gender_entry.configure(font=font10)\n gender_entry.configure(foreground=\"#ffffff\")\n gender_entry.configure(justify='center')\n gender_entry.configure(relief=\"flat\")\n gender_entry.configure(selectbackground=\"#c4c4c4\")\n if gender_data != None:\n gender_entry.insert(0, gender_data[0])\n\n birthday_entry = tkinter.Entry(Frame1)\n birthday_entry.place(relx=0.21, rely=0.58, height=53, relwidth=0.754)\n birthday_entry.configure(background=\"#dfe6e9\")\n birthday_entry.configure(font=font10)\n birthday_entry.configure(foreground=\"#ffffff\")\n birthday_entry.configure(justify='center')\n birthday_entry.configure(relief=\"flat\")\n birthday_entry.configure(selectbackground=\"#c4c4c4\")\n if user_data[4] != None:\n birthday_entry.insert(0, user_data[4])\n\n image_entry = tkinter.Entry(Frame1)\n image_entry.place(relx=0.21, rely=0.69, height=53, relwidth=0.754)\n image_entry.configure(background=\"#dfe6e9\")\n image_entry.configure(font=font10)\n image_entry.configure(foreground=\"#ffffff\")\n image_entry.configure(justify='center')\n image_entry.configure(relief=\"flat\")\n image_entry.configure(selectbackground=\"#c4c4c4\")\n if user_data[5] != None:\n image_entry.insert(0, user_data[5]) \n\n connection.commit()\n connection.close()\n\n edit_profile_submit_button = tkinter.Button(Frame1, command=lambda: edit_profile_db(firstname_entry.get(), lastname_entry.get(), insurance_entry.get(), gender_entry.get(), image_entry.get()))\n edit_profile_submit_button.place(relx=0.038, rely=0.84, height=54, width=491)\n edit_profile_submit_button.configure(activebackground=\"#dfe6e9\")\n edit_profile_submit_button.configure(background=\"#2d3436\")\n edit_profile_submit_button.configure(font=font9)\n edit_profile_submit_button.configure(foreground=\"#ffffff\")\n edit_profile_submit_button.configure(relief=\"flat\")\n edit_profile_submit_button.configure(text='''Submit''')\n\n return\n\ndef add_family_db(first_name, last_name, phone_number, insurance_id, password, gender_id, birthday):\n\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT insurance_id FROM Insurance WHERE name = '{insurance_id}';\")\n insurance_id = cursor.fetchone()\n\n cursor.execute(f\"SELECT gender_id FROM Gender WHERE title = '{gender_id}';\")\n gender_id = cursor.fetchone()\n\n cursor.execute(f\"INSERT INTO User (phone_number, first_name, last_name, password, insurance_id, gender_id, birthday) VALUES('{phone_number}', '{first_name}', '{last_name}', '{password}', {insurance_id[0]}, {gender_id[0]}, '{birthday}');\")\n\n cursor.execute(f\"INSERT INTO User_User VALUES ('{current_phone_number}', '{phone_number}')\")\n\n connection.commit()\n connection.close()\n\n return\n\ndef add_family_inner_ui():\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font9 = \"-family ubvazir -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n font10 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global add_family_inner_page\n\n add_family_inner_page = tkinter.Tk()\n add_family_inner_page.title('Add Family Page')\n add_family_inner_page.attributes('-fullscreen', True)\n add_family_inner_page.configure(background=\"#2d3436\")\n\n back_button = tkinter.Button(add_family_inner_page, command=add_family_inner_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n Frame1 = tkinter.Frame(add_family_inner_page)\n Frame1.place(relx=0.365, rely=0.250, relheight=0.500, relwidth=0.273)\n Frame1.configure(relief='flat')\n Frame1.configure(borderwidth=\"2\")\n Frame1.configure(background=\"#ffffff\")\n\n firstname_inner_label = tkinter.Label(Frame1)\n firstname_inner_label.place(relx=0.0, rely=0.03, height=54, width=98)\n firstname_inner_label.configure(background=\"#ffffff\")\n firstname_inner_label.configure(font=font9)\n firstname_inner_label.configure(text='''First Name''')\n\n lastname_inner_label = tkinter.Label(Frame1)\n lastname_inner_label.place(relx=-0.019, rely=0.15, height=74, width=118)\n lastname_inner_label.configure(activebackground=\"#f9f9f9\")\n lastname_inner_label.configure(background=\"#ffffff\")\n lastname_inner_label.configure(font=font9)\n lastname_inner_label.configure(text='''Last Name''')\n\n insurance_inner_label = tkinter.Label(Frame1)\n insurance_inner_label.place(relx=0.0, rely=0.39, height=54, width=98)\n insurance_inner_label.configure(activebackground=\"#f9f9f9\")\n insurance_inner_label.configure(background=\"#ffffff\")\n insurance_inner_label.configure(font=font9)\n insurance_inner_label.configure(text='''Insurance''')\n\n phone_number_inner_label = tkinter.Label(Frame1)\n phone_number_inner_label.place(relx=0.0, rely=0.27, height=54, width=108)\n phone_number_inner_label.configure(activebackground=\"#f9f9f9\")\n phone_number_inner_label.configure(background=\"#ffffff\")\n phone_number_inner_label.configure(font=font9)\n phone_number_inner_label.configure(text='''Phone Number''')\n\n gender_inner_label = tkinter.Label(Frame1)\n gender_inner_label.place(relx=0.0, rely=0.51, height=54, width=108)\n gender_inner_label.configure(activebackground=\"#f9f9f9\")\n gender_inner_label.configure(background=\"#ffffff\")\n gender_inner_label.configure(font=font9)\n gender_inner_label.configure(text='''Gender''')\n\n birthday_inner_label = tkinter.Label(Frame1)\n birthday_inner_label.place(relx=0.0, rely=0.63, height=54, width=108)\n birthday_inner_label.configure(activebackground=\"#f9f9f9\")\n birthday_inner_label.configure(background=\"#ffffff\")\n birthday_inner_label.configure(font=font9)\n birthday_inner_label.configure(text='''Birthday''')\n\n password_inner_label = tkinter.Label(Frame1)\n password_inner_label.place(relx=0.0, rely=0.75, height=54, width=108)\n password_inner_label.configure(activebackground=\"#f9f9f9\")\n password_inner_label.configure(background=\"#ffffff\")\n password_inner_label.configure(font=font9)\n password_inner_label.configure(text='''Password''')\n\n firstname_inner_entry = tkinter.Entry(Frame1)\n firstname_inner_entry.place(relx=0.21, rely=0.03, height=53, relwidth=0.754)\n firstname_inner_entry.configure(background=\"#dfe6e9\")\n firstname_inner_entry.configure(font=font10)\n firstname_inner_entry.configure(foreground=\"#ffffff\")\n firstname_inner_entry.configure(justify='center')\n firstname_inner_entry.configure(relief=\"flat\")\n\n lastname_inner_entry = tkinter.Entry(Frame1)\n lastname_inner_entry.place(relx=0.21, rely=0.15, height=53, relwidth=0.754)\n lastname_inner_entry.configure(background=\"#dfe6e9\")\n lastname_inner_entry.configure(cursor=\"fleur\")\n lastname_inner_entry.configure(font=font10)\n lastname_inner_entry.configure(foreground=\"#ffffff\")\n lastname_inner_entry.configure(justify='center')\n lastname_inner_entry.configure(relief=\"flat\")\n lastname_inner_entry.configure(selectbackground=\"#c4c4c4\")\n\n\n phone_number_inner_entry = tkinter.Entry(Frame1)\n phone_number_inner_entry.place(relx=0.21, rely=0.27, height=53, relwidth=0.754)\n phone_number_inner_entry.configure(background=\"#dfe6e9\")\n phone_number_inner_entry.configure(font=font10)\n phone_number_inner_entry.configure(justify='center')\n phone_number_inner_entry.configure(relief=\"flat\")\n phone_number_inner_entry.configure(selectbackground=\"#c4c4c4\")\n phone_number_inner_entry.configure(foreground=\"#ffffff\")\n\n insurance_inner_entry = tkinter.Entry(Frame1)\n insurance_inner_entry.place(relx=0.21, rely=0.39, height=53, relwidth=0.754)\n insurance_inner_entry.configure(background=\"#dfe6e9\")\n insurance_inner_entry.configure(font=font10)\n insurance_inner_entry.configure(foreground=\"#ffffff\")\n insurance_inner_entry.configure(justify='center')\n insurance_inner_entry.configure(relief=\"flat\")\n insurance_inner_entry.configure(selectbackground=\"#c4c4c4\")\n\n\n gender_inner_entry = tkinter.Entry(Frame1)\n gender_inner_entry.place(relx=0.21, rely=0.51, height=53, relwidth=0.754)\n gender_inner_entry.configure(background=\"#dfe6e9\")\n gender_inner_entry.configure(font=font10)\n gender_inner_entry.configure(foreground=\"#ffffff\")\n gender_inner_entry.configure(justify='center')\n gender_inner_entry.configure(relief=\"flat\")\n gender_inner_entry.configure(selectbackground=\"#c4c4c4\")\n\n\n birthday_inner_entry = tkinter.Entry(Frame1)\n birthday_inner_entry.place(relx=0.21, rely=0.63, height=53, relwidth=0.754)\n birthday_inner_entry.configure(background=\"#dfe6e9\")\n birthday_inner_entry.configure(font=font10)\n birthday_inner_entry.configure(foreground=\"#ffffff\")\n birthday_inner_entry.configure(justify='center')\n birthday_inner_entry.configure(relief=\"flat\")\n birthday_inner_entry.configure(selectbackground=\"#c4c4c4\")\n\n password_inner_entry = tkinter.Entry(Frame1)\n password_inner_entry.place(relx=0.21, rely=0.75, height=53, relwidth=0.754)\n password_inner_entry.configure(background=\"#dfe6e9\")\n password_inner_entry.configure(font=font10)\n password_inner_entry.configure(foreground=\"#ffffff\")\n password_inner_entry.configure(justify='center')\n password_inner_entry.configure(relief=\"flat\")\n password_inner_entry.configure(selectbackground=\"#c4c4c4\")\n\n\n add_family_submit_button = tkinter.Button(Frame1, command=lambda: add_family_db(firstname_inner_entry.get(), lastname_inner_entry.get(), phone_number_inner_entry.get(), insurance_inner_entry.get(), password_inner_entry.get(), gender_inner_entry.get(), birthday_inner_entry.get()))\n add_family_submit_button.place(relx=0.038, rely=0.88, height=54, width=491)\n add_family_submit_button.configure(activebackground=\"#dfe6e9\")\n add_family_submit_button.configure(background=\"#2d3436\")\n add_family_submit_button.configure(font=font9)\n add_family_submit_button.configure(foreground=\"#ffffff\")\n add_family_submit_button.configure(relief=\"flat\")\n add_family_submit_button.configure(text='''Submit''')\n\n return\n\ndef delete_family_db(phone_number):\n if len(phone_number) == 0:\n return\n \n phone_number = phone_number[0][2]\n\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"DELETE FROM User WHERE phone_number = '{phone_number}';\")\n cursor.execute(f\"DELETE FROM User_User WHERE phone_number_2 = '{phone_number}';\")\n\n connection.commit()\n connection.close()\n\n return\n\ndef update_family_db(first_name, last_name, insurance_id, phone_number, gender, birthday):\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT insurance_id FROM Insurance WHERE name = '{insurance_id}';\")\n insurance_id = cursor.fetchone()\n\n cursor.execute(f\"SELECT gender_id FROM Gender WHERE title = '{gender}';\")\n gender_id = cursor.fetchone()\n\n cursor.execute(f\"UPDATE User SET first_name = '{first_name}', last_name = '{last_name}', insurance_id = {insurance_id[0]}, gender_id = {gender_id[0]}, birthday = '{birthday}' WHERE phone_number = '{phone_number}';\")\n\n connection.commit()\n connection.close()\n\n update_family_page.destroy()\n \n return\n\n\ndef update_family_ui(phone_number):\n\n if len(phone_number) == 0:\n return\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font10 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n font9 = \"-family ubvazir -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global update_family_page\n\n update_family_page = tkinter.Toplevel()\n update_family_page.title('Update Member Page')\n update_family_page.attributes('-fullscreen', True)\n update_family_page.configure(background=\"#2d3436\")\n\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT first_name, last_name, insurance_id, gender_id, birthday, photo FROM User WHERE phone_number = '{phone_number[0][2]}';\")\n temp_user_data = cursor.fetchone()\n\n user_data = []\n for temp in temp_user_data:\n if temp != None:\n user_data.append(temp)\n else:\n user_data.append('')\n \n cursor.execute(f\"SELECT name FROM Insurance WHERE insurance_id = {user_data[2]};\")\n insurance_data = cursor.fetchone()\n\n cursor.execute(f\"SELECT title FROM Gender WHERE gender_id = {user_data[3]};\")\n gender_data = cursor.fetchone()\n\n back_button = tkinter.Button(update_family_page, command=update_family_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n if not (user_data[5] == None or len(user_data[5]) == 0):\n image_path=user_data[5]\n profile_image = Image.open(image_path)\n profile_image = profile_image.resize((150, 150), Image.ANTIALIAS)\n profile_image = ImageTk.PhotoImage(image=profile_image)\n profile_label = tkinter.Label(update_family_page,image=profile_image)\n profile_label.image = profile_image\n profile_label.place(relx=0.4675, rely=0.125)\n\n Frame1 = tkinter.Frame(update_family_page)\n Frame1.place(relx=0.365, rely=0.325, relheight=0.500, relwidth=0.273)\n Frame1.configure(relief='flat')\n Frame1.configure(borderwidth=\"2\")\n Frame1.configure(background=\"#ffffff\")\n\n firstname_label = tkinter.Label(Frame1)\n firstname_label.place(relx=0.0, rely=0.04, height=54, width=98)\n firstname_label.configure(background=\"#ffffff\")\n firstname_label.configure(font=font9)\n firstname_label.configure(text='''First Name''')\n\n lastname_label = tkinter.Label(Frame1)\n lastname_label.place(relx=-0.019, rely=0.17, height=74, width=118)\n lastname_label.configure(activebackground=\"#f9f9f9\")\n lastname_label.configure(background=\"#ffffff\")\n lastname_label.configure(font=font9)\n lastname_label.configure(text='''Last Name''')\n\n insurance_label = tkinter.Label(Frame1)\n insurance_label.place(relx=0.0, rely=0.46, height=54, width=98)\n insurance_label.configure(activebackground=\"#f9f9f9\")\n insurance_label.configure(background=\"#ffffff\")\n insurance_label.configure(font=font9)\n insurance_label.configure(text='''Insurance''')\n\n phone_number_label = tkinter.Label(Frame1)\n phone_number_label.place(relx=0.0, rely=0.32, height=54, width=108)\n phone_number_label.configure(activebackground=\"#f9f9f9\")\n phone_number_label.configure(background=\"#ffffff\")\n phone_number_label.configure(font=font9)\n phone_number_label.configure(text='''Phone Number''')\n\n gender_label = tkinter.Label(Frame1)\n gender_label.place(relx=0.0, rely=0.6, height=54, width=108)\n gender_label.configure(activebackground=\"#f9f9f9\")\n gender_label.configure(background=\"#ffffff\")\n gender_label.configure(font=font9)\n gender_label.configure(text='''Gender''')\n\n birthday_label = tkinter.Label(Frame1)\n birthday_label.place(relx=0.0, rely=0.74, height=54, width=108)\n birthday_label.configure(activebackground=\"#f9f9f9\")\n birthday_label.configure(background=\"#ffffff\")\n birthday_label.configure(font=font9)\n birthday_label.configure(text='''Birthday''')\n\n firstname_entry = tkinter.Entry(Frame1)\n firstname_entry.place(relx=0.21, rely=0.04, height=53, relwidth=0.754)\n firstname_entry.configure(background=\"#dfe6e9\")\n firstname_entry.configure(font=font10)\n firstname_entry.configure(foreground=\"#ffffff\")\n firstname_entry.configure(justify='center')\n firstname_entry.configure(relief=\"flat\")\n firstname_entry.insert(0, user_data[0])\n\n lastname_entry = tkinter.Entry(Frame1)\n lastname_entry.place(relx=0.21, rely=0.18, height=53, relwidth=0.754)\n lastname_entry.configure(background=\"#dfe6e9\")\n lastname_entry.configure(cursor=\"fleur\")\n lastname_entry.configure(font=font10)\n lastname_entry.configure(foreground=\"#ffffff\")\n lastname_entry.configure(justify='center')\n lastname_entry.configure(relief=\"flat\")\n lastname_entry.configure(selectbackground=\"#c4c4c4\")\n lastname_entry.insert(0, user_data[1])\n\n phone_number_entry = tkinter.Entry(Frame1)\n phone_number_entry.place(relx=0.21, rely=0.32, height=53, relwidth=0.754)\n phone_number_entry.configure(background=\"#dfe6e9\")\n phone_number_entry.configure(font=font10)\n phone_number_entry.configure(justify='center')\n phone_number_entry.configure(relief=\"flat\")\n phone_number_entry.configure(selectbackground=\"#c4c4c4\")\n phone_number_entry.insert(0, phone_number[0][2])\n phone_number_entry.configure(state='readonly')\n phone_number_entry.configure(foreground=\"#ffffff\")\n\n insurance_entry = tkinter.Entry(Frame1)\n insurance_entry.place(relx=0.21, rely=0.46, height=53, relwidth=0.754)\n insurance_entry.configure(background=\"#dfe6e9\")\n insurance_entry.configure(font=font10)\n insurance_entry.configure(foreground=\"#ffffff\")\n insurance_entry.configure(justify='center')\n insurance_entry.configure(relief=\"flat\")\n insurance_entry.configure(selectbackground=\"#c4c4c4\")\n if insurance_data != None:\n insurance_entry.insert(0, insurance_data[0])\n\n gender_entry = tkinter.Entry(Frame1)\n gender_entry.place(relx=0.21, rely=0.6, height=53, relwidth=0.754)\n gender_entry.configure(background=\"#dfe6e9\")\n gender_entry.configure(font=font10)\n gender_entry.configure(foreground=\"#ffffff\")\n gender_entry.configure(justify='center')\n gender_entry.configure(relief=\"flat\")\n gender_entry.configure(selectbackground=\"#c4c4c4\")\n if gender_data != None:\n gender_entry.insert(0, gender_data[0])\n\n birthday_entry = tkinter.Entry(Frame1)\n birthday_entry.place(relx=0.21, rely=0.74, height=53, relwidth=0.754)\n birthday_entry.configure(background=\"#dfe6e9\")\n birthday_entry.configure(font=font10)\n birthday_entry.configure(foreground=\"#ffffff\")\n birthday_entry.configure(justify='center')\n birthday_entry.configure(relief=\"flat\")\n birthday_entry.configure(selectbackground=\"#c4c4c4\")\n birthday_entry.insert(0, user_data[4])\n \n\n connection.commit()\n connection.close()\n\n update_family_submit_button = tkinter.Button(Frame1, command=lambda: update_family_db(firstname_entry.get(), lastname_entry.get(), insurance_entry.get(), phone_number[0][2], gender_entry.get(), birthday_entry.get()))\n update_family_submit_button.place(relx=0.038, rely=0.88, height=54, width=491)\n update_family_submit_button.configure(activebackground=\"#dfe6e9\")\n update_family_submit_button.configure(background=\"#2d3436\")\n update_family_submit_button.configure(font=font9)\n update_family_submit_button.configure(foreground=\"#ffffff\")\n update_family_submit_button.configure(relief=\"flat\")\n update_family_submit_button.configure(text='''Submit''')\n\n return\n\ndef add_family_ui():\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font9 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global add_family_page\n\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n \n cursor.execute(f\"SELECT first_name, last_name, phone_number, insurance_id, gender_id, birthday FROM USER WHERE phone_number IN (SELECT phone_number_2 FROM User, User_User WHERE User.phone_number = User_User.phone_number_1 AND User.phone_number = '{current_phone_number}')\");\n family_members = cursor.fetchall()\n\n insurance=[]\n for i in range(len(family_members)):\n cursor.execute(f\"SELECT name FROM Insurance WHERE insurance_id = '{family_members[i][3]}';\");\n insurance.append(cursor.fetchone())\n\n gender = []\n for i in range(len(family_members)):\n cursor.execute(f\"SELECT title FROM Gender WHERE gender_id = '{family_members[i][4]}';\");\n gender.append(cursor.fetchone())\n\n connection.commit()\n connection.close()\n\n add_family_page = tkinter.Tk()\n add_family_page.title('Add Family')\n add_family_page.attributes('-fullscreen', True)\n add_family_page.configure(background=\"#2d3436\")\n\n back_button = tkinter.Button(add_family_page, command=add_family_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n Frame1 = tkinter.Frame(add_family_page)\n Frame1.place(relx=0.208, rely=0.644, relheight=0.132, relwidth=0.586)\n Frame1.configure(relief='flat')\n Frame1.configure(borderwidth=\"2\")\n\n delete_family_button = tkinter.Button(Frame1, command=lambda: delete_family_db([family_members[add_family_listbox.curselection()[0]] for _ in range(1) if 0 != len(add_family_listbox.curselection())]))\n delete_family_button.place(relx=0.249, rely=-0.074, height=154, width=291)\n delete_family_button.configure(activebackground=\"#f9f9f9\")\n delete_family_button.configure(background=\"#ffffff\")\n delete_family_button.configure(borderwidth=\"5\")\n delete_family_button.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n delete_family_button.configure(text='''Delete Member''')\n\n update_family_button = tkinter.Button(Frame1, command=lambda: update_family_ui([family_members[add_family_listbox.curselection()[0]] for _ in range(1) if 0 != len(add_family_listbox.curselection())])) \n update_family_button.place(relx=0.507, rely=-0.074, height=154, width=281)\n update_family_button.configure(activebackground=\"#f9f9f9\")\n update_family_button.configure(background=\"#ffffff\")\n update_family_button.configure(borderwidth=\"5\")\n update_family_button.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n update_family_button.configure(text='''Update Member''')\n\n appointment_family_button = tkinter.Button(Frame1, command=appointment_family_ui)\n appointment_family_button.place(relx=0.756, rely=-0.074, height=154, width=281)\n appointment_family_button.configure(activebackground=\"#f9f9f9\")\n appointment_family_button.configure(background=\"#ffffff\")\n appointment_family_button.configure(borderwidth=\"5\")\n appointment_family_button.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n appointment_family_button.configure(text='''Family Appointments''')\n\n add_family_button = tkinter.Button(Frame1, command=add_family_inner_ui)\n add_family_button.place(relx=-0.009, rely=-0.074, height=154, width=291)\n add_family_button.configure(activebackground=\"#f9f9f9\")\n add_family_button.configure(background=\"#ffffff\")\n add_family_button.configure(borderwidth=\"5\")\n add_family_button.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n add_family_button.configure(text='''Add Member''')\n\n add_family_listbox = tkinter.Listbox(add_family_page)\n add_family_listbox.place(relx=0.208, rely=0.205, relheight=0.416, relwidth=0.585)\n add_family_listbox.configure(background=\"white\")\n add_family_listbox.configure(cursor=\"dotbox\")\n add_family_listbox.configure(font=font9)\n add_family_listbox.configure(highlightbackground=\"#dfe6e9\")\n add_family_listbox.configure(justify='center')\n add_family_listbox.configure(relief=\"flat\")\n add_family_listbox.configure(selectbackground=\"#dfe6e9\")\n add_family_listbox.configure(setgrid=\"1\")\n\n for i in range(len(family_members)):\n\n firstname_text = f'{family_members[i][0]}'\n lastname_text = f'{family_members[i][1]}'\n phone_number_text = f'{family_members[i][2]}'\n insurance_text = f'{insurance[i][0]}'\n gender_text = f'{gender[i][0]}'\n birthday_text = f'{family_members[i][5]}'\n\n for i in range(15):\n if i == len(firstname_text) - 1:\n firstname_text += ' '\n if i == len(lastname_text) - 1:\n lastname_text += ' '\n if i == len(phone_number_text) - 1:\n phone_number_text += ' '\n if i == len(insurance_text) - 1:\n insurance_text += ' '\n if i == len(gender_text) - 1:\n gender_text += ' '\n if i == len(birthday_text) - 1:\n birthday_text += ' '\n\n add_family_listbox.insert(tkinter.END, f'First Name: {firstname_text}| Last Name: {lastname_text}| Phone Number: {phone_number_text}| Insurance: {insurance_text}| Gender: {gender_text}| Birthday: {birthday_text}')\n\n return\n\ndef my_appointments_ui():\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font9 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global my_appointments_page\n\n my_appointments_page = tkinter.Tk()\n my_appointments_page.attributes('-fullscreen', True)\n my_appointments_page.configure(background=\"#2d3436\")\n\n back_button = tkinter.Button(my_appointments_page, command=my_appointments_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n my_appointments_listbox = tkinter.Listbox(my_appointments_page)\n my_appointments_listbox.place(relx=0.050, rely=0.205, relheight=0.552, relwidth=0.9)\n my_appointments_listbox.configure(cursor=\"spider\")\n my_appointments_listbox.configure(font=font9)\n my_appointments_listbox.configure(justify='center')\n my_appointments_listbox.configure(relief=\"flat\")\n my_appointments_listbox.configure(selectbackground=\"#dfe6e9\")\n my_appointments_listbox.configure(setgrid=\"1\")\n\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n \n cursor.execute(f\"SELECT Appointment.*, first_name, last_name FROM Appointment, User WHERE User.phone_number = Appointment.phone_number AND User.phone_number = '{current_phone_number}';\")\n my_appointments_names = cursor.fetchall()\n\n for my_appointments_name in my_appointments_names:\n\n appointment_data = []\n doctor_council = my_appointments_name[3]\n doctor_username = my_appointments_name[1]\n\n cursor.execute(f\"SELECT first_name, last_name FROM Doctor WHERE medical_council_code = '{doctor_council}' AND username = '{doctor_username}';\")\n doctor_data = cursor.fetchone()\n\n\n first_name_text = f'{my_appointments_name[-2]}'\n last_name_text = f'{my_appointments_name[-1]}'\n phone_number_text= f'{current_phone_number}'\n appointment_date_text = f'{my_appointments_name[6]}'\n doctor_firstname_text = f'{doctor_data[0]}'\n doctor_lastname_text = f'{doctor_data[1]}'\n \n for i in range(15):\n if i == len(appointment_date_text) - 1:\n appointment_date_text += ' '\n if i == len(doctor_firstname_text) - 1:\n doctor_firstname_text += ' '\n if i == len(doctor_lastname_text) - 1:\n doctor_lastname_text += ' '\n if i == len(phone_number_text) - 1:\n phone_number_text += ' '\n if i == len(first_name_text) - 1:\n first_name_text += ' '\n if i == len(last_name_text) - 1:\n last_name_text += ' '\n\n my_appointments_listbox.insert(tkinter.END, f'Appointment Date: {appointment_date_text}| Doctor First Name: {doctor_firstname_text}| Doctor Last Name: {doctor_lastname_text}| Patient Phone Number: {phone_number_text}| Patient First Name: {first_name_text}| Patient Last Name: {last_name_text}')\n\n\n connection.commit()\n connection.close()\n\n return\n\n\ndef find_appointment():\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font10 = \"-family ubvazir -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n font9 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global find_appointment_page\n\n find_appointment_page = tkinter.Tk()\n find_appointment_page.title('Search an Speciality')\n find_appointment_page.attributes('-fullscreen', True)\n find_appointment_page.configure(background=\"#2d3436\")\n\n back_button = tkinter.Button(find_appointment_page, command=find_appointment_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n Frame1 = tkinter.Frame(find_appointment_page)\n Frame1.place(relx=0.2, rely=0.585, relheight=0.085, relwidth=0.6)\n Frame1.configure(relief='flat')\n Frame1.configure(borderwidth=\"2\")\n Frame1.configure(background=\"#ffffff\")\n\n appointment_id_entry = tkinter.Entry(Frame1)\n appointment_id_entry.place(relx=0.05, rely=0.155, height=54, relwidth=0.4)\n appointment_id_entry.configure(background=\"#dfe6e9\")\n appointment_id_entry.configure(font=font9)\n appointment_id_entry.configure(justify='center')\n appointment_id_entry.configure(relief=\"flat\")\n appointment_id_entry.configure(selectbackground=\"#c4c4c4\")\n appointment_id_entry.configure(foreground=\"#ffffff\")\n appointment_id_entry.insert(0, 'Appointment Id')\n\n find_button = tkinter.Button(Frame1, command=lambda: find_appointment_db(appointment_id_entry.get()))\n find_button.place(relx=0.55, rely=0.155, height=54, relwidth=0.4)\n find_button.configure(activebackground=\"#dfe6e9\")\n find_button.configure(background=\"#2d3436\")\n find_button.configure(font=font10)\n find_button.configure(foreground=\"#ffffff\")\n find_button.configure(relief=\"flat\")\n find_button.configure(text='''Search Doctor''')\n\n find_appointment_listbox = tkinter.Listbox(find_appointment_page)\n find_appointment_listbox.place(relx=0.2, rely=0.156, relheight=0.377, relwidth=0.6)\n find_appointment_listbox.configure(background=\"white\")\n find_appointment_listbox.configure(font=font9)\n find_appointment_listbox.configure(justify='center')\n find_appointment_listbox.configure(relief=\"flat\")\n find_appointment_listbox.configure(selectbackground=\"#dfe6e9\")\n find_appointment_listbox.configure(setgrid=\"1\")\n \n def find_appointment_db(ap_id):\n \n find_appointment_listbox.delete(0, tkinter.END)\n\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n cursor.execute(f\"SELECT Distinct Appointment.appointment_id, phone_number, start_time, appointment_date, getter_phone_number FROM DOH, Doctor, Appointment WHERE DOH.username = Appointment.username AND DOH.medical_council_code=Appointment.medical_council_code AND DOH.medical_council_code=Doctor.medical_council_code AND Appointment.phone_number = '{current_phone_number}' AND Appointment.appointment_id = '{ap_id}'; \")\n found = cursor.fetchone()\n \n connection.commit()\n connection.close()\n\n if found == None:\n find_appointment_listbox.insert(tkinter.END , \"Appointment Not Found\")\n\n else:\n appointment_id_text = f'{found[0]}'\n phone_number_text= f'{found[1]}'\n start_time_text = f'{found[2]}'\n appointment_date_text = f'{found[3]}'\n getter_phone_number_text = f'{found[4]}'\n \n for i in range(10):\n if i == len(appointment_id_text) - 1:\n appointment_id_text += ' '\n if i == len(phone_number_text) - 1:\n phone_number_text += ' '\n if i == len(start_time_text) - 1:\n start_time_text += ' '\n if i == len(appointment_date_text) - 1:\n appointment_date_text += ' '\n if i == len(getter_phone_number_text) - 1:\n getter_phone_number_text += ' '\n\n find_appointment_listbox.insert(tkinter.END, f'Appointment Id: {appointment_id_text}| Phone Number: {phone_number_text}| Appointment Date: {appointment_date_text}| Start Time: {start_time_text}| Getter Phone Number: {getter_phone_number_text}')\n return\n\ndef profile_ui():\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font9 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global profile_page\n\n profile_page = tkinter.Tk()\n profile_page.title('Profile Page')\n profile_page.attributes('-fullscreen', True)\n profile_page.configure(background=\"#2d3436\")\n\n back_button = tkinter.Button(profile_page, command=profile_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n Frame1 = tkinter.Frame(profile_page)\n Frame1.place(relx=0.193, rely=0.4, relheight=0.132, relwidth=0.586)\n Frame1.configure(relief='flat')\n Frame1.configure(borderwidth=\"2\")\n\n add_family_button = tkinter.Button(Frame1, command=add_family_ui)\n add_family_button.place(relx=0.2, rely=-0.074, height=164, relwidth=0.2)\n add_family_button.configure(activebackground=\"#f9f9f9\")\n add_family_button.configure(background=\"#ffffff\")\n add_family_button.configure(borderwidth=\"5\")\n add_family_button.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n add_family_button.configure(text='''View Members''')\n\n my_appointments_button = tkinter.Button(Frame1, command=my_appointments_ui)\n my_appointments_button.place(relx=0.4, rely=-0.074, height=164, relwidth=0.2)\n my_appointments_button.configure(activebackground=\"#f9f9f9\")\n my_appointments_button.configure(background=\"#ffffff\")\n my_appointments_button.configure(borderwidth=\"5\")\n my_appointments_button.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n my_appointments_button.configure(text='''My Appointments''')\n\n my_appointments_by_others_button = tkinter.Button(Frame1, command=my_appointments_by_others_ui)\n my_appointments_by_others_button.place(relx=0.6, rely=-0.074, height=164, relwidth=0.2)\n my_appointments_by_others_button.configure(activebackground=\"#f9f9f9\")\n my_appointments_by_others_button.configure(background=\"#ffffff\")\n my_appointments_by_others_button.configure(borderwidth=\"5\")\n my_appointments_by_others_button.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n my_appointments_by_others_button.configure(text='''Appointments By Others''')\n\n edit_profile_button = tkinter.Button(Frame1, command=edit_profile_ui)\n edit_profile_button.place(relx=-0.01, rely=-0.074, height=164, relwidth=0.21)\n edit_profile_button.configure(activebackground=\"#f9f9f9\")\n edit_profile_button.configure(background=\"#ffffff\")\n edit_profile_button.configure(borderwidth=\"5\")\n edit_profile_button.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n edit_profile_button.configure(text='''Edit Profile''')\n\n find_appointments_button = tkinter.Button(Frame1, command=find_appointment)\n find_appointments_button.place(relx=0.8, rely=-0.074, height=164, relwidth=0.21)\n find_appointments_button.configure(activebackground=\"#f9f9f9\")\n find_appointments_button.configure(background=\"#ffffff\")\n find_appointments_button.configure(borderwidth=\"5\")\n find_appointments_button.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n find_appointments_button.configure(text='''Find Appointment''')\n\n return\n\n\ndef get_appointment(doctor, username, price):\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font10 = \"-family ubvazir -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n font9 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global appointment_page\n\n appointment_page = tkinter.Tk()\n appointment_page.title('Set Appointment')\n appointment_page.attributes('-fullscreen', True)\n appointment_page.configure(background=\"#2d3436\")\n \n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n cursor.execute(f\"SELECT Work_Hour.start_hour, Work_Hour.end_hour, Work_Hour.w_date, DOH.DOH_id, 0 FROM Work_Hour, DOH, Doctor WHERE Doctor.medical_council_code = DOH.medical_council_code AND Doctor.username = DOH.username AND DOH.DOH_id = Work_Hour.DOH_id AND Doctor.medical_council_code='{doctor[3]}' AND Doctor.username = '{username}';\")\n times = cursor.fetchall()\n\n cursor.execute(f\"SELECT Work_Hour.start_hour, Work_Hour.end_hour, Work_Hour.w_date, 0, DHH.DHH_id FROM Work_Hour, DHH, Doctor WHERE Doctor.medical_council_code = DHH.medical_council_code AND Doctor.username = DHH.username AND DHH.DHH_id = Work_Hour.DHH_id AND Doctor.medical_council_code='{doctor[3]}' AND Doctor.username = '{username}';\")\n times += cursor.fetchall()\n \n connection.commit()\n connection.close()\n \n dates = []\n years = []\n months = []\n days = []\n \n for i in range(len(times)):\n dates.append(times[i][2])\n \n for i in range(len(dates)):\n if (dates[i].split(\"/\"))[0] not in years:\n years.append((dates[i].split(\"/\"))[0])\n\n Frame1_2 = tkinter.Frame(appointment_page)\n Frame1_2.place(relx=0.052, rely=0.215, relheight=0.502, relwidth=0.169)\n Frame1_2.configure(relief='flat')\n Frame1_2.configure(borderwidth=\"2\")\n Frame1_2.configure(background=\"#ffffff\")\n\n select_years = tkinter.Button(Frame1_2, command=lambda: selected_year(years[all_years_listbox.curselection()[0]] ))\n select_years.place(relx=0.031, rely=0.835, height=74, width=301)\n select_years.configure(activebackground=\"#dfe6e9\")\n select_years.configure(background=\"#2d3436\")\n select_years.configure(font=font10)\n select_years.configure(foreground=\"#ffffff\")\n select_years.configure(relief=\"flat\")\n select_years.configure(text='''Select Year''')\n\n all_years_listbox = tkinter.Listbox(appointment_page)\n all_years_listbox.place(relx=0.057, rely=0.224, relheight=0.396, relwidth=0.158)\n all_years_listbox.configure(background=\"white\")\n all_years_listbox.configure(font=font9)\n all_years_listbox.configure(justify='center')\n all_years_listbox.configure(relief=\"flat\")\n all_years_listbox.configure(selectbackground=\"#dfe6e9\")\n \n for year in years:\n all_years_listbox.insert(tkinter.END, year)\n \n def selected_year(y):\n\n for i in range(len(dates)):\n if (dates[i].split(\"/\"))[0] == y and (dates[i].split(\"/\"))[1] not in months:\n months.append((dates[i].split(\"/\"))[1])\n \n Frame1_1 = tkinter.Frame(appointment_page)\n Frame1_1.place(relx=0.234, rely=0.215, relheight=0.502, relwidth=0.169)\n Frame1_1.configure(relief='flat')\n Frame1_1.configure(borderwidth=\"2\")\n Frame1_1.configure(background=\"#ffffff\")\n\n select_months = tkinter.Button(Frame1_1, command=lambda: selected_month(months[all_months_listbox.curselection()[0]] ))\n select_months.place(relx=0.031, rely=0.835, height=74, width=301)\n select_months.configure(activebackground=\"#dfe6e9\")\n select_months.configure(background=\"#2d3436\")\n select_months.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n select_months.configure(foreground=\"#ffffff\")\n select_months.configure(relief=\"flat\")\n select_months.configure(text='''Select Month''')\n\n all_months_listbox = tkinter.Listbox(Frame1_1)\n all_months_listbox.place(relx=0.031, rely=0.019, relheight=0.788, relwidth=0.935)\n all_months_listbox.configure(background=\"white\")\n all_months_listbox.configure(font=\"-family {DejaVu Sans Mono} -size 10 -weight bold\")\n all_months_listbox.configure(justify='center')\n all_months_listbox.configure(relief=\"flat\")\n all_months_listbox.configure(selectbackground=\"#dfe6e9\")\n\n for month in months:\n all_months_listbox.insert(tkinter.END, month)\n \n def selected_month(m):\n for i in range(len(dates)):\n if (dates[i].split(\"/\"))[0] == y and (dates[i].split(\"/\"))[1] == m and (dates[i].split(\"/\"))[2] not in days:\n days.append((dates[i].split(\"/\"))[2])\n \n Frame1 = tkinter.Frame(appointment_page)\n Frame1.place(relx=0.417, rely=0.215, relheight=0.502, relwidth=0.169)\n Frame1.configure(relief='flat')\n Frame1.configure(borderwidth=\"2\")\n Frame1.configure(background=\"#ffffff\")\n\n all_days_listbox = tkinter.Listbox(Frame1)\n all_days_listbox.place(relx=0.031, rely=0.019, relheight=0.788, relwidth=0.935)\n all_days_listbox.configure(background=\"white\")\n all_days_listbox.configure(font=\"-family {DejaVu Sans Mono} -size 10 -weight bold\")\n all_days_listbox.configure(justify='center')\n all_days_listbox.configure(relief=\"flat\")\n all_days_listbox.configure(selectbackground=\"#dfe6e9\")\n\n select_days = tkinter.Button(Frame1, command=lambda: selected_day(days[all_days_listbox.curselection()[0]] ))\n select_days.place(relx=0.031, rely=0.835, height=74, width=301)\n select_days.configure(activebackground=\"#dfe6e9\")\n select_days.configure(background=\"#2d3436\")\n select_days.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n select_days.configure(foreground=\"#ffffff\")\n select_days.configure(relief=\"flat\")\n select_days.configure(text='''Select Day''')\n\n for day in days:\n all_days_listbox.insert(tkinter.END, day)\n \n \n def selected_day(d):\n selected_date = f'{str(y)}/{str(m)}/{str(d)}'\n \n for time in times:\n if time[2] == selected_date:\n start = time[0]\n end = time[1]\n \n \n all_times = []\n start_minute = int((start.split(\":\"))[1])\n end_minute = int((end.split(\":\"))[1])\n start_time = int((start.split(\":\"))[0])\n end_time = int((end.split(\":\"))[0])\n if(end_minute == 30):\n end_time += 0.5\n if(start_minute == 30):\n start_time += 0.5\n \n while start_time <= end_time:\n all_times.append(start_time)\n start_time += 0.5\n\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT start_time FROM Appointment WHERE medical_council_code = '{doctor[3]}' AND appointment_date = '{selected_date}' AND username = '{username}';\")\n not_available_times = cursor.fetchall()\n \n connection.commit()\n connection.close()\n\n not_available_times_intger = []\n for i in range(len(not_available_times)):\n hour_not_available = int((not_available_times[i][0].split(\":\"))[0])\n minute_not_available = int((not_available_times[i][0].split(\":\"))[1])\n if minute_not_available == 30:\n hour_not_available = hour_not_available + 0.5\n not_available_times_intger.append(hour_not_available)\n \n available_times = [all_time for all_time in all_times if all_time not in not_available_times_intger]\n \n Frame1_3 = tkinter.Frame(appointment_page)\n Frame1_3.place(relx=0.599, rely=0.215, relheight=0.502, relwidth=0.169)\n Frame1_3.configure(relief='flat')\n Frame1_3.configure(borderwidth=\"2\")\n Frame1_3.configure(background=\"#ffffff\")\n\n all_times_listbox = tkinter.Listbox(Frame1_3)\n all_times_listbox.place(relx=0.031, rely=0.019, relheight=0.788, relwidth=0.935)\n all_times_listbox.configure(background=\"white\")\n all_times_listbox.configure(font=\"-family {DejaVu Sans Mono} -size 10 -weight bold\")\n all_times_listbox.configure(justify='center')\n all_times_listbox.configure(relief=\"flat\")\n all_times_listbox.configure(selectbackground=\"#dfe6e9\")\n\n for available_time in available_times:\n all_times_listbox.insert(tkinter.END, available_time)\n\n selecet_time = tkinter.Button(Frame1_3, command=lambda: selected_time(available_times[all_times_listbox.curselection()[0]]))\n selecet_time.place(relx=0.031, rely=0.835, height=74, width=301)\n selecet_time.configure(activebackground=\"#dfe6e9\")\n selecet_time.configure(background=\"#2d3436\")\n selecet_time.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n selecet_time.configure(foreground=\"#ffffff\")\n selecet_time.configure(relief=\"flat\")\n selecet_time.configure(text='''Select Time''')\n \n def selected_time(selected_time):\n if selected_time % 1 != 0:\n selected_time = f'{int(selected_time)}:30'\n else:\n selected_time = f'{int(selected_time)}:00'\n \n for time in times:\n if time[0] <= selected_time and selected_time <=time[1] and selected_date == time[2]:\n DOH_id = time[3]\n DHH_id = time[4]\n \n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT first_name, last_name, insurance_id, User_User.phone_number_2 FROM User, User_User WHERE User.phone_number = User_User.phone_number_2 AND User_User.phone_number_1='{current_phone_number}';\")\n family_members = cursor.fetchall() \n\n connection.commit()\n connection.close()\n \n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n cursor.execute(f\"SELECT first_name, last_name, insurance_id, phone_number FROM User WHERE User.phone_number = '{current_phone_number}';\")\n user_info=cursor.fetchall()\n \n connection.commit()\n connection.close()\n \n \n family_members += user_info\n\n Frame1_4 = tkinter.Frame(appointment_page)\n Frame1_4.place(relx=0.781, rely=0.215, relheight=0.502, relwidth=0.169)\n Frame1_4.configure(relief='flat')\n Frame1_4.configure(borderwidth=\"2\")\n Frame1_4.configure(background=\"#ffffff\")\n\n all_people_listbox = tkinter.Listbox(Frame1_4)\n all_people_listbox.place(relx=0.031, rely=0.019, relheight=0.788, relwidth=0.935)\n all_people_listbox.configure(background=\"white\")\n all_people_listbox.configure(font=\"-family {DejaVu Sans Mono} -size 10 -weight bold\")\n all_people_listbox.configure(justify='center')\n all_people_listbox.configure(relief=\"flat\")\n all_people_listbox.configure(selectbackground=\"#dfe6e9\")\n\n selecet_people = tkinter.Button(Frame1_4, command=lambda: selected_people(family_members[all_people_listbox.curselection()[0]], DOH_id, DHH_id))\n selecet_people.place(relx=0.031, rely=0.835, height=74, width=301)\n selecet_people.configure(activebackground=\"#dfe6e9\")\n selecet_people.configure(background=\"#2d3436\")\n selecet_people.configure(cursor=\"fleur\")\n selecet_people.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n selecet_people.configure(foreground=\"#ffffff\")\n selecet_people.configure(relief=\"flat\")\n selecet_people.configure(text='''Select Person''')\n\n for family_member in family_members:\n person_name = f'{family_member[0]} {family_member[1]} | {family_member[3]}'\n all_people_listbox.insert(tkinter.END, person_name)\n \n def selected_people(person, DOH_id, DHH_id):\n \n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"INSERT INTO Payment (cost, payment_code) VALUES ('{price}', '{20}');\")\n payment = cursor.fetchall()\n\n connection.commit()\n connection.close()\n \n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT payment_id FROM Payment\")\n payment=cursor.fetchall()\n\n connection.commit()\n connection.close()\n \n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n if DOH_id != 0:\n cursor.execute(f\"INSERT INTO Appointment (username, phone_number, medical_council_code, payment_id, start_time, appointment_date, getter_phone_number, DOH_id) VALUES ('{username}', '{person[3]}', '{doctor[3]}', '{payment[-1][0]}', '{selected_time}', '{selected_date}', '{current_phone_number}', '{DOH_id}');\")\n elif DHH_id != 0:\n cursor.execute(f\"INSERT INTO Appointment (username, phone_number, medical_council_code, payment_id, start_time, appointment_date, getter_phone_number, DHH_id) VALUES ('{username}', '{person[3]}', '{doctor[3]}', '{payment[-1][0]}', '{selected_time}', '{selected_date}', '{current_phone_number}', {DHH_id});\")\n \n appointment = cursor.fetchall() \n \n connection.commit()\n\n cursor.execute(f\"SELECT appointment_id FROM Appointment WHERE username = '{username}' AND phone_number = '{person[3]}' AND medical_council_code = '{doctor[3]}' AND payment_id = '{payment[-1][0]}' AND start_time = '{selected_time}' AND appointment_date = '{selected_date}' AND getter_phone_number = '{current_phone_number}'\")\n\n messagebox.showinfo('Appointment ID', f\"You Appointmet ID is {cursor.fetchone()[0]}\")\n\n appointment_page.destroy()\n\n connection.close()\n \n return\n\ndef doctor_search_db(firstname, lastname, names_found_listbox):\n \n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT first_name, last_name, name, medical_council_code FROM Doctor, Speciality WHERE Doctor.speciality_id = Speciality.speciality_id AND first_name LIKE '%{firstname}%' AND last_name LIKE '%{lastname}%'\")\n names_found = cursor.fetchall()\n \n names_found_listbox.delete(0, tkinter.END)\n\n for i in range(len(names_found)):\n\n firstname_text = f'{names_found[i][0]}'\n lastname_text = f'{names_found[i][1]}'\n speciality_text = f'{names_found[i][2]}'\n council_text = f'{names_found[i][3]}'\n\n for i in range(10):\n if i == len(firstname_text) - 1:\n firstname_text += ' '\n if i == len(lastname_text) - 1:\n lastname_text += ' '\n if i == len(speciality_text) - 1:\n speciality_text += ' '\n if i == len(council_text) - 1:\n council_text += ' '\n\n names_found_listbox.insert(tkinter.END, f'First Name: {firstname_text}| Last Name: {lastname_text}| Speciality: {speciality_text}| Medical Council Code: {council_text}\\n')\n \n connection.commit()\n connection.close()\n\n return\n\ndef doctor_search_ui():\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font10 = \"-family ubvazir -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n font9 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global doctor_search_page\n\n doctor_search_page = tkinter.Tk()\n doctor_search_page.title('Search a Doctor')\n doctor_search_page.attributes('-fullscreen', True)\n doctor_search_page.configure(background=\"#2d3436\")\n\n back_button = tkinter.Button(doctor_search_page, command=doctor_search_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n names_found_listbox = tkinter.Listbox(doctor_search_page)\n names_found_listbox.place(relx=0.271, rely=0.156, relheight=0.377, relwidth=0.45)\n names_found_listbox.configure(background=\"white\")\n names_found_listbox.configure(font=font9)\n names_found_listbox.configure(justify='center')\n names_found_listbox.configure(relief=\"flat\")\n names_found_listbox.configure(selectbackground=\"#dfe6e9\")\n names_found_listbox.configure(setgrid=\"1\")\n\n Frame1 = tkinter.Frame(doctor_search_page)\n Frame1.place(relx=0.271, rely=0.585, relheight=0.151, relwidth=0.451)\n Frame1.configure(relief='flat')\n Frame1.configure(borderwidth=\"2\")\n Frame1.configure(background=\"#ffffff\")\n\n firstname_entry = tkinter.Entry(Frame1)\n firstname_entry.place(relx=0.035, rely=0.129, height=53, relwidth=0.435)\n firstname_entry.configure(background=\"#dfe6e9\")\n firstname_entry.configure(font=font9)\n firstname_entry.configure(justify='center')\n firstname_entry.configure(relief=\"flat\")\n firstname_entry.configure(selectbackground=\"#c4c4c4\")\n firstname_entry.configure(foreground=\"#ffffff\")\n firstname_entry.insert(0, 'First Name')\n\n set_appointment_button = tkinter.Button(Frame1)\n set_appointment_button.place(relx=0.543, rely=0.516, height=54, width=371)\n set_appointment_button.configure(activebackground=\"#dfe6e9\")\n set_appointment_button.configure(background=\"#2d3436\")\n set_appointment_button.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n set_appointment_button.configure(foreground=\"#ffffff\")\n set_appointment_button.configure(relief=\"flat\")\n set_appointment_button.configure(text='''Set Appointment''')\n\n lastname_entry = tkinter.Entry(Frame1)\n lastname_entry.place(relx=0.035, rely=0.516, height=53, relwidth=0.435)\n lastname_entry.configure(background=\"#dfe6e9\")\n lastname_entry.configure(font=\"-family {DejaVu Sans Mono} -size 10 -weight bold\")\n lastname_entry.configure(justify='center')\n lastname_entry.configure(relief=\"flat\")\n lastname_entry.configure(selectbackground=\"#c4c4c4\")\n lastname_entry.configure(foreground=\"#ffffff\")\n lastname_entry.insert(0, 'Last Name')\n\n search_doctor_button = tkinter.Button(Frame1, command=lambda: doctor_search_db(firstname_entry.get(), lastname_entry.get(), names_found_listbox))\n search_doctor_button.place(relx=0.543, rely=0.129, height=54, width=371)\n search_doctor_button.configure(activebackground=\"#dfe6e9\")\n search_doctor_button.configure(background=\"#2d3436\")\n search_doctor_button.configure(font=font10)\n search_doctor_button.configure(foreground=\"#ffffff\")\n search_doctor_button.configure(relief=\"flat\")\n search_doctor_button.configure(text='''Search Doctor''')\n\n return\n\ndef speciality_search_db(speciality_name, specialities_found_listbox):\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT first_name, last_name, name, medical_council_code FROM Doctor, Speciality WHERE Doctor.speciality_id = Speciality.speciality_id AND name LIKE '%{speciality_name}%'\")\n specialities_found = cursor.fetchall()\n\n specialities_found_listbox.delete(0, tkinter.END)\n\n for i in range(len(specialities_found)):\n\n firstname_text = f'{specialities_found[i][0]}'\n lastname_text = f'{specialities_found[i][1]}'\n speciality_text = f'{specialities_found[i][2]}'\n council_text = f'{specialities_found[i][3]}'\n\n for i in range(10):\n if i == len(firstname_text) - 1:\n firstname_text += ' '\n if i == len(lastname_text) - 1:\n lastname_text += ' '\n if i == len(speciality_text) - 1:\n speciality_text += ' '\n if i == len(council_text) - 1:\n council_text += ' '\n\n specialities_found_listbox.insert(tkinter.END, f'First Name: {firstname_text}| Last Name: {lastname_text}| Speciality: {speciality_text}| Medical Council Code: {council_text}\\n')\n\n connection.commit()\n connection.close()\n\n return\n\ndef speciality_search_ui():\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font10 = \"-family ubvazir -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n font9 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global speciality_search_page\n\n speciality_search_page = tkinter.Tk()\n speciality_search_page.title('Search an Speciality')\n speciality_search_page.attributes('-fullscreen', True)\n speciality_search_page.configure(background=\"#2d3436\")\n\n back_button = tkinter.Button(speciality_search_page, command=speciality_search_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n specialities_found_listbox = tkinter.Listbox(speciality_search_page)\n specialities_found_listbox.place(relx=0.271, rely=0.156, relheight=0.377, relwidth=0.45)\n specialities_found_listbox.configure(background=\"white\")\n specialities_found_listbox.configure(font=font9)\n specialities_found_listbox.configure(justify='center')\n specialities_found_listbox.configure(relief=\"flat\")\n specialities_found_listbox.configure(selectbackground=\"#dfe6e9\")\n specialities_found_listbox.configure(setgrid=\"1\")\n\n Frame1 = tkinter.Frame(speciality_search_page)\n Frame1.place(relx=0.271, rely=0.585, relheight=0.151, relwidth=0.451)\n Frame1.configure(relief='flat')\n Frame1.configure(borderwidth=\"2\")\n Frame1.configure(background=\"#ffffff\")\n\n speciality_entry = tkinter.Entry(Frame1)\n speciality_entry.place(relx=0.035, rely=0.129, height=113, relwidth=0.435)\n speciality_entry.configure(background=\"#dfe6e9\")\n speciality_entry.configure(font=font9)\n speciality_entry.configure(justify='center')\n speciality_entry.configure(relief=\"flat\")\n speciality_entry.configure(selectbackground=\"#c4c4c4\")\n speciality_entry.configure(foreground=\"#ffffff\")\n speciality_entry.insert(0, 'Speciality Name')\n\n set_appointment_button = tkinter.Button(Frame1)\n set_appointment_button.place(relx=0.543, rely=0.516, height=54, width=371)\n set_appointment_button.configure(activebackground=\"#dfe6e9\")\n set_appointment_button.configure(background=\"#2d3436\")\n set_appointment_button.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n set_appointment_button.configure(foreground=\"#ffffff\")\n set_appointment_button.configure(relief=\"flat\")\n set_appointment_button.configure(text='''Set Appointment''')\n\n search_speciality_button = tkinter.Button(Frame1, command=lambda: speciality_search_db(speciality_entry.get(), specialities_found_listbox))\n search_speciality_button.place(relx=0.543, rely=0.129, height=54, width=371)\n search_speciality_button.configure(activebackground=\"#dfe6e9\")\n search_speciality_button.configure(background=\"#2d3436\")\n search_speciality_button.configure(font=font10)\n search_speciality_button.configure(foreground=\"#ffffff\")\n search_speciality_button.configure(relief=\"flat\")\n search_speciality_button.configure(text='''Search Doctor''')\n\n return\n\ndef first_time(council, username):\n\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT Work_Hour.start_hour, Work_Hour.end_hour, Work_Hour.w_date FROM Work_Hour, DOH, Doctor WHERE Doctor.medical_council_code = DOH.medical_council_code AND Doctor.username = DOH.username AND DOH.DOH_id = Work_Hour.DOH_id AND Doctor.medical_council_code = '{council}' AND Doctor.username = '{username}';\")\n all_times = cursor.fetchall()\n\n cursor.execute(f\"SELECT Work_Hour.start_hour, Work_Hour.end_hour, Work_Hour.w_date FROM Work_Hour, DHH, Doctor WHERE Doctor.medical_council_code = DHH.medical_council_code AND Doctor.username = DHH.username AND DHH.DHH_id = Work_Hour.DHH_id AND Doctor.medical_council_code = '{council}' AND Doctor.username = '{username}';\")\n all_times += cursor.fetchall()\n\n connection.commit()\n connection.close()\n\n x = len(all_times)\n \n for i in range(x):\n\n if len(all_times) == 0:\n return\n \n date = min(all_times, key=lambda tup: tup[2])\n time = \"\"\n all_work_hour_times = []\n \n start_minute = int((date[0].split(\":\"))[1])\n end_minute = int((date[1].split(\":\"))[1])\n start_time = int((date[0].split(\":\"))[0])\n end_time = int((date[1].split(\":\"))[0])\n\n if(end_minute == 30):\n end_time += 0.5\n if(start_minute==30):\n start_time += 0.5\n while start_time <= end_time:\n all_work_hour_times.append(start_time)\n start_time+=0.5\n \n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT start_time FROM Appointment WHERE medical_council_code = '{council}' AND username = '{username}' AND appointment_date = '{date[2]}';\")\n not_available_times=cursor.fetchall()\n\n connection.commit()\n connection.close()\n not_available_times_intger = []\n \n for i in range(len(not_available_times)):\n\n not_available_time_hour = int((not_available_times[i][0].split(\":\"))[0])\n not_available_time_minute = int((not_available_times[i][0].split(\":\"))[1])\n if not_available_time_minute == 30:\n not_available_time_hour = not_available_time_hour+0.5\n not_available_times_intger.append(not_available_time_hour)\n\n available_times = [i for i in all_work_hour_times if i not in not_available_times_intger] \n\n if len(available_times) != 0:\n\n if min(available_times) % 1 != 0:\n\n time = f'{int(min(available_times))}:30'\n available_time_and_date = [time, date[2]]\n return available_time_and_date\n \n else:\n time = f'{int(min(available_times))}:00'\n available_time_and_date=[time, date[2]]\n return available_time_and_date\n\n else:\n all_times.pop(all_times.index(date))\n \n return\n\ndef appointment_ui():\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font9 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global all_doctors_page\n\n\n all_doctors_page = tkinter.Tk()\n all_doctors_page.title('Add Family')\n all_doctors_page.attributes('-fullscreen', True)\n all_doctors_page.configure(background=\"#2d3436\")\n\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n \n cursor.execute(f\"SELECT first_name, last_name, Speciality.name, medical_council_code, username, visit_price FROM Doctor, Speciality WHERE Doctor.speciality_id = Speciality.speciality_id \")\n temp_doctors = cursor.fetchall()\n\n\n doctors = []\n usernames = []\n price = []\n \n for temp_doctor in temp_doctors:\n doctors.append(temp_doctor[:4])\n usernames.append(temp_doctor[4])\n price.append(temp_doctor[5])\n \n connection.commit()\n connection.close()\n\n all_doctors_listbox = tkinter.Listbox(all_doctors_page)\n all_doctors_listbox.place(relx=0.208, rely=0.205, relheight=0.416, relwidth=0.585)\n all_doctors_listbox.configure(background=\"white\")\n all_doctors_listbox.configure(cursor=\"dotbox\")\n all_doctors_listbox.configure(font=font9)\n all_doctors_listbox.configure(highlightbackground=\"#dfe6e9\")\n all_doctors_listbox.configure(justify='center')\n all_doctors_listbox.configure(relief=\"flat\")\n all_doctors_listbox.configure(selectbackground=\"#dfe6e9\")\n all_doctors_listbox.configure(setgrid=\"1\")\n\n for i in range(len(doctors)):\n\n first_visit_time = first_time(doctors[i][3], usernames[i])\n\n name_text = f'{doctors[i][0]} {doctors[i][1]}'\n speciality_text = f'{doctors[i][2]}'\n council_text = f'{doctors[i][3]}'\n if first_visit_time != None:\n first_time_text = f'{first_visit_time[0]} - {first_visit_time[1]}'\n else:\n first_time_text = 'Does Not Have'\n\n for i in range(20):\n if i == len(name_text) - 1:\n name_text += ' '\n if i == len(speciality_text) - 1:\n speciality_text += ' '\n if i == len(council_text) - 1:\n council_text += ' '\n if i == len(first_time_text) - 1:\n first_time_text += ' '\n\n all_doctors_listbox.insert(tkinter.END, f'Name: {name_text}| Speciality: {speciality_text}| Medical Council Code: {council_text} | First Time: {first_time_text}')\n\n back_button = tkinter.Button(all_doctors_page, command=all_doctors_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n Frame1 = tkinter.Frame(all_doctors_page)\n Frame1.place(relx=0.208, rely=0.644, relheight=0.132, relwidth=0.586)\n Frame1.configure(relief='flat')\n Frame1.configure(borderwidth=\"2\")\n\n\n set_appointment_button = tkinter.Button(Frame1, command=lambda: get_appointment(doctors[all_doctors_listbox.curselection()[0]], usernames[all_doctors_listbox.curselection()[0]], price[all_doctors_listbox.curselection()[0]]))\n set_appointment_button.place(relx=0.249, rely=-0.074, height=154, width=291)\n set_appointment_button.configure(activebackground=\"#f9f9f9\")\n set_appointment_button.configure(background=\"#ffffff\")\n set_appointment_button.configure(borderwidth=\"5\")\n set_appointment_button.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n set_appointment_button.configure(text='''Set Appointment''')\n\n search_by_name = tkinter.Button(Frame1, command=doctor_search_ui) \n search_by_name.place(relx=0.507, rely=-0.074, height=154, width=281)\n search_by_name.configure(activebackground=\"#f9f9f9\")\n search_by_name.configure(background=\"#ffffff\")\n search_by_name.configure(borderwidth=\"5\")\n search_by_name.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n search_by_name.configure(text='''Search Name''')\n\n search_by_speciality = tkinter.Button(Frame1, command=speciality_search_ui)\n search_by_speciality.place(relx=0.756, rely=-0.074, height=154, width=281)\n search_by_speciality.configure(activebackground=\"#f9f9f9\")\n search_by_speciality.configure(background=\"#ffffff\")\n search_by_speciality.configure(borderwidth=\"5\")\n search_by_speciality.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n search_by_speciality.configure(text='''Search Speciality''')\n\n view_profile_button = tkinter.Button(Frame1, command=lambda:doctor_profile(doctors[all_doctors_listbox.curselection()[0]], usernames[all_doctors_listbox.curselection()[0]]))\n view_profile_button.place(relx=-0.009, rely=-0.074, height=154, width=291)\n view_profile_button.configure(activebackground=\"#f9f9f9\")\n view_profile_button.configure(background=\"#ffffff\")\n view_profile_button.configure(borderwidth=\"5\")\n view_profile_button.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n view_profile_button.configure(text='''View Profile''')\n\n return\n \n \n\ndef doctor_profile(doctor, username):\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font9 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global doctor_page\n\n doctor_page = tkinter.Toplevel()\n doctor_page.title('Doctor Profile')\n doctor_page.attributes('-fullscreen', True)\n doctor_page.configure(background=\"#2d3436\")\n\n back_button = tkinter.Button(doctor_page, command=doctor_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n doctor_info_listbox = tkinter.Listbox(doctor_page)\n doctor_info_listbox.place(relx=0.271, rely=0.325, relheight=0.542, relwidth=0.466)\n doctor_info_listbox.configure(background=\"white\")\n doctor_info_listbox.configure(font=font9)\n doctor_info_listbox.configure(justify='left')\n doctor_info_listbox.configure(relief=\"flat\")\n doctor_info_listbox.configure(setgrid=\"1\")\n\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT DISTINCT first_name, last_name, Speciality.name, Doctor.medical_council_code, photo, visit_price FROM Doctor, DOH, Speciality WHERE Doctor.speciality_id = Speciality.speciality_id AND Doctor.medical_council_code = DOH.medical_council_code AND Doctor.username = DOH.username AND Doctor.medical_council_code = '{doctor[3]}' AND Doctor.username = '{username}';\");\n doctor_info = cursor.fetchone()\n if doctor_info == None:\n cursor.execute(f\"SELECT DISTINCT first_name, last_name, Speciality.name, Doctor.medical_council_code, photo, visit_price FROM Doctor, DHH, Speciality WHERE Doctor.speciality_id = Speciality.speciality_id AND Doctor.medical_council_code = DHH.medical_council_code AND Doctor.username = DHH.username AND Doctor.medical_council_code = '{doctor[3]}' AND Doctor.username = '{username}';\");\n doctor_info = cursor.fetchone()\n elif doctor_info == None:\n cursor.execute(f\"SELECT DISTINCT first_name, last_name, Speciality.name, Doctor.medical_council_code, photo, visit_price FROM Doctor, Speciality WHERE Doctor.speciality_id = Speciality.speciality_id AND Doctor.medical_council_code = '{doctor[3]}' AND Doctor.username = '{username}';\");\n doctor_info = cursor.fetchone()\n\n cursor.execute(f\"SELECT name FROM Insurance WHERE insurance_id IN (SELECT insurance_id FROM Insurance_Doctor WHERE medical_council_code = '{doctor[3]}' AND username = '{username}');\")\n insurance_names = cursor.fetchall()\n\n if doctor_info[4] != None:\n image_path = doctor_info[4]\n profile_image = Image.open(image_path)\n profile_image = profile_image.resize((150, 150), Image.ANTIALIAS)\n profile_image = ImageTk.PhotoImage(image=profile_image)\n profile_label = tkinter.Label(doctor_page,image=profile_image)\n profile_label.image = profile_image\n profile_label.place(relx=0.4675, rely=0.125)\n\n doctor_info_listbox.insert(tkinter.END, f' ')\n doctor_info_listbox.insert(tkinter.END, f' First Name: {doctor_info[0]}')\n doctor_info_listbox.insert(tkinter.END, f' ')\n doctor_info_listbox.insert(tkinter.END, f' Last Name: {doctor_info[1]}')\n doctor_info_listbox.insert(tkinter.END, f' ')\n doctor_info_listbox.insert(tkinter.END, f' Medical Council Code: {doctor_info[3]}')\n doctor_info_listbox.insert(tkinter.END, f' ')\n doctor_info_listbox.insert(tkinter.END, f' Speciality: {doctor_info[2]}')\n doctor_info_listbox.insert(tkinter.END, f' ')\n doctor_info_listbox.insert(tkinter.END, f' Visit Price: {doctor_info[4]}')\n doctor_info_listbox.insert(tkinter.END, f' ')\n\n connection.commit()\n connection.close()\n \n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT Work_Hour.w_date , Work_Hour.start_hour , Work_Hour.end_hour , Doctor_Office.phone_number, Address.alley, Address.street, Address.plaque FROM Work_Hour,Doctor, DOH, Doctor_Office, Address WHERE DOH.DOH_id=Work_Hour.DOH_id AND Doctor.medical_council_code = DOH.medical_council_code AND Doctor.username = DOH.username AND DOH.doctor_office_id=Doctor_Office.doctor_office_id AND Doctor_Office.address_id=Address.address_id AND Doctor.medical_council_code='{doctor[3]}';\");\n work_info=cursor.fetchall()\n\n connection.commit()\n connection.close()\n \n doctor_info_listbox.insert(tkinter.END, \" Offices And Work Hours:\")\n doctor_info_listbox.insert(tkinter.END, f' ')\n for work_hours_and_offices in work_info:\n doctor_info_listbox.insert(tkinter.END, f' Date: {work_hours_and_offices[0]}')\n doctor_info_listbox.insert(tkinter.END, f' Start Time: {work_hours_and_offices[1]}')\n doctor_info_listbox.insert(tkinter.END, f' End Time: {work_hours_and_offices[2]}')\n doctor_info_listbox.insert(tkinter.END, f' Phone Number: {work_hours_and_offices[3]}')\n doctor_info_listbox.insert(tkinter.END, f' Address: {work_hours_and_offices[4]} - {work_hours_and_offices[5]} - {work_hours_and_offices[6]}')\n doctor_info_listbox.insert(tkinter.END, ' ')\n\n doctor_info_listbox.insert(tkinter.END, \" Insurances:\")\n doctor_info_listbox.insert(tkinter.END, f' ')\n for insurance_name in insurance_names:\n doctor_info_listbox.insert(tkinter.END, f' Insurance: {insurance_name[0]}')\n\n return\n\n \n\ndef HCC_doctors_show(index, health_care_centers, HCC_doctors_listbox):\n\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT first_name, last_name, Speciality.name, Doctor.medical_council_code, HCC.name FROM Doctor, Speciality, HCC, DHH WHERE Doctor.medical_council_code = DHH.medical_council_code AND Doctor.username = DHH.username AND DHH.HCC_id = HCC.HCC_id AND Doctor.speciality_id = Speciality.speciality_id AND HCC.HCC_id = {health_care_centers[index][0]};\");\n HCC_doctors = cursor.fetchall()\n \n connection.commit()\n connection.close()\n\n HCC_doctors_listbox.delete(0, tkinter.END)\n\n for HCC_doctor in HCC_doctors:\n\n first_name_text = f'{HCC_doctor[0]}'\n last_name_text = f'{HCC_doctor[1]}'\n speciality_text = f'{HCC_doctor[2]}'\n name_text = f'{HCC_doctor[4]}'\n\n for i in range(8):\n if i == len(first_name_text) - 1:\n first_name_text += ' '\n if i == len(last_name_text) - 1:\n last_name_text += ' '\n if i == len(speciality_text) - 1:\n speciality_text += ' '\n if i == len(name_text) - 1:\n name_text += ' '\n\n HCC_doctors_listbox.insert(tkinter.END, f'First Name: {first_name_text}| Last Name: {last_name_text}| Speciality: {speciality_text}| Name: {name_text}')\n\n return\n\n\ndef health_care_centers_ui():\n \n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font9 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global health_care_centers_page\n\n health_care_centers_page = tkinter.Tk()\n health_care_centers_page.title('Health Care Centers')\n health_care_centers_page.attributes('-fullscreen', True)\n health_care_centers_page.configure(background=\"#2d3436\")\n\n back_button = tkinter.Button(health_care_centers_page, command=health_care_centers_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n HCC_doctors_listbox = tkinter.Listbox(health_care_centers_page)\n HCC_doctors_listbox.place(relx=0.339, rely=0.185, relheight=0.328, relwidth=0.32)\n HCC_doctors_listbox.configure(background=\"white\")\n HCC_doctors_listbox.configure(cursor=\"dot\")\n HCC_doctors_listbox.configure(font=font9)\n HCC_doctors_listbox.configure(justify='center')\n HCC_doctors_listbox.configure(relief=\"flat\")\n HCC_doctors_listbox.configure(selectforeground=\"#2d3436\")\n HCC_doctors_listbox.configure(setgrid=\"1\")\n\n health_care_center_doctor_listbox = tkinter.Listbox(health_care_centers_page)\n health_care_center_doctor_listbox.place(relx=0.672, rely=0.185, relheight=0.328, relwidth=0.32)\n health_care_center_doctor_listbox.configure(background=\"white\")\n health_care_center_doctor_listbox.configure(cursor=\"dot\")\n health_care_center_doctor_listbox.configure(font=\"-family {DejaVu Sans Mono} -size 10 -weight bold\")\n health_care_center_doctor_listbox.configure(justify='center')\n health_care_center_doctor_listbox.configure(relief=\"flat\")\n health_care_center_doctor_listbox.configure(selectbackground=\"#c4c4c4\")\n health_care_center_doctor_listbox.configure(selectforeground=\"#2d3436\")\n health_care_center_doctor_listbox.configure(setgrid=\"1\")\n\n health_care_center_listbox = tkinter.Listbox(health_care_centers_page)\n health_care_center_listbox.place(relx=0.005, rely=0.185, relheight=0.328, relwidth=0.32)\n health_care_center_listbox.configure(background=\"white\")\n health_care_center_listbox.configure(cursor=\"dot\")\n health_care_center_listbox.configure(font=\"-family {DejaVu Sans Mono} -size 10 -weight bold\")\n health_care_center_listbox.configure(justify='center')\n health_care_center_listbox.configure(relief=\"flat\")\n health_care_center_listbox.configure(selectbackground=\"#c4c4c4\")\n health_care_center_listbox.configure(selectforeground=\"#2d3436\")\n health_care_center_listbox.configure(setgrid=\"1\")\n\n Frame1 = tkinter.Frame(health_care_centers_page)\n Frame1.place(relx=0.005, rely=0.556, relheight=0.132, relwidth=0.987)\n Frame1.configure(borderwidth=\"2\")\n Frame1.configure(relief=\"flat\")\n Frame1.configure(background=\"#ffffff\")\n\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n \n cursor.execute(f\"SELECT * FROM HCC\")\n health_care_centers = cursor.fetchall()\n\n for health_care_center in health_care_centers:\n\n phone_number_text= f'{health_care_center[1]}'\n name_text = f'{health_care_center[2]}'\n \n for i in range(25):\n if i == len(phone_number_text) - 1:\n phone_number_text += ' '\n if i == len(name_text) - 1:\n name_text += ' '\n \n health_care_center_listbox.insert(tkinter.END, f'Phone Number: {phone_number_text}| Name: {name_text}')\n\n \n cursor.execute(f\"SELECT first_name, last_name, Speciality.name, Doctor.medical_council_code, HCC.name FROM Doctor, Speciality, HCC, DHH WHERE Doctor.medical_council_code = DHH.medical_council_code AND Doctor.username = DHH.username AND DHH.HCC_id = HCC.HCC_id AND Doctor.speciality_id = Speciality.speciality_id\")\n health_care_center_doctors = cursor.fetchall()\n\n for health_care_center_doctor in health_care_center_doctors:\n\n first_name_text = f'{health_care_center_doctor[0]}'\n last_name_text = f'{health_care_center_doctor[1]}'\n speciality_text = f'{health_care_center_doctor[2]}'\n name_text = f'{health_care_center_doctor[4]}'\n\n for i in range(8):\n if i == len(first_name_text) - 1:\n first_name_text += ' '\n if i == len(last_name_text) - 1:\n last_name_text += ' '\n if i == len(speciality_text) - 1:\n speciality_text += ' '\n if i == len(name_text) - 1:\n name_text += ' '\n\n health_care_center_doctor_listbox.insert(tkinter.END, f'First Name: {first_name_text}| Last Name: {last_name_text}| Speciality: {speciality_text}| Name: {name_text}')\n\n HCC_doctors_button = tkinter.Button(Frame1, command=lambda: HCC_doctors_show(health_care_center_listbox.curselection()[0], health_care_centers, HCC_doctors_listbox))\n HCC_doctors_button.place(relx=0.011, rely=0.148, height=94, width=1851)\n HCC_doctors_button.configure(activebackground=\"#dfe6e9\")\n HCC_doctors_button.configure(background=\"#2d3436\")\n HCC_doctors_button.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n HCC_doctors_button.configure(foreground=\"#ffffff\")\n HCC_doctors_button.configure(relief=\"flat\")\n HCC_doctors_button.configure(text='''Show Doctors''')\n\n connection.commit()\n connection.close()\n \n return\n\ndef home_ui():\n\n _bgcolor = '#d9d9d9' \n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font9 = \"-family ubvazir -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global home_page\n\n home_page = tkinter.Tk()\n home_page.title('Home Page')\n home_page.attributes('-fullscreen', True)\n home_page.configure(background=\"#2d3436\")\n\n menu_frame = tkinter.Frame(home_page)\n menu_frame.place(relx=0.188, rely=0.4, relheight=0.132, relwidth=0.643)\n menu_frame.configure(relief='flat')\n menu_frame.configure(borderwidth=\"2\")\n menu_frame.configure(background=\"#ffffff\")\n menu_frame.configure(cursor=\"tcross\")\n\n profile_button = tkinter.Button(menu_frame, command=profile_ui)\n profile_button.place(relx=0.332, rely=-0.074, height=164, width=421)\n profile_button.configure(activebackground=\"#f9f9f9\")\n profile_button.configure(background=\"#ffffff\")\n profile_button.configure(borderwidth=\"5\")\n profile_button.configure(cursor=\"mouse\")\n profile_button.configure(font=font9)\n profile_button.configure(text='''View Profile''')\n\n appointment_button = tkinter.Button(menu_frame, command=appointment_ui)\n appointment_button.place(relx=-0.008, rely=-0.074, height=164, width=421)\n appointment_button.configure(activebackground=\"#f9f9f9\")\n appointment_button.configure(background=\"#ffffff\")\n appointment_button.configure(borderwidth=\"5\")\n appointment_button.configure(font=font9)\n appointment_button.configure(text='''Visit Doctors''')\n\n health_care_center_button = tkinter.Button(menu_frame, command=health_care_centers_ui)\n health_care_center_button.place(relx=0.672, rely=-0.074, height=164, width=411)\n health_care_center_button.configure(activebackground=\"#f9f9f9\")\n health_care_center_button.configure(background=\"#ffffff\")\n health_care_center_button.configure(borderwidth=\"5\")\n health_care_center_button.configure(font=font9)\n health_care_center_button.configure(text='''Health Care Centers''')\n\n return\n\n\ndef login_db(phone_number, password):\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n cursor.execute(f\"SELECT password FROM User WHERE phone_number = '{phone_number}';\")\n\n real_password = cursor.fetchone()\n\n connection.commit()\n connection.close()\n\n if type(real_password) != type(None):\n real_password = real_password[0]\n\n if real_password == password:\n global current_phone_number\n\n current_phone_number = phone_number\n\n root.destroy()\n login_page.destroy()\n home_ui()\n\n return\n\ndef signup_db(phone_number, password):\n connection = sqlite3.connect('TabibYab.db')\n cursor = connection.cursor()\n cursor.execute(f\"SELECT phone_number FROM User\")\n all_phone_numbers = cursor.fetchall()\n all_phone_numbers = [all_phone_numbers[i][0] for i in range(len(all_phone_numbers))]\n if phone_number not in all_phone_numbers:\n cursor.execute(f\"INSERT INTO User (phone_number, password) VALUES ('{phone_number}', '{password}')\")\n connection.commit()\n connection.close()\n\ndef login_ui():\n\n global login_page\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n\n font10 = \"-family ubvazir -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n font9 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n login_page = tkinter.Tk()\n login_page.configure(background=\"#2d3436\")\n login_page.configure(cursor=\"arrow\")\n login_page.title('Sign Up')\n login_page.attributes('-fullscreen', True)\n\n back_button = tkinter.Button(login_page, command=login_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n Login = tkinter.Frame(login_page)\n Login.place(relx=0.391, rely=0.302, relheight=0.337, relwidth=0.211)\n Login.configure(relief='flat')\n Login.configure(borderwidth=\"2\")\n Login.configure(background=\"#ffffff\")\n Login.configure(cursor=\"heart\")\n\n phone_number_entry = tkinter.Entry(Login)\n phone_number_entry.place(relx=0.101, rely=0.131, height=53, relwidth=0.825)\n phone_number_entry.configure(background=\"#dfe6e9\")\n phone_number_entry.configure(font=font9)\n phone_number_entry.configure(relief=\"flat\")\n phone_number_entry.configure(justify=\"center\")\n phone_number_entry.configure(foreground=\"#ffffff\")\n phone_number_entry.insert(0, 'Phone Number')\n\n password_entry = tkinter.Entry(Login)\n password_entry.place(relx=0.101, rely=0.426,height=53, relwidth=0.825)\n password_entry.configure(background=\"#dfe6e9\")\n password_entry.configure(font=font9)\n password_entry.configure(relief=\"flat\")\n password_entry.configure(justify=\"center\")\n password_entry.configure(foreground=\"#ffffff\")\n password_entry.insert(0, 'Password')\n\n login = tkinter.Button(Login, command=lambda: login_db(phone_number_entry.get(), password_entry.get()))\n login.place(relx=0.101, rely=0.721, height=54, width=331)\n login.configure(activebackground=\"#dfe6e9\")\n login.configure(background=\"#2d3436\")\n login.configure(font=font10)\n login.configure(relief=\"flat\")\n login.configure(foreground=\"#ffffff\")\n login.configure(text='''Login''')\n\n return\n\n\ndef signup_ui():\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font10 = \"-family ubvazir -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n font9 = \"-family {DejaVu Sans Mono} -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global signup_page\n\n\n signup_page = tkinter.Tk()\n signup_page.title('Sign Up')\n signup_page.attributes('-fullscreen', True)\n signup_page.configure(relief=\"ridge\")\n signup_page.configure(background=\"#2d3436\")\n signup_page.configure(cursor=\"arrow\")\n\n back_button = tkinter.Button(signup_page, command=signup_page.destroy)\n back_button.place(relx=0.016, rely=0.02, height=54, width=71)\n back_button.configure(activeforeground=\"#2d3436\")\n back_button.configure(background=\"#2d3436\")\n back_button.configure(font=font9)\n back_button.configure(foreground=\"#ffffff\")\n back_button.configure(relief=\"flat\")\n back_button.configure(text='''Back''')\n\n Signup = tkinter.Frame(signup_page)\n Signup.place(relx=0.391, rely=0.302, relheight=0.337, relwidth=0.211)\n Signup.configure(relief='flat')\n Signup.configure(borderwidth=\"2\")\n Signup.configure(background=\"#ffffff\")\n Signup.configure(cursor=\"heart\")\n\n phone_number_entry = tkinter.Entry(Signup)\n phone_number_entry.place(relx=0.101, rely=0.131, height=53, relwidth=0.825)\n phone_number_entry.configure(background=\"#dfe6e9\")\n phone_number_entry.configure(font=font9)\n phone_number_entry.configure(justify='center')\n phone_number_entry.configure(relief=\"flat\")\n phone_number_entry.configure(foreground=\"#ffffff\")\n phone_number_entry.insert(0, 'Password')\n\n password_entry = tkinter.Entry(Signup)\n password_entry.place(relx=0.101, rely=0.426, height=53, relwidth=0.825)\n password_entry.configure(background=\"#dfe6e9\")\n password_entry.configure(font=font9)\n password_entry.configure(relief=\"flat\")\n password_entry.configure(justify=\"center\")\n password_entry.configure(foreground=\"#ffffff\")\n password_entry.insert(0, 'Password')\n\n signup_submit_button = tkinter.Button(Signup, command=lambda: signup_db(phone_number_entry.get(), password_entry.get()))\n signup_submit_button.place(relx=0.101, rely=0.721, height=54, width=331)\n signup_submit_button.configure(activebackground=\"#dfe6e9\")\n signup_submit_button.configure(background=\"#2d3436\")\n signup_submit_button.configure(font=font10)\n signup_submit_button.configure(relief=\"flat\")\n signup_submit_button.configure(text='''Sign Up''')\n signup_submit_button.configure(foreground=\"#ffffff\")\n\n return\n\n\ndef start():\n\n _bgcolor = '#d9d9d9'\n _fgcolor = '#000000'\n _compcolor = '#d9d9d9'\n _ana1color = '#d9d9d9'\n _ana2color = '#ececec'\n font9 = \"-family ubvazir -size 10 -weight bold -slant roman -underline 0 -overstrike 0\"\n\n global root\n\n root = tkinter.Tk()\n root.title('TabibYab')\n root.attributes('-fullscreen', True)\n root.configure(background=\"#2d3436\") \n\n start_frame = tkinter.Frame(root)\n start_frame.place(relx=0.391, rely=0.302, relheight=0.337, relwidth=0.211)\n start_frame.configure(relief='flat')\n start_frame.configure(borderwidth=\"2\")\n start_frame.configure(background=\"#ffffff\")\n\n login_button = tkinter.Button(start_frame, command=login_ui)\n login_button.place(relx=0.074, rely=0.261, height=54, width=351)\n login_button.configure(activebackground=\"#dfe6e9\")\n login_button.configure(background=\"#2d3436\")\n login_button.configure(font=font9)\n login_button.configure(relief=\"flat\")\n login_button.configure(foreground=\"#ffffff\")\n login_button.configure(text='''Login''')\n\n signup_button = tkinter.Button(start_frame, command=signup_ui)\n signup_button.place(relx=0.074, rely=0.696, height=54, width=351)\n signup_button.configure(activebackground=\"#dfe6e9\")\n signup_button.configure(background=\"#2d3436\")\n signup_button.configure(font=font9)\n signup_button.configure(relief=\"flat\")\n signup_button.configure(text='''Sign Up''')\n signup_button.configure(foreground=\"#ffffff\")\n\n Label1 = tkinter.Label(start_frame)\n Label1.place(relx=0.099, rely=0.145, height=24, width=329)\n Label1.configure(background=\"#ffffff\")\n Label1.configure(font=font9)\n Label1.configure(text='''Already Have An Account?''')\n\n Label1_3 = tkinter.Label(start_frame)\n Label1_3.place(relx=0.074, rely=0.58, height=24, width=349)\n Label1_3.configure(activebackground=\"#f9f9f9\")\n Label1_3.configure(background=\"#ffffff\")\n Label1_3.configure(font=\"-family {ubvazir} -size 10 -weight bold\")\n Label1_3.configure(text='''Still Does Not Have An Account?''')\n\n root.mainloop()\n\n return\n\nstart()", "repo_name": "RahilEbrahimi98/Doctor-appointment-booking-application", "sub_path": "TabibYab.py", "file_name": "TabibYab.py", "file_ext": "py", "file_size_in_byte": 108818, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "26", "api": [{"api_name": "tkinter.Tk", "line_number": 17, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 22, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 31, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 40, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 68, "usage_type": "attribute"}, {"api_name": "tkinter.Tk", "line_number": 88, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 93, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 102, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 111, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 148, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 157, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 190, "usage_type": "call"}, {"api_name": "tkinter.Toplevel", "line_number": 215, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 222, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 222, "usage_type": "name"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 223, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 223, "usage_type": "name"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 224, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 224, "usage_type": "name"}, {"api_name": "tkinter.Label", "line_number": 225, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 229, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 238, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 244, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 250, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 257, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 264, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 271, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 278, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 285, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 292, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 301, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 312, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 323, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 334, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 345, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 356, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 370, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 383, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 413, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 418, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 427, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 433, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 439, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 446, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 453, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 460, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 467, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 474, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 481, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 489, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 500, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 509, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 519, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 529, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 538, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 548, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 565, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 577, "usage_type": "call"}, {"api_name": "tkinter.Toplevel", "line_number": 611, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 616, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 635, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 646, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 646, "usage_type": "name"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 647, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 647, "usage_type": "name"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 648, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 648, "usage_type": "name"}, {"api_name": "tkinter.Label", "line_number": 649, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 653, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 659, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 665, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 672, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 679, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 686, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 693, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 700, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 709, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 720, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 731, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 742, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 753, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 767, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 789, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 808, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 813, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 822, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 827, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 835, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 843, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 851, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 859, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 893, "usage_type": "attribute"}, {"api_name": "tkinter.Tk", "line_number": 908, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 912, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 921, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 930, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 967, "usage_type": "attribute"}, {"api_name": "tkinter.Tk", "line_number": 988, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 993, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 1002, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 1008, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1018, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 1027, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 1038, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 1040, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 1049, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1070, "usage_type": "attribute"}, {"api_name": "tkinter.Tk", "line_number": 1084, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1089, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 1098, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1103, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1111, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1119, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1127, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1135, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 1158, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 1163, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 1186, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1192, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 1201, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 1210, "usage_type": "attribute"}, {"api_name": "tkinter.Frame", "line_number": 1218, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1224, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 1233, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 1242, "usage_type": "attribute"}, {"api_name": "tkinter.Frame", "line_number": 1249, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 1255, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1263, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 1273, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 1299, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 1318, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 1324, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 1333, "usage_type": "attribute"}, {"api_name": "tkinter.Button", "line_number": 1335, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 1355, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 1364, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 1375, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 1381, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1389, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 1401, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 1405, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 1414, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 1423, "usage_type": "call"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 1437, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 1437, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 1447, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 1453, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1472, "usage_type": "attribute"}, {"api_name": "tkinter.Tk", "line_number": 1491, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1496, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 1505, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 1514, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 1520, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1530, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 1539, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1549, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 1561, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 1567, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1586, "usage_type": "attribute"}, {"api_name": "tkinter.Tk", "line_number": 1605, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1610, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 1619, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 1628, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 1634, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1644, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1653, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 1666, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 1702, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 1752, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 1757, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 1776, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 1809, "usage_type": "attribute"}, {"api_name": "tkinter.Button", "line_number": 1811, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 1820, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1826, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1834, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1842, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1850, "usage_type": "call"}, {"api_name": "tkinter.Toplevel", "line_number": 1873, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 1878, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 1887, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 1895, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 1912, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 1912, "usage_type": "name"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 1913, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 1913, "usage_type": "name"}, {"api_name": "PIL.ImageTk.PhotoImage", "line_number": 1914, "usage_type": "call"}, {"api_name": "PIL.ImageTk", "line_number": 1914, "usage_type": "name"}, {"api_name": "tkinter.Label", "line_number": 1915, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 1919, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1920, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1921, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1922, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1923, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1924, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1925, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1926, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1927, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1928, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1929, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 1934, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 1943, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1944, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1946, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1947, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1948, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1949, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1950, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1951, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1953, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1954, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1956, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 1964, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 1973, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 1992, "usage_type": "attribute"}, {"api_name": "tkinter.Tk", "line_number": 2008, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 2013, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 2022, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 2032, "usage_type": "call"}, {"api_name": "tkinter.Listbox", "line_number": 2043, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 2054, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 2060, "usage_type": "call"}, {"api_name": "tkinter.END", "line_number": 2077, "usage_type": "attribute"}, {"api_name": "tkinter.END", "line_number": 2100, "usage_type": "attribute"}, {"api_name": "tkinter.Button", "line_number": 2102, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 2127, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 2132, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 2139, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 2148, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 2156, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 2168, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 2192, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 2215, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 2221, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 2230, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 2237, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 2246, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 2255, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 2280, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 2287, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 2296, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 2303, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 2312, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 2321, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 2344, "usage_type": "call"}, {"api_name": "tkinter.Frame", "line_number": 2349, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 2355, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 2364, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 2373, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 2379, "usage_type": "call"}]} +{"seq_id": "32478794110", "text": "from flask import request, jsonify\nfrom app.webappl import app\nfrom werkzeug.middleware.dispatcher import DispatcherMiddleware\nfrom app.webappl import app as frontend\nimport json\nfrom flask_pymongo import PyMongo, pymongo\nfrom os.path import join\nimport os\n\ndirname = os.path.dirname(__file__)\nCLASSIFY_PATH = join(dirname, '../car_scraper/label/car_labels.json')\nwith open(CLASSIFY_PATH, 'rt', encoding=\"utf8\") as f:\n car_label = json.load(f)\n\napp.config[\"DEBUG\"] = True\napp.config['MONGO_DBNAME'] = 'sosanhgiaxe'\napp.config['MONGO_URI'] = \"mongodb://localhost:27017/sosanhgiaxe\"\nmongo = PyMongo(app)\n\n\ndef convert_price(price_text):\n if len(price_text) > 9:\n result = price_text[0:-9] + \" tỷ \" + str(int(float(price_text[-9:-6]))) + \" triệu\"\n elif len(price_text) > 6:\n result = str(int(float(price_text[0:-6]))) + \" triệu\"\n return result\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return \"

    404

    The resource could not be found in Careno.

    \", 404\n\n\n@app.route('/api/test', methods=['GET'])\ndef test():\n return \"Indexes created\"\n\n\n@app.route('/api/v1/resources/groups/search', methods=['GET'])\ndef search_group():\n base_cars = mongo.db.basecar\n query_parameters = request.args\n car_name = query_parameters.get('q').strip()\n if car_name == '':\n groups_cursor = base_cars.find({}, {'_id': 0})\n else:\n groups_cursor = base_cars.find({\"$text\": {'$search': '\\\"' + car_name + '\\\"'}},\n {'_id': 0}).collation({'locale': 'en', 'strength': 2})\n groups = [doc for doc in groups_cursor]\n return jsonify({'groups': groups})\n\n\n@app.route('/api/v1/resources/groups/info', methods=['GET'])\ndef get_group_info():\n base_cars = mongo.db.basecar\n query_parameters = request.args\n car_name = query_parameters.get('q')\n info_cursor = base_cars.find({\"identity.name\": car_name},\n {'_id': 0}).collation({'locale': 'en', 'strength': 2})\n info = [doc for doc in info_cursor]\n return jsonify({'info': info})\n\n\n@app.route('/api/v1/resources/cars/search', methods=['GET'])\ndef search_car():\n car_posts = mongo.db.carpost\n query_parameters = request.args\n brand = query_parameters.get('brand', default=\"\")\n line = query_parameters.get('line', default=\"\")\n trim_level = query_parameters.get('trim_level', default=\"\")\n sub_version = query_parameters.get('sub_version', default=\"\")\n transmission = query_parameters.get('transmission', default=\"\")\n car_status = query_parameters.get('status', default=\"all\")\n year = query_parameters.get('year', default=\"all\")\n engine_volume = query_parameters.get('engine_volume', default=\"\")\n city = query_parameters.get('location', default='all')\n # source = query_parameters.get('source', default=\"all\")\n price_min = int(float(query_parameters.get('min_price', default=0)))*1000000\n price_max = int(float(query_parameters.get('max_price', default=100000)))*1000000\n\n list_car_cursor = car_posts.find({\"$and\": [{\"brand\": brand},\n {\"line\": line},\n {\"$or\": [{\"trim_level\": trim_level}, {\"trim_level\": \"other\"}]},\n {\"$or\": [{\"transmission\": transmission}, {\"transmission\": \"other\"}]},\n {\"$or\": [{\"engine_volume\": engine_volume}, {\"engine_volume\": \"other\"}]},\n {\"$or\": [{\"sub_version\": sub_version}, {\"sub_version\": \"other\"}]},\n {\"$and\": [{\"price\": {\"$lte\": price_max}}, {\"price\": {\"$gte\": price_min}}]}\n ]},\n {'_id': 0}).collation({'locale': 'en', 'strength': 2}).sort(\"price\", pymongo.ASCENDING)\n # list_car_cursor = car_posts.find({\"$and\": [{\"brand\": brand}, {\"line\": line}]},\n # {'_id': 0}).collation({'locale': 'en', 'strength': 2})\n list_car_raw = [car for car in list_car_cursor]\n list_car = []\n post_title = []\n for car in list_car_raw:\n if car['post_title'] not in post_title:\n post_title.append(car['post_title'])\n list_car.append(car)\n if year != \"all\" and year != \"\":\n list_car = [car for car in list_car if car['year'] == year]\n if car_status != \"all\" and car_status != \"\":\n list_car = [car for car in list_car if car['status'] == car_status]\n if city != \"all\" and city != \"\":\n list_car = [car for car in list_car if city in car['location']]\n for car in list_car:\n if car['source'] == \"Banxehoi.com\":\n car['src_img'] = 'static/img/banxehoi.jpg'\n if car['source'] == \"carmudi.vn\":\n car['src_img'] = 'static/img/carmudi.png'\n if car['source'] == \"Chotot.com\":\n car['src_img'] = 'static/img/chotot.png'\n if car['source'] == \"Choxe.net\":\n car['src_img'] = 'static/img/choxe.png'\n car['price_text'] = convert_price(str(car['price']))\n return jsonify({'car': list_car})\n\n\n@app.route('/api/v1/resources/cars/chart', methods=['GET'])\ndef load_chart_data():\n car_posts = mongo.db.carpost\n base_cars = mongo.db.basecar\n query_parameters = request.args\n car_name = query_parameters.get('name')\n info_cursor = base_cars.find({\"identity.name\": car_name},\n {'_id': 0}).collation({'locale': 'en', 'strength': 2})\n info = [doc for doc in info_cursor]\n print(info[0])\n list_car_cursor = car_posts.find({\"$and\": [{\"brand\": info[0]['identity']['brand']},\n {\"line\": info[0]['identity']['line']},\n {\"$or\": [{\"trim_level\": info[0]['identity']['trim_level']}, {\"trim_level\": \"other\"}]},\n {\"$or\": [{\"transmission\": info[0]['transmission']}, {\"transmission\": \"other\"}]},\n {\"$or\": [{\"engine_volume\": info[0]['identity']['engine_volume']}, {\"engine_volume\": \"other\"}]},\n {\"$or\": [{\"sub_version\": info[0]['identity']['sub_version']}, {\"sub_version\": \"other\"}]},\n ]},\n {'_id': 0}).collation({'locale': 'en', 'strength': 2})\n chart_data = [{'x': int(float(car['year'])), 'y': car['price']/1000000} for car in list_car_cursor]\n return jsonify(chart_data)\n\n\n@app.route('/api/v1/resources/lines/search', methods=['GET'])\ndef search_line():\n query_parameters = request.args\n brand = query_parameters.get('brand')\n if brand == '':\n return []\n else:\n for car in car_label['car']:\n if car['brand'] == brand:\n return jsonify([line['model'][0] for line in car['model']])\n\n\n@app.route('/api/v1/resources/cars/search_all', methods=['GET'])\ndef search_all_car():\n car_posts = mongo.db.carpost\n query_parameters = request.args\n brand = query_parameters.get('brand', default=\"\")\n line = query_parameters.get('line', default=\"\")\n car_status = query_parameters.get('status', default=\"all\")\n year = query_parameters.get('year', default=\"all\")\n city = query_parameters.get('location', default='all')\n price_min = int(float(query_parameters.get('min_price', default=0)))*1000000\n price_max = int(float(query_parameters.get('max_price', default=100000)))*1000000\n\n if brand == '' and line != '':\n list_car_cursor = car_posts.find({\"$and\": [{\"line\": line},\n {\"$and\": [{\"price\": {\"$lte\": price_max}},\n {\"price\": {\"$gte\": price_min}}]}\n ]},\n {'_id': 0}).collation({'locale': 'en', 'strength': 2}).sort(\"price\",\n pymongo.ASCENDING)\n elif brand != '' and line == '':\n list_car_cursor = car_posts.find({\"$and\": [{\"brand\": brand},\n {\"$and\": [{\"price\": {\"$lte\": price_max}},\n {\"price\": {\"$gte\": price_min}}]}\n ]},\n {'_id': 0}).collation({'locale': 'en', 'strength': 2}).sort(\"price\",\n pymongo.ASCENDING)\n elif brand != '' and line != '':\n list_car_cursor = car_posts.find({\"$and\": [{\"brand\": brand},\n {\"line\": line},\n {\"$and\": [{\"price\": {\"$lte\": price_max}}, {\"price\": {\"$gte\": price_min}}]}\n ]},\n {'_id': 0}).collation({'locale': 'en', 'strength': 2}).sort(\"price\", pymongo.ASCENDING)\n else:\n list_car_cursor = car_posts.find({\"$and\": [{\"$and\": [{\"price\": {\"$lte\": price_max}},\n {\"price\": {\"$gte\": price_min}}]}\n ]},\n {'_id': 0}).collation({'locale': 'en', 'strength': 2}).sort(\"price\",\n pymongo.ASCENDING)\n # list_car_cursor = car_posts.find({\"$and\": [{\"brand\": brand}, {\"line\": line}]},\n # {'_id': 0}).collation({'locale': 'en', 'strength': 2})\n list_car_raw = [car for car in list_car_cursor]\n list_car = []\n post_title = []\n for car in list_car_raw:\n if car['post_title'] not in post_title:\n post_title.append(car['post_title'])\n list_car.append(car)\n if year != \"all\" and year != \"\":\n list_car = [car for car in list_car if car['year'] == year]\n if car_status != \"all\" and car_status != \"\":\n list_car = [car for car in list_car if car['status'] == car_status]\n if city != \"all\" and city != \"\":\n list_car = [car for car in list_car if city in car['location']]\n for car in list_car:\n if car['source'] == \"Banxehoi.com\":\n car['src_img'] = 'static/img/banxehoi.jpg'\n if car['source'] == \"carmudi.vn\":\n car['src_img'] = 'static/img/carmudi.png'\n if car['source'] == \"Chotot.com\":\n car['src_img'] = 'static/img/chotot.png'\n if car['source'] == \"Choxe.net\":\n car['src_img'] = 'static/img/choxe.png'\n car['price_text'] = convert_price(str(car['price']))\n return jsonify({'car': list_car})\n\n\nif __name__ == '__main__':\n application = DispatcherMiddleware(frontend, {\n '/api': app\n })\n base = mongo.db.basecar\n base.create_index([(\"identity.brand\", 1),\n (\"identity.line\", 1)])\n base.create_index([(\"identity.name\", \"text\")])\n app.run()\n", "repo_name": "quang-ph/car-comparison-website", "sub_path": "api/res_api.py", "file_name": "res_api.py", "file_ext": "py", "file_size_in_byte": 11231, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "26", "api": [{"api_name": "os.path.dirname", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 11, "usage_type": "call"}, {"api_name": "json.load", "line_number": 13, "usage_type": "call"}, {"api_name": "app.webappl.app.config", "line_number": 15, "usage_type": "attribute"}, {"api_name": "app.webappl.app", "line_number": 15, "usage_type": "name"}, {"api_name": "app.webappl.app.config", "line_number": 16, "usage_type": "attribute"}, {"api_name": "app.webappl.app", "line_number": 16, "usage_type": "name"}, {"api_name": "app.webappl.app.config", "line_number": 17, "usage_type": "attribute"}, {"api_name": "app.webappl.app", "line_number": 17, "usage_type": "name"}, {"api_name": "flask_pymongo.PyMongo", "line_number": 18, "usage_type": "call"}, {"api_name": "app.webappl.app", "line_number": 18, "usage_type": "argument"}, {"api_name": "app.webappl.app.errorhandler", "line_number": 29, "usage_type": "call"}, {"api_name": "app.webappl.app", "line_number": 29, "usage_type": "name"}, {"api_name": "app.webappl.app.route", "line_number": 34, "usage_type": "call"}, {"api_name": "app.webappl.app", "line_number": 34, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 42, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 42, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 50, "usage_type": "call"}, {"api_name": "app.webappl.app.route", "line_number": 39, "usage_type": "call"}, {"api_name": "app.webappl.app", "line_number": 39, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 56, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 56, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 61, "usage_type": "call"}, {"api_name": "app.webappl.app.route", "line_number": 53, "usage_type": "call"}, {"api_name": "app.webappl.app", "line_number": 53, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 67, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 67, "usage_type": "name"}, {"api_name": "flask_pymongo.pymongo.ASCENDING", "line_number": 89, "usage_type": "attribute"}, {"api_name": "flask_pymongo.pymongo", "line_number": 89, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 115, "usage_type": "call"}, {"api_name": "app.webappl.app.route", "line_number": 64, "usage_type": "call"}, {"api_name": "app.webappl.app", "line_number": 64, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 122, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 122, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 137, "usage_type": "call"}, {"api_name": "app.webappl.app.route", "line_number": 118, "usage_type": "call"}, {"api_name": "app.webappl.app", "line_number": 118, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 142, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 142, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 149, "usage_type": "call"}, {"api_name": "app.webappl.app.route", "line_number": 140, "usage_type": "call"}, {"api_name": "app.webappl.app", "line_number": 140, "usage_type": "name"}, {"api_name": "flask.request.args", "line_number": 155, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 155, "usage_type": "name"}, {"api_name": "flask_pymongo.pymongo.ASCENDING", "line_number": 170, "usage_type": "attribute"}, {"api_name": "flask_pymongo.pymongo", "line_number": 170, "usage_type": "name"}, {"api_name": "flask_pymongo.pymongo.ASCENDING", "line_number": 177, "usage_type": "attribute"}, {"api_name": "flask_pymongo.pymongo", "line_number": 177, "usage_type": "name"}, {"api_name": "flask_pymongo.pymongo.ASCENDING", "line_number": 183, "usage_type": "attribute"}, {"api_name": "flask_pymongo.pymongo", "line_number": 183, "usage_type": "name"}, {"api_name": "flask_pymongo.pymongo.ASCENDING", "line_number": 189, "usage_type": "attribute"}, {"api_name": "flask_pymongo.pymongo", "line_number": 189, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 215, "usage_type": "call"}, {"api_name": "app.webappl.app.route", "line_number": 152, "usage_type": "call"}, {"api_name": "app.webappl.app", "line_number": 152, "usage_type": "name"}, {"api_name": "werkzeug.middleware.dispatcher.DispatcherMiddleware", "line_number": 219, "usage_type": "call"}, {"api_name": "app.webappl.app", "line_number": 219, "usage_type": "argument"}, {"api_name": "app.webappl.app", "line_number": 220, "usage_type": "name"}, {"api_name": "app.webappl.app.run", "line_number": 226, "usage_type": "call"}, {"api_name": "app.webappl.app", "line_number": 226, "usage_type": "name"}]}